SharePoint Server Object Model Sample Code snippets


Below are  sample code snippets using SharePoint Object model, probably use full for some people who wants to learn SharePoint Server Object model

Creating a subsite

SPWeb mySite = SPContext.Current.Web;
SPWebCollection mySiteCollection = mySite.Webs;
uint lcid = mySite.Language;
string templateName = "WIKI#0";
mySiteCollection.Add("Nani Site", "Nani", "Site Created using object model", lcid, templateName, false, false);
mySite.Dispose();

Creating a list

SPSite mySiteCollection = SPContext.Current.Site;
SPWeb mySite = mySiteCollection.OpenWeb();
SPListCollection myListCollection = mySite.Lists;
myListCollection.Add("Niru6", "created using object model",SPListTemplateType.Contacts);

Show all top level sites in farm

SPWebServiceCollection myservices = new SPWebServiceCollection(SPFarm.Local);
foreach (SPWebService myservice in myservices)
{
SPWebApplicationCollection myWebAppCollection = myservice.WebApplications;
foreach (SPWebApplication mywebApp in myWebAppCollection)
{
SPSiteCollection mySiteCollection = mywebApp.Sites;
SPSite mySite = mySiteCollection[0];
Label1.Text += mySite.RootWeb.Url + "";
}
}

Return the collection of site collections in a SharePoint Web application

SPWebApplication myWebApp = SPContext.Current.Site.WebApplication;
SPSiteCollection mySiteCollection = myWebApp.Sites;
foreach (SPSite mySite in mySiteCollection)
{my
Label1.Text += mySite.RootWeb.Title + "";
mySite.Dispose();
}

To return the collection of The all the Webs or sites within a site collection, including the top-level site and all subsites

SPWebApplication myWebApp = SPContext.Current.Site.WebApplication;
SPSiteCollection mySiteCollection = myWebApp.Sites;
foreach (SPSite mySite in mySiteCollection)
{
SPWebCollection myWebCollection = mySite.AllWebs;
foreach (SPWeb myWeb in myWebCollection)
{
Label1.Text += mySite.Url + " " + myWeb.Title + "";
myWeb.Dispose();
}
mySite.Dispose();
}

To return the all the subsites and lists of the current site

SPSite mySite = SPContext.Current.Site;
SPWebCollection myWebCollection = mySite.AllWebs;
foreach (SPWeb myWeb in myWebCollection)
{
SPListCollection myListCollection = myWeb.Lists;
foreach (SPList myList in myListCollection)
{
Label1.Text += myWeb.Title +" " + myList.Title + "";
}
myWeb.Dispose();

}

Show all roles in a site

SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.RootWeb;
SPRoleDefinitionCollection myRoleCollection = myWeb.RoleDefinitions;
foreach (SPRoleDefinition myRole in myRoleCollection)
{
Label1.Text += myRole.Name + "";
}

Show all alerts in a site

SPWeb mySite = SPContext.Current.Web;
SPAlertCollection myAlertCollection = mySite.Alerts;
foreach (SPAlert myAlert in myAlertCollection)
{
Label1.Text += myAlert.Title + "";
}

Show all lists in a site

SPWeb mySite = SPContext.Current.Web;
SPListCollection myListCollection = mySite.Lists;
foreach (SPList myList in myListCollection)
{
Label1.Text += myList.Title + "";
}

Show all list templates in a site

SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.RootWeb;
SPListTemplateCollection myTemplateCollection = myWeb.ListTemplates;
foreach (SPListTemplate myTemplate in myTemplateCollection)
{
Label1.Text += myTemplate.Name + " " + myTemplate.Type + "";
}

Show all fields in a list

SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.RootWeb;
SPList myList = myWeb.Lists["Niru3"];
SPFieldCollection myFieldCollection = myList.Fields;
foreach (SPField myField in myFieldCollection)
{
Label1.Text += myField.Title + "";
}

Show all items in a list column

SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.RootWeb;
SPList myList = myWeb.Lists["Niru3"];
SPListItemCollection myItemCollection = myList.Items;

foreach (SPListItem myItem in myItemCollection)
{

Label1.Text += myItem["Last Name"].ToString() + "";

}

Delete all items from a list

When using a for Loop, if you wish to remove an item from the collection you are iterating through it can be done very easily. When using foreach you will get an exception stating that the item cannot be removed
Refer :Link

SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.RootWeb;
SPList myList = myWeb.Lists["Niru3"];
for (int i = myList.Items.Count - 1; i >= 0; i--)
{
myList.Items.Delete(i);
}

Show all groups in a site

SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.RootWeb;
SPGroupCollection myGroupCollection = myWeb.Groups;
foreach (SPGroup myGroup in myGroupCollection)
{
Label1.Text += myGroup.Name + "";

}

Delete a item in a list based on condition

SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.RootWeb;
SPList myList = myWeb.Lists["Niru3"];
for (int i = myList.Items.Count - 1; i >= 0; i--)
{
if (myList.Items[i]["Last Name"].ToString() == "Nani")
{
myList.Items.Delete(i);
}

}

Show all users in a group

SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.RootWeb;
SPGroupCollection myGroupCollection = myWeb.Groups;
SPGroup myGroup = myGroupCollection["Viewers"];
SPUserCollection myUserCollection = myGroup.Users;
foreach (SPUser myUser in myUserCollection)
{
Label1.Text += myUser.Name + "
";
}

Show all users from all groups from user collection

SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.RootWeb;
SPGroupCollection myGroupCollection = myWeb.Groups;
foreach (SPGroup myGroup in myGroupCollection)
{
SPUserCollection myUserCollection = myGroup.Users;
foreach (SPUser myUser in myUserCollection)
{
Label1.Text += myGroup.Name + "" + myUser.Name + "";
}

}

Show only blog sites

SPSite mySite = SPContext.Current.Site;
SPWebCollection myWebCollection = mySite.AllWebs;
foreach (SPWeb myWeb in myWebCollection)
{
if (myWeb.WebTemplate == "BLOG")
{
Label1.Text += myWeb.Title + "" ;
}
myWeb.Dispose();

}

Show services and status in sharepoint server farm

SPFarm myFarm = SPFarm.Local;
SPServiceCollection myServiceCollection = myFarm.Services;
foreach (SPService myService in myServiceCollection)
{
Label1.Text += myService.Name + " " + myService.Status + "
";
}

To get the timer jobs history for a particular service in the SharePoint 2010 farm

SPFarm myFarm = SPFarm.Local;
SPServiceCollection myServiceCollection = myFarm.Services;
foreach (SPService myService in myServiceCollection)
{
if (myService.DisplayName == "My Sample Service")
{
foreach (SPJobHistory entry in myService.JobHistoryEntries)
{
Label1.Text += "Job Definition Title - " + entry.JobDefinitionTitle + " : Status - " + entry.Status + " : Start Time - " + entry.StartTime + "
";
}

}
}

Get content database for all site collections

SPWebServiceCollection myWebServiceCollection = new SPWebServiceCollection(SPFarm.Local);
foreach (SPWebService myWebService in myWebServiceCollection)
{
SPWebApplicationCollection myWebApplicationCollection = myWebService.WebApplications;
foreach (SPWebApplication myWebApplication in myWebApplicationCollection)
{
SPContentDatabaseCollection myContentDatabaseCollection = myWebApplication.ContentDatabases;
foreach (SPContentDatabase myContentDatabase in myContentDatabaseCollection)
{
Label1.Text += myContentDatabase.Name + "
";
}
}

}

Add fields to list and add it to default view

SPWeb mySite = SPContext.Current.Web;
SPList myList = mySite.Lists.TryGetList("Niru2");
SPFieldCollection myFieldCollection = myList.Fields;
string strNewFieldName = myFieldCollection.Add("Native Place", SPFieldType.Text, false);
SPField oField = myFieldCollection.GetField(strNewFieldName);
SPView oView = myList.DefaultView;
SPViewFieldCollection colViewFields = oView.ViewFields;
colViewFields.Add(oField);
oView.Update();

