Useful CSOM Snippets

Introduction

In this article, we will learn about some important Csom codes used for SharePoint operations
 
Nuget Package Required:
  1. SharePointPnPCoreOnline  
Required imports are:
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Text;    
  5. using System.Threading.Tasks;    
  6. using Microsoft.SharePoint.Client;    
  7. using OfficeDevPnP.Core;     
Authenticating with Sharepoint:
  1. string siteUrl = "Your Site Collection Url";  
  2.             string userName = "UserName of Account";  
  3.             string password = "Password";  
  4.             OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager();  
  5.             using (var clientContext= authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))  
The above code creates authentication with Sharepoint with a valid username and password. It returns a clientcontext object. With the clientcontext object, we will do our required operations in Sharepoint.
 
Getting Listitems from sharepoint
  1. string listName = "mynewlist";   
  2.    List list = clientContext.Web.Lists.GetByTitle(listName);    
  3. clientContext.Load(List);  
  4.          if (list != null)    
  5.                   {    
  6.                       CamlQuery query = CamlQuery.CreateAllItemsQuery(100);    
  7.                       ListItemCollection items = list.GetItems(query);    
  8.                       clientContext.Load(items);    
  9.                       clientContext.ExecuteQuery();    
  10.                   foreach (ListItem listItem in items)    
  11.                   {    
  12.                       Console.WriteLine(listItem.FieldValues["ID"]);    
  13.                   }    
  14.               }    
  15.     
  16.                   else    
  17.                   {    
  18.                       Console.WriteLine("List is not available on the site");    
  19.                   }    
The above code returns items from the sharepoint list, depending upon the caml query provided.
 
Creating new items in the SharePoint list
  1. string listName = "mynewlist";    
  2.    List list = clientContext.Web.Lists.GetByTitle(listName);   
  3. clientContext.Load(List);
  4.    if (list != null)  
  5.                 {  
  6.                     ListItemCreationInformation newItem = new ListItemCreationInformation();  
  7.                     ListItem listItem = list.AddItem(newItem);  
  8.                     listItem["Title"] = "Madhan";  
  9.                     listItem.Update();  
  10.                     clientContext.ExecuteQuery();  
  11.                 }  
  12.   
  13.                 else  
  14.                 {  
  15.                     Console.WriteLine("List is not available on the site");  
  16.                 }  
The above code will insert a new item in the SharePoint list (i.e. create a new id and Title  value as Madhan)
 
 Updating Listitem in sharepoint
  1. string listName = "mynewlist";      
  2.    List list = clientContext.Web.Lists.GetByTitle(listName);  
  3. clientContext.Load(List);
  4. if (list != null)  
  5.                 {  
  6.                       
  7.                     ListItem oListItem = list.GetItemById(5);  
  8.                     clientContext.Load(oListItem);  
  9.                     clientContext.ExecuteQuery();  
  10.                     // clientContext.ExecuteQuery();  
  11.                     if (oListItem.FieldValues.Count >0) {   
  12.                     oListItem["Title"] = "My Updated Title.";  
  13.   
  14.                     oListItem.Update();  
  15.   
  16.                     clientContext.ExecuteQueryRetry(); }  
  17.                 }  
  18.   
  19.                 else  
  20.                 {  
  21.                     Console.WriteLine("List is not available on the site");  
  22.                 }  
 Basically updating and deleting are processed based on ID, the above code will update the value of Title field  to "My Updated Title" for Id "5" in the SharePoint list mynewlist
 
Deleting a ListItem in Sharepoint
  1. string listName = "mynewlist";        
  2.    List list = clientContext.Web.Lists.GetByTitle(listName); 
  3. clientContext.Load(List);   
  4.               ListItem oListItem = list.GetItemById(5);  
  5.                     clientContext.Load(oListItem);  
  6.                     clientContext.ExecuteQuery();  
  7.                     if (oListItem.FieldValues.Count > 0)  
  8.                     {  
  9.                         oListItem.DeleteObject();  
  10.   
  11.                         clientContext.ExecuteQuery();  
  12.                     }  
  13.                 }  
  14.   
  15.                 else  
  16.                 {  
  17.                     Console.WriteLine("List is not available on the site");  
  18.                 }  
As I said earlier, deleting an item is based on ID. The above code will delete the listitem corresponding to the ID "5" 
 
Creating a New List
  1. clientContext.Web.CreateList(ListTemplateType.DocumentLibrary, "WithPnpDOC",false);  
The above code will create a new document library in the Sharepoint site. We want to provide a valid listtemplatetype for creating various lists. The types are:
 
GenericList 100 0 A basic list which can be adapted for multiple purposes.
DocumentLibrary 101 1 Contains a list of documents and other files.
Survey 102 4 Fields on a survey list represent questions that are asked of survey participants. Items in a list represent a set of responses to a particular survey.
Links 103 0 Contains a list of hyperlinks and their descriptions.
Announcements 104 0 Contains a set of simple announcements.
Contacts 105 0 Contains a list of contacts used for tracking people in a site.
Events 106 0 Contains a list of single and recurring events. An events list typically has special views for displaying events on a calendar.
Tasks 107 0 Contains a list of items that represent completed and pending work items.
DiscussionBoard 108 0 Contains discussions topics and their replies.
PictureLibrary 109 1 Contains a library adapted for storing and viewing digital pictures.
DataSources 110 1 Contains data connection description files.
XmlForm 115 1 Contains XML documents. An XML form library can also contain templates for displaying and editing XML files via forms, as well as rules for specifying how XML data is converted to and from list items.
NoCodeWorkflows 117 1 Contains additional workflow definitions that describe new processes that can be used within lists. These workflow definitions do not contain advanced code-based extensions.
WorkflowProcess 118 0 Contains a list used to support execution of custom workflow process actions.
WebPageLibrary 119 1 Contains a set of editable Web pages.
CustomGrid 120 0 Contains a set of list items with a grid-editing view.
WorkflowHistory 140 0 Contains a set of history items for instances of workflows.
GanttTasks 150 0 Contains a list of tasks with specialized Gantt views of task data.
IssuesTracking 1100 5 Contains a list of items used to track issues.
 
