Wednesday 8 May 2013

Create Site/Sub Site using Custom SiteTemplate in Sharepoint programatically

Programmatically create Sites and Site Collections based on Site Templates.


using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb parentWeb = site.OpenWeb())
{
string webTitle = txtSiteName.Text.ToString().Trim(); // Site Name
 
string webDesc = “Site Description”;
 
string webName = txtSitepath.Text.ToString().Trim(); // URL to new Site
 
string webUrl = string.Empty;
 
if (string.IsNullOrEmpty(parentWebName))
{
webUrl = webName;
}
else
{
webUrl = parentWebName.ToString().Trim()+”/”+webName;
}
 
uint webLcid = parentWeb.Language;
SPWebTemplate webTemplate = null;
// site.GetWebTemplates((uint)1033); OR site.GetCustomWebTemplates((uint)1033); From Root Site

foreach (SPWebTemplate wt in parentWeb.GetAvailableWebTemplates((uint)1033))
{
if (wt.Title == “Collaboration Meeting Site Template”) // template name
{
webTemplate = wt;
break;
}
}
 
// Name value for the Document Workspace template.
// Create the new web.
SPWeb newWeb = null;
try
{
newWeb = site.AllWebs.Add(webUrl, webTitle, webDesc, webLcid, webTemplate, true, false);
lblMessage.Text = “Sub Site ” + webTitle + ” Successfully Created !! ;
}
catch (ArgumentException ex)
{
Console.WriteLine(ex.Message);
}
 
// Add a link to the new web on the RootWeb’s topnav bar.
if (newWeb != null)
{
// Set the new web’s top link bar to inherit links from its parent web.
newWeb.Navigation.UseShared = true;
 
// Create a link pointing to the new web.
SPNavigationNode node = new SPNavigationNode(newWeb.Title, newWeb.ServerRelativeUrl);
 
// Find out if the parent inherits links.
bool parentInheritsTopNav = newWeb.ParentWeb.Navigation.UseShared;
if (parentInheritsTopNav)
{
// Add the link to the top link bar on the root web.
site.RootWeb.Navigation.TopNavigationBar.AddAsLast(node);
}
else
{
// Add the link to the top link bar on the parent web.
newWeb.ParentWeb.Navigation.TopNavigationBar.AddAsLast(node);
}
newWeb.Dispose();
}
}
}

No comments:

Post a Comment