PNP Core Csom Programming Basic Operations On Sharepoint Using PNP Core Csom Lib
PNP Core Csom Programming Basic Operations On Sharepoint Using PNP Core Csom Lib
Programming
Basic Operations on SharePoint Using
PnP Core CSOM Library
Nakkeeran Natarajan
About the Author
Nakkeeran Natarajan have been working in IT industry over 5 years and have more than 4
years of experience in SharePoint technology.
Nakkeeran holds master’s degree in Computer Science and Engineering from VIT University.
He has started his career as intern from Honeywell Technology Solutions, Bengaluru. He is
working as a Senior Software Consultant in Cognizant Technology Solutions, Bengaluru. He
is involved in architecting, designing, developing solutions and SharePoint training.
Nakkeeran currently hold Most Valued Professional award from C# Corner forum
(Mindcracker Network). He has shared over 100 articles of SharePoint on C# Corner forum.
He has also authored a book on SharePoint PnP PowerShell Scripts programming. He has
produced reusable components and white papers on SharePoint technology.
Nakkeeran Nataraja
(Author, Blogger & C# Corner MVP
Senior SharePoint Developer)
Acknowledgment
I would like to thank Mahesh Chand, Praveen Kumar and Dinesh Beniwal from C# Corner
core team for their continuous support on C# Corner forum. I would also like to thank the
technical team who helps me in reviewing the content on the forum.
I am thankful to my colleagues and mentors for their support. My special thanks for Vijai
Anand and Ramakrishnan who always support and guide me in sharing my knowledge
through books, blogs and articles.
I am really grateful for my friends and family members who motivate me in sharing the
knowledge.
Table of Contents
1 SharePoint PnP Core CSOM Overview ............................................................................................ 1
2 Prerequisites ................................................................................................................................... 2
3 Tool Used ........................................................................................................................................ 2
4 Connect to SharePoint site ............................................................................................................. 3
5 SharePoint Site Operations ............................................................................................................. 8
5.1 How to create a sub site ......................................................................................................... 8
5.2 How to retrieve sub site URL’s .............................................................................................. 10
5.3 How to retrieve sub site ........................................................................................................ 11
5.4 How to check if Sub Site Exists .............................................................................................. 12
5.5 How to check if current web is sub site ................................................................................ 13
5.6 How to delete a sub site ....................................................................................................... 14
5.7 How to enable a feature (site scoped) on a site collection .................................................. 15
5.8 How to disable a feature (site scoped) on a site collection .................................................. 17
5.9 How to check if site collection feature is active (site scoped) .............................................. 18
5.10 How to enable a feature (web scoped) on a site or a sub site ............................................. 19
5.11 How to disable a feature (web scoped) on a site or a sub site ............................................. 21
5.12 How to check if site feature is active (web scoped) ............................................................. 22
6 SharePoint List Operations ........................................................................................................... 24
6.1 How to create a list ............................................................................................................... 24
6.2 How to check if list exists using list name ............................................................................. 26
6.3 How to check if list exists using list ID .................................................................................. 27
6.4 How to retrieve a list using list name ................................................................................... 28
6.5 How to retrieve a list using list URL ...................................................................................... 30
6.6 How to retrieve a list ID ........................................................................................................ 31
6.7 How to update permissions on the list ................................................................................. 32
6.8 How to enable versioning for the list.................................................................................... 34
7 SharePoint List View Operations................................................................................................... 36
7.1 How to create a list view....................................................................................................... 36
7.2 How to retrieve a list view using view name ........................................................................ 38
7.3 How to retrieve a list view using view Id .............................................................................. 39
8 SharePoint Content Type Operations ........................................................................................... 41
8.1 How to retrieve site content type by content type name .................................................... 41
8.2 How to retrieve site content type by content type Id .......................................................... 43
8.3 How to create a site content type ........................................................................................ 45
8.4 How to create a site content type using content type XML ................................................. 47
8.5 How to check if a site content type already exists by content type name ........................... 49
8.6 How to check if a site content type already exists by content type Id ................................. 51
8.7 How to add site content type to List..................................................................................... 52
8.8 How to add site content type to List By content type Id ...................................................... 54
8.9 How to add site content type to List By content type name ................................................ 56
8.10 How to check if a content type already exists on a List by content type name ................... 57
8.11 How to check if a content type already exists on a List by content type Id ......................... 59
8.12 How to delete a content type by Name ................................................................................ 60
8.13 How to delete a content type by Id ...................................................................................... 61
9 SharePoint Field Operations ......................................................................................................... 63
9.1 How to create a field on SharePoint site .............................................................................. 63
9.2 How to create a field on SharePoint site using Field XML .................................................... 66
9.3 How to retrieve a field using field Id ..................................................................................... 68
9.4 How to check if a field exists using field Id ........................................................................... 70
9.5 How to check if a field exists using field Name ..................................................................... 71
9.6 How to add a field to site content type ................................................................................ 73
9.7 How to add a field to site content type using Content type Id............................................. 75
9.8 How to add a field to site content type using Content type name....................................... 77
9.9 How to check if a field exists in the Content type ................................................................ 79
10 SharePoint Folder tasks ............................................................................................................ 81
10.1 How to create a folder on a library ....................................................................................... 81
10.2 How to check if a folder exists on a library using folder name ............................................. 83
10.3 How to check if a folder exists on a library using folder path .............................................. 84
10.4 How to retrieve folder from library ...................................................................................... 86
10.5 How to check and create a folder on a library using folder name........................................ 87
10.6 How to check and create a folder on a library using folder URL .......................................... 89
11 SharePoint Basic File tasks ........................................................................................................ 91
11.1 How to upload a file .............................................................................................................. 91
11.2 How to retrieve a file ............................................................................................................ 93
11.3 How to download a file ......................................................................................................... 95
11.4 How to check-out a file ......................................................................................................... 96
11.5 How to check-in a file............................................................................................................ 98
11.6 How to update file properties............................................................................................... 99
12 SharePoint Page Tasks ............................................................................................................ 102
12.1 How to create a publishing page ........................................................................................ 102
12.2 How to retrieve a publishing page ...................................................................................... 104
12.3 How to create a wiki page using page name ...................................................................... 105
12.4 How to create a wiki page using URL and file content ....................................................... 106
12.5 How to retrieve wiki page content ..................................................................................... 108
12.6 How to ensure a wiki page .................................................................................................. 109
12.7 How to update a wiki page content .................................................................................... 111
12.8 How to add layout to a wiki page ....................................................................................... 112
12.9 How to retrieve web parts from a page.............................................................................. 114
12.10 How to add web part to a publishing page ..................................................................... 115
12.11 How to delete web part from a page .............................................................................. 117
12.12 How to retrieve web part properties .............................................................................. 118
12.13 How to update web part properties ............................................................................... 120
12.14 How to add web part to a wiki page ............................................................................... 121
13 SharePoint User and Group Operations ................................................................................. 123
13.1 How to retrieve site collection administrator ..................................................................... 123
13.2 How to add site collection administrator ........................................................................... 125
13.3 How to create a SharePoint group...................................................................................... 126
13.4 How to retrieve a SharePoint group ID ............................................................................... 128
13.5 How to check if a SharePoint group exists on Site.............................................................. 129
13.6 How to add User to a SharePoint group ............................................................................. 130
13.7 Add permissions to SharePoint group / Add Groups with permissions to Site (or list or item)
132
13.8 Removes permissions from SharePoint group / Removes group with permissions from site
(or list or item) ................................................................................................................................ 134
13.9 Add permissions to SharePoint User / Add User with permissions to Site (or list or item) 135
13.10 Remove permissions for SharePoint User / Remove User with permissions from Site (or
list or item) ...................................................................................................................................... 137
13.11 Grant read permissions to everyone except external users ........................................... 139
14 Taxonomy Tasks ...................................................................................................................... 141
14.1 How to create Term Group ................................................................................................. 141
14.2 How to ensure Term Group ................................................................................................ 143
14.3 How to retrieve Term Group by Name ............................................................................... 144
14.4 How to retrieve Term Group by ID ..................................................................................... 146
14.5 How to create/ensure Term Set ......................................................................................... 147
14.6 How to retrieve Term Sets .................................................................................................. 148
14.7 How to create a Term on Term Set ..................................................................................... 150
14.8 How to retrieve Term from Term Set ................................................................................. 151
14.9 How to retrieve Term from Term Store by Path ................................................................. 153
14.10 How to import Terms ...................................................................................................... 154
14.11 How to export Term Set .................................................................................................. 156
14.12 How to export all Terms.................................................................................................. 157
14.13 How to create Taxonomy Field on Site/List .................................................................... 159
14.14 How to update Taxonomy Field on List Item .................................................................. 161
14.15 How to remove Taxonomy Field from Site ..................................................................... 162
15 Office 365 Site Collection tasks ............................................................................................... 164
15.1 How to create a site collection on tenant site .................................................................... 164
15.2 How to retrieve site collections from tenant site ............................................................... 166
15.3 How to check if a site collection exists on tenant site ........................................................ 167
15.4 How to delete a site collection ........................................................................................... 169
16 Summary ................................................................................................................................. 171
17 References .............................................................................................................................. 171
1
1 SharePoint PnP Core CSOM Overview
What is PnP? Patterns and Practices where Microsoft and external members contributes to the
implementation practices for SharePoint. PnP libraries are created to serve the needs of
developers for easy learning and implementation of logic through client side programming.
There are various PnP programming methodologies. In this book, I have explained about
implementing PnP programming with .Net managed client side code.
Why we need PnP core CSOM? PnP core library internally has implemented Client Side
Object model for its operations. This in turn makes the operations adaptable. The same set of
operations can be executed on any SharePoint environment. It simplified the remote
development like provider hosted app or windows code. PnP Core CSOM helps users to get
the required information in less piece of code, where in with traditional client side or server
side object model multiple lines of code is required to access objects. The code complexity
reduced through this implementation.
The SharePoint on premise or SharePoint online sites can be managed remotely using PnP
core component. The operations are actually supported by PnP packages/libraries. The PnP
core component libraries are open source extensions on top of classic SharePoint CSOM and
REST APIs. The PnP core CSOM libraries can be imported to user’s machine from the
official site whenever required.
The book is designed for SharePoint developers who can easily learn and implement the
functionalities.
The PnP Core CSOM libraries are available for different versions of SharePoint like
SharePoint 2013 & 2016 on-premises and Office 365 environments.
SharePoint online is part of Office 365 which has/provides powerful features without
managing the infrastructure, while SharePoint on-premises gives us the luxury of accessing
the infrastructure and SharePoint features. There are limited ways of accessing SharePoint
online data compared to SharePoint on-premises. The SharePoint online approach should
have client side methods to access the content. So we can use PnP Core CSOM to access the
SharePoint online objects independent of infrastructure, since Client Side packages are
internally used on PnP libraries. The same can be adapted/compatible for on-premises
environments.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
2
Some of the operations that can be performed on SharePoint are
The operations related to each of the above items are explained in detail in the following
sections.
2 Prerequisites
Here, you will see the prerequisites required for executing any of the PnP Core operations.
The latest version of the packages can be downloaded from Nuget site and installed on NuGet
Package Manager console available on the Visual Studio
(https://www.nuget.org/packages/SharePointPnPCoreOnline/).
In this book, you will see the operations executed on Visual Studio.
The examples explained are compatible for any environment like SharePoint 2013,
SharePoint 2016 and Office 365. I have executed the samples using SharePoint online site.
3 Tool Used
In this book, I have explained about creating/running the code using Microsoft Visual Studio.
The steps explained in the below sections are tested/taken from development environment. If
its production, you have to package the solution developed using below samples and should
be deployed on to the environments using scripts.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
3
4 Connect to SharePoint site
The below operations are executed using Visual Studio. The following steps are used to
create and run the code.
1. Go to Start Menu and search for Visual Studio. Right click on Visual Studio and run
as administrator.
2. Click on File -> New -> Project. Under the templates, navigate to Visual C# and then
select Console Application on the templates pane. Provide the project name and click
on Ok.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
4
3. From menu, navigate to Tools -> NuGet Package Manager -> Package Manager
Console.
4. The NuGet Package Manager console will open in Visual Studio. Depending on the
SharePoint target version, import the package.
a. For SharePoint 2013 sites, import the SharePoint 2013 PnP Core CSOM
package on the console using the command “Install-Package
SharePointPnPCore2013”.
b. For SharePoint 2016 sites, import the SharePoint 2016 PnP Core CSOM
package on the console using the command “Install-Package
SharePointPnPCore2016”.
c. For SharePoint online sites, import the SharePoint online PnP Core CSOM
package on the console, using the command “Install-Package
SharePointPnPCoreOnline”.
For example, I have imported the SharePoint online package as shown below.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
5
Once the command is executed, Visual Studio will take maximum a minute to
complete the installation. The command will run and import the libraries from the
NuGetsite
5. Paste the required code inside the Main method of program file and save the project.
The following steps helps in authentication.
a. For authentication, the required inputs are site URL, User Id and password. In
case if your target version is SharePoint on premise, domain is required as
additional input.
b. Create the authentication manager object.
c. Get the client context of the site by using authentication manager object and
invoke appropriate method with the above inputs.
If your target version is SharePoint online, then method will be
GetSharePointOnlineAuthenticatedContextTenant.
var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName,
password)
var clientContext =
authManager.GetNetworkCredentialAuthenticatedContext(siteUrl, userName,
password, domain)
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
6
d. Subsequently, using the client context obtained, access the necessary
objects/methods.
e. The code snippet given below shows the authentication, also shows the code
logic to check whether the list is exist or not. This code shows for SharePoint
online authentication. For SharePoint On-Premises, put the required
authentication, as explained in step c.
namespace ConnectToSPSite
{
class Program
{
static void Main(string[] args)
{
// Input Parameters
string siteUrl = "https://nakkeerann.sharepoint.com/";
string userName = "abc@nakkeerann.onmicrosoft.com";
string password = "***";
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
// List Name
string listName = "TestList";
bool listExists = clientContext.Site.RootWeb.ListExists(listName);
Console.WriteLine(listExist);
Console.ReadKey();
}
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
7
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
}
}
}
6. If required, keep the breakpoints for debugging the code. For example, go to line
number 32, then go to Debug option Toggle Break Point. Or just press F9 from the
required line.
7. For testing/debugging the code hit F5 or from the top menu, navigate and click on
Debug -> Start Debugging option.
8. You can see necessary information/response on the Debugger console.
Note
In all my examples below, I will be using SharePoint online sites. So SharePoint online
authentication method is used. If your target platform is SharePoint 2013/2016 On-Premise,
then please use the appropriate authentication mechanism as explained in the above steps.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
8
5 SharePoint Site Operations
In this section, you will learn how to perform create, retrieve, check and delete sites using
PnP Core CSOM library. You will also learn the feature operations for the SharePoint sites.
The methods given below are used for the operations/examples explained in this section.
CreateWeb
GetAllWebUrls
GetWeb
WebExists
IsSubSite
DeleteWeb
ActivateFeature
DeactivateFeature
IsFeatureActive
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
In the program file, paste the code given below and save the file.
The input parameters for the operation are given below.
o Sub Site Title
o Sub Site URL
o Description
o Template
o Language
o Inherit Permissions (Boolean)
o Inherit Navigation (Boolean)
Run the code from Debug menu or by pressing F5.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
9
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Gets Sub Site URLs
string subSiteTitle = "SubSite3";
string subSiteUrl = "SubSite3";
string subSiteDesc = "SubSite Created using PnP CSOM";
string subSiteTemplate = "STS#0";
int language = 1033;
bool inheritPermissions = true;
bool inheritNavigation = false;
// Creates Subsite
Web newWebSite = clientContext.Site.RootWeb.CreateWeb(subSiteTitle, subSiteUrl, subSiteDesc,
subSiteTemplate, language, inheritPermissions, inheritNavigation);
Console.WriteLine(newWebSite.Title + " subsite created");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The sub site will be created. You can check the site by pasting the URL
(https://nakkeerann.sharepoint.com/sites/learning/Subsite3) on the Browser.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
10
5.2 How to retrieve sub site URL’s
In this example, you will learn how to retrieve site collection information using PnP Core
CSOM library.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
In the program file, paste the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
// Gets all Subsites
var webs = clientContext.Site.GetAllWebUrls();
Result
The results will be displayed on console, as shown below.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
11
5.3 How to retrieve sub site
In this example, you will learn how to retrieve sub site from SharePoint site, using PnP Core
CSOM. The sub site can be retrieved, using GetWeb method with the help of the root web
object.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The input parameter will be Sub Site leaf URL.
In the program file, paste the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
// Gets Subsite by subsite url
Web web = clientContext.Site.RootWeb.GetWeb("SubSite3");
// Displays server relative Url.
Console.WriteLine(web.ServerRelativeUrl);
Console.ReadKey();
}
}
catch (Exception ex)
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
12
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on console, as shown below.
All the Website properties cannot be accessed directly, using PnP Core CSOM. To access all
the properties, use traditional CSOM managed code.
In this example, you will learn, if the sub site exists on the SharePoint site, using PnP Core
CSOM. The sub site existence can be checked, using WebExists object.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The necessary input parameter is Sub Site leaf URL.
In the program file, paste the code given below and save the file.
Run the code from Debug menu or by pressing F5.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
13
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
// Checks if subsite exists Subsite by subsite url
bool siteExists = clientContext.Site.RootWeb.WebExists("SubSite3");
if (siteExists)
{
Console.WriteLine("Subsite exists");
}
else
{
Console.WriteLine("Subsite doesnt exists");
}
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console.
In this example, you will learn how to check a Website is a sub site or not, using PnP Core
CSOM library. IsSubSite method is used to check, if the current site is sub site.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
In the program file, paste the code given below and save the file.
Run the code from Debug menu or by pressing F5.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
14
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
string subsiteName = "SubSite3";
// Checks if the web accessed is subsite or not
bool isSubSite = clientContext.Site.OpenWeb(subsiteName).IsSubSite();
if (isSubSite)
{
Console.WriteLine("SubSite3 is Subsite");
}
else
{
Console.WriteLine("SubSite3 is not a sub site");
}
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console.
In this example, you will learn how to delete a site (Web scoped), using PnP Core CSOM
library. The sub site can be deleted, using DeleteWeb method with the help of the root Web
object.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The required input parameter is a sub site name.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
15
In the program file, insert the code mentioned below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
string subsiteName = "SubSite3";
// Delete subsite
bool isSubSite = clientContext.Site.RootWeb.DeleteWeb(subsiteName);
if (isSubSite)
{
Console.WriteLine("Site deleted");
}
else
{
Console.WriteLine("Site not deleted");
}
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The result will be displayed on the console.
In this example, you will learn how to activate or enable the site collection feature, which is
not active, using PnP Core CSOM library. In this example, we will see how to activate the
OOB feature, which is not active on the site. You will learn how to activate Document ID
Service feature. The ID of the document ID Service feature is b50e3104-6812-424f-a011-
cc90e6327318.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
16
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book for
importing the packages and creating authentication manager object.
The required input parameter for the operation is feature ID.
In the program file, insert the code mentioned below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
// Document ID Service Feature Id
Guid featureId = new Guid("b50e3104-6812-424f-a011-cc90e6327318");
// Activates site collection feature
clientContext.Site.ActivateFeature(featureId);
Console.WriteLine("Feature is activated");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The Document ID Service feature is activated. The feature can be identified on the site
collection features page. The site collection features page URL of the example site is
https://nakkeerann.sharepoint.com/sites/learning_layouts/15/ManageFeatures.aspx?Scope=Sit
e. The image given below shows the document ID Service feature, which is activated.
The OOB features list along with feature ID of SharePoint 2013 is available on MSDN blog
site. The required site scoped feature Id can be copied from the list.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
17
5.8 How to disable a feature (site scoped) on a site collection
In this example, you will learn how to deactivate or disable the feature (site scoped), which is
active on the site collection, using PnP Core CSOM library.
In this example, we will see how to deactivate the OOB feature, which is active on the site.
The OOB features list along with the feature ID of SharePoint 2013 is available on MSDN
blog site. The required site scoped feature Id can be copied from the list. You will learn how
to deactivate the site policy feature. The ID of the site policy feature is 2fcd5f8a-26b7-4a6a-
9755-918566dba90a.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
In the program file, insert the code given below and save the file.
The required input parameter for the operation is the feature ID.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
// Site Policy Feature Id
Guid featureId = new Guid("2fcd5f8a-26b7-4a6a-9755-918566dba90a");
// Deactivates site collection feature
clientContext.Site.DeactivateFeature(featureId);
Console.WriteLine("Feature is deactivated");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
18
Result
The result will be displayed on the console. The site policy feature is deactivated. The feature
can be identified on the site collection features page. The site collection features page URL of
the example site is
https://nakkeerann.sharepoint.com/sites/learning/_layouts/15/ManageFeatures.aspx?Scop
e=Site. The below image shows the document ID service feature which is activated.
5.9 How to check if the site collection feature is active (site scoped)
In this example, you will learn how to check, if the site collection feature (site scoped) is
activated or not, using PnP Core CSOM library.
In this example, we will see how to check the OOB feature status on the site. The OOB
features list along with the feature ID of SharePoint 2013 is available on MSDN blog site.
The required site scoped feature Id can be copied from the list. You will learn how to check
the site policy feature status. The ID of the site policy feature is 2fcd5f8a-26b7-4a6a-9755-
918566dba90a.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The required input parameter for the operation is the feature ID.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
// Site Policy Feature Id
Guid featureId = new Guid("2fcd5f8a-26b7-4a6a-9755-918566dba90a");
// Checks if site collection feature is active
bool isActive = clientContext.Site.IsFeatureActive(featureId);
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
19
if (isActive)
{
Console.WriteLine("Site Collection Feature is Active");
}
else
{
Console.WriteLine("Site Collection Feature is Not Active");
}
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The site policy feature status result will be displayed on the console. The feature can be
identified on the site collection features page manually. The site collection features page URL
of the example site is
https://nakkeerann.sharepoint.com/sites/learning/_layouts/15/ManageFeatures.aspx?Scop
e=Site.
In this example, you will learn how to activate or enable the Web scoped feature which is not
active, using PnP Core CSOM library.
In this example, we will see how to activate OOB Web feature, which is not active on the
site. The OOB features list along with the feature ID of SharePoint 2013 is available on
MSDN blog site. The required Web scoped feature Id can be copied from the list. You will
learn how to activate SharePoint Server Publishing feature on the sub site. The ID of the
SharePoint Server Publishing feature is 94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The required input parameter for the operation is the feature ID. The operation is
triggered, using necessary web object.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
20
In the program file, insert the code mentioned below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
// SharePoint Server Publishing Feature Id
Guid featureId = new Guid("94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb");
// Activates web collection feature
clientContext.Site.OpenWeb("SubSite2").ActivateFeature(featureId);
Result
SharePoint Server publishing feature is activated. The feature can be identified on the site
features page. The site features page URL of the example site is
https://nakkeerann.sharepoint.com/sites/learning/SubSite2/_layouts/15/ManageFeatures.aspx.
The snapshot given below depicts the feature.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
21
5.11 How to disable a feature (web scoped) on a site or a sub site
In this example, you will learn how to deactivate or disable the Web scoped site feature ,
which is active, using PnP Core CSOM library.
In this example, we will see how to deactivate OOB Web feature, which is active on the site.
OOB features list along with the feature ID of SharePoint 2013 is available on MSDN blog
site. The required Web scoped feature Id can be copied from the list. You will learn how to
deactivate SharePoint Server Publishing feature on the sub site. The ID of SharePoint Server
Publishing feature is 94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The required input parameter for the operation is the feature ID. The operation is
triggered, using necessary Web object.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// SharePoint Server Publishing Feature Id
Guid featureId = new Guid("94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb");
// Deactivates site collection feature
clientContext.Site.OpenWeb("SubSite2").DeactivateFeature(featureId);
Console.WriteLine("Web Feature is deactivated");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
22
Result
SharePoint Server publishing feature is deactivated. The feature can be identified on the site
features page. The site features page URL of the example site is
https://nakkeerann.sharepoint.com/sites/learning/SubSite2/_layouts/15/ManageFeatures.aspx.
The snapshot depicts the deactivated feature.
In this example, you will learn how to check if the Web feature is activated or not, using PnP
Core CSOM library.
In this example, we will see how to check OOB Web feature, which is active on the site. The
OOB features list along with the feature ID of SharePoint 2013 is available on MSDN blog
site. The required Web scoped feature Id can be copied from the list. You will learn how to
check SharePoint Server Publishing feature is active on the sub site. The ID of SharePoint
Server Publishing feature is 94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The required input parameter for the operation is the feature ID. The operation is
triggered, using necessary Web object.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
// SharePoint Server Publishing Feature Id
Guid featureId = new Guid("94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb");
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
23
// Checks if web feature is active
bool isActive = clientContext.Site.OpenWeb("SubSite2").IsFeatureActive(featureId);
if (isActive) {
Console.WriteLine("Web Feature is Active");
}
else
{
Console.WriteLine("Web Feature is Not Active");
}
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The feature can be identified manually on the site features page. The site features page URL
of the example site is
https://nakkeerann.sharepoint.com/sites/learning/SubSite2/_layouts/15/ManageFeatures.aspx.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
24
6 SharePoint List Operations
In this section, you will learn how to work with the lists, using PnP Core CSOM library.
Some of the basic operations like create, retrieve, update and check list operations are
explained.
The methods given below are used for the examples explained in this section.
CreateList
ListExists
GetListByTitle
GetListByUrl
GetListId
SetListPermission
UpdateListVersioning
In this example, you will learn how to create a list on SharePoint site, using PnP Core CSOM
library. The list is created, using CreateList from the Web object. SharePoint custom list will
be created, using the steps given below.
Steps involved
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
25
{
// List Name
string listName = "TestList";
// Custom List Template
ListTemplateType listTemplate = ListTemplateType.GenericList;
// No versioning
bool enableVersioning = false;
// Creates List
List list = clientContext.Site.RootWeb.CreateList(listTemplate, listName,
enableVersioning);
Result
The snapshot given below shows the list created on the site.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
26
6.2 How to check if the list exists using the list name
In this example, you will learn how to check, if a list exists or not, using PnP Core CSOM
library by the list name. ListExists method is used for the operation.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The required input parameter for the operation is the list name.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
// List name input
string listName = "TestList";
// Checks the list exists
bool listExists = clientContext.Site.RootWeb.ListExists(listName);
if (listExists)
{
Console.WriteLine("List is available on the site");
}
else
{
Console.WriteLine("List is not available on the site");
}
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
27
Result
The results will be displayed on the console, as shown below.
In this example, you will learn how to check, if a list exists or not, using PnP Core CSOM
library by list Id. ListExists method is used for the operation.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The required input parameter is the list ID.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
// List Id input
Guid listId = new Guid("F36FCF25-AE26-4CAA-933B-A9F52376ED4F");
// Checks the list exists using list Id
bool listExists = clientContext.Site.RootWeb.ListExists(listId);
if (listExists)
{
Console.WriteLine("List is available on the site");
}
else
{
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
28
Console.WriteLine("List is not available on the site");
}
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console, as shown below.
In this example, you will learn how to retrieve a particular list from the current SharePoint
site by the list name, using PnP core CSOM library. Here, we will see how we can retrieve
the list object, using the list name. GetListByTitle method is used for the operation.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The required input parameter is the list name.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
29
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
// List Name input
string listName = "TestList";
// Retrieves list object using title
List list = clientContext.Site.RootWeb.GetListByTitle(listName);
if (list != null)
{
// Displays required result
Console.WriteLine("List Title : " + list.Title);
Console.WriteLine("List Id : " + list.Id);
}
else
{
Console.WriteLine("List is not available on the site");
}
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console, as shown below.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
30
6.5 How to retrieve a list using the list URL
In this example, you will learn how to retrieve a particular list from the current SharePoint
site by the list URL, using PnP core CSOM library. GetListByUrl method is used for the
operation.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The required input parameter for the operation is the list URL.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
Console.WriteLine("Get List By URL :");
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
31
Result
The results will be displayed on the console, as shown below.
In this example, you will learn how to retrieve a particular list ID from the current SharePoint
site, using PnP core CSOM library. ID of the list can be retrieved, using GetListID method.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The required input parameter for the method is the list name.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
Console.WriteLine("Get List Id By List Name ::");
// List Name
string listName = "TestList";
// Get List Id
Guid listId = clientContext.Site.RootWeb.GetListID(listName);
Result
The results will be displayed on the console, as shown below.
Steps involved
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
// List name input
string listName = "TestList";
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
33
// Get List
List list = clientContext.Site.RootWeb.GetListByTitle(listName);
// Set Permissions
list.SetListPermission(OfficeDevPnP.Core.Enums.BuiltInIdentity.Everyone,
RoleType.Editor);
Console.WriteLine("Provided permission");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console, as shown below. Navigate to the List -> List
Settings -> Permissions. Subsequently, check the permissions granted. In this example, if the
list is inheriting the permissions from the parent site, the inheritance will break and unique
permissions will be provided to the list.
The snapshot given below shows the list with the unique permissions and provides the access.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
34
6.8 How to enable versioning for the list
In this example, you will learn how to enable versioning for a SharePoint list, using PnP core
CSOM library. The versioning for the list cane be updated, using UpdateListVersioning
method.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The required input parameters for the method are given below.
o Enable versioning (Boolean).
o Enable minor versioning (Boolean).
o Update Query (Boolean).
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// List name input
string listName = "TestList";
// Get List
List list = clientContext.Site.RootWeb.GetListByTitle(listName);
// Parameters for enabling versioning
bool enableVersioning = true; // Enable, false for disabling
bool enableMinorVersioning = false;
bool updateQuery = true;
// Enables versioning
list.UpdateListVersioning(enableVersioning, enableMinorVersioning, updateQuery);
Console.WriteLine("Versioning enabled");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
35
Result
The results will be displayed on the console, as shown below. Navigate to the List -> List
Settings -> Version Settings and check the settings.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
36
7 SharePoint List View Operations
In this section, you will learn how to work with the views, using PnP Core CSOM library.
Some of the basic operations like, create, retrieve, update and delete view operations are
explained.
The commands given below are used in the examples, which are explained in this section.
CreateView
GetViewByName
GetViewById
In this example, you will learn how to create a list view for a list on SharePoint site, using
PnP Core CSOM library. SharePoint Custom list views will be created, using CreateView
method.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The required input parameters for the method are given below.
o View name
o View fields array
o Default view (Boolean)
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
// List Name
string listName = "TestList";
// Get List
List list = clientContext.Site.RootWeb.GetListByTitle(listName);
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
37
// Input for creating view
string viewName = "customview";
string[] viewFields = { "Title", "Author" };
bool defaultView = true;
// Output
Console.WriteLine("The view has been created.");
Console.WriteLine("View Name : " + newView.Title);
Console.WriteLine("View ID : "+newView.Id);
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console, as shown below.
The snapshot given below shows the list view created for a SharePoint list on the site.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
38
7.2 How to retrieve a list view using view name
In this example, you will learn how to retrieve a particular list view by the view name from a
SharePoint list on SharePoint site, using PnP Core CSOM library. Here, we will see how we
can retrieve the list view object, using the list view name.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The required input parameter for the method is the view name.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
// Input Parameters
// List Name
string listName = "TestList";
// View Name
string viewName = "customview";
// Output
Console.WriteLine("View Name : " + view.Title);
Console.WriteLine("View Url : " + view.ServerRelativeUrl);
Console.WriteLine("View Id : " + view.Id);
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
39
Result
The results will be displayed on the console, as shown below.
In this example, you will learn how to retrieve a particular list view by Id from a SharePoint
list, using PnP Core CSOM library. Here, we will see, how we can retrieve the list view
object, using list name and view Id.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The required input parameter for the method is the view ID.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
// Input Parameters
// List Name
string listName = "TestList";
// View Id
Guid viewId = new Guid("122ccac1-48e5-4dc3-ac3a-e2650189648b");
// Get View By Id
View view =
clientContext.Site.RootWeb.GetListByTitle(listName).GetViewById(viewId);
// Output
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
40
Console.WriteLine("View Name : " + view.Title);
Console.WriteLine("View Url : " + view.ServerRelativeUrl);
Console.WriteLine("View Id : " + view.Id);
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console, as shown below.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
41
8 SharePoint Content Type Operations
In this section, you will learn how to complete the basic content type operations available,
using PnP Core CSOM library. Some of the basic operations like create, retrieve, check if
exists, add to the list and delete the content type operations, which are explained.
The commands given below are used in the examples, which are explained in this section.
GetContentTypeByName
GetContentTypeById0
CreateContentType
CreateContentTypeFromXMLString
ContentTypeExistsByName
ContentTypeExistsById
AddContentTypeToList
AddContentTypeToListById
AddContentTypeToListByName
ContentTypeExistsByName
ContentTypeExistsById
DeleteContentTypeByName
DeleteContentTypeById
In this section, you will learn how to retrieve the required site content type from SharePoint
site, using PnP Core CSOM library with the help of an existing content type name. The Item
Site content type is retrieved in the example given below, using GetContentTypeByName
method.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The required input parameters for the method is the content type name.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
42
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
// Input Parameters
string contentTypeName = "Item";
// Output
Console.WriteLine("Content Type Details:");
Console.WriteLine("Name : " + contentType.Name);
Console.WriteLine("ID : " + contentType.Id);
Console.WriteLine("Description : " + contentType.Description);
Console.WriteLine("Group : " + contentType.Group);
Console.WriteLine("XML : " + contentType.SchemaXml);
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console, as shown below. The item site content type
information is retrieved from the site.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
43
Note
Similarly, other field values can also be retrieved.
In this section, you will learn how to retrieve the required site content type by content type Id
from SharePoint site, using PnP Core CSOM library. Item Site content type is retrieved in the
example given below, using GetContentTypeById method.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The required input parameter is the content type ID. The default item content type id
is 0x01.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
44
{
// Input Parameters
string contentTypeId = "0x01";
// Output
Console.WriteLine("Content Type Details:");
Console.WriteLine("Name : " + contentType.Name);
Console.WriteLine("ID : " + contentType.Id);
Console.WriteLine("Description : " + contentType.Description);
Console.WriteLine("Group : " + contentType.Group);
Console.WriteLine("XML : " + contentType.SchemaXml);
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console, as shown below. The item site content type
information is retrieved from the site.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
45
8.3 How to create a site content type
In this section, you will learn how to create a new site content type on SharePoint site using
PnP Core CSOM library. The scope of the content type is defined in the Web object, where
the method is initiated. The scope can also be identified, which is based on the site URL.
In the example given below, site collection URL is used for setting the context. The create
site content type method is initiated, using the root level Web object. Thus, the scope of the
content type to be created is the site.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The parent content type should be retrieved for assigning it to the new content type,
since the parent content type will be considered as base content type.
The required input parameters should be set.
o Content type name
o Content type description
o Content type Id – If not decided, then it can be null
o Content type group
o Parent content type
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
// Input Parameters
string contentTypeName = "NakkeeranCT";
string contentTypeDesc = "Test Content Type using PnP CSOM";
string contentTypeId = null;
string contentTypeGroup = "CustomCTGroup";
// Output
Console.WriteLine("The content type " + contentType.Name + " has been created on the
site.");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console, as shown below.
The snapshot given below shows the content type created on the site. The content types can
be found on the site content type’s page
(https://nakkeerann.sharepoint.com/sites/learning/_layouts/15/mngctype.aspx).
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
47
8.4 How to create a site content type using content type XML
In this section, you will learn how to create a new site content type on SharePoint site by
content type XML, using PnP Core CSOM library.
In the example given below, site collection URL is used for setting the context. The content
type XML is built and is used as an input parameter to create the content type in this
approach. The create site content type method is initiated, using the root level Web object.
Thus, the scope of the content type to be created is the site.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The content type XML is built. The content type Id is generated with the help of
Visual Studio.
o From the Visual Studio menu options, click on Tools Create GUID.
o GUID dialog box will open, as shown below. Leave the default option, click
on New GUID and then click on copy. The GUID will be copied to the clip
board.
<ContentType ID ='0x01002D36199798184855BDE6CC5FA9F14E87'
Name='NakkeeranCT1' Group='CustomCTGroup' Description='Content Type using
XML' Inherits='TRUE'>
<FieldRefs>
</FieldRefs>
</ContentType>
The necessary fields can be inserted within the FieldRefs tag, using field tags.
In the program file, insert the code mentioned below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
// Output
Console.WriteLine("The content type " + contentType.Name + " has been created on the
site.");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
49
Result
The results will be displayed on the console, as shown below.
The snapshot given below shows the content type created on the site. The content types can
be found on the site content type’s page
(https://nakkeerann.sharepoint.com/sites/learning/_layouts/15/mngctype.aspx).
Note
This approach can only be used for the development purposes, since the content type Id is
generated manually.
8.5 How to check if a site content type already exists by content type name
In this section, you will learn how to check, if a site content type already exists by content
type name on SharePoint site, using PnP Core CSOM library.
In the example given below, site collection URL is used for setting the context.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The required input parameters should be set.
o Content type name
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
50
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
// Output
if (contentTypeExists)
{
Console.WriteLine("Content Type Exists");
}
else
{
Console.WriteLine("Content Type doesn't exists");
}
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console, as shown below.
The content types can be found on the site content type’s page
(https://nakkeerann.sharepoint.com/sites/learning/_layouts/15/mngctype.aspx).
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
51
8.6 How to check if a site content type already exists by content type Id
In this section, you will learn how to check, if a site content type already exists by the content
type Id on SharePoint site, using PnP Core CSOM library.
In the following example, site collection URL is used for setting the context.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The required input parameters should be set.
o Content type Id
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
// Output
if (contentTypeExists)
{
Console.WriteLine("Content Type Exists");
}
else
{
Console.WriteLine("Content Type doesn't exists");
}
Console.ReadKey();
}
}
catch (Exception ex)
{
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
52
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console, as shown below.
The content types can be found on the site content type’s page
(https://nakkeerann.sharepoint.com/sites/learning/_layouts/15/mngctype.aspx).
In this section, you will learn how to add the site content type (created above) to SharePoint
list available on the site, using PnP Core CSOM library.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The required input parameters for the method are given below.
o Content type
o Is default content type
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
53
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
if (contentTypeAdd)
{
Console.WriteLine("Content Type Added to List");
}
else
{
Console.WriteLine("Content Type Not added");
}
// Output
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console. You can navigate to the list settings to check, if
the content type is added successfully or not.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
54
8.8 How to add site content type to List By content type Id
In this section, you will learn how to add the site content type (created above) to the
SharePoint list available on the site by content type Id, using PnP Core CSOM library.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The required input parameters for the method are given below.
o Content type Id.
o Is default content type.
In the program file, insert the code given below and save the file.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
Result
The results will be displayed on the console. You can navigate to the list settings to check, if
the content type is added successfully.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
56
8.9 How to add site content type to List By content type name
In this section, you will learn how to add the site content type (created above) to SharePoint
list available on the site by content type name using PnP Core CSOM library.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The required input parameters for the method are given below.
o Content type Id.
o Is default content type.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
Result
The results will be displayed on the console. You can navigate to the list settings to check, if
the content type is added successfully or not.
8.10 How to check if a content type already exists on a list by the content
type name
In this section, you will learn how to check, if a site content type already exists by the content
type name on SharePoint list, using PnP Core CSOM library.
In the example given below, site collection URL is used for setting the context.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The required input parameters should be set.
o List URL.
o Content type name.
In the program file, insert the code given below and save the file.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
58
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
// Input Parameters
string contentTypeName = "NakkeeranCT";
string listUrl = "Lists/TestList"; // List Server Relative Url
// Output
if (contentTypeExists)
{
Console.WriteLine("Content Type Exists");
}
else
{
Console.WriteLine("Content Type doesn't exists");
}
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console, as shown below. The same can be checked by
navigating to the list settings.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
59
8.11 How to check if a content type already exists on a List by content type
Id
In this section, you will learn how to check, if a site content type already exists by the content
type Id on SharePoint list, using PnP Core CSOM library.
In the example given below, the site collection URL is used to set the context.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The required input parameters should be set.
o List URL
o Content type Id
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext =
authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
// Input Parameters
string contentTypeId = "0x0100C6D6909EB935D44F88615A32BB60B9F9";
string listUrl = "Lists/TestList"; // List Server Relative Url
// Output
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
60
if (contentTypeExists)
{
Console.WriteLine("Content Type Exists");
}
else
{
Console.WriteLine("Content Type doesn't exists");
}
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
}
Result
The results will be displayed on the console, as shown below. The same can be checked by
navigating to the list settings.
In this section, you will learn how to delete a content type from the SharePoint site by the
content type name, using PnP Core CSOM library.
In the example given below, the site collection URL is used to set the context.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The required input parameters should be set.
o Content type name.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
61
In the program file, insert the code mentioned below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
Result
The results will be displayed on the console, as shown below. The same can be checked by
navigating to the content type page.
In this section, you will learn how to delete a content type from the SharePoint site by content
type Id, using PnP Core CSOM library.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
62
In the example given below, the site collection URL is used to set the context.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book for
importing the packages and creating authentication manager object.
The required input parameters should be set.
o Content type Id
In the program file, insert the following code and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
Result
The results will be displayed on the console, as shown below. The same can be checked by
navigating to the content type page.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
63
9 SharePoint Field Operations
In this topic, you will learn how to perform the basic field operations like add, retrieve or
delete to/from the sites/content types, using PnP Core CSOM library. Fields are otherwise
called as columns.
CreateField
CreateFieldsFromXMLString
GetFieldById
FieldExistsById
FieldExistsByName
AddFieldToContentType
AddFieldToContentTypeById
AddFieldToContentTypeByName
FieldExistsByNameInContentType
The fields can be accessed manually from the site columns page
(https://nakkeerann.sharepoint.com/sites/learning/_layouts/15/mngfield.aspx).
In this section, you will learn how to create a site column (field) on SharePoint site, using
PnP Core CSOM library. CreateField method is used to create columns with the necessary
input parameters.
In the example given below, the site collection URL is used for setting the context.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The input parameters should be set.
o Display Name
o Group Name
o Field Id
o Field Type
The field GUID needs to be generated.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
64
o From Visual Studio menu options, click on Tools Create GUID.
o GUID dialog box will open as shown below. Leave the default option, click on
New GUID and then click on copy. GUID will be copied to the clip board.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameter
string displayName = "NakkeeranColumn1";
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
65
string internalName = "NakkeeranColumn1";
string groupName = "NavColumnGroup";
string fieldId = "F73936BD-F86C-4672-A06D-56F76ABABAC2";
FieldType fieldType = FieldType.Text;
// Output
Console.WriteLine("New " + newField.Title + " Column is created");
Console.WriteLine("Scope : " + newField.Scope);
Console.WriteLine("Schema XML : " + newField.SchemaXml);
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console, as shown below.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
66
9.2 How to create a field on SharePoint site using Field XML
In this section, you will learn how to create a site column (field) on SharePoint site, using
PnP Core CSOM library by field XML. CreateFieldsFromXMLString method is used to
create the columns with the necessary XML.
In the example given below, the site collection URL is used for setting the context.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The field XML should contain the following.
o Title or name.
o Display name.
o Group name.
o Type.
o GUID.
The field GUID needs to be generated.
o From Visual Studio menu options, click on Tools Create GUID.
o GUID dialog box will open, as shown below. Leave the default option, click
on New GUID and then click on copy. GUID will be copied to the clip board.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
67
o The GUID will be [Guid("36ADABD2-C4B6-432E-B6FE-
68992CEBB23C")]. Select only the alpha numeric data and assign it to a
variable. The field ID will be 36ADABD2-C4B6-432E-B6FE-
68992CEBB23C in this example.
Create Field method is used from the Web object to create the fields, where the field
XML is used as an input parameter.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameter - New Field XML as string
string fieldXML = "<Field Type =\"Text\" Name=\"NakkeeranColumn4\"
DisplayName=\"NakkeeranColumn4\" ID=\"{36ADABD2-C4B6-432E-B6FE-68992CEBB23C}\"
Group =\"NavColumnGroup\" Required=\"FALSE\" />";
// Output
Console.WriteLine("New Column is created");
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
68
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The success/failure results will be displayed on the console.
In this section, you will learn how to retrieve the required field (columns), using the field Id
from SharePoint site by PnP Core CSOM library.
Steps involved
Open Visual Studio as administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The input parameters should be set.
o Field Id as GUID variable.
The field can be retrieved, using GetFieldById method.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
69
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameter
string fieldIdStr = "F73936BD-F86C-4672-A06D-56F76ABABAC2";
// As Guid
Guid fieldId = new Guid(fieldIdStr);
// Retrieves Field
Field field = clientContext.Site.RootWeb.GetFieldById<Field>(fieldId);
// Output
Console.WriteLine("Field Details : ");
Console.WriteLine("Field Name : " + field.Title);
Console.WriteLine("Field Type Name : " + field.TypeDisplayName);
Console.WriteLine("Field Type : " + field.FieldTypeKind);
Console.WriteLine("Field Group: "+field.Group);
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console, as shown below.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
70
9.4 How to check if a field exists using field Id
In this section, you will learn how to check, if the field is already available, using the field Id
from SharePoint site by PnP Core CSOM library.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The input parameters should be set.
o Field Id as GUID variable.
The existing field can be checked, using FieldExistsById method, using the Web
object.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameter
string fieldIdStr = "F73936BD-F86C-4672-A06D-56F76ABABAC2";
// As Guid
Guid fieldId = new Guid(fieldIdStr);
// Checks Field
bool fieldExists = clientContext.Site.RootWeb.FieldExistsById(fieldId);
// Output
if (fieldExists)
{
Console.WriteLine("Field is available");
}
else
{
Console.WriteLine("Field is not available");
}
Console.ReadKey();
}
}
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
71
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console, as shown below.
In this section, you will learn how to check, if the field is already available, using field
title/name from SharePoint site by PnP Core CSOM library.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The input parameters should be set.
o Field Title.
The existing field can be checked, using FieldExistsByName method, using the Web
object.
In the program file, insert the code snippet given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameter
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
72
string fieldName = "NakkeeranColumn1";
// Checks Field
bool fieldExists = clientContext.Site.RootWeb.FieldExistsByName(fieldName);
// Output
if (fieldExists)
{
Console.WriteLine("Field is available");
}
else
{
Console.WriteLine("Field is not available");
}
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console, as shown below.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
73
9.6 How to add a field to site content type
In this section, you will learn how to add an existing site column to the site content type by
the field object and the content type object, using PnP Core CSOM library. The existing site
column is added to the existing site content type in the example given below.
In the example given below, the site collection URL is used to set the context.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The input parameters should be set.
o Field Id – Field to be added.
o Content Type Name – Content type, where the field is added.
o Required – Field needs to be mandatory column?
o Hidden – Field needs to be hidden on the lists/content types?
Field is retrieved, using the field Id.
Content Type is retrieved, using the content type name.
Then AddFieldToContentType method is used to add the field to the content type
with the help of the field and the content type objects retrieved.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string fieldIdStr = "F73936BD-F86C-4672-A06D-56F76ABABAC2";
string contentTypeName = "NakkeeranCT";
bool isRequired = false;
bool isHidden = false;
// Field As Guid
Guid fieldId = new Guid(fieldIdStr);
// Retrieves Field
Field field = clientContext.Site.RootWeb.GetFieldById<Field>(fieldId);
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
74
// Retrieves Content Type
ContentType contentType =
clientContext.Site.RootWeb.GetContentTypeByName(contentTypeName);
// Output
Console.WriteLine("Field is added to Content Type");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console given below. The result can be viewed by
opening the “NakkeeranCT” from the site content type’s page. The URL for the content
type’s page is https://nakkeerann.sharepoint.com/_layouts/15/mngctype.aspx. The snapshot
given below shows the field added to the content type.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
75
9.7 How to add a field to site content type using Content type Id
In this section, you will learn how to add an existing site column to the site content type
directly with the help of the field Id and the content type Id, using PnP Core CSOM library.
The existing site column is added to the existing site content type in the example given
below.
In the example given below, the site collection URL is used for setting the context.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The input parameters should be set.
o Field Id – Field to be added
o Content Type Id – Content type, where the field is added
o Required – Field needs to be mandatory column
o Hidden – Field needs to be hidden on the lists/content types
Subsequently, AddFieldToContentTypeById method is used to add the field to the
content type, using the field Id with the help of the web object.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string fieldId = "F73936BD-F86C-4672-A06D-56F76ABABAC2";
string contentTypeId = "0x01006699DA2F8D486148BB11DE9FEFA816FA";
bool isRequired = false;
bool isHidden = false;
clientContext.Site.RootWeb.AddFieldToContentTypeById(contentTypeId,fieldId,isRequired,isHidde
n);
// Output
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
76
Console.WriteLine("Field is added to Content Type");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console. The result can be viewed by opening the
“NakkeeranCT” from the site content type’s page. The URL for the content type’s page is
https://nakkeerann.sharepoint.com/_layouts/15/mngctype.aspx. The snapshot given below
shows the field added to the content type.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
77
9.8 How to add a field to site content type using Content type name
In this section, you will learn how to add existing site column to the site content type with the
help of the field Id and the content type name, using PnP Core CSOM library. The existing
site column is added to the existing site content type in the example given below.
In the example given below, the site collection URL is used to set the context.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The input parameters should be set.
o Field Id – Field to be added.
o Content Type Name – Content type, where the field is added
o Required – Field needs to be the mandatory column?
o Hidden – Field needs to be hidden on the lists/content types?
Then AddFieldToContentTypeByName method is used to add the field to the content
type, using field Id with the help of the Web object.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string fieldIdStr = "F73936BD-F86C-4672-A06D-56F76ABABAC2";
string contentTypeName = "NakkeeranCT";
bool isRequired = false;
bool isHidden = false;
// Field As Guid
Guid fieldId = new Guid(fieldIdStr);
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
78
// Output
Console.WriteLine("Field is added to Content Type");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console. The result can be viewed by opening the
“NakkeeranCT” from the site content type page. The URL for the content type’s page is
https://nakkeerann.sharepoint.com/_layouts/15/mngctype.aspx. The snapshot given below
shows the field added to the content type.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
79
9.9 How to check if a field exists in the Content type
In this section, you will learn how to check if the field already exists in the content type,
using PnP Core CSOM library.
In the example given below, the site collection URL is used to set the context.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The input parameters should be set.
o Field Name.
o Content Type Name.
Then FieldExistsByNameInContentType method is used to check, if the field already
exists with the help of the Web object.
In the program file, insert the code, mentioned below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameter
string fieldName = "NakkeeranColumn1";
string contentTypeName = "NakkeeranCT";
// Checks Field exists in CT
bool fieldExists =
clientContext.Site.RootWeb.FieldExistsByNameInContentType(contentTypeName, fieldName);
// Output
if (fieldExists)
{
Console.WriteLine("Field is available");
}
else
{
Console.WriteLine("Field is not available");
}
Console.ReadKey();
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
80
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console. The result can be viewed by opening the
“NakkeeranCT” from the site content type page. The URL for the content type’s page is
https://nakkeerann.sharepoint.com/_layouts/15/mngctype.aspx. The snapshot given below
shows the field added to the content type.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
81
10 SharePoint Folder tasks
In this topic, you will learn how to perform the basic folder operations like add, retrieve or
delete to/from libraries, using PnP Core CSOM library.
The methods given below are used for the folder operations are
CreateFolder
FolderExists
ResolveSubFolder
EnsureFolder
EnsureFolderPath
In this section, you will learn how to create the folders on SharePoint library, using PnP Core
CSOM library. CreateFolder method is used to create a folder on the document library.
The example given below creates a folder “Folder1”, under “Documents” library.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The input parameters should be set.
o List Name.
o Folder Name.
The list is retrieved from the root level site object, using the list title.
Subsequently, using the list object, the folders are created. The folder is created, using
CreateFolder method with the new folder name as an input.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
82
// Input Parameter
string listName = "TestList";
string folderName = "Folder1";
// Get Library
List list = clientContext.Site.RootWeb.GetListByTitle(listName);
// Create Folder
Folder folder = list.RootFolder.CreateFolder(folderName);
// Output
Console.WriteLine("New " + folder.Name + " folder is created");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console, as shown below.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
83
10.2 How to check if a folder exists on a library using folder name
In this section, you will learn how to check if a folder already exists on a SharePoint library
using PnP Core CSOM library with folder name. FolderExists method is used to create a
folder on the document library.
The example given below checks for a folder “Folder1”, under “Documents” library.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The input parameters should be set.
o List name.
o Folder name.
The list is retrieved from the root level site object, using the list title.
Subsequently, using the list object, the folder is checked. The folder is checked, using
FolderExists method with the folder name as an input. The return type is Boolean.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameter
string listName = "Documents";
string folderName = "Folder1";
// Get Library
List list = clientContext.Site.RootWeb.GetListByTitle(listName);
// Checks for folder
bool folderExists = list.RootFolder.FolderExists(folderName);
// Output
if (folderExists)
{
Console.WriteLine("Folder already exists on the library");
}
else
{
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
84
Console.WriteLine("Folder doesn't exists on the library");
}
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console, as shown below.
In this section, you will learn how to check, if a folder already exists on a SharePoint library ,
using PnP Core CSOM library with the folder Server relative path. DoesFolderExists method
is used to check a folder on the document library with the help of the Web object.
The example given below checks for a folder “Folder1”, under “Documents” library.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The input parameters should be set.
o Folder Server relative URL.
Using the Web object, the folder is checked. The folder is checked, using
DoesFolderExists method with the folder URL as an input. The return type is
Boolean.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
85
In the program file, insert the code give below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameter
string folderUrl = "/sites/learning/Shared Documents";
// Output
if (folderExists)
{
Console.WriteLine("Folder Exists");
}
else
{
Console.WriteLine("Folder doesn't exists");
}
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console, as shown below.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
86
10.4 How to retrieve the folder from the library
In this section, you will learn how to retrieve the required folder from SharePoint library ,
using PnP Core CSOM library. ResolveSubFolder method is used to retrieve the folder.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The input parameters should be set.
o List Name.
o Folder Name.
The list is retrieved from the root level site object, using the list title.
Subsequently, using the list object, the folders are retrieved with the list and the folder
names as an input.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
// PnP component to set context
AuthenticationManager authManager = new AuthenticationManager();
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameter
string listName = "Documents";
string folderName = "Folder1";
// Get Library
List list = clientContext.Site.RootWeb.GetListByTitle(listName);
// Retrieves Folder
Folder folder = list.RootFolder.ResolveSubFolder(folderName);
// Output
Console.WriteLine("Server Relative Path : " + folder.ServerRelativeUrl);
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
87
Console.ReadKey();
}
Result
The results will be displayed on the console, as shown below.
10.5 How to check and create a folder on a library using folder name
In this section, you will learn how to check, if the folder exists and if it doesn’t exist, the
method will create the necessary folder, using the folder name. This can be done in a single
method call on SharePoint library, using PnP Core CSOM library. EnsureFolder method is
used to check and create a folder on the document library.
The example given below checks and creates a folder “Folder2”, under “Documents” library.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The input parameters should be set.
o List Name
o Folder Name
The list is retrieved from the root level site object, using the list title.
Now, using the list object, the folders are checked and created. The folder is created ,
using EnsureFolder method with the new folder name as an input.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
88
{
// Input Parameter
string listName = "Documents";
string folderName = "Folder2";
// Get Library
List list = clientContext.Site.RootWeb.GetListByTitle(listName);
// Output
Console.WriteLine("Folder Name : " + folder.Name);
Console.WriteLine("Server Relative Path : " + folder.ServerRelativeUrl);
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console, as shown below.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
89
10.6 How to check and create a folder on a library using folder URL
In this section, you will learn how to check if folder exists and if it doesn’t exists, the method
will create the necessary folder with the help of the folder URL as an input. This can be done
in a single method call on SharePoint library, using PnP Core CSOM library.
EnsureFolderPath method is used to check and create a folder on the document library , using
folder relative URL.
The following example checks for Folder3 and if it doesn’t exists, creates a folder “Folder3”,
under “Documents” library.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The input parameters should be set.
o Folder Server relative URL
Using the Web object, the folders are checked for the existence and are created. If the
folder doesn’t exist, it is created using EnsureFolderPath method.
In the program file, insert the code, mentioned below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameter
string folderUrl = "/Shared Documents/Folder3";
// Output
Console.WriteLine("Folder Name : " + folder.Name);
Console.WriteLine("Server Relative Path : " + folder.ServerRelativeUrl);
Console.ReadKey();
}
}
catch (Exception ex)
{
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
90
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console, as shown below.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
91
11 SharePoint Basic File tasks
In this topic, you will learn how to perform the basic file operations like add, find, retrieve,
download or delete to/from the libraries, using PnP Core CSOM library.
UploadFile
GetFile
SaveFileToLocal
CheckOutFile
CheckInFile
SetFileProperties
In this section, you will learn how to upload a file to SharePoint library, using PnP Core
CSOM library. UploadFile method is used to upload a file from the local system to
SharePoint document library. Local file path, file name and library object are used to upload
the documents.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The input parameters should be set.
o List Name
o Folder Name, where the file is uploaded
o File Name on the site
o Local file path
The list is retrieved from the root level site object, using the list title.
Subsequently, using the list object, the appropriate folder is accessed. With the help of
the folder object, the file is uploaded to the library, using UploadFile method.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
92
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameter
string listName = "Documents";
string folderName = "Folder1";
string fileName = "TestFile.docx";
string localPath = "C:/Solution/TestFile.docx";
// Get Library
List list = clientContext.Site.RootWeb.GetListByTitle(listName);
// Retrieves Folder
Folder folder = list.RootFolder.ResolveSubFolder(folderName);
// Uploads File
File newFile = folder.UploadFile(fileName, localPath, true);
// Output
Console.WriteLine(newFile.Title + " is uploaded to the site");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console. The file is successfully added to the folder under
SharePoint library. The snapshot given below shows the library with the added file.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
93
11.2 How to retrieve a file
In this section, you will learn how to retrieve a file from SharePoint library, using PnP Core
CSOM library. GetFile method is used to retrieve the file, using the folder name and the file
name.
The example given below shows retrieving file from a library or a folder.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The input parameters should be set.
o List Name
o Folder Name, where file is uploaded
o File Name on the site
The list is retrieved from the root level site object, using the list title.
Using the list object, the appropriate folder is accessed. With the help of the folder
object, the file is retrieved from the library, using GetFile method.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
94
// Input Parameter
string listName = "Documents";
string folderName = "Folder1";
string fileName = "TestFile.docx";
// Get Library
List list = clientContext.Site.RootWeb.GetListByTitle(listName);
// Create Folder
Folder folder = list.RootFolder.ResolveSubFolder(folderName);
File file = folder.GetFile(fileName);
// Output
Console.WriteLine("File Name : " + file.Name);
Console.WriteLine("Folder URL : " + file.ServerRelativeUrl);
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console, as shown below.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
95
11.3 How to download a file
In this section, you will learn how to download a file from SharePoint library, using PnP Core
CSOM library. The Server file path, local file path and local file name are the required
parameters for downloading a file.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The input parameters should be set.
o Server relative URL of the file
o Local path
o Local file name
Using the Web object, download the file, using SaveFileToLocal method with the
help of the input parameters, mentioned above.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameter
string fileServerRelativeUrl = "/sites/learning/Shared Documents/Folder1/TestFile.docx";
string localPath = "C:/Solution";
string localFileName = "TestFileNew.docx";
// Output
Console.WriteLine("File Downloaded");
Console.ReadKey();
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
96
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console. The file is successfully downloaded. Similarly,
the files can be downloaded from the library/subfolders on the library. The respective folder
URL should be given.
In this section, you will learn how to checkout a file from SharePoint library, using PnP Core
CSOM library. CheckOutFile method is used to checkout a file from SharePoint document
library. Server relative URL of file is the required parameter to check out a file.
The example given below checks out a file from SharePoint library.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The input parameters should be set.
o Server relative URL of the file.
Using the Web object, check out the file, using CheckOutFile method with the help of
the input parameter given above.
In the program file, insert the code given above and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameter
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
97
string fileServerRelativeUrl = "/sites/learning/Shared Documents/Folder1/TestFile.docx";
// Output
Console.WriteLine("File checked out");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console. The file is successfully checked out for editing
on SharePoint library. Similarly, the files can be checked out from the folders/subfolders on
the library.
The snapshot given below shows the file checked out from SP library.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
98
11.5 How to checkin a file
In this section, you will learn how to checkin a file on SharePoint library, using PnP Core
CSOM library. CheckInFile method is used to check in a file on SharePoint document library.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
The input parameters should be set.
o Server relative URL of the file.
o Check-in type.
o Comments.
Using the Web object, check in the file, using CheckInFile method with the help of
the input parameters stated above.
In the program file, insert the following code and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameter
string fileServerRelativeUrl = "/sites/learning/Shared Documents/Folder1/TestFile.docx";
CheckinType checkinType = CheckinType.MajorCheckIn;
string comment = "Checked in through PnP Programming";
// Check In file
clientContext.Site.RootWeb.CheckInFile(fileServerRelativeUrl,checkinType,comment);
// Output
Console.WriteLine("File checked in");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
99
Result
The results will be displayed on the console. The file is successfully checked in on
SharePoint library. Similarly, the files can be checked in to the folders/subfolders on the
library. The snapshot given below shows the file checked in details on SP library. The
version history of the file shows the recent check in information.
In this section, you will learn how to update the file properties on SharePoint library, using
PnP Core CSOM library. SetFileProperties method is used to update the file properties
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the Web object, retrieve the library with the library name and then retrieve the
root folder or the sub folder. Retrieve the file, using GetFile method.
The input parameters should be set.
o File Properties as a dictionary variable
o Checkout Boolean value, if required (optional)
Using the file object, update the file properties, using the dictionary variable. Here,
the dictionary variable contains the title and description values to be updated.
In the program file, insert the code shown below and save the file.
Run the code from Debug menu or by pressing F5.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
100
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameter
string listName = "Documents";
string folderName = "Folder1";
string fileName = "TestFile.docx";
// Get Library
List list = clientContext.Site.RootWeb.GetListByTitle(listName);
// Create Folder
Folder folder = list.RootFolder.ResolveSubFolder(folderName);
File file = folder.GetFile(fileName);
Dictionary<string, string> fileProperties = new Dictionary<string, string>();
fileProperties.Add("Title", "Test File");
fileProperties.Add("Description0", "Properties updated using PnP Programming");
file.SetFileProperties(fileProperties);
// Output
Console.WriteLine("File properties updated");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console. The file is successfully updated with title and
description properties. The snapshot given below shows the updated properties.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
101
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
102
12 SharePoint Page Tasks
In this topic, you will learn how to perform basic page operations on SharePoint site, using
PnP Core CSOM library.
The methods used for the page operations are shown below.
AddPublishingPage
GetPublishingPage
AddWikiPage
AddWikiPageByUrl
GetWikiPageContent
EnsureWikiPage
AddHtmlToWikiPage
AddLayoutToWikiPage
GetWebParts
AddWebPartToWebPartPage
DeleteWebPart
GetWebPartProperties
SetWebPartProperties
AddWebPartToWikiPage
In this section, you will learn how to create a publishing page on SharePoint site, using PnP
Core CSOM library.
SharePoint publishing features should be activated at both site and Web scopes, prior to
running this operation.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the Web object, create the page, using AddPublishingPage method. The
required input parameters are given below.
o Page Name
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
103
o Page Template Name
o Title for page
In the program file, insert the code, mentioned below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string pageName = "CustomPage";
string pageTemplate = "BlankWebPartPage";
string pageTitle = "CustomPage";
// Output
Console.WriteLine("Publishing Page Created");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console. The file is successfully created on the pages
library. The snapshot given below shows the pages library with the created page.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
104
12.2 How to retrieve a publishing page
In this section, you will learn how to retrieve a page from pages library, using PnP Core
CSOM library.
The example given below retrieves the pages from pages library.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the Web object, retrieve the page, using GetPublishingPage method. The
required input parameter is given below.
o Page Leaf URL.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string fileUrl = "CustomPage1.aspx";
// Output
if (page != null)
{
// Process the Page
}
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
105
Result
The results will be displayed on the console.
Note
The publishing pages library should be available before executing the operation shown
above.
In this section, you will learn how to create a wiki page on SharePoint site using PnP Core
CSOM library. AddWikiPage method is used to create a wiki page, using wiki page name
and library name.
The example given below creates a wiki page on the site, using the page content.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the Web object, create the page, using the input parameters,
o Wiki Page Name
o Wiki Pages Library Name
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string libraryName = "WikiPages";
string pageName = "CustomPage";
// Output
Console.WriteLine("Wiki Page Created. Page URL : " + wikiPage);
Console.ReadKey();
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
106
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console. The page is successfully created on SharePoint
site wiki page’s library.
Note
The wiki pages library should be created before executing the operation shown above.
12.4 How to create a wiki page using URL and the file content
In this section, you will learn how to create a wiki page on SharePoint site, using the page
URL with the page content by using PnP Core CSOM library. AddWikiPageByUrl method is
used to create a wiki page on the site. Page name and page content are passed as the
parameters to create a page.
The example given below creates a wiki page on the site, using page content.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the Web object, create the page, using the input parameters.
o Wiki page URL.
o Wiki page content.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
107
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string pageContent = "Page Created using PnP Core library";
string pageUrl = "/sites/learning/WikiPages/WikiPage1.aspx";
// Output
Console.WriteLine("Wiki Page Created");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console. The page is successfully created on SharePoint
site wiki page’s library. The snapshot given below shows the page with the page content.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
108
Note
The wiki pages library should be created before executing the operation shown above.
In this section, you will learn how to retrieve wiki page content, using PnP Core CSOM
library. GetWikiPageContent method is used to retrieve the page content.
The example given below retrieves the pages from the pages library.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the Web object, retrieve the page content, using wiki page Server relative URL.
The required input parameter is given below.
o Wiki Page URL
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string pageUrl = "/sites/learning/WikiPages/WikiPage1.aspx";
// Output
Console.WriteLine("Wiki Page Content : " + pageContent);
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
109
Result
The results will be displayed on the console. The snapshot given below shows the page
content retrieved.
Note
The wiki pages library should be available before executing the operation given below.
In this section, you will learn how to check, if wiki page exists or not. If it’s not present, the
same method will create a wiki page on the specified library. This can be accomplished,
using single method by PnP Core CSOM library. EnsureWikiPage method is used for the
operation.
The example given below checks and creates a wiki page on the site.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the Web object, create the page, using the input parameters.
o Wiki page library name
o Wiki page name
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
110
// Input Parameters
string libraryName = "WikiPages";
string pageName = "WikiPage2.aspx";
// Output
Console.WriteLine("Wiki Page is Availalbe");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console. The page is successfully ensured on SharePoint
site wiki page’s library. The snapshot given below shows the wiki page.
Note
The wiki pages library should be created before executing the operation given below.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
111
12.7 How to update a wiki page content
In this section, you will learn how to update the page content of wiki page, using PnP Core
CSOM library. AddHtmlToWikiPage method is used for updating the wiki page content. The
wiki page URL and content are passed as the parameters for updating.
The example given below retrieves the page content of wiki page.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the Web object, update the page content, using wiki page Server relative URL.
The required input parameter is given below.
o Wiki page URL.
o HTML content to be updated.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string pageContent = "Wiki Page Content Updated using PnP CSOM";
string pageUrl = "/sites/learning/WikiPages/WikiPage1.aspx";
// Output
Console.WriteLine("Wiki Page Content Updated");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
112
Result
The results will be displayed on the console. The snapshot given below shows the page
content updated.
In this section, you will learn how to apply existing page layout to a wiki page, using PnP
Core CSOM library. AddLayoutToWikiPage method is used to update wiki page layout.
The example given below applies the page layout to wiki page.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the Web object, apply the page layout. The page layouts can be accessed, using
WikiPageLayout object. The required input parameters are given below.
o Wiki Page URL
o Page Layout
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
113
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string pageUrl = "/sites/learning/WikiPages/WikiPage1.aspx";
WikiPageLayout pageLayout = WikiPageLayout.ThreeColumnsHeaderFooter;
// Output
Console.WriteLine("Wiki Page Content Updated");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console. The snapshot given below shows the page layout
is applied.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
114
12.9 How to retrieve web parts from a page
In this section, you will learn how to retrieve the Web parts from a page, using PnP Core
CSOM library. GetWebParts method is used to retrieve the Webparts from a specified page.
The example given below applies the page layout to wiki page.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the Web object, retrieve the Web parts from a page, using the page relative
URL. The required parameter is given below.
o Page URL
In the program file, insert the code mentioned below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string pageUrl = "/sites/learning/Pages/CustomPage.aspx";
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
115
Result
The results will be displayed on console.
In this section, you will learn how to add a Web part to a publishing page, using PnP Core
CSOM library. AddWebPartToWebPartPage method is used to adding Webpart to a specified
page.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the Web object, add the Web part to a page, using page relative URL. The
required parameter is
o Page URL
o Web part XML
The Web part XML defines the Web part properties, which needs to be added to the
page. The sample given below shows the Web part XML of the content editor Web
part, which will be used for adding it to the page.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
116
Web Part XML
<?xml version="1.0" encoding="utf-8"?>
<WebPart xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.microsoft.com/WebPart/v2">
<Title>Custom Content Editor</Title>
<FrameType>Default</FrameType>
<Description>Allows authors to enter rich text content.</Description>
<IsIncluded>true</IsIncluded>
<ZoneID>Header</ZoneID>
<PartOrder>0</PartOrder>
<FrameState>Normal</FrameState>
<Height />
<Width />
<AllowRemove>true</AllowRemove>
<AllowZoneChange>true</AllowZoneChange>
<AllowMinimize>true</AllowMinimize>
<AllowConnect>true</AllowConnect>
<AllowEdit>true</AllowEdit>
<AllowHide>true</AllowHide>
<IsVisible>true</IsVisible>
<DetailLink />
<HelpLink />
<HelpMode>Modeless</HelpMode>
<Dir>Default</Dir>
<PartImageSmall />
<MissingAssembly>Cannot import this Web Part.</MissingAssembly>
<PartImageLarge>/_layouts/15/images/mscontl.gif</PartImageLarge>
<IsIncludedFilter />
<Assembly>Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral,
PublicKeyToken=71e9bce111e9429c</Assembly>
<TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>
<ContentLink xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor" />
<Content xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor" />
<PartStorage xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor" />
</WebPart>
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string webPartXml = @"C:\Solution\PnPCSOM\PageOperations\webpart.xml";
string pageUrl = "/sites/learning/Pages/CustomPage.aspx";
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
117
WebPartEntity webpart = new WebPartEntity();
webpart.WebPartXml = System.IO.File.ReadAllText(webPartXml);
webpart.WebPartZone = "Right";
// Adds web part
clientContext.Site.RootWeb.AddWebPartToWebPartPage(pageUrl, webpart);
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console. The page will be updated with the Web part.
In this section, you will learn how to remove a Web part from the page, using PnP Core
CSOM library. DeleteWebPart method is used to remove the Webpart from a specified page.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the Web object, remove the Web part from a page, using page relative URL.
The required parameters are given below.
o Page URL.
o Web part title.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
118
{
// Input Parameters
string pageUrl = "/sites/learning/Pages/CustomPage.aspx";
string webpartTitle = "Custom Content Editor";
Result
The results will be displayed on the console. The Web part will be removed successfully from
the page.
In this section, you will learn how to retrieve the properties of a Web part, using PnP Core
CSOM library. GetWebPartProperties method is used for retrieving the properties of a Web
part from a specified page.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the Web object, retrieve the properties, using the input parameters given below.
o Web part GUID
o Page URL
In the program file, insert the code, mentioned below and save the file.
Run the code from Debug menu or by pressing F5.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
119
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string pageUrl = "/sites/learning/Pages/CustomPage.aspx";
Guid webpartId = new Guid("97825521-36a8-4302-a0d5-7b4911dfbc0c");
// Retrieves web part properties
PropertyValues webpartProps = clientContext.Site.RootWeb.GetWebPartProperties(webpartId,
pageUrl);
// Output
Console.WriteLine("Title : "+webpartProps["Title"]);
// Similarly other properties can also be accessed
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console.
Note
In the above sample, title of a web part is accessed. Similarly, other required properties can
be accessed.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
120
12.13 How to update the Web part properties
In this section, you will learn how to update the properties of a Web part, using PnP Core
CSOM library. SetWebPartProperties method is used to update the properties of a Web part
from a specified page.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the Web object, retrieve the properties, using the input parameters given below.
o Web part GUID
o Page URL
o Web part property key
o Web part property value
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string pageUrl = "/sites/learning/Pages/CustomPage.aspx";
Guid webpartId = new Guid("97825521-36a8-4302-a0d5-7b4911dfbc0c");
string propertyName = "Description";
string propertyValue = "Content query web part used to query the SP lists";
// Output
Console.WriteLine("Web Part Properties updated, Similarly other properties can be updated.");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
121
Console.ReadKey();
}
Result
The results will be displayed on console.
Note
1. To check the updated values, export the Web part from a page manually and check the
Web part description file.
2. In the sample given above, description of a Web part is updated. Similarly, other
required properties can be updated.
In this section, you will learn how to add a Web part to a wiki page, using PnP Core CSOM
library. AddWebPartToWikiPage method is used to add the Web part to a specified page.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the Web object, add the Web part to a page, using page relative URL. The
required parameters are given below.
o Page URL
o Web part XML
o Row – Page table row value
o Column – Page table column value
o Space (Boolean) – Blank line after the Web part in the page
The Web part XML defines the Web part properties, which needs to be added to the
page. Please refer to section 12.10 (How to add web part to a publishing page) section
for the Web part sample XML content.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
122
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string webPartXml = @"C:\Solution\PnPCSOM\PageOperations\webpart.xml";
string pageUrl = "/sites/learning/WikiPages/WikiPage1.aspx";
// Output
Console.WriteLine("Web part is successfully added to Wiki Page");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console. The page will be updated with the Web part.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
123
13 SharePoint User and Group Operations
In this topic, you will learn how to perform basic SharePoint user and group that can be
performed on SharePoint site, using PnP Core CSOM library.
The methods used for the user and group operations are given below.
GetAdministrators
AddAdministrators
AddGroup
GetGroupID
GroupExists
AddUserToGroup
AddPermissionLevelToGroup
RemovePermissionLevelFromGroup
AddPermissionLevelToUser
AddPermissionLevelToPrincipal
RemovePermissionLevelFromUser
RemovePermissionLevelFromPrincipal
AddReaderAccess
In this section, you will learn how to retrieve the site collection administrators from a
SharePoint site, using PnP Core CSOM library. GetAdministrators method is used to retrieve
all the site collection administrators of a site.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the Web object, retrieve the administrators, using GetAdministrators method.
The input parameters are not required for this process.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
124
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Gets Site Collection Admins
List<UserEntity> admins = clientContext.Site.RootWeb.GetAdministrators();
Result
The results will be displayed on the console.
Note
The above operation is applicable only for SharePoint online sites.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
125
13.2 How to add the site collection administrator
In this section, you will learn how to add a user as a site collection administrator to a
SharePoint site, using PnP Core CSOM library. AddAdministrators method is used to add the
site collection administrators to a site.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book for
importing the packages and creating authentication manager object.
Using the web object, add the administrators, using AddAdministrators method. The
input parameters are given below.
o User Entity List – List with the set of users
o Add to owners group (Boolean) – The users to be added to the site group
owners.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
List<UserEntity> admins = new List<UserEntity>();
UserEntity admin = new UserEntity();
admin.LoginName = "nirmal";
admins.Add(admin);
// Multiple users can be added as admins with the help of above list
Result
The results will be displayed on the console. Navigate to the site collection administrators’
page to check the output. The snapshot given below shows the site collection administrators’
page.
Note
The operation given above is applicable only for SharePoint online sites.
In this section, you will learn how to create a SharePoint group on SharePoint site, using PnP
Core CSOM library. AddGroup method is used to create a group on the site. Group name and
group description are required to create a group.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the Web object, create/add the group, using AddGroup method. The input
parameters are given below.
o Group Name
o Group Description
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
127
o Site Ownership for group
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
string groupName = "CustomGroup1";
string groupDesc = "Provides unqiue site permissions";
bool siteOwnership = false;
// Adds group to site
Group customGroup = clientContext.Site.RootWeb.AddGroup(groupName, groupDesc,
siteOwnership);
// Other properties / Users can be added to group directly
Console.WriteLine("Group is created and added to site");
Result
The results will be displayed on the console. The snapshot given below shows the SharePoint
group created on SharePoint portal.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
128
13.4 How to retrieve a SharePoint group ID
In this section, you will learn how to retrieve ID of a SharePoint group from SharePoint site ,
using PnP Core CSOM library. GetGroupID method is used to retrieve the ID of a group.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the Web object, retrieve the Id, using GetGroupID method. The input
parameter is given below.
o Group Name.
In the program file, insert the code, mentioned below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string groupName = "CustomGroup1";
// Retrieves group ID using group name
int groupId = clientContext.Site.RootWeb.GetGroupID(groupName);
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
129
//Output
Console.WriteLine("Group ID : " + groupId);
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console.
In this section, you will learn how to check, if the group already exists on the site or not,
using PnP Core CSOM library. GroupExists method is used for this operation.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the Web object, check if the group exists, using GroupExists method. The input
parameter is given below.
o Group Name.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
130
string groupName = "CustomGroup1";
// Retrieves group ID using group name
bool groupExists = clientContext.Site.RootWeb.GroupExists(groupName);
//Output
if (groupExists)
{
Console.WriteLine("Group exists");
}
else
{
Console.WriteLine("Group doesnt exists");
}
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console.
In this section, you will learn how to add a user to SharePoint group, using PnP Core CSOM
library. AddUserToGroup method is used for this operation.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the Web object, add the user to group, using AddUserToGroup method. The
input parameters are given below.
o Group Name
o User Login Name
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
131
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string groupName = "CustomGroup1";
string userLoginName = "Nirmal";
// Adds user to group
clientContext.Site.RootWeb.AddUserToGroup(groupName, userLoginName);
// Output
Console.WriteLine("Added user to group");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console. The snapshot given below shows the group with
the added users.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
132
13.7 Add permissions to SharePoint group / add groups with permissions
to the site (or list or item)
In this section, you will learn how to add the permissions to SharePoint group, using PnP
Core CSOM library. AddPermissionLevelToGroup method is used for updating the
permissions. Adding permissions to the group will literally add the group to the site
permissions.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the Web object, add the permissions to the group, using
AddPermissionLevelToGroup method. The input parameters are given below.
o Group Name.
o Role Type.
o Remove Existing Permissions (Boolean).
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string groupName = "CustomGroup1";
RoleType roleType = RoleType.Reader;
bool removeExistingPermission = true;
// Updates group permissions
clientContext.Site.RootWeb.AddPermissionLevelToGroup(groupName, roleType,
removeExistingPermission);
// Output
Console.WriteLine("Group permissions updated");
Console.ReadKey();
}
}
catch (Exception ex)
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
133
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console. To check the permission manually, navigate to
Site Settings Site Permissions. The snapshot given below shows the group with the added
permissions.
The permissions of a group can be accessed from the respective group page by navigating to
Site Settings People and Group Groups Respective Group Settings Group
Permissions. The snapshot given below depicts the same.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
134
Note
1. In the sample given above, the group permissions is with respect to the sites. If the
method AddPermissionLevelToGroup is accessed from the lists/permissions instead
from the Web object, the permissions will be updated for the respective objects.
2. If you are going to perform the operation with the group, object exists instead of the
group name, then the same operation can be carried out, using
AddPermissionLevelToPrincipal method. The code snippet given below shows the
logic.
clientContext.Site.RootWeb.AddPermissionLevelToPrincipal(group, roleType,
removeExistingPermission);
In this section, you will learn how to remove the permissions from SharePoint group, using
PnP Core CSOM library. RemovePermissionLevelFromGroup method is used to remove the
permissions. Removing the permissions from the group will literally remove the group from
the site permissions, if no other permissions exists.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the Web object, remove the permissions from the group, using
RemovePermissionLevelFromGroup method. The input parameters are given below.
o Group Name
o Role Type
o Remove All Permissions (Boolean)
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
135
string groupName = "CustomGroup1";
RoleType roleType = RoleType.Reader;
bool removeAllPermissions = true;
// Removes group permissions
clientContext.Site.RootWeb.RemovePermissionLevelFromGroup(groupName, roleType,
removeAllPermissions);
// Output
Console.WriteLine("Group permissions removed");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console. To check the permission manually, navigate to
Site Settings Site Permissions.
The permissions of a group can be accessed from the respective group page by navigating to
Site Settings People and Group Groups Respective Group Settings Group
Permissions.
Note
1. In the sample given above, the group permissions are with respect to the site. If the
method RemovePermissionLevelFromGroup is accessed from the lists/permissions
instead from the Web object, the permissions will be removed for the respective
objects.
2. If the group object exists, the same operation can be carried out, using
RemovePermissionLevelFromPrincipal method. The code snippet given below shows
the logic.
clientContext.Site.RootWeb.RemovePermissionLevelFromPrincipal(group, roleType,
removeExistingPermission);
13.9 Add the permissions to SharePoint User / add the user with
permissions to the site (or list or item)
In this section, you will learn how to add the permissions to SharePoint user, using PnP Core
CSOM library. AddPermissionLevelToUser method is used to update the permissions.
Adding permissions to the user will literally add the user to the site permissions.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
136
Note- In the sample given below, the permissions are respect to the site/Web. If the method
AddPermissionLevelToUser is accessed from the lists/permissions instead of the Web object,
the permissions will be updated for the respective objects.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the Web object, add the user to group, using AddPermissionLevelToUser
method. The input parameters are given below.
o User Login Name
o Role Type
o Remove Existing Permissions (Boolean)
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string userLoginName = "ram";
RoleType roleType = RoleType.Reader;
bool removeExistingPermission = true;
// Updates user permissions
clientContext.Site.RootWeb.AddPermissionLevelToUser(userLoginName, roleType,
removeExistingPermission);
// Output
Console.WriteLine("Added user to site with read permission");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
137
Result
The results will be displayed on the console. To check the permission manually, navigate to
Site Settings Site Permissions. The snapshot given below shows the group with the added
permissions.
Note
If the user object exists, then the same operation can be carried out, using
AddPermissionLevelToPrincipal method. The code snippet given below shows the logic.
clientContext.Site.RootWeb.AddPermissionLevelToPrincipal(user, roleType,
removeExistingPermission);
13.10 Remove the permissions for SharePoint user / remove the user with the
permissions from the site (or list or item)
In this section, you will learn how to remove the permissions for SharePoint user, using PnP
Core CSOM library. RemovePermissionLevelFromUser method is used to update the
permissions. Adding permissions to the user will literally remove the user from the site
permissions, if no other permissions exists for the user.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the Web object, add the user to the group, using
RemovePermissionLevelFromUser method. The input parameters are given below.
o User Login Name
o Role Type
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
138
o Remove All Permissions (Boolean)
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string userLoginName = "ram";
RoleType roleType = RoleType.Reader;
bool removeAllPermission = true;
// Removes user permissions
clientContext.Site.RootWeb.RemovePermissionLevelFromUser(userLoginName, roleType,
removeAllPermission);
// Output
Console.WriteLine("Removed user from the site permissions");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console. To check the permission manually, navigate to
Site Settings Site Permissions.
Note
1. In the sample given above, the permissions are respect to the site/Web. If the method
RemovePermissionLevelFromUser is accessed from the lists/permissions instead of
the Web object, the user permissions will be removed for the respective objects.
2. If you are using the user object instead of the user name, the same operation can be
carried out, using RemovePermissionLevelFromPrincipal method. The code snippet
given below shows the logic.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
139
clientContext.Site.RootWeb.RemovePermissionLevelFromPrincipal(user, roleType,
removeExistingPermission);
In this section, you will learn how to provide read level permissions to all SharePoint users ,
using PnP Core CSOM library. AddReaderAccess method is used to provide the permissions.
This will not include the permissions for the external users. For On-Premise sites, the input
parameter is required.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the Web object, provide the permissions, using AddReaderAccess method. No
input parameters are required.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Provides read permissions to all users except external users
clientContext.Site.RootWeb.AddReaderAccess();
// Output
Console.WriteLine("Read permission granted for all users (except external users)");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
140
Result
The results will be displayed on the console. The same can be accomplished with the input
parameter.
clientContext.Site.RootWeb.AddReaderAccess(OfficeDevPnP.Core.Enums.BuiltInIdentity.Everyone
ButExternalUsers)
For On-Premise sites, only the method given below will work.
clientContext.Site.RootWeb.AddReaderAccess(OfficeDevPnP.Core.Enums.BuiltInIdentity.Everyone)
To check the permission manually, navigate to Site Settings Site Permissions Visitors
group. The snapshot given below shows the group with the added permissions.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
141
14 Taxonomy Tasks
In this topic, you will learn how to perform taxonomy operations, using PnP Core CSOM
Library.
The taxonomy term store of a site can be accessed on term stores page. For example, the term
store URL is https://nakkeerann.sharepoint.com/_layouts/15/termstoremanager.aspx.
Please make sure, you are a term store administrator before executing any of the operations.
It can be changed on the tenant site. The URL will be https://nakkeerann-
admin.sharepoint.com/_layouts/15/termstoremanager.aspx.
CreateTermGroup
EnsureTermGroup
GetTermGroupByName
GetTermGroupById
EnsureTermSet
GetTermSetsByName
AddTermToTermSet
GetTermByName
ImportTerms
ExportTermSet
ExportAllTerms
GetTaxonomyItemByPath
In this section, you will learn how to create a term group on SharePoint taxonomy, using PnP
Core CSOM library.
The example given below creates a term group called Cities on the taxonomy term store.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Retrieve the taxonomy session and appropriate taxonomy term store, using
GetDefaultSiteCollectionTermStore method. Subsequently, create the term group ,
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
142
using CreateTermGroup method. The input parameters, which are required are given
below.
o Term Store
o Group Name
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string groupName = "Cities";
// Output
Console.WriteLine("Term Group Created");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console. The snapshot given below shows the taxonomy
page with the created term group.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
143
14.2 How to ensure Term Group
In this section, you will learn how to ensure whether a term group exists or not. If it doesn’t
exists, the term group will be created on the term set of portal using PnP Core CSOM library.
The example given below ensures a term group called Cities on the taxonomy term store.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the TaxonomyExtensions class, term group is ensured, using
EnsureTermGroup method. The required parameters are given below.
o Site Object – Retrieved using client context.
o Group Name.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
144
// Input Parameters
string groupName = "Cities";
// Output
Console.WriteLine("The following term group exists on the site : " + termGroup.Name);
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console.
In this section, you will learn how to retrieve the term group by name from term store, using
PnP Core CSOM library.
The example given below retrieves a term group called Cities from the taxonomy term store.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the TaxonomyExtensions class, term group is retrieved, using
GetTermGroupByName method. The required parameters are given below.
o Site Object – Retrieved using the client context.
o Group Name.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
145
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string groupName = "Cities";
// Output
Console.WriteLine("The following term group exists on the site : ");
Console.WriteLine("Name : " + termGroup.Name);
Console.WriteLine("ID : " + termGroup.Id);
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The results will be displayed on the console, as shown below.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
146
14.4 How to retrieve Term Group by ID
In this section, you will learn how to retrieve the term group by ID from term store, using
PnP Core CSOM library.
The following example retrieves a term group called Cities from the taxonomy term store.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the TaxonomyExtensions class, term group is ensured, using
GetTermGroupById method. The required parameters are given below.
o Site Object – Retrieved using client context.
o Group ID – GUID.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
Guid groupId = new Guid("e7b274f6-16ac-45a8-add5-b15c33b0e107");
// Output
Console.WriteLine("The following term group exists on the site : ");
Console.WriteLine("Name : " + termGroup.Name);
Console.WriteLine("ID : " + termGroup.Id);
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
147
Result
The results will be displayed on the console.
In this section, you will learn how to create or ensure the term set on term store, using PnP
Core CSOM library.
The example given below creates/ensures a term set called “Vellore” on term group “Cities”
from the taxonomy term store.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the TaxonomyExtensions class, retrieve the term group and term set is
created/ensured, using EnsureTermSet method. The required parameters are given
below.
o Term group name.
o Term set name.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string groupName = "Cities";
string termSetName = "Vellore";
// PnP CSOM method to retrieve term group
TermGroup termGroup = TaxonomyExtensions.GetTermGroupByName(clientContext.Site,
groupName);
Result
The results will be displayed on the console, as shown below.
In this section, you will learn how to retrieve the term sets from term store, using PnP Core
CSOM library.
The example given below retrieves a term set called “Vellore” from term group “Cities”.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the TaxonomyExtensions class, retrieve the term sets, using
GetTermSetsByName method. The required parameters are given below.
o Site object.
o Term set name.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
149
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string termSetName = "Vellore";
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The snapshot given below shows the result on the console.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
150
14.7 How to create a Term on Term Set
In this section, you will learn how to create/add term on taxonomy term set, using PnP Core
CSOM library.
The example given below creates a term called “Term1” on term set “Vellore” of the term
group “Cities” from the taxonomy term store.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the TaxonomyExtensions class, add the terms, using AddTermToTermset
method. The required parameters are given below.
o Site object.
o Source Term Set ID.
o New Term Name.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string termName = "Term1";
Guid termSetId = new Guid("6798d644-3b33-4f58-926e-c22a17cecf1c"); // Term Set Id of
Vellore
Console.ReadKey();
}
}
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
151
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The result will be displayed on the console. The snapshot given below shows the term added
to the term set.
In this section, you will learn how to retrieve the term from taxonomy term set, using PnP
Core CSOM library.
The example given below retrieves a term called “Term1” from the term set “Vellore” of the
term group “Cities” on the taxonomy term store.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the TaxonomyExtensions class, retrieve the term, using GetTermByName
method. The required parameters are given below.
o Site object.
o Source Term Set ID.
o Term Name.
In the program file, insert the code given below and save the file.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
152
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string termName = "Term1";
Guid termSetId = new Guid("6798d644-3b33-4f58-926e-c22a17cecf1c"); // Term Set Id of
Vellore
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The result will be displayed on the console, as shown below.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
153
14.9 How to retrieve the term from the term store by the path
In this section, you will learn how to retrieve term from taxonomy term store by the path,
using PnP Core CSOM library.
The example given below retrieves a term called “Term1” from the term set “Vellore” of the
term group “Cities” on the taxonomy term store.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the TaxonomyExtensions class, retrieve the term, using
GetTaxonomyItemByPath method. The required parameters are given below.
o Site object.
o Term path separated by delimiters.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Term path on term store
string termPath = "Cities|Vellore|Term1";
// Retrieve term by path
TaxonomyItem taxonomyItem =
TaxonomyExtensions.GetTaxonomyItemByPath(clientContext.Site, termPath);
// Output
Console.WriteLine("Term details :");
Console.WriteLine("ID : " + taxonomyItem.Id);
Console.WriteLine("Name : " + taxonomyItem.Name);
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
154
Result
The result will be displayed on the console, as shown below.
In this section, you will learn how to import terms into the existing taxonomy term sets, using
PnP Core CSOM library.
The example given below imports few terms into the term set “Vellore” of the term group
“Cities” on the taxonomy term store.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the TaxonomyExtensions class, add the terms to the term set, using
ImportTerms method. The required parameters are given below.
o Site object.
o Terms – String array which contains the terms defined as
TermGroup|TermSet|Term
o Locale value.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string[] terms = { "Cities|Vellore|Term2", "Cities|Vellore|Term3", "Cities|Vellore|Term5" };
// Imports Terms
TaxonomyExtensions.ImportTerms(clientContext.Site, terms, 1033);
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
155
// Output
Console.WriteLine("The terms has been imported.");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The result will be displayed on the console. The terms which are import can be viewed from
the term store page.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
156
14.11 How to export the term set
In this section, you will learn how to export the term set with the terms from taxonomy term
sets, using PnP Core CSOM library.
The example given below exports the terms from the term set “Vellore” of the term group
“Cities” on the taxonomy term store.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the TaxonomyExtensions class, export the term sets, using ExportTermSet
method. The required parameters are given below.
o Site object
o Term Set ID
o IncludeId - Export ID’s as well (Boolean)
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
Guid termSetId = new Guid("6798d644-3b33-4f58-926e-c22a17cecf1c"); // Term Set Id of
Vellore
// Export Term Set
List<string> termSets = TaxonomyExtensions.ExportTermSet(clientContext.Site, termSetId,
true);
// Output
foreach(string term in termSets)
{
Console.WriteLine(term);
}
Console.ReadKey();
}
}
catch (Exception ex)
{
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
157
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The result will be displayed on the console.
Note
To get only the names in the result, Include Id parameter, which should be set to false.
In this section, you will learn how to export all the terms from taxonomy term store, using
PnP Core CSOM library.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Using the TaxonomyExtensions class, export the term sets, using ExportAllTerms
method. The required parameters are given below.
o Site object.
o IncludeId - Export IDs as well (Boolean).
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
158
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
List<string> terms = TaxonomyExtensions.ExportAllTerms(clientContext.Site, false);
// Output
foreach (string term in terms)
{
Console.WriteLine(term);
}
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The result will be displayed on the console.
Note
To get term/term set GUIDs within the result, IncludeId parameter should be set to true.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
159
14.13 How to create Taxonomy Field on Site/List
In this section, you will learn how to create a taxonomy field on SharePoint site or the list,
using PnP Core CSOM library.
The example give below creates a taxonomy field on a site with the term store value.
Steps involved
Open Visual Studio as administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Retrieve the term from term store, using section 14.9
Using the TaxonomyExtensions class, create a taxonomy field, using
CreateTaxonomyField method. The required parameters are given below.
o Web object or list object.
o Field Creation info, which contains the field details like GUID, internal name,
display name, group and taxonomy item.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Term path on term store
string termPath = "Cities|Vellore|Term1";
// Retrieve term by path
TaxonomyItem taxonomyItem =
TaxonomyExtensions.GetTaxonomyItemByPath(clientContext.Site, termPath);
Result
The results will be displayed on the console. The field can be viewed from the site
columns/list column pages, as shown below.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
161
14.14 How to update Taxonomy Field on List Item
In this section, you will learn how to update a taxonomy field value of the list item, using PnP
Core CSOM library.
The example given below updates a list item with the term store value.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
Retrieve the list item to be updated.
Using the TaxonomyExtensions class, update the taxonomy field value, using
SetTaxonomyFieldValueByTermPath method. The required parameters are given
below.
o List item
o Term path
o Field GUID
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Term path on term store
string termPath = "Cities|Vellore|Term2";
// Input parameters for taxonomy field
string fieldId = "C584C999-1E90-4D67-AA99-D05374E25C38";
Guid fieldGuid = new Guid(fieldId);
Result
The results will be displayed on the console. The snapshot given below shows the updated
value.
In this section, you will learn how to remove a taxonomy field from SharePoint site, using
PnP Core CSOM library.
The example given below removes a list item with the term store value.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
163
Using the TaxonomyExtensions class, remove the field from the site, using
RemoveTaxonomyFieldByInternalName method. The required parameters are given
below.
o Web object
o Field name
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input parameters
string fieldName = "NakkeeranTaxColumn1";
Result
The results will be displayed on the console.
Note
The field can be removed from the site, using field ID as well. The method for removing
using ID is RemoveTaxonomyFieldById(web,fieldGuid).
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
164
15 Office 365 Site Collection tasks
In this topic, you will learn how to perform the operations on Office 365 tenant site, using
PnP Core CSOM library. These operations can be used only on Office 365 sites.
The methods given below are majorly used for the operations in this topic.
CreateSiteCollection.
GetSiteCollections.
CheckIfSiteExists.
DeleteSiteCollection.
In this section, you will learn how to create a site collection on Office 365 tenant site.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object. In place of site user
details, URL (https://***-admin.sharepoint.com) of the tenant site should be passed
along with the tenant user credentials.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
165
Using the client context object, create the site collection, using CreateSiteCollection
method. The input parameters are initialized and passed, using SiteEntity class. The
required parameters are given below.
o Title
o Template
o URL
o Owner
o Maximum Storage
o Maximum resources
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
var tenant = new Tenant(clientContext);
SiteEntity siteEntity = new SiteEntity();
siteEntity.Title = "Samplepnp";
siteEntity.Template = "STS#0";
siteEntity.Url = "https://***.sharepoint.com/sites/Samplepnp";
siteEntity.SiteOwnerLogin = "abc@nakkeerann.onmicrosoft.com";
siteEntity.UserCodeMaximumLevel = 10;
siteEntity.StorageMaximumLevel = 30;
// Output
Console.WriteLine("Site Collection is created " + tenantSiteCollectionId);
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
166
Result
The result will be displayed on the console. The created site collection can be accessed from
the tenant site (https://***-admin.sharepoint.com/_layouts/15/online/SiteCollections.aspx).
15.2 How to retrieve the site collections from the tenant site
In this section, you will learn how to retrieve the site collections from Office 365 tenant site.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book for
importing the packages and creating authentication manager object. In place of site
user details, URL (https://***-admin.sharepoint.com) of the tenant site should be
passed along with the tenant user credentials.
Using the client context object, retrieve the site collection, using GetSiteCollections
method. The return object will be the list containing the site collection as the site
entity type.
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
var tenant = new Tenant(clientContext);
List<SiteEntity> siteCollections = tenant.GetSiteCollections() as List<SiteEntity>;
// Output
foreach (SiteEntity siteCollection in siteCollections)
{
Console.WriteLine(siteCollection.Title + " - " + siteCollection.Url);
}
Console.ReadKey();
}
}
catch (Exception ex)
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
167
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The result will be displayed on the console, as shown below.
The site collections can be accessed from the tenant site (https://***-
admin.sharepoint.com/_layouts/15/online/SiteCollections.aspx).
In this section, you will learn how to check whether a site collection exists on a tenant site or
not, using PnP Core CSOM library.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object. In place of site user
details, URL (https://***-admin.sharepoint.com) of the tenant site should be passed
along with the tenant user credentials.
Using the client context object, check the status of site collection, using
CheckIfSiteExists method. The return type is Boolean. The input parameters are given
below.
o Site Collection URL
o Status (Active, Creating or Recycled)
In the program file, insert the code given below and save the file.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
168
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string siteCollectionUrl = "https://nakkeerann.sharepoint.com/sites/Samplepnp";
string siteStatus = "Active";
var tenant = new Tenant(clientContext);
// Output
if (siteExists)
{
Console.WriteLine("Site is Active");
}
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
Console.ReadKey();
}
Result
The result will be displayed on the console.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
169
15.4 How to delete a site collection
In this section, you will learn how to delete a site collection from the tenant site, using PnP
Core CSOM library.
Steps involved
Open Visual Studio as an administrator.
Follow the steps explained in section 4 (Connect to SharePoint site) of the book to
import the packages and create authentication manager object. In place of the site user
details, the URL (https://***-admin.sharepoint.com) of the tenant site should be
passed along with the tenant user credentials.
Using the client context object, remove the site collection from the tenant site, using
DeleteSiteCollection method. The required input parameters are given below.
o Site collection URL
o Use recycle bin (Boolean) – Whether to use recycle bin or not?
In the program file, insert the code given below and save the file.
Run the code from Debug menu or by pressing F5.
Code
try
{
// Get and set the client context
// Connects to SharePoint online site using inputs provided
using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl,
userName, password))
{
// Input Parameters
string siteCollectionUrl = "https://nakkeerann.sharepoint.com/sites/Samplepnp";
bool useRecycleBin = true;
var tenant = new Tenant(clientContext);
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
170
Result
The result will be displayed on the console. The site collection will be deleted and moved to
recycle bin.
Note
To remove the site collection from recycle bin, DeleteSiteCollectionFromRecycleBin method
is used.
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
171
16 Summary
Thus we have learnt programming on PnP Core CSOM library programming. The book
covers all the basic operations required to access the various objects on SharePoint instances.
The advanced or complex code can be developed and executed from the base samples given
above. The operations explained in the sections mentioned above are compatible for
SharePoint 2013, SharePoint 2016 and SharePoint online (Office 365) versions.
17 References
https://github.com/OfficeDev/PnP-Sites-Core/blob/master/Core/Documentation.md
©2016 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.