Checking if the folder exists. If not, then creating a new folder:
  1. string listName = "mynewlist";          
  2.    List list = clientContext.Web.Lists.GetByTitle(listName); 
  3. clientContext.Load(List);  
  4. var  folder = list1.RootFolder.EnsureFolder("WithPnpDOC1");  
As the heading describes, it checks the library with the foldername "WithPnpDOC1". If it does not exist, it will create a new folder.
 
Creating a new Folder without checking existing
  1. string listName = "mynewlist";            
  2.    List list = clientContext.Web.Lists.GetByTitle(listName);  
  3. clientContext.Load(List);
  4. var folder = list.RootFolder.CreateFolder("WithPnpDOC");  
Simply creates the new folder in the Sharepoint document library
 
Creating Contenttype
  1. clientContext.Web.CreateContentType("Contenttype name""description""Guid ""Group");  
The above code will create new contenttype in Sharepoint where the name and guid are unique. In the Guid, starting characters represents the parent content type. The available types are:
  • System    0x
  • Item    0x01
  • Document    0x0101
  • Event    0x0102
  • Issue    0x0103
  • Announcement    0x0104
  • Link    0x0105
  • Contact    0x0106
  • Message    0x0107
  • Task    0x0108
  • Workflow History    0x0109
  • Post    0x0110
  • Comment    0x0111
  • Folder    x0120
e.g.
  1. clientContext.Web.CreateContentType("PNP doc3""My Desc""0x010100C2D5F149518B119D801AC6C18942554A""PNP grp CT");   
Adding fields to Content Type
  1. string fieldIdStr = "5b0a8635-49a5-469f-8d42-1b92e8d4e17b";  
  2.                   string contentTypeName = "PNP Ct";  
  3.                   bool isRequired = false;  
  4.                   bool isHidden = false;  
  5.                   // Field As Guid    
  6.                   Guid fieldId = new Guid(fieldIdStr);  
  7.                   // Adds Field to Content Type using Name    
  8.                   clientContext.Web.AddFieldToContentTypeByName(contentTypeName, fieldId, isRequired, isHidden);  
The above code will add sitecolumns field to content type PNP ct where guid is the valid site column guid.
 
Setting default Content type to list
  1. clientContext.Web.SetDefaultContentTypeToList("mynewlist""0x0100A33D9AD9805788419BDAAC2CCB37509F");  
The above code will sets the default contenttype to the list ,where the first parameter is listname, the next one is contenttype Guid
 
Creating Fields and SiteColumn
  1. string displayName = "TestColumn2";  
  2.               string internalName = "TestColumn2";  
  3.               string groupName = "TestPnPGroup";  
  4.       string fieldId = "4FDD339E-6B98-4A11-B1AC-9C6B8C37AE2E";  
  5.               FieldType fieldType = FieldType.DateTime;  
  6.               OfficeDevPnP.Core.Entities.FieldCreationInformation newFieldInfo = new OfficeDevPnP.Core.Entities.FieldCreationInformation(fieldType)  
  7.               {  
  8.                   DisplayName = displayName,  
  9.                   InternalName = internalName,  
  10.                   Id = new Guid(fieldId),  
  11.                   Group = groupName  
  12.               };  
  13.               // Creates new Field    
  14.               Field newField = mycleint.Web.CreateField(newFieldInfo);  
The above code creates a new datetime site column in your Sharepoint site with the name TestColumn2
  1. string listName = "mynewlist";
    List list = clientContext.Web.Lists.GetByTitle(listName);
    clientContext.Load(List);
  2. OfficeDevPnP.Core.Entities.FieldCreationInformation fldEmpID = new OfficeDevPnP.Core.Entities.FieldCreationInformation(FieldType.Number);  
  3.                fldEmpID.DisplayName = "Employee IDd";  
  4.                fldEmpID.InternalName = "EmpIDd";  
  5.                fldEmpID.AddToDefaultView = true;  
  6.                fldEmpID.Id = Guid.NewGuid();  
  7.                list.CreateField(fldEmpID);  
  8.                list.Update();  
  9.                mycleint.ExecuteQueryRetry();  
The above code creates new number field with name Employee IDd in the list "mynewlist" the available types are:
  • Invalid = 0,
  • Integer = 1,
  • Text = 2,
  • Note = 3,
  • DateTime = 4,
  • Counter = 5,
  • Choice = 6,
  • Lookup = 7,
  • Boolean = 8,
  • Number = 9,
  • Currency = 10,
  • URL = 11,
  • Computed = 12,
  • Threading = 13,
  • Guid = 14,
  • MultiChoice = 15,
  • GridChoice = 16,
  • Calculated = 17,
  • File = 18,
  • Attachments = 19,
  • User = 20,
  • Recurrence = 21,
  • CrossProjectLink = 22,
  • ModStat = 23,
  • Error = 24,
  • ContentTypeId = 25,
  • PageSeparator = 26,
  • ThreadIndex = 27,
  • WorkflowStatus = 28,
  • AllDayEvent = 29,
  • WorkflowEventType = 30,
  • Geolocation = 31,
  • OutcomeChoice = 32,
  • Location = 33,
  • Thumbnail = 34,
  • MaxItems = 35

Conclusion

We have learned some crucial operations in SharePoint using PnpCore CSOM. Hope this helps somone. Happy Coding! :)