Monday, January 28, 2008

Creating Sites and List folders in a SharePoint using C# programmatically

Purpose of the Content:
Objective of this document is to throw some light on object model in MOSS using C#
This article will cover following topics
1. Introduction
2. Prerequisites
3. SPWebCollection.Add Method
4. Creating sites in SharePoint
5.SPListItemCollection.Add Method:
6.Creating folders in SharePoint List:


Introduction
The Windows SharePoint Services object model consists of forty-two namespaces in ten assemblies that are used in SharePoint sites on the server that is running Windows SharePoint Services1. The Microsoft.SharePoint and Microsoft.SharePoint.Administration namespaces provide types and members that can be used with lists and sites, as well as to manage a server or collection of servers that are running Windows SharePoint Services.

Now creating sites programmatically is one of the features that SharePoint SDK provides. The following sections will focus on how we can achieve this functionality.



Prerequisites :
Creating sites may be one of the task or the only that a web part does। So one must know how to develop and configure the web parts using SharePoint. Here I m using a web part consist a button on click of which, the new site creation logic will execute.

While sites are created through SharePoint we associate a site template name with the site. So it will be helpful to know how to develop and configure custom site templates if you want to use in new site. You can also refer the existing site template provided by SharePoint

SPWebCollection.Add Method:
The method Creates a Web site object with the specified site-relative URL, title, description, locale ID, and site definition or site template object.

SPWebCollection.Add Method (String, String, String, UInt32, SPWebTemplate, Boolean, Boolean) (Microsoft.SharePoint)

Namespace: Microsoft.SharePointAssembly: Microsoft.SharePoint (in microsoft.sharepoint.dll)
public SPWeb Add (
string strWebUrl,
string strTitle,
string strDescription,
uint nLCID,
SPWebTemplate WebTemplate,
bool useUniquePermissions,
bool bConvertIfThere
)

Parameters:


strWebUrl :A string that contains the new Web site URL relative to the root Web site in the site collection. For example, to create a Web site at http://MyServer/sites/MySiteCollection/MyNewWebsite, specify MyNewWebsite, or to create a Web site one level lower at http://MyServer/sites/MySiteCollection/Website/MyNewWebsite, specify Website/MyNewWebsite.

strTitle: A string that contains the title.

strDescription: A string that contains the description.

nLCID: An unsigned 32-bit integer that specifies the locale ID.

WebTemplate: An
SPWebTemplate object that represents the site definition or site template.

6· useUniquePermissions: true to create a subsite that does not inherit permissions from another site; otherwise, false.

bConvertIfThere: true to convert an existing folder of the same name to a SharePoint site. false to throw an exception that indicates that a URL path with the specified site name already exists.


Return ValueAn SPWeb object that represents the Web site.

Creating sites in SharePoint:

1· Add the following namespaces and reference the DLL Microsoft. SharePoint.dll
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

2· Get the sp web object of the current site in which site is to create as
SPWeb spCurrentWeb = new SPSite(strSiteURL).OpenWeb(); where strSiteURL is the URL of the site as http://chdsez108269d:999/

3· Place the site template in the following SharePoint directory
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\SiteTemplates\

4· Now call the following function with given required parameters
private SPWeb CreateNewSite(SPWeb spCurrentWeb, string siteName, string siteDesc, string siteTemplateName, string strWebUrl)

Usage:

SPWeb spEventWeb = this.CreateNewSite(spcurrentweb, ”MyNewSite”,”siteDescription”,”MyCustomTemplate”,”MyNewSiteURL”))

Where spcurrentweb is spweb object of current site
o siteName and siteDesc is the name and description of the new site to create
o siteTemplateName is name of the template of the new site
o strWebUrl is the relative URL of the new site which can be different or same as the siteName
Full function body is below

private SPWeb CreateNewSite(SPWeb spCurrentWeb, string siteName, string siteDesc, string siteTemplateName, string strWebUrl)
{
try
{
if (spCurrentWeb != null)
{
if (spCurrentWeb.Webs[siteName].Exists == false)
{
//get the template collection from site based on locale Id
SPWebTemplateCollection Templates = spCurrentWeb.Site.GetWebTemplates(Convert.ToUInt32(1033));
if (Templates != null)
{
//get the template object from template collection based on locale Id
SPWebTemplate siteTemplate = Templates[siteTemplateName];
if (siteTemplate != null)
{
//create a new site and add it in web collection of the parent web
using (SPWeb spChildWeb = spCurrentWeb.Webs.Add(strWebUrl, siteName, siteDesc, (uint)1033, siteTemplate, false, false))
{
if (spChildWeb != null)
{
spChildWeb.AllowUnsafeUpdates = true;
spChildWeb.Update();
return spChildWeb;
}
else
{
throw new Exception("Site " + siteName + "can't be created");
}
}
}
}
}
else
{
throw new Exception("Site " + siteName + " already exist");
}
}
return null;
}
catch (Exception ex)
{
LogException(ex, "Site can't be created!!! some exception has occoured");
return null;
}
finally
{
if (spCurrentWeb != null)
spCurrentWeb.Dispose();
}
}