Creating a new view in a list

SPWeb mySite = SPContext.Current.Web;
SPList myList = mySite.Lists.TryGetList("List_Name");

SPViewCollection myViewCollection = myList.Views;
string strViewName = "View_Name";
System.Collections.Specialized.StringCollection collViewFields = new System.Collections.Specialized.StringCollection();
collViewFields.Add("Field1_Name");
collViewFields.Add("Field2_Name");
collViewFields.Add("Field3_Name");
string strQuery = "" +
"1000";

myViewCollection.Add(strViewName, collViewFields, strQuery, 100, true, false,
Microsoft.SharePoint.SPViewCollection.SPViewType.Grid, false);

Source : MSDN

Creating a new content type and add it to a list, Adding the existing site columns to existing content type

– Check for duplicate content type, field, and list names.
– Create a new site content type.
– Add the content type to the site collection
– Create a site field to link to
– Link the content type to the field
– Commit changes to the database
– Create a list
– Apply the new content type to the list
o Add the new content type
o Remove the default content type
o Commit changes to the list

– Refer : Link

Delete recycle bin items

SPSite site = new SPSite(<>);
SPWeb web = site.RootWeb;
SPRecycleBinQuery q = new SPRecycleBinQuery();

q.RowLimit = Int32.Parse(<>);
q.OrderBy = SPRecycleBinOrderBy.Default;
SPRecycleBinItemCollection itemColl = web.GetRecycleBinItems(q);
foreach (SPRecycleBinItem item in itemColl)
{
Guid[] id = new Guid[1];
id[0] = item.ID;
itemColl.Delete(id);
}

Source: MSDN

• creating folder, uploading file to folder, deleting folder searching the folder in a doc lib
Refer to MSDN

Use about AllowUnsafeUpdates  :Refer this link

About Disposing objects :link

My Notes :
* (SPSite -> AllWebs)The AllWebs property of the SPSite class returns all the Web sites within a site collection, including the top-level site and all subsites.
* (SPWeb ->webs) To return a list of all the first-tier subsites beneath a specific Web site, use the Webs property of the SPWeb class.
* (SPWeb) openweb – return the site that is associated with the url that is used in SPSite constructor
* To return the collection of site collections in a SharePoint Web application, use the Sites property of the Microsoft.SharePoint.Administration.SPWebApplication class. Use properties of the Microsoft.SharePoint.SPContext class to return the current Web application.
* (SPWeb ->RootWeb)To return the top-level Web site of the current site collection, use the RootWeb property.
* close method — Closes the website at the end of a request and releases resources.
* Dispose method — Releases all resources used by the current instance of the website.

*  To Get the web site where the feature is activated.

SPWeb parentWeb = properties.Feature.Parent as SPWeb;

* when we use Rootweb and SPContext ie No explicit  dispose required.

 

Disclaimer:
The sample code provided is on “AS IS” basis with no warranties, and confers no rights.

About niranjanrao

Tech savy intrested in knowing things
This entry was posted in SharePoint, Uncategorized. Bookmark the permalink.

2 Responses to SharePoint Server Object Model Sample Code snippets

  1. DaviD says:

    Hi, niranjanrao.
    Actually you shouldn’t use Dispose() method on SPContext.Current.Web. And also you should use Dispose() method when you create new Site. E.g var myNewSite = mySiteCollection.Add(“Nani Site”, “Nani”, “Site Created using object model”, lcid, templateName, false, false); myNewSite.Dispose(). Or you could use using clause. See http://msdn.microsoft.com/en-us/library/aa973248.aspx#sharepointobjmodel__spsiteobjects

  2. Pingback: SharePoint Server Object Model Sample Code snippets | msaishere

Leave a comment