SharePoint Server Object Model Tutorial

This is a complete tutorial on the SharePoint server object model, we will also discuss various SharePoint server-side object model examples, and also we will see the SharePoint server-side object model vs client-side object model.

SharePoint server side object model

We can use the SharePoint server object model to work with SharePoint objects. In the case of the SharePoint server object model, the code will run in the server where SharePoint is installed. So to run the SharePoint 2019 server-side object model code, SharePoint has to be installed on the server.

To work with the SharePoint server object model, we need to refer to the Microsoft.SharePoint.dll that is presented in the C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI directory.

We mainly develop farm solutions using SharePoint server object model code and we can deploy the farm solutions using PowerShell to SharePoint production environments.

SharePoint server object model hierarchy

Below is the SharePoint server object model hierarchy.

sharepoint server object model
sharepoint server object model

There are various classes that we can use.

sharepoint server object model hierarchy
sharepoint server object model hierarchy

Below is the SharePoint classes and namespaces that we can use.

SharePoint ComponentsServer Object Model ClassNamespace
FarmSPFarmMicrosoft.SharePoint.Administration
ServerSPServerMicrosoft.SharePoint.Administration
Web ApplicationSPWebApplicationMicrosoft.SharePoint.Administration
Content DatabaseSPContentDatabaseMicrosoft.SharePoint.Administration
Site CollectionSPSiteMicrosoft.SharePoint
SiteSPWebMicrosoft.SharePoint
List/LibrarySPListMicrosoft.SharePoint
ItemSPItemMicrosoft.SharePoint
sharepoint server object model classes

SharePoint server side object model vs client side object model

Let us see, the difference between the SharePoint server side object model vs client side object model. I will explain the SharePoint client side and server side code. What are various client-side techniques are available in SharePoint 2013/2016/Online? Learn the Difference between client side object model and server side object model in SharePoint 2013/2016/Online.

In the SharePoint on-premise environment, you have the option to use both SharePoint server-side object model code as well as SharePoint client-side object model code. But in Office 365 SharePoint Online, you can only use SharePoint client-side object model code.

SharePoint Server Side Object Model Code

Server-side is only supported in on-premises implementations of SharePoint. Server Object Model core assembly is Microsoft.SharePoint.dll which is installed in the Global Assembly Cache.

You can use Visual Studio 2019/2017/2015 for SharePoint server side development using SharePoint server object model code.

The Server Object Model will be executed in the server side & it provides a rich set of classes in representing & manipulating SharePoint objects. Must be deployed on same farm Server-side object model.

You cannot use the Server Object Model to connect remotely to a SharePoint Server. Like you cannot use the SharePoint server object model code in Office 365 SharePoint Online because Microsoft does not allow us to execute any code on the Server for SharePoint Online.

SharePoint Client Side Object Model Code

.Net Managed Object Model

CSOM offers remote APIs to connect to the SharePoint environment and perform the operations. It allows access to SharePoint data and features from remote clients. It is introduced in SharePoint 2010.

The two core assemblies for the .NET Manage Implementation are

  • Microsoft.SharePoint.Client.dll
  • Microsoft.SharePoint.Client.Runtime.dll

JavaScript Object Model

JavaScript Object Model (JSOM) supports performing operations remotely against SharePoint using JavaScript.

The Three JavaScript libraries are SP.js, Sp.Runtime.js, and SP.Core.js.

Rest API

The REST Services in SharePoint offer nearly the same functionality as JSOM. The main advantage of using REST is that you don’t have to add references to any SharePoint libraries or client assemblies.

Instead, you make HTTP requests to the appropriate endpoints to retrieve or update SharePoint entities, such as webs, lists, and list items.

Check out SharePoint Rest API – Complete Useful Tutorial.

Create a windows application to use SharePoint server object model code

Let us see how to create a windows application to use the SharePoint server object model code.

To create a windows application follow below steps:

Note: We need to create the windows application in the SharePoint server.

Open Visual Studio and then click on File -> New -> Project.

