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?

Course Booking Details:

DatesDetailsOfferBook
Jan 3, 2019 – Jan 31, 2019XMAS2018Book

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:

  1. Obtain a Site Context for a given Site URL. 
  2. Load the context with the site object you need to use like a Site, Web or List.
  3. Call the ExecuteQuery.
  4. Access the properties of the object.
    CSOM

    CSOM Thangu

If you cannot remember the above steps, here is a real-world scenario to help you remember. 

  1. Imagine you are making a new Garden in London
  2. You load your Garden location with objects like tools, seeds
  3. Wait for the seeds to bloom
  4. 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

Connection Code

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

CRUD Operations

Let’s look at CRUD examples on SharePoint List. We do the following operations:

  1. Create a list named Fruits
  2. Update Fruits List
  3. Read Fruits List
  4. 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

$mangoid=$mangoItem.Recycle()
$Context.ExecuteQuery()

You can view more CSOM  that creates a Site, adds items to a List from here.

Best Practices

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:

  1. 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.
  2. Load only the properties you need. 
  3. Do not call ExecuteQuery() unnecessarily. Mostly, calling ExecuteQuery at the end of your logic is enough.
  4. Make sure that the app/user running the code has the permissions to the SharePoint objects.
  5. If your application Logic is complex, log the errors and information into a SharePoint Log_App_Name list.
  6. Use try/catch to log the errors.
  7. If your code is moving from DEV to UAT to PROD, get the Item by Name and not any specific ID.
  8. 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.

 

 

(307)

Course Booking Details:

DatesDetailsOfferBook
Jan 3, 2019 – Jan 31, 2019XMAS2018Book
5/5 (2)

Please rate this

Views: 307  | Categories: Development, SharePoint
About The Author
- I love exploring SharePoint and talking about SharePoint. Few of my contributions can be viewed here https://www.youtube.com/channel/UCGqSWCnFPZ4GuPEwjtCYx1A/videos?sort=dd&view=0&shelf_id=0