protected override void RunJobInternal(ProvisioningJob job)
        {
            SiteCollectionProvisioningJob scj = job as SiteCollectionProvisioningJob;

            if (scj == null)
            {
                throw new ArgumentException("Invalid job type for SiteCollectionProvisioningJobHandler.");
            }

            CreateSiteCollection(scj);
        }
        private Guid EnqueueSiteCollectionProvisioningJob(SiteCollectionProvisioningJob job)
        {
            //Enrich incoming job
            job.Title = String.Format("Provisioning of Site Collection \"{1}\" with Template \"{0}\" by {2}",
                                      job.ProvisioningTemplateUrl,
                                      job.RelativeUrl,
                                      job.Owner);

            var jobId = ProvisioningRepositoryFactory.Current.EnqueueProvisioningJob(job);

            return(jobId);
        }
Esempio n. 3
0
        private void CreateSiteCollectionsBatch(SiteCollectionsBatchJob job)
        {
            var batches = JsonConvert.DeserializeObject <batches>(job.BatchSites);

            // For each Site Collection that we have to create
            foreach (var batch in batches.siteCollection)
            {
                // Prepare the Job to provision the Site Collection
                SiteCollectionProvisioningJob siteJob = new SiteCollectionProvisioningJob();

                // Prepare all the other information about the Provisioning Job
                siteJob.SiteTitle   = batch.title;
                siteJob.Description = batch.description;
                siteJob.Language    = Int32.Parse(batch.language);
                siteJob.TimeZone    = batch.timeZone;
                siteJob.RelativeUrl = String.Format("/{0}/{1}", batch.managedPath, batch.relativeUrl);
                siteJob.SitePolicy  = batch.sitePolicy == baseSiteSettingsSitePolicy.LBI ? "LBI" :
                                      batch.sitePolicy == baseSiteSettingsSitePolicy.MBI ? "MBI" :
                                      "HBI";
                siteJob.Owner = job.Owner;
                siteJob.PrimarySiteCollectionAdmin   = batch.primarySiteCollectionAdmin;
                siteJob.SecondarySiteCollectionAdmin = batch.secondarySiteCollectionAdmin;
                siteJob.ProvisioningTemplateUrl      = batch.templateUrl;
                siteJob.TemplatesProviderTypeName    = batch.templatesProviderName;
                siteJob.StorageMaximumLevel          = batch.storageMaximulLevel;
                siteJob.StorageWarningLevel          = batch.storageWarningLevel;
                siteJob.UserCodeMaximumLevel         = 0;
                siteJob.UserCodeWarningLevel         = 0;
                siteJob.ExternalSharingEnabled       = batch.externalSharingEnabled;
                siteJob.ResponsiveDesignEnabled      = batch.responsiveDesignEnabled;
                siteJob.PartnerPackExtensionsEnabled = batch.partnerPackExtensionsEnabled;
                siteJob.ApplyTenantBranding          = batch.applyTenantBranding;
                siteJob.Title = String.Format("Provisioning of Site Collection \"{1}\" with Template \"{0}\" by {2}",
                                              siteJob.ProvisioningTemplateUrl,
                                              siteJob.RelativeUrl,
                                              siteJob.Owner);

                if (batch.templateParameters != null)
                {
                    siteJob.TemplateParameters = batch.templateParameters.ToDictionary(i => i.Key, i => i.Value);
                }

                var jobId = ProvisioningRepositoryFactory.Current.EnqueueProvisioningJob(siteJob);

                Console.WriteLine($"Scheduled Site Collection creation job with ID: {jobId}");
            }
        }
        private void CreateSiteCollectionsBatch(SiteCollectionsBatchJob job)
        {
            var batches = JsonConvert.DeserializeObject<batches>(job.BatchSites);

            // For each Site Collection that we have to create
            foreach (var batch in batches.siteCollection)
            {
                // Prepare the Job to provision the Site Collection
                SiteCollectionProvisioningJob siteJob = new SiteCollectionProvisioningJob();

                // Prepare all the other information about the Provisioning Job
                siteJob.SiteTitle = batch.title;
                siteJob.Description = batch.description;
                siteJob.Language = Int32.Parse(batch.language);
                siteJob.TimeZone = batch.timeZone;
                siteJob.RelativeUrl = String.Format("/{0}/{1}", batch.managedPath, batch.relativeUrl);
                siteJob.SitePolicy = batch.sitePolicy == baseSiteSettingsSitePolicy.LBI ? "LBI" :
                    batch.sitePolicy == baseSiteSettingsSitePolicy.MBI ? "MBI" :
                    "HBI";
                siteJob.Owner = job.Owner;
                siteJob.PrimarySiteCollectionAdmin = batch.primarySiteCollectionAdmin;
                siteJob.SecondarySiteCollectionAdmin = batch.secondarySiteCollectionAdmin;
                siteJob.ProvisioningTemplateUrl = batch.templateUrl;
                siteJob.TemplatesProviderTypeName = batch.templatesProviderName;
                siteJob.StorageMaximumLevel = batch.storageMaximulLevel;
                siteJob.StorageWarningLevel = batch.storageWarningLevel;
                siteJob.UserCodeMaximumLevel = 0;
                siteJob.UserCodeWarningLevel = 0;
                siteJob.ExternalSharingEnabled = batch.externalSharingEnabled;
                siteJob.ResponsiveDesignEnabled = batch.responsiveDesignEnabled;
                siteJob.PartnerPackExtensionsEnabled = batch.partnerPackExtensionsEnabled;
                siteJob.ApplyTenantBranding = batch.applyTenantBranding;
                siteJob.Title = String.Format("Provisioning of Site Collection \"{1}\" with Template \"{0}\" by {2}",
                    siteJob.ProvisioningTemplateUrl,
                    siteJob.RelativeUrl,
                    siteJob.Owner);

                if (batch.templateParameters != null)
                {
                    siteJob.TemplateParameters = batch.templateParameters.ToDictionary(i => i.Key, i => i.Value);
                }

                var jobId = ProvisioningRepositoryFactory.Current.EnqueueProvisioningJob(siteJob);

                Console.WriteLine($"Scheduled Site Collection creation job with ID: {jobId}");
            }
        }
 public Guid CreateSiteCollectionSingle([FromBody] SiteCollectionProvisioningJob value)
 {
     return(this.EnqueueSiteCollectionProvisioningJob(value));
 }
        private void CreateSiteCollection(SiteCollectionProvisioningJob job)
        {
            Console.WriteLine("Creating Site Collection \"{0}\".", job.RelativeUrl);

            // Define the full Site Collection URL
            String siteUrl = String.Format("{0}{1}",
                                           PnPPartnerPackSettings.InfrastructureSiteUrl.Substring(0, PnPPartnerPackSettings.InfrastructureSiteUrl.IndexOf("sharepoint.com/") + 14),
                                           job.RelativeUrl);

            // Load the template from the source Templates Provider
            if (!String.IsNullOrEmpty(job.TemplatesProviderTypeName))
            {
                ProvisioningTemplate template = null;

                var templatesProvider = PnPPartnerPackSettings.TemplatesProviders[job.TemplatesProviderTypeName];
                if (templatesProvider != null)
                {
                    template = templatesProvider.GetProvisioningTemplate(job.ProvisioningTemplateUrl);
                }

                if (template != null)
                {
                    using (var adminContext = PnPPartnerPackContextProvider.GetAppOnlyTenantLevelClientContext())
                    {
                        adminContext.RequestTimeout = Timeout.Infinite;

                        // Configure the Site Collection properties
                        SiteEntity newSite = new SiteEntity();
                        newSite.Description         = job.Description;
                        newSite.Lcid                = (uint)job.Language;
                        newSite.Title               = job.SiteTitle;
                        newSite.Url                 = siteUrl;
                        newSite.SiteOwnerLogin      = job.PrimarySiteCollectionAdmin;
                        newSite.StorageMaximumLevel = job.StorageMaximumLevel;
                        newSite.StorageWarningLevel = job.StorageWarningLevel;

                        // Use the BaseSiteTemplate of the template, if any, otherwise
                        // fallback to the pre-configured site template (i.e. STS#0)
                        newSite.Template = !String.IsNullOrEmpty(template.BaseSiteTemplate) ?
                                           template.BaseSiteTemplate :
                                           PnPPartnerPackSettings.DefaultSiteTemplate;

                        newSite.TimeZoneId           = job.TimeZone;
                        newSite.UserCodeMaximumLevel = job.UserCodeMaximumLevel;
                        newSite.UserCodeWarningLevel = job.UserCodeWarningLevel;

                        // Create the Site Collection and wait for its creation (we're asynchronous)
                        var tenant = new Tenant(adminContext);
                        tenant.CreateSiteCollection(newSite, true, true); // TODO: Do we want to empty Recycle Bin?

                        Site site = tenant.GetSiteByUrl(siteUrl);
                        Web  web  = site.RootWeb;

                        adminContext.Load(site, s => s.Url);
                        adminContext.Load(web, w => w.Url);
                        adminContext.ExecuteQueryRetry();

                        // Enable Secondary Site Collection Administrator
                        if (!String.IsNullOrEmpty(job.SecondarySiteCollectionAdmin))
                        {
                            Microsoft.SharePoint.Client.User secondaryOwner = web.EnsureUser(job.SecondarySiteCollectionAdmin);
                            secondaryOwner.IsSiteAdmin = true;
                            secondaryOwner.Update();

                            web.SiteUsers.AddUser(secondaryOwner);
                            adminContext.ExecuteQueryRetry();
                        }

                        Console.WriteLine("Site \"{0}\" created.", site.Url);

                        // Check if external sharing has to be enabled
                        if (job.ExternalSharingEnabled)
                        {
                            EnableExternalSharing(tenant, site);

                            // Enable External Sharing
                            Console.WriteLine("Enabled External Sharing for site \"{0}\".",
                                              site.Url);
                        }
                    }

                    // Move to the context of the created Site Collection
                    using (ClientContext clientContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext(siteUrl))
                    {
                        clientContext.RequestTimeout = Timeout.Infinite;

                        Site site = clientContext.Site;
                        Web  web  = site.RootWeb;

                        clientContext.Load(site, s => s.Url);
                        clientContext.Load(web, w => w.Url);
                        clientContext.ExecuteQueryRetry();

                        // Check if we need to enable PnP Partner Pack overrides
                        if (job.PartnerPackExtensionsEnabled)
                        {
                            // Enable Responsive Design
                            PnPPartnerPackUtilities.EnablePartnerPackOnSite(site.Url);

                            Console.WriteLine("Enabled PnP Partner Pack Overrides on site \"{0}\".",
                                              site.Url);
                        }

                        // Check if the site has to be responsive
                        if (job.ResponsiveDesignEnabled)
                        {
                            // Enable Responsive Design
                            PnPPartnerPackUtilities.EnableResponsiveDesignOnSite(site.Url);

                            Console.WriteLine("Enabled Responsive Design Template to site \"{0}\".",
                                              site.Url);
                        }

                        // Apply the Provisioning Template
                        Console.WriteLine("Applying Provisioning Template \"{0}\" to site.",
                                          job.ProvisioningTemplateUrl);

                        // We do intentionally remove taxonomies, which are not supported
                        // in the AppOnly Authorization model
                        // For further details, see the PnP Partner Pack documentation
                        ProvisioningTemplateApplyingInformation ptai =
                            new ProvisioningTemplateApplyingInformation();

                        // Write provisioning steps on console log
                        ptai.MessagesDelegate += delegate(string message, ProvisioningMessageType messageType)
                        {
                            Console.WriteLine("{0} - {1}", messageType, messageType);
                        };
                        ptai.ProgressDelegate += delegate(string message, int step, int total)
                        {
                            Console.WriteLine("{0:00}/{1:00} - {2}", step, total, message);
                        };

                        // Exclude handlers not supported in App-Only
                        ptai.HandlersToProcess ^=
                            OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.TermGroups;
                        ptai.HandlersToProcess ^=
                            OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.SearchSettings;

                        // Configure template parameters
                        if (job.TemplateParameters != null)
                        {
                            foreach (var key in job.TemplateParameters.Keys)
                            {
                                if (job.TemplateParameters.ContainsKey(key))
                                {
                                    template.Parameters[key] = job.TemplateParameters[key];
                                }
                            }
                        }

                        // Fixup Title and Description
                        if (template.WebSettings != null)
                        {
                            template.WebSettings.Title       = job.SiteTitle;
                            template.WebSettings.Description = job.Description;
                        }

                        // Apply the template to the target site
                        web.ApplyProvisioningTemplate(template, ptai);

                        // Save the template information in the target site
                        var info = new SiteTemplateInfo()
                        {
                            TemplateProviderType = job.TemplatesProviderTypeName,
                            TemplateUri          = job.ProvisioningTemplateUrl,
                            TemplateParameters   = template.Parameters,
                            AppliedOn            = DateTime.Now,
                        };
                        var jsonInfo = JsonConvert.SerializeObject(info);
                        web.SetPropertyBagValue(PnPPartnerPackConstants.PropertyBag_TemplateInfo, jsonInfo);

                        // Set site policy template
                        if (!String.IsNullOrEmpty(job.SitePolicy))
                        {
                            web.ApplySitePolicy(job.SitePolicy);
                        }

                        // Apply Tenant Branding, if requested
                        if (job.ApplyTenantBranding)
                        {
                            var brandingSettings = PnPPartnerPackUtilities.GetTenantBrandingSettings();

                            using (var repositoryContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext(
                                       PnPPartnerPackSettings.InfrastructureSiteUrl))
                            {
                                var brandingTemplate = BrandingJobHandler.PrepareBrandingTemplate(repositoryContext, brandingSettings);

                                // Fixup Title and Description
                                if (brandingTemplate != null)
                                {
                                    if (brandingTemplate.WebSettings != null)
                                    {
                                        brandingTemplate.WebSettings.Title       = job.SiteTitle;
                                        brandingTemplate.WebSettings.Description = job.Description;
                                    }

                                    // TO-DO: Need to handle exception here as there are multiple webs inside this where
                                    BrandingJobHandler.ApplyBrandingOnWeb(web, brandingSettings, brandingTemplate);
                                }
                            }
                        }


                        Console.WriteLine("Applied Provisioning Template \"{0}\" to site.",
                                          job.ProvisioningTemplateUrl);
                    }
                }
            }
        }
