3

How to show Friendly Date in SharePoint using Javascript or using Server side code

 

JAVASCRIPT

You can use following javascript code in order to show Date field value in Friendly format


var yourDate = new Date();

var friendlyDate = SP.DateTimeUtil.SPRelativeDateTime.getRelativeDateTimeString(yourDate , true, SP.DateTimeUtil.SPCalendarType.none, false)

console.log(friendlyDate);

 

Note that you need to add reference of “SP.dateTimeUtil.js” js in your page

<script type="text/javascript" src="/_layouts/15/SP.dateTimeUtil.js></script>

Following is the description about method argument:
1. Your date (Date ISO8601)
2. Specify whether want to include tiem or not(IncludeTime)
3. Calendar type (CalendarType)
4. Specify whether want to adjust time with server(AdjustToServersNowTime)
————————————————————————–
SERVER SIDE


DateTime date = DateTime.Now;
string friendlyDate = SPRelativeDateTime.GetRelativeDateString(web, date.ToUniversalTime(), date); 

I Hope it will same someone’s time.
 

Advertisements
0

Get User Profile Properties From SharePoint Online Using CSOM Console application

Hi,

Explain you and share Code How to retrieve User profile Properties For SharePoint online site

Step1-Create Console application From VS

Step2-Put SharepointClient.dll and SharepointClient.Runtime.dll in you dll Folder

Step3-Go to your Solution add dll From your bin Folder path

Step4-Copy past below Code

step5-Change in bold text in Code(SiteUrl,Password,User)

Step6-Run Solution , Properties Export in CSV Format

using System;
using System.Security;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.UserProfiles;
using Microsoft.Web.Hosting.Administration;
namespace UserProfileProp
{
class Program
{
static void Main(string[] args)
{
using (ClientContext tenantContext = new ClientContext(“Sharepoint Online SiteURL”))
{
SecureString passWord = new SecureString();
foreach (char c in “password”.ToCharArray())
passWord.AppendChar(c);
tenantContext.Credentials = new SharePointOnlineCredentials(“Username”, “password”,);

PeopleManager peopleManager = new PeopleManager(tenantContext);

UserCollection users = tenantContext.Web.SiteUsers;
tenantContext.Load(users);
tenantContext.ExecuteQuery();

string csvFilePath = @”C:\Users\sp_admin\Desktop\users.csv”;
StringBuilder items = new StringBuilder();

//PeopleManager peopleManager = new PeopleManager(tenantContext);
PersonProperties personProperties = peopleManager.GetMyProperties();

tenantContext.Load(personProperties);
tenantContext.ExecuteQuery();

tenantContext.Load(personProperties, p => p.AccountName, p => p.UserProfileProperties);
tenantContext.ExecuteQuery();
string[] userProfileProperties = new string[personProperties.UserProfileProperties.Count+1];

// string[] userProfileProperties = { “AccountName”, “FirstName”, “LastName”, “PreferredName”, “Manager”, “AboutMe”, “PersonalSpace”, “PictureURL”, “UserName”, “WorkEmail”, “SPS-Birthday” };
int i = 0;
foreach (string key in personProperties.UserProfileProperties.Keys)
{

userProfileProperties[i] = key;
i++;
}
foreach (string propertyKey in userProfileProperties)
{
items.Append(propertyKey);
items.Append(“,”);
}
items.AppendLine();

foreach (Microsoft.SharePoint.Client.User user in users)
{
try
{
if (user.PrincipalType != Microsoft.SharePoint.Client.Utilities.PrincipalType.User) continue;

UserProfilePropertiesForUser userProfilePropertiesForUser = new UserProfilePropertiesForUser(tenantContext, user.LoginName, userProfileProperties);
IEnumerable<string> profileProperties = peopleManager.GetUserProfilePropertiesFor(userProfilePropertiesForUser);
tenantContext.Load(userProfilePropertiesForUser);
tenantContext.ExecuteQuery();
foreach (string property in profileProperties)
{
items.Append(property);
items.Append(“,”);
}
items.AppendLine();
}
catch (Exception ex)
{
throw ex;
}

}

System.IO.File.WriteAllText(csvFilePath, items.ToString());
}
}
}
}

dO

 

Remarks: when you want to run this console in client machine where share point is not installed To run your Console Followe below step in your solution
– you have to change your dll property Name Copy To Local= True
-Change solution to Release mode and build solutions
-after that copy Release Folder and past in client machine after that run your Exe from that Folder

Hope its Help you

Thanks
SPS

3

Send Email through REST API in SharePoint

In this article i will explain you how to send E-Mails through REST API in SharePoint.

We can send E-Mails through REST API using SP.Utilities.Utility.SendEmail.

Here is code to send E-Mail using REST API in SharePoint

$.ajax({
        contentType: 'application/json',
        url: urlEmail,
        type: "POST",
        data: JSON.stringify({
                  'properties': {
                  '__metadata': { 'type': 'SP.Utilities.EmailProperties' },
                  'Body': 'Hello user.. You got mail from codeplayandlearn.wordpress.com',
                  'To' : { 'results': ['admin@codeplayandlearn.com'] },
                  'Subject': "E-Mail From REST API";
                }
            }),
        headers: {
                    "Accept": "application/json;odata=verbose",
                    "content-type": "application/json;odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val()
                },
        success: function (data) {
                alert("Email Send Successful.");
                },
        error: function (err) {
                alert(err.responseText);
                }
        });

Here you don’t need to specify from E-Mail Id.

And make sure that To(Send to) E-Mail id should be E-Mail Id of any user from SharePoint Users.

And also make sure that metadata of Email should be

'type':'SP.Utilities.EmailProperties'

If this method not work or still you are getting error while sending E-Mails then try this method

Using separate function to send E-Mail from REST API


function processSendEmails() {
    var from = 'system@codeplayandlearn.com',
        to = 'member@codeplayandlearn.com',
        body = 'Dear member you got mail from Code Play and Learn',
        subject = 'Email from REST API';
    // Call sendEmail function
    sendEmail(from, to, body, subject);
}

function sendEmail(from, to, body, subject) {
    //Get the relative url of the site
    var siteurl = _spPageContextInfo.webServerRelativeUrl;
    var urlTemplate = siteurl + "/_api/SP.Utilities.Utility.SendEmail";
    $.ajax({
        contentType: 'application/json',
        url: urlTemplate,
        type: "POST",
        data: JSON.stringify({
            'properties': {
                '__metadata': {
                    'type': 'SP.Utilities.EmailProperties'
                },
                'From': from,
                'To': {
                    'results': [to]
                },
                'Body': body,
                'Subject': subject
            }
        }),
        headers: {
            "Accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
        },
        success: function(data) {
            alert('Email Sent Successfully');
        },
        error: function(err) {
            alert('Error in sending Email: ' + JSON.stringify(err));
        }
    });
}

$(document).ready(function () {
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', processSendEmails);
});

Here i have created separate function to send E-Mail in which i am passing information of E-Mails.

By using this methods you can send E-Mails through REST API in SharePoint.

If this blog helps you in understanding SharePoint please share and like this blog.

Happy coding..!!

Learn code while playing with it..!!

0

Display and slide picture From Picture Library in Content Editor webpart using CSOM in 2010/13

Hi,

Today,I am going to Explain you here How to Display and slide picture From Picture Library in Content Editor webpart using CSOM

this is simple task Just Follow below step you will get the output

  • Create Js File or txt File and copy past below code in your File (Explainationcode of  code Find with comment in code file)
  •  Uplode file in style Library(Recomended) or any Library
  • Create Picture Library or you can use asset Library as well and uplode some slider images.
  •  Go to Your SP site and add Content Editor web part..
  • Editwebpart and   link with your JS(provide full URL or path of your Js which you have uplode in Style Library)
  • Apply and Ok now your Images is Ready to Slides in CEWP Cheers!!!

Below is Code for your JS or txt File

<div style="position: relative" id="imgCntr" paddingLeft="5px" peddingRight="5px">

</div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

<script type="text/javascript">

ExecuteOrDelayUntilScriptLoaded(loadSlideImages, "sp.js");
//Recommended to define this fun First 

function onQuerySucceeded(sender, args) {
var listItemInfo = '';
var listItemEnumerator = frontPictureItems.getEnumerator();
var listItems = '';
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
listItems += '<img src="http://sp:1000/student/iin/MySlider1/' + oListItem.get_displayName() + '.jpg" style="position:absolute" height="300px" width="900px"/>';
}

$('#imgCntr').html(listItems);
initSlider();
}

function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + 'n' + args.get_stackTrace());
}

