40+ SharePoint server object model examples

This SharePoint tutorial explains, 40+ SharePoint server object model examples. Various SharePoint server object model classes which are available in SharePoint 2010/2013/2016.

Let us discuss more on the SharePoint server object model.

SharePoint 2016 Tutorial Contents

SharePoint server object model

There are two types of object model in SharePoint.

  • Server object model
  • Client object model

We will discuss how to work with the SharePoint server object model. SharePoint server object model code will run in the SharePoint server (where SharePoint is installed).

Apart from visual web parts, custom features etc, we can also develop client applications like a console application, windows applications or Asp.Net web-based applications which will run on a SharePoint server.

To work with the SharePoint server object model, we need to add Microsoft.SharePoint.dll.

Microsoft provides Microsoft.SharePoint namespace to work with the top-level site, site, subsite or list, etc. The dll is located in the below directory.

E:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI

Here I have installed SharePoint 2016 in my E drive.

Below are various SharePoint components, classes, and namespaces.

SharePoint ComponentsServer Object Model ClassesNamespace
FarmSPFarmMicrosoft.SharePoint.Administration
ServerSPServerMicrosoft.SharePoint.Administration
Web ApplicationSPWebAplicationMicrosoft.SharePoint.Administration
Content DatabaseSPContentDatabaseMicrosoft.SharePoint.Administration
Site CollectionSPSiteMicrosoft.SharePoint
SiteSPWebMicrosoft.SharePoint
List/LibrarySPListMicrosoft.SharePoint
ListItemSPListItemMicrosoft.SharePoint

We can create a windows application or console application using visual studio and then we can add the Microsoft.SharePoint.dll to work with the SharePoint server object model.

To create a console application, Open visuals studio -> File -> New Project.

Then Select “Windows Forms App (.NET Framework)” project template.

Sharepoint Server Object Model features

Then Add reference to Microsoft.SharePoint.dll

sharepoint server object model classes

Then you can write the SharePoint server object model code.

We will see how to create a list programmatically using the SharePoint server object model and how to check if a list exists or not using TryGetList method in SharePoint server object model code and delete items to recycle bin programmatically using SharePoint server object model code.

By using the SharePoint server object model, we will discuss how to add a user to the SharePoint group using programmatically using the server object model code.

Also, we will discuss how to change master page and page layout programmatically using the SharePoint server object model and how to get URL value SharePoint hyperlink field using the SharePoint server object model.

Finally, we will discuss how to insert Flat Data to SharePoint List using server object model code. All the codes will work in SharePoint 2010/2013/2016.

SharePoint server object model classes

Let us first discuss the various hierarchy of SharePoint server object model classes. All the server object classes are derived from Microsoft.SharePoint namespace and the administration classes inside the Microsoft.SharePoint.Administration namespace.

SharePoint server object model examples
SharePoint server object model examples

SPFarm:
This reference the entire SharePoint Server Farm.
By using this you can create a new farm or you can connect to an existing farm.
Namespace: Microsoft.SharePoint.Administration

SharePoint server farm can be small, medium or large based on the various factors like organizations infrastructure, number of web applications, number of users accessing it, etc. The smallest server farm consists of a database server running on Microsoft SQL Server, one or more servers running IIS and office SharePoint server.

SPServer:
By using this class you can browse through the collections of servers belongs to the Farm.

SPWebApplication:

SharePoint web application is similar to that of the IIS web site. When a web application is created using the “Create or Extend Web Application” link in “Application Management” it creates a content database for the site collection, creates an IIS website and the virtual directories like “control templates. _layouts, _vti_bin, etc” mapped to the 16/14/12 hive SharePoint structure. You can have multiple content database in a single web application.

SPSite:
Represent a Site collection.

SPWeb:
Represent a web site.

SPUserToken:
The SPUserToken class represents a token for a valid SharePoint user.

SPList:
SPList corresponds to a single list instance, whether that is a list of items or a document library.

SPListItem:
This defines a reference to a specific item of a list.

SPDocumentLibrary:
This type represents a document library.

SPFile:
This class is used to enumerate the files contained in a document library.

SPPrincipal:
This class is the parent class for SPGroup and SPUser.

SPControl:
This class we need while developing web controls or Web Parts.

SPContext:
This is a very useful class and it has some direct methods to access useful information about current requests.

Create list programmatically using SharePoint server object model

In this SharePoint server example, we will discuss how to create a list using the SharePoint server object model. The code will work in SharePoint 2010/2013/2016.

To work with the SharePoint server object model we need to use Microsoft.SharePoint.dll and you have to execute the code where SharePoint server is installed.

If you have not installed SharePoint 2013/2016/2019, you can download free installation PDF on SharePoint 2016 and SharePoint 2019.

Create a list using the SharePoint server object model (By using SPContext)

Below is the code to create a list using SharePoint server object model programmatically using SPContext.

public void CreateList()
{
SPWeb site = SPContext.Current.Web;
string ListTitle = “Our List Name”;
string ListDescription = “This is our description for our list”;
Guid ListId = site.Lists.Add(ListTitle, ListDescription, SPListTemplateType.Contacts); //We are using Contacts list template for our list.
SPList list = site.Lists[ListId];
list.OnQuickLaunch = true; // This is to show the list in the quick launch bar.
list.Update();
}

Create list using SharePoint server object model (Without using SPContext)

Below is the SharePoint server object model code to create a SharePoint list programmatically using the server object model code. The code will work in SharePoint 2013/2016/2010 versions.

