Client-side object model – SharePoint Online

What is CSOM? What can it do for SharePoint developers and IT professionals? Most of the SharePoint developers use CSOM in the code and all are familiar with .NET. So, in this topic we would like to share CSOM and its importance. CSOM includes JavaScript object model (JSOM). Developers think a lot before consuming REST, CSOM, and web services for either developing or helping IT Professionals in automation tasks. Each has its own pros and cons. It depends on when and how we use it. So, let us ignore REST and web service for now, and focus on CSOM, because this works based on the .NET Client-side object model of the SharePoint platform.

  • CSOM is an acronym for Client-side object model
  • CSOM provides a subset of the Server Object Model
  • CSOM supports remote execution via JavaScript and .NET
  • CSOM allows Collaborative Application Markup Language (CAML) query to query SharePoint lists
  • CSOM has three distinct API, these are:
    1. .NET managed client object.

      This has more subsets of functionalities which allow developers and IT professionals to make use of it

    2. ECMAScript.
    3. Silverlight client object model.

Following are the download links:

The installation is similar to LYNC SDK—just download the required version and proceed with installation.

How does CSOM Work?

The basic usage of Windows PowerShell is by declaring a variable, we load the context, execute the query, and get the result from the variable. To know more about request batching using CAML, LINQ, and so on, refer to the following link:

https://msdn.microsoft.com/en-us/library/ff798388.aspx?f=255&MSPPError=-2147217396

In this exercise we will do different tasks on the SharePoint Online site using CSOM and PowerShell.

We have some basic information about the CSOM; this greatly integrates SharePoint IT professionals and developers.

Note

If you are looking for PowerShell tools for your Visual Studio, refer to the following link:

https://visualstudiogallery.msdn.microsoft.com/c9eb3ba8-0c59-4944-9a62-6eee37294597

One most common scenario in SharePoint is to audit a user profile; most of the organizations need it either to audit, or to ensure users align with corporate standards by updating their profile information. Most of the fields are mapped with active directory with a few exceptions for fields like date of birth, skills, interests, or any custom property we created in SharePoint user profile application.

In this topic we will cover a demo of below tasks using CSOM:

  • Exporting user profiles
  • Creating and deleting Lists
  • Manipulating web settings

Using PowerShell and CSOM we can easily query the user profile information and export to CSV. Execute the following code:

#Import the required DLL
Import-Module 'C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions15ISAPIMicrosoft.SharePoint.Client.UserProfiles.dll'
#Mysite URL
$site = 'https://Domain-my.sharepoint.com/'
#Admin User Principal Name
$admin = '[email protected]'
#Get Password as secure String
$password = Read-Host 'Enter Password' -AsSecureString
#Get the Client Context and Bind the Site Collection
$context = New-Object Microsoft.SharePoint.Client.ClientContext($site)
#Authenticate
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($admin , $password)
$context.Credentials = $credentials
#Fetch the users in Site Collection
$users = $context.Web.SiteUsers
$context.Load($users)
$context.ExecuteQuery()
#Create an Object [People Manager] to retrieve profile information
$people = New-Object Microsoft.SharePoint.Client.UserProfiles.PeopleManager($context)
$collection = @()
Foreach($user in $users)
{
    $userprofile = $people.GetPropertiesFor($user.LoginName)
    $context.Load($userprofile)
    $context.ExecuteQuery()
    if($userprofile.Email -ne $null)
    {
        $upp = $userprofile.UserProfileProperties
        foreach($ups in $upp)
        {
            $profileData = "" | Select "FirstName" , "LastName" , "WorkEmail" , "Title" , "Responsibility"
            $profileData.FirstName = $ups.FirstName
            $profileData.LastName = $ups.LastName
            $profileData.WorkEmail = $ups.WorkEmail
            $profileData.Responsibility = $ups.'SPS-Responsibility'
            $collection += $profileData
        }
    }
}
$collection | Export-Csv C:TempSPO-UserInformation.csv -NoTypeInformation -Encoding UTF8

The output is illustrated in the following screenshot:

How does CSOM Work?

We can add the properties to get more information based on settings in your SharePoint farm.

Creating and deleting list

Using CSOM we can create lists and delete lists—below is the code for the same.

Following is the code for creating list:

#Import the required DLL
Import-Module 'C:TempCSOMMicrosoft.SharePoint.Client.dll'
Import-Module 'C:TempCSOMMicrosoft.SharePoint.Client.Runtime.dll'
$site = 'https://Chensoffice365.sharepoint.com/'
$admin = '[email protected]'
$password = Read-Host 'Enter Password' -AsSecureString
$context = New-Object Microsoft.SharePoint.Client.ClientContext($site)
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($admin , $password)
$context.Credentials = $credentials
$site = $context.Web
$context.Load($site)
$context.ExecuteQuery()
#Create List
$listinfo =New-Object Microsoft.SharePoint.Client.ListCreationInformation
$listinfo.Title = 'CSOM List'
$listinfo.TemplateType = [Microsoft.SharePoint.Client.ListTemplateType]'GenericList'
$list = $Site.Lists.Add($listinfo)
$context.ExecuteQuery()
Write-Host "Successfully Created List $($listinfo.Title)"

