Showing posts with label SiteCollectionFeatures. Show all posts
Showing posts with label SiteCollectionFeatures. 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. });  


Monday 23 May 2016

Working With SharePoint Site Collection Features Using CSOM PowerShell


In this article, you will learn how retrieve, enable or disable the site collection features programmatically using CSOM with PowerShell on SharePoint 2013 / SharePoint 2016 / SharePoint online.


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 necessary reference paths. The necessary references are Microsoft.SharePoint.Client.dll, Microsoft.SharePoint.Client.Runtime.dll.

    Add-Type -Path 

    "C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.dll" 

    Add-Type -Path 

    "C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.Runtime.dll" 
  2. Initialize client context object with the site URL.
    1. $siteURL = ""  
    2. $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)  
    3. $siteFeatureId = "" 
  3. If you are trying to access SharePoint Online site, then you need to setup the site credentials with credentials parameter and get it set to the client context. 
    1. #Not required for on premise site - 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. #Not required for on premise site - 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.


Get Active Site Collection Features:

  • Initialize the site object and get the site property.
  • Get the features from site object using features property.
  • Load the objects and execute query to get the data.
  • Get the feature details individually using for each loop.
    • For each site collection feature, use the retrieve method to get the appropriate property value. In this case, feature display name will be retrieved.
    • Load the site collection feature object and execute the query. Then access the feature properties. The feature properties retrieved are feature id and feature name.
      1. function GetSiteCollectionFeatures(){  
      2.     # Access the site  
      3.     $site = $ctx.Site  
      4.     # Get the features  
      5.     $siteFeatures = $site.Features  
      6.     $ctx.Load($site)  
      7.     $ctx.Load($siteFeatures)  
      8.     $ctx.ExecuteQuery()      
      9.       
      10.     foreach($siteFeature in $siteFeatures){  
      11.         # Set the property name to retrieve the value  
      12.         $siteFeature.Retrieve("DisplayName")  
      13.         $ctx.Load($siteFeature)  
      14.         $ctx.ExecuteQuery()  
      15.         Write-Host $siteFeature.DefinitionId  
      16.         Write-Host $siteFeature.DisplayName  
      17.     }  
      18. }  



Get/Check Site Collection Feature Properties/Status:

Here we will see how we can get the particular feature and check whether the site collection feature is active 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.
  • Use the retrieve method to get the appropriate property value.
  • Load the feature and execute the query.
  • Using the if else condition, identify whether the site collection feature is active. If the feature id or name exists from the above object, then the feature is in active mode.
    1. function GetSiteCollectionFeature(){  
    2.     # Set Feature ID  
    3.     $siteFeatureId = "b50e3104-6812-424f-a011-cc90e6327318" # Document ID Service feature  
    4.     $site = $ctx.Site  
    5.     $checkFeature = $site.Features.GetById($siteFeatureId)  
    6.     $checkFeature.Retrieve("DisplayName")  
    7.     $ctx.Load($checkFeature)  
    8.     $ctx.ExecuteQuery()  
    9.       
    10.     if($checkFeature.DefinitionId -eq $null){  
    11.         Write-Host "Site Feature is not active"  
    12.     }  
    13.     else{  
    14.         Write-Host $checkFeature.DisplayName "Site Feature is active"  
    15.     }  
    16. }  



Activate the site collection feature:

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 method to the features collection. The necessary parameters are feature id, boolean value to force enable the feature and the scope. The scope here will be none, since we are already adding the feature to site object. Boolean value is true to force enable the feature.
  • Use the retrieve method to get the appropriate property value.
  • Load the feature object and execute the query.
  • Check the definition id, if definition id is not null then the site collection feature is activated.
    1. # Activate the site collection feature  
    2. function EnableSiteCollectionFeature(){  
    3.     try{  
    4.         $site = $ctx.Site  
    5.         # Add the feature using feature id and scope.  
    6.         $newSiteFeature = $site.Features.Add($siteFeatureId, $true, [Microsoft.SharePoint.Client.FeatureDefinitionScope]::None)  
    7.         $newSiteFeature.Retrieve("DisplayName")  
    8.         $ctx.Load($newSiteFeature)  
    9.         $ctx.ExecuteQuery()  
    10.         if($newSiteFeature.DefinitionId -ne $null){  
    11.             Write-Host $newSiteFeature.DisplayName "Site Feature activated"  
    12.         }          
    13.     }  
    14.     catch{  
    15.         Write-Host "Error in activating site feature : $($_.Exception.Message)" -ForegroundColor Red  
    16.     }  
    17. }  



Deactivate the Site Collection feature:

In the above section, we have seen how we can activate the site collection feature. Now we will see how we can deactivate the site collection feature.
  • To de-activate the site collection feature, use the remove method to the features collection. The necessary parameters are feature id, boolean value to force enable the feature. The feature id can be identified from the microsoft blog site (mentioned above). Boolean value is true to force disable the feature.
  • Load the site collection object and execute the query.
    1. # Deactivate the site collection feature  
    2. function DisableSiteCollectionFeature(){  
    3.     try{  
    4.         $site = $ctx.Site  
    5.         $site.Features.Remove($siteFeatureId, $true)  
    6.         $ctx.Load($site)  
    7.         $ctx.ExecuteQuery()  
    8.         Write-Host "Site Feature deactivated"  
    9.     }  
    10.     catch{  
    11.         Write-Host "Error in deactivating feature : $($_.Exception.Message)"-ForegroundColor Red  
    12.     }  
    13. }  


Note: The above set of operations needs to be called to get it executed.
  1. GetSiteCollectionFeatures # Gets all the features from site scope.
  2. GetSiteCollectionFeature # Gets a feature using feature id at site scope.
  3. EnableSiteCollectionFeature # Adds site collection feature.
  4. DisableSiteCollectionFeature # Removes site collection feature.