public void CreateList()
{
using (SPSite site = new SPSite(“http://mypc:29024/sites/SPTraining/”))
{
using (SPWeb web = site.OpenWeb())
{
string ListTitle = “Our List Name”;
string ListDescription = “This is our description for our list”;
Guid ListId = web.Lists.Add(ListTitle, ListDescription, SPListTemplateType.Contacts); //We are using Contacts list template for our list.
SPList list = web.Lists[ListId];
list.OnQuickLaunch = true; // This is to show the list in the quick launch bar.
list.Update();
}
}
}

Also you may like below SharePoint list tutorials:

Retrieve subsites users having permission using the SharePoint server object model

Now, we will see how we can retrieve the collection of child sites of the current site based on user permission. For this, we can use SPWeb.GetSubwebsForCurrentUser Method which is presented in the SharePoint server object model.

It will return all the subsite which the user has permission to access. This returns a SPWebCollection object.

void GetAllWebs()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
SPWeb currentWeb = SPContext.Current.Site.RootWeb;
foreach (SPWeb web in currentWeb.GetSubwebsForCurrentUser())
{
if (web.Webs != null && web.Webs.Count > 0)
{
sb.Append(“Site Title ” + web.Title + ” Site URL” + web.Url);
}
}
}

Benefits of this method are if your site collection contains some subsite which the logged-in user does not have permission, then it will not through any exception rather it will return null.

Delete items to recycle bin programmatically using SharePoint server object model code

Now, we will see how we can delete items to recycle bin programmatically using the SharePoint server object model code. The same server object model code will delete items programmatically in SharePoint 2010/2013/2016.

The item will be there available in recycle bin.

Suppose you delete an item from a SharePoint list Programmatically then it will not go to Recycle Bin rather it will delete completely. But If you delete an item from the browser then it will go to Recycle Bin.

Recycle() method of SPListItem will help us in this type of situation. Refer below code.

void RecycleListItem()
{
SPSite myTopSite = SPContext.Current.Site;
{
SPWeb myTopWeb = SPContext.Current.Site.RootWeb;
{
SPList list = myTopWeb.Lists.TryGetList(“MyCustomList”);

if (list != null)
{
if (list.ItemCount > 2000)
{
foreach (SPListItem item in list.Items)
{
item.Recycle();
}
}
}
}
}
}

The above code will move the items to the recycle bin.

You can see PowerShell SharePoint Examples.

You may like following SharePoint recycle bin tutorials:

Change master page programmatically using SharePoint server object model

Now, we will see how we can change a master page programmatically using the SharePoint server object model code.

Below is the code to change master page programmatically in SharePoint.

using (SPWeb currentWeb = properties.Web)
{
currentWeb.AllowUnsafeUpdates = true;
currentWeb.MasterUrl = “/_catalogs/masterpage/MyCustomMaster.master”;
currentWeb.CustomMasterUrl = “/_catalogs/masterpage/MyCustomMaster.master”;

//You can use the below approach also, but sometimes that did not work.

//currentWeb.CustomMasterUrl = currentWeb.Site.RootWeb.ServerRelativeUrl + “/_catalogs/masterpage/MyHpIndigo2ndLevelMaster.master”;
currentWeb.Update();
currentWeb.AllowUnsafeUpdates = false;
}

Change SharePoint master page using event handler

Change the master page at the time of site creation in SharePoint 2010/2013. So for that purpose, we will have to write one event handler that will fire in the WebProvisioned event. You can check an article on how to Create an event handler to prevent items from deleting item from SharePoint list using Visual Studio 2010.

Once we created the event receiver we need to override the WebProvisioned() method as below to change the master page.

public override void WebProvisioned(SPWebEventProperties properties)
{
try
{
using (SPWeb currentWeb = properties.Web)
{
currentWeb.AllowUnsafeUpdates = true;
currentWeb.MasterUrl = “/_catalogs/masterpage/MyCustomMaster.master”;
currentWeb.CustomMasterUrl = “/_catalogs/masterpage/MyCustomMaster.master”;

//You can use the below approach also, but sometimes that did not work.

//currentWeb.CustomMasterUrl = currentWeb.Site.RootWeb.ServerRelativeUrl + “/_catalogs/masterpage/MyHpIndigo2ndLevelMaster.master”;
currentWeb.Update();
currentWeb.AllowUnsafeUpdates = false;
}
}
catch (Exception ex)
{
throw;
}
}

You may like following SharePoint master page tutorials:

Get URL value SharePoint hyperlink field using SharePoint server object model

Now, we will discuss how to get URL value SharePoint hyperlink field SharePoint 2010/2013/2016.

Suppose your custom list contains a column of type Hyperlink or Picture. And suppose you want to retrieve the list items through the SharePoint object model, then if you directly try to retrieve like below:

SPListItem item = list.GetItemById(1); //Suppose you want to retrieve the 1st item from the custom list.

string URL = item[“URL”].ToString(); //Trying to retrive the value of URL which is of type Hyperlink or Picture

If you try to get the URL by the above approach you will return with two times the URL with a comma-separated. Why we get this because it returns the URL and the Description.

If you left the description field black while adding the list item you will get two time URL with comma-separated.

But if you put something in the description field you will get URL and Description with comma-separated.

So to overcome the above issue you can use the SPFieldUrlValue SharePoint Object model Class like below:

SPFieldUrlValue value = new SPFieldUrlValue(item[“URL”].ToString());
string acturlURL = value.Url;

Change Page Layout using SharePoint server object model

Here we will discuss how we can programmatically change page layout using the SharePoint server object model in a publishing site in SharePoint 2010/2013/2016.

Page layouts and master pages are ECM capabilities of SharePoint sites. And Master pages and page layouts dictate the overall look and feel of your SharePoint site. Master pages contain controls that are shared across multiple page layouts, such as navigation, search, or language-preference for multilingual sites.

Page layouts contain field controls and Web Parts in SharePoint 2010/2013/2016. A page layout is a template that is used in conjunction with a master page to control the look, feel, and content of a page.

Each page layout has an associated content type that determines the kind of content that can be stored on pages based on that page layout. Page layouts are stored in the Master Page Gallery.

public override void WebProvisioned(SPWebEventProperties properties)
{
base.WebProvisioned(properties);
try
{
if (PublishingWeb.IsPublishingWeb(properties.Web))
{
PublishingWeb curPubWeb = PublishingWeb.GetPublishingWeb(properties.Web);

foreach (PageLayout curLayout in curPubWeb.GetAvailablePageLayouts())
{
if (curLayout.Name == “yourpagelayoutname.aspx”)
{
foreach (PublishingPage curPage in curPubWeb.GetPublishingPages())
{
curPage.CheckOut();
curPage.Layout = curLayout;
curPage.Update();
curPage.CheckIn(“”);
}
break;
}
}
}
}
catch (Exception ex)
{
/* Handle exception here */
}
}

Once you run the above code, the new page layout “yourpagelayoutname.aspx” will be applied in SharePoint 2010/2013. This way change page layout programmatically in SharePoint.

Get Default Page Layout in SharePoint server object model

Now, we will discuss how to get the default page layout using the server object model in SharePoint 2010/2013.

using Microsoft.SharePoint.Publishing;

using (SPSite site = new SPSite(“http://SiteURL”))
{
using (SPWeb web = site.OpenWeb())
{
PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);
PageLayout pageLayout = publishingWeb.DefaultPageLayout;
string PageLayoutName = pageLayout.Name;
string PageLayoutURL = pageLayout.ServerRelativeUrl;
}
}

Add user to SharePoint group programmatically using server object model code

Now, we will discuss how to add a user to SharePoint group programmatically using the SharePoint server object model code.

Below is the code which has one method as “AddUsersToSharePointGroup”, this method is taking two parameters, one group name and another on a username.

void AddUsersToSharePointGroup(string groupname, string username)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb thisWeb = site.OpenWeb())
{
thisWeb.AllowUnsafeUpdates = true;
SPUser Name = thisWeb.EnsureUser(username);
thisWeb.Groups[groupname].AddUser(Name);
thisWeb.AllowUnsafeUpdates = false;
}
}
});
}
catch (Exception ex)
{

}
}

