Showing posts with label SharePointOnline. Show all posts
Showing posts with label SharePointOnline. Show all posts

Friday 27 May 2016

Working With SharePoint Site Collection Features Using REST API


In this post, you will learn how retrieve, enable or disable the site collection features (site scoped) programmatically using REST API on SharePoint 2013 / SharePoint 2016 / SharePoint online. There are different ways that we use to work with site collection features. We will see how we can use REST APIs to achieve the functionalities.
  • Identify the site collection URL and build the REST API URL. 
  • In the URL, site denotes the site collection scope and set the necessary parameters to filter out the data. You need to provide select parameters to get the necessary feature properties in get request.
  • Use Ajax jQuery call to accomplish the necessary operation.
  • You can set the return value type in the ajax call request. In my case, I have specified JSON to be return value in the data parameter.
  • In these cases, You can check the result values in browser debugger console. You can change the logic to display results on pages.
  • Place these scripts on page using the web parts (content editor / script editor / any custom web part). 


Get Active Site Collection Features and Properties (Site scope):


The operation will fetch all the active site collection features present on the site.
  • In the URL, select parameters has necessary properties to be retrieved.
  • Using foreach loop, get and display the results.
    1. // Retrieves all the site collection features enabled (site scoped features)  
    2. function GetSiteCollectionFeatures(){  
    3.     var featuresURI = sitecollectionURL + "/_api/site/features?$select=DisplayName,DefinitionId";  
    4.     $.ajax({  
    5.         url: featuresURI,  
    6.         method: 'GET',  
    7.         headers: { "Accept""application/json; odata=verbose" },  
    8.         dataType: "json",  
    9.         success: function (data) {  
    10.             var siteCollectionFeatures = data.d.results;  
    11.             for(var i=0;i<siteCollectionFeatures.length;i++){  
    12.                 console.log(siteCollectionFeatures[i].DefinitionId + " - " + siteCollectionFeatures[i].DisplayName);  
    13.             }  
    14.         },  
    15.         error: function(data) {  
    16.         }  
    17.     });  
    18. }  



Get/Check Site Collection Feature Properties/Status (Site scope):


Here we will see how we can get the particular feature and check whether the site collection feature is active or not. You can identify whether the feature is activated at site scope or not.
  • Get the feature id from the Microsoft site. The scope of the feature should be site.
  • Get the feature using GetById method with feature id in the REST API.
    1. // Retrieves the site collection feature by id enabled (site scoped features)  
    2. function GetSiteCollectionFeatureByID(){  
    3.     var featuresURI = sitecollectionURL + "/_api/site/features/GetByID('151d22d9-95a8-4904-a0a3-22e4db85d1e0')?$select=DisplayName,DefinitionId";   
    4.     // Cross-Site Collection Publishing Feature ID  
    5.     $.ajax({  
    6.         url: featuresURI,  
    7.         method: 'GET',  
    8.         headers: { "Accept""application/json; odata=verbose" },  
    9.         dataType: "json",  
    10.         success: function (data) {  
    11.             if(data.d != null){  
    12.                 console.log(data.d.DefinitionId + " - " + data.d.DisplayName + " feature is active");  
    13.             }  
    14.             else{  
    15.                 console.log("Feature is not active");  
    16.             }  
    17.         },  
    18.         error: function(data) {  
    19.         }  
    20.     });  
    21. }  



Activate the site collection feature (Site scope):


In the above section, we have seen how we can check the status of the site collection feature. Here we will see how we can activate the feature which is already installed on the site.
  • To activate the site feature, use the add method to the features collection. The necessary parameter to be passed in the query is feature id.
  • POST method will be used to accomplish the task.
  • RequestDigest will be passed in the header to validate the page requests.
    1. // Enables site collection feature (Site scoped feature)  
    2. function EnableSiteCollectionFeature(){  
    3.     var featuresURI = sitecollectionURL + "/_api/site/features/add('151d22d9-95a8-4904-a0a3-22e4db85d1e0')"// Cross-Site Collection Publishing Feature ID  
    4.     $.ajax({  
    5.         url: featuresURI,  
    6.         method: 'POST',  
    7.         headers: {   
    8.             "Accept""application/json;odata=verbose",  
    9.             "X-RequestDigest": $("#__REQUESTDIGEST").val()   
    10.         },  
    11.         success: function (data) {  
    12.             console.log("Feature Activated");  
    13.         },  
    14.         error: function(data) {  
    15.             console.log(data.responseJSON.error.message.value);  
    16.         }  
    17.     });  
    18. }  



Deactivate the site collection feature (Site scope):


