public Web CreateHRSubsite() { Console.WriteLine("Creating HR subsite"); try { WebCreationInformation webCreationInfo = new WebCreationInformation { Url = "HR", Title = "HR Department", Description = "Subsite for HR", UseSamePermissionsAsParentSite = true, WebTemplate = "STS#0", Language = 1033, }; Web web = _context.Site.RootWeb.Webs.Add(webCreationInfo); _context.Load(web); _context.ExecuteQuery(); return(web); } catch (Exception ex) { Console.WriteLine("Lỗi tạo HR subsite"); Console.WriteLine("Lỗi: " + ex.GetType().Name + " " + ex.Message); } return(null); }
public void CreateSite(ClientContext context, string UrlOfSiteRelativeToRoot, string NameOfSite, string Description) { Web rootWeb = context.Site.RootWeb; context.Load(rootWeb, w => w.CustomMasterUrl); WebCreationInformation wci = new WebCreationInformation(); wci.Url = UrlOfSiteRelativeToRoot; wci.Title = NameOfSite; wci.Description = Description; wci.UseSamePermissionsAsParentSite = true; wci.WebTemplate = "BLANKINTERNET#0"; wci.Language = 1033; Web subWeb = context.Site.RootWeb.Webs.Add(wci); context.ExecuteQuery(); //Update MasterPage subWeb.CustomMasterUrl = rootWeb.CustomMasterUrl; subWeb.MasterUrl = rootWeb.CustomMasterUrl; subWeb.Update(); context.Load(subWeb); context.ExecuteQuery(); }
/// <summary> /// Adds a new child Web (site) to a parent Web. /// </summary> /// <param name="parentWeb">The parent Web (site) to create under</param> /// <param name="title">The title of the new site. </param> /// <param name="leafUrl">A string that represents the URL leaf name.</param> /// <param name="description">The description of the new site. </param> /// <param name="template">The name of the site template to be used for creating the new site. </param> /// <param name="language">The locale ID that specifies the language of the new site. </param> /// <param name="inheritPermissions">Specifies whether the new site will inherit permissions from its parent site.</param> /// <param name="inheritNavigation">Specifies whether the site inherits navigation.</param> public static Web CreateWeb(this Web parentWeb, string title, string leafUrl, string description, string template, int language, bool inheritPermissions = true, bool inheritNavigation = true) { // TODO: Check for any other illegal characters in SharePoint if (leafUrl.Contains('/') || leafUrl.Contains('\\')) { throw new ArgumentException("The argument must be a single web URL and cannot contain path characters.", "leafUrl"); } LoggingUtility.Internal.TraceInformation((int)EventId.CreateWeb, CoreResources.WebExtensions_CreateWeb, leafUrl, template); WebCreationInformation creationInfo = new WebCreationInformation() { Url = leafUrl, Title = title, Description = description, UseSamePermissionsAsParentSite = inheritPermissions, WebTemplate = template, Language = language }; Web newWeb = parentWeb.Webs.Add(creationInfo); newWeb.Navigation.UseShared = inheritNavigation; newWeb.Update(); parentWeb.Context.ExecuteQueryRetry(); return(newWeb); }
public void CreatenewSubsite(string url, string Username, SecureString password) { using (clientcntx = new ClientContext(url)) { clientcntx.Credentials = new SharePointOnlineCredentials(Username, password); WebCreationInformation crete = new WebCreationInformation(); crete.Url = "newsite1"; Console.WriteLine("Enter the title for share point site"); string title = Console.ReadLine(); crete.Title = title; webpage = clientcntx.Web.Webs.Add(crete); clientcntx.Load(webpage, w => w.Title); try { clientcntx.ExecuteQuery(); } catch (Exception e) { Console.WriteLine("Error : " + e); throw e; } Console.WriteLine("New site" + crete.Title); Console.ReadKey(); } }
/// <summary> /// Adds a new child Web (site) to a parent Web. /// </summary> /// <param name="parentWeb">The parent Web (site) to create under</param> /// <param name="title">The title of the new site. </param> /// <param name="leafUrl">A string that represents the URL leaf name.</param> /// <param name="description">The description of the new site. </param> /// <param name="template">The name of the site template to be used for creating the new site. </param> /// <param name="language">The locale ID that specifies the language of the new site. </param> /// <param name="inheritPermissions">Specifies whether the new site will inherit permissions from its parent site.</param> /// <param name="inheritNavigation">Specifies whether the site inherits navigation.</param> public static Web CreateWeb(this Web parentWeb, string title, string leafUrl, string description, string template, int language, bool inheritPermissions = true, bool inheritNavigation = true) { if (leafUrl.ContainsInvalidUrlChars()) { throw new ArgumentException("The argument must be a single web URL and cannot contain path characters.", "leafUrl"); } Log.Info(Constants.LOGGING_SOURCE, CoreResources.WebExtensions_CreateWeb, leafUrl, template); WebCreationInformation creationInfo = new WebCreationInformation() { Url = leafUrl, Title = title, Description = description, UseSamePermissionsAsParentSite = inheritPermissions, WebTemplate = template, Language = language }; Web newWeb = parentWeb.Webs.Add(creationInfo); newWeb.Navigation.UseShared = inheritNavigation; newWeb.Update(); parentWeb.Context.ExecuteQueryRetry(); return newWeb; }
public static void CreateWebSite(ClientContext clientContext) { Web web = clientContext.Web; string blogDescription = "A new blog Web site."; int blogLanguage = 1033; string blogTitle = "backend"; string webTemplate = "BLOG#0"; WebCreationInformation webCreationInformation = new WebCreationInformation(); webCreationInformation.Description = blogDescription; webCreationInformation.Title = blogTitle; webCreationInformation.Language = blogLanguage; webCreationInformation.WebTemplate = webTemplate; Web website = web.Webs.Add(webCreationInformation); clientContext.Load(website, website1 => website1.ServerRelativeUrl, website2 => website2.Created ); clientContext.ExecuteQuery(); Console.WriteLine("ServerRelativeurl:{0} Created:{1}", website.ServerRelativeUrl, website.Created); }
public Web CreateSubSite(Microsoft.SharePoint.Client.ClientContext ctx, Web hostWeb, string txtUrl, string template, string title, string description) { // Create web creation configuration WebCreationInformation information = new WebCreationInformation(); information.WebTemplate = template; information.Description = description; information.Title = title; information.Url = txtUrl; // Currently all english, could be extended to be configurable based on language pack usage information.Language = 1033; Microsoft.SharePoint.Client.Web newWeb = null; newWeb = hostWeb.Webs.Add(information); ctx.ExecuteQuery(); ctx.Load(newWeb); ctx.ExecuteQuery(); // Add sub site link override new LabHelper().AddJsLink(ctx, newWeb, this.Request); // Set oob theme to the just created site new LabHelper().SetThemeBasedOnName(ctx, newWeb, hostWeb, "Orange"); // All done, let's return the newly created site return(newWeb); }
public string PostCreateSubSites([FromBody] NewSite Site) { try { if (Site != null && !string.IsNullOrEmpty(Site.Name)) { WebCreationInformation wci = new WebCreationInformation(); wci.Url = Site.Name; wci.Title = Site.Name; wci.Description = Site.Name; wci.UseSamePermissionsAsParentSite = true; wci.WebTemplate = "STS#0"; wci.Language = 1033; Web w = context.Site.RootWeb.Webs.Add(wci); context.Load(w, website => website.Url ); context.ExecuteQuery(); return("El sitio " + Site.Name + " fue creado con exito. La URL es " + w.Url); } return("El nombre del sitio no puede ser vacio"); } catch (Exception e) { return(Site.Name + " no pudo ser creado, ya le envie la informacion del error al administrador"); } }
public ActionResult Index() { User spUser = null; var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { if (clientContext != null) { WebCreationInformation creation = new WebCreationInformation(); creation.Url = "web1"; creation.Title = "Web1"; Web newWeb = clientContext.Web.Webs.Add(creation); clientContext.Load(newWeb, w => w.Title); clientContext.ExecuteQuery(); spUser = clientContext.Web.CurrentUser; clientContext.Load(spUser, user => user.Title); clientContext.ExecuteQuery(); ViewBag.UserName = spUser.Title; } } return View(); }
public Uri BuildAppSite(string siteName) { try { // Load RootSite e.g. JusticeLeague Web rootSite = SharePointContext.Web; SharePointContext.Load(rootSite); //build new project site WebCreationInformation subsiteToCreationInfo = new WebCreationInformation() { Url = siteName.Replace(" ", ""), Title = siteName, Description = "For Justice!" }; Web newSubsite = SharePointContext.Web.Webs.Add(subsiteToCreationInfo); SharePointContext.Load(newSubsite, site => site.Lists); ListCollection lists = newSubsite.Lists; ListCreationInformation listCreationInfo = new ListCreationInformation() { Title = TASK_LIST_TITLE, TemplateType = 107, // ListTemplateType.Tasks, Description = "Complete these quests to save the city!" }; lists.Add(listCreationInfo); SharePointContext.ExecuteQuery(); return(new Uri(ConstructFullUrl(siteName.Replace(" ", "")))); } catch (Exception ex) { return(new Uri(ConstructFullUrl(siteName.Replace(" ", "")))); //Debug.WriteLine(ex.Message); //throw ex; } }
public static CSOMOperation CreateWeb(this CSOMOperation operation, string title, int?lcid, string url = "", string template = "") { operation.LogInfo($"Creating web {title}"); url = url.IsNotNullOrEmpty() ? url : operation.NormalizeUrl(title); Web rootWeb = operation.DecideWeb(); lcid = (int)((uint?)lcid ?? operation.DecideWeb().Language); operation.LogDebug($"Web creation information set to Title: {title}, Url: {url}, Lcid: {lcid}, Template: {template}"); WebCreationInformation webInformation = new WebCreationInformation { Title = title, Url = url, WebTemplate = template, Language = lcid.Value }; var web = rootWeb.Webs.Add(webInformation); operation.LoadWebWithDefaultRetrievals(web); operation.SetLevel(OperationLevels.Web, web); operation.ActionQueue.Enqueue(new DeferredAction { ClientObject = web, Action = DeferredActions.Load }); return(operation); }
public async Task <IActionResult> NewDoc([FromBody] SharePointDoc param) { try{ // Starting with ClientContext, the constructor requires a URL to the // server running SharePoint. //string teamURL = @"https://dddevops.sharepoint.com"; WebCreationInformation creation = new WebCreationInformation(); //context.Credentials = new NetworkCredential("khteh", "", "dddevops.onmicrosoft.com"); creation.Url = param.URL; creation.Title = param.Title; creation.Description = param.Description; creation.UseSamePermissionsAsParentSite = true; creation.WebTemplate = param.Template;//"STS#0"; creation.Language = 1033; Web newWeb = cc.Web.Webs.Add(creation); // Retrieve the new web information. cc.Load(newWeb, w => w.Id); //context.Load(newWeb); await cc.ExecuteQueryAsync(); return(StatusCode(newWeb.Id != Guid.Empty ? StatusCodes.Status201Created : StatusCodes.Status404NotFound)); } catch (Exception ex) { return(StatusCode(StatusCodes.Status500InternalServerError, ex)); } }
/********Create Subsite*********************/ public static void CreateNewSubsite(ClientContext clientcntx) { // clientcntx.Credentials = new SharePointOnlineCredentials(Username, password); WebCreationInformation crete = new WebCreationInformation(); Console.WriteLine("Enter Site Name"); crete.Url = Console.ReadLine().Trim().Replace(" ", ""); Console.WriteLine("Enter the title for share point site"); crete.Title = Console.ReadLine(); clientcntx.Web.Webs.Add(crete); clientcntx.Load(clientcntx.Web, w => w.Title); try { clientcntx.ExecuteQuery(); } catch (Exception e) { Console.WriteLine("Error : " + e); throw e; } Console.WriteLine("New site" + crete.Title); Console.ReadKey(); }
public ActionResult Index(string Title, string SPHostUrl) { ViewBag.SPHostUrl = SPHostUrl; if (!string.IsNullOrEmpty(Title)) { var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext); using (var ctx = spContext.CreateUserClientContextForSPHost()) { if (ctx != null) { //ctx.Web.Title = Title; //ctx.Web.Update(); //ctx.ExecuteQuery(); WebCreationInformation info = new WebCreationInformation(); info.Url = Title; //TODO Remove äöå from title and spaces from url info.Title = Title; info.Language = 1033; info.WebTemplate = "STS#0"; info.Description = "yo"; ctx.Web.Webs.Add(info); ctx.ExecuteQuery(); } } } return(View()); }
public Web CreateSubSite(Microsoft.SharePoint.Client.ClientContext ctx, Web hostWeb, string txtUrl, string template, string title, string description) { // Create web creation configuration WebCreationInformation information = new WebCreationInformation(); information.WebTemplate = template; information.Description = description; information.Title = title; information.Url = txtUrl; // Currently all english, could be extended to be configurable based on language pack usage information.Language = 1033; Microsoft.SharePoint.Client.Web newWeb = null; newWeb = hostWeb.Webs.Add(information); ctx.ExecuteQuery(); ctx.Load(newWeb); ctx.ExecuteQuery(); // Add sub site link override new LabHelper().AddJsLink(ctx, newWeb, this.Request); // Set oob theme to the just created site new LabHelper().SetThemeBasedOnName(ctx, newWeb, hostWeb, "Orange"); // All done, let's return the newly created site return newWeb; }
/// <summary> /// Adds a new child Web (site) to a parent Web. /// </summary> /// <param name="parentWeb">The parent Web (site) to create under</param> /// <param name="title">The title of the new site. </param> /// <param name="leafUrl">A string that represents the URL leaf name.</param> /// <param name="description">The description of the new site. </param> /// <param name="template">The name of the site template to be used for creating the new site. </param> /// <param name="language">The locale ID that specifies the language of the new site. </param> /// <param name="inheritPermissions">Specifies whether the new site will inherit permissions from its parent site.</param> /// <param name="inheritNavigation">Specifies whether the site inherits navigation.</param> public static Web CreateWeb(this Web parentWeb, string title, string leafUrl, string description, string template, int language, bool inheritPermissions = true, bool inheritNavigation = true) { if (leafUrl.ContainsInvalidUrlChars()) { throw new ArgumentException("The argument must be a single web URL and cannot contain path characters.", "leafUrl"); } Log.Info(Constants.LOGGING_SOURCE, CoreResources.WebExtensions_CreateWeb, leafUrl, template); WebCreationInformation creationInfo = new WebCreationInformation() { Url = leafUrl, Title = title, Description = description, UseSamePermissionsAsParentSite = inheritPermissions, WebTemplate = template, Language = language }; Web newWeb = parentWeb.Webs.Add(creationInfo); newWeb.Navigation.UseShared = inheritNavigation; newWeb.Update(); parentWeb.Context.ExecuteQueryRetry(); return(newWeb); }
/// <summary> /// Adds a new child Web (site) to a parent Web. /// </summary> /// <param name="parentWeb">The parent Web (site) to create under</param> /// <param name="title">The title of the new site. </param> /// <param name="leafUrl">A string that represents the URL leaf name.</param> /// <param name="description">The description of the new site. </param> /// <param name="template">The name of the site template to be used for creating the new site. </param> /// <param name="language">The locale ID that specifies the language of the new site. </param> /// <param name="inheritPermissions">Specifies whether the new site will inherit permissions from its parent site.</param> /// <param name="inheritNavigation">Specifies whether the site inherits navigation.</param> public static Web CreateWeb(this Web parentWeb, string title, string leafUrl, string description, string template, int language, bool inheritPermissions = true, bool inheritNavigation = true) { // TODO: Check for any other illegal characters in SharePoint if (leafUrl.Contains('/') || leafUrl.Contains('\\')) { throw new ArgumentException("The argument must be a single web URL and cannot contain path characters.", "leafUrl"); } LoggingUtility.Internal.TraceInformation((int)EventId.CreateWeb, CoreResources.WebExtensions_CreateWeb, leafUrl, template); WebCreationInformation creationInfo = new WebCreationInformation() { Url = leafUrl, Title = title, Description = description, UseSamePermissionsAsParentSite = inheritPermissions, WebTemplate = template, Language = language }; Web newWeb = parentWeb.Webs.Add(creationInfo); newWeb.Navigation.UseShared = inheritNavigation; newWeb.Update(); parentWeb.Context.ExecuteQuery(); return newWeb; }
public void CreateHRSubsite() { try { WebCreationInformation webCreationInfo = new WebCreationInformation(); // This is relative URL of the url provided in context webCreationInfo.Url = "HR"; webCreationInfo.Title = "HR Department"; webCreationInfo.Description = "Subsite for HR"; // This will inherit permission from parent site webCreationInfo.UseSamePermissionsAsParentSite = true; // "STS#0" is the code for 'Team Site' template webCreationInfo.WebTemplate = "STS#0"; webCreationInfo.Language = 1033; Web web = tenantContext.Site.RootWeb.Webs.Add(webCreationInfo); tenantContext.Load(web); tenantContext.ExecuteQuery(); } catch (Exception) { } }
public override Web CreateSubSite(SiteInformation siteRequest, Template template) { Web newWeb; int pos = siteRequest.Url.LastIndexOf("/"); string parentUrl = siteRequest.Url.Substring(0, pos); string subSiteUrl = siteRequest.Url.Substring(pos + 1, siteRequest.Url.Length); Log.Info("Provisioning.Common.Office365SiteProvisioningService.CreateSubSite", PCResources.SiteCreation_Creation_Starting, siteRequest.Url); Uri siteUri = new Uri(siteRequest.Url); Uri subSiteParent = new Uri(parentUrl); string realm = TokenHelper.GetRealmFromTargetUrl(subSiteParent); string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, subSiteParent.Authority, realm).AccessToken; using (var ctx = TokenHelper.GetClientContextWithAccessToken(parentUrl, accessToken)) { try { Stopwatch _timespan = Stopwatch.StartNew(); try { // Get a reference to the parent Web Web parentWeb = ctx.Web; // Create the new sub site as a new child Web WebCreationInformation webinfo = new WebCreationInformation(); webinfo.Description = siteRequest.Description; webinfo.Language = (int)siteRequest.Lcid; webinfo.Title = siteRequest.Title; webinfo.Url = subSiteUrl; webinfo.UseSamePermissionsAsParentSite = true; webinfo.WebTemplate = template.RootTemplate; newWeb = parentWeb.Webs.Add(webinfo); ctx.ExecuteQueryRetry(); } catch (ServerException ex) { var _message = string.Format("Error occured while provisioning site {0}, ServerErrorTraceCorrelationId: {1} Exception: {2}", siteRequest.Url, ex.ServerErrorTraceCorrelationId, ex); Log.Error("Provisioning.Common.Office365SiteProvisioningService.CreateSubSite", _message); throw; } _timespan.Stop(); Log.TraceApi("SharePoint", "Office365SiteProvisioningService.CreateSubSite", _timespan.Elapsed, "SiteUrl={0}", siteRequest.Url); } catch (Exception ex) { Log.Error("Provisioning.Common.Office365SiteProvisioningService.CreateSubSite", PCResources.SiteCreation_Creation_Failure, siteRequest.Url, ex.Message, ex); throw; } Log.Info("Provisioning.Common.Office365SiteProvisioningService.CreateSubSite", PCResources.SiteCreation_Creation_Successful, siteRequest.Url); }; return(newWeb); }
public static string createSubSite(SiteRequest siteRequest) { try { var o365SecurePassword = Common.getSecureString(Configuration.strO365AdminPassword); var O365Context = new AuthenticationManager().GetSharePointOnlineAuthenticatedContextTenant(siteRequest.ParentSiteUrl, Configuration.strO365AdminId, o365SecurePassword); O365Context.Load(O365Context.Web); O365Context.ExecuteQuery(); WebCreationInformation wci = new WebCreationInformation(); wci.Url = siteRequest.URLName; wci.Title = siteRequest.Title; wci.Description = siteRequest.Description; wci.WebTemplate = siteRequest.Template; wci.UseSamePermissionsAsParentSite = true; wci.Language = 1033; Web subSite = O365Context.Site.RootWeb.Webs.Add(wci); O365Context.Load(subSite, w => w.AllProperties, w => w.Title, w => w.Url); O365Context.ExecuteQuery(); return("Sub-Site : " + subSite.Title + " created successfully. This is your sub-site URL: " + subSite.Url); } catch (Exception ex) { throw ex; } }
static void Main(string[] args) { string targetSiteURL = @"https://xxx.sharepoint.com/sites/xxx"; var login = "******"; var password = "******"; SharePointOnlineCredentials onlineCredentials = new SharePointOnlineCredentials(login, password); ClientContext ctx = new ClientContext(targetSiteURL); ctx.Credentials = onlineCredentials; WebCreationInformation wci = new WebCreationInformation(); wci.Url = "Site1"; // This url is relative to the url provided in the context wci.Title = "Site 1"; wci.UseSamePermissionsAsParentSite = true; wci.WebTemplate = "STS#0"; wci.Language = 1033; var newWeb = ctx.Web.Webs.Add(wci); ctx.Load(newWeb, w => w.Title); ctx.ExecuteQueryAsync(); Console.WriteLine("Web title:" + newWeb.Title); Console.ReadKey(); }
public static void CreateSubWeb(string scurl, string subwebname, string title, string desc) { string UserName = "******"; //Supply your User Name OR this could be done using App Only in Azure AD string Password = "******"; //Supply your own or this would go away if you used Azure AD by registering an App usign Azure AD using (ClientContext ctx = new ClientContext(scurl)) { SecureString passWord = new SecureString(); foreach (char c in Password.ToCharArray()) { passWord.AppendChar(c); } ctx.Credentials = new SharePointOnlineCredentials(UserName, passWord); WebCreationInformation wci = new WebCreationInformation(); wci.Url = subwebname; // This url is relative to the url provided in the context wci.Title = title; wci.Description = desc; wci.UseSamePermissionsAsParentSite = true; wci.WebTemplate = "STS#0"; wci.Language = 1033; Web w = ctx.Site.RootWeb.Webs.Add(wci); ctx.ExecuteQuery(); } }
static void Main(string[] args) { string url = "http://win-k1qikcue0no:85/"; string destription = "Create this site CSOM approch"; int languge = 1033; string title = "NewSite"; string SiteURL = "NewSite"; bool sitePremissions = false; string siteTemplate = "STS#0"; ClientContext context = new ClientContext(url); Web web = context.Web; WebCreationInformation webCreationInformation = new WebCreationInformation(); webCreationInformation.Description = destription; webCreationInformation.Language = languge; webCreationInformation.Title = title; webCreationInformation.Url = SiteURL; webCreationInformation.UseSamePermissionsAsParentSite = sitePremissions; webCreationInformation.WebTemplate = siteTemplate; Web newWeb = web.Webs.Add(webCreationInformation); context.Load(newWeb, w => w.Title, w => w.Description); context.ExecuteQuery(); Console.WriteLine($"Title {newWeb.Title}; Description: {newWeb.Description}"); Console.ReadKey(); }
private void createSubsites(SourceSiteCollectionSettings sourceSiteColl, string destinationSiteCollectionURL, string SiteCollectionURL, string username, string password) { AuthenticationManager am = new AuthenticationManager(); using (ClientContext ctx = am.GetSharePointOnlineAuthenticatedContextTenant(SiteCollectionURL, username, password)) { foreach (SubsiteDef s in sourceSiteColl.Subsites) { try { WebCreationInformation WCI = new WebCreationInformation(); WCI.Url = s.Url; WCI.Title = s.Title; WCI.WebTemplate = s.WebTemplate; WCI.Language = int.Parse(s.Langauage.ToString()); Web w = ctx.Web.Webs.Add(WCI); ctx.ExecuteQuery(); System.Threading.Thread.Sleep(5000); //create the library foreach (ListDef l in sourceSiteColl.Lists) { if (!ctx.Web.ListExists(l.Name)) { try { ListCreationInformation lci = new ListCreationInformation(); lci.TemplateType = l.TemplateType; lci.Title = l.Name; lci.Description = l.Description; ctx.Site.RootWeb.Lists.Add(lci); ctx.ExecuteQuery(); } catch (Exception ex) { MessageBox.Show($"error on moving {l.Name}, error: {ex.Message}"); } } else { //MessageBox.Show("library exist"); } } // end of library creation } catch (Exception e) { MessageBox.Show(e.Message); } } } }
private static Web Auto_CreateSubSite(string siteCollectionUrl, string title, string description, string webtemplateid, string url) { Web newWeb = null; Uri site_Uri = new Uri(siteCollectionUrl); //Get the realm for the URL string realm = TokenHelper.GetRealmFromTargetUrl(site_Uri); //Get the access token for the URL. string accessToken = TokenHelper.GetAppOnlyAccessToken( TokenHelper.SharePointPrincipal, site_Uri.Authority, realm).AccessToken; try { using (var sitectx = TokenHelper.GetClientContextWithAccessToken(site_Uri.ToString(), accessToken)) { //sitectx.Credentials = new SharePointOnlineCredentials(userName, pwd); sitectx.RequestTimeout = Timeout.Infinite; var web = sitectx.Web; sitectx.Load(web.Webs); sitectx.ExecuteQuery(); // Create web creation configuration var information = new WebCreationInformation() { WebTemplate = webtemplateid, Description = description, Title = title, Url = url, UseSamePermissionsAsParentSite = true }; // Currently all english, could be extended to be configurable based on language pack usage information.Language = 1033; newWeb = web.Webs.Add(information); sitectx.ExecuteQuery(); sitectx.Load(newWeb); sitectx.ExecuteQuery(); } Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("Created Subsite {0}" + newWeb.Title); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("Error occurred while creating subsite {0} with error {1}", title, ex.Message); } return(newWeb); }
/// <summary> /// Creates/returns News subsite obj. /// </summary> /// <param name="ctx"></param> /// <returns></returns> private static Web CreateOrGetSubsite(ClientContext ctx, String webName, String subsiteName, String description) { try { Console.WriteLine(String.Format("\nCreating subsite {0}, please wait...", subsiteName)); Web web; Web newWeb = null; var site = ctx.Site; ctx.Load(site, r => r.RootWeb); ctx.ExecuteQuery(); var webs = site.RootWeb.Webs; ctx.Load(webs); ctx.ExecuteQuery(); web = webs.Any(r => r.Title == webName) == true?webs.FirstOrDefault(r => r.Title == webName) : site.RootWeb; ctx.Load(web, w => w.Webs); ctx.ExecuteQuery(); if (!web.Webs.Any(r => r.Title == subsiteName)) { try { newWeb = web.CreateWeb(new OfficeDevPnP.Core.Entities.SiteEntity { Template = "blankinternet#0", Description = description, Title = subsiteName, Url = subsiteName }, true, true); } catch { ctx.RequestTimeout = 10 * 60 * 1000; var information = new WebCreationInformation { Description = description, Title = subsiteName, Url = subsiteName, UseSamePermissionsAsParentSite = true, WebTemplate = "blankinternet#0" }; newWeb = web.Webs.Add(information); ctx.ExecuteQueryRetry(); } } else { newWeb = web.Webs.FirstOrDefault(r => r.Title == subsiteName); } return(newWeb); } catch (Exception) { throw; } }
protected static Web CreateSubSite(ClientContext ctx, string Title, string Url, string Template) { WebCreationInformation wci_projects = new WebCreationInformation(); wci_projects.Title = Title; wci_projects.Url = Url; wci_projects.UseSamePermissionsAsParentSite = true; wci_projects.WebTemplate = Template; wci_projects.Language = 1033; //LCID Web web_project = ctx.Web.Webs.Add(wci_projects); return(web_project); }
private static void CreateSite(ClientContext clientContext, string siteName, string siteNameUrl) { if (null == clientContext) { throw new ArgumentNullException("clientContext"); } if (String.IsNullOrEmpty(siteName)) { throw new ArgumentNullException("siteName"); } if (String.IsNullOrEmpty(siteNameUrl)) { throw new ArgumentNullException("siteNameUrl"); } // Create a new Site clientContext.Load(clientContext.Web); clientContext.ExecuteQuery(); // Get available templates. var templates = clientContext.Web.GetAvailableWebTemplates(1033, true); clientContext.Load(templates); clientContext.ExecuteQuery(); var templateName = "STS#1"; var templateStr = AppHelper.GetProperty(clientContext, Constants.TEMPLATENAME_PROPERY); if (null != templateStr) { // See if template is installed. var template = templates.FirstOrDefault(wt => 0 == String.Compare(wt.Name, templateStr.ToString(), StringComparison.OrdinalIgnoreCase)); if (null != template) { templateName = template.Name; } } var uniquePerms = AppHelper.GetProperty(clientContext, Constants.UNIQUEPERMS_PROPERTY); var useUniqePerms = uniquePerms != null && 0 == String.Compare(uniquePerms.ToString(), "TRUE", StringComparison.OrdinalIgnoreCase); var webCreation = new WebCreationInformation { Title = siteName, Description = "", Url = siteNameUrl, WebTemplate = templateName, UseSamePermissionsAsParentSite = !useUniqePerms }; var newWeb = clientContext.Web.Webs.Add(webCreation); clientContext.Load(newWeb, w => w.Title); clientContext.ExecuteQuery(); }
/// <summary> /// This is simple demo on sub site creation based on selected "template" with configurable options /// </summary> /// <param name="txtUrl"></param> /// <param name="template"></param> /// <param name="title"></param> /// <param name="description"></param> /// <param name="cc"></param> /// <param name="page"></param> /// <param name="configuration"></param> /// <returns></returns> public Web CreateSubSite(string txtUrl, string template, string title, string description, Microsoft.SharePoint.Client.ClientContext cc, Page page, XDocument baseConfiguration, bool isChildSite = false, Web subWeb = null) { // Resolve the template configuration to be used for chosen template XElement templateConfig = GetTemplateConfig(template, baseConfiguration); string siteTemplate = SolveUsedTemplate(template, templateConfig); // Create web creation configuration WebCreationInformation information = new WebCreationInformation(); information.WebTemplate = siteTemplate; information.Description = description; information.Title = title; information.Url = txtUrl; // Currently all english, could be extended to be configurable based on language pack usage information.Language = 1033; Microsoft.SharePoint.Client.Web newWeb = null; //if it's child site from xml, let's do somethign else if (!isChildSite) { // Load host web and add new web to it. Microsoft.SharePoint.Client.Web web = cc.Web; cc.Load(web); cc.ExecuteQuery(); newWeb = web.Webs.Add(information); } else { newWeb = subWeb.Webs.Add(information); } cc.ExecuteQuery(); cc.Load(newWeb); cc.ExecuteQuery(); DeployFiles(cc, newWeb, templateConfig); DeployCustomActions(cc, newWeb, templateConfig); DeployLists(cc, newWeb, templateConfig); DeployNavigation(cc, newWeb, templateConfig); DeployTheme(cc, newWeb, templateConfig, baseConfiguration); SetSiteLogo(cc, newWeb, templateConfig); if (!isChildSite) { DeploySubSites(cc, newWeb, templateConfig, page, baseConfiguration); } // All done, let's return the newly created site return(newWeb); }
public void CreateSubSite(ClientContext context) { WebCreationInformation webCreationInformation = new WebCreationInformation { Url = Constants.SUBSITE, Title = "HR Subsite", UseSamePermissionsAsParentSite = true, WebTemplate = "STS#0" // 'Team Site' template }; context.Site.RootWeb.Webs.Add(webCreationInformation); context.ExecuteQuery(); }
public static void createNewWebsite(ClientContext context) { WebCreationInformation creation = new WebCreationInformation(); Console.WriteLine("Enter the web endpoint on which this site will be hosted"); creation.Url = Console.ReadLine(); Console.WriteLine("Enter the site name which is going to be hosted at url web1"); creation.Title = Console.ReadLine(); Web newWeb = context.Web.Webs.Add(creation); // Retrieve the new web information. context.Load(newWeb, w => w.Title); context.ExecuteQuery(); Console.WriteLine(newWeb.Title); }
public void CreateNewWebsite() { var context = new ClientContext(_baseUrl); WebCreationInformation creation = new WebCreationInformation(); creation.Url = "web1"; creation.Title = "Hello web1"; Web newWeb = context.Web.Webs.Add(creation); // Retrieve the new web information. context.Load(newWeb, w => w.Title); // context.ExecuteQuery(); Console.WriteLine(newWeb.Title); }
public override SPDGWeb AddWeb(string url, string siteName, string description, uint lcid, string templateName, bool useUniquePermissions, bool convertIfThere) { WebCreationInformation creation = new WebCreationInformation(); creation.Url = url; creation.Title = siteName; creation.Description = description; creation.Language = (int)lcid; creation.UseSamePermissionsAsParentSite = !useUniquePermissions; creation.WebTemplate = templateName; Web newWeb = _web.Webs.Add(creation); _context.Load(newWeb); _context.ExecuteQuery(); return(new SPDGClientWeb(newWeb, this, _context, _site)); }
public SimWeb AddWeb(WebCreationInformation options) { var url = new Uri(Parent.Url.TrimEnd('/') + '/' + options.Url); var simWeb = new SimWeb { Title = options.Title, Url = url.AbsoluteUri.TrimEnd('/'), ServerRelativeUrl = url.AbsolutePath, Description = options.Description }; // todo: add other properties this.Add(simWeb.Instance); return(simWeb); }
internal string CreateWeb(string siteName, string siteTitle, string siteDescription, string templateName) { var webCreationInformation = new WebCreationInformation { Title = siteTitle, Description = siteDescription, WebTemplate = templateName, Language = 1033, Url = siteName }; var newSite = _rootWeb.Webs.Add(webCreationInformation); _clientContext.Load(newSite); _clientContext.ExecuteQuery(); return string.Format("{0}{1}", _root, newSite.ServerRelativeUrl); }
public void Initialize() { Console.WriteLine("BrandingExtensionsTests.Initialise"); customColorFilePath = Path.Combine(Path.GetTempPath(), "custom.spcolor"); System.IO.File.WriteAllBytes(customColorFilePath, OfficeDevPnP.Core.Tests.Properties.Resources.custom); customBackgroundFilePath = Path.Combine(Path.GetTempPath(), "custombg.jpg"); Properties.Resources.custombg.Save(customBackgroundFilePath); testWebName = string.Format("Test_CL{0:yyyyMMddTHHmmss}", DateTimeOffset.Now); pageLayoutTestWeb = Setup(); using (var context = TestCommon.CreateClientContext()) { var wci1 = new WebCreationInformation(); wci1.Url = testWebName; wci1.Title = testWebName; wci1.WebTemplate = "CMSPUBLISHING#0"; var web1 = context.Web.Webs.Add(wci1); context.ExecuteQueryRetry(); web1.ActivateFeature(new Guid("41E1D4BF-B1A2-47F7-AB80-D5D6CBBA3092")); var wci2 = new WebCreationInformation(); wci2.Url = "a"; wci2.Title = "A"; wci2.WebTemplate = "CMSPUBLISHING#0"; var webA = web1.Webs.Add(wci2); context.ExecuteQueryRetry(); webA.ActivateFeature(new Guid("41E1D4BF-B1A2-47F7-AB80-D5D6CBBA3092")); var wci3 = new WebCreationInformation(); wci3.Url = "b"; wci3.Title = "B"; wci3.WebTemplate = "CMSPUBLISHING#0"; var webB = web1.Webs.Add(wci3); context.ExecuteQueryRetry(); webB.ActivateFeature(new Guid("41E1D4BF-B1A2-47F7-AB80-D5D6CBBA3092")); } }
public Web CreateSubSiteAndApplyProvisioningTemplate(ClientContext ctx, Web hostWeb, string txtUrl, string title, string description) { // Create web creation configuration WebCreationInformation information = new WebCreationInformation(); information.WebTemplate = listSites.SelectedItem.Value; information.Description = description; information.Title = title; information.Url = txtUrl; Web newWeb = null; newWeb = hostWeb.Webs.Add(information); ctx.ExecuteQuery(); ctx.Load(newWeb); ctx.ExecuteQuery(); ProvisioningTemplate _provisioningTemplate = GetProvTemplateAndMakeAdjustments(newWeb); newWeb.ApplyProvisioningTemplate(_provisioningTemplate); return newWeb; }
protected override void ProcessRecord() { base.ProcessRecord(); var ctx = base.Context; Web web = ctx.Site.OpenWeb(ParentWeb.Read()); var webci = new WebCreationInformation { Description = Description, Language = Language, Title = Title, Url = Url, UseSamePermissionsAsParentSite = !UniquePermissions, WebTemplate = WebTemplate }; Web newWeb = web.Webs.Add(webci); ctx.ExecuteQuery(); SPOWeb.LoadWeb(ctx, newWeb, true); WriteObject(new SPOWeb(newWeb)); }
public override SPDGWeb AddWeb(string url, string siteName, string description, uint lcid, string templateName, bool useUniquePermissions, bool convertIfThere) { WebCreationInformation creation = new WebCreationInformation(); creation.Url = url; creation.Title = siteName; creation.Description = description; creation.Language = (int) lcid; creation.UseSamePermissionsAsParentSite = !useUniquePermissions; creation.WebTemplate = templateName; Web newWeb = _web.Webs.Add(creation); _context.Load(newWeb); _context.ExecuteQuery(); return new SPDGClientWeb(newWeb, this, _context, _site); }
public override void DeployModel(object modelHost, DefinitionBase model) { var csomModelHost = modelHost.WithAssertAndCast<WebModelHost>("modelHost", value => value.RequireNotNull()); var webModel = model.WithAssertAndCast<WebDefinition>("model", value => value.RequireNotNull()); var parentWeb = GetParentWeb(csomModelHost); ; var context = parentWeb.Context; context.Load(parentWeb, w => w.RootFolder); context.Load(parentWeb, w => w.ServerRelativeUrl); context.ExecuteQuery(); var currentWebUrl = GetCurrentWebUrl(context, parentWeb, webModel); Web currentWeb = null; InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = null, ObjectType = typeof(Web), ObjectDefinition = model, ModelHost = modelHost }); InvokeOnModelEvent<WebDefinition, Web>(currentWeb, ModelEventType.OnUpdating); try { // TODO // how else??? using (var tmp = new ClientContext(currentWebUrl)) { tmp.Credentials = context.Credentials; tmp.Load(tmp.Web); tmp.ExecuteQuery(); } } catch (Exception) { var newWebInfo = new WebCreationInformation { Title = webModel.Title, Url = webModel.Url, Description = webModel.Description ?? string.Empty, WebTemplate = webModel.WebTemplate, UseSamePermissionsAsParentSite = !webModel.UseUniquePermission }; parentWeb.Webs.Add(newWebInfo); context.ExecuteQuery(); } using (var tmpContext = new ClientContext(currentWebUrl)) { tmpContext.Credentials = context.Credentials; var tmpWeb = tmpContext.Web; tmpContext.Load(tmpWeb); tmpContext.ExecuteQuery(); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = tmpWeb, ObjectType = typeof(Web), ObjectDefinition = model, ModelHost = modelHost }); InvokeOnModelEvent<WebDefinition, Web>(tmpContext.Web, ModelEventType.OnUpdated); tmpWeb.Update(); tmpContext.ExecuteQuery(); } }
public string CreateSite(string urlRoot_, string siteUrl_, string title_, string administrator_, XmlDocument params_) { using (ClientContext ctx = new ClientContext(urlRoot_)) { ctx.Credentials = SelectCreds(params_); Web rootWeb = ctx.Web; ctx.Load(rootWeb); ctx.ExecuteQuery(); // Site web WebCreationInformation wci = new WebCreationInformation(); wci.Url = siteUrl_; wci.Title = title_; wci.Language = Convert.ToInt32(params_.DocumentElement.Attributes["Langue"].Value); wci.WebTemplate = params_.DocumentElement.Attributes["Template"].Value; wci.Description = ""; wci.UseSamePermissionsAsParentSite = false; Web newWeb = ctx.Web.Webs.Add(wci); // Paramétrage du site // Masterpage /* newWeb.MasterUrl = ctx.Web.ServerRelativeUrl + params_.DocumentElement.Attributes["MasterPage"].Value; newWeb.CustomMasterUrl = ctx.Web.ServerRelativeUrl + params_.DocumentElement.Attributes["MasterPage"].Value; // Features à desactiver XmlNode feats = params_.DocumentElement.SelectSingleNode("/CNPCloud/FeaturesToDeactivate"); foreach (XmlNode xnf in feats.ChildNodes) { newWeb.Features.Remove(new Guid(xnf.Attributes["Id"].Value), true); } */ /* * Groupe administrateur du site en cours * */ XmlNode groupAdmin = params_.DocumentElement.SelectSingleNode("/CNPCloud/GroupAdmin"); GroupCreationInformation gcadmin = new GroupCreationInformation(); gcadmin.Title = siteUrl_ + groupAdmin.Attributes["Suffix"].Value; Group gAdmins = newWeb.SiteGroups.Add(gcadmin); gAdmins.Owner = ctx.Web.EnsureUser(params_.DocumentElement.Attributes["SPAdmin"].Value); UserCreationInformation uci = new UserCreationInformation(); uci.LoginName = administrator_; gAdmins.Users.Add(uci); gAdmins.Update(); SetRoleForGroup(ctx, newWeb, gAdmins, groupAdmin.Attributes["Role"].Value); newWeb.AssociatedOwnerGroup = gAdmins; newWeb.Update(); /* * Creation des groupes supplémentaire * ex: <GroupsToCreate> * <Group Suffix="_Collaborateurs" Role="Modification"/> */ XmlNode groups = params_.DocumentElement.SelectSingleNode("/CNPCloud/GroupsToCreate"); foreach (XmlNode xng in groups.ChildNodes) { GroupCreationInformation gci = new GroupCreationInformation(); gci.Title = siteUrl_ + xng.Attributes["Suffix"].Value; Group g = newWeb.SiteGroups.Add(gci); g.Owner = gAdmins; g.Update(); SetRoleForGroup(ctx, newWeb, g, xng.Attributes["Role"].Value); } /* GroupCreationInformation gcAdmin = new GroupCreationInformation(); gcAdmin.Title = siteUrl_ + "_Admins"; gAdmins = newWeb.SiteGroups.Add(gcAdmin); gAdmins.Owner = ctx.Web.EnsureUser(params_.Attributes["SPAdmin"].Value); UserCreationInformation uci = new UserCreationInformation(); uci.LoginName = administrator_; gAdmins.Users.Add(uci); gAdmins.Update(); SetRoleForGroup(ctx, newWeb, gAdmins, RoleType.WebDesigner); /* // Collab GroupCreationInformation gcCollab = new GroupCreationInformation(); gcCollab.Title = siteUrl_ + "_Collaborateurs"; Group gCollab = newWeb.SiteGroups.Add(gcCollab); gCollab.Owner = gAdmins; gCollab.Update(); SetRoleForGroup(ctx, newWeb, gCollab, RoleType.Contributor); // Lecteur GroupCreationInformation gcVisit = new GroupCreationInformation(); gcVisit.Title = siteUrl_ + "_Visiteurs"; Group gVisit = newWeb.SiteGroups.Add(gcVisit); gVisit.Owner = gAdmins; gVisit.Update(); SetRoleForGroup(ctx, newWeb, gVisit, RoleType.Reader); */ ctx.ExecuteQuery(); return "OK"; } }
private void CreateSubSite(SubSiteProvisioningJob job) { // Determine the reference URLs and relative paths String subSiteUrl = job.RelativeUrl; String siteCollectionUrl = PnPPartnerPackUtilities.GetSiteCollectionRootUrl(job.ParentSiteUrl); String parentSiteUrl = job.ParentSiteUrl; Console.WriteLine("Creating Site \"{0}\" as child Site of \"{1}\".", subSiteUrl, parentSiteUrl); using (ClientContext context = PnPPartnerPackContextProvider.GetAppOnlyClientContext(parentSiteUrl)) { context.RequestTimeout = Timeout.Infinite; // Get a reference to the parent Web Web parentWeb = context.Web; // Load the template from the source Templates Provider if (!String.IsNullOrEmpty(job.TemplatesProviderTypeName)) { ProvisioningTemplate template = null; var templatesProvider = PnPPartnerPackSettings.TemplatesProviders[job.TemplatesProviderTypeName]; if (templatesProvider != null) { template = templatesProvider.GetProvisioningTemplate(job.ProvisioningTemplateUrl); } if (template != null) { // Create the new sub site as a new child Web WebCreationInformation newWeb = new WebCreationInformation(); newWeb.Description = job.Description; newWeb.Language = job.Language; newWeb.Title = job.SiteTitle; newWeb.Url = subSiteUrl; newWeb.UseSamePermissionsAsParentSite = job.InheritPermissions; // Use the BaseSiteTemplate of the template, if any, otherwise // fallback to the pre-configured site template (i.e. STS#0) newWeb.WebTemplate = !String.IsNullOrEmpty(template.BaseSiteTemplate) ? template.BaseSiteTemplate : PnPPartnerPackSettings.DefaultSiteTemplate; Web web = parentWeb.Webs.Add(newWeb); context.ExecuteQueryRetry(); Console.WriteLine("Site \"{0}\" created.", subSiteUrl); // Apply the Provisioning Template Console.WriteLine("Applying Provisioning Template \"{0}\" to site.", job.ProvisioningTemplateUrl); // We do intentionally remove taxonomies, which are not supported in the AppOnly Authorization model // For further details, see the PnP Partner Pack documentation ProvisioningTemplateApplyingInformation ptai = new ProvisioningTemplateApplyingInformation(); // Write provisioning steps on console log ptai.MessagesDelegate += delegate (string message, ProvisioningMessageType messageType) { Console.WriteLine("{0} - {1}", messageType, messageType); }; ptai.ProgressDelegate += delegate (string message, int step, int total) { Console.WriteLine("{0:00}/{1:00} - {2}", step, total, message); }; // Exclude handlers not supported in App-Only ptai.HandlersToProcess ^= OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.TermGroups; ptai.HandlersToProcess ^= OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.SearchSettings; // Configure template parameters foreach (var key in template.Parameters.Keys) { if (job.TemplateParameters.ContainsKey(key)) { template.Parameters[key] = job.TemplateParameters[key]; } } // Fixup Title and Description template.WebSettings.Title = job.SiteTitle; template.WebSettings.Description = job.Description; // Apply the template to the target site web.ApplyProvisioningTemplate(template, ptai); // Save the template information in the target site var info = new SiteTemplateInfo() { TemplateProviderType = job.TemplatesProviderTypeName, TemplateUri = job.ProvisioningTemplateUrl, TemplateParameters = template.Parameters, AppliedOn = DateTime.Now, }; var jsonInfo = JsonConvert.SerializeObject(info); web.SetPropertyBagValue(PnPPartnerPackConstants.PropertyBag_TemplateInfo, jsonInfo); // Set site policy template if (!String.IsNullOrEmpty(job.SitePolicy)) { web.ApplySitePolicy(job.SitePolicy); } // Apply Tenant Branding, if requested if (job.ApplyTenantBranding) { var brandingSettings = PnPPartnerPackUtilities.GetTenantBrandingSettings(); using (var repositoryContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext( PnPPartnerPackSettings.InfrastructureSiteUrl)) { var brandingTemplate = BrandingJobHandler.PrepareBrandingTemplate(repositoryContext, brandingSettings); // Fixup Title and Description brandingTemplate.WebSettings.Title = job.SiteTitle; brandingTemplate.WebSettings.Description = job.Description; BrandingJobHandler.ApplyBrandingOnWeb(web, brandingSettings, brandingTemplate); } } Console.WriteLine("Applyed Provisioning Template \"{0}\" to site.", job.ProvisioningTemplateUrl); } } } }
public override void DeployModel(object modelHost, DefinitionBase model) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Extracting web from modelhost"); var parentWeb = ExtractWeb(modelHost); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Extracting host client context from model host"); var hostclientContext = ExtractHostClientContext(modelHost); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Casting web model definition"); var webModel = model.WithAssertAndCast<WebDefinition>("model", value => value.RequireNotNull()); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Loading Url/ServerRelativeUrl"); var context = parentWeb.Context; context.Load(parentWeb, w => w.Url); //context.Load(parentWeb, w => w.RootFolder); context.Load(parentWeb, w => w.ServerRelativeUrl); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()"); context.ExecuteQueryWithTrace(); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Extracting current web URL"); var currentWebUrl = GetCurrentWebUrl(context, parentWeb, webModel); TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Current web URL: [{0}].", currentWebUrl); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Loading existing web."); var currentWeb = GetExistingWeb(hostclientContext.Site, parentWeb, currentWebUrl); TraceService.Verbose((int)LogEventId.ModelProvisionUpdatingEventCall, "Calling OnUpdating event."); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = null, ObjectType = typeof(Web), ObjectDefinition = model, ModelHost = modelHost }); if (currentWeb == null) { TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new web"); var webUrl = webModel.Url; // Enhance web provision - handle '/' slash #620 // https://github.com/SubPointSolutions/spmeta2/issues/620 webUrl = UrlUtility.RemoveStartingSlash(webUrl); WebCreationInformation newWebInfo; if (string.IsNullOrEmpty(webModel.CustomWebTemplate)) { newWebInfo = new WebCreationInformation { Title = webModel.Title, Url = webUrl, Description = webModel.Description ?? string.Empty, WebTemplate = webModel.WebTemplate, UseSamePermissionsAsParentSite = !webModel.UseUniquePermission, Language = (int)webModel.LCID }; } else { var customWebTemplateName = webModel.CustomWebTemplate; // by internal name var templateCollection = parentWeb.GetAvailableWebTemplates(webModel.LCID, true); var templateResult = context.LoadQuery(templateCollection .Include(tmp => tmp.Name, tmp => tmp.Title) .Where(tmp => tmp.Name == customWebTemplateName)); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Trying to find template based on the given CustomWebTemplate and calling ExecuteQuery."); context.ExecuteQueryWithTrace(); if (templateResult.FirstOrDefault() == null) { // one more try by title templateResult = context.LoadQuery(templateCollection .Include(tmp => tmp.Name, tmp => tmp.Title) .Where(tmp => tmp.Title == customWebTemplateName)); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Trying to find template based on the given CustomWebTemplate and calling ExecuteQuery."); context.ExecuteQueryWithTrace(); } var template = templateResult.FirstOrDefault(); if (template == null) throw new SPMeta2ModelDeploymentException("Couldn't find custom web template: " + webModel.CustomWebTemplate); newWebInfo = new WebCreationInformation { Title = webModel.Title, Url = webModel.Url, Description = webModel.Description ?? string.Empty, WebTemplate = template.Name, UseSamePermissionsAsParentSite = !webModel.UseUniquePermission, Language = (int)webModel.LCID }; } TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Adding new web to the web collection and calling ExecuteQuery."); var newWeb = parentWeb.Webs.Add(newWebInfo); context.ExecuteQueryWithTrace(); MapProperties(newWeb, webModel); ProcessLocalization(newWeb, webModel); context.Load(newWeb); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()"); context.ExecuteQueryWithTrace(); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = newWeb, ObjectType = typeof(Web), ObjectDefinition = model, ModelHost = modelHost }); } else { TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Current web is not null. Updating Title/Description."); MapProperties(currentWeb, webModel); // locale is not available with CSOM yet ProcessLocalization(currentWeb, webModel); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentWeb, ObjectType = typeof(Web), ObjectDefinition = model, ModelHost = modelHost }); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "currentWeb.Update()"); currentWeb.Update(); context.ExecuteQueryWithTrace(); } }
/// <summary> /// /// </summary> /// <param name="web"></param> /// <param name="title"></param> /// <param name="description"></param> /// <param name="template"></param> /// <param name="language"></param> /// <param name="inheritPermissions"></param> /// <param name="inheritNavigation"></param> public static Web CreateSite(this Web web, string title, string url, string description, string template, int language, bool inheritPermissions = true, bool inheritNavigation = true) { WebCreationInformation wci = new WebCreationInformation(); wci.Url = url; wci.Title = title; wci.Description = description; wci.UseSamePermissionsAsParentSite = inheritPermissions; wci.WebTemplate = template; wci.Language = language; Web w = web.Webs.Add(wci); w.Navigation.UseShared = inheritNavigation; w.Update(); web.Context.ExecuteQuery(); return w; }
public Web CreateSubSite(ClientContext ctx, Web hostWeb, string txtUrl, string template, string title, string description) { // Create web creation configuration WebCreationInformation information = new WebCreationInformation(); information.WebTemplate = template; information.Description = description; information.Title = title; information.Url = txtUrl; // Currently all English, could be extended to be configurable based on language pack usage Web newWeb = null; newWeb = hostWeb.Webs.Add(information); ctx.ExecuteQuery(); ctx.Load(newWeb); ctx.ExecuteQuery(); // Add sub site link override new subsitehelper().AddJsLink(ctx, newWeb, this.Request); // Let's first upload the custom theme to host web new subsitehelper().DeployThemeToWeb(hostWeb, "MyCustomTheme", HostingEnvironment.MapPath(string.Format("~/{0}", "Pages/subsite/resources/custom.spcolor")), string.Empty, HostingEnvironment.MapPath(string.Format("~/{0}", "Pages/subsite/resources/custombg.jpg")), string.Empty); // Setting the Custom theme to host web new subsitehelper().SetThemeBasedOnName(ctx, newWeb, hostWeb, "MyCustomTheme"); // Set logo to the site // Get the path to the file which we are about to deploy new subsitehelper().UploadAndSetLogoToSite(ctx.Web, HostingEnvironment.MapPath( string.Format("~/{0}", "Pages/subsite/resources/template-icon.png"))); // All done, let's return the newly created site return newWeb; }
/// <summary> /// This is simple demo on sub site creation based on selected "template" with configurable options /// </summary> /// <param name="txtUrl"></param> /// <param name="template"></param> /// <param name="title"></param> /// <param name="description"></param> /// <param name="cc"></param> /// <param name="page"></param> /// <param name="configuration"></param> /// <returns></returns> public Web CreateSubSite(string txtUrl, string template, string title, string description, Microsoft.SharePoint.Client.ClientContext cc, Page page, XDocument baseConfiguration, bool isChildSite = false, Web subWeb = null) { // Resolve the template configuration to be used for chosen template XElement templateConfig = GetTemplateConfig(template, baseConfiguration); string siteTemplate = SolveUsedTemplate(template, templateConfig); // Create web creation configuration WebCreationInformation information = new WebCreationInformation(); information.WebTemplate = siteTemplate; information.Description = description; information.Title = title; information.Url = txtUrl; // Currently all english, could be extended to be configurable based on language pack usage information.Language = 1033; Microsoft.SharePoint.Client.Web newWeb = null; //if it's child site from xml, let's do somethign else if (!isChildSite) { // Load host web and add new web to it. Microsoft.SharePoint.Client.Web web = cc.Web; cc.Load(web); cc.ExecuteQuery(); newWeb = web.Webs.Add(information); } else { newWeb = subWeb.Webs.Add(information); } cc.ExecuteQuery(); cc.Load(newWeb); cc.ExecuteQuery(); DeployFiles(cc, newWeb, templateConfig); DeployCustomActions(cc, newWeb, templateConfig); DeployLists(cc, newWeb, templateConfig); DeployNavigation(cc, newWeb, templateConfig); DeployTheme(cc, newWeb, templateConfig, baseConfiguration); SetSiteLogo(cc, newWeb, templateConfig); if (!isChildSite) { DeploySubSites(cc, newWeb, templateConfig, page, baseConfiguration); } // All done, let's return the newly created site return newWeb; }
public SPRemoteEventResult ProcessEvent(SPRemoteEventProperties properties) { SPRemoteEventResult result = new SPRemoteEventResult(); try { using (ClientContext clientContext = TokenHelper.CreateAppEventClientContext(properties, useAppWeb: false)) { if (clientContext != null) { /*INSTALLED*/ if (properties.EventType == SPRemoteEventType.AppInstalled) { //Enable Publishing Feature Guid id = new Guid(PUBLISHING_INFRASTRUCTURE_FEATURE_ID); var query1 = from f in clientContext.Site.Features where f.DefinitionId == id select f; var features = clientContext.LoadQuery(query1); clientContext.ExecuteQuery(); if (features.Count() == 0) { clientContext.Site.Features.Add(id, false, FeatureDefinitionScope.None); clientContext.ExecuteQuery(); } //Create Search Center var query2 = from w in clientContext.Site.RootWeb.Webs where w.Title == SEARCH_CENTER_TITLE select w; var webs = clientContext.LoadQuery(query2); clientContext.ExecuteQuery(); if (webs.Count() == 0) { WebCreationInformation webCreationInfo = new WebCreationInformation(); webCreationInfo.Url = SEARCH_CENTER_URL; webCreationInfo.Title = SEARCH_CENTER_TITLE; webCreationInfo.UseSamePermissionsAsParentSite = true; webCreationInfo.WebTemplate = SEARCH_CENTER_TEMPLATE; Web newWeb = clientContext.Web.Webs.Add(webCreationInfo); clientContext.ExecuteQuery(); } //Upload Display template List gallery = clientContext.Site.RootWeb.Lists.GetByTitle(MASTER_PAGE_GALLERY_TITLE); Folder folder = clientContext.Site.RootWeb.GetFolderByServerRelativeUrl(DISPLAY_TEMPLATE_FOLDER_URL); clientContext.ExecuteQuery(); var query3 = from f in folder.Files where f.Name == DISPLAY_TEMPLATE_NAME select f; var files = clientContext.LoadQuery(query3); clientContext.ExecuteQuery(); if (files.Count() == 0) { System.IO.FileStream fs = System.IO.File.Open( HostingEnvironment.MapPath(DISPLAY_TEMPLATE_PATH), System.IO.FileMode.Open, System.IO.FileAccess.Read); FileCreationInformation fileCreationInfo = new FileCreationInformation(); fileCreationInfo.ContentStream = fs; fileCreationInfo.Url = DISPLAY_TEMPLATE_NAME; fileCreationInfo.Overwrite = true; Microsoft.SharePoint.Client.File newFile = folder.Files.Add(fileCreationInfo); clientContext.Load(newFile); clientContext.ExecuteQuery(); } //Set web part properties webs = clientContext.LoadQuery(query2); clientContext.ExecuteQuery(); File resultsPage = webs.First().GetFileByServerRelativeUrl(SEARCH_PAGE_URL); resultsPage.CheckOut(); clientContext.ExecuteQuery(); LimitedWebPartManager manager = resultsPage.GetLimitedWebPartManager(PersonalizationScope.Shared); var webPartDefs = manager.WebParts; clientContext.Load(webPartDefs, parts => parts.Include(part => part.WebPart.Properties), parts => parts.Include(part => part.WebPart.Title)); clientContext.ExecuteQuery(); foreach (var webPartDef in webPartDefs) { if (webPartDef.WebPart.Title == RESULTS_WEB_PART_TITLE) { webPartDef.WebPart.Properties[DATA_PROVIDER_PROPERTY] = "{\"QueryGroupName\":\"Default\",\"QueryPropertiesTemplateUrl\":\"sitesearch://webroot\",\"IgnoreQueryPropertiesTemplateUrl\":false,\"SourceID\":\"33b36a58-671f-4805-8db1-0078509b88c9\",\"SourceName\":\"InstallerResultSource\",\"SourceLevel\":\"SPSite\",\"CollapseSpecification\":\"\",\"QueryTemplate\":\"{searchboxquery}\",\"FallbackSort\":null,\"FallbackSortJson\":\"null\",\"RankRules\":null,\"RankRulesJson\":\"null\",\"AsynchronousResultRetrieval\":false,\"SendContentBeforeQuery\":true,\"BatchClientQuery\":true,\"FallbackLanguage\":-1,\"FallbackRankingModelID\":\"\",\"EnableStemming\":true,\"EnablePhonetic\":false,\"EnableNicknames\":false,\"EnableInterleaving\":true,\"EnableQueryRules\":true,\"EnableOrderingHitHighlightedProperty\":false,\"HitHighlightedMultivaluePropertyLimit\":-1,\"IgnoreContextualScope\":false,\"ScopeResultsToCurrentSite\":false,\"TrimDuplicates\":true,\"Properties\":{},\"PropertiesJson\":\"{}\",\"ClientType\":\"AllResultsQuery\",\"UpdateAjaxNavigate\":true,\"SummaryLength\":180,\"DesiredSnippetLength\":90,\"PersonalizedQuery\":false,\"FallbackRefinementFilters\":null,\"IgnoreStaleServerQuery\":true,\"RenderTemplateId\":\"\",\"AlternateErrorMessage\":null,\"Title\":\"\"}"; webPartDef.SaveWebPartChanges(); clientContext.ExecuteQuery(); } if (webPartDef.WebPart.Title == NAVIGATION_WEB_PART_TITLE) { webPartDef.DeleteWebPart(); clientContext.ExecuteQuery(); } } resultsPage.CheckIn("Modified by Search Installer.", CheckinType.MajorCheckIn); resultsPage.Publish("Modified by Search Installer."); clientContext.ExecuteQuery(); } /*UNINSTALLING*/ if (properties.EventType == SPRemoteEventType.AppUninstalling) { //Find Search Center var web = clientContext.Site.RootWeb; var query = from w in clientContext.Site.RootWeb.Webs where w.Url == SEARCH_CENTER_URL select w; var webs = clientContext.LoadQuery(query); clientContext.ExecuteQuery(); //Delete the Search Center if (webs.First() != null) { webs.First().DeleteObject(); clientContext.ExecuteQuery(); } } } } result.Status = SPRemoteEventServiceStatus.Continue; } catch (ServerException x) { #if DEBUG if (!System.Diagnostics.EventLog.SourceExists("Installer App Events")) System.Diagnostics.EventLog.CreateEventSource( "Installer App Events", "Application"); System.Diagnostics.EventLog.WriteEntry( "Installer App Events", x.Message); #endif result.Status = SPRemoteEventServiceStatus.Continue; } return result; }
public Web CreateNewSubSite(string webName, string webAddress, string webTemplateId, string parentRelativeAddress, bool deleteIfexists) { var parentWeb = this.currentSite.OpenWeb(parentRelativeAddress); this.ctx.Load(parentWeb, pa=>pa.Webs, pa => pa.Webs.Include(wb => wb.Title)); this.ctx.ExecuteQuery(); var alreadyExists = parentWeb.Webs.FirstOrDefault(wb => wb.Title == webName); if(alreadyExists!=null && !deleteIfexists) { Console.WriteLine("{0} already exists, exiting createsite.", webName); return null; } if(alreadyExists!=null && deleteIfexists) { Console.WriteLine("{0} deleting existing site.", webName); alreadyExists.DeleteObject(); ctx.ExecuteQuery(); } WebCreationInformation wci = new WebCreationInformation { Title = webName, Url = webAddress, Language = 1033, WebTemplate = webTemplateId, UseSamePermissionsAsParentSite = true }; var newWeb = parentWeb.Webs.Add(wci); ctx.Load(newWeb); ctx.ExecuteQuery(); return newWeb; }
private void CreatePublishingWeb(ClientContext wciCtx, string urlAndName) { int retryAttempts = 0; int retryCount = 10; int delay = 500; int backoffInterval = delay; // Do while retry attempt is less than retry count while (retryAttempts < retryCount) { try { var wci1 = new WebCreationInformation(); wci1.Url = urlAndName; wci1.Title = urlAndName; wci1.WebTemplate = "CMSPUBLISHING#0"; var web1 = wciCtx.Web.Webs.Add(wci1); wciCtx.ExecuteQueryRetry(); Console.WriteLine("Web {0} created", urlAndName); return; } catch (Microsoft.SharePoint.Client.ServerException ex) { Console.WriteLine(ex.ToDetailedString()); //retry Console.WriteLine("Site creation failed. Sleeping for {0} seconds before retrying.", backoffInterval); //Add delay for retry System.Threading.Thread.Sleep(backoffInterval); //Add to retry count and increase delay. retryAttempts++; backoffInterval = backoffInterval * 2; } } throw new Exception(string.Format("Maximum site creation retry attempts {0} has been reached.", retryCount)); }
private Web CreateTestTeamSubSite(Web parentWeb) { var siteUrl = GetRandomString(); var webInfo = new WebCreationInformation { Title = siteUrl, Url = siteUrl, Description = siteUrl, Language = 1033, UseSamePermissionsAsParentSite = true, WebTemplate = "STS#0" }; var web = parentWeb.Webs.Add(webInfo); parentWeb.Context.Load(web); parentWeb.Context.ExecuteQueryRetry(); return web; }
public override void DeployModel(object modelHost, DefinitionBase model) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Extracting web from modelhost"); var parentWeb = ExtractWeb(modelHost); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Extracting host client context from model host"); var hostclientContext = ExtractHostClientContext(modelHost); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Casting web model definition"); var webModel = model.WithAssertAndCast<WebDefinition>("model", value => value.RequireNotNull()); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Loading Url/ServerRelativeUrl"); var context = parentWeb.Context; context.Load(parentWeb, w => w.Url); //context.Load(parentWeb, w => w.RootFolder); context.Load(parentWeb, w => w.ServerRelativeUrl); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()"); context.ExecuteQueryWithTrace(); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Extracting current web URL"); var currentWebUrl = GetCurrentWebUrl(context, parentWeb, webModel); TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Current web URL: [{0}].", currentWebUrl); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Loading existing web."); var currentWeb = GetExistingWeb(hostclientContext.Site, parentWeb, currentWebUrl); TraceService.Verbose((int)LogEventId.ModelProvisionUpdatingEventCall, "Calling OnUpdating event."); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = null, ObjectType = typeof(Web), ObjectDefinition = model, ModelHost = modelHost }); InvokeOnModelEvent<WebDefinition, Web>(currentWeb, ModelEventType.OnUpdating); if (currentWeb == null) { TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new web"); var newWebInfo = new WebCreationInformation { Title = webModel.Title, Url = webModel.Url, Description = webModel.Description ?? string.Empty, WebTemplate = webModel.WebTemplate, UseSamePermissionsAsParentSite = !webModel.UseUniquePermission, Language = (int)webModel.LCID }; TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Adding new web to the web collection and calling ExecuteQuery."); var newWeb = parentWeb.Webs.Add(newWebInfo); context.ExecuteQueryWithTrace(); context.Load(newWeb); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()"); context.ExecuteQueryWithTrace(); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = newWeb, ObjectType = typeof(Web), ObjectDefinition = model, ModelHost = modelHost }); InvokeOnModelEvent<WebDefinition, Web>(newWeb, ModelEventType.OnUpdated); } else { TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Current web is not null. Updating Title/Description."); currentWeb.Title = webModel.Title; currentWeb.Description = webModel.Description ?? string.Empty; // locale is not available with CSOM yet InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentWeb, ObjectType = typeof(Web), ObjectDefinition = model, ModelHost = modelHost }); InvokeOnModelEvent<WebDefinition, Web>(currentWeb, ModelEventType.OnUpdated); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "currentWeb.Update()"); currentWeb.Update(); context.ExecuteQueryWithTrace(); } }
private void CreateSubSite(SubSiteProvisioningJob job) { // Determine the reference URLs and relative paths String subSiteUrl = job.RelativeUrl; String siteCollectionUrl = PnPPartnerPackUtilities.GetSiteCollectionRootUrl(job.ParentSiteUrl); String parentSiteUrl = job.ParentSiteUrl; Console.WriteLine("Creating Site \"{0}\" as child Site of \"{1}\".", subSiteUrl, parentSiteUrl); using (ClientContext context = PnPPartnerPackContextProvider.GetAppOnlyClientContext(parentSiteUrl)) { // Get a reference to the parent Web Web parentWeb = context.Web; // Create the new sub site as a new child Web WebCreationInformation newWeb = new WebCreationInformation(); newWeb.Description = job.Description; newWeb.Language = job.Language; newWeb.Title = job.SiteTitle; newWeb.Url = subSiteUrl; newWeb.UseSamePermissionsAsParentSite = job.InheritPermissions; newWeb.WebTemplate = PnPPartnerPackSettings.DefaultSiteTemplate; Web web = parentWeb.Webs.Add(newWeb); context.ExecuteQueryRetry(); Console.WriteLine("Site \"{0}\" created.", subSiteUrl); // Apply the Provisioning Template Console.WriteLine("Applying Provisioning Template \"{0}\" to site.", job.ProvisioningTemplateUrl); // Determine the reference URLs and file names String templatesSiteUrl = job.ProvisioningTemplateUrl.Substring(0, job.ProvisioningTemplateUrl.IndexOf(PnPPartnerPackConstants.PnPProvisioningTemplates)); String templateFileName = job.ProvisioningTemplateUrl.Substring(job.ProvisioningTemplateUrl.LastIndexOf("/") + 1); // Configure the XML file system provider XMLTemplateProvider provider = new XMLSharePointTemplateProvider(context, templatesSiteUrl, PnPPartnerPackConstants.PnPProvisioningTemplates); // Load the template from the XML stored copy ProvisioningTemplate template = provider.GetTemplate(templateFileName); template.Connector = provider.Connector; // We do intentionally remove taxonomies, which are not supported in the AppOnly Authorization model // For further details, see the PnP Partner Pack documentation ProvisioningTemplateApplyingInformation ptai = new ProvisioningTemplateApplyingInformation(); ptai.HandlersToProcess ^= OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.TermGroups; // Configure template parameters foreach (var key in template.Parameters.Keys) { if (job.TemplateParameters.ContainsKey(key)) { template.Parameters[key] = job.TemplateParameters[key]; } } // Apply the template to the target site web.ApplyProvisioningTemplate(template, ptai); Console.WriteLine("Applyed Provisioning Template \"{0}\" to site.", job.ProvisioningTemplateUrl); } }
public override Web CreateSubSite(SiteInformation siteRequest, Template template) { Web newWeb; int pos = siteRequest.Url.LastIndexOf("/"); string parentUrl = siteRequest.Url.Substring(0, pos); string subSiteUrl = siteRequest.Url.Substring(pos + 1, siteRequest.Url.Length); Log.Info("Provisioning.Common.Office365SiteProvisioningService.CreateSubSite", PCResources.SiteCreation_Creation_Starting, siteRequest.Url); Uri siteUri = new Uri(siteRequest.Url); Uri subSiteParent = new Uri(parentUrl); string realm = TokenHelper.GetRealmFromTargetUrl(subSiteParent); string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, subSiteParent.Authority, realm).AccessToken; using (var ctx = TokenHelper.GetClientContextWithAccessToken(parentUrl, accessToken)) { try { Stopwatch _timespan = Stopwatch.StartNew(); try { // Get a reference to the parent Web Web parentWeb = ctx.Web; // Create the new sub site as a new child Web WebCreationInformation webinfo = new WebCreationInformation(); webinfo.Description = siteRequest.Description; webinfo.Language = (int)siteRequest.Lcid; webinfo.Title = siteRequest.Title; webinfo.Url = subSiteUrl; webinfo.UseSamePermissionsAsParentSite = true; webinfo.WebTemplate = template.RootTemplate; newWeb = parentWeb.Webs.Add(webinfo); ctx.ExecuteQueryRetry(); } catch (ServerException ex) { var _message = string.Format("Error occured while provisioning site {0}, ServerErrorTraceCorrelationId: {1} Exception: {2}", siteRequest.Url, ex.ServerErrorTraceCorrelationId, ex); Log.Error("Provisioning.Common.Office365SiteProvisioningService.CreateSubSite", _message); throw; } _timespan.Stop(); Log.TraceApi("SharePoint", "Office365SiteProvisioningService.CreateSubSite", _timespan.Elapsed, "SiteUrl={0}", siteRequest.Url); } catch (Exception ex) { Log.Error("Provisioning.Common.Office365SiteProvisioningService.CreateSubSite", PCResources.SiteCreation_Creation_Failure, siteRequest.Url, ex.Message, ex); throw; } Log.Info("Provisioning.Common.Office365SiteProvisioningService.CreateSubSite", PCResources.SiteCreation_Creation_Successful, siteRequest.Url); }; return newWeb; }
/// <summary> /// Creates a new web /// </summary> /// <param name="url"></param> /// <param name="title"></param> /// <param name="locale"></param> /// <param name="description"></param> /// <param name="webtemplate"></param> /// <param name="useSamePermissionAsParentSite"></param> public static Web CreateWeb(string url, string title, int locale, string description, string webtemplate, Web web, ClientContext clientContext, bool useSamePermissionAsParentSite = false) { var webCreateInfo = new WebCreationInformation(); webCreateInfo.Description = description; webCreateInfo.Language = locale; webCreateInfo.Title = title; webCreateInfo.Url = url; webCreateInfo.UseSamePermissionsAsParentSite = useSamePermissionAsParentSite; webCreateInfo.WebTemplate = webtemplate; Web newWeb = web.Webs.Add(webCreateInfo); clientContext.Load(newWeb); clientContext.ExecuteQuery(); return newWeb; }