Showing posts with label o365. Show all posts
Showing posts with label o365. Show all posts

Monday 13 June 2016

Upload And Set Custom Master Page To Site Using CSOM PowerShell On SharePoint

In this article post, you will learn how to upload custom master page to master page gallery and apply custom master pages to the site using CSOM Powershell on SharePoint 2013 / SharePoint 2016 / SharePoint online sites.


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.
    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"  
  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. #Not required for on premise site - Start  
    2. $userId = "abc@abc.onmicrosoft.com"  
    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.
    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  


Upload and Apply Master Page:


We will see how we can upload the master page file from local system to master page gallery and apply the uploaded master page to the site.
  • Get the master page from local.
    • Get the master page file local system URL and access the properties of master page file using Get-ChildItem method.
    • Then read the master page content using ReadAllBytes method and initialize the content to variable ($fileBytes).
      1. $pageFilePath = "D:\custom.master"  
      2. $pageFilePath = Get-ChildItem $pageFilePath  
      3. $fileBytes = [System.IO.File]::ReadAllBytes($pageFilePath.FullName)  
  • Set the master page file details.
    • Initialize file creation information object to set the master page file properties to be uploaded. 
    • To the object created, set the necessary parameters like URL, content. Overwrite parameter can be used to force write the file to the server.
      1.   
      2. $newFileInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation  
      3. $newFileInfo.Url = $pageFilePath.Name  
      4. $newFileInfo.Content = $fileBytes  
      5. $newFileInfo.Overwrite = $true  
  • Access the folder and add the master page.
    • Using the context, access the web. It should be root web since master page gallery is present at the top level site.
    • Then access the master page gallery folder using web and GetByTitle method.
    • From the web, get the source list and destination list using the list names. Then access the appropriate folder and the files method to add our new master page. Add new file creation information object created above. Load and execute the query.
      1. $web = $ctx.Site.RootWeb  
      2. $folder = $web.Lists.GetByTitle("Master Page Gallery")  
      3. $masterPage = $folder.RootFolder.Files.Add($newFileInfo)  
      4. $ctx.Load($web)  
      5. $ctx.Load($masterPage)  
      6. $ctx.ExecuteQuery()  
  • Publish as major version.
    • Then to publish the master page, we need to check out the file. Check out is required since the master page is neither checked out nor checked in as major version when the master page is uploaded. Load and execute the query for check out operation.
    •  Then check in the master page with comments and check in type. Check in type should be major version.
      1. #Check Out  
      2. $masterPage.CheckOut()  
      3. $ctx.Load($masterPage)  
      4. $ctx.ExecuteQuery()  
      5. #Check In and Publish  
      6. $masterPage.CheckIn("Majorversion checkin",[Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn)  
      7. $ctx.Load($masterPage)  
      8. $ctx.ExecuteQuery()  
  • We have successfully uploaded the master page. No we will apply the master page to the site. 
    • From the web object, access the custom master url property and set the master page relative url. 
    • To set master page for custom pages, use CustomMasterUrl property. 
    • To set master page for system master pages, use MasterUrl property. 
    • After setting the properties, update the web object. Then load and execute the web object with the context.
      1. $web.CustomMasterUrl = $masterPage.ServerRelativeUrl  
      2. $web.MasterUrl = $masterPage.ServerRelativeUrl  
      3. $web.Update()  
      4. $ctx.Load($web)  
      5. $ctx.ExecuteQuery()  
The above steps will help us in uploading and setting the master page. The article focused on setting master pages for root level sites. If the master page needs to be set for subsite, then corresponding web object needs to be created before applying master page.

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. });  


Update User Profile Properties On SharePoint Online Using CSOM PowerShell


In this article, you will learn how to update SharePoint user profile properties programmatically in different ways using CSOM with PowerShell on SharePoint online - Office 365 sites. The update property option is available only on Office 365 sites as of now and it is not available on on-premise versions.


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 and UserProfile dll. The references should be from 16 folder, since these are latest updates from Microsoft.
    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 get it set 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. There are multiple ways of updating the properties of SharePoint user profile. There will be properties with just a value or line of text and properties with collection of values. Two different methods are used to update those properties. Following tells us with examples. 
    • Single Value properties - WorkPhone, Mobile, FirstName, LastName, etc. 
    • Multi Valued properties - Ask Me About, Skills, Interests, etc. 


Update Single Value Properties:

  • Initialize the people manager object with the context to get the user profile data.
  • Using SetSingleValueProfileProperty method set the property for any target user.
  • Load the object and execute query to get the data.
    1. # Update User Profile property (office 365)  
    2. function SetSingleValueProperty(){  
    3.     try{  
    4.         $peopleManager = New-Object Microsoft.SharePoint.Client.UserProfiles.PeopleManager($ctx)                  
    5.         $peopleManager.SetSingleValueProfileProperty("i:0#.f|membership|abc@abc.onmicrosoft.com""AboutMe""Your description")  
    6.         $ctx.Load($peopleManager)  
    7.         $ctx.ExecuteQuery()  
    8.         Write-Host "Property updated"  
    9.     }  
    10.     catch{  
    11.         Write-Host "$($_.Exception.Message)" -foregroundcolor Red  
    12.     }  
    13. }  
You can update as many properties as possible. 
  1. $peopleManager = New-Object Microsoft.SharePoint.Client.UserProfiles.PeopleManager($ctx)                  
  2. $peopleManager.SetSingleValueProfileProperty("i:0#.f|membership|abc@abc.onmicrosoft.com""AboutMe""Your description")  
  3. $peopleManager.SetSingleValueProfileProperty("i:0#.f|membership|abc@abc.onmicrosoft.com""SPS-Location""Bangalore")  
  4. $ctx.Load($peopleManager)  
  5. $ctx.ExecuteQuery()  
  6. Write-Host "Properties updated"   


Update Multi Valued Properties:

In the above section, we have seen how we can set the single value profile properties for target user. Now we will see how we can set user profile multi valued properties for target user.
  • Initialize the people manager object with the context to get the user profile data.
  • Then initialize the list collection object and set the values in the collection variable.
  • Using SetMultiValuedProfileProperty method, set the multi valued property for any target user. (Here updated ask me about - Responsibility field).
  • Load the object and execute query to get the data.
    1. # Update User Profile Multi Valued properties (office 365)  
    2. function SetMultiValuedProperty(){  
    3.     try{  
    4.         $peopleManager = New-Object Microsoft.SharePoint.Client.UserProfiles.PeopleManager($ctx)                  
    5.         $propertyValues =New-Object "System.Collections.Generic.List``1[System.string]"  
    6.         # My responsibilities  
    7.         $propertyValues.Add("SharePoint")  
    8.         $propertyValues.Add("Project1")          
    9.         $propertyValues.Add("Project2")          
    10.         #update value  
    11.         $peopleManager.SetMultiValuedProfileProperty("i:0#.f|membership|abc@abc.onmicrosoft.com""SPS-Responsibility", $propertyValues)  
    12.         $ctx.Load($peopleManager)  
    13.         $ctx.ExecuteQuery()  
    14.     }  
    15.     catch{  
    16.         Write-Host "$($_.Exception.Message)" -foregroundcolor Red  
    17.     }  
    18. }  
The above operation will override (set) the existing property values. If you want to update the existing property values, you need to retrieve the existing value using get operation and then set the properties along with new values.

Note: The above set of operations needs to be called to get it executed.
  1. SetSingleValueProperty # Update User Profile properties (office 365)  
  2. SetMultiValuedProperty # Update User Profile Multi Valued properties (office 365)