Wednesday, July 4, 2012

Add Sitetemplate progrmatically in SharePoint 2010


Hello,
Today we will add the site template programatically in sharepoint site to each and every subsites.
We will create the window application for that.
Next steps is to add the Microsoft.SharePoint.dll form the 14 hives
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\isapi.
Now put one lable from the toolbox section and set the text property as "Site Url".
Now put one text box beside of label and name it as txtSiteUrl.
Now add one button and named it as btnStart and set the text property as "Start".
so Final look of the window form is like





now add following lines of code to the button click event


private void btnStart_Click(object sender, EventArgs e)
{
try
{
using(SPSite site = new SPSite(txtSiteUrl.Text))
{
SPWeb rootWeb = site.RootWeb;
ConfigureSiteTemplate(site, rootWeb);
MessageBox.Show("Operation Completed Successfully........");
}
}
catch (Exception ex)
{
throw ex;
}
}



Below are the custom functions


private void ConfigureSiteTemplate(SPSite site, SPWeb web)
{
try
{
using (SPSite CurrentSite = new SPSite(web.Url))
{
using (SPWeb CurrentWeb = CurrentSite.OpenWeb())
{
SetSiteTemplate(CurrentWeb);
foreach (SPWeb currentWebSite in CurrentWeb.Webs)
{
ConfigureSiteTemplate(site, currentWebSite);//we are calling recursive function for each and every sub site
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
public void SetSiteTemplate(SPWeb currentWeb)
{
bool SharePointCutomTemplateAvailable = false;
Collection<SPWebTemplate> Collection = new Collection<SPWebTemplate>();
try
{
using (SPWeb curWeb = currentWeb)
{
using (SPSite curSite = curWeb.Site)
{
SPWebTemplateCollection TemplateCollection = curWeb.GetAvailableWebTemplates(curWeb.Language);
foreach (SPWebTemplate Template in TemplateCollection)
{
if (Template.Title == "Custom Sharepoint Template")//This is custom sharepoint template
{
SharePointCutomTemplateAvailable = true;//Here we are checking that the custom template with name "Custom Sharepoint Template" is already added or not
}
if (Template.Name != "ENTERWIKI#0")//we are adding wiki template
{
Collection.Add(Template);
}


}
foreach (SPWebTemplate template in curSite.GetWebTemplates(curWeb.Language))
{
if (!SharePointCutomTemplateAvailable && template.Title == "Custom Sharepoint Template")//If the custom template is not available we will add it
{
Collection.Add(template);//Here custom template is added
}
}
curWeb.SetAvailableCrossLanguageWebTemplates(Collection);
curWeb.Update();
}
}
}
catch (Exception ex)
{
throw ex;
}
}



Now run the application , and give the site url ( http://server:port ) of you sharepoint site and click on the button , it will add the given site template to your sharepoint sites and subsites.


Regards
Hiren Patel



No comments:

Post a Comment