Then from the templates -> Window and then choose Windows Forms Application.

Then we need to add reference to the Microsoft.SharePoint.dll.

Then right click on the References and then click on Add Reference… like below:

sharepoint 2013 server side object model
sharepoint 2013 server side object model

Then go to the below path: C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI. Then add Microsoft.SharePoint.dll from the folder.

Then you can write the below code to get all site collections under a SharePoint web application.

string s = string.Empty;
            SPWebApplication web = SPWebApplication.Lookup(new Uri("http://mypc:4120"));
            foreach (SPSite site in web.Sites)
            {
                s += "Site URL: " + site.Url + " Site RootWeb Title " + site.RootWeb.Title + " Rootweb URL " + site.RootWeb.Url + "\n";

            }
            label2.Text = s;

This is how we can use the SharePoint server object model code.

SharePoint server side object model examples

Let us check out a few SharePoint server side object model examples. These are examples of SharePoint 2019 server side object model, SharePoint 2016 server object model, and SharePoint 2013 server object model.

1. Create document library in SharePoint programmatically

Let us see, how to create a Document Library in SharePoint 2016/2013 programmatically using SharePoint 2016 server object model.

Here, I have created a visual web part in SharePoint and add the code.

Follow the step by step tutorial to create a document library in SharePoint 2016/2013 programmatically using SharePoint 2016 server object model.

Now we will have to design the form where users can enter the details like Document library name and description etc to create the document library/ In the visual web part, we can design the form in the .ascx file. Here we will add the below controls.

Below are the controls we will use to develop the form.

  • TextBox: This control helps to create a text box in the input design form.
  • Button: This control helps to create a button. So that when a user click on button, the document library will create in the SharePoint 2016 Site.
  • Label: If some error will come after deploying the code, then this control helps to show the error message.
<table>
    <tr>
        <td>Document Library Name:</td>
        <td><asp:TextBox ID="txtDocumentLibraryName" runat="server"></asp:TextBox></td>
    </tr>
    <tr>
        <td>Description:</td>
        <td><asp:TextBox ID="txtDescription" runat="server" TextMode="MultiLine"></asp:TextBox></td>
    </tr>
    <tr>
        <td></td>
        <td><asp:Button ID="btnCreateDocumentLibrary" runat="server" Text="Create" Width="90px" OnClick="BtnCreateDocumentLibrary_Click" /></td>
    </tr>
    <tr>
        <td><asp:Label ID="lblMessage" runat="server" Text=""></asp:Label></td>
    </tr>
</table>

The input design form looks like below:

create a document library programmatically in sharepoint 2016
create a document library programmatically in sharepoint 2016

Code to create document library in SharePoint programmatically

Below SharePoint 2016 server object model code to create SharePoint 2016 Document Library programmatically.

using Microsoft.SharePoint;
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace Document_Library_Creation.Document_Library_Creation
{
    public partial class Document_Library_CreationUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                {
            }
        }

        protected void BtnCreateDocumentLibrary_Click(object sender, EventArgs e)
        {
            CreateDocumentLibrary();
        }
        public void CreateDocumentLibrary()
        {
            try
            {
                SPSite siteCollection = SPContext.Current.Site;
                SPWeb web = SPContext.Current.Web;
                web.AllowUnsafeUpdates = true;
                SPList spList = web.Lists.TryGetList(txtDocumentLibraryName.Text.Trim());
                if (spList == null)
                {
                    web.Lists.Add(txtDocumentLibraryName.Text.Trim(), txtDescription.Text.Trim(), SPListTemplateType.DocumentLibrary);
                    //SPList newList = web.Lists["TestList"];
                    web.AllowUnsafeUpdates = false;
                    CreateColumn(web);
                    lblMessage.Text = "Your document library created successfully";
                }
                else
                {
                    lblMessage.Text = "This document library already exists";
                }

            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message;
            }
        }
    }
}

Once you will add your custom web part, you can see the form like below screenshot. Once you will fill all the field value and then click on the “Create” button, then the document library will create in SharePoint 2016.

programmatically create sharepoint document library c#
programmatically create sharepoint document library c#

While the document library will create successfully in SharePoint 2016, then there will appear a status as “Your document library created successfully” (because of Label control).

sharepoint server side object model examples
create a SharePoint document library programmatically using C#

Once you will go to SharePoint 2016 “Site Contents” page, the document library which you have created recently will be available. Once you will open the document library, it will show you like below screenshot.

create SharePoint document library programmatically using C#
create SharePoint document library programmatically using C#

This is how to add a document library in SharePoint using server object model. Here, we saw, how to create a document library programmatically c#.net using SharePoint 2016/2013 server object model code.

2. Add columns to SharePoint document library using server object model

In this below example, we will see how can we add columns (Choice columns and Single line of text column) to the SharePoint 2016 document library. We are adding below 3 columns programmatically to SharePoint 2016 document library.

  • DocumentLocation (Single line of text): This column is a Single line of text.
  • DocumentLanguage (Choice column): This column is a Choice field. This language field column has some choice values as:
    • English
    • Hindi
    • Kannad
  • DocumentDepartment (Choice Column): This column is also a Choice field. This department field column has some choice values as:
    • IT
    • HR
    • Finance

