private static void CreateSiteCollectionFromTemplate(ClientContext cc, string tenantUrl, string newSiteUrl, string userName) { Tenant tenant = new Tenant(cc); SiteCreationProperties newsiteProp = new SiteCreationProperties(); newsiteProp.Lcid = 1033; newsiteProp.Owner = userName; newsiteProp.Title = "New Site"; newsiteProp.Url = newSiteUrl; newsiteProp.StorageMaximumLevel = 100; //MB newsiteProp.UserCodeMaximumLevel = 10; SpoOperation spoO = tenant.CreateSite(newsiteProp); cc.Load(spoO, i => i.IsComplete); cc.ExecuteQuery(); while (!spoO.IsComplete) { //Wait for 30 seconds and then try again System.Threading.Thread.Sleep(10000); spoO.RefreshLoad(); cc.ExecuteQuery(); Console.WriteLine("Site creation status: " + (spoO.IsComplete ? "completed" : "waiting")); } Console.WriteLine("SiteCollection Created."); }
public void CreateNewSiteCollection(string title, string name, string owner) { var url = string.Format("https://{0}-admin.sharepoint.com", _generatorDefinition.TenantName); using (ClientContext context = new ClientContext(url)) { context.Credentials = new SharePointOnlineCredentials(_generatorDefinition.Username, Utilities.Common.StringToSecureString(_generatorDefinition.Password)); var officeTenant = new Microsoft.Online.SharePoint.TenantAdministration.Tenant(context); var newSiteProperties = new SiteCreationProperties() { Url = string.Format("https://{0}.sharepoint.com/sites/{1}", _generatorDefinition.TenantName, name), Owner = _generatorDefinition.SiteCollOwnerLogin, Template = "STS#0", }; var spo= officeTenant.CreateSite(newSiteProperties); context.Load(spo, i => i.IsComplete); context.ExecuteQuery(); while (!spo.IsComplete) { System.Threading.Thread.Sleep(10000); spo.RefreshLoad(); context.ExecuteQuery(); } } }
/// <summary> /// Adds a SiteEntity by launching site collection creation and waits for the creation to finish /// </summary> /// <param name="tenant">A tenant object pointing to the context of a Tenant Administration site</param> /// <param name="properties">Describes the site collection to be created</param> public static void CreateSiteCollection(this Tenant tenant, SiteEntity properties) { SiteCreationProperties newsite = new SiteCreationProperties(); newsite.Url = properties.Url; newsite.Owner = properties.SiteOwnerLogin; newsite.Template = properties.Template; newsite.Title = properties.Title; newsite.StorageMaximumLevel = properties.StorageMaximumLevel; newsite.StorageWarningLevel = properties.StorageWarningLevel; newsite.TimeZoneId = properties.TimeZoneId; newsite.UserCodeMaximumLevel = properties.UserCodeMaximumLevel; newsite.UserCodeWarningLevel = properties.UserCodeWarningLevel; newsite.Lcid = properties.Lcid; try { tenant.CreateSite(newsite); tenant.Context.ExecuteQueryRetry(); } catch (Exception ex) { // Eat the siteSubscription exception to make the same code work for MT as on-prem April 2014 CU+ if (ex.Message.IndexOf("Parameter name: siteSubscription") == -1) { throw; } } }
protected void Button1_Click(object sender, EventArgs e) { Uri tenantAdministrationUrl = new Uri("https://dotnetrocks-admin.sharepoint.com/"); string accessToken = TokenHelper.GetAppOnlyAccessToken( TokenHelper.SharePointPrincipal, tenantAdministrationUrl.Authority, TokenHelper.GetRealmFromTargetUrl(tenantAdministrationUrl)).AccessToken; var newSite = new SiteCreationProperties() { Url = "https://dotnetrocks.sharepoint.com/sites/" + SiteName.Text, Owner = SiteOwner.Text, Template = "STS#0", // Team Site Title = "App Provisioned Site - " + SiteName.Text, StorageMaximumLevel = 1000, StorageWarningLevel = 500, TimeZoneId = 7, UserCodeMaximumLevel = 7, UserCodeWarningLevel = 1 }; using (var clientContext = TokenHelper.GetClientContextWithAccessToken(tenantAdministrationUrl.ToString(), accessToken)) { var tenant = new Tenant(clientContext); var spoOperation = tenant.CreateSite(newSite); clientContext.Load(spoOperation); clientContext.ExecuteQuery(); } }
public async Task <SiteCollection> CreateSiteCollectionAsync(SiteCollection siteCollection) { try { var endpoint = $"https://{configuration["SharePointTenantPrefix"]}.sharepoint.com"; var context = new ClientContext(endpoint); context.ExecutingWebRequest += ContextExecutingWebRequest; var tenant = new Tenant(context); var properties = new SiteCreationProperties() { Url = siteCollection.Url, Owner = siteCollection.Owner, Title = siteCollection.Title, Template = siteCollection.Template, StorageMaximumLevel = siteCollection.StorageMaximumLevel, UserCodeMaximumLevel = siteCollection.UserCodeMaximumLevel }; var op = tenant.CreateSite(properties); context.Load(tenant); context.Load(op, i => i.IsComplete); // TODO: Fails with 400 Bad Request context.ExecuteQuery(); return(await Task.FromResult(siteCollection)); } catch (System.Exception ex) { throw ex; } }
static void Main(string[] args) { string SHAREPOINT_PID = "00000003-0000-0ff1-ce00-000000000000"; //This is hard-coded for SharePoint Online (ie - all tenants) //The app must have tenant-level permissions and can be installed on any site in the tenancy. You must use the tenant //admin site url to get client context. var sharePointUrl = new Uri("https://<Office 365 domain>-admin.sharepoint.com"); string sharePointRealm = TokenHelper.GetRealmFromTargetUrl(sharePointUrl); var token = TokenHelper.GetAppOnlyAccessToken(SHAREPOINT_PID, sharePointUrl.Authority, sharePointRealm).AccessToken; //read the Sites.xml file and then release the file so we can save over it later string path = @"C:\<path>\Sites.xml"; XDocument doc; using (var fileStream = System.IO.File.OpenRead(path)) { doc = XDocument.Load(fileStream); } //get all the requested sites from the Sites.xml file and loop through each for processing var sites = doc.Root.Elements("site"); foreach (var site in sites) { using (var clientContext = TokenHelper.GetClientContextWithAccessToken(sharePointUrl.ToString(), token)) { clientContext.Load(clientContext.Web.Lists); clientContext.ExecuteQuery(); var siteUrl = site.Attribute("url").Value; var tenant = new Tenant(clientContext); var newSite = new SiteCreationProperties() { Url = siteUrl, Owner = "<admin user>@<Office 365 domain>.onmicrosoft.com", Template = "STS#0", Title = "Batch provisioning test site", //StorageMaximumLevel = 100, //StorageWarningLevel = 300, TimeZoneId = 7, UserCodeMaximumLevel = 7, UserCodeWarningLevel = 1, }; var spoOperation = tenant.CreateSite(newSite); clientContext.Load(spoOperation); clientContext.ExecuteQuery(); while (!spoOperation.IsComplete) { System.Threading.Thread.Sleep(2000); clientContext.Load(spoOperation); clientContext.ExecuteQuery(); } } } }
private static string ProcessSiteCreationRequest(ClientContext ctx, ListItem listItem) { // Create the site collection //get the base tenant admin urls string tenantStr = ConfigurationManager.AppSettings["SiteCollectionRequests_SiteUrl"]; tenantStr = tenantStr.ToLower().Replace("-my", "").Substring(8); tenantStr = tenantStr.Substring(0, tenantStr.IndexOf(".")); //create site collection using the Tenant object var webUrl = String.Format("https://{0}.sharepoint.com/{1}/{2}", tenantStr, "sites", listItem["SiteUrl"]); var tenantAdminUri = new Uri(String.Format("https://{0}-admin.sharepoint.com", tenantStr)); string realm = TokenHelper.GetRealmFromTargetUrl(tenantAdminUri); var token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, tenantAdminUri.Authority, realm).AccessToken; using (var adminContext = TokenHelper.GetClientContextWithAccessToken(tenantAdminUri.ToString(), token)) { var tenant = new Tenant(adminContext); var properties = new SiteCreationProperties() { Url = webUrl, Owner = listItem["RequestorEmail"].ToString(), Title = listItem["Title"].ToString(), Template = listItem["Template"].ToString(), StorageMaximumLevel = 100, UserCodeMaximumLevel = 100 }; //start the SPO operation to create the site SpoOperation op = tenant.CreateSite(properties); adminContext.Load(tenant); adminContext.Load(op, i => i.IsComplete); adminContext.ExecuteQuery(); //check if site creation operation is complete while (!op.IsComplete) { //wait 15 seconds and try again System.Threading.Thread.Sleep(15000); op.RefreshLoad(); adminContext.ExecuteQuery(); } } //get the new site collection var siteUri = new Uri(webUrl); token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken; using (var newWebContext = TokenHelper.GetClientContextWithAccessToken(siteUri.ToString(), token)) { var newWeb = newWebContext.Web; newWebContext.Load(newWeb); newWebContext.ExecuteQuery(); // Do some branding just for the demo... could be much more complex stuff than this SetThemeBasedOnName(newWebContext, newWeb, "Orange"); } return(webUrl); }
//gavdcodebegin 01 static void SpCsCsomCreateOneSiteCollection(ClientContext spAdminCtx) { Tenant myTenant = new Tenant(spAdminCtx); string myUser = ConfigurationManager.AppSettings["spUserName"]; SiteCreationProperties mySiteCreationProps = new SiteCreationProperties { Url = ConfigurationManager.AppSettings["spBaseUrl"] + "/sites/NewSiteCollectionModernCsCsom01", Title = "NewSiteCollectionModernCsCsom01", Owner = ConfigurationManager.AppSettings["spUserName"], Template = "STS#3", StorageMaximumLevel = 100, UserCodeMaximumLevel = 50 }; SpoOperation myOps = myTenant.CreateSite(mySiteCreationProps); spAdminCtx.Load(myOps, ic => ic.IsComplete); spAdminCtx.ExecuteQuery(); while (myOps.IsComplete == false) { System.Threading.Thread.Sleep(5000); myOps.RefreshLoad(); spAdminCtx.ExecuteQuery(); } }
private static void CreateSiteCollection(SpoOperation spo, ClientContext tenantCtx, Tenant tenant) { var siteCreationProperties = new SiteCreationProperties(); siteCreationProperties.Url = AuthHelper.siteUrl; siteCreationProperties.Title = "Site Created from Code"; siteCreationProperties.Owner = AuthHelper.userName; //Assign Team Site Template of the SiteCollection. siteCreationProperties.Template = "STS#0"; //Storage Limit in MB siteCreationProperties.StorageMaximumLevel = 100; //UserCode Resource Points Allowed siteCreationProperties.UserCodeMaximumLevel = 100; //Create the SiteCollection spo = tenant.CreateSite(siteCreationProperties); tenantCtx.Load(tenant); //Get the IsComplete property to check if the Site Collection creation is complete. tenantCtx.Load(spo, i => i.IsComplete); tenantCtx.ExecuteQuery(); var msg = "Site Collection creation process..."; WaitForOperation(tenantCtx, spo, msg); }
public void CreatePolicyCenterSite(Uri policyCenterSiteUrl, string siteOwner, long timeoutInMilliSeconds) { ArgumentValidator.ThrowIfNull("policyCenterSiteUrl", policyCenterSiteUrl); ArgumentValidator.ThrowIfNullOrEmpty("siteOwner", siteOwner); Utils.WrapSharePointCsomCall(this.SpAdminSiteUrl, this.credentials, delegate(ClientContext context) { SiteCreationProperties siteCreationProperties = new SiteCreationProperties { Url = policyCenterSiteUrl.AbsoluteUri, Owner = siteOwner, Template = "POLICYCTR#0", Title = "Compliance Policy Center" }; Tenant tenant = new Tenant(context); SpoOperation spoOperation = tenant.CreateSite(siteCreationProperties); context.Load <SpoOperation>(spoOperation, new Expression <Func <SpoOperation, object> > [0]); context.ExecuteQuery(); long num = timeoutInMilliSeconds; while (!spoOperation.IsComplete) { if (num <= 0L || spoOperation.HasTimedout) { throw new ErrorCreateSiteTimeOutException(policyCenterSiteUrl.AbsoluteUri); } int num2 = Math.Min(Math.Max(5000, spoOperation.PollingInterval), (int)num); num -= (long)num2; Thread.Sleep(num2); context.Load <SpoOperation>(spoOperation, new Expression <Func <SpoOperation, object> > [0]); context.ExecuteQuery(); } }); }
public void CreateNewSiteCollection(string title, string name, string owner) { var url = string.Format("https://{0}-admin.sharepoint.com", _generatorDefinition.TenantName); using (ClientContext context = new ClientContext(url)) { context.Credentials = new SharePointOnlineCredentials(_generatorDefinition.Username, Utils.StringToSecureString(_generatorDefinition.Password)); var officeTenant = new Microsoft.Online.SharePoint.TenantAdministration.Tenant(context); var newSiteProperties = new SiteCreationProperties() { Url = string.Format("https://{0}.sharepoint.com/sites/{1}", _generatorDefinition.TenantName, name), Owner = _generatorDefinition.SiteCollOwnerLogin, Template = "STS#0", }; var spo = officeTenant.CreateSite(newSiteProperties); context.Load(spo, i => i.IsComplete); context.ExecuteQuery(); while (!spo.IsComplete) { System.Threading.Thread.Sleep(10000); spo.RefreshLoad(); context.ExecuteQuery(); } } }
/// <summary> /// Method to create site collections /// </summary> /// <param name="clientContext">SharePoint Client Context</param> /// <param name="configVal">Values in Config sheet</param> /// <param name="clientUrl">Url for Site Collection</param> /// <param name="clientTitle">Name of Site Collection</param> internal static void CreateSiteCollections(ClientContext clientContext, Dictionary <string, string> configVal, string clientUrl, string clientTitle) { try { Tenant tenant = new Tenant(clientContext); clientContext.Load(tenant); clientContext.ExecuteQuery(); //login into SharePoint Online SPOSitePropertiesEnumerable spoSiteProperties = tenant.GetSiteProperties(0, true); clientContext.Load(spoSiteProperties); clientContext.ExecuteQuery(); SiteProperties siteProperties = (from properties in spoSiteProperties where properties.Url.ToString().ToUpper() == clientUrl.ToUpper() select properties).FirstOrDefault(); if (null != siteProperties) { // site exists Console.WriteLine(clientUrl + " already exists..."); return; } else { // site does not exists SiteCreationProperties newSite = new SiteCreationProperties() { Url = clientUrl, Owner = configVal["Username"], Template = ConfigurationManager.AppSettings["template"], //using the team site template, check the MSDN if you want to use other template StorageMaximumLevel = Convert.ToInt64(ConfigurationManager.AppSettings["storageMaximumLevel"], CultureInfo.InvariantCulture), //1000 UserCodeMaximumLevel = Convert.ToDouble(ConfigurationManager.AppSettings["userCodeMaximumLevel"], CultureInfo.InvariantCulture), //300 Title = clientTitle, CompatibilityLevel = 15, //15 means SharePoint online 2013, 14 means SharePoint online 2010 }; SpoOperation spo = tenant.CreateSite(newSite); clientContext.Load(tenant); clientContext.Load(spo, operation => operation.IsComplete); clientContext.ExecuteQuery(); Console.WriteLine("Creating site collection at " + clientUrl); Console.WriteLine("Loading."); //Check if provisioning of the SiteCollection is complete. while (!spo.IsComplete) { Console.Write("."); //Wait for 30 seconds and then try again System.Threading.Thread.Sleep(30000); spo.RefreshLoad(); clientContext.ExecuteQuery(); } Console.WriteLine("Site Collection: " + clientUrl + " is created successfully"); } } catch (Exception exception) { Console.WriteLine("Exception occurred while creating site collection: " + exception.Message); } }
public static string CreateSiteCollection(ClientContext ctx, string hostWebUrl, string template, string title, string description, string userEmail) { //get the base tenant admin urls var tenantStr = hostWebUrl.ToLower().Replace("-my", "").Substring(8); tenantStr = tenantStr.Substring(0, tenantStr.IndexOf(".")); //create site collection using the Tenant object var webUrl = String.Format("https://{0}.sharepoint.com/{1}/{2}", tenantStr, "sites", title); var tenantAdminUri = new Uri(String.Format("https://{0}-admin.sharepoint.com", tenantStr)); string realm = TokenHelper.GetRealmFromTargetUrl(tenantAdminUri); var token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, tenantAdminUri.Authority, realm).AccessToken; using (var adminContext = TokenHelper.GetClientContextWithAccessToken(tenantAdminUri.ToString(), token)) { var tenant = new Tenant(adminContext); var properties = new SiteCreationProperties() { Url = webUrl, Owner = userEmail, Title = title, Template = template, StorageMaximumLevel = 100, UserCodeMaximumLevel = 100 }; //start the SPO operation to create the site SpoOperation op = tenant.CreateSite(properties); adminContext.Load(tenant); adminContext.Load(op, i => i.IsComplete); adminContext.ExecuteQuery(); //check if site creation operation is complete while (!op.IsComplete) { //wait 30seconds and try again System.Threading.Thread.Sleep(30000); op.RefreshLoad(); adminContext.ExecuteQuery(); } } //get the new site collection var siteUri = new Uri(webUrl); token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken; using (var newWebContext = TokenHelper.GetClientContextWithAccessToken(siteUri.ToString(), token)) { var newWeb = newWebContext.Web; newWebContext.Load(newWeb); newWebContext.ExecuteQuery(); new LabHelper().SetThemeBasedOnName(newWebContext, newWeb, newWeb, "Orange"); // All done, let's return the newly created site return(newWeb.Url); } }
public static Guid AddSiteCollectionTenant(this Web web, SiteEntity properties) { Tenant tenant = new Tenant(web.Context); SiteCreationProperties newsite = new SiteCreationProperties(); newsite.Url = properties.Url; newsite.Owner = properties.SiteOwnerLogin; newsite.Template = properties.Template; newsite.Title = properties.Title; newsite.StorageMaximumLevel = properties.StorageMaximumLevel; newsite.StorageWarningLevel = properties.StorageWarningLevel; newsite.TimeZoneId = properties.TimeZoneId; newsite.UserCodeMaximumLevel = properties.UserCodeMaximumLevel; newsite.UserCodeWarningLevel = properties.UserCodeWarningLevel; newsite.Lcid = properties.Lcid; try { SpoOperation op = tenant.CreateSite(newsite); web.Context.Load(tenant); web.Context.Load(op, i => i.IsComplete, i => i.PollingInterval); web.Context.ExecuteQuery(); //check if site creation operation is complete while (!op.IsComplete) { System.Threading.Thread.Sleep(op.PollingInterval); op.RefreshLoad(); if (!op.IsComplete) { try { web.Context.ExecuteQuery(); } catch (WebException webEx) { // Context connection gets closed after action completed. // Calling ExecuteQuery again returns an error which can be ignored LoggingUtility.LogWarning(MSG_CONTEXT_CLOSED, webEx, EventCategory.Site); } } } } catch (Exception ex) { // Eat the siteSubscription exception to make the same code work for MT as on-prem april 2014 CU+ if (ex.Message.IndexOf("Parameter name: siteSubscription") == -1) { throw ex; } } // Get site guid and return var siteGuid = web.GetSiteGuidByUrlTenant(new Uri(properties.Url)); return(siteGuid); }
public override void CreateSiteCollection(SiteInformation siteRequest, Template template) { Log.Info("Provisioning.Common.Office365SiteProvisioningService.CreateSiteCollection", PCResources.SiteCreation_Creation_Starting, siteRequest.Url); UsingContext(ctx => { try { Stopwatch _timespan = Stopwatch.StartNew(); Tenant _tenant = new Tenant(ctx); var _newsite = new SiteCreationProperties(); _newsite.Title = siteRequest.Title; _newsite.Url = siteRequest.Url; _newsite.Owner = siteRequest.SiteOwner.Name; _newsite.Template = template.RootTemplate; _newsite.Lcid = siteRequest.Lcid; _newsite.TimeZoneId = siteRequest.TimeZoneId; _newsite.StorageMaximumLevel = template.StorageMaximumLevel; _newsite.StorageWarningLevel = template.StorageWarningLevel; _newsite.UserCodeMaximumLevel = template.UserCodeMaximumLevel; _newsite.UserCodeMaximumLevel = template.UserCodeWarningLevel; SpoOperation op = _tenant.CreateSite(_newsite); ctx.Load(_tenant); ctx.Load(op, i => i.IsComplete); ctx.ExecuteQuery(); while (!op.IsComplete) { //wait 30seconds and try again System.Threading.Thread.Sleep(30000); op.RefreshLoad(); ctx.ExecuteQuery(); } var _site = _tenant.GetSiteByUrl(siteRequest.Url); var _web = _site.RootWeb; _web.Description = siteRequest.Description; _web.Update(); ctx.Load(_web); ctx.ExecuteQuery(); _timespan.Stop(); Log.TraceApi("SharePoint", "Office365SiteProvisioningService.CreateSiteCollection", _timespan.Elapsed, "SiteUrl={0}", siteRequest.Url); } catch (Exception ex) { Log.Error("Provisioning.Common.Office365SiteProvisioningService.CreateSiteCollection", PCResources.SiteCreation_Creation_Failure, siteRequest.Url, ex.Message, ex); throw; } Log.Info("Provisioning.Common.Office365SiteProvisioningService.CreateSiteCollection", PCResources.SiteCreation_Creation_Successful, siteRequest.Url); }); }
/// <summary> /// Adds a SiteEntity by launching site collection creation and waits for the creation to finish /// </summary> /// <param name="tenant">A tenant object pointing to the context of a Tenant Administration site</param> /// <param name="properties">Describes the site collection to be created</param> /// <param name="removeFromRecycleBin">It true and site is present in recycle bin, it will be removed first from the recycle bin</param> /// <param name="wait">If true, processing will halt until the site collection has been created</param> /// <param name="timeoutFunction">An optional function that will be called while waiting for the site to be created. If set will override the wait variable. Return true to cancel the wait loop.</param> /// <returns>Guid of the created site collection and Guid.Empty is the wait parameter is specified as false. Returns Guid.Empty if the wait is cancelled.</returns> public static Guid CreateSiteCollection(this Tenant tenant, SiteEntity properties, bool removeFromRecycleBin = false, bool wait = true, Func <TenantOperationMessage, bool> timeoutFunction = null) { if (removeFromRecycleBin) { if (tenant.CheckIfSiteExists(properties.Url, SITE_STATUS_RECYCLED)) { tenant.DeleteSiteCollectionFromRecycleBin(properties.Url); } } SiteCreationProperties newsite = new SiteCreationProperties(); newsite.Url = properties.Url; newsite.Owner = properties.SiteOwnerLogin; newsite.Template = properties.Template; newsite.Title = properties.Title; newsite.StorageMaximumLevel = properties.StorageMaximumLevel; newsite.StorageWarningLevel = properties.StorageWarningLevel; newsite.TimeZoneId = properties.TimeZoneId; newsite.UserCodeMaximumLevel = properties.UserCodeMaximumLevel; newsite.UserCodeWarningLevel = properties.UserCodeWarningLevel; newsite.Lcid = properties.Lcid; SpoOperation op = tenant.CreateSite(newsite); tenant.Context.Load(tenant); tenant.Context.Load(op, i => i.IsComplete, i => i.PollingInterval); tenant.Context.ExecuteQueryRetry(); // Get site guid and return. If we create the site asynchronously, return an empty guid as we cannot retrieve the site by URL yet. Guid siteGuid = Guid.Empty; if (timeoutFunction != null) { wait = true; } if (wait) { // Let's poll for site collection creation completion if (WaitForIsComplete(tenant, op, timeoutFunction, TenantOperationMessage.CreatingSiteCollection)) { // Return site guid of created site collection try { siteGuid = tenant.GetSiteGuidByUrl(new Uri(properties.Url)); } catch (Exception ex) { // Eat all exceptions cause there's currently (December 16) an issue in the service that can make this call fail in combination with app-only usage Log.Error("Temp eating exception to issue in service (December 2016). Exception is {0}.", ex.ToDetailedString()); } } } return(siteGuid); }
public override void CreateSiteCollection(SiteInformation siteRequest, Template template) { Log.Info("Provisioning.Common.OnPremSiteProvisioningService.CreateSiteCollection", PCResources.SiteCreation_Creation_Starting, siteRequest.Url); Web _web = null; try { UsingContext(ctx => { Stopwatch _timespan = Stopwatch.StartNew(); Tenant _tenant = new Tenant(ctx); var _newsite = new SiteCreationProperties(); _newsite.Title = siteRequest.Title; _newsite.Url = siteRequest.Url; _newsite.Owner = siteRequest.SiteOwner.Name; _newsite.Template = template.RootTemplate; _newsite.Lcid = siteRequest.Lcid; _newsite.TimeZoneId = siteRequest.TimeZoneId; _newsite.StorageMaximumLevel = template.StorageMaximumLevel; _newsite.StorageWarningLevel = template.StorageWarningLevel; _newsite.UserCodeMaximumLevel = template.UserCodeMaximumLevel; _newsite.UserCodeMaximumLevel = template.UserCodeWarningLevel; _tenant.CreateSite(_newsite); ctx.ExecuteQuery(); Tenant tenant = new Tenant(ctx); var site = tenant.GetSiteByUrl(siteRequest.Url); using (var _cloneCtx = site.Context.Clone(siteRequest.Url)) { _web = _cloneCtx.Site.RootWeb; _web.Description = siteRequest.Description; _web.Update(); _cloneCtx.Load(_web); _cloneCtx.ExecuteQuery(); } _timespan.Stop(); Log.TraceApi("SharePoint", "OnPremSiteProvisioningService.CreateSiteCollection", _timespan.Elapsed, "SiteUrl={0}", siteRequest.Url); }, 1200000); } catch (Exception ex) { Log.Error("Provisioning.Common.OnPremSiteProvisioningService.CreateSiteCollection", PCResources.SiteCreation_Creation_Failure, siteRequest.Url, ex, ex.InnerException); throw; } Log.Info("Provisioning.Common.OnPremSiteProvisioningService.CreateSiteCollection", PCResources.SiteCreation_Creation_Successful, siteRequest.Url); this.HandleDefaultGroups(siteRequest); }
public static Guid AddSiteCollectionTenant(this Web web, SiteEntity properties) { Tenant tenant = new Tenant(web.Context); SiteCreationProperties newsite = new SiteCreationProperties(); newsite.Url = properties.Url; newsite.Owner = properties.SiteOwnerLogin; newsite.Template = properties.Template; newsite.Title = properties.Title; newsite.StorageMaximumLevel = properties.StorageMaximumLevel; newsite.StorageWarningLevel = properties.StorageWarningLevel; newsite.TimeZoneId = properties.TimeZoneId; newsite.UserCodeMaximumLevel = properties.UserCodeMaximumLevel; newsite.UserCodeWarningLevel = properties.UserCodeWarningLevel; newsite.Lcid = properties.Lcid; try { SpoOperation op = tenant.CreateSite(newsite); web.Context.Load(tenant); web.Context.Load(op, i => i.IsComplete, i => i.PollingInterval); web.Context.ExecuteQuery(); //check if site creation operation is complete while (!op.IsComplete) { System.Threading.Thread.Sleep(op.PollingInterval); op.RefreshLoad(); if (!op.IsComplete) { try { web.Context.ExecuteQuery(); } catch (WebException webEx) { // Context connection gets closed after action completed. // Calling ExecuteQuery again returns an error which can be ignored LoggingUtility.LogWarning(MSG_CONTEXT_CLOSED, webEx, EventCategory.Site); } } } } catch(Exception ex) { // Eat the siteSubscription exception to make the same code work for MT as on-prem april 2014 CU+ if (ex.Message.IndexOf("Parameter name: siteSubscription") == -1) { throw ex; } } // Get site guid and return var siteGuid = web.GetSiteGuidByUrlTenant(new Uri(properties.Url)); return siteGuid; }
public static void CreateSiteCollection(ClientContext clientContext, SiteCreationProperties siteCreationProperties) { var tenant = new Tenant(clientContext); var spoOperation = tenant.CreateSite(siteCreationProperties); clientContext.Load(spoOperation); clientContext.ExecuteQuery(); }
public void ProcessOneWayEvent(SPRemoteEventProperties properties) { string SHAREPOINT_PID = "00000003-0000-0ff1-ce00-000000000000"; //This is hard-coded for SharePoint Online (ie - all tenants) //The app must have tenant-level permissions and can be installed on any site in the tenancy. You must use the tenant //admin site url to get client context. Uri sharePointUrl = new Uri("https://<your-domain>-admin.sharepoint.com"); string myRealm = TokenHelper.GetRealmFromTargetUrl(sharePointUrl); try { string accessToken = TokenHelper.GetAppOnlyAccessToken(SHAREPOINT_PID, sharePointUrl.Authority, myRealm).AccessToken; using (ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharePointUrl.ToString(), accessToken)) { if (clientContext != null) { var requestTitle = properties.ItemEventProperties.AfterProperties["Title"]; var tenant = new Tenant(clientContext); var newSite = new SiteCreationProperties() { Url = "https://<your domain>.sharepoint.com/sites/" + requestTitle, Owner = "administrator@<your domain>.onmicrosoft.com", Template = "STS#0", Title = "Workflow provisioning test site two", StorageMaximumLevel = 1000, StorageWarningLevel = 500, TimeZoneId = 7, UserCodeMaximumLevel = 7, UserCodeWarningLevel = 1, }; var spoOperation = tenant.CreateSite(newSite); clientContext.Load(spoOperation); clientContext.ExecuteQuery(); while (!spoOperation.IsComplete) { System.Threading.Thread.Sleep(2000); clientContext.Load(spoOperation); clientContext.ExecuteQuery(); } } } } catch (Exception ex) { var exception = ex; } }
public static string CreateSiteCollection(ClientContext ctx, string hostWebUrl, string template, string title, string description, string userEmail) { //get the base tenant admin urls var tenantStr = hostWebUrl.ToLower().Replace("-my", "").Substring(8); tenantStr = tenantStr.Substring(0, tenantStr.IndexOf(".")); //create site collection using the Tenant object var webUrl = String.Format("https://{0}.sharepoint.com/{1}/{2}", tenantStr, "sites", title); var tenantAdminUri = new Uri(String.Format("https://{0}-admin.sharepoint.com", tenantStr)); string realm = TokenHelper.GetRealmFromTargetUrl(tenantAdminUri); var token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, tenantAdminUri.Authority, realm).AccessToken; using (var adminContext = TokenHelper.GetClientContextWithAccessToken(tenantAdminUri.ToString(), token)) { var tenant = new Tenant(adminContext); var properties = new SiteCreationProperties() { Url = webUrl, Owner = userEmail, Title = title, Template = template, StorageMaximumLevel = 100, UserCodeMaximumLevel = 100 }; //start the SPO operation to create the site SpoOperation op = tenant.CreateSite(properties); adminContext.Load(tenant); adminContext.Load(op, i => i.IsComplete); adminContext.ExecuteQuery(); //check if site creation operation is complete while (!op.IsComplete) { //wait 30seconds and try again System.Threading.Thread.Sleep(30000); op.RefreshLoad(); adminContext.ExecuteQuery(); } } //get the new site collection var siteUri = new Uri(webUrl); token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken; using (var newWebContext = TokenHelper.GetClientContextWithAccessToken(siteUri.ToString(), token)) { var newWeb = newWebContext.Web; newWebContext.Load(newWeb); newWebContext.ExecuteQuery(); new LabHelper().SetThemeBasedOnName(newWebContext, newWeb, newWeb, "Orange"); // All done, let's return the newly created site return newWeb.Url; } }
public string CreateSiteCollection() { var user = GetSpUser.ResolveUserById(_ctx, _actionRequest.User); var tenant = new Tenant(_ctx); var webUrl = $"https://{_actionRequest.TenantName}.sharepoint.com/{_siteCollectionRequest.ManagedPath}/{_actionRequest.Name}"; if (tenant.SiteExists(webUrl)) { // "Site already existed. Used URL - {0}" } else { var newsite = new SiteCreationProperties { Title = _actionRequest.Name, Url = webUrl, Owner = user.Email, Template = "STS#0", Lcid = _siteCollectionRequest.Lcid, TimeZoneId = _siteCollectionRequest.TimeZoneId, StorageMaximumLevel = _siteCollectionRequest.StorageMaximumLevel, StorageWarningLevel = _siteCollectionRequest.StorageMaximumLevel, UserCodeMaximumLevel = 0, UserCodeWarningLevel = 0 }; SpoOperation op = tenant.CreateSite(newsite); _ctx.Load(tenant); _ctx.Load(op, i => i.IsComplete); _ctx.ExecuteQuery(); var step = 0; while (!op.IsComplete) { step = step + 1; Updatehelper.UpdateProgressView($"{step} Creating site collection", _actionRequest); Thread.Sleep(10000); op.RefreshLoad(); _ctx.ExecuteQuery(); } } var site = tenant.GetSiteByUrl(webUrl); var web = site.RootWeb; web.Description = _actionRequest.Description; web.Update(); _ctx.Load(web); _ctx.ExecuteQuery(); return(web.Url); }
public static bool CreateSiteColleciton(AuthResult result, CreateSiteCollectionQuery formResult, string tenantUrl, string resourceId) { var telemetry = new TelemetryClient(); bool succes = false; var telProps = new Dictionary <string, string>(); try { AuthenticationManager authManager = new AuthenticationManager(); using (ClientContext context = authManager.GetAzureADAccessTokenAuthenticatedContext(tenantUrl, result.AccessToken)) { telProps.Add("Create Site collection connection URL", tenantUrl); Tenant t = new Tenant(context); SiteCreationProperties props = new SiteCreationProperties { Url = $"https://{resourceId}.sharepoint.com/sites/{HttpContext.Current.Server.UrlEncode(formResult.Title)}", Title = formResult.Title, Owner = result.Upn, StorageMaximumLevel = formResult.Storage, UserCodeMaximumLevel = formResult.Resource, Template = "STS#0" }; switch (formResult.SiteTemplate) { case SiteTemplate.TeamSite: props.Template = "STS#0"; break; case SiteTemplate.CommunitySite: props.Template = "COMMUNITY#0"; break; case SiteTemplate.WikiSite: props.Template = "WIKI#0"; break; } telProps.Add("Create site props", JsonConvert.SerializeObject(props)); telemetry.TrackEvent("Create site collection", telProps); t.CreateSite(props); context.ExecuteQuery(); succes = true; } } catch (Exception ex) { //TODO return ex message telemetry.TrackException(ex, telProps); } return(succes); }
/// <summary> /// Adds a SiteEntity by launching site collection creation and waits for the creation to finish /// </summary> /// <param name="tenant">A tenant object pointing to the context of a Tenant Administration site</param> /// <param name="properties">Describes the site collection to be created</param> /// <param name="removeFromRecycleBin">It true and site is present in recycle bin, it will be removed first from the recycle bin</param> /// <param name="wait">If true, processing will halt until the site collection has been created</param> /// <returns>Guid of the created site collection and Guid.Empty is the wait parameter is specified as false</returns> public static Guid CreateSiteCollection(this Tenant tenant, SiteEntity properties, bool removeFromRecycleBin = false, bool wait = true) { if (removeFromRecycleBin) { if (tenant.CheckIfSiteExists(properties.Url, SITE_STATUS_RECYCLED)) { tenant.DeleteSiteCollectionFromRecycleBin(properties.Url); } } SiteCreationProperties newsite = new SiteCreationProperties(); newsite.Url = properties.Url; newsite.Owner = properties.SiteOwnerLogin; newsite.Template = properties.Template; newsite.Title = properties.Title; newsite.StorageMaximumLevel = properties.StorageMaximumLevel; newsite.StorageWarningLevel = properties.StorageWarningLevel; newsite.TimeZoneId = properties.TimeZoneId; newsite.UserCodeMaximumLevel = properties.UserCodeMaximumLevel; newsite.UserCodeWarningLevel = properties.UserCodeWarningLevel; newsite.Lcid = properties.Lcid; try { SpoOperation op = tenant.CreateSite(newsite); tenant.Context.Load(tenant); tenant.Context.Load(op, i => i.IsComplete, i => i.PollingInterval); tenant.Context.ExecuteQuery(); if (wait) { WaitForIsComplete(tenant, op); } } catch (Exception ex) { // Eat the siteSubscription exception to make the same code work for MT as on-prem April 2014 CU+ if (ex.Message.IndexOf("Parameter name: siteSubscription") == -1) { throw; } } // Get site guid and return. If we create the site asynchronously, return an empty guid as we cannot retrieve the site by URL yet. Guid siteGuid = Guid.Empty; if (wait) { siteGuid = tenant.GetSiteGuidByUrl(new Uri(properties.Url)); } return(siteGuid); }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] CreateSiteRequest request, TraceWriter log) { string adminUrl = $"https://{request.Tenant}-admin.sharepoint.com"; try { if (string.IsNullOrWhiteSpace(request.Title)) { throw new ArgumentException("Parameter cannot be null", "Title"); } if (string.IsNullOrWhiteSpace(request.Tenant)) { throw new ArgumentException("Parameter cannot be null", "Tenant"); } if (string.IsNullOrWhiteSpace(request.Url)) { throw new ArgumentException("Parameter cannot be null", "Url"); } var adminContext = await ConnectADAL.GetClientContext(adminUrl, log); Tenant tenant = new Tenant(adminContext); adminContext.ExecuteQuery(); string url = $"https://{request.Tenant}.sharepoint.com/sites/{request.Url}"; var siteCreationProperties = new SiteCreationProperties() { Title = request.Title, Url = url, Owner = request.OwnerEmail, Template = !string.IsNullOrWhiteSpace(request.Template) ? request.Template : "STS#3", StorageMaximumLevel = 100, UserCodeMaximumLevel = 0, Lcid = request.Language != 0 ? request.Language : 1033, }; tenant.CreateSite(siteCreationProperties); adminContext.ExecuteQuery(); return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new ObjectContent <CreateSiteResponse>(new CreateSiteResponse { SiteURL = url }, new JsonMediaTypeFormatter()) })); } catch (Exception e) { log.Error($"Error: {e.Message }\n\n{e.StackTrace}"); return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable) { Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter()) })); } }
/// <summary> /// サイトコレクション作成 /// </summary> /// <param name="tenantConnectionInfo">テナント接続情報</param> /// <param name="sitecollectionInfo">サイトコレクション作成情報</param> /// <param name="progress">進捗報告オブジェクト</param> public static async Task CreateSiteCollectionAsync(TenantConnectionInfo tenantConnectionInfo, SiteCollectionInfo sitecollectionInfo, IProgress <string> progress = null) { progress?.Report("テナント接続開始"); using (var ctx = new ClientContext(tenantConnectionInfo.SPOAdminCenterUrl)) { // 認証 ctx.Credentials = new SharePointOnlineCredentials(tenantConnectionInfo.UserAccount, tenantConnectionInfo.UserSecurePassword); ctx.RequestTimeout = Timeout.Infinite; // テナント取得 var tenant = new Tenant(ctx); // サイトコレクション作成情報 progress?.Report("サイトコレクション作成開始"); var creationInfo = new SiteCreationProperties() { Title = sitecollectionInfo.Title, Url = sitecollectionInfo.Url, Owner = sitecollectionInfo.SiteOwnerLogin, Template = sitecollectionInfo.Template, StorageMaximumLevel = sitecollectionInfo.StorageMaximumLevel, UserCodeMaximumLevel = 0, Lcid = sitecollectionInfo.Lcid, TimeZoneId = sitecollectionInfo.TimeZoneId, CompatibilityLevel = (int)SiteCollectionInfo.CompatibilityLevels.SPS2013 }; // サイトコレクション作成 var operation = tenant.CreateSite(creationInfo); ctx.Load(tenant); ctx.Load(operation, i => i.IsComplete); await ctx.ExecuteQueryRetryAsync(); var siteCollections = tenant.GetSiteCollections(0, 0, true, true); ctx.Load(tenant); progress?.Report("サイトコレクション作成完了まで待機します・・・"); await ctx.ExecuteQueryRetryAsync(); // 作成完了まで待機 while (!operation.IsComplete) { progress?.Report("サイトコレクション作成完了まで待機します・・・"); Thread.Sleep(30000); operation.RefreshLoad(); await ctx.ExecuteQueryRetryAsync(); } progress?.Report("サイトコレクション作成完了"); } progress?.Report("テナント接続終了"); }
/// <summary> /// Adds a SiteEntity by launching site collection creation and waits for the creation to finish /// </summary> /// <param name="tenant">A tenant object pointing to the context of a Tenant Administration site</param> /// <param name="properties">Describes the site collection to be created</param> /// <param name="removeFromRecycleBin">It true and site is present in recycle bin, it will be removed first from the recycle bin</param> /// <param name="wait">If true, processing will halt until the site collection has been created</param> /// <returns>Guid of the created site collection and Guid.Empty is the wait parameter is specified as false</returns> public static Guid CreateSiteCollection(this Tenant tenant, SiteEntity properties, bool removeFromRecycleBin = false, bool wait = true) { if (removeFromRecycleBin) { if (tenant.CheckIfSiteExists(properties.Url, SITE_STATUS_RECYCLED)) { tenant.DeleteSiteCollectionFromRecycleBin(properties.Url); } } SiteCreationProperties newsite = new SiteCreationProperties(); newsite.Url = properties.Url; newsite.Owner = properties.SiteOwnerLogin; newsite.Template = properties.Template; newsite.Title = properties.Title; newsite.StorageMaximumLevel = properties.StorageMaximumLevel; newsite.StorageWarningLevel = properties.StorageWarningLevel; newsite.TimeZoneId = properties.TimeZoneId; newsite.UserCodeMaximumLevel = properties.UserCodeMaximumLevel; newsite.UserCodeWarningLevel = properties.UserCodeWarningLevel; newsite.Lcid = properties.Lcid; try { SpoOperation op = tenant.CreateSite(newsite); tenant.Context.Load(tenant); tenant.Context.Load(op, i => i.IsComplete, i => i.PollingInterval); tenant.Context.ExecuteQuery(); if (wait) { WaitForIsComplete(tenant, op); } } catch (Exception ex) { // Eat the siteSubscription exception to make the same code work for MT as on-prem April 2014 CU+ if (ex.Message.IndexOf("Parameter name: siteSubscription") == -1) { throw; } } // Get site guid and return. If we create the site asynchronously, return an empty guid as we cannot retrieve the site by URL yet. Guid siteGuid = Guid.Empty; if (wait) { siteGuid = tenant.GetSiteGuidByUrl(new Uri(properties.Url)); } return siteGuid; }
public string CreateSite(string rootSiteUrl, string siteUrl, string userName, string siteTitle) { siteUrl = rootSiteUrl + "/sites/" + siteUrl; var tenant = new Tenant(tenantContext); //Properties of the New SiteCollection var siteCreationProperties = new SiteCreationProperties(); //New SiteCollection Url siteCreationProperties.Url = siteUrl; //Title of the Root Site siteCreationProperties.Title = siteTitle; //Login name of Owner siteCreationProperties.Owner = userName; //Template of the Root Site. Using Team Site for now. siteCreationProperties.Template = "BLANKINTERNETCONTAINER#0"; //Storage Limit in MB siteCreationProperties.StorageMaximumLevel = 100; //UserCode Resource Points Allowed siteCreationProperties.UserCodeMaximumLevel = 50; siteCreationProperties.TimeZoneId = 7; //Create the SiteCollection SpoOperation spo = tenant.CreateSite(siteCreationProperties); tenantContext.Load(tenant); //We will need the IsComplete property to check if the provisioning of the Site Collection is complete. tenantContext.Load(spo, i => i.IsComplete); tenantContext.ExecuteQuery(); //Check if provisioning of the SiteCollection is complete. while (!spo.IsComplete) { //Wait for 30 seconds and then try again System.Threading.Thread.Sleep(30000); spo.RefreshLoad(); tenantContext.Load(spo); tenantContext.ExecuteQuery(); } Console.WriteLine("Site Created."); return(siteUrl); }
public string CreateSite(string rootSiteUrl, string loginName, string siteTitle, string siteUrl) { siteUrl = rootSiteUrl + "/sites/" + siteUrl; #region Create Site var tenant = new Tenant(_context); var siteCreationProperties = new SiteCreationProperties { //New SiteCollection Url Url = siteUrl, //Title of the Root Site Title = siteTitle, //Login name of Owner Owner = loginName, //Template of the Root Site. Using Team Site for now. // BLANKINTERNETCONTAINER#0 STS#0 Template = "BLANKINTERNETCONTAINER#0", //Storage Limit in MB StorageMaximumLevel = 5, TimeZoneId = 7 }; //Create the SiteCollection SpoOperation spo = tenant.CreateSite(siteCreationProperties); _context.Load(spo); Console.WriteLine("Start creating site..."); _context.ExecuteQuery(); //Check if provisioning of the SiteCollection is complete. while (!spo.IsComplete) { //Wait for 30 seconds and then try again System.Threading.Thread.Sleep(30000); //spo.RefreshLoad(); _context.Load(spo); Console.WriteLine("Sau 30 giây...."); _context.ExecuteQuery(); } Console.WriteLine("Site Created."); return(siteUrl); #endregion }
// This method relies on the April 2014 CU in SP2013. // http://blogs.msdn.com/b/vesku/archive/2014/06/09/provisioning-site-collections-using-sp-app-model-in-on-premises-with-just-csom.aspx private static void CreateSiteCollection(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 site collection. SPCommon.LoadTenant(clientContext, (tenant, adminContext) => { var webUrl = GetUrlFromSiteName(clientContext, siteName); // Ensure the user var username = AppHelper.GetProperty(clientContext, Constants.SITEOWNER_PROPERTY) as string; if (String.IsNullOrEmpty(username)) { throw new Exception("Default site owner not set"); } clientContext.Load(clientContext.Web); clientContext.ExecuteQuery(); var user = clientContext.Web.EnsureUser(username); if (null == user) { throw new Exception(String.Format("User {0} not found", username)); } clientContext.Load(user); clientContext.ExecuteQuery(); var properties = new SiteCreationProperties { Url = webUrl, Owner = user.LoginName, Title = siteName, // Use a blank site template until we can add customizations to the created site collection // On-Prem won't allow creation of site collection w/o valid template. Template = "STS#1" }; // Start the SPO operation to create the site // Note in O365 this operation is asynchronous whereas on prem it synchronous. var op = tenant.CreateSite(properties); adminContext.Load(op, i => i.IsComplete); adminContext.ExecuteQuery(); }); }
public void CreateNewSiteCollection(string title, string siteCollectionUrl, string owner) { bool isSiteCollectionExists = false; var url = string.Format("https://{0}-admin.sharepoint.com", _generatorDefinition.TenantName); using (ClientContext siteContext = new ClientContext(siteCollectionUrl)) { try { var site = siteContext.Site; siteContext.Load(site); siteContext.ExecuteQuery(); isSiteCollectionExists = true; } catch (Exception ex) { isSiteCollectionExists = false; } } if (!isSiteCollectionExists) { using (ClientContext context = new ClientContext(url)) { context.Credentials = new SharePointOnlineCredentials(_generatorDefinition.Username, Utils.StringToSecureString(_generatorDefinition.Password)); var officeTenant = new Microsoft.Online.SharePoint.TenantAdministration.Tenant(context); var newSiteProperties = new SiteCreationProperties() { Url = siteCollectionUrl, Owner = _generatorDefinition.SiteCollOwnerLogin, Template = "STS#0" }; var spo = officeTenant.CreateSite(newSiteProperties); context.Load(spo, i => i.IsComplete); context.ExecuteQuery(); while (!spo.IsComplete) { System.Threading.Thread.Sleep(10000); spo.RefreshLoad(); context.ExecuteQuery(); } CreateCustomPermissionLevels(siteCollectionUrl); } } }
private void CreatDestinationSiteCollection(SourceSiteCollectionSettings SourceSiteColl, string tenantname, string managedpath, string newurl, string username, string password) { string DestinationSiteCollectionURL = $"https://{tenantname}.sharepoint.com/{managedpath}/{newurl}"; string tenantURL = $"https://{tenantname}-admin.sharepoint.com"; //create root site collection at destination AuthenticationManager AM = new AuthenticationManager(); using (ClientContext ctx = AM.GetSharePointOnlineAuthenticatedContextTenant(tenantURL, username, password)) { try { Tenant objTenant = new Tenant(ctx); SiteCreationProperties newSite = new SiteCreationProperties(); newSite.Owner = username; newSite.Title = SourceSiteColl.Title; newSite.Url = DestinationSiteCollectionURL; newSite.CompatibilityLevel = 15; if (SourceSiteColl.Template.ToUpper().Trim() == "BLANKINTERNET#0") { newSite.Template = "BLANKINTERNETCONTAINER#0"; } else { newSite.Template = SourceSiteColl.Template; } newSite.Lcid = SourceSiteColl.LanguageID; newSite.UserCodeMaximumLevel = 0; SpoOperation oSpoOps = objTenant.CreateSite(newSite); ctx.Load(oSpoOps, spo => spo.IsComplete); ctx.ExecuteQuery(); MessageBox.Show("DO NOT PROCEED ! wait for site collection creation. Click on ok AFTER you can opened the site collection in browser."); } catch (Exception ex) { MessageBox.Show(ex.Message); } //create libraies createSiteCollectionLists(SourceSiteColl, DestinationSiteCollectionURL, username, password); //create subsites createSubsites(SourceSiteColl, DestinationSiteCollectionURL, DestinationSiteCollectionURL, username, password); } }
/// <summary> /// Ccloud request processing. Based on following project: /// This should be located in cloud specific buisness logic component, but added here for simplicity reasons. /// </summary> /// <param name="request"></param> /// <param name="log"></param> private static void ProcessCloudRequest(SiteCollectionRequest request, TextWriter log) { //get the base tenant admin urls string tenantStr = ConfigurationManager.AppSettings["Office365Tenant"]; //create site collection using the Tenant object var webUrl = String.Format("https://{0}.sharepoint.com/{1}/{2}", tenantStr, "sites", Guid.NewGuid().ToString().Replace("-", "")); var tenantAdminUri = new Uri(String.Format("https://{0}-admin.sharepoint.com", tenantStr)); // Connecting to items using app only token string realm = TokenHelper.GetRealmFromTargetUrl(tenantAdminUri); var token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, tenantAdminUri.Authority, realm).AccessToken; using (var adminContext = TokenHelper.GetClientContextWithAccessToken(tenantAdminUri.ToString(), token)) { var tenant = new Tenant(adminContext); var properties = new SiteCreationProperties() { Url = webUrl, Owner = request.OwnerIdentifier, Title = request.Title, Template = "STS#0", // Create always team site and specialize after site collection is created as needed StorageMaximumLevel = 100, UserCodeMaximumLevel = 100 }; //start the SPO operation to create the site SpoOperation op = tenant.CreateSite(properties); adminContext.Load(tenant); adminContext.Load(op, i => i.IsComplete); adminContext.ExecuteQuery(); //check if site creation operation is complete while (!op.IsComplete) { //wait 15 seconds and try again System.Threading.Thread.Sleep(15000); op.RefreshLoad(); adminContext.ExecuteQuery(); } } log.WriteLine(String.Format("Create new site collection with URL '{1}' at {0}", webUrl, DateTime.Now.ToLongTimeString())); ApplyTemplateForCreatedSiteCollection(webUrl, token, realm); log.WriteLine(String.Format("Applied custom branding to new site collection with URL '{1}' at {0}", webUrl, DateTime.Now.ToLongTimeString())); }
/// <summary> /// Actual business logic to create the site collections. /// See more details on the requirements for on-premises from following blog post: /// http://blogs.msdn.com/b/vesku/archive/2014/06/09/provisioning-site-collections-using-sp-app-model-in-on-premises-with-just-csom.aspx /// </summary> /// <param name="request"></param> /// <returns></returns> private static string ProcessSiteCreationRequest(SiteCollectionRequest request) { // Get the base tenant admin url needed for site collection creation string tenantStr = ConfigurationManager.AppSettings[Consts.AdminSiteCollectionUrl]; // Resolve root site collection URL from host web. string rootSiteUrl = ConfigurationManager.AppSettings[Consts.LeadingURLForSiteCollections]; // Create unique URL based on GUID. In real production implementation you might do this otherways, but this is for simplicity purposes var webUrl = string.Format("{0}/sites/{1}", rootSiteUrl, Guid.NewGuid().ToString().Replace("-", "")); var tenantAdminUri = ConfigurationManager.AppSettings[Consts.AdminSiteCollectionUrl]; // Notice that we do NOT use app model where for this sample. We use just specific service account. Could be easily // changed for example based on following sample: https://github.com/OfficeDev/PnP/tree/master/Samples/Provisioning.OnPrem.Async using (var ctx = new ClientContext(tenantAdminUri)) { ctx.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings[Consts.ProvisioningAccount], ConfigurationManager.AppSettings[Consts.ProvisioningPassword], ConfigurationManager.AppSettings[Consts.ProvisioningDomain]); // Set the time out as high as possible ctx.RequestTimeout = Timeout.Infinite; var tenant = new Tenant(ctx); var properties = new SiteCreationProperties() { Url = webUrl, Owner = string.Format("{0}\\{1}", ConfigurationManager.AppSettings[Consts.ProvisioningDomain], ConfigurationManager.AppSettings[Consts.ProvisioningAccount]), Title = request.Title, Template = "STS#0" // Create always team site, but specialize the site based on the template value }; //start the SPO operation to create the site SpoOperation op = tenant.CreateSite(properties); ctx.Load(op, i => i.IsComplete); ctx.ExecuteQuery(); } // Do some branding for the new site SetThemeToNewSite(webUrl); // Do addditional customziations based on the selected template request.Template return(webUrl); }
/// <summary> /// Adds a SiteEntity by launching site collection creation and waits for the creation to finish /// </summary> /// <param name="tenant">A tenant object pointing to the context of a Tenant Administration site</param> /// <param name="properties">Describes the site collection to be created</param> /// <param name="removeFromRecycleBin">It true and site is present in recycle bin, it will be removed first from the recycle bin</param> /// <param name="wait">If true, processing will halt until the site collection has been created</param> /// <returns>Guid of the created site collection and Guid.Empty is the wait parameter is specified as false</returns> public static Guid CreateSiteCollection(this Tenant tenant, SiteEntity properties, bool removeFromRecycleBin = false, bool wait = true) { if (removeFromRecycleBin) { if (tenant.CheckIfSiteExists(properties.Url, SITE_STATUS_RECYCLED)) { tenant.DeleteSiteCollectionFromRecycleBin(properties.Url); } } SiteCreationProperties newsite = new SiteCreationProperties(); newsite.Url = properties.Url; newsite.Owner = properties.SiteOwnerLogin; newsite.Template = properties.Template; newsite.Title = properties.Title; newsite.StorageMaximumLevel = properties.StorageMaximumLevel; newsite.StorageWarningLevel = properties.StorageWarningLevel; newsite.TimeZoneId = properties.TimeZoneId; newsite.UserCodeMaximumLevel = properties.UserCodeMaximumLevel; newsite.UserCodeWarningLevel = properties.UserCodeWarningLevel; newsite.Lcid = properties.Lcid; SpoOperation op = tenant.CreateSite(newsite); tenant.Context.Load(tenant); tenant.Context.Load(op, i => i.IsComplete, i => i.PollingInterval); tenant.Context.ExecuteQueryRetry(); // Get site guid and return. If we create the site asynchronously, return an empty guid as we cannot retrieve the site by URL yet. Guid siteGuid = Guid.Empty; if (wait) { // Let's poll for site collection creation completion WaitForIsComplete(tenant, op); // Add delay to avoid race conditions Thread.Sleep(30 * 1000); // Return site guid of created site collection siteGuid = tenant.GetSiteGuidByUrl(new Uri(properties.Url)); } return siteGuid; }
public string ProcessSiteCreationRequest(ClientContext adminCtx, ProvisioningData provisionData) { // Create the site collection //get the base tenant administration urls var webFullUrl = String.Format("https://{0}.sharepoint.com/{1}/{2}", provisionData.TenantName, "sites", provisionData.RequestData.Url); var tenant = new Tenant(adminCtx); var properties = new SiteCreationProperties() { Url = webFullUrl, Owner = provisionData.RequestData.Owner, Title = provisionData.RequestData.Title, Template = provisionData.RequestData.Template, TimeZoneId = provisionData.RequestData.TimeZoneId, Lcid = provisionData.RequestData.Lcid, StorageMaximumLevel = provisionData.RequestData.StorageMaximumLevel }; //start the SPO operation to create the site SpoOperation op = tenant.CreateSite(properties); adminCtx.Load(tenant); adminCtx.Load(op, i => i.IsComplete); adminCtx.ExecuteQuery(); //check if site creation operation is complete while (!op.IsComplete) { //wait 15 seconds and try again System.Threading.Thread.Sleep(15000); op.RefreshLoad(); adminCtx.ExecuteQuery(); } // Apply branding if theme information is provided if (!string.IsNullOrEmpty(provisionData.BrandingData.ThemeName)) { ApplyTemplateForCreatedSiteCollection(webFullUrl, provisionData); } return webFullUrl; }
public override void DeployModel(object modelHost, DefinitionBase model) { var siteModelHost = modelHost.WithAssertAndCast<SiteModelHost>("modelHost", value => value.RequireNotNull()); //var siteModel = model.WithAssertAndCast<SiteDefinition>("model", value => value.RequireNotNull()); var context = siteModelHost.HostClientContext; var tenant = new Tenant(context); var properties = new SiteCreationProperties() { Url = "https://<TENANT>.sharepoint.com/sites/site1", Owner = "<USER>@<TENANT>.onmicrosoft.com", Template = "STS#0", StorageMaximumLevel = 1000, UserCodeMaximumLevel = 300 }; tenant.CreateSite(properties); context.Load(tenant); context.ExecuteQuery(); }
public override void CreateSiteCollection(SiteInformation siteRequest, Template template) { Log.Info("Provisioning.Common.OnPremSiteProvisioningService.CreateSiteCollection", PCResources.SiteCreation_Creation_Starting, siteRequest.Url); Web _web = null; try { UsingContext(ctx => { Tenant _tenant = new Tenant(ctx); var _newsite = new SiteCreationProperties(); _newsite.Title = siteRequest.Title; _newsite.Url = siteRequest.Url; _newsite.Owner = siteRequest.SiteOwner.Name; _newsite.Template = template.RootTemplate; _newsite.Lcid = siteRequest.Lcid; _newsite.TimeZoneId = siteRequest.TimeZoneId; _newsite.StorageMaximumLevel = template.StorageMaximumLevel; _newsite.StorageWarningLevel = template.StorageWarningLevel; _newsite.UserCodeMaximumLevel = template.UserCodeMaximumLevel; _newsite.UserCodeMaximumLevel = template.UserCodeWarningLevel; _tenant.CreateSite(_newsite); ctx.ExecuteQuery(); Tenant tenant = new Tenant(ctx); var site = tenant.GetSiteByUrl(siteRequest.Url); using (var _cloneCtx = site.Context.Clone(siteRequest.Url)) { _web = _cloneCtx.Site.RootWeb; _web.Description = siteRequest.Description; _web.Update(); _cloneCtx.Load(_web); _cloneCtx.ExecuteQuery(); } }, 1200000); } catch(Exception ex) { Log.Error("Provisioning.Common.OnPremSiteProvisioningService.CreateSiteCollection", PCResources.SiteCreation_Creation_Failure, siteRequest.Url, ex, ex.InnerException); throw; } Log.Info("Provisioning.Common.OnPremSiteProvisioningService.CreateSiteCollection", PCResources.SiteCreation_Creation_Successful, siteRequest.Url); this.HandleDefaultGroups(siteRequest); }
/// <summary> /// Actual business logic to create the site collections. /// See more details on the requirements for on-premises from following blog post: /// http://blogs.msdn.com/b/vesku/archive/2014/06/09/provisioning-site-collections-using-sp-app-model-in-on-premises-with-just-csom.aspx /// </summary> /// <param name="request"></param> /// <returns></returns> private static string ProcessSiteCreationRequest(SiteCollectionRequest request) { // Get the base tenant admin url needed for site collection creation string tenantStr = ConfigurationManager.AppSettings[Consts.AdminSiteCollectionUrl]; // Resolve root site collection URL from host web. string rootSiteUrl = ConfigurationManager.AppSettings[Consts.LeadingURLForSiteCollections]; // Create unique URL based on GUID. In real production implementation you might do this otherways, but this is for simplicity purposes var webUrl = string.Format("{0}/sites/{1}", rootSiteUrl, Guid.NewGuid().ToString().Replace("-", "")); var tenantAdminUri = ConfigurationManager.AppSettings[Consts.AdminSiteCollectionUrl]; // Notice that we do NOT use app model where for this sample. We use just specific service account. Could be easily // changed for example based on following sample: https://github.com/OfficeDev/PnP/tree/master/Samples/Provisioning.OnPrem.Async using (var ctx = new ClientContext(tenantAdminUri)) { ctx.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings[Consts.ProvisioningAccount], ConfigurationManager.AppSettings[Consts.ProvisioningPassword], ConfigurationManager.AppSettings[Consts.ProvisioningDomain]); // Set the time out as high as possible ctx.RequestTimeout = Timeout.Infinite; var tenant = new Tenant(ctx); var properties = new SiteCreationProperties() { Url = webUrl, Owner = string.Format("{0}\\{1}", ConfigurationManager.AppSettings[Consts.ProvisioningDomain], ConfigurationManager.AppSettings[Consts.ProvisioningAccount]), Title = request.Title, Template = "STS#0" // Create always team site, but specialize the site based on the template value }; //start the SPO operation to create the site SpoOperation op = tenant.CreateSite(properties); ctx.Load(op, i => i.IsComplete); ctx.ExecuteQuery(); } // Do some branding for the new site SetThemeToNewSite(webUrl); // Do addditional customziations based on the selected template request.Template return webUrl; }
/// <summary> /// Adds a SiteEntity by launching site collection creation and waits for the creation to finish /// </summary> /// <param name="tenant">A tenant object pointing to the context of a Tenant Administration site</param> /// <param name="properties">Describes the site collection to be created</param> /// <param name="removeSiteFromRecycleBin">It true and site is present in recycle bin, it will be removed first from the recycle bin</param> /// <param name="wait">If true, processing will halt until the site collection has been created</param> /// <returns>Guid of the created site collection</returns> public static Guid CreateSiteCollection(this Tenant tenant, SiteEntity properties, bool removeFromRecycleBin = false, bool wait = true) { if (removeFromRecycleBin) { if (tenant.CheckIfSiteExists(properties.Url, SITE_STATUS_RECYCLED)) { tenant.DeleteSiteCollectionFromRecycleBin(properties.Url); } } SiteCreationProperties newsite = new SiteCreationProperties(); newsite.Url = properties.Url; newsite.Owner = properties.SiteOwnerLogin; newsite.Template = properties.Template; newsite.Title = properties.Title; newsite.StorageMaximumLevel = properties.StorageMaximumLevel; newsite.StorageWarningLevel = properties.StorageWarningLevel; newsite.TimeZoneId = properties.TimeZoneId; newsite.UserCodeMaximumLevel = properties.UserCodeMaximumLevel; newsite.UserCodeWarningLevel = properties.UserCodeWarningLevel; newsite.Lcid = properties.Lcid; try { SpoOperation op = tenant.CreateSite(newsite); tenant.Context.Load(tenant); tenant.Context.Load(op, i => i.IsComplete, i => i.PollingInterval); tenant.Context.ExecuteQuery(); if (wait) { //check if site creation operation is complete while (!op.IsComplete) { System.Threading.Thread.Sleep(op.PollingInterval); op.RefreshLoad(); if (!op.IsComplete) { try { tenant.Context.ExecuteQuery(); } catch (WebException webEx) { // Context connection gets closed after action completed. // Calling ExecuteQuery again returns an error which can be ignored LoggingUtility.Internal.TraceWarning((int)EventId.ClosedContextWarning, webEx, CoreResources.TenantExtensions_ClosedContextWarning); } } } } } catch (Exception ex) { // Eat the siteSubscription exception to make the same code work for MT as on-prem April 2014 CU+ if (ex.Message.IndexOf("Parameter name: siteSubscription") == -1) { throw; } } // Get site guid and return var siteGuid = tenant.GetSiteGuidByUrl(new Uri(properties.Url)); return siteGuid; }
private static string ProcessSiteCreationRequest(ClientContext ctx, ListItem listItem) { // Create the site collection //get the base tenant admin urls string tenantStr = ConfigurationManager.AppSettings["SiteCollectionRequests_SiteUrl"]; tenantStr = tenantStr.ToLower().Replace("-my", "").Substring(8); tenantStr = tenantStr.Substring(0, tenantStr.IndexOf(".")); //create site collection using the Tenant object var webUrl = String.Format("https://{0}.sharepoint.com/{1}/{2}", tenantStr, "sites", listItem["SiteUrl"]); var tenantAdminUri = new Uri(String.Format("https://{0}-admin.sharepoint.com", tenantStr)); string realm = TokenHelper.GetRealmFromTargetUrl(tenantAdminUri); var token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, tenantAdminUri.Authority, realm).AccessToken; using (var adminContext = TokenHelper.GetClientContextWithAccessToken(tenantAdminUri.ToString(), token)) { var tenant = new Tenant(adminContext); var properties = new SiteCreationProperties() { Url = webUrl, Owner = listItem["RequestorEmail"].ToString(), Title = listItem["Title"].ToString(), Template = listItem["Template"].ToString(), StorageMaximumLevel = 100, UserCodeMaximumLevel = 100 }; //start the SPO operation to create the site SpoOperation op = tenant.CreateSite(properties); adminContext.Load(tenant); adminContext.Load(op, i => i.IsComplete); adminContext.ExecuteQuery(); //check if site creation operation is complete while (!op.IsComplete) { //wait 15 seconds and try again System.Threading.Thread.Sleep(15000); op.RefreshLoad(); adminContext.ExecuteQuery(); } } ApplyTemplateForCreatedSiteCollection(webUrl, token, realm); return webUrl; }
/// <summary> /// /// </summary> /// <param name="hostWebUrl"></param> /// <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="baseConfiguration"></param> /// <returns></returns> public Web CreateSiteCollection(string hostWebUrl, string txtUrl, string template, string title, string description, Microsoft.SharePoint.Client.ClientContext cc, Page page, XDocument baseConfiguration) { //get the template element XElement templateConfig = GetTemplateConfig(template, baseConfiguration); string siteTemplate = SolveUsedTemplate(template, templateConfig); //get the base tenant admin urls var tenantStr = hostWebUrl.ToLower().Replace("-my", "").Substring(8); tenantStr = tenantStr.Substring(0, tenantStr.IndexOf(".")); //get the current user to set as owner var currUser = cc.Web.CurrentUser; cc.Load(currUser); cc.ExecuteQuery(); //create site collection using the Tenant object var webUrl = String.Format("https://{0}.sharepoint.com/{1}/{2}", tenantStr, templateConfig.Attribute("ManagedPath").Value, txtUrl); var tenantAdminUri = new Uri(String.Format("https://{0}-admin.sharepoint.com", tenantStr)); string realm = TokenHelper.GetRealmFromTargetUrl(tenantAdminUri); var token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, tenantAdminUri.Authority, realm).AccessToken; using (var adminContext = TokenHelper.GetClientContextWithAccessToken(tenantAdminUri.ToString(), token)) { var tenant = new Tenant(adminContext); var properties = new SiteCreationProperties() { Url = webUrl, Owner = currUser.Email, Title = title, Template = siteTemplate, StorageMaximumLevel = Convert.ToInt32(templateConfig.Attribute("StorageMaximumLevel").Value), UserCodeMaximumLevel = Convert.ToDouble(templateConfig.Attribute("UserCodeMaximumLevel").Value) }; //start the SPO operation to create the site SpoOperation op = tenant.CreateSite(properties); adminContext.Load(tenant); adminContext.Load(op, i => i.IsComplete); adminContext.ExecuteQuery(); //check if site creation operation is complete while (!op.IsComplete) { //wait 30seconds and try again System.Threading.Thread.Sleep(30000); op.RefreshLoad(); adminContext.ExecuteQuery(); } } //get the new site collection var siteUri = new Uri(webUrl); token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken; using (var newWebContext = TokenHelper.GetClientContextWithAccessToken(siteUri.ToString(), token)) { var newWeb = newWebContext.Web; newWebContext.Load(newWeb); newWebContext.ExecuteQuery(); //process the remiander of the template configuration DeployFiles(newWebContext, newWeb, templateConfig); DeployCustomActions(newWebContext, newWeb, templateConfig); DeployLists(newWebContext, newWeb, templateConfig); DeployNavigation(newWebContext, newWeb, templateConfig); DeployTheme(newWebContext, newWeb, templateConfig, baseConfiguration); SetSiteLogo(newWebContext, newWeb, templateConfig); // All done, let's return the newly created site return newWeb; } }
private static string ProcessSiteCreationRequest(ClientContext ctx, ListItem listItem) { //get the base tenant admin urls string tenantStr = ConfigurationManager.AppSettings["SiteCollectionRequests_SiteUrl"]; // Resolve root site collection URL from host web. We assume that this has been set as the "TenantAdminSite" string rootSiteUrl = tenantStr.Substring(0, 8 + tenantStr.Substring(8).IndexOf("/")); //Resolve URL for the new site collection var webUrl = string.Format("{0}/sites/{1}", rootSiteUrl, listItem["SiteUrl"].ToString()); var tenantAdminUri = new Uri(rootSiteUrl); string realm = TokenHelper.GetRealmFromTargetUrl(tenantAdminUri); var token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, tenantAdminUri.Authority, realm).AccessToken; using (var adminContext = TokenHelper.GetClientContextWithAccessToken(tenantAdminUri.ToString(), token)) { // Set the time out as high as possible adminContext.RequestTimeout = int.MaxValue; var tenant = new Tenant(adminContext); var properties = new SiteCreationProperties() { Url = webUrl, Owner = listItem["AdminAccount"].ToString(), Title = listItem["Title"].ToString(), Template = listItem["Template"].ToString(), }; //start the SPO operation to create the site SpoOperation op = tenant.CreateSite(properties); adminContext.Load(op, i => i.IsComplete); adminContext.RequestTimeout = int.MaxValue; adminContext.ExecuteQuery(); } // Do some branding for the new site SetThemeToNewSite(webUrl); return webUrl; }
/// <summary> /// Method to create site collections /// </summary> /// <param name="clientContext">SharePoint Client Context</param> /// <param name="configVal">Values in Config sheet</param> /// <param name="clientUrl">Url for Site Collection</param> /// <param name="clientTitle">Name of Site Collection</param> internal static void CreateSiteCollections(ClientContext clientContext, Dictionary<string, string> configVal, string clientUrl, string clientTitle) { try { Tenant tenant = new Tenant(clientContext); clientContext.Load(tenant); clientContext.ExecuteQuery(); //login into SharePoint Online SPOSitePropertiesEnumerable spoSiteProperties = tenant.GetSiteProperties(0, true); clientContext.Load(spoSiteProperties); clientContext.ExecuteQuery(); SiteProperties siteProperties = (from properties in spoSiteProperties where properties.Url.ToString().ToUpper() == clientUrl.ToUpper() select properties).FirstOrDefault(); if (null != siteProperties) { // site exists Console.WriteLine(clientUrl + " already exists..."); return; } else { // site does not exists SiteCreationProperties newSite = new SiteCreationProperties() { Url = clientUrl, Owner = configVal["Username"], Template = ConfigurationManager.AppSettings["template"], //using the team site template, check the MSDN if you want to use other template StorageMaximumLevel = Convert.ToInt64(ConfigurationManager.AppSettings["storageMaximumLevel"], CultureInfo.InvariantCulture), //1000 UserCodeMaximumLevel = Convert.ToDouble(ConfigurationManager.AppSettings["userCodeMaximumLevel"], CultureInfo.InvariantCulture), //300 Title = clientTitle, CompatibilityLevel = 15, //15 means SharePoint online 2013, 14 means SharePoint online 2010 }; SpoOperation spo = tenant.CreateSite(newSite); clientContext.Load(tenant); clientContext.Load(spo, operation => operation.IsComplete); clientContext.ExecuteQuery(); Console.WriteLine("Creating site collection at " + clientUrl); Console.WriteLine("Loading."); //Check if provisioning of the SiteCollection is complete. while (!spo.IsComplete) { Console.Write("."); //Wait for 30 seconds and then try again System.Threading.Thread.Sleep(30000); spo.RefreshLoad(); clientContext.ExecuteQuery(); } Console.WriteLine("Site Collection: " + clientUrl + " is created successfully"); } } catch (Exception exception) { Console.WriteLine("Exception occurred while creating site collection: " + exception.Message); } }
/// <summary> /// Make a Site using SPO /// </summary> /// <param name="siteUrl">Url of the site to make</param> /// <param name="title">Title of the site to make</param> /// <param name="owner">Email of the account that will be the site owner</param> /// <param name="template">Name of the site template to use. e.g. STS#0</param> /// <param name="storageMaximumLevel">Maximum size of the site in MB</param> /// <param name="userCodeMaximumLevel">UserCode Resource Points Allowed</param> public void ProvisionSite(Uri siteUrl, string title, string owner, string template, int storageMaximumLevel, int userCodeMaximumLevel) { if (siteUrl == null) throw new ArgumentNullException("siteUrl"); if (string.IsNullOrEmpty(title)) throw new ArgumentNullException("title"); if (string.IsNullOrEmpty(owner)) throw new ArgumentNullException("owner"); if (string.IsNullOrEmpty(template)) throw new ArgumentNullException("template"); var tenant = new Tenant(_client); var siteCreationProperties = new SiteCreationProperties { Url = siteUrl.ToString(), Title = title, Owner = owner, Template = template, StorageMaximumLevel = storageMaximumLevel, UserCodeMaximumLevel = userCodeMaximumLevel }; SpoOperation spo = tenant.CreateSite(siteCreationProperties); ExecuteAndWaitForCompletion(tenant, spo); }
/// <summary> /// Adds a SiteEntity by launching site collection creation and waits for the creation to finish /// </summary> /// <param name="tenant">A tenant object pointing to the context of a Tenant Administration site</param> /// <param name="properties">Describes the site collection to be created</param> /// <param name="removeFromRecycleBin">It true and site is present in recycle bin, it will be removed first from the recycle bin</param> /// <param name="wait">If true, processing will halt until the site collection has been created</param> /// <returns>Guid of the created site collection and Guid.Empty is the wait parameter is specified as false</returns> public static Guid CreateSiteCollection(this Tenant tenant, SiteEntity properties, bool removeFromRecycleBin = false, bool wait = true) { if (removeFromRecycleBin) { if (tenant.CheckIfSiteExists(properties.Url, SITE_STATUS_RECYCLED)) { tenant.DeleteSiteCollectionFromRecycleBin(properties.Url); } } SiteCreationProperties newsite = new SiteCreationProperties(); newsite.Url = properties.Url; newsite.Owner = properties.SiteOwnerLogin; newsite.Template = properties.Template; newsite.Title = properties.Title; newsite.StorageMaximumLevel = properties.StorageMaximumLevel; newsite.StorageWarningLevel = properties.StorageWarningLevel; newsite.TimeZoneId = properties.TimeZoneId; newsite.UserCodeMaximumLevel = properties.UserCodeMaximumLevel; newsite.UserCodeWarningLevel = properties.UserCodeWarningLevel; newsite.Lcid = properties.Lcid; SpoOperation op = tenant.CreateSite(newsite); tenant.Context.Load(tenant); tenant.Context.Load(op, i => i.IsComplete, i => i.PollingInterval); tenant.Context.ExecuteQueryRetry(); // Get site guid and return. If we create the site asynchronously, return an empty guid as we cannot retrieve the site by URL yet. Guid siteGuid = Guid.Empty; if (wait) { // Let's poll for site collection creation completion WaitForIsComplete(tenant, op); // Add delay to avoid race conditions Thread.Sleep(30 * 1000); // Return site guid of created site collection try { siteGuid = tenant.GetSiteGuidByUrl(new Uri(properties.Url)); } catch(Exception ex) { // Eat all exceptions cause there's currently (December 16) an issue in the service that can make this call fail in combination with app-only usage Log.Error("Temp eating exception to issue in service (December 2016). Exception is {0}.", ex.ToDetailedString()); } } return siteGuid; }
private string CreateSiteCollection(string hostWebUrl, string url, string template, string title, string adminAccount) { // Resolve root site collection URL from host web. We assume that this has been set as the "TenantAdminSite" string rootSiteUrl = hostWebUrl.Substring(0, 8 + hostWebUrl.Substring(8).IndexOf("/")); //Resolve URL for the new site collection var webUrl = string.Format("{0}/sites/{1}", rootSiteUrl, url); // Notice that this assumes that AdministrationSiteType as been set as TenantAdministration for root site collection // If this tenant admin URI is pointing to site collection which is host named site collection, code does create host named site collection as well var tenantAdminUri = new Uri(rootSiteUrl); string realm = TokenHelper.GetRealmFromTargetUrl(tenantAdminUri); var token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, tenantAdminUri.Authority, realm).AccessToken; using (var adminContext = TokenHelper.GetClientContextWithAccessToken(tenantAdminUri.ToString(), token)) { var tenant = new Tenant(adminContext); var properties = new SiteCreationProperties() { Url = webUrl, Owner = adminAccount, Title = title, Template = template }; //start the SPO operation to create the site SpoOperation op = tenant.CreateSite(properties); adminContext.Load(op, i => i.IsComplete); adminContext.ExecuteQuery(); } // Set theme for the new site SetThemeToNewSite(webUrl); // Return URL for redirection return webUrl; }
public override void CreateSiteCollection(SiteInformation siteRequest, Template template) { Log.Info("Provisioning.Common.Office365SiteProvisioningService.CreateSiteCollection", PCResources.SiteCreation_Creation_Starting, siteRequest.Url); UsingContext(ctx => { try { Stopwatch _timespan = Stopwatch.StartNew(); bool timeout_detected = false; Tenant _tenant = new Tenant(ctx); var _newsite = new SiteCreationProperties(); _newsite.Title = siteRequest.Title; _newsite.Url = siteRequest.Url; _newsite.Owner = siteRequest.SiteOwner.Name; _newsite.Template = template.RootTemplate; _newsite.Lcid = siteRequest.Lcid; _newsite.TimeZoneId = siteRequest.TimeZoneId; _newsite.StorageMaximumLevel = template.StorageMaximumLevel; _newsite.StorageWarningLevel = template.StorageWarningLevel; _newsite.UserCodeMaximumLevel = template.UserCodeMaximumLevel; _newsite.UserCodeMaximumLevel = template.UserCodeWarningLevel; SpoOperation op = _tenant.CreateSite(_newsite); ctx.Load(_tenant); ctx.Load(op, i => i.IsComplete); try { ctx.ExecuteQuery(); while (!op.IsComplete) { //wait 30seconds and try again System.Threading.Thread.Sleep(30000); op.RefreshLoad(); ctx.ExecuteQuery(); // we need this one in Azure Web jobs (it pings the service so it knows it's still alive) Log.Info("Provisioning.Common.Office365SiteProvisioningService.CreateSiteCollection", "Waiting for Site Collection to be created...."); } } catch (WebException we) { if (we.Status != WebExceptionStatus.Timeout) { Log.Info("Provisioning.Common.Office365SiteProvisioningService.CreateSiteCollection", "Creation WebException (" + we.ToString() + ")"); throw; } } Site _site = null; // NOTE: this is experimental due to current issues with the site collection creation while (_site == null) { try { _site = _tenant.GetSiteByUrl(siteRequest.Url); } catch (Exception ex) { _site = null; Log.Info("Provisioning.Common.Office365SiteProvisioningService.CreateSiteCollection", "Waiting for Site Collection to be created (" + ex.ToString() + ")"); System.Threading.Thread.Sleep(30000); } } var _web = _site.RootWeb; _web.Description = siteRequest.Description; _web.Update(); ctx.Load(_web); ctx.ExecuteQuery(); _timespan.Stop(); Log.TraceApi("SharePoint", "Office365SiteProvisioningService.CreateSiteCollection", _timespan.Elapsed, "SiteUrl={0}", siteRequest.Url); } catch (Exception ex) { Log.Error("Provisioning.Common.Office365SiteProvisioningService.CreateSiteCollection", PCResources.SiteCreation_Creation_Failure, siteRequest.Url, ex.Message, ex); throw; } Log.Info("Provisioning.Common.Office365SiteProvisioningService.CreateSiteCollection", PCResources.SiteCreation_Creation_Successful, siteRequest.Url); }, 25000); }
/// <summary> /// Creates a site collection /// </summary> /// <param name="ctx"></param> /// <param name="hostWebUrl"></param> /// <param name="url"></param> /// <param name="template"></param> /// <param name="title"></param> /// <param name="description"></param> /// <returns></returns> private static string CreateSiteCollection(ClientContext ctx, string hostWebUrl, string url, string template, string title, string description, string ownerEmail, ProvisioningTemplate provisioningTemplate = null) { //get the base tenant admin urls var tenantStr = hostWebUrl.ToLower().Replace("-my", "").Substring(8); tenantStr = tenantStr.Substring(0, tenantStr.IndexOf(".")); //get the current user to set as owner var currUser = ctx.Web.CurrentUser; ctx.Load(currUser); ctx.ExecuteQuery(); //create site collection using the Tenant object var webUrl = String.Format("https://{0}.sharepoint.com/{1}/{2}", tenantStr, "sites", url); var tenantAdminUri = new Uri(String.Format("https://{0}-admin.sharepoint.com", tenantStr)); string realm = TokenHelper.GetRealmFromTargetUrl(tenantAdminUri); var token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, tenantAdminUri.Authority, realm).AccessToken; using (var adminContext = TokenHelper.GetClientContextWithAccessToken(tenantAdminUri.ToString(), token)) { var tenant = new Tenant(adminContext); var properties = new SiteCreationProperties() { Url = webUrl, Owner = ownerEmail, Title = title, Template = template, StorageMaximumLevel = 100, UserCodeMaximumLevel = 100 }; //start the SPO operation to create the site if (tenant.SiteExists(webUrl)) throw new Exception(String.Format("A site at URL {0} already exists.", webUrl)); SpoOperation op = tenant.CreateSite(properties); adminContext.Load(tenant); adminContext.Load(op, i => i.IsComplete); adminContext.ExecuteQuery(); // Set timeout for the request - notice that since we are using web site, this could still time out adminContext.RequestTimeout = Timeout.Infinite; //check if site creation operation is complete while (!op.IsComplete) { //wait 30seconds and try again System.Threading.Thread.Sleep(30000); op.RefreshLoad(); adminContext.ExecuteQuery(); } } //get the new site collection var siteUri = new Uri(webUrl); token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken; using (var newWebContext = TokenHelper.GetClientContextWithAccessToken(siteUri.ToString(), token)) { var newWeb = newWebContext.Web; newWebContext.Load(newWeb); newWebContext.ExecuteQuery(); if (provisioningTemplate != null) { //Delegate for logging var applyingInfo = new ProvisioningTemplateApplyingInformation(); applyingInfo.ProgressDelegate = (message, step, total) => { Console.WriteLine("{0}/{1} Provisioning {2}", step, total, message); }; //Add owner to PSC Owners site group try { //Add owner to PSC Owners site group var pscOwners = provisioningTemplate.Security.SiteGroups.Where(p => p.Title == "PSC Owners").FirstOrDefault(); var user = new OfficeDevPnP.Core.Framework.Provisioning.Model.User(); user.Name = ownerEmail; pscOwners.Members.Add(user); } catch (Exception ex) { Console.WriteLine("Could not add user {0} to PSC Owners group. Exception: {1}", ownerEmail, ex.Message); } newWeb.ApplyProvisioningTemplate(provisioningTemplate, applyingInfo); //Post-template changes ApplyPostTemplateModifications(newWeb.Url, SiteType.SiteCollection); } // All done, let's return the newly created site return newWeb.Url; } }
public override void CreateSiteCollection(SiteInformation siteRequest, Template template) { Log.Info("Provisioning.Common.Office365SiteProvisioningService.CreateSiteCollection", PCResources.SiteCreation_Creation_Starting, siteRequest.Url); UsingContext(ctx => { try { Stopwatch _timespan = Stopwatch.StartNew(); Tenant _tenant = new Tenant(ctx); var _newsite = new SiteCreationProperties(); _newsite.Title = siteRequest.Title; _newsite.Url = siteRequest.Url; _newsite.Owner = siteRequest.SiteOwner.Email; _newsite.Template = template.RootTemplate; _newsite.Lcid = siteRequest.Lcid; _newsite.TimeZoneId = siteRequest.TimeZoneId; _newsite.StorageMaximumLevel = template.StorageMaximumLevel; _newsite.StorageWarningLevel = template.StorageWarningLevel; _newsite.UserCodeMaximumLevel = template.UserCodeMaximumLevel; _newsite.UserCodeMaximumLevel = template.UserCodeWarningLevel; try { SpoOperation _spoOperation = _tenant.CreateSite(_newsite); ctx.Load(_tenant); ctx.Load(_spoOperation); ctx.ExecuteQuery(); try { this.OperationWithRetry(ctx, _spoOperation, siteRequest); } 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.CreateSiteCollection", _message); throw; } } 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.CreateSiteCollection", _message); throw; } var _site = _tenant.GetSiteByUrl(siteRequest.Url); var _web = _site.RootWeb; _web.Description = siteRequest.Description; _web.Update(); ctx.Load(_web); ctx.ExecuteQuery(); User newOwner = _web.EnsureUser(siteRequest.SiteOwner.Email); ctx.Load(newOwner); ctx.ExecuteQuery(); if (!newOwner.ServerObjectIsNull.Value) { //_site.Owner = newOwner; //ctx.Load(_site); //ctx.Load(_site.Owner); //ctx.ExecuteQuery(); newOwner.IsSiteAdmin = true; newOwner.Update(); ctx.Load(newOwner); ctx.ExecuteQuery(); } _timespan.Stop(); Log.TraceApi("SharePoint", "Office365SiteProvisioningService.CreateSiteCollection", _timespan.Elapsed, "SiteUrl={0}", siteRequest.Url); } catch (Exception ex) { Log.Error("Provisioning.Common.Office365SiteProvisioningService.CreateSiteCollection", PCResources.SiteCreation_Creation_Failure, siteRequest.Url, ex.Message, ex); throw; } Log.Info("Provisioning.Common.Office365SiteProvisioningService.CreateSiteCollection", PCResources.SiteCreation_Creation_Successful, siteRequest.Url); }, SPDataConstants.CSOM_WAIT_TIME); }
private static string ProcessSiteCreationRequest(ClientContext ctx, ListItem listItem) { //get the base tenant admin urls string tenantStr = ConfigurationManager.AppSettings["SiteCollectionRequests_SiteUrl"]; // Resolve root site collection URL from host web. We assume that this has been set as the "TenantAdminSite" string rootSiteUrl = tenantStr.Substring(0, 8 + tenantStr.Substring(8).IndexOf("/")); //Resolve URL for the new site collection var webUrl = string.Format("{0}/sites/{1}", rootSiteUrl, listItem["SiteUrl"].ToString()); var tenantAdminUri = new Uri(rootSiteUrl); string realm = TokenHelper.GetRealmFromTargetUrl(tenantAdminUri); var token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, tenantAdminUri.Authority, realm).AccessToken; using (var actx = TokenHelper.GetClientContextWithAccessToken(tenantAdminUri.ToString(), token)) { // Set the time out as high as possible actx.RequestTimeout = Timeout.Infinite; // Create tenant object - used for on-premises as well var tenant = new Tenant(actx); // Get the request details for the site creation object var properties = new SiteCreationProperties() { Url = webUrl, Owner = listItem["AdminAccount"].ToString(), Title = listItem["Title"].ToString(), Template = listItem["Template"].ToString(), }; // Start the operation to create the site SpoOperation op = tenant.CreateSite(properties); // Notice that following line is synchronious in on-premises actx.ExecuteQuery(); } // Apply needed customizations to just created site collection SetThemeToNewSite(webUrl); return webUrl; }
public string CreateSiteCollection() { var user = GetSpUser.ResolveUserById(_ctx, _actionRequest.User); var tenant = new Tenant(_ctx); var webUrl = $"https://{_actionRequest.TenantName}.sharepoint.com/{_siteCollectionRequest.ManagedPath}/{_actionRequest.Name}"; if (tenant.SiteExists(webUrl)) { // "Site already existed. Used URL - {0}" } else { var newsite = new SiteCreationProperties { Title = _actionRequest.Name, Url = webUrl, Owner = user.Email, Template = "STS#0", Lcid = _siteCollectionRequest.Lcid, TimeZoneId = _siteCollectionRequest.TimeZoneId, StorageMaximumLevel = _siteCollectionRequest.StorageMaximumLevel, StorageWarningLevel = _siteCollectionRequest.StorageMaximumLevel, UserCodeMaximumLevel = 0, UserCodeWarningLevel = 0 }; SpoOperation op = tenant.CreateSite(newsite); _ctx.Load(tenant); _ctx.Load(op, i => i.IsComplete); _ctx.ExecuteQuery(); var step = 0; while (!op.IsComplete) { step = step + 1; Updatehelper.UpdateProgressView($"{step} Creating site collection", _actionRequest); Thread.Sleep(10000); op.RefreshLoad(); _ctx.ExecuteQuery(); } } var site = tenant.GetSiteByUrl(webUrl); var web = site.RootWeb; web.Description = _actionRequest.Description; web.Update(); _ctx.Load(web); _ctx.ExecuteQuery(); return web.Url; }