Welcome to a short tutorial that introduces you to the Client Side Object Model in SharePoint. Long ago, all the coding had to be done on the server. The server takes care of your business logic and the results are returned to the client. Slowly, the client machines are able to do most of the business logic much faster. The client machines you use now are Old Powerful servers.
Why did CSOM get introduced?
Before, we look at CSOM, let’s brush up the concepts of the old SSOM model or Server Side Object Model. In SSOM, you would code directly on the SharePoint. Specifically, you’d log-in to the SharePoint Server, install your development tools and start coding. Every SharePoint Object in SSOM starts with SP. Example:
- A web object is called “SPWeb”
- A list object is called “SPList”
In CSOM, the “SP” is gone. In addition to this, the worries that server-side coding brought with it are also gone. Administrators were fearful that server-side coding in web parts would harm the server in a variety of ways. For example, if the code was poorly written without any concern for performance or security then it was possible to either bring down the server or create a security issue.
If you are wondering … why not use REST instead of CSOM? Personally, writing REST queries is a headache for me. I have spent hours fixing a typo or parsing the JSON results that I need to get the job done. I can develop CSOM code much faster than REST. CSOM code is very clean if written in C# or PowerShell.
CSOM Code Structure
Any CSOM code has the following steps:
- Obtain a Site Context for a given Site URL.
- Load the context with the site object you need to use like a Site, Web or List.
- Call the ExecuteQuery.
- Access the properties of the object.
If you cannot remember the above steps, here is a real-world scenario to help you remember.
- Imagine you are making a new Garden in London
- You load your Garden location with objects like tools, seeds
- Wait for the seeds to bloom
- Then, watch the flowers
Just as you can see the flowers only after some waiting, the CSOM results can never be seen without the ExecuteQuery method. This is a very common mistake and hence, remember to use ExecuteQuery if you do not see the results even after loading the site objects.
CSOM with PowerShell
There are various ways to do CSOM coding. Let’s start with the simplest tool like PowerShell which doesn’t require a lengthy install proces. Download the SharePoint Online Client components from Microsoft. The DLL’s are downloaded in the following location:
C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions16ISAPI
Any CSOM code begins with a Connection to the SharePoint Site. Below is the code which connects using the credentials you give.
#Specify tenant admin and site URL $User = "[email protected]" $SiteURL = "https://xxx.sharepoint.com/sites/dev" #Add references to SharePoint client assemblies $spPath="C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions16ISAPI" Add-Type -Path ($spPath+"Microsoft.SharePoint.Client.dll") Add-Type -Path ($spPath+"Microsoft.SharePoint.Client.Runtime.dll") Add-Type -Path ($spPath+"Microsoft.SharePoint.Client.Search.dll") Add-Type -Path ($spPath+"Microsoft.SharePoint.Client.Taxonomy.dll") Add-Type -Path ($spPath+"Microsoft.SharePoint.Client.Publishing.dll") Add-Type -Path ($spPath+"Microsoft.SharePoint.Client.UserProfiles.dll") $Password = Read-Host -Prompt "Please enter your password" -AsSecureString $Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password) #Bind to site collection $Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL) $Context.Credentials = $Creds
Let’s look at CRUD examples on SharePoint List. We do the following operations:
- Create a list named Fruits
- Update Fruits List
- Read Fruits List
- Delete Mango Fruit
Below is the code to create a Fruits list. Any creation in CSOM mostly uses a CreationInformation Object.
$listInfo = New-Object Microsoft.SharePoint.Client.ListCreationInformation $listInfo.Title="Fruits" $listInfo.TemplateType=[Microsoft.SharePoint.Client.ListTemplateType]::GenericList $psList=$context.Web.Lists.Add($listInfo) $Context.ExecuteQuery()
Update the description of Fruits List. Use the “Update” method.
$psList.Description = "Fruits List through code" $psList.Update() $Context.ExecuteQuery()
List all items in Fruits list
$camlQ= [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery() $listItems=$psListFruits.GetItems($camlQ) $Context.Load($listItems) $Context.ExecuteQuery()
Delete a Mango in Fruits list
You can view more CSOM that creates a Site, adds items to a List from here.
CSOM code is extremely powerful and helps you accomplish almost anything which cannot be done in REST or PnP. PnP uses CSOM to get many common requirements on SharePoint Sites, Lists, Files and many objects. While writing CSOM code, here are some tips to ensure your code works best in all scenarios:
- Load only the objects you need and not all objects. For example, use CAML Query to get subset of List data based on some criteria.
- Load only the properties you need.
- Do not call ExecuteQuery() unnecessarily. Mostly, calling ExecuteQuery at the end of your logic is enough.
- Make sure that the app/user running the code has the permissions to the SharePoint objects.
- If your application Logic is complex, log the errors and information into a SharePoint Log_App_Name list.
- Use try/catch to log the errors.
- If your code is moving from DEV to UAT to PROD, get the Item by Name and not any specific ID.
- If performance is a concern with large data, use GUID to get the specific item.
Finally, If you do not like CSOM and would like to learn about REST or PNP, check out my other blogs posts below.