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

Advertisements

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..!!