Monday, March 4, 2013

Create Sites Using SharePoint 2010 Server Object Model


Introduction

In this article we will see how to create sites using custom site templates programmatically in the SharePoint 2010 Server Object Model.

Steps

The following code shows how we usually create a site using the default SharePoint 2010 templates/definitions.

Creating-site-in-SharePoint1.jpg

The "SPWeb" object's "Add" method creates a Web Site object with the specified site-relative URL, title, description, locale ID  and site definition or site template name. "STS#1" represents the blank site template.

We will create a sample UI page to get the inputs as shown below.

Creating-site-in-SharePoint2.jpg

Once the site has been created successfully, we can navigate to the site and check whether the blank site was created or not.

Creating-site-in-SharePoint3.jpg

But we need to create a site using a custom template. For demo purpose we use any existing site and store it as "Site Template" in the "Solution Gallery" and activate the solution. We will see the solutions in the following navigation path for any root site. All the solution files are saved in .wsp file format.

Path: "Site Actions" --> "Site Settings" --> "Solutions"

Next we need to get the solution/template id dynamically from the solution gallery. We will have the following code to get the template id and write it as a helper function.

Creating-site-in-SharePoint4.jpg

Usually many templates are available in the collection. If required we will pass the "Solution Name" as input and get the particular template id.

Creating-site-in-SharePoint5.jpg

Finally we need to pass the result template Id to create a new site, instead of default templates. It'll create a new site using our custom template.

Creating-site-in-SharePoint6.jpg

Summary

Suppose we have a large site with hundreds of lists and a document library, it's really easy to get the entire site structure as a template and using this method we can use the same custom template to create new sites programmatically.

Notes
  • Before we try this logic, we need to ensure that the "SharePoint Server Publishing Infrastructure" feature is activated at the site collection and site level.
  • The Site template will not have any information about the sub-sites and its content.
  • Before we save the site as "Site Template", we need to check to determine if any custom features are deployed and activated. Because while we use the same template , it'll expect the same features need to be activated.

No comments:

Post a Comment