function initSlider() {
$('#imgCntr img:gt(0)').hide();
setInterval(function(){$('#imgCntr :first-child').fadeOut().next('img').fadeIn().end().appendTo('#imgCntr');}, 6000);
}

var siteUrl='http://sp:1000/student/iin';
//i have taken static URL here you can used Absolute URL as well

function loadSlideImages() {
var clientContext = new SP.ClientContext(siteUrl); 
var oList = clientContext.get_web().get_lists().getByTitle('MySlider');//get PicLibrary

var camlQuery = SP.CamlQuery.createAllItemsQuery();
//you can use caml syntax to get desire result i have Just take all field
   		
this.frontPictureItems = oList.getItems(camlQuery);
clientContext.load(frontPictureItems, 'Include(Id,DisplayName,FileLeafRef,FileDirRef)');
//load neccessary Field to load image

clientContext.executeQueryAsync(
 Function.createDelegate(this, this.onQuerySucceeded),
 Function.createDelegate(this, this.onQueryFailed));
}

</script>

now Run your site…. wow your CEWP Image slider is ready

Happy Coding

Thanks
SPS

1

How Get Calendar recurrent events by CSOM from SharePoint 2013.

Hi I am Going to Explain you here how to get Recurrence Event From your Sharepoint Calender List Using Client Object model(CSOM) Getting Recurrence Event From List using Server OM  is bit eassy as Below

SPQuery query = new SPQuery();
query.ExpandRecurrence = true;

query.Query = String.Format(
"" +
"" +
"" +
"",
Fields.StartDate,
Fields.EndDate,
Fields.RecurrenceId,
orderBy);

Now Coming on CSOM-

  • The problem with recurrence is that there is only a single list item. The recurrence information is stored inside a hidden field of that list item called ‘RecurrenceData’ as XML that gets calculated out. Unfortunately Microsoft.SharePoint.Client.CamlQuery doesn’t have the properties that SPQuery does in the server object model to transform this information.
  • What is a little more frustrating is that the new OData operations through REST do not support the DateTimeRangesOverlap operator or “querying as to whether a date time falls inside a recurrent date time pattern

But Nothing is impossible…….. Final way is call old-fashion List.asmx.

  • There was a way to call Lists.asmx in versions before 2013 using SOAP and pass an entire XML message which would allow you to use the DateRangesOverlap filter in the query, and allow you to pass QueryOptions that would include ExpandRecurrence and CalendarDate, but it was flaky trying to pass an actual datetime value for CalendarDate as the value to check if the event overlaps with.
  function GetItemsFromCalendarAsmx () {
wsURL = webUrl + “_vti_bin/Lists.asmx”;
var xmlCall =
“<listName>” + calendarGuid + “</listName>” +
“<query>” +
“<Query>” +
“<Where>” +
“<DateRangesOverlap>” +
“<FieldRef Name=\”EventDate\” />” +
“<FieldRef Name=\”EndDate\” />” +
“<FieldRef Name=\”RecurrenceID\” />” +
“<Value Type=’DateTime’><Year/></Value>” +
“</DateRangesOverlap>” +
“</Where>” +
“</Query>” +
“</query>” +
“<queryOptions>” +
“<QueryOptions>” +
“<ExpandRecurrence>TRUE</ExpandRecurrence>” +
“</QueryOptions>” +
“</queryOptions>” +
“</GetListItems>” +
“</soap:Body></soap:Envelope>”;
var result = [];
$.ajax({
url: wsURL,
type: “POST”,
dataType: “xml”,
async: false,
data: xmlCall,
complete: function (xData, status) {
Core.LogMessage(“Core.GetItemsFromCalendarAsmx-> url: ” + wsURL + ” status: ” + status);
if (status === “success”) {
var root = $(xData.responseText);
root.find(“listitems”).children().children().each(function () {
$this = $(this);
var ids = $this.attr(“ows_UniqueId”).split(“;”);
var rec = $this.attr(“ows_fRecurrence”);
result.push({
“StartTime”: $this.attr(“ows_EventDate”),
“EndTime”: $this.attr(“ows_EndDate”),
“Title”: $this.attr(“ows_Title”),
“Recurrence”: (rec === “1” ? true : false),
“Description”: Core.HtmlDecode($this.attr(“ows_Description”)),
“Guid”: ids[1],
“Id”: ids[0],
});
});
}
},
contentType: “text/xml; charset=\”utf-8\””
});
return result;
};

hope you GET expected Solutions

Happy Coding Thanks SPS