Я использую следующий код для создания нового сайта:
newWeb = SPContext.GetContext(HttpContext.Current).Web.Webs.Add(newSiteUrl, newSiteName, null, (uint)1033, siteTemplate, true, false);
try
{
newWeb.Update();
}
NewSiteUrl и newSiteName являются значениями из двух текстовых полей, и на каком бы сайте я ни использовал этот код (в веб-части), новый сайт будетбыть дочерним сайтом для этого сайта.
Теперь я хотел бы иметь возможность выбрать родительский сайт, чтобы новый сайт мог находиться где угодно в семействе сайтов, а не только как дополнительный сайт к сайту, на котором я используювеб-часть.
Я создал следующую функцию, чтобы получить все сайты в семействе сайтов, и заполнил раскрывающийся список с именем и URL-адресом для каждого сайта
private void getSites()
{
SPSite oSiteCollection = SPContext.Current.Site;
SPWebCollection collWebsite = oSiteCollection.AllWebs;
for (int i = 0; i < collWebsite.Count; i++)
{
ddlParentSite.Items.Add(new ListItem(collWebsite[i].Title, collWebsite[i].Url));
}
oSiteCollection.Dispose();
}
Если пользователь выбираетсайт в раскрывающемся списке, возможно ли использовать этот URL в newSiteUrl, чтобы решить, где должен быть новый сайт?Я не заставляю его работать на самом деле, и новый сайт все еще становится вспомогательным по отношению к текущему.Я думаю, это связано с HttpContext.Current?Любые идеи о том, как мне это сделать вместо этого?
Впервые я пишу собственные веб-части, и объектная модель sharepoint на данный момент немного ошеломляет.
Заранее спасибо.
Редактировать: с обновленным кодом выдает ошибку: Trying to use an SPWeb object that has been closed or disposed and is no longer valid.
if (!siteExists(newSiteName) && newSiteName.Length > 0)
{
using (var parent = SPContext.GetContext(HttpContext.Current).Site)
{
using(var parentWeb = parent.OpenWeb(new Guid(parentSite)))
{
newWeb = parentWeb.Webs.Add(newSiteUrl, newSiteName, null, (uint)1033, siteTemplate, true, false);
try
{
newWeb.Update();
}
catch
{
lblErrorCreateSite.Text = "An error occured when trying to create a new site, please try again.";
}
finally
{
txtSiteName.Text = "";
// Show link to new site
lblNewSite.Text = "A new site was successfully created at ";
hplNewSite.Visible = true;
hplNewSite.NavigateUrl = siteURL() + newSiteName;
hplNewSite.Text = newSiteName;
// Dispose to reload the SharePoint content database
newWeb.Dispose();
}
// Set permissions
try
{
string site = siteURL();
SPSite spSite = new SPSite(site + newSiteName);
SPWeb web = spSite.OpenWeb();
// Assign Full Access role to the selected groups
string fullAccessGroup = null;
string fullAccessRole = null;
foreach (ListItem item in lbFullAccess.Items)
{
fullAccessGroup = item.Value;
fullAccessRole = "Full Control";
SPRoleAssignment roleAssignment = new SPRoleAssignment(web.SiteGroups[fullAccessGroup]);
SPRoleDefinitionBindingCollection roleDefinition = roleAssignment.RoleDefinitionBindings;
roleDefinition.Add(web.RoleDefinitions[fullAccessRole]);
web.RoleAssignments.Add(roleAssignment);
web.Properties[fullAccessGroup] = fullAccessRole;
web.Properties.Update();
}
// Assign Contributor role to the selected groups
string contributeGroup = null;
string contributeRole = null;
foreach (ListItem item in lbContributor.Items)
{
contributeGroup = item.Value.ToString();
contributeRole = "Contribute";
SPRoleAssignment roleAssignment = new SPRoleAssignment(web.SiteGroups[contributeGroup]);
SPRoleDefinitionBindingCollection roleDefinition = roleAssignment.RoleDefinitionBindings;
roleDefinition.Add(web.RoleDefinitions[contributeRole]);
web.RoleAssignments.Add(roleAssignment);
web.Properties[contributeGroup] = contributeRole;
web.Properties.Update();
}
// Assign Reader role to the selected groups
string readerGroup = null;
string readerRole = null;
foreach (ListItem item in lbReadOnly.Items)
{
readerGroup = item.Value.ToString();
readerRole = "Read";
SPRoleAssignment roleAssignment = new SPRoleAssignment(web.SiteGroups[readerGroup]);
SPRoleDefinitionBindingCollection roleDefinition = roleAssignment.RoleDefinitionBindings;
roleDefinition.Add(web.RoleDefinitions[readerRole]);
web.RoleAssignments.Add(roleAssignment);
web.Properties[readerGroup] = readerRole;
web.Properties.Update();
}
}
catch
{
lblErrorSetPermissions.Text = "Error trying to set permissions for this site, please try again.";
}
finally
{
}
}
}
}
else
{
if (siteExists(newSiteName))
{
lblErrorCreateSite.Text = "A site with that name already exists. Please select another name.<br/>";
}
if (newSiteName.Length == 0)
{
lblErrorCreateSite.Text = "A Site Name is required.<br/>";
}
hplNewSite.Visible = false;
}
Редактировать2: поэтому я использую
SPSite currentContext = SPContext.GetContext(HttpContext.Current).Site;
SPWeb parentID = currentContext.OpenWeb(new Guid(parentSiteValue));
newWeb = parentID.Webs.Add(newSiteUrl, newSiteName, null, (uint)1033, siteTemplate, true, false);
Но как мне проще всего получить URL для вновь созданногосайт (для отображения правильного URL-адреса в создаваемой ссылке и использования при настройке разрешений)?