Below SharePoint 2016 server object model Code, you can use for creating column ((Single line of text and Choice column) in SharePoint 2016 Document Library programmatically.

string libraryDocumentLocationColumnName = "DocumentLocation";
        string libraryLanguageColumnName = "DocumentLanguage";
        string languageChoiceColumn1 = "English";
        string languageChoiceColumn2 = "Hindi";
        string languageChoiceColumn3 = "Kannad";
        string libraryDepartmentColumnName = "DocumentDepartment";
        string departmentChoiceColumn1 = "IT";
        string departmentChoiceColumn2 = "HR";
        string departmentChoiceColumn3 = "Finance";

public void CreateColumn(SPWeb web)
        {
            try
            {
                web.AllowUnsafeUpdates = true;
                SPList spList = web.Lists.TryGetList

(txtDocumentLibraryName.Text.Trim());
                spList.Fields.Add

(libraryDocumentLocationColumnName, SPFieldType.Text, false);
                spList.Fields.Add(libraryLanguageColumnName, 

SPFieldType.Choice, false);
                spList.Fields.Add(libraryDepartmentColumnName, SPFieldType.Choice, false);
                
                /* get the newly added choice field instance */
                SPFieldChoice chFldDocLanguage = 

(SPFieldChoice)spList.Fields[libraryLanguageColumnName];
                
                /* set field format type i.e. radio / dropdown */
                chFldDocLanguage.EditFormat = 

SPChoiceFormatType.Dropdown;

                /* set the choice strings and update the field */
                chFldDocLanguage.Choices.Add

(languageChoiceColumn1);
                chFldDocLanguage.Choices.Add

(languageChoiceColumn2);
                chFldDocLanguage.Choices.Add

(languageChoiceColumn3);
                chFldDocLanguage.Update();
          
                /* get the newly added choice field instance */
                SPFieldChoice chFldDocDepartment = 

(SPFieldChoice)spList.Fields[libraryDepartmentColumnName];

                /* set field format type i.e. radio / dropdown */
                chFldDocDepartment.EditFormat = 

SPChoiceFormatType.Dropdown;

                /* set the choice strings and update the field */
                chFldDocDepartment.Choices.Add

(departmentChoiceColumn1);
                chFldDocDepartment.Choices.Add

(departmentChoiceColumn2);
                chFldDocDepartment.Choices.Add

(departmentChoiceColumn3);
                chFldDocDepartment.Update();
                spList.Update();
                web.AllowUnsafeUpdates = false;
            }
            catch (Exception exc)
            {
                lblMessage.Text = exc.Message;
            } 
        }

Now deploy the code and go to that existing SharePoint 2016 document library, then you can see that there will be available one single line of the text column and other choice columns as shown below.

sharepoint 2013 server side object model examples
create column in sharepoint document library programmatically c#

Once you will go to the “Columns” section of “Library Settings” of that SharePoint 2016 Document Library, then you can see all the Column name with their “Type“.

sharepoint 2019 server side object model
create column in sharepoint document library programmatically

While you will click on the Choice Column name, then you can see all the choice field values in “Type each choice on a separate line” option as like below screenshot.

sharepoint server object model
create column in sharepoint 2016 document library programmatically

Also, we saw, how to create and add different types of columns in SharePoint 2016/2013 Document Library. How to give choice field values programmatically using SharePoint 2016 server object model.

3. How to get choices from choice field programmatically in SharePoint

Let us see, how to get choices from choice field programmatically in SharePoint using the SharePoint server object model.

The below code represents that, there is a SharePoint Document Library in a SharePoint Site. In that library, there are two choice columns are presented as: “Language” and “Department“.

In both the choice field column, it has some choice options values. So by using this below C# Code (SharePoint server object model), we can get choices from choice field programmatically in SharePoint.

using Microsoft.SharePoint;
using System;
using System.IO;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace TSInfo_Intranet.File_Upload
{
    public partial class File_UploadUserControl : UserControl
    {
        string siteURL = "";
        string listTitle = "Company Document";
        string libraryLanguageColumnName = "Language";
        string libraryDepartmentColumnName = "Department";
        SPSite siteCollection = SPContext.Current.Site;
        SPWeb web = SPContext.Current.Web;
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetChoiceLanguageColumn();
                GetChoiceDepartmentColumn();
            }
        }
        
        public void GetChoiceLanguageColumn()
        {
            try
            {
                SPList spList = web.Lists.TryGetList(listTitle);
                SPFieldChoice chFldDocLanguage = (SPFieldChoice)spList.Fields[libraryLanguageColumnName];
                if (chFldDocLanguage != null)
                {
                    for (int i = 0; i < chFldDocLanguage.Choices.Count; i++)
                    {                       ddlLanguage.Items.Add(chFldDocLanguage.Choices[i].ToString());
                    }
                }
                else
                {
                    lblMessage.Text="Something went wrong";
                }
            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message;
            }
        }
        public void GetChoiceDepartmentColumn()
        {
            try
            {
                SPList spList = web.Lists.TryGetList(listTitle);
                SPFieldChoice chFldDocDepartment = (SPFieldChoice)spList.Fields[libraryDepartmentColumnName];
                if(chFldDocDepartment !=null)
                {
                    for (int i = 0; i < chFldDocDepartment.Choices.Count; i++)
                    {
                        ddlDepartment.Items.Add(chFldDocDepartment.Choices[i].ToString());
                    }
                }
                else
                {
                    lblMessage.Text = "Something went wrong. Kindly contact with your administrator.";
                }
            }
            catch (Exception exc)
            {
                lblMessage.Text=exc.Message;
            }
        }
    }
}

This is how to get choices from the choice field programmatically in SharePoint using SharePoint 2016 server object model.

4. Add columns to list view programmatically using SharePoint 2019 server object model

Let us see, how to add columns to view programmatically in SharePoint 2019/2016/2013. We will see how to add columns to the SharePoint list view programmatically using SharePoint 2016 server object model in SharePoint 2013/2016 list or document library in Visual Studio.

In this below example, I have a SharePoint 2016 Document Library. This SharePoint 2016 Document Library has two different data types of columns. Those columns are:

  • DocumentLocation (Single line of text):
    This column is a Single line of text.
  • DocumentLanguage (Choice): This column is a Choice field. This language field column has some choice values as:
    • English
    • Hindi
    • Kannad
  • DocumentDepartment (Choice):
    This column is also a Choice field. This department field column has some choice values as: 
    • IT
    • HR
    • Finance