The above code will add the user to the SharePoint group programmatically.

Check if list exists or not using TryGetList method in SharePoint

Now, we will discuss how to check if a list exists or not using TryGetList method in SharePoint server object model.

This method belongs to class SPListCollection and it is available in SharePoint 2010, It was not there in MOSS 2007.

Syntax of TryGetList method:
public SPList TryGetList ( string listTitle )

Here listTitle is the title of list and it returns a SPList object.

But if the list is not available then it will not give any exception as it was giving in MOSS 2007, rather it will return NULL value.

Previously we usually retrieve like below:
SPList list = web.Lists[“OurListName”];

But here if the list does not exists then it will throw an exception.

using ( SPSite site = new SPSite ( “http://Top Site URL” ) )
{
using ( SPWeb web = site.RootWeb )
{
SPList list = web.Lists.TryGetList(“Our List Name”);
if ( list != null )
{
// We found the List
}
else
{
//If List does not exists then it will not through any exception, it will return Null
}
}
}

The above method will check if the list exists or not using the SharePoint server object model TryGetList method.

Add user to SharePoint site using server object model code

Now, we will discuss how to add a user to the SharePoint site using SharePoint object model. The code will work in SharePoint 2010/2013/2016 version.

using (SPSite site = new SPSite(“http://Site URL”))
{

using (SPWeb web = site.OpenWeb())
{
web.SiteUsers.Add(“EnjoySharePoint\\TestUser”, “contact@enjoysharepoint.com”,”EnjoySharePoint Test User”, null);
SPUser userAdded = web.SiteUsers[“EnjoySharePoint\\TestUser”];
}
}

This add method will ignore if the user already exists in the site. Similarly, we can also use the EnsureUser method which will check whether the user is already existing or not like below:

using (SPSite site = new SPSite(“http://Site URL”))
{
using (SPWeb web = site.OpenWeb())
{
SPUser userAdded = web.EnsureUser(“EnjoySharePoint\\TestUser”);
}
}

Hope, this SharePoint server object model code will help to add user to a SharePoint site.

Insert Flat Data to SharePoint List using server object model code

Now we will see how to insert flat data into a custom list in SharePoint 2010/2013/2016. Flat data means suppose the data is in notepad like below:

1 IT 10
2 Gov 20

SPWeb web = new SPSite(“http://demo:500/”).OpenWeb();
SPList empList = web.Lists[“Dept”];
SPListItem item;
StreamReader sr = new StreamReader(“C:\\a.txt”);
while (sr.Peek() != -1)
{
string record = sr.ReadLine();
string[] data=record.Split(‘ ‘);
item=empList.Items.Add();
item[“Title”]=data[0];
item[“DeptName”]=data[1];
item[“DeptId”]=data[2];
item.Update();
}

This way you can able to insert flat data to SharePoint custom list using SharePoint server object model code.

Get Profile picture URL from User Information List using SharePoint 2013/2016 server object model

Here we will discuss how we can get a profile picture URL from the User Information List using SharePoint 2013 server object model. User Information List is a hidden list maintains by SharePoint which contains one entry for every user who accessed the site collection or explicit access has been given to any particular user. This list contains basic information like About me, Picture URL, Name, Title, Department, etc.

If SharePoint farm is using User Profile Application, then these User Information List fields will not be editable rather it will redirect to My Site Host. If your SharePoint farm is not using User Profile Application, the user can be able to edit the User Information List fields.

Here in this example, we will try to retrieve the user profile picture URL from the User Information List using the Server object model.

try
{
string LoginName = string.Empty;
string SiteUrl = SPContext.Current.Site.Url;
string Username = SPContext.Current.Web.CurrentUser.LoginName;
SPSite Site = new SPSite(SiteUrl);
string pictureUrl = string.Empty;
using (SPWeb Web = Site.OpenWeb())
{
SPList List = Web.Lists[“User Information List”];
SPQuery Query = new SPQuery();
Query.Query = “<Where><Eq><FieldRef Name = ‘ID’/><Value Type=’Text’>”+Username+”</Value></Eq></Where>”;
SPListItemCollection ItemCollection;
ItemCollection = List.GetItems(Query);
if (ItemCollection.Count > 0)
{
foreach(SPListItem ListItem in ItemCollection)
{
if(ListItem[“Picture”] != null)
{
pictureUrl = ListItem[“Picture”].ToString();
}
}
}
}
}
catch(Exception ex)
{
}

How to know which site definition being used by SharePoint 2013/2016 site using server object model?

Here we will discuss how we can retrieve the site definition used by any SharePoint site using SharePoint 2016 server object model.

Whenever we want to create a site we used to select a template which comes from a site definition. Default site definitions are like STS, MPS, BLOG, etc.

Below is the code which will display all the subsites of a site collection and the corresponding site definition used to create the site.

string s = string.Empty;
using (SPSite ospSite = new SPSite(“http://mypc:29024/sites/SPTraining/”))
{
SPWebCollection webs = ospSite.AllWebs;
foreach (SPWeb web in webs)
{
try
{
s+=”Site URL ” + web.Url.ToString() + ” :: “+ web.WebTemplate.ToString() + “\n”;
}
finally { web.Dispose(); }
}
}
label12.Text = s.ToString();

Once you run the code, it will display details like below:

retrieve site definition being used by SharePoint 2016 site
retrieve site definition being used by SharePoint 2016 site

If you are using SharePoint on-premises versions, then the above SharePoint server object model examples will help to you.

Get all content types in SharePoint server object model

We will discuss how we can retrieve all content types using the SharePoint 2010/2013/2016 object model.

Below is the code that will get all the content types from the content types gallery of the current site.

SPWeb site = SPContext.Current.Web;
foreach (SPContentType ctype in site.ContentTypes)
{
// enumerate content types for current site
}

SPWeb class has a method name as AvailableContentTypes, which will get content types from the current site and all parent sites.

Below is the code that will enumerate all content types from the current site as well as all parent sites.

SPWeb site = SPContext.Current.Web;
foreach (SPContentType ctype in site.AvailableContentTypes)
{
// enumerate content types for current site and parent sites
}

Modify SharePoint All Items view using server object model

Now, we will discuss how to modify SharePoint AllItems view using the SharePoint server object model code.

Views are ways to display a SharePoint list or document library data. The default view for each list or document library is the All Items view. You can check this article to read more about different views in SharePoint.

Below is the code to modify the All Items view of a custom list.

using (SPSite site = new SPSite(“http://SiteURL”))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists[“MyCustomList”];
SPView view = list.Views[“All Items”];
SPViewFieldCollection fieldCol = view.ViewFields;
fieldCol.Add(“FirstName”);
fieldCol.Add(“LastName”);
fieldCol.Add(“Email”);
view.Update();
}
}

After executing this code FirstName, LastName and Email columns will be added to the All Items view.

Get SharePoint hive file path by using SharePoint server object model

We will discuss how we can get the 14/15/16 hive file path in SharePoint 2010/2013/2016 using the server object model.

SPUtility class helps us in finding the 14/15/16 hive folder path.

Below is the command to get the path:

string strPath = SPUtility.GetGenericSetupPath(“”);

This will return like this C:\Program Files\Common Files\Microsoft Shared\web server extensions\15 if you have installed SharePoint in C drive.

Similarly, if you want to retrieve the feature path of the 14/15/16 hive folder then write like below:

string featureFolderPath = SPUtility.GetGenericSetupPath(“template\features”);

Create site page using SharePoint server object model

Here we will see how to create a simple site page using SharePoint server object model. A page that is tracked within the virtual file system of a site is known as a site page.

MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.WriteLine(“<%@ Page %>”);
writer.WriteLine(“<html>”);
writer.WriteLine(“<body>”);|
writer.WriteLine(“<h1>Hello World</h1>”);
writer.WriteLine(“</body>”);
writer.WriteLine(“</html>”);
writer.Flush();
SPWeb site = SPContext.Current.Web;
site.Files.Add(“MySitePage.aspx”,stream, true);

The above code will create a site page name as MySitePage.aspx in SharePoint 2010/2013/2016.

Query Search with SharePoint 2013/2016 server object model

This SharePoint 2013 example explains, how to query search using SharePoint 2013 server object model.

Here we will see how we can do a search using the KeywordQuery class in SharePoint 2013/2016.

First, give reference to the below dll which are located in 15 hive folder under ISAPI folder.

  • Microsoft.Office.Server
  • Microsoft.Office.Server.Search
  • Microsoft.SharePoint
  • Microsoft.SharePoint.Security
using System.Data;
using Microsoft.SharePoint;
using Microsoft.Office.Server.Search.Query;

using (SPSite siteCollection = new SPSite(“http://SiteURL”))
{
KeywordQuery keywordQuery = new KeywordQuery(siteCollection);
keywordQuery.QueryText = “SharePoint 2013”;
SearchExecutor searchExecutor = new SearchExecutor();
ResultTableCollection resultTableCollection = searchExecutor.ExecuteQuery(keywordQuery);
resultTableCollection = resultTableCollection.Filter(“TableType”, KnownTableTypes.RelevantResults);
ResultTable resultTable = resultTableCollection.FirstOrDefault();
DataTable dataTable = resultTable.Table;
}

Here in SharePoint 2013, a new class name as SearchExecutor has been provided. To submit the query we should use the ExecuteQuery() method of the SearchExecutor class.

Remember in SharePoint 2010 search, we were using Execute method which is obsolete now. Though it will work, we should use SearchExecutor class.

Prevent delete of SharePoint list using server object model

We can prevent delete of SharePoint list using the server object model in SharePoint 2013/2016. We will know how to prevent delete of a Sharepoint list in SharePoint. So that user will not able to delete a particular list or document library. This will be the same for both the SharePoint list or document library.

using(SPSite site = new SPSite(“http://SiteURL”))
{
using(SPWeb web = site.OpenWeb())
{
SPList list = web.Lists[“My Custom List”];
list.AllowDeletion = false;
list.Update();
}
}

Hide ribbon programmatically in SharePoint 2010

Here we will see how to hide ribbon programmatically in SharePoint 2010 using SharePoint 2010 server object model code.

Below is the code that will hide the ribbon in SharePoint 2010 programmatically.

SPRibbon ribbon = SPRibbon.GetCurrent(this.Page);
if (ribbon != null)
{
ribbon.CommandUIVisible = false;
}

Similarly, if you want to hide the ribbon by using SPSecurityTrimmedControl then you can do like below:

<Sharepoint:SPSecurityTrimmedControl runat=”server” Permissions=”AddAndCustomizePages”>
Ribbon will be inside the control
</SharePoint:SPSecurityTrimmedControl>

Retrieve all content types from site using SharePoint Server Object Model

A content type is first introduced in WSS 3.0. A content type defines the underlying schema for either an item in a list or a document in a document library. But content types are defined independently outside the scope of any list or document library.

Also, you can define a content type as A content type represents a group of informational items in your organization that share common properties. Properties may be like name, description, a grouping category, etc.

Microsoft provides different out of box content types for SharePoint as well as also developers can create custom content types.

While creating a custom content type, it is very much necessary to choose a parent content type. You can configure a single list to support multiple content types.

Different content types like Document content type, list content type, Folder Content Types etc, Page Layout Content Types, Publishing Content Types, etc.

Below is an example to get all the available content types in a SharePoint site using SharePoint server object model.

public void GetContentTypes()
{
string contentTypeNames = string.Empty;

using (SPSite siteCollection = new SPSite(“http://mypc:29024/sites/SPTraining/”))
{
using (SPWeb site = siteCollection.OpenWeb())
{
foreach (SPContentType contentType in site.AvailableContentTypes)
{
contentTypeNames += contentType.Name;
}
}
}
}

The above code will work in SharePoint 2013/2016/2019.

Add folder to document library programmatically in SharePoint 2010/2013/2016

Now we will see how to add a folder to the document library programmatically using the SharePoint 2010 object model. Here we will add a subfolder to the “Shared Documents” document library.

Below is the code to create a subfolder inside the Shared Documents document library.

using (SPSite site = new SPSite(“http://SiteURL”))
{
using (SPWeb web = site.OpenWeb())
{
SPList library = web.Lists[“Shared Documents”];
SPFolder parentFolder = library.RootFolder;
SPFolder child = parentFolder.SubFolders.Add(“My New Sub Folder”);
parentFolder.Update();
}
}

Delete folder programmatically in SharePoint using server object model

This SharePoint server object model example, we will discuss how to delete a folder programmatically using the SharePoint 2010/2013/2016 using the server object model code.

Below is the SharePoint server object model code to delete folder programmatically in SharePoint 2010/2013/2016.

using (SPSite site = new SPSite("http://SiteURL"))
{
using (SPWeb web = site.OpenWeb())
{
SPFolderCollection folders = web.Folders["MyList"].SubFolders;
foreach (SPFolder folder in folders)
{
if (folder.Name == "MyFolderToDelete")
{
web.Folders[“MyList”].SubFolders.Delete(folder.Url);
}
}
}
}

Get or Set SharePoint lookup field value using SharePoint object model

Now in this SharePoint server object model example, we will see how to set or retrieve SharePoint lookup field value in List in SharePoint 2010/2013/2016 using the object model.

Here we have a SharePoint list name as Users and Country. Users List has a lookup column name as CountryName and is mapped to the Country List.

If you will directly (like a list) retrieve the lookup field value then it will come in the below format: (ID);#(VALUE).

Example: 10#India.

But our requirement is to retrieve only India.

Get lookup field value using SharePoint object model

Below is the code to Get the Lookup field in SharePoint using the server object model.

SPList list = web.Lists[“Users”];
SPListItem item = list.Items[0];
SPFieldLookupValue group = new SPFieldLookupValue(item[“CountryName”].ToString());
string countryName = group.LookupValue;

The above code will give us India.

Set lookup field value using SharePoint object model

Below is the code to Set the Lookup field in SharePoint using the server object model:

SPList list = web.Lists[“Users”];
SPListItem newItem = list.Items.Add();
newItem[“UserName”] = “Bijay”;
SPFieldLookupValue newLookupValue = new SPFieldLookupValue(10, “India”);
newItem[“Country”] = newLookupValue;
newItem.Update();

The above code will add one new item to the list with username as Bijay and Country as India.

Get SharePoint column display name and internal name using SharePoint server object model

This SharePoint server object model example explains, how to get display and internal name for columns or fields in SharePoint using SharePoint server object model

Below is the SharePoint server object model code to Get SharePoint column display name and internal name using the SharePoint server object model.

using (SPSite site = new SPSite("http://SiteURL"))
{
using (SPWeb web = site.OpenWeb())
{
SPList library = web.Lists["Announcements"];
string title = string.Empty;
string internalName = = string.Empty;
foreach (SPField field in list.Fields)
{
title += field.Title + " ";
internalName += field.InternalName + " ";
}
}
}

Programmatically Create or Delete a list in multiple sites using SharePoint server object model code

This SharePoint server object model example, we will see how to Programmatically Create or Delete a list in multiple sites in SharePoint using SharePoint object model.

Create a list in Multiple sites in SharePoint

Below is the SharePoint server object model code to create a list in multiple sites in SharePoint.

string listTitle = “MyCustomList”;
string listDescription = “My Custom List Description”;
SPSite mySite = SPContext.Current.Site;
SPWebCollection allWebs = mySite.AllWebs;
foreach (SPWeb web in allWebs)
{
SPListCollection allLists = web.Lists;
allLists.Add(listTitle,listDescription, SPListTemplateType.GenericList);
}

This will create a generic list on every site in SharePoint.

Delete a list in Multiple sites in SharePoint

Below is the SharePoint server object model in a list in multiple sites in SharePoint.

SPSite mySite = SPContext.Current.Site;
SPWebCollection allWebs = mySite.AllWebs;
foreach (SPWeb web in allWebs)
{
SPListCollection allLists = web.Lists;
for (int i=0; i<allLists.Count; i++)
{
SPList list = allLists[i];
if (list.Title == “MyCustomList”)
{
Guid listGuid = list.ID;
allLists.Delete(listGuid);
}
}
}

Here it will search for all web sites and inside all web sites it will visit all lists and it will delete the particular list whose title is MyCustonList.

Delete a file from document library using SharePoint server object model

In this SharePoint server object model code, we will discuss how to delete a file from document library using SharePoint 2010/2013 object model. We will check how we can delete a document from the Shared Documents library.

Delete File using SharePoint server object model

using (SPSite site = new SPSite(“http://SIteURL”))
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPFolder folder = web.Folders[web.Url + “/Shared Documents/”];
folder.Files[“MyDocument.docx”].Delete();
folder.Update();
}
}

The above code will delete MyDocument.docx from the Shared Documents in SharePoint.

Recycle File using SharePoint server object model

But if you want to recycle the item in SharePoint then you can use the below code.

using (SPSite site = new SPSite(“http://SIteURL”))
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPFolder folder = web.Folders[web.Url + “/Shared Documents/”];
folder.Files[“MyDocument.docx”].Recycle();
folder.Update();
}
}

Programmatically create or delete subsite in SharePoint using SharePoint server object model

In this SharePoint server object model example, we will discuss how to create or delete a subsite under a site using SharePoint server object model.

Create a site using SharePoint server object model

Below is the full code to create a site:

SPWeb mySite = SPContext.Current.Web;
SPWebCollection subSites = mySite.Webs;
string currentTemplate = mySite.WebTemplate;
string siteUrl = “http://SiteURL”;
string siteTitle = “Title of the site”;
string siteDescription = “Description of the site”;
subSites.Add(siteUrl, siteTitle, siteDescription, 1033, currentTemplate, true, false);

Here mySite.WebTemplate returns the name of the current site definition.

Delete a site using SharePoint server object model

Below is the full code to Delete a site in SharePoint:

string deleteSite = “http://SiteURL”;
SPSite mySite = SPContext.Current.Site;
SPWebCollection sites = mySite.AllWebs;
sites.Delete(deleteSite);

Make the content type as sealed in SharePoint using server object model

This SharePoint server object model example, we will discuss how we can make a content type as sealed and unsealed using SharePoint server object model.

Once you make a content type as the sealed user will not able to modify that content type. To make a content type as sealed we need to set true to the sealed property of the content type.

You must be an administrator for the site collection to make a seal content type.

Make the content type as sealed in SharePoint using server object model

Below is the code to make a content type as sealed:

using (SPSite currentSiteCollection = new SPSite(“URL of the site collection”))
{
SPContentType contentType = currentSiteCollection.RootWeb.ContentType[“ContentTypeName”];
contentType.Sealed = true;
contentType.Update();
}

UnSealed Content type in SharePoint server object model code

Below is the code to unsealed a content type:

using (SPSite currentSiteCollection = new SPSite(“URL of the site collection”))
{
SPContentType contentType = currentSiteCollection.RootWeb.ContentTypes[“ContentTypeName”];
contentType.Sealed = false;
contentType.Update();
}

Associate workflow to a list programmatically in SharePoint

This SharePoint client object model example, we will discuss, how to associate a workflow to a list programmatically in SharePoint using server object model code.

using(SPSite site = new SPSite(“Site URL”))
{
SPWeb web = site.OpenWeb();
SPList list = web.Lists[“List Name”];
SPWorkflowTemplate workflowTemplate = web.WorkflowTemplates.GetTemplateByName
(“NameOfWorkflowTemplate”, System.Globalization.CultureInfo.CurrentCulture);
SPList workflowTaskList = web.Lists[“Tasks”];
SPList workflowHistoryList = web.Lists[“Workflow History”];
SPWorkflowAssociation wfAssociation = SPWorkflowAssociation.CreateListAssociation
(workflowTemplate, “Give Workflow Name”, workflowTaskList, workflowHistoryList);
wfAssociation.AutoStartChange = false;
wfAssociation.AutoStartCreate = false;
wfAssociation.AllowManual = true;
web.AllowUnsafeUpdates = true;
list.AddWorkflowAssociation(wfAssociation);
list.Update();
web.AllowUnsafeUpdates = false;
}

Programmatically Check appSettings tag inside web.config file in SharePoint

This SharePoint server object example, we will discuss, how we can check programmatically appSettings tag inside a web.config file in SharePoint 2010/2013/2016.

We can check whether the tag is presented in a SharePoint site or not.

Below is the full code to check appSettings tag inside web.config file in SharePoint.

using (SPSite site = new SPSite(“http://SiteURL”))
{
Configuration config = WebConfigurationManager.OpenWebConfiguration(“/”, site.WebApplication.Name);
AppSettingsSection appSettings = config.AppSettings;
bool isAppSettingsTagPresent = appSettings.ElementInformation.IsPresent;
}

Programmatically get SharePoint List Url using SharePoint Server Object Model

This SharePoint server object model example explains, how to programmatically get SharePoint List Url in C#.Net using SharePoint object model.

We can pass the GUID of the List and will get the list URL.

Below is the full code to Programmatically get SharePoint List Url using SharePoint Server Object Model.

SPSite Site = SPContext.Current.Site;
SPWeb web = Site.OpenWeb();
Guid listid = new Guid(“{xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}”);
web.AllowUnsafeUpdates = true;
SPList List = web.Lists[listid];
string url = SPContext.Current.Site.Url + “/” + List.RootFolder.Url;
web.AllUnSafeUpdates = false;
web.Dispose();

Create SharePoint Document Library programmatically using C#.Net

This SharePoint server object model example, we will discuss how to create a SharePoint Document Library programmatically using C#.Net.

We will use the SharePoint 2010/2013/2016 server object model to create the document library.

Below is the full code:

SPSite site = SPContext.Current.Site as SPSite;
SPWeb web = site.RootWeb as SPWeb;
try
{
Guid customListID = web.Lists.Add(“Document Lib Name”, “Document Lib Description”, SPListTemplateType.DocumentLibrary);
web.Update();
}

Another Method to Create SharePoint Document Library programmatically

SPSite site = SPContext.Current.Site;
SPWeb web = site.OpenWeb() as SPWeb;
web.AllowUnsafeUpdates = true;
Guid customListID = web.Lists.Add(“Document Lib Name”, “Document Lib Description”, SPListTemplateType.DocumentLibrary);
SPList listdoc = web.Lists[customListID];
listdoc.OnQuickLaunch = true; // The document library will appear in Quick Launch bar.
listdoc.Update();
web.AllowUnsafeUpdates = false;

Download documents from Document Library using SharePoint Server Object Model

In this SharePoint server object model example, we will discuss, how we can download documents from SharePoint 2013 document library using a server-side object model.

Below is the full code:

using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MySP2013
{
class DownloadDocumentFromDocumentLibrary
{
String siteURL = “http://SiteURL:12345/sites/Employee”;
//String listName = “Employee”;
string folderpath = @”C:\Download”;

public void DownloadDocumentFromDocLibrary()
{
string downloadItemLocation = string.Empty;
using (SPSite site = new SPSite(siteURL)) // Site Collection
{
using (SPWeb web = site.OpenWeb()) // Site
{
SPList list = web.Lists[“EmployeeDocuments”];
foreach (SPFile file in list.RootFolder.Files)
{
DownloadFileUsingFileStream(file, folderpath);
}
}
}
}

private void DownloadFileUsingFileStream(SPFile file, string path)
{
byte[] filecontent = file.OpenBinary();
FileStream fs = new FileStream(path +”\\”+ file.Name, FileMode.CreateNew);
using (fs)
{
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(filecontent, 0, filecontent.Length);
bw.Close();
}
}
}
}

Here we saw how we check how to create a list, add a user to SharePoint group, check if a list exists or not in SharePoint, change the page layout and master page, delete items to recycle bin, get URL value using SharePoint server object model code.

Create custom content type using SharePoint server object model

This example explains, how to create a custom content type using SharePoint server object model.

SPWeb site = SPContext.Current.Site.RootWeb;
string contenttypeName = "My Custom Content Type";
SPContentType contenttypeParent = site.ContentTypes["Item"];
SPContentType contenttype = new SPContentType(contenttypeParent, site.ContentTypes, contenttypeName);
contenttype.Description = "Our First Custom Content Type";
contenttype.Group = "Custom Content Type";
site.ContentTypes.Add(contenttype);

The above code will create a custom content type which inherits from Item content type in SharePoint.

Get content database for web application in SharePoint programmatically using server object model

This SharePoint PowerShell tutorial, we will discuss, how to get a content database for web application using PowerShell in SharePoint 2013/2016.

Here, I have created a windows application and added the Microsoft.SharePoint.dll in the solution. I have created the windows application inside the SharePoint server (Where SharePoint 2016 is installed) using Visual Studio 2017.

Below is the full code to get the content database name:

string s = string.Empty;

SPFarm farm = SPFarm.Local;
SPWebService service = farm.Services.GetValue<SPWebService>("");
foreach (SPWebApplication webapp in service.WebApplications)
{
foreach (SPSite site in webapp.Sites)
{
s += "Site Collection URL: " + site.Url + " Content Database Name: " + site.ContentDatabase.Name + "\n";
}
}

lblResult.Text = s;
get content database for web application sharepoint

Once you run the code, it will display all SharePoint site collection URLs and corresponding content database names like below:

This SharePoint tutorial, we saw how to display all the content databases for web application using SharePoint 2013/2016 server object model code.

Retrieve all site collections under particular content databases using SharePoint server object model

This example, we will see how to retrieve all site collections under a particular content database programmatically using the SharePoint server object model code. The code will work for SharePoint 2013 or SharePoint 2016.

Below is the code which will retrieve all site collections under particular content databases in SharePoint 2013/2016.

The code first retrieves what is the content database name the site collection is using.

string s = string.Empty;
SPSite oSiteCollection = new SPSite("http://mypc:29024/sites/HydTraining/");

SPSiteCollection sc = oSiteCollection.ContentDatabase.Sites;

foreach (SPSite site in sc)

{
s += "Site Collection URL: " + site.Url + "\n";

}

lblResult.Text = s.ToString();

This will display all the SharePoint site collection URLs from a particular content database in SharePoint.

Retrieve all site collections under particular content databases sharepoint

Get all web applications from SharePoint server farm programmatically

This SharePoint server example we will discuss how to get all web applications from SharePoint 2013/2016 server farm programmatically using SharePoint server object model code.

I have SharePoint 2016 installed on the same machine, so I can add Microsoft.SharePoint.dll into the windows application and can write server-side code inside it.

Below is the full code to retrieve all web applications from the local SharePoint server farm.

string s = string.Empty;
SPFarm farm = SPFarm.Local;
SPWebService service = farm.Services.GetValue<SPWebService>("");
foreach (SPWebApplication webapp in service.WebApplications)
{
s += "Web App Name: " + webapp.Name + " URL:"+ webapp.GetResponseUri(SPUrlZone.Default) +"\n";
}
lblResult.Text = s;

Once you will run the code then the web applications name and URL will be populated like below:

Get all web applications from SharePoint server farm programmatically

Get all workflows from all site collections using server object model in SharePoint 2013/2016

In this post, we will discuss how to get all the workflows from site collection using the server object model in SharePoint 2013/2016.

Here we have written a console application which gave us the workflows presented in all the site collections.

Below is the code to get all workflows from all site collections using server object model in SharePoint 2013/2016.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Workflow;
using System.IO;
namespace GetAllWFs
{
class Program
{
static void Main(string[] args)
{
string site;
Console.WriteLine("Enter the Web Application URL:");
site = Console.ReadLine();

string date = string.Format("{0:dd-MM-yyyy}", DateTime.Now);
string path = "WorkFlowList_" + date + ".xls";
Directory.SetCurrentDirectory("E:\\Bijay");
StreamWriter sw = File.CreateText(path);
SPSite tmpRoot = new SPSite(site);
SPSiteCollection tmpRootColl = tmpRoot.WebApplication.Sites;
int count = 0;
foreach (SPSite tmpSite in tmpRootColl)
{

foreach (SPWeb tmpWeb in tmpSite.AllWebs)
{
foreach (SPList tmpList in tmpWeb.Lists)
{
SPWorkflowManager manager = tmpSite.WorkflowManager;
SPWorkflowAssociationCollection associationColl = tmpList.WorkflowAssociations;
foreach (SPWorkflowAssociation association in associationColl)
{
sw.AutoFlush = true;
sw.Write(association.Name.ToString() + "\t");
sw.Write("\n");
count++;
}
}
}

}
Console.WriteLine(count + " work flows exported to excel :E:\\Bijay\\" + path);
Console.Read();
}
}
}

It will put in an excel file in the specified location.

You may also like a few more SharePoint Server Object Model tutorials:

Hope, you like this SharePoint server object model examples.

free sharepoint training

SharePoint Online FREE Training

JOIN a FREE SharePoint Video Course (3 Part Video Series)

envelope
envelope

Bijay Kumar

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site SharePointSky.com

  • […] A- Most of the SharePoint 2010 farm solutions will work in SharePoint 2013. But it is always good to redevelop the solutions using visual studio. Read 15+ SharePoint server object model examples […]

  • >