Monday, 28 January 2013

Create a Site Using Custom Template / Solution in SharePoint 2010

Notes
  • Before attempt this , 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.
  • The sample codes are follows.

Ex:1 On Button Click Get all the Default Web Templates

protected void Button1_Click(object sender, EventArgs e)
{
string server = @"http://MohanServer:8787";
using (SPSite siteColl = new SPSite(server))
   {
      SPWebTemplateCollection templatesCol = siteColl.GetWebTemplates(1033);
      foreach (SPWebTemplate template in templatesCol)
      {
          ddTemplates.Items.Add(new ListItem(template.Title, template.Name));
      }
   }
 
}

Ex: 2 On Button Click Get your cusom template
protected void Button3_Click(object sender, EventArgs e)
{

   SPSite mySite = new SPSite(@"http://spsportal:8787");
   SPWeb myWeb = mySite.OpenWeb();  
myWeb.AllowUnsafeUpdates = true;

   SPWebTemplateCollection tempCols = myWeb.GetAvailableWebTemplates(1033, true);
   foreach (SPWebTemplate temps in tempCols)  
{

       if (temps.Title == "MyTest Temp")// || temps.Name.ToLower().StartsWith("my") ||  temps.Name.Contains("my"))      
{
          ddCustomTemps.Items.Add(new ListItem(temps.Title, temps.Name));      

      }
   }
}

Get the custom template ID form the SharePoint Solution Gallary

SPSite mySite = new SPSite(@"http://spsportal:8787");
        SPWeb myWeb = mySite.OpenWeb();
        myWeb.AllowUnsafeUpdates = true;


        SPWebTemplateCollection tempCols = myWeb.GetAvailableWebTemplates(1033, true);
        foreach (SPWebTemplate temps in tempCols)
        {
            if (temps.Title == "MyTest Temp

            {
                Response.Write(temps.Name);
            }
        }


Output : - {5BD38D14-E7B6-4031-969C-5D300A33F4C8}#1MyTestTemp


Pass that Name as Id in the following code


SPSite mySite = new SPSite(@"http://spsportal:8787");
        SPWeb myWeb = mySite.OpenWeb();
        myWeb.AllowUnsafeUpdates = true;

        SPWebCollection subSites = myWeb.Webs;
        try
        {
            SPWeb web = subSites.Add("Sample", "SampleTitle", "Sample Desc", 1033, "{5BD38D14-E7B6-4031-969C-5D300A33F4C8}#1MyTestTemp", false, false);
            Response.Write(" Is Created..");
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }

No comments:

Post a Comment