public SiteCollectionManager(ActionRequest actionRequest, ClientContext ctx) { _actionRequest = actionRequest; _siteCollectionRequest = actionRequest.SiteCollectionRequest; _ctx = ctx; _siteTemplate = GetSiteTemplate(); }
// This function will get triggered/executed when a new message is written // on an Azure Queue called queue. public static void ProcessQueueMessage([QueueTrigger(SiteManager.StorageQueueName)] SiteCollectionRequest siteRequest, TextWriter log) { log.WriteLine(string.Format("Received new site request with URL of {0}.", siteRequest.Url)); try { string webFullUrl = string.Empty; //create site collection using the Tenant object. Notice that you will need to have valid app ID and secret for this one var tenantAdminUri = new Uri(String.Format("https://{0}-admin.sharepoint.com", siteRequest.TenantName)); string realm = TokenHelper.GetRealmFromTargetUrl(tenantAdminUri); var token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, tenantAdminUri.Authority, realm).AccessToken; using (var ctx = TokenHelper.GetClientContextWithAccessToken(tenantAdminUri.ToString(), token)) { // Perform processing somewhere else webFullUrl = new SiteManager().ProcessSiteCreationRequest(ctx, siteRequest); // Log successful creation log.WriteLine(string.Format("Successfully created site collection at {0}.", webFullUrl)); } var newWebUri = new Uri(webFullUrl); token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, newWebUri.Authority, TokenHelper.GetRealmFromTargetUrl(newWebUri)).AccessToken; using (var ctx = TokenHelper.GetClientContextWithAccessToken(webFullUrl, token)) { new SiteManager().ApplyCustomTemplateToSite(ctx, siteRequest, Path.Combine(Environment.GetEnvironmentVariable("WEBROOT_PATH"), "Resources")); log.WriteLine(string.Format("Successfully applied template to site collection at {0}.", webFullUrl)); } } catch (Exception ex) { log.WriteLine(string.Format("Site collection creation to URL {0} failed with following details.", siteRequest.Url)); log.WriteLine(ex.ToString()); throw; } }
private void AddRequestToQueue(string ownerEmail) { //get the base tenant url var tenantName = Page.Request["SPHostUrl"].ToLower().Replace("-my", "").Substring(8); tenantName = tenantName.Substring(0, tenantName.IndexOf(".")); // Create provisioning message objects for the storage queue SiteCollectionRequest data = new SiteCollectionRequest() { TenantName = tenantName, Url = txtUrl.Text, Owner = ownerEmail, ManagedPath = "sites", TimeZoneId = int.Parse(timeZone.SelectedValue), StorageMaximumLevel = int.Parse(txtStorage.Text), Lcid = uint.Parse(language.SelectedValue), Title = txtTitle.Text }; if (templateSelectionType.SelectedValue == "Site") { data.ProvisioningType = SiteProvisioningType.TemplateSite; data.TemplateId = templateSiteLink.Text; } else { data.ProvisioningType = SiteProvisioningType.Identity; data.TemplateId = listTemplates.SelectedValue; } new SiteManager().AddConfigRequestToQueue(data, ConfigurationManager.AppSettings["StorageConnectionString"]); }
static void Main(string[] args) { // Update these accordingly for your environment string tenantName = ConfigurationManager.AppSettings["TenantName"]; string ownwerEmail = ConfigurationManager.AppSettings["SiteColTestOwnerEmail"]; //create site collection using the Tenant object. Notice that you will need to have valid app ID and secret for this one var tenantAdminUri = new Uri(String.Format("https://{0}-admin.sharepoint.com", tenantName)); string realm = TokenHelper.GetRealmFromTargetUrl(tenantAdminUri); var token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, tenantAdminUri.Authority, realm).AccessToken; using (var adminContext = TokenHelper.GetClientContextWithAccessToken(tenantAdminUri.ToString(), token)) { // Call the creation. SiteCollectionRequest data = new SiteCollectionRequest() { TenantName = tenantName, Url = DateTime.Now.Ticks.ToString(), Owner = ownwerEmail, ManagedPath = "sites", ProvisioningType = SiteProvisioningType.Identity, TemplateId = "CT1", TimeZoneId = 16, StorageMaximumLevel = 110, Title = "Test site collection" }; // Process request for new site new SiteManager().ProcessSiteCreationRequest(adminContext, data); } }
/// <summary> /// Perform call to on-prem /// </summary> /// <param name="request"></param> /// <param name="log"></param> private static void ProcessOnPremRequest(SiteCollectionRequest request, TextWriter log) { log.WriteLine(String.Format("Send request to create new site collection at {0}", DateTime.Now.ToLongTimeString())); string returnMessage = new ServiceBusMessageManager().SendSiteRequestMessage(request, ConfigurationManager.AppSettings[Consts.ServiceBusNamespaceKey], ConfigurationManager.AppSettings[Consts.ServiceBusSecretKey]); log.WriteLine(String.Format("Got followign message back '{0}' at {1}", returnMessage, DateTime.Now.ToLongTimeString())); }
// This function will get triggered/executed when a new message is written // on an Azure Queue called queue. public static void ProcessQueueMessage([QueueTrigger(Consts.StorageQueueName)] SiteCollectionRequest request, TextWriter log) { switch (request.TargetEnvironment.ToLowerInvariant()) { case Consts.DeploymentTypeCloud: ProcessCloudRequest(request, log); break; case Consts.DeploymentTypeOnPremises: ProcessOnPremRequest(request, log); break; default: break; } }
public ActionResult CreateSiteCollection(SiteCollectionTemplateCreationModel siteCollectionTemplateCreationModel) { User spUser = null; Site spSite = null; var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { if (clientContext != null) { spUser = clientContext.Web.CurrentUser; clientContext.Load(spUser, user => user.Email); clientContext.ExecuteQuery(); spSite = clientContext.Site; clientContext.Load(spSite, site => site.Url); clientContext.ExecuteQuery(); } } var siteCollectionRequest = new SiteCollectionRequest { Lcid = siteCollectionTemplateCreationModel.Lcid, ManagedPath = siteCollectionTemplateCreationModel.ManagedPath, ProvisioningType = siteCollectionTemplateCreationModel.ProvisioningType, StorageMaximumLevel = siteCollectionTemplateCreationModel.StorageMaximumLevel, TemplateId = siteCollectionTemplateCreationModel.TemplateId, TimeZoneId = siteCollectionTemplateCreationModel.TimeZoneId, }; var request = new ActionRequest { Name = siteCollectionTemplateCreationModel.Name, Description = siteCollectionTemplateCreationModel.Description, SiteTemplateName = siteCollectionTemplateCreationModel.SelectedSiteCreationTemplate, User = spUser.Email, Url = spSite.Url, SiteCollectionRequest = siteCollectionRequest, TenantName = new Uri(spSite.Url).Host.Split('.')[0] }; request.IsSiteCollection = true; _createRequestService.PutCreateRequestInQueue(request); _logService.SendLog(request, State.Queued); return RedirectToAction("Queue", "Log", new { SPHostUrl = Request.QueryString["SPHostUrl"] }); }
public ActionResult CreateSiteCollection(SiteCollectionTemplateCreationModel siteCollectionTemplateCreationModel) { User spUser = null; Site spSite = null; var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { if (clientContext != null) { spUser = clientContext.Web.CurrentUser; clientContext.Load(spUser, user => user.Email); clientContext.ExecuteQuery(); spSite = clientContext.Site; clientContext.Load(spSite, site => site.Url); clientContext.ExecuteQuery(); } } var siteCollectionRequest = new SiteCollectionRequest { Lcid = siteCollectionTemplateCreationModel.Lcid, ManagedPath = siteCollectionTemplateCreationModel.ManagedPath, ProvisioningType = siteCollectionTemplateCreationModel.ProvisioningType, StorageMaximumLevel = siteCollectionTemplateCreationModel.StorageMaximumLevel, TemplateId = siteCollectionTemplateCreationModel.TemplateId, TimeZoneId = siteCollectionTemplateCreationModel.TimeZoneId, }; var request = new ActionRequest { Name = siteCollectionTemplateCreationModel.Name, Description = siteCollectionTemplateCreationModel.Description, SiteTemplateName = siteCollectionTemplateCreationModel.SelectedSiteCreationTemplate, User = spUser.Email, Url = spSite.Url, SiteCollectionRequest = siteCollectionRequest, TenantName = new Uri(spSite.Url).Host.Split('.')[0] }; request.IsSiteCollection = true; _createRequestService.PutCreateRequestInQueue(request); _logService.SendLog(request, State.Queued); return(RedirectToAction("Queue", "Log", new { SPHostUrl = Request.QueryString["SPHostUrl"] })); }
/// <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> /// 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())); }
static void Main(string[] args) { string returnMessage = ""; try { string message = string.Format("Test message sent at {0}", DateTime.Now.ToLongTimeString()); System.Console.WriteLine(String.Format("Sending this message: '{0}'", message)); // Send message using centralized business component for testing purposes returnMessage = new ServiceBusMessageManager().SendMessage(message, ConfigurationManager.AppSettings[Consts.ServiceBusNamespaceKey], ConfigurationManager.AppSettings[Consts.ServiceBusSecretKey]); System.Console.WriteLine(String.Format("Got back this message: '{0}' at {1}", returnMessage, DateTime.Now.ToLongTimeString())); // Alternative to test site collection creation using console SiteCollectionRequest request = new SiteCollectionRequest() { Template = "STS#0", Title = "New site", OwnerIdentifier = "", TargetEnvironment = Consts.DeploymentTypeOnPremises }; System.Console.WriteLine(String.Format("Send request to create new site collection at {0}", DateTime.Now.ToLongTimeString())); returnMessage = new ServiceBusMessageManager().SendSiteRequestMessage(request, ConfigurationManager.AppSettings[Consts.ServiceBusNamespaceKey], ConfigurationManager.AppSettings[Consts.ServiceBusSecretKey]); System.Console.ForegroundColor = ConsoleColor.Green; System.Console.WriteLine(String.Format("Got followign message back: '{0}' at {1}", returnMessage, DateTime.Now.ToLongTimeString())); } catch (Exception ex) { System.Console.ForegroundColor = ConsoleColor.Red; System.Console.WriteLine(String.Format("Exception with the execution. Error description: '{0}'", ex.ToString())); } // Just to keep it hanging in the service... could be hosted for example as windows service for better handling System.Console.ForegroundColor = ConsoleColor.Gray; System.Console.WriteLine("Press ENTER to close"); System.Console.ReadLine(); }
static void Main(string[] args) { Console.WriteLine("*************"); Console.WriteLine("** PnP provisioning Engine"); Console.WriteLine("************"); string templateSite = GetUserInput("Template site URL:"); string targetSite = GetUserInput("Target site URL:"); // Log the start time Console.WriteLine("Start: {0:hh.mm.ss}", DateTime.Now); //Get the realm for the target URL Uri siteUri = new Uri(targetSite); string realm = TokenHelper.GetRealmFromTargetUrl(siteUri); //Get the access token for the URL. Requires this app to be registered with the tenant string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken; //Get client context with access token using (var ctx = TokenHelper.GetClientContextWithAccessToken(siteUri.ToString(), accessToken)) { SiteCollectionRequest data = new SiteCollectionRequest() { TenantName = "contoso", Url = DateTime.Now.Ticks.ToString(), Owner = "*****@*****.**", ManagedPath = "sites", ProvisioningType = SiteProvisioningType.TemplateSite, TemplateId = templateSite, TimeZoneId = 16, StorageMaximumLevel = 110, Title = "Test site collection" }; // Execute the transformation new SiteManager().ApplyCustomTemplateToSite(ctx, data, @".\Resources"); } // Log the end time Console.WriteLine("End: {0:hh.mm.ss}", DateTime.Now); }
public async Task <string> CreateSiteCollectionAsync(SiteCollectionRequest request) { var accessToken = await tokenManager.GetAccessTokenSPOAsync(spoSetting.SiteUrlAdmin); var accessTokenSecure = accessToken.ToSecureString(); using var authManager = new AuthenticationManager(accessTokenSecure); using var context = authManager.GetContext(spoSetting.SiteUrlAdmin); var site = new TeamNoGroupSiteCollectionCreationInformation { Owner = spoSetting.UserName, Title = request.Title, Url = $"{spoSetting.SiteUrl.RemoveLastSlash()}/sites/{request.Alias}", Lcid = 1033, ShareByEmailEnabled = true, }; await SiteCollection.CreateAsync(context, site, noWait : true); return(site.Url); }
static void Main(string[] args) { // Update parameters accordingly based on our environment from app.config // Update these accordingly for your environment string tenantName = ConfigurationManager.AppSettings["TenantName"]; string ownwerEmail = ConfigurationManager.AppSettings["SiteColTestOwnerEmail"]; // Create provisioning message objects for the storage queue SiteCollectionRequest data = new SiteCollectionRequest() { TenantName = tenantName, Url = DateTime.Now.Ticks.ToString(), Owner = ownwerEmail, ManagedPath = "sites", ProvisioningType = SiteProvisioningType.TemplateSite, TemplateId = "https://contoso.sharepoint.com/sites/templatesite", TimeZoneId = 16, StorageMaximumLevel = 110, Title = "Test site collection" }; new SiteManager().AddConfigRequestToQueue(data, ConfigurationManager.AppSettings["StorageConnectionString"]); }
// Site creation request to queue private void ProcessSiteRequest(string adminEmail) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString")); // Get queue... create if does not exist. CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient(); CloudQueue queue = queueClient.GetQueueReference(Provisioning.Hybrid.Simple.Common.Consts.StorageQueueName); queue.CreateIfNotExists(); // Pass in data for modification var newSiteRequest = new SiteCollectionRequest() { Title = txtTitle.Text, OwnerIdentifier = adminEmail, TargetEnvironment = drlEnvironment.SelectedValue, Template = drlTemplate.SelectedValue }; // Add entry to queue queue.AddMessage(new CloudQueueMessage(JsonConvert.SerializeObject(newSiteRequest))); }