After the successful execution of this code we can see the list in our site as shown in the following image:

Creating and deleting list

The following code simply deletes the list. Please ensure to check the names and ID:

Import-Module 'C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions15ISAPIMicrosoft.SharePoint.Client.Runtime.dll'
#OR
Add-Type -Path 'C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions15ISAPIMicrosoft.SharePoint.Client.dll'
#Site URL
$site = 'https://Domain.sharepoint.com/'
#Admin User Principal Name
$admin = '[email protected]'
#Get Password as secure String
$password = Read-Host 'Enter Password' -AsSecureString
#Get the Client Context and Bind the Site Collection
$context = New-Object Microsoft.SharePoint.Client.ClientContext($site)
#Authenticate
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($admin , $password)
$context.Credentials = $credentials
#Delete List
$list = $context.Web.Lists.GetByTitle('PowerShell CSOM')
$context.Load($list)
$list.DeleteObject()
$list.Update()

Making PowerShell modules with SDKs

So far we have seen three different technologies, namely Exchange Online, Lync and SharePoint along with creating smaller tasks using the API with DLL and web services. In the next exercise we will build another binary module which combines all the above sample code and delivers nice PowerShell cmdlets to do the tasks. This is just a sample code you can start building on your own for your environment.

The following code is a binary module built using C# which has three cmdlets:

  • Add-LyncPersonalNote: Adds/updates your LYNC personal note status
  • Get-OSInformation: Retrieves OS information—just .NET way
  • Get-PhotoStatus: Retrieves LYNC photo status

The code is as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
using Microsoft.Lync.Model;
using System.Collections.ObjectModel;
namespace OfficeServers
{
    [Cmdlet(VerbsCommon.Get,"PhotoStatus")]
    public class PhotoStatus : PSCmdlet
    {
        protected override void ProcessRecord()
        {
            //base.ProcessRecord();
            Console.WriteLine("Lync Group Name Information....");
            var cl = LyncClient.GetClient();
            bool photo = cl.Self.PhotoDisplayed;
            if(photo == true)
            {
                Console.WriteLine("Photo will be visible to others!");
            }
            else 
            {
                Console.WriteLine("Photo is hidden!");
            }
        }
    }
    [Cmdlet(VerbsCommon.Get,"OSInformation")]
    public class OSInformation : PSCmdlet
    {
        protected override void ProcessRecord()
        {
            //base.ProcessRecord();
            Console.WriteLine("OS Version is {0}", (Environment.OSVersion).ToString());
        }
    }
    [Cmdlet(VerbsCommon.Add, "LyncPersonalNote")]
    public class LyncPersonalNote : PSCmdlet
    {
        [Parameter(Mandatory = true)]
        public string notetext{get;set;}
        protected override void ProcessRecord()
        {
            //base.ProcessRecord();
            var cl = LyncClient.GetClient();
            var self = cl.Self;
            var noteinfo = new System.Collections.Generic.Dictionary<Microsoft.Lync.Model.PublishableContactInformationType, Object>();
            noteinfo.Add(Microsoft.Lync.Model.PublishableContactInformationType.PersonalNote,notetext);
            self.BeginPublishContactInformation(noteinfo,null,null);
            //self.EndPublishContactInformation(noteinfo);
        }
    }
}

After building the solution, the DLL will be located in the project folder. So, we need to import the module and test the output. Following are the steps:

  1. Following is the command to import cmdlets:
    Import-Module C:TempOfficeServersOfficeServersinDebugOfficeServers.dll -Verbose
    

    This code will import the cmdlets as illustrated in the following figure:

    Making PowerShell modules with SDKs
  2. Following command lists all cmdlets in the OfficeServers module:
    Get-Command -Module OfficeServers
    

    Following figure illustrates the output of this command:

    Making PowerShell modules with SDKs
  3. Let's test the following command:
    Add-LyncPersonalNote -notetext "This is Automated!"
    

    Following figure illustrates the output of this command:

    Making PowerShell modules with SDKs

    Execute the following command:

    Get-OSInformation
    

    Following figure illustrates the output of this command:

    Making PowerShell modules with SDKs

    Execute the following command:

    Get-PhotoStatus
    

    Following figure illustrates the output of this command:

    Making PowerShell modules with SDKs
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset