SharePoint Hassles: Script for Creating Subsites

As I’m learning SharePoint, I’m encountering all sorts of strange issues. Here’s some workarounds.

Site Creation
I needed a script to allow a user to create a subsite. It worked fine as the System account, but not as a Contributor. Here’s the code that finally worked:

public static void CreateSite(string sSiteUrl, string sTemplateName, string sSiteCollectionAdminName, string sSiteName, string sTitle, string sDescription, string sUserName, string sUserEmail, string sUserDisplayName)
{
//If you just open the site without passing the token then the current windows’s user (if windows authentication is used),
//is used. To ensure site collection admin’s token during the template upload and creation process, the adminUserToken is used
SPUserToken adminUserToken = GetUserToken(sSiteUrl, sSiteCollectionAdminName);
if (adminUserToken == null)
{
HttpContext.Current.Response.Write(“Site collection admin’s token not found. Site creation failed.”);
return;
}

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(sSiteUrl, adminUserToken))
{
//add a new spweb in the allweb collection of the current SPSite
//local ID 1033 specifies the english local
//if you provide no name in the templatename the site will be created without any template
//and when you try to access the site you’ll be prompted to select a site template
try
{

string sDomain = GetDomain();
string sSubSiteName = GetSiteName();

SPSite mySiteCollection = new SPSite(sDomain + “/” + sSubSiteName);
mySiteCollection.AllowUnsafeUpdates = true;
SPWeb mySite = mySiteCollection.AllWebs[0];
mySite.AllowUnsafeUpdates = true;

SPWebCollection subSites = mySite.Webs;
subSites.Add(sSiteName, sTitle, sDescription, 1033, sTemplateName, true, false);

try
{

string sNewSiteName = sDomain + “/” + sSiteName;
SPSite spNewSite = new SPSite(sNewSiteName);
SPWeb spNewWeb = spNewSite.OpenWeb();
string sNotes = “”;

spNewWeb.AllowUnsafeUpdates = true;
SPRoleAssignment spRoleAssignment = new SPRoleAssignment(sUserName, sUserEmail, sUserDisplayName, sNotes);

SPRoleDefinition spSPRoleDefinition = spNewWeb.RoleDefinitions[“Full Control”];

spRoleAssignment.RoleDefinitionBindings.Add(spSPRoleDefinition);
spNewWeb.RoleAssignments.Add(spRoleAssignment);

//Update site

spNewWeb.Update();
spNewWeb.AllowUnsafeUpdates = false;
}
catch (Exception ex)
{
HttpContext.Current.Response.Write(ex.ToString());
}
mySite.AllowUnsafeUpdates = false;
mySite.Dispose();

}

catch (Exception ex)
{
HttpContext.Current.Response.Write(ex.ToString());

}
}
});

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s