Esempio n. 7
0
        private void CreateSiteCollection(SiteCollectionProvisioningJob job)
        {
            Console.WriteLine("Creating Site Collection \"{0}\".", job.RelativeUrl);

            // Define the full Site Collection URL
            String siteUrl = String.Format("{0}{1}",
                                           PnPPartnerPackSettings.InfrastructureSiteUrl.Substring(0, PnPPartnerPackSettings.InfrastructureSiteUrl.IndexOf("sharepoint.com/") + 14),
                                           job.RelativeUrl);

            using (var adminContext = PnPPartnerPackContextProvider.GetAppOnlyTenantLevelClientContext())
            {
                adminContext.RequestTimeout = Timeout.Infinite;

                // Configure the Site Collection properties
                SiteEntity newSite = new SiteEntity();
                newSite.Description          = job.Description;
                newSite.Lcid                 = (uint)job.Language;
                newSite.Title                = job.SiteTitle;
                newSite.Url                  = siteUrl;
                newSite.SiteOwnerLogin       = job.PrimarySiteCollectionAdmin;
                newSite.StorageMaximumLevel  = job.StorageMaximumLevel;
                newSite.StorageWarningLevel  = job.StorageWarningLevel;
                newSite.Template             = PnPPartnerPackSettings.DefaultSiteTemplate;
                newSite.TimeZoneId           = job.TimeZone;
                newSite.UserCodeMaximumLevel = job.UserCodeMaximumLevel;
                newSite.UserCodeWarningLevel = job.UserCodeWarningLevel;

                // Create the Site Collection and wait for its creation (we're asynchronous)
                var tenant = new Tenant(adminContext);
                tenant.CreateSiteCollection(newSite, true, true); // TODO: Do we want to empty Recycle Bin?

                Site site = tenant.GetSiteByUrl(siteUrl);
                Web  web  = site.RootWeb;

                adminContext.Load(site, s => s.Url);
                adminContext.Load(web, w => w.Url);
                adminContext.ExecuteQueryRetry();

                // Enable Secondary Site Collection Administrator
                if (!String.IsNullOrEmpty(job.SecondarySiteCollectionAdmin))
                {
                    Microsoft.SharePoint.Client.User secondaryOwner = web.EnsureUser(job.SecondarySiteCollectionAdmin);
                    secondaryOwner.IsSiteAdmin = true;
                    secondaryOwner.Update();

                    web.SiteUsers.AddUser(secondaryOwner);
                    adminContext.ExecuteQueryRetry();
                }

                Console.WriteLine("Site \"{0}\" created.", site.Url);

                // Check if external sharing has to be enabled
                if (job.ExternalSharingEnabled)
                {
                    EnableExternalSharing(tenant, site);

                    // Enable External Sharing
                    Console.WriteLine("Enabled External Sharing for site \"{0}\".",
                                      site.Url);
                }
            }

            // Move to the context of the created Site Collection
            using (ClientContext clientContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext(siteUrl))
            {
                Site site = clientContext.Site;
                Web  web  = site.RootWeb;

                clientContext.Load(site, s => s.Url);
                clientContext.Load(web, w => w.Url);
                clientContext.ExecuteQueryRetry();

                // Check if we need to enable PnP Partner Pack overrides
                if (job.PartnerPackExtensionsEnabled)
                {
                    // Enable Responsive Design
                    PnPPartnerPackUtilities.EnablePartnerPackOnSite(site.Url);

                    Console.WriteLine("Enabled PnP Partner Pack Overrides on site \"{0}\".",
                                      site.Url);
                }

                // Check if the site has to be responsive
                if (job.ResponsiveDesignEnabled)
                {
                    // Enable Responsive Design
                    PnPPartnerPackUtilities.EnableResponsiveDesignOnSite(site.Url);

                    Console.WriteLine("Enabled Responsive Design Template to site \"{0}\".",
                                      site.Url);
                }

                // Apply the Provisioning Template
                Console.WriteLine("Applying Provisioning Template \"{0}\" to site.",
                                  job.ProvisioningTemplateUrl);

                // Determine the reference URLs and file names
                String templatesSiteUrl = PnPPartnerPackUtilities.GetSiteCollectionRootUrl(job.ProvisioningTemplateUrl);
                String templateFileName = job.ProvisioningTemplateUrl.Substring(job.ProvisioningTemplateUrl.LastIndexOf("/") + 1);

                using (ClientContext repositoryContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext(templatesSiteUrl))
                {
                    // Configure the XML file system provider
                    XMLTemplateProvider provider =
                        new XMLSharePointTemplateProvider(
                            repositoryContext,
                            templatesSiteUrl,
                            PnPPartnerPackConstants.PnPProvisioningTemplates);

                    // Load the template from the XML stored copy
                    ProvisioningTemplate template = provider.GetTemplate(templateFileName);
                    template.Connector = provider.Connector;

                    // We do intentionally remove taxonomies, which are not supported
                    // in the AppOnly Authorization model
                    // For further details, see the PnP Partner Pack documentation
                    ProvisioningTemplateApplyingInformation ptai =
                        new ProvisioningTemplateApplyingInformation();

                    // Write provisioning steps on console log
                    ptai.MessagesDelegate += delegate(string message, ProvisioningMessageType messageType) {
                        Console.WriteLine("{0} - {1}", messageType, messageType);
                    };
                    ptai.ProgressDelegate += delegate(string message, int step, int total) {
                        Console.WriteLine("{0:00}/{1:00} - {2}", step, total, message);
                    };

                    ptai.HandlersToProcess ^=
                        OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.TermGroups;

                    // Configure template parameters
                    if (job.TemplateParameters != null)
                    {
                        foreach (var key in job.TemplateParameters.Keys)
                        {
                            if (job.TemplateParameters.ContainsKey(key))
                            {
                                template.Parameters[key] = job.TemplateParameters[key];
                            }
                        }
                    }

                    web.ApplyProvisioningTemplate(template, ptai);
                }

                Console.WriteLine("Applyed Provisioning Template \"{0}\" to site.",
                                  job.ProvisioningTemplateUrl);
            }
        }
        private void CreateSiteCollection(SiteCollectionProvisioningJob job)
        {
            Console.WriteLine("Creating Site Collection \"{0}\".", job.RelativeUrl);

            // Define the full Site Collection URL
            String siteUrl = String.Format("{0}{1}",
                PnPPartnerPackSettings.InfrastructureSiteUrl.Substring(0, PnPPartnerPackSettings.InfrastructureSiteUrl.IndexOf("sharepoint.com/") + 14),
                job.RelativeUrl);

            using (var adminContext = PnPPartnerPackContextProvider.GetAppOnlyTenantLevelClientContext())
            {
                // Configure the Site Collection properties
                SiteEntity newSite = new SiteEntity();
                newSite.Description = job.Description;
                newSite.Lcid = (uint)job.Language;
                newSite.Title = job.SiteTitle;
                newSite.Url = siteUrl;
                newSite.SiteOwnerLogin = job.PrimarySiteCollectionAdmin;
                newSite.StorageMaximumLevel = job.StorageMaximumLevel;
                newSite.StorageWarningLevel = job.StorageWarningLevel;
                newSite.Template = PnPPartnerPackSettings.DefaultSiteTemplate;
                newSite.TimeZoneId = job.TimeZone;
                newSite.UserCodeMaximumLevel = job.UserCodeMaximumLevel;
                newSite.UserCodeWarningLevel = job.UserCodeWarningLevel;

                // Create the Site Collection and wait for its creation (we're asynchronous)
                var tenant = new Tenant(adminContext);
                tenant.CreateSiteCollection(newSite, true, true); // TODO: Do we want to empty Recycle Bin?

                Site site = tenant.GetSiteByUrl(siteUrl);
                Web web = site.RootWeb;

                adminContext.Load(site, s => s.Url);
                adminContext.Load(web, w => w.Url);
                adminContext.ExecuteQueryRetry();

                // Enable Secondary Site Collection Administrator
                if (!String.IsNullOrEmpty(job.SecondarySiteCollectionAdmin))
                {
                    Microsoft.SharePoint.Client.User secondaryOwner = web.EnsureUser(job.SecondarySiteCollectionAdmin);
                    secondaryOwner.IsSiteAdmin = true;
                    secondaryOwner.Update();

                    web.SiteUsers.AddUser(secondaryOwner);
                    adminContext.ExecuteQueryRetry();
                }

                Console.WriteLine("Site \"{0}\" created.", site.Url);

                // Check if external sharing has to be enabled
                if (job.ExternalSharingEnabled)
                {
                    EnableExternalSharing(tenant, site);

                    // Enable External Sharing
                    Console.WriteLine("Enabled External Sharing for site \"{0}\".",
                        site.Url);
                }
            }

            // Move to the context of the created Site Collection
            using (ClientContext clientContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext(siteUrl))
            {
                Site site = clientContext.Site;
                Web web = site.RootWeb;

                clientContext.Load(site, s => s.Url);
                clientContext.Load(web, w => w.Url);
                clientContext.ExecuteQueryRetry();

                // Check if we need to enable PnP Partner Pack overrides
                if (job.PartnerPackExtensionsEnabled)
                {
                    // Enable Responsive Design
                    PnPPartnerPackUtilities.EnablePartnerPackOnSite(site.Url);

                    Console.WriteLine("Enabled PnP Partner Pack Overrides on site \"{0}\".",
                        site.Url);
                }

                // Check if the site has to be responsive
                if (job.ResponsiveDesignEnabled)
                {
                    // Enable Responsive Design
                    PnPPartnerPackUtilities.EnableResponsiveDesignOnSite(site.Url);

                    Console.WriteLine("Enabled Responsive Design Template to site \"{0}\".",
                        site.Url);
                }

                // Apply the Provisioning Template
                Console.WriteLine("Applying Provisioning Template \"{0}\" to site.",
                    job.ProvisioningTemplateUrl);

                // Determine the reference URLs and file names
                String templatesSiteUrl = PnPPartnerPackUtilities.GetSiteCollectionRootUrl(job.ProvisioningTemplateUrl);
                String templateFileName = job.ProvisioningTemplateUrl.Substring(job.ProvisioningTemplateUrl.LastIndexOf("/") + 1);

                using (ClientContext repositoryContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext(templatesSiteUrl))
                {
                    // Configure the XML file system provider
                    XMLTemplateProvider provider =
                        new XMLSharePointTemplateProvider(
                            repositoryContext,
                            templatesSiteUrl,
                            PnPPartnerPackConstants.PnPProvisioningTemplates);

                    // Load the template from the XML stored copy
                    ProvisioningTemplate template = provider.GetTemplate(templateFileName);
                    template.Connector = provider.Connector;

                    // We do intentionally remove taxonomies, which are not supported
                    // in the AppOnly Authorization model
                    // For further details, see the PnP Partner Pack documentation
                    ProvisioningTemplateApplyingInformation ptai =
                        new ProvisioningTemplateApplyingInformation();

                    // Write provisioning steps on console log
                    ptai.MessagesDelegate += delegate (string message, ProvisioningMessageType messageType) {
                        Console.WriteLine("{0} - {1}", messageType, messageType);
                    };
                    ptai.ProgressDelegate += delegate (string message, int step, int total) {
                        Console.WriteLine("{0:00}/{1:00} - {2}", step, total, message);
                    };

                    ptai.HandlersToProcess ^=
                        OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.TermGroups;

                    // Configure template parameters
                    if (job.TemplateParameters != null)
                    {
                        foreach (var key in job.TemplateParameters.Keys)
                        {
                            if (job.TemplateParameters.ContainsKey(key))
                            {
                                template.Parameters[key] = job.TemplateParameters[key];
                            }
                        }
                    }

                    web.ApplyProvisioningTemplate(template, ptai);
                }

                Console.WriteLine("Applyed Provisioning Template \"{0}\" to site.",
                    job.ProvisioningTemplateUrl);
            }
        }
        public ActionResult CreateSiteCollection(CreateSiteCollectionViewModel model)
        {
            switch (model.Step)
            {
            case CreateSiteStep.SiteInformation:
                ModelState.Clear();
                if (String.IsNullOrEmpty(model.Title))
                {
                    // Set initial value for PnP Partner Pack Extensions Enabled
                    model.PartnerPackExtensionsEnabled = true;
                    model.ResponsiveDesignEnabled      = true;
                }
                break;

            case CreateSiteStep.TemplateParameters:
                if (!ModelState.IsValid)
                {
                    model.Step = CreateSiteStep.SiteInformation;
                }
                else
                {
                    if (!String.IsNullOrEmpty(model.ProvisioningTemplateUrl) &&
                        model.ProvisioningTemplateUrl.IndexOf(PnPPartnerPackConstants.PnPProvisioningTemplates) > 0)
                    {
                        String templateSiteUrl  = model.ProvisioningTemplateUrl.Substring(0, model.ProvisioningTemplateUrl.IndexOf(PnPPartnerPackConstants.PnPProvisioningTemplates));
                        String templateFileName = model.ProvisioningTemplateUrl.Substring(model.ProvisioningTemplateUrl.IndexOf(PnPPartnerPackConstants.PnPProvisioningTemplates) + PnPPartnerPackConstants.PnPProvisioningTemplates.Length + 1);
                        String templateFolder   = String.Empty;

                        if (templateFileName.IndexOf("/") > 0)
                        {
                            templateFolder   = templateFileName.Substring(0, templateFileName.LastIndexOf("/") - 1);
                            templateFileName = templateFileName.Substring(templateFolder.Length + 1);
                        }
                        model.TemplateParameters = PnPPartnerPackUtilities.GetProvisioningTemplateParameters(
                            templateSiteUrl,
                            templateFolder,
                            templateFileName);
                    }
                }
                break;

            case CreateSiteStep.SiteCreated:
                AntiForgery.Validate();
                if (ModelState.IsValid)
                {
                    // Prepare the Job to provision the Site Collection
                    SiteCollectionProvisioningJob job = new SiteCollectionProvisioningJob();

                    // Prepare all the other information about the Provisioning Job
                    job.SiteTitle   = model.Title;
                    job.Description = model.Description;
                    job.Language    = model.Language;
                    job.TimeZone    = model.TimeZone;
                    job.RelativeUrl = String.Format("/{0}/{1}", model.ManagedPath, model.RelativeUrl);
                    job.SitePolicy  = model.SitePolicy;
                    job.Owner       = ClaimsPrincipal.Current.Identity.Name;
                    job.PrimarySiteCollectionAdmin = model.PrimarySiteCollectionAdmin != null &&
                                                     model.PrimarySiteCollectionAdmin.Length > 0 ? model.PrimarySiteCollectionAdmin[0].Email : null;
                    job.SecondarySiteCollectionAdmin = model.SecondarySiteCollectionAdmin != null &&
                                                       model.SecondarySiteCollectionAdmin.Length > 0 ? model.SecondarySiteCollectionAdmin[0].Email : null;
                    job.ProvisioningTemplateUrl      = model.ProvisioningTemplateUrl;
                    job.StorageMaximumLevel          = model.StorageMaximumLevel;
                    job.StorageWarningLevel          = model.StorageWarningLevel;
                    job.UserCodeMaximumLevel         = model.UserCodeMaximumLevel;
                    job.UserCodeWarningLevel         = model.UserCodeWarningLevel;
                    job.ExternalSharingEnabled       = model.ExternalSharingEnabled;
                    job.ResponsiveDesignEnabled      = model.ResponsiveDesignEnabled;
                    job.PartnerPackExtensionsEnabled = model.PartnerPackExtensionsEnabled;
                    job.Title = String.Format("Provisioning of Site Collection \"{1}\" with Template \"{0}\" by {2}",
                                              job.ProvisioningTemplateUrl,
                                              job.RelativeUrl,
                                              job.Owner);

                    job.TemplateParameters = model.TemplateParameters;

                    model.JobId = ProvisioningRepositoryFactory.Current.EnqueueProvisioningJob(job);
                }
                break;

            default:
                break;
            }

            return(PartialView(model.Step.ToString(), model));
        }