In the above section, we have seen how we can activate the site collection feature. Here we will see how we can deactivate the feature.
  • To deactivate the site feature, use the remove method on URL. The necessary parameters to be passed in the query is feature id.
  • POST method will be used to accomplish the task.
  • RequestDigest will be passed in the header to validate the page requests.
    1. // Disables site collection feature (Site scoped feature)  
    2. function DisableSiteCollectionFeature(){  
    3.     var featuresURI = sitecollectionURL + "/_api/site/features/remove('151d22d9-95a8-4904-a0a3-22e4db85d1e0')"// Cross-Site Collection Publishing Feature ID  
    4.     $.ajax({  
    5.         url: featuresURI,  
    6.         method: 'POST',  
    7.         headers: {   
    8.             "Accept""application/json;odata=verbose",  
    9.             "X-RequestDigest": $("#__REQUESTDIGEST").val()   
    10.         },  
    11.         success: function (data) {  
    12.             console.log("Feature De-Activated");  
    13.         },  
    14.         error: function(data) {  
    15.             console.log(data.responseJSON.error.message.value);  
    16.         }  
    17.     });  
    18. }  
Note: The above set of operations needs to be called to get it executed.
  1. $(document).ready(function(){  
  2.     GetSiteCollectionFeatures(); // Retrieves all the site collection features enabled (site scoped features)  
  3.     GetSiteCollectionFeatureByID(); // Retrieves the site collection feature by id enabled (site scoped features)  
  4.     EnableSiteCollectionFeature(); // Enables site collection feature (Site scoped feature)  
  5.     DisableSiteCollectionFeature(); // Disables site collection feature (Site scoped feature)  
  6. });  


Retrieve Followers or Following Users From SharePoint User Profile Using CSOM PowerShell


In this article, you will learn how to retrieve people following (followed by user) or followers information from SharePoint user profile programmatically in different ways using CSOM with PowerShell on SharePoint 2013 / SharePoint 2016 / SharePoint online.

SharePoint My Sites should be configured on the environment as a prerequisite.


Steps Involved:


The following prerequisites need to be executed before going for any operations using CSOM PowerShell on SharePoint sites.
  1. Add the references using the Add-Type command with the necessary reference paths. The necessary references are Microsoft.SharePoint.Client.dll, Microsoft.SharePoint.Client.Runtime.dll and UserProfile dll.
    1. Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"  
    2. Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"  
    3. Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.UserProfiles.dll"  
  2. Initialize client context object with the site URL.
    1. $siteURL = ""  
    2. $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)  
  3. If you are trying to access SharePoint Online site then you need to setup the site credentials with credentials parameter and load it to the client context. 
    1. #Setting Credentials for o365 - Start  
    2. $userId = ""  
    3. $pwd = Read-Host -Prompt "Enter password" -AsSecureString  
    4. $creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userId, $pwd)  
    5. $ctx.credentials = $creds  
    6. #Setting Credentials for o365 - End  
  4. If you are trying to access the SharePoint on premise site then the credentials parameter is not required to be set to the context but you need to run the code on the respective SharePoint Server or you need to pass the network credentials and set the context.
    1. #Credentials for on premise site - Start  
    2. $pwd = Read-Host -Prompt "Enter password" -AsSecureString  
    3. $creds = New-Object System.Net.NetworkCredential("domain\userid", $pwd)  
    4. $ctx.Credentials = $creds  
    5. #Credentials for on premise site - End  


Retrieve Current User Followers:


  • Initialize the people manager object with the context to get the user profile data.
  • With people manager object, use GetMyFollowers() method to retrieve current user (User running the script) followers information.
  • Load the object and execute query to get the data.
  • In the below code snippet, $follower will hold the basic profile information of user and $follower.UserProfileProperties will hold the entire property set of a particular user.
    1. # Get My Follower Profiles & Properties  
    2. function GetMyFollowers(){  
    3.      try{  
    4.         $peopleManager = New-Object Microsoft.SharePoint.Client.UserProfiles.PeopleManager($ctx)  
    5.         $myFollowers = $peopleManager.GetMyFollowers()  
    6.         $ctx.Load($myFollowers)  
    7.         $ctx.ExecuteQuery()  
    8.         Write-Host "I have " $myFollowers.Count " followers"  
    9.         foreach($follower in $myFollowers){  
    10.             Write-Host "Display Name : " $follower.DisplayName  
    11.             Write-Host "Title : " $follower.Title  
    12.             $followerProfProp = $follower.UserProfileProperties  
    13.             # Other User Profile properties can be retrieved from $follower.UserProfileProperties using foreach loop  
    14.             Write-Host "Interests : " $follower.UserProfileProperties["SPS-Interests"]  
    15.         }  
    16.           
    17.     }  
    18.     catch{  
    19.         Write-Host "$($_.Exception.Message)" -foregroundcolor Red  
    20.     }  
    21. }  


