//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(); } }
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(); } }); }
private bool WaitForIsComplete(ClientContext context, SpoOperation op, Func <TenantOperationMessage, bool> timeoutFunction = null, TenantOperationMessage operationMessage = TenantOperationMessage.None) { bool succeeded = true; while (!op.IsComplete) { if (timeoutFunction != null && timeoutFunction(operationMessage)) { succeeded = false; break; } Thread.Sleep(op.PollingInterval); op.RefreshLoad(); if (!op.IsComplete) { try { context.ExecuteQueryRetry(); } catch (WebException) { // Context connection gets closed after action completed. // Calling ExecuteQuery again returns an error which can be ignored } } } return(succeeded); }
/// <summary> /// Deletes a site collection from the site collection recyle bin /// </summary> /// <param name="web">Site to be processed - can be root web or sub site</param> /// <param name="siteUrl">URL of the site collection to delete</param> /// <returns>True if deleted</returns> public static bool DeleteSiteCollectionFromRecycleBinTenant(this Web web, string siteUrl) { bool ret = false; Tenant tenant = new Tenant(web.Context); SpoOperation op = tenant.RemoveDeletedSite(siteUrl); web.Context.Load(op, i => i.IsComplete, i => i.PollingInterval); web.Context.ExecuteQuery(); 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); } } } ret = true; return(ret); }
private void OperationWithRetry(ClientContext ctx, SpoOperation operation, SiteInformation siteRequest) { int currentRetry = 0; for (;;) { try { System.Threading.Thread.Sleep(30000); ctx.Load(operation); ctx.ExecuteQuery(); Log.Info("Provisioning.Common.Office365SiteProvisioningService.CreateSiteCollection", "Waiting for Site Collection {0} to be created", siteRequest.Url); if (operation.IsComplete) { break; } } catch (Exception ex) { currentRetry++; if (currentRetry > this._retryCount || !IsTransientException(ex)) { throw; } } } }
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); }
/// <summary> /// Sets a site to Unlock access or NoAccess. This operation may occur immediately, but the site lock may take a short while before it goes into effect. /// </summary> /// <param name="tenant">A tenant object pointing to the context of a Tenant Administration site (i.e. https://[tenant]-admin.sharepoint.com)</param> /// <param name="siteFullUrl">The target site to change the lock state.</param> /// <param name="lockState">The target state the site should be changed to.</param> /// <param name="wait">If true, processing will halt until the site collection lock state has been implemented</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> public static void SetSiteLockState(this Tenant tenant, string siteFullUrl, SiteLockState lockState, bool wait = false, Func <TenantOperationMessage, bool> timeoutFunction = null) { var siteProps = tenant.GetSitePropertiesByUrl(siteFullUrl, true); tenant.Context.Load(siteProps); tenant.Context.ExecuteQueryRetry(); Log.Info(CoreResources.TenantExtensions_SetLockState, siteProps.LockState, lockState); if (siteProps.LockState != lockState.ToString()) { siteProps.LockState = lockState.ToString(); SpoOperation op = siteProps.Update(); tenant.Context.Load(op, i => i.IsComplete, i => i.PollingInterval); tenant.Context.ExecuteQueryRetry(); if (timeoutFunction != null) { wait = true; } if (wait) { WaitForIsComplete(tenant, op, timeoutFunction, TenantOperationMessage.SettingSiteLockState); } } }
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 static void ProvisionSiteCollection() { try { //Check if Site Collection is exist var siteCtx = AuthHelper.GetClientContext(); bool isSiteExist = false; // This will not check if Site Collection is deleted and available in Recycle bin if (siteCtx.WebExistsFullUrl(AuthHelper.siteUrl)) { isSiteExist = true; } //Create Context of SPO Admin var tenantCtx = AuthHelper.GetTenantContext(); var tenant = new Tenant(tenantCtx); SpoOperation spo = null; if (isSiteExist) { DeleteSiteCollectionAndRecycled(spo, tenantCtx, tenant); RemoveSiteFromRecycleBin(spo, tenantCtx, tenant); } else { CreateSiteCollection(spo, tenantCtx, tenant); } } catch (Exception) { throw; } }
private static bool WaitForIsComplete(Tenant tenant, SpoOperation op, Func <TenantOperationMessage, bool> timeoutFunction = null, TenantOperationMessage operationMessage = TenantOperationMessage.None) { bool succeeded = true; while (!op.IsComplete) { if (timeoutFunction != null && timeoutFunction(operationMessage)) { succeeded = false; break; } Thread.Sleep(op.PollingInterval); op.RefreshLoad(); if (!op.IsComplete) { try { tenant.Context.ExecuteQueryRetry(); } catch (WebException webEx) { // Context connection gets closed after action completed. // Calling ExecuteQuery again returns an error which can be ignored Log.Warning(CoreResources.TenantExtensions_ClosedContextWarning, webEx.Message); } } } return(succeeded); }
/// <summary> /// Deletes a site collection from the site collection recycle bin /// </summary> /// <param name="tenant">A tenant object pointing to the context of a Tenant Administration site</param> /// <param name="siteFullUrl">URL of the site collection to delete</param> /// <returns>True if deleted</returns> public static bool DeleteSiteCollectionFromRecycleBin(this Tenant tenant, string siteFullUrl) { bool ret = false; SpoOperation op = tenant.RemoveDeletedSite(siteFullUrl); tenant.Context.Load(op, i => i.IsComplete, i => i.PollingInterval); tenant.Context.ExecuteQuery(); 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); } } } ret = true; return(ret); }
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 ProcessResponse(string response) { #region Json response /* * [ * { * "SchemaVersion": "15.0.0.0", * "LibraryVersion": "16.0.21722.12002", * "ErrorInfo": null, * "TraceCorrelationId": "fd97f49f-8009-3000-4ac5-078be4dab272" * }, * 3, * { * "_ObjectType_": "Microsoft.Online.SharePoint.TenantAdministration.SpoOperation", * "_ObjectIdentity_": "fd97f49f-8009-3000-4ac5-078be4dab272|908bed80-a04a-4433-b4a0-883d9847d110:6492ece7-7f5d-4499-8130-50e761e25bd9\nSpoOperation\nRemoveSite\n637686125576711919\nhttps%3a%2f%2fbertonline.sharepoint.com%2fsites%2f130021\n35708a6b-88bc-4c47-9c13-d227dabbee4d", * "PollingInterval": 15000, * "IsComplete": true * } * ] */ #endregion SpoOperation resultItem = ResponseHelper.ProcessResponse <SpoOperation>(response, QueryIdPath); Result = resultItem; }
/// <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 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); }); }
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); }
/// <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); }
private static void RemoveSiteFromRecycleBin(SpoOperation spo, ClientContext tenantCtx, Tenant tenant) { //Removing Site Collection from Recycle bin spo = tenant.RemoveDeletedSite(AuthHelper.siteUrl); tenantCtx.Load(spo, i => i.IsComplete); tenantCtx.ExecuteQuery(); var msg = "Removing Site Collection from Recycle bin process..."; WaitForOperation(tenantCtx, spo, msg); }
public void ProcessResponse(string response) { #region Json response /* */ #endregion SpoOperation resultItem = ResponseHelper.ProcessResponse <SpoOperation>(response, QueryIdPath); Result = resultItem; }
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); }
/// <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); }
private static void DeleteSiteCollectionAndRecycled(SpoOperation spo, ClientContext tenantCtx, Tenant tenant) { // Remove SiteCollection, it will go to Recycle bin spo = tenant.RemoveSite(AuthHelper.siteUrl); tenantCtx.Load(tenant); //Get the IsComplete property to check if the Site Collection is been removed. tenantCtx.Load(spo, i => i.IsComplete); tenantCtx.ExecuteQuery(); var msg = "Site Collection Recycling process..."; WaitForOperation(tenantCtx, spo, msg); }
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 }
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); }
private static void WaitForOperation(ClientContext tenantCtx, SpoOperation spo, string msg) { Console.WriteLine($"{msg} status: {"Waiting"}"); while (!spo.IsComplete) { //Wait for 15 seconds and then try again Thread.Sleep(15000); //tenantCtx.Load(spo); spo.RefreshLoad(); tenantCtx.ExecuteQuery(); } Console.WriteLine($"{msg} status: {"Completed"}"); }
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> /// Deletes a site collection from the site collection recycle bin /// </summary> /// <param name="tenant">A tenant object pointing to the context of a Tenant Administration site</param> /// <param name="siteFullUrl">URL of the site collection to delete</param> /// <param name="wait">If true, processing will halt until the site collection has been deleted from the recycle bin</param> /// <returns>True if deleted</returns> public static bool DeleteSiteCollectionFromRecycleBin(this Tenant tenant, string siteFullUrl, bool wait = true) { bool ret = false; SpoOperation op = tenant.RemoveDeletedSite(siteFullUrl); tenant.Context.Load(op, i => i.IsComplete, i => i.PollingInterval); tenant.Context.ExecuteQueryRetry(); if (wait) { WaitForIsComplete(tenant, op); } ret = true; return(ret); }
/// <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); }
internal static void WaitForOperation(SpoOperation longRunningOperation, String operation = "") { if (!string.IsNullOrEmpty(operation)) { Console.WriteLine("Waiting for : {0}", operation); } var polTime = longRunningOperation.PollingInterval; while (!longRunningOperation.IsComplete && !longRunningOperation.HasTimedout) { Thread.Sleep(polTime); Console.Write("..."); longRunningOperation.Context.Load(longRunningOperation); longRunningOperation.Context.ExecuteQuery(); } if (longRunningOperation.IsComplete) { Console.WriteLine("Completed"); } }
private void OperationWithRetry(ClientContext ctx, SpoOperation operation, SiteInformation siteRequest) { int currentRetry = 0; for (;;) { try { System.Threading.Thread.Sleep(30000); ctx.Load(operation); ctx.ExecuteQuery(); Log.Info("Provisioning.Common.Office365SiteProvisioningService.CreateSiteCollection", "Waiting for Site Collection {0} to be created", siteRequest.Url); if (operation.IsComplete) break; } catch (Exception ex) { currentRetry++; if (currentRetry > this._retryCount || !IsTransientException(ex)) { throw; } } } }
private static void WaitForIsComplete(Tenant tenant, SpoOperation op) { 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); } } } }
private static void WaitForIsComplete(Tenant tenant, SpoOperation op) { while (!op.IsComplete) { Thread.Sleep(op.PollingInterval); op.RefreshLoad(); if (!op.IsComplete) { try { tenant.Context.ExecuteQueryRetry(); } catch (WebException webEx) { // Context connection gets closed after action completed. // Calling ExecuteQuery again returns an error which can be ignored Log.Warning(CoreResources.TenantExtensions_ClosedContextWarning, webEx.Message); } } } }
/// <summary> /// Executes tennant operations, waits with a timeout until completed /// </summary> /// <param name="tenant"></param> /// <param name="spo"></param> private void ExecuteAndWaitForCompletion(Tenant tenant, SpoOperation spo) { _client.Load(tenant); _client.Load(spo, i => i.IsComplete); _client.ExecuteQuery(); //Check if provisioning of the SiteCollection is complete. while (!spo.IsComplete) { //Wait for a bit and then try again Thread.Sleep(_waitTime); spo.RefreshLoad(); _client.ExecuteQuery(); } }