Esempio n. 10
0
        public ActionResult CreateSiteCollection(CreateSiteCollectionViewModel model)
        {
            if (model.Step == CreateSiteStep.SiteInformation)
            {
                ModelState.Clear();
                if (String.IsNullOrEmpty(model.Title))
                {
                    // Set initial value for PnP Partner Pack Extensions Enabled
                    model.PartnerPackExtensionsEnabled = true;
                    model.ResponsiveDesignEnabled      = true;
                }
            }
            if (model.Step == CreateSiteStep.TemplateParameters)
            {
                if (!ModelState.IsValid)
                {
                    model.Step = CreateSiteStep.SiteInformation;
                }
                else
                {
                    if (!String.IsNullOrEmpty(model.ProvisioningTemplateUrl) &&
                        !String.IsNullOrEmpty(model.TemplatesProviderTypeName))
                    {
                        var templatesProvider = PnPPartnerPackSettings.TemplatesProviders[model.TemplatesProviderTypeName];
                        if (templatesProvider != null)
                        {
                            var template = templatesProvider.GetProvisioningTemplate(model.ProvisioningTemplateUrl);
                            model.TemplateParameters = template.Parameters;
                        }
                    }

                    if (model.TemplateParameters == null || model.TemplateParameters.Count == 0)
                    {
                        model.Step = CreateSiteStep.SiteCreated;
                    }
                }
            }
            if (model.Step == CreateSiteStep.SiteCreated)
            {
                AntiForgery.Validate();
                if (ModelState.IsValid)
                {
                    // Prepare the Job to provision the Site Collection
                    SiteCollectionProvisioningJob job = new SiteCollectionProvisioningJob();

                    // Prepare all the other information about the Provisioning Job
                    job.SiteTitle           = model.Title;
                    job.Description         = model.Description;
                    job.Language            = model.Language;
                    job.TimeZone            = model.TimeZone;
                    job.RelativeUrl         = String.Format("/{0}/{1}", model.ManagedPath, model.RelativeUrl);
                    job.SitePolicy          = model.SitePolicy;
                    job.Owner               = ClaimsPrincipal.Current.Identity.Name;
                    job.ApplyTenantBranding = model.ApplyTenantBranding;

                    job.PrimarySiteCollectionAdmin = model.PrimarySiteCollectionAdmin != null &&
                                                     model.PrimarySiteCollectionAdmin.Principals.Count > 0 ?
                                                     (!String.IsNullOrEmpty(model.PrimarySiteCollectionAdmin.Principals[0].Mail) ?
                                                      model.PrimarySiteCollectionAdmin.Principals[0].Mail :
                                                      null) : null;
                    job.SecondarySiteCollectionAdmin = model.SecondarySiteCollectionAdmin != null &&
                                                       model.SecondarySiteCollectionAdmin.Principals.Count > 0 ?
                                                       (!String.IsNullOrEmpty(model.SecondarySiteCollectionAdmin.Principals[0].Mail) ?
                                                        model.SecondarySiteCollectionAdmin.Principals[0].Mail :
                                                        null) : null;

                    job.ProvisioningTemplateUrl      = model.ProvisioningTemplateUrl;
                    job.TemplatesProviderTypeName    = model.TemplatesProviderTypeName;
                    job.StorageMaximumLevel          = model.StorageMaximumLevel;
                    job.StorageWarningLevel          = model.StorageWarningLevel;
                    job.UserCodeMaximumLevel         = model.UserCodeMaximumLevel;
                    job.UserCodeWarningLevel         = model.UserCodeWarningLevel;
                    job.ExternalSharingEnabled       = model.ExternalSharingEnabled;
                    job.ResponsiveDesignEnabled      = model.ResponsiveDesignEnabled;
                    job.PartnerPackExtensionsEnabled = model.PartnerPackExtensionsEnabled;
                    job.Title = String.Format("Provisioning of Site Collection \"{1}\" with Template \"{0}\" by {2}",
                                              job.ProvisioningTemplateUrl,
                                              job.RelativeUrl,
                                              job.Owner);

                    job.TemplateParameters = model.TemplateParameters;

                    model.JobId = ProvisioningRepositoryFactory.Current.EnqueueProvisioningJob(job);
                }
            }

            return(PartialView(model.Step.ToString(), model));
        }
        private void CreateSiteCollection(SiteCollectionProvisioningJob job)
        {
            using (PnPMonitoredScope Log = new PnPMonitoredScope("CreateSiteCollection"))
            {
                // build site collection url
                String siteUrl = String.Format("{0}{1}",
                                               ConfigurationHelper.GetConfiguration.HostSiteUrl.Substring(0, ConfigurationHelper.GetConfiguration.HostSiteUrl.LastIndexOf("/") + 1),
                                               job.RelativeUrl.TrimStart('/'));

                // get provisioning template
                var provisioningTemplate = GetProvisioningTemplate(job.PnPTemplate);

                if (provisioningTemplate != null)
                {
                    job.BaseTemplate = string.IsNullOrEmpty(provisioningTemplate.BaseSiteTemplate)
                        ? (string.IsNullOrEmpty(job.BaseTemplate)
                            ? ConfigurationHelper.GetConfiguration.BaseSiteTemplate
                            : job.BaseTemplate)
                        : provisioningTemplate.BaseSiteTemplate;
                }
                else
                {
                    job.BaseTemplate = string.IsNullOrEmpty(job.BaseTemplate)
                            ? ConfigurationHelper.GetConfiguration.BaseSiteTemplate
                            : job.BaseTemplate;
                }

                using (var adminContext = AppOnlyContextProvider.GetAppOnlyContext(ConfigurationHelper.GetConfiguration.TenantAdminUrl))
                {
                    adminContext.RequestTimeout = Timeout.Infinite;

                    // Create the Site Collection and wait for its creation (we're asynchronous)
                    var tenant = new Tenant(adminContext);

                    // check if site collection already exists and in active state.
                    if (tenant.CheckIfSiteExists(siteUrl, Constants.Site_Status_Active))
                    {
                        Log.LogError($"Site collection with url \"{siteUrl}\" already exists.");
                    }
                    else
                    {
                        Log.LogInfo($"Creating site collection \"{job.RelativeUrl}\" with template {job.BaseTemplate})");

                        try
                        {
                            tenant.CreateSiteCollection(new SiteEntity()
                            {
                                Description         = job.Description,
                                Title               = job.Title,
                                Url                 = siteUrl,
                                SiteOwnerLogin      = ConfigurationHelper.GetConfiguration.PrimarySiteCollectionAdministrator,
                                StorageMaximumLevel = job.StorageMaximumLevel,
                                StorageWarningLevel = job.StorageWarningLevel,
                                Template            = job.BaseTemplate,
                                Lcid                = ((provisioningTemplate != null && provisioningTemplate.RegionalSettings != null) &&
                                                       provisioningTemplate.RegionalSettings.LocaleId > 0)
                                        ? uint.Parse(provisioningTemplate.RegionalSettings.LocaleId.ToString())
                                        : job.Language,
                                TimeZoneId = ((provisioningTemplate != null && provisioningTemplate.RegionalSettings != null) &&
                                              provisioningTemplate.RegionalSettings.TimeZone > 0)
                                        ? provisioningTemplate.RegionalSettings.TimeZone
                                        : job.TimeZone,
                            }, removeFromRecycleBin: true, wait: true);
                        }
                        catch (Exception exception)
                        {
                            Log.LogError($"Error occured while creating site collection {job.RelativeUrl}");

                            if (tenant.SiteExists(siteUrl))
                            {
                                tenant.DeleteSiteCollection(siteUrl, useRecycleBin: false);
                            }

                            throw exception;
                        }
                    }

                    if (provisioningTemplate != null)
                    {
                        Log.LogInfo($"Applying provisioning template {provisioningTemplate.DisplayName}");
                        ApplyProvisioningTemplate(provisioningTemplate, siteUrl);
                    }

                    Log.LogInfo($"Site collection {siteUrl} provisioned successfully.");
                }
            }
        }
        private void CreateSiteCollection(SiteCollectionProvisioningJob job)
        {
            Console.WriteLine("Creating Site Collection \"{0}\".", job.RelativeUrl);

            // Define the full Site Collection URL
            String siteUrl = String.Format("{0}{1}",
                PnPPartnerPackSettings.InfrastructureSiteUrl.Substring(0, PnPPartnerPackSettings.InfrastructureSiteUrl.IndexOf("sharepoint.com/") + 14),
                job.RelativeUrl);

            // Load the template from the source Templates Provider
            if (!String.IsNullOrEmpty(job.TemplatesProviderTypeName))
            {
                ProvisioningTemplate template = null;

                var templatesProvider = PnPPartnerPackSettings.TemplatesProviders[job.TemplatesProviderTypeName];
                if (templatesProvider != null)
                {
                    template = templatesProvider.GetProvisioningTemplate(job.ProvisioningTemplateUrl);
                }

                if (template != null)
                {
                    using (var adminContext = PnPPartnerPackContextProvider.GetAppOnlyTenantLevelClientContext())
                    {
                        adminContext.RequestTimeout = Timeout.Infinite;

                        // Configure the Site Collection properties
                        SiteEntity newSite = new SiteEntity();
                        newSite.Description = job.Description;
                        newSite.Lcid = (uint)job.Language;
                        newSite.Title = job.SiteTitle;
                        newSite.Url = siteUrl;
                        newSite.SiteOwnerLogin = job.PrimarySiteCollectionAdmin;
                        newSite.StorageMaximumLevel = job.StorageMaximumLevel;
                        newSite.StorageWarningLevel = job.StorageWarningLevel;

                        // Use the BaseSiteTemplate of the template, if any, otherwise
                        // fallback to the pre-configured site template (i.e. STS#0)
                        newSite.Template = !String.IsNullOrEmpty(template.BaseSiteTemplate) ?
                            template.BaseSiteTemplate :
                            PnPPartnerPackSettings.DefaultSiteTemplate;

                        newSite.TimeZoneId = job.TimeZone;
                        newSite.UserCodeMaximumLevel = job.UserCodeMaximumLevel;
                        newSite.UserCodeWarningLevel = job.UserCodeWarningLevel;

                        // Create the Site Collection and wait for its creation (we're asynchronous)
                        var tenant = new Tenant(adminContext);
                        tenant.CreateSiteCollection(newSite, true, true); // TODO: Do we want to empty Recycle Bin?

                        Site site = tenant.GetSiteByUrl(siteUrl);
                        Web web = site.RootWeb;

                        adminContext.Load(site, s => s.Url);
                        adminContext.Load(web, w => w.Url);
                        adminContext.ExecuteQueryRetry();

                        // Enable Secondary Site Collection Administrator
                        if (!String.IsNullOrEmpty(job.SecondarySiteCollectionAdmin))
                        {
                            Microsoft.SharePoint.Client.User secondaryOwner = web.EnsureUser(job.SecondarySiteCollectionAdmin);
                            secondaryOwner.IsSiteAdmin = true;
                            secondaryOwner.Update();

                            web.SiteUsers.AddUser(secondaryOwner);
                            adminContext.ExecuteQueryRetry();
                        }

                        Console.WriteLine("Site \"{0}\" created.", site.Url);

                        // Check if external sharing has to be enabled
                        if (job.ExternalSharingEnabled)
                        {
                            EnableExternalSharing(tenant, site);

                            // Enable External Sharing
                            Console.WriteLine("Enabled External Sharing for site \"{0}\".",
                                site.Url);
                        }
                    }

                    // Move to the context of the created Site Collection
                    using (ClientContext clientContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext(siteUrl))
                    {
                        clientContext.RequestTimeout = Timeout.Infinite;

                        Site site = clientContext.Site;
                        Web web = site.RootWeb;

                        clientContext.Load(site, s => s.Url);
                        clientContext.Load(web, w => w.Url);
                        clientContext.ExecuteQueryRetry();

                        // Check if we need to enable PnP Partner Pack overrides
                        if (job.PartnerPackExtensionsEnabled)
                        {
                            // Enable Responsive Design
                            PnPPartnerPackUtilities.EnablePartnerPackOnSite(site.Url);

                            Console.WriteLine("Enabled PnP Partner Pack Overrides on site \"{0}\".",
                                site.Url);
                        }

                        // Check if the site has to be responsive
                        if (job.ResponsiveDesignEnabled)
                        {
                            // Enable Responsive Design
                            PnPPartnerPackUtilities.EnableResponsiveDesignOnSite(site.Url);

                            Console.WriteLine("Enabled Responsive Design Template to site \"{0}\".",
                                site.Url);
                        }

                        // Apply the Provisioning Template
                        Console.WriteLine("Applying Provisioning Template \"{0}\" to site.",
                            job.ProvisioningTemplateUrl);

                        // We do intentionally remove taxonomies, which are not supported
                        // in the AppOnly Authorization model
                        // For further details, see the PnP Partner Pack documentation
                        ProvisioningTemplateApplyingInformation ptai =
                            new ProvisioningTemplateApplyingInformation();

                        // Write provisioning steps on console log
                        ptai.MessagesDelegate += delegate (string message, ProvisioningMessageType messageType)
                        {
                            Console.WriteLine("{0} - {1}", messageType, messageType);
                        };
                        ptai.ProgressDelegate += delegate (string message, int step, int total)
                        {
                            Console.WriteLine("{0:00}/{1:00} - {2}", step, total, message);
                        };

                        // Exclude handlers not supported in App-Only
                        ptai.HandlersToProcess ^=
                            OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.TermGroups;
                        ptai.HandlersToProcess ^=
                            OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.SearchSettings;

                        // Configure template parameters
                        if (job.TemplateParameters != null)
                        {
                            foreach (var key in job.TemplateParameters.Keys)
                            {
                                if (job.TemplateParameters.ContainsKey(key))
                                {
                                    template.Parameters[key] = job.TemplateParameters[key];
                                }
                            }
                        }

                        // Fixup Title and Description
                        if (template.WebSettings != null)
                        {
                            template.WebSettings.Title = job.SiteTitle;
                            template.WebSettings.Description = job.Description;
                        }

                        // Apply the template to the target site
                        web.ApplyProvisioningTemplate(template, ptai);

                        // Save the template information in the target site
                        var info = new SiteTemplateInfo()
                        {
                            TemplateProviderType = job.TemplatesProviderTypeName,
                            TemplateUri = job.ProvisioningTemplateUrl,
                            TemplateParameters = template.Parameters,
                            AppliedOn = DateTime.Now,
                        };
                        var jsonInfo = JsonConvert.SerializeObject(info);
                        web.SetPropertyBagValue(PnPPartnerPackConstants.PropertyBag_TemplateInfo, jsonInfo);

                        // Set site policy template
                        if (!String.IsNullOrEmpty(job.SitePolicy))
                        {
                            web.ApplySitePolicy(job.SitePolicy);
                        }

                        // Apply Tenant Branding, if requested
                        if (job.ApplyTenantBranding)
                        {
                            var brandingSettings = PnPPartnerPackUtilities.GetTenantBrandingSettings();

                            using (var repositoryContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext(
                                PnPPartnerPackSettings.InfrastructureSiteUrl))
                            {
                                var brandingTemplate = BrandingJobHandler.PrepareBrandingTemplate(repositoryContext, brandingSettings);

                                // Fixup Title and Description
                                if (brandingTemplate != null)
                                {
                                    if (brandingTemplate.WebSettings != null)
                                    {
                                        brandingTemplate.WebSettings.Title = job.SiteTitle;
                                        brandingTemplate.WebSettings.Description = job.Description;
                                    }

                                    // TO-DO: Need to handle exception here as there are multiple webs inside this where
                                    BrandingJobHandler.ApplyBrandingOnWeb(web, brandingSettings, brandingTemplate);
                                }
                            }
                        }

                        Console.WriteLine("Applyed Provisioning Template \"{0}\" to site.",
                            job.ProvisioningTemplateUrl);
                    }
                }
            }
        }