Retrieve Current user following data:


In the above section, we have seen that how we can get current user followers. Now we will see how we can retrieve following (people followed by user) information of a user who is running the script. The steps followed are very similar to the above section. Only the method is changed to get the target user properties.
  1. # Get People current user is following  
  2. function GetMyFollowing(){  
  3.     try{  
  4.         $peopleManager = New-Object Microsoft.SharePoint.Client.UserProfiles.PeopleManager($ctx)  
  5.         $myfollowingUsers = $peopleManager.GetPeopleFollowedByMe()  
  6.         $ctx.Load($myfollowingUsers)  
  7.         $ctx.ExecuteQuery()  
  8.         Write-Host "I am following " $myfollowingUsers.Count " People"  
  9.         foreach($myfollowingUser in $myfollowingUsers){  
  10.               
  11.             Write-Host "Display Name : " $myfollowingUser.DisplayName  
  12.             Write-Host "Title : " $myfollowingUser.Title  
  13.  
  14.             # Other User Profile properties can be retrieved from $follower.UserProfileProperties using foreach loop  
  15.             Write-Host "Interests : " $myfollowingUser.UserProfileProperties["SPS-Interests"]  
  16.         }  
  17.     }  
  18.     catch{  
  19.         Write-Host "$($_.Exception.Message)" -foregroundcolor Red  
  20.     }  
  21. }   


Retrieve Followers for Target User:


In the above sections, we have seen that how we can retrieve followers or following information of user who is running the script. Now, we will see, how we can get the follower information for target users.
  • Initialize the people manager object with the context to get the user profile data.
  • User GetFollowersFor(user) method with user ID and people manager to retrieve followers information about target user.
  • Load the object and execute query to get the data.
    1. # Get Followers for target user  
    2. function GetFollowers(){  
    3.     try{  
    4.         $peopleManager = New-Object Microsoft.SharePoint.Client.UserProfiles.PeopleManager($ctx)  
    5.         $followers = $peopleManager.GetFollowersFor("domain\userid")  
    6.         $ctx.Load($followers)  
    7.         $ctx.ExecuteQuery()  
    8.         Write-Host "User is followed by " $followers.Count " People"  
    9.         foreach($follower in $followers){  
    10.               
    11.             Write-Host "Display Name : " $follower.DisplayName  
    12.             Write-Host "Title : " $follower.Title  
    13.  
    14.             # Other User Profile properties can be retrieved from $follower.UserProfileProperties using foreach loop  
    15.             Write-Host "Interests : " $follower.UserProfileProperties["SPS-Interests"]  
    16.         }  
    17.     }  
    18.     catch{  
    19.         Write-Host "$($_.Exception.Message)" -foregroundcolor Red  
    20.     }  
    21. }  


Retrieve Following User Information for Target User:


In the above section, we have seen that how we can retrieve followers information for target user. Now, we will see, how we can get the following information for target users.
  • The logic is same as that of above section. But use GetPeopleFollowedBy(UserID) method to get the target user's following data (people followed by user).
    1. # Get People following  
    2. function GetFollowing(){  
    3.     try{  
    4.         $peopleManager = New-Object Microsoft.SharePoint.Client.UserProfiles.PeopleManager($ctx)  
    5.         $followingUsers = $peopleManager.GetPeopleFollowedBy("domain\userid")   # Login id of SharePoint account       
    6.         $ctx.Load($followingUsers)  
    7.         $ctx.ExecuteQuery()  
    8.         Write-Host "User is following " $followingUsers.Count " People"  
    9.         foreach($followingUser in $followingUsers){  
    10.               
    11.             Write-Host "Display Name : " $followingUser.DisplayName  
    12.             Write-Host "Title : " $followingUser.Title  
    13.  
    14.             # Other User Profile properties can be retrieved from $follower.UserProfileProperties using foreach  
    15.             Write-Host "Interests : " $followingUser.UserProfileProperties["SPS-Interests"]  
    16.         }  
    17.     }  
    18.     catch{  
    19.         Write-Host "$($_.Exception.Message)" -foregroundcolor Red  
    20.     }  
    21. }   
Note - The above set of operations needs to be called to get it executed.
  1. GetMyFollowers # Get my followers  
  2. GetFollowers # Get Followers  
  3. GetMyFollowing # Get my following  
  4. GetFollowing # Get Following