By default, these columns will not appear in the list view in the SharePoint 2016 Document Library or list, So we have to display programmatically using Server object model code (C#) in Visual Studio 2017/2019.

Below SharePoint 2016 server object model code to display a SharePoint 2016 List/Library Column in View programmatically.

Here I have a button and on the button click, I am adding the columns to the SharePoint document library or list.

        public void AddListColumnsToView()
        {
            try
            {
                                
	SPWeb web = SPContext.Current.Web;

                web.AllowUnsafeUpdates = true;
                SPList spList = web.Lists.TryGetList("My List Name");

                /* display a column in view */
                SPView defaultView = spList.DefaultView;
                defaultView.ViewFields.Add("DocumentLocation");
                defaultView.ViewFields.Add("DocumentLanguage");
                defaultView.ViewFields.Add("DocumentDepartment");
                defaultView.Update();

                spList.Update();
                web.AllowUnsafeUpdates = false;
            }
            catch (Exception exc)
            {                
            }            
        }

In the below screenshot, you can see that there will be available one single line of the text column and other choice columns as a view.

sharepoint 2016 server object model
Display column as view programmatically in SharePoint

This is how to add a SharePoint List/Library column in the list view programmatically c#.net using SharePoint 2016/2013 server object model code.

5. Create Site Columns programmatically using SharePoint Server Object Model

Now, let us see, ow to create different types of Site columns (Single line of text, Multiline of text, and Choice) using Server object model code in SharePoint 2016/2013 using Visual Studio 2017/2019.

Here I have taken 3 buttons (Single line/Multiline/Choice) and on click on each button, a site column will be created in the SharePoint 2016 site.

In the visual web part, we can design the form in the .ascx file. Here we will add the below controls:

  • Button: This control helps to create a text box in the input design form. Hence we have to create three different data types of Site columns (Single line of text, Multiline of text and choice), So take three buttons with different IDs of each one.
  • Label: If some error will come after deploying the code, then this control helps to show the error message.
<table>
    <tr>
        <td>Create SiteColumn (Single line of text):</td>
        <td><asp:Button ID="btnSingleLineSiteColumn" runat="server" Text="Create SiteColumn (Single line of text)" OnClick="btnSingleLineSiteColumn_Click" /></td>
    </tr>
    <tr>
        <td>Create SiteColumn (Multiline of text):</td>
        <td><asp:Button ID="btnMultiLineSiteColumn" runat="server" Text="Create SiteColumn (Multiline of text)" OnClick="btnMultiLineSiteColumn_Click" /></td>
    </tr>
    <tr>
        <td>Create SiteColumn (Choice):</td>
        <td><asp:Button ID="Button1" runat="server" Text="Create Choice Column" OnClick="Button1_Click" /></td>
    </tr>
    <tr>
        <td><asp:Label ID="lblMessage" runat="server" Text=""></asp:Label></td>
    </tr>
</table>

The input design form looks like below:

sharepoint 2019 server object model
create site columns programmatically sharepoint 2016

SharePoint Server Object Model Code to Create Site Columns (Single line, Multiline & Choice)

Below SharePoint 2016 server object model code to create Site Columns (Single line, Multiline & Choice) in SharePoint 2016 programmatically.

using Microsoft.SharePoint;
using System;
using System.Collections.Specialized;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace Create_Site_Column.CreateSiteColumn
{
    public partial class CreateSiteColumnUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
               
            }
        }

        protected void btnSingleLineSiteColumn_Click(object sender, EventArgs e)
        {
            CreateSingleLineSiteColumn();
        }

        protected void btnMultiLineSiteColumn_Click(object sender, EventArgs e)
        {
            CreateMultiLineSiteColumn();
        }

        public void CreateSingleLineSiteColumn()
        {
         try
            {
                SPWeb web = SPContext.Current.Web;
                web.Fields.Add("DocumentLocation", SPFieldType.Text, true);                
            }
            catch (Exception exc)
            {
                lblMessage.Text = exc.Message;
            }
        }

        public void CreateMultiLineSiteColumn()
        {
        try
            {
                SPWeb web = SPContext.Current.Web;
                string fieldName = "Feedback";
                 web.Fields.Add(fieldName, SPFieldType.Note, false);
            }
            catch (Exception exce)
            {
                lblMessage.Text = exce.Message;
            }
        }

        public void CreateChoiceSiteColumn()
        {
         try
            {
                SPWeb web = SPContext.Current.Web;
                //Add choice Field "Document Department"
                string departmentField = web.Fields.Add("DocumentDepartment", SPFieldType.Choice, true);

                //Set the Field Properties
                SPFieldChoice documentDepartment = (SPFieldChoice)web.Fields.GetField(departmentField);

                //Set the group for the Site column
                documentDepartment.Group = "Custom Columns";

                //Add the choices
                string[] departments = new string[] { "IT", "HR", "Finance" };
                documentDepartment.Choices.AddRange(departments);

                //Set the default value
                documentDepartment.DefaultValue = "DocumentDepartment";

                //Set Fillable value
                documentDepartment.FillInChoice = true;

                //Update the field
                documentDepartment.Update();
            }
            catch (Exception ex)
            {

                lblMessage.Text=ex.Message;
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            CreateChoiceSiteColumn();
        }
    }
}

Once you will add your custom web part, you can see the form like the below screenshot. Once you will click on the “Create” button of each different type of Site Column, it will create the specific Site column in the SharePoint 2016/2013 site.

For example, if you want to create a Site column as a Single line of text, then click on the button “Create SiteColumn (Single line of text)”. Similarly, if you want to create a Site column as a multiline of text, then click on “Create SiteColumn (Multiline of text)” and so on.

SharePoint Server Object Model Tutorial
create site columns programmatically sharepoint 2013

Now go to “Site Settings“-> “Site columns“-> “Custom Columns“. There you can see your different types of Site Columns as like the below screenshot.

sharepoint server object model classes
create site columns programmatically sharepoint 2013

To ensure that whether the choice Site column is having the choice field values or not, click on the “DocumentDepartment“. Then you can see all the choice field values as shown in below:

sharepoint server object model hierarchy
create site columns programmatically sharepoint 2016 in visual studio

This is how to create different types of Site columns (Single line of text, Multiline of text, and Choice) programmatically c#.net using SharePoint 2016/2013 server object model code in Visual Studio.

Microsoft SharePoint is not supported in 32-bit process

Recently while working with the SharePoint server object model inside a windows application, I received the below error. System.PlatformNotSupportedException occurred in Microsoft.SharePoint.dll. An unhandled exception of type ‘System.PlatformNotSupportedException’ occurred in Microsoft.SharePoint.dll. Additional information: Microsoft SharePoint is not supported in 32-bit process. Please verify that you are running in a 64-bit executable.

microsoft sharepoint is not supported in 32-bit process. please verify
microsoft sharepoint is not supported in 32-bit process. please verify

We can work with the SharePoint server object model inside a windows application by adding Microsoft.SharePoint.dll.

To resolve the issue, Right-click on the Project -> Properties.

Then select Build and uncheck Prefer 32-bit option which looks like below.

Please verify that you are running in a 64-bit executable
Please verify that you are running in a 64-bit executable

After this Microsoft SharePoint is not supported in 32-bit process. Please verify that you are running in a 64-bit executable that will not appear.

You may like the following SharePoint tutorials:

In this SharePoint tutorial, we learned about the SharePoint server object model and we checked various SharePoint server-side object model examples.

  • SharePoint server side object model
  • SharePoint server object model hierarchy
  • SharePoint server side object model vs client side object model
  • Create a windows application to use SharePoint server object model code
  • SharePoint server side object model examples
  • Create a document library in SharePoint programmatically
  • Add columns to SharePoint document library using the server object model
  • How to get choices from choice field programmatically in SharePoint
  • Add columns to list view programmatically using SharePoint 2019 server object model
  • Create Site Columns programmatically using SharePoint Server Object Model
  • >