SPListItemCollection.Add Method:

The following method Create an item that uses the specified folder URL, object type, and leaf name but requires the Update method to actually add the item to the list.

SPListItemCollection.Add Method (String, SPFileSystemObjectType, String) (Microsoft.SharePoint)

Namespace: Microsoft.SharePointAssembly: Microsoft.SharePoint (in microsoft.sharepoint.dll)

public SPListItem Add
(
string folderUrl,
SPFileSystemObjectType underlyingObjectType,
string leafName
)
Parameters

o folderUrl : A string that contains the server-relative URL of the folder, beginning with a forward slash; for example, /sites/mysite/subweb/Lists/mylist/myfolder.

underlyingObjectType : A
Microsoft.SharePoint.SPFileSystemObjectType value that indicates the object type. Only File and Folder are valid types for the underlying object type.


leafName: A string that contains the leaf name, which is everything after the last forward slash in the URL, including the file extension.

Return Value: A
Microsoft.SharePoint.SPListItem object that represents the new item.
Creating folders in SharePoint List:
1· Add the following namespaces and reference the DLL Microsoft. SharePoint.dll
using Microsoft.SharePoint;

2· Get the sp web object of the current site in which site is to create as
SPWeb spCurrentWeb = new SPSite(strSiteURL).OpenWeb(); where strSiteURL is the URL of the site as http://chdsez108269d:999/

3· Now call the following function with given required parameters


private SPFolder GetFolder(SPWeb spCurrentWeb,string strSiteLink, string strListName, string strFolderName)
Usage:

spFolder spNewFolder = this.GetFolder(spcurrentweb, “MySiteLink”, “MyListName”, “MyFolderName”);
Where spcurrentweb is spweb object of current site
o MyListName and MyFolderName is the list name and folder name in the given list.
o MySiteLink is the relative URL of the new site which can be different or same as the siteName
Full function body is below


private SPFolder GetFolder(SPWeb spCurrentWeb,string strSiteLink, string strListName, string strFolderName)
{
using (spCurrentWeb)
{
if (!string.IsNullOrEmpty(strFolderName))
{
//create a folder with the given name in the event list if don't exist, otherwise return the existing folder
if (spCurrentWeb.GetFolder("Lists/" + strListName + "/" + strFolderName).Exists != true)
{
spCurrentWeb.AllowUnsafeUpdates = true;
SPList spListEvent = spCurrentWeb.Lists[strListName];
//create a new folder in the list
SPListItem spFolderEvent = spListEvent.Items.Add(strSiteLink + "/Lists/" + strListName, SPFileSystemObjectType.Folder, strFolderName);
spFolderEvent.Update();
spListEvent.Update();
spCurrentWeb.Update();
}
//return the existing folder from the list
return spCurrentWeb.GetFolder("Lists/" + strListName + "/" + strFolderName);
}
return null;
}
}




References:
http://msdn2.microsoft.com/en-us/library/ms439689.aspx
http://msdn2.microsoft.com/en-us/library/ms448720.aspx

3 comments:

B1ju said...

Hi,

I have a requirement to delete the webpart from the gallery on deactivating an feature(it is feature for customizing list event handler).
I do it using the following code,


using (SPWeb web = properties.Feature.Parent as SPWeb)
{
SPList list = web.Lists["Web Part Gallery"];
for (int i = list.ItemCount - 1; i >= 0; i--)
{
if (list.Items[i].DisplayName.Equals("RegisterEventHandler"))
{
list.Items[i].Delete();
list.Items.Add();
break;
}
}
}



Can you please suggest how to populate the webpart on activating the feature using

SPListItem Add(string folderUrl, SPFileSystemObjectType underlyingObjectType, string leafName);

B1ju said...

I have a requirement to delete the webpart from the gallery on deactivating an feature(it is feature for customizing list event handler).
I do it using the following code,


using (SPWeb web = properties.Feature.Parent as SPWeb)
{
SPList list = web.Lists["Web Part Gallery"];
for (int i = list.ItemCount - 1; i >= 0; i--)
{
if (list.Items[i].DisplayName.Equals("RegisterEventHandler"))
{
list.Items[i].Delete();
list.Items.Add();
break;
}
}
}



Can you please suggest how to populate the webpart on activating the feature using

SPListItem Add(string folderUrl, SPFileSystemObjectType underlyingObjectType, string leafName);

B1ju said...

Sorry , i was trying something with my code and by mistake copied the same code snippet. Please ignore the line
list.Items.Add();


With regards
Biju