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 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

There are various classes that we can use.

sharepoint server object model hierarchy

Below are 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 and the client-side object model.

In the SharePoint on-premise environment, you can use both the SharePoint server-side object model code and the 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. The server Object Model core assembly is Microsoft.SharePoint.dll installed in the Global Assembly Cache.

Using SharePoint server object model code, you can use Visual Studio for SharePoint server-side development.

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

You cannot use the Server Object Model to connect remotely to a SharePoint Server. 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 the 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 the 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, choose Windows and then choose Windows Forms Application.

Then, we need to add a 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

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 code below 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 examples will work on every SharePoint on-premise version like SharePoint server 2019, SharePoint server 2016, etc.

1. Create a document library in SharePoint programmatically

Let us see how to programmatically create a Document Library in SharePoint using the SharePoint server object model.

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

Follow the step-by-step tutorial to create a document library in SharePoint programmatically using the SharePoint 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 controls below.

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 clicks on the button, the document library will be created on the SharePoint 2016 Site.
  • Label: If some error occurs 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

Code to create a document library in SharePoint programmatically

Below is the SharePoint server object model code to create the SharePoint 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;
            }
        }
    }
}

Like the screenshot below, you can see the form once you add your custom web part. Once you fill in all the field values and click the “Create” button, the document library will be created in SharePoint site.

programmatically create sharepoint document library c#

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

create a SharePoint document library programmatically using C#

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

create SharePoint document library programmatically using C#

This is how to create a document library programmatically c#.net using SharePoint server object model code.

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

In the below example, we will see how can we add columns (Choice columns and Single line of text column) to the SharePoint document library. We are adding the below 3 columns programmatically to the SharePoint 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:
  • DocumentDepartment (Choice Column): This column is also a Choice field. This department field column has some choice values as:
    • IT
    • HR
    • Finance

Below is the SharePoint server object model Code you can use for creating (Single line of text and Choice column) in SharePoint 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 document library; then you can see that one single line of the text column and other choice columns will be available, as shown below.

sharepoint 2013 server side object model examples

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

sharepoint 2019 server side object model

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

sharepoint server object model

Also, we saw how to create and add different types of columns in the SharePoint document library. How to give choice field values programmatically using the SharePoint server object model.

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

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

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

In both the choice field columns, it has some choice options values. So by using this below C# Code (SharePoint server object model), we can get choices from the 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 programmatically get choices from the choice field in SharePoint using the SharePoint server object model.

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

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

In the 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:
  • 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 Document Library or list. So, we must display programmatically using Server object model code (C#) in Visual Studio.

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

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 screenshot below, you can see that one single line of the text column and other choice columns will be available as a view.

sharepoint server object model

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

5. Create Site Columns programmatically using SharePoint Server Object Model

Now, let us see how to create different types of Site columns (Single line of text, multiple of text, and Choice) using Server object model code in SharePoint using Visual Studio.

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

We can design the form in the .ascx file in the visual web part. 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, multiple of text, and choice), So take three buttons with different IDs of each one.
  • Label: If some error occurs 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

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

Below is the code to create Site Columns (Single line, Multiline, and choice) in SharePoint 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();
        }
    }
}

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

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

SharePoint Server Object Model Tutorial

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

sharepoint server object model classes
create site columns programmatically sharepoint 2013

To ensure that whether the choice Site column has the choice field values, click on the “DocumentDepartment”. Then you can see all the choice field values as shown below:

sharepoint server object model hierarchy

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

Conclusion

In this tutorial, I have explained everything about the SharePoint server object model code, and we also saw a few examples of the server object model in SharePoint.

You may also like:

  • >