EnjoySharePoint YouTube Channel

25+ SharePoint server object model examples

SharePoint server object model examples

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

Get Office 365 Enterprise E3 Or Business Premium Subscription & Try out all the features

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 SharePoint server object model, we will disucss how to add user to SharePoint group using programmatically using server object model code.

SharePoint 2016 Tutorial Contents

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 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 variou 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 SharePoint server object model. The code will work in SharePoint 2010/2013/2016.

To work with 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 collection of child sites of the current site based on the user permission. For this we can use SPWeb.GetSubwebsForCurrentUser Method which is presented in SharePoint server object model.

It will return all the sub site 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 completly. But If you delete an item from the browser then it will go to Recycle Bin.

Recycle() method of SPListItem will help us for 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 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 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 returned 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 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 user to SharePoint group programmatically using 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 an 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 exists 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 profile picture url from 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 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 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 sub sites of a site collection and the corresponding site defintion 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 helpful 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 using SharePoint server object model code.

Views are ways to display 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 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 feture 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();
}
}

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

Check out Best Alternative to InfoPath -> Try Now
You May Also like the Following SharePoint Tutorials:

About 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

View all posts by Bijay Kumar →