private void UpdateTemplateOnWeb(Web targetWeb, RefreshSitesJob job)
        {
            targetWeb.EnsureProperty(w => w.Url);

            var infoJson = targetWeb.GetPropertyBagValueString(PnPPartnerPackConstants.PropertyBag_TemplateInfo, null);
            if (!String.IsNullOrEmpty(infoJson))
            {
                Console.WriteLine($"Updating template for site: {targetWeb.Url}");

                var info = JsonConvert.DeserializeObject<SiteTemplateInfo>(infoJson);

                // If we have the template info
                if (info != null && !String.IsNullOrEmpty(info.TemplateProviderType))
                {
                    ProvisioningTemplate template = null;

                    // Try to retrieve the template
                    var templatesProvider = PnPPartnerPackSettings.TemplatesProviders[info.TemplateProviderType];
                    if (templatesProvider != null)
                    {
                        template = templatesProvider.GetProvisioningTemplate(info.TemplateUri);
                    }

                    // If we have the template
                    if (template != null)
                    {
                        // Configure proper settings for the provisioning engine
                        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 (info.TemplateParameters != null)
                        {
                            foreach (var key in info.TemplateParameters.Keys)
                            {
                                if (info.TemplateParameters.ContainsKey(key))
                                {
                                    template.Parameters[key] = info.TemplateParameters[key];
                                }
                            }
                        }

                        targetWeb.ApplyProvisioningTemplate(template, ptai);

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

                        Console.WriteLine($"Updated template on site: {targetWeb.Url}");

                        // Update (recursively) all the subwebs of the current web
                        targetWeb.EnsureProperty(w => w.Webs);

                        foreach (var subweb in targetWeb.Webs)
                        {
                            UpdateTemplateOnWeb(subweb, job);
                        }
                    }
                }
            }
        }
예제 #2
1
파일: Template.cs 프로젝트: coupalm/PnP
        // ===========================================================================================================
        /// <summary>
        /// Applies the current template as an open XML ".pnp" package on the specified web
        /// </summary>
        /// <param name="web">The <b>Web</b> on which to apply the template</param>
        /// <param name="templateProvider">The <b>XMLTemplateProvider</b> that is mapped to the client's working directory</param>
        // ===========================================================================================================
        private void ApplyOpenXML(Web web, XMLTemplateProvider templateProvider)
        {
            logger.Info("Applying open XML package '{0}' from file '{1}'", this.Name, this.Path);

            // --------------------------------------------------
            // Formats the template's execution rendering
            // --------------------------------------------------
            ProvisioningTemplateApplyingInformation ptai = GetTemplateApplyInfo();

            // --------------------------------------------------
            // Replaces the regular provider by an OpenXml one
            // --------------------------------------------------
            string workingDirectory = templateProvider.Connector.Parameters[PARAMETER_CONNECTION_STRING].ToString();
            FileSystemConnector fileSystemConnector = new FileSystemConnector(workingDirectory, "");
            OpenXMLConnector openXmlConnector = new OpenXMLConnector(this.Path, fileSystemConnector);
            XMLTemplateProvider openXmlTemplateProvider = new XMLOpenXMLTemplateProvider(openXmlConnector);

            // --------------------------------------------------
            // Loops through all templates within the .pnp package
            // --------------------------------------------------
            List<ProvisioningTemplate> templates = openXmlTemplateProvider.GetTemplates();

            foreach (ProvisioningTemplate template in templates)
            {
                logger.Info("Applying template '{0}' from file '{1}'", template.Id, this.Path);

                // --------------------------------------------------
                // Applies the template 
                // --------------------------------------------------
                template.Connector = openXmlTemplateProvider.Connector;
                web.ApplyProvisioningTemplate(template, ptai);
            }
        }
예제 #3
0
        private void ApplyProvisioningTemplate(ProvisioningTemplate template, Web web)
        {
            using (PnPMonitoredScope Log = new PnPMonitoredScope("ApplyProvisioningTemplate"))
            {
                web.Context.Load(web);
                web.Context.ExecuteQueryRetry();

                try
                {
                    var applyingInfo = new ProvisioningTemplateApplyingInformation
                    {
                        ProgressDelegate =
                            (message, step, total) =>
                        {
                            Log.LogInfo($"{step}/{total} Provisioning {message}");
                        }
                    };

                    web.ApplyProvisioningTemplate(template, applyingInfo);
                }
                catch (Exception exception)
                {
                    Log.LogError($"Error occured while applying template {template.DisplayName}: {exception.Message}");
                }
            }
        }
예제 #4
0
        public static void ApplyCustomTemplateToSite(ConsoleColor defaultForeground, ClientContext ctx, ProvisioningTemplate template)
        {
            try
            {
                {
                    //ctx.Credentials = new NetworkCredentials(userName, pwd);
                    //ctx.Credentials = new SharePointOnlineCredentials(userName, pwd);
                    //ctx.RequestTimeout = Timeout.Infinite;

                    // Just to output the site details
                    Web web = ctx.Web;
                    ctx.Load(web, w => w.Title);
                    ctx.ExecuteQueryRetry();

                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine("Your site title is:" + ctx.Web.Title);
                    Console.ForegroundColor = defaultForeground;

                    // Apply template to the site
                    var applyingInformation = new ProvisioningTemplateApplyingInformation();

                    applyingInformation.HandlersToProcess = Handlers.All;
                    applyingInformation.ProgressDelegate  = new ProvisioningProgressDelegate(progressDelegateHandler);
                    web.ApplyProvisioningTemplate(template, applyingInformation);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
예제 #5
0
        // ===========================================================================================================
        /// <summary>
        /// Applies the current template as an open XML ".pnp" package on the specified web
        /// </summary>
        /// <param name="web">The <b>Web</b> on which to apply the template</param>
        /// <param name="templateProvider">The <b>XMLTemplateProvider</b> that is mapped to the client's working directory</param>
        // ===========================================================================================================
        private void ApplyOpenXML(Web web, XMLTemplateProvider templateProvider)
        {
            logger.Info("Applying open XML package '{0}' from file '{1}'", this.Name, this.Path);

            // --------------------------------------------------
            // Formats the template's execution rendering
            // --------------------------------------------------
            ProvisioningTemplateApplyingInformation ptai = GetTemplateApplyInfo();

            // --------------------------------------------------
            // Replaces the regular provider by an OpenXml one
            // --------------------------------------------------
            string workingDirectory = templateProvider.Connector.Parameters[PARAMETER_CONNECTION_STRING].ToString();
            FileSystemConnector fileSystemConnector     = new FileSystemConnector(workingDirectory, "");
            OpenXMLConnector    openXmlConnector        = new OpenXMLConnector(this.Path, fileSystemConnector);
            XMLTemplateProvider openXmlTemplateProvider = new XMLOpenXMLTemplateProvider(openXmlConnector);

            // --------------------------------------------------
            // Loops through all templates within the .pnp package
            // --------------------------------------------------
            List <ProvisioningTemplate> templates = openXmlTemplateProvider.GetTemplates();

            foreach (ProvisioningTemplate template in templates)
            {
                logger.Info("Applying template '{0}' from file '{1}'", template.Id, this.Path);

                // --------------------------------------------------
                // Applies the template
                // --------------------------------------------------
                template.Connector = openXmlTemplateProvider.Connector;
                web.ApplyProvisioningTemplate(template, ptai);
            }
        }
예제 #6
0
        /// <summary>
        /// Apply a template on Sharepoint site
        /// </summary>
        /// <param name="targetWebUrl">Url Web Site template</param>
        /// <param name="userName">User Name</param>
        /// <param name="pwd">Password</param>
        /// <param name="template">The template from Sharepoint</param>
        private static void ApplyProvisioningTemplate(string targetWebUrl, string userName, SecureString pwd, ProvisioningTemplate template)
        {
            using (var ctx = new ClientContext(targetWebUrl))
            {
                // ctx.Credentials = new NetworkCredentials(userName, pwd);
                ctx.Credentials    = new SharePointOnlineCredentials(userName, pwd);
                ctx.RequestTimeout = Timeout.Infinite;

                Web web = ctx.Web;

                ProvisioningTemplateApplyingInformation ptai = new ProvisioningTemplateApplyingInformation();
                ptai.ProgressDelegate = delegate(String message, Int32 progress, Int32 total)
                {
                    Console.WriteLine("{0:00}/{1:00} - {2}", progress, total, message);
                };

                // Associate file connector for assets
                FileSystemConnector connector = new FileSystemConnector(@"C:\Users\DIOUM2TOUBA\pnpprovisioningdemo", "");
                template.Connector = connector;

                // Because the template is actual object, we can modify this using code as needed
                template.Lists.Add(new ListInstance()
                {
                    Title             = "PnP Sample Contacts",
                    Url               = "lists/PnPContacts",
                    TemplateType      = (Int32)ListTemplateType.Contacts,
                    EnableAttachments = true
                });

                web.ApplyProvisioningTemplate(template, ptai);
            }
        }
예제 #7
0
        public static bool ApplyTemplate(Web web, string provisioningFolder, string templateFile)
        {
            var template = GetTemplateFromUrl(provisioningFolder, templateFile);
            
            if (template != null)
            {
                try
                {
                    // Change files location
                    foreach(var file in template.Files)
                    {
                        file.Src = string.Concat(provisioningFolder, file.Src);
                    }

                    web.ApplyProvisioningTemplate(template);

                    Console.WriteLine("INFO: ProvisioningHelper.ApplyTemplate({0}) - {1}", templateFile, "Provisioning template has been applied!");
                    return true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("ERROR: ProvisioningHelper.ApplyTemplate({0}) - {1}", templateFile, ex.Message);
                    return false;
                }
            }
            else
            {
                Console.WriteLine("INFO: ProvisioningHelper.ApplyTemplate({0}) - {1}", templateFile, "Provisioning Template is NULL");
                return false;
            }
        }
예제 #8
0
        public static void ProvisionArtifactsByTemplate()
        {
            // Create a PnP AuthenticationManager object
            AuthenticationManager am = new AuthenticationManager();

            // Authenticate against SPO with an App-Only access token
            using (ClientContext context = am.GetAzureADAppOnlyAuthenticatedContext(
                       O365ProjectsAppContext.CurrentSiteUrl, O365ProjectsAppSettings.ClientId,
                       O365ProjectsAppSettings.TenantId, O365ProjectsAppSettings.AppOnlyCertificate))
            {
                Web web = context.Web;

                // Load the template from the file system
                XMLTemplateProvider provider =
                    new XMLFileSystemTemplateProvider(
                        String.Format(HttpContext.Current.Server.MapPath(".")),
                        "ProvisioningTemplates");

                ProvisioningTemplate template = provider.GetTemplate("O365ProjectsAppSite.xml");

                // Configure the AppSiteUrl parameter
                template.Parameters["AppSiteUrl"] = O365ProjectsAppContext.CurrentAppSiteUrl;

                // Apply the template to the target site
                template.Connector = provider.Connector;
                web.ApplyProvisioningTemplate(template);
            }
        }
        private void ApplyProvisioningTemplate(ProvisioningTemplate template, string siteCollectionUrl)
        {
            using (PnPMonitoredScope Log = new PnPMonitoredScope("ApplyProvisioningTemplate"))
            {
                using (var siteContext = AppOnlyContextProvider.GetAppOnlyContext(siteCollectionUrl))
                {
                    Site site = siteContext.Site;
                    Web  web  = site.RootWeb;

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

                    try
                    {
                        var applyingInfo = new ProvisioningTemplateApplyingInformation
                        {
                            ProgressDelegate =
                                (message, step, total) =>
                            {
                                Log.LogInfo($"{step}/{total} Provisioning {message}");
                            }
                        };

                        web.ApplyProvisioningTemplate(template, applyingInfo);
                    }
                    catch (Exception exception)
                    {
                        Log.LogError($"Error occured while applying template {template.DisplayName}: {exception.Message}");
                    }
                }
            }
        }
예제 #10
0
        public static void Apply(Web web, string templatePath, string templateName)
        {
            try
            {
                LogWriter.Current.WriteLine("Applying " + templateName);
                // Connector to file system. Use current .exe folder as root, don't specify a subfolder
                var connector = new FileSystemConnector(LocalFilePaths.LocalPath, string.Empty);
                // Provider to get template
                XMLTemplateProvider provider = new XMLFileSystemTemplateProvider();
                provider.Connector = connector;
                var result = provider.GetTemplate(templatePath + "\\" + templateName);

                // Connector needs to be specified once more in ProvisioningTemplate because he is not copied from the provider on template creation
                result.Connector = connector;
                var applyingInformation = new ProvisioningTemplateApplyingInformation();
                applyingInformation.ProgressDelegate = (message, step, total) =>
                {
                    LogWriter.Current.WriteLine(string.Format("{0}/{1} Provisioning {2}", step, total, message));
                };

                web.ApplyProvisioningTemplate(result, applyingInformation);
            }
            catch (Exception ex)
            {
                LogWriter.Current.WriteLine(string.Format("Error applying template {0} : {1} - {2}", templateName, ex.Message, ex.StackTrace));
            }
        }
예제 #11
0
        /// <summary>
        /// This method will apply the PnP template to all sites in the SP List that have the 'Apply Global Nav' field set to Yes
        /// </summary>
        /// <param name="sitesToApply"></param>
        /// <param name="userName"></param>
        /// <param name="pwd"></param>
        /// <param name="template"></param>
        private static void ApplyPnPTemplate(List <GlobalNavSiteCollections> sitesToApply, string userName, SecureString pwd, ProvisioningTemplate template)
        {
            foreach (GlobalNavSiteCollections site in sitesToApply)
            {
                using (var ctx = new ClientContext(site.SiteURL))
                {
                    // ctx.Credentials = new NetworkCredentials(userName, pwd);
                    ctx.Credentials    = new SharePointOnlineCredentials(userName, pwd);
                    ctx.RequestTimeout = Timeout.Infinite;

                    // Just to output the site details
                    Web web = ctx.Web;
                    ctx.Load(web, w => w.Title);
                    ctx.ExecuteQueryRetry();

                    // start timer
                    Console.WriteLine("Start Applying Template: {0:hh.mm.ss}", DateTime.Now);

                    // Apply the template to another site
                    var applyingInformation = new ProvisioningTemplateApplyingInformation();

                    // overwrite and remove existing navigation nodes
                    applyingInformation.ClearNavigation = true;

                    applyingInformation.ProgressDelegate = (message, step, total) =>
                    {
                        Console.WriteLine("{0}/{1} Provisioning {2}", step, total, message);
                    };

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

                    Console.WriteLine("Done applying template: {0:hh.mm.ss}", DateTime.Now);

                    // Check governance of property bags
                    Console.WriteLine("Look what the engine left behind!");
                    Console.Write("_PnP_ProvisioningTemplateId: ");

                    Console.WriteLine(
                        web.GetPropertyBagValueString("_PnP_ProvisioningTemplateId", "")
                        );
                    Console.Write("_PnP_ProvisioningTemplateInfo: ");

                    Console.WriteLine(
                        web.GetPropertyBagValueString("_PnP_ProvisioningTemplateInfo", "")
                        );


                    // Configure the XML file system provider
                    //XMLTemplateProvider providerNewNav =
                    // new XMLFileSystemTemplateProvider(@"c:\temp\pnpprovisioningdemo\", "");

                    // Load the template from the XML stored copy
                    // ProvisioningTemplate templateNewNav = providerNewNav.GetTemplate("GlobalNav.xml");
                }
            }
        }
예제 #12
0
        static void Main(string[] args)
        {
            try
            {
                ConsoleColor defaultForeground = Console.ForegroundColor;

                // Collect information
                // string templateWebUrl = GetInput("Enter the URL of the template site: ", false, defaultForeground);
                string targetWebUrl = GetInput("Enter the URL of the target site: ", false, defaultForeground);
                string userName     = GetInput("Enter your user name:", false, defaultForeground);
                string pwdS         = GetInput("Enter your password:"******"Get XMl Path:", false, defaultForeground);
                string filename     = GetInput("Get XMl filename:", false, defaultForeground);

                SecureString pwd = new SecureString();

                foreach (char c in pwdS.ToCharArray())
                {
                    pwd.AppendChar(c);
                }
                using (var context = new ClientContext(targetWebUrl))
                {
                    context.Credentials = new SharePointOnlineCredentials(userName, pwd);
                    Web web = context.Web;
                    context.Load(web, w => w.Title);
                    context.ExecuteQueryRetry();
                    XMLTemplateProvider provider =
                        new XMLFileSystemTemplateProvider(filepath, "");


                    ProvisioningTemplate template = provider.GetTemplate(filename);
                    ProvisioningTemplateApplyingInformation ptai =
                        new ProvisioningTemplateApplyingInformation();
                    ptai.ProgressDelegate = delegate(String message, Int32 progress, Int32 total)
                    {
                        Console.WriteLine("{0:00}/{1:00} - {2}", progress, total, message);
                    };



                    template.Connector = provider.Connector;

                    web.ApplyProvisioningTemplate(template, ptai);
                }
                // Get the template from existing site and serialize that (not really needed)
                // Just to pause and indicate that it's all done
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("We are all done. Press enter to continue.");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
예제 #13
0
파일: Program.cs 프로젝트: sr3007/CoxComm
        private static string ApplyProvisioningTemplate(ConsoleColor defaultForeground, string webUrl, string userName, SecureString pwd, ProvisioningTemplate template)
        {
            string errorMessage = string.Empty;

            using (var ctx = new ClientContext(webUrl))
            {
                ctx.Credentials    = new SharePointOnlineCredentials(userName, pwd);
                ctx.RequestTimeout = Timeout.Infinite;

                // Just to output the site details
                Web web = ctx.Web;
                ctx.Load(web, w => w.Title);
                ctx.ExecuteQueryRetry();

                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("Your site title is:" + ctx.Web.Title);
                Console.ForegroundColor = defaultForeground;

                ProvisioningTemplateApplyingInformation ptai
                    = new ProvisioningTemplateApplyingInformation();
                ptai.ProgressDelegate = delegate(String message, Int32 progress, Int32 total)
                {
                    Console.WriteLine("{0:00}/{1:00} - {2}", progress, total, message);
                };

                // Associate file connector for assets
                FileSystemConnector connector = new FileSystemConnector(ConfigurationManager.AppSettings["XMLConfigRootPath"], "");
                template.Connector = connector;

                try
                {
                    web.ApplyProvisioningTemplate(template, ptai);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error Occured.Details:{0}", ex.Message);
                    if (!string.IsNullOrEmpty(ex.Message))
                    {
                        errorMessage = ex.Message;
                    }
                    else if (!string.IsNullOrEmpty(ex.StackTrace))
                    {
                        errorMessage = string.Format("Error Occured. Stack Trace:-{0}", ex.StackTrace);
                    }
                    else
                    {
                        errorMessage = string.Format("Error Occured.");
                    }
                }
            }
            return(errorMessage);
        }
예제 #14
0
        //gavdcodeend 47

        //gavdcodebegin 48
        static void SpCsPnpcoreApplySiteTemplate(ClientContext spCtx)
        {
            Web myWeb = spCtx.Web;

            spCtx.Load(myWeb, w => w.Title);
            spCtx.ExecuteQueryRetry();

            OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.XMLTemplateProvider
                myXmlProvider = new OfficeDevPnP.Core.Framework.Provisioning.Providers.
                                Xml.XMLFileSystemTemplateProvider(@"C:\Temporary", "");

            OfficeDevPnP.Core.Framework.Provisioning.Model.ProvisioningTemplate
                myTemplate = myXmlProvider.GetTemplate("TestProvisioningSite.xml");

            myWeb.ApplyProvisioningTemplate(myTemplate);
        }
예제 #15
0
        private static void ApplyProvisioningTemplate(ConsoleColor defaultForeground, string webUrl, string userName, SecureString pwd, ProvisioningTemplate template)
        {
            using (var ctx = new ClientContext(webUrl))
            {
                // ctx.Credentials = new NetworkCredentials(userName, pwd);
                ctx.Credentials    = new SharePointOnlineCredentials(userName, pwd);
                ctx.RequestTimeout = Timeout.Infinite;

                // Just to output the site details
                Web web = ctx.Web;
                ctx.Load(web, w => w.Title);
                ctx.ExecuteQueryRetry();

                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("Your site title is:" + ctx.Web.Title);
                Console.ForegroundColor = defaultForeground;

                // We could potentially also upload the template from file system, but we at least need this for branding file
                XMLTemplateProvider provider =
                    new XMLFileSystemTemplateProvider(@"c:\temp\pnpprovisioningdemo", "");
                template = provider.GetTemplate("PnPProvisioningDemo.xml");

                ProvisioningTemplateApplyingInformation ptai = new ProvisioningTemplateApplyingInformation
                {
                    ProgressDelegate =
                        delegate(string message, int progress, int total)
                    {
                        Console.WriteLine("{0:00}/{1:00} - {2}", progress, total, message);
                    }
                };

                // Associate file connector for assets
                FileSystemConnector connector = new FileSystemConnector(@"c:\temp\pnpprovisioningdemo", "");
                template.Connector = connector;

                // Since template is actual object, we can modify this using code as needed
                template.Lists.Add(new ListInstance
                {
                    Title             = "PnP Sample Contacts",
                    Url               = "lists/PnPContacts",
                    TemplateType      = (int)ListTemplateType.Contacts,
                    EnableAttachments = true
                });

                web.ApplyProvisioningTemplate(template, ptai);
            }
        }
        private static void ApplyProvisioningTemplate(Web web, string container, string filename)
        {
            XMLTemplateProvider provider =
                new XMLFileSystemTemplateProvider(
                    String.Format(@"{0}\..\..\..\OfficeDevPnP.PartnerPack.SiteProvisioning\Templates",
                                  AppDomain.CurrentDomain.BaseDirectory),
                    container);

            ProvisioningTemplate template = provider.GetTemplate(filename);

            template.Connector = provider.Connector;

            ProvisioningTemplateApplyingInformation ptai =
                new ProvisioningTemplateApplyingInformation();

            web.ApplyProvisioningTemplate(template, ptai);
        }
예제 #17
0
        private static void applyTemplate(string siteUrl, ExecutionContext functionContext, ClientCredentials credentials, TraceWriter log)
        {
            try
            {
                using (var ctx = new AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, credentials.ClientID, credentials.ClientSecret))
                {
                    Web web = ctx.Web;
                    ctx.Load(web, w => w.Title);
                    ctx.ExecuteQueryRetry();

                    log.Info($"Successfully connected to site: {web.Title}");

                    string              currentDirectory = functionContext.FunctionDirectory;
                    DirectoryInfo       dInfo            = new DirectoryInfo(currentDirectory);
                    var                 schemaDir        = dInfo.Parent.FullName + "\\Templates";
                    XMLTemplateProvider sitesProvider    = new XMLFileSystemTemplateProvider(schemaDir, "");

                    log.Info($"About to get template with with filename '{PNP_TEMPLATE_FILE}'");

                    ProvisioningTemplate template = sitesProvider.GetTemplate(PNP_TEMPLATE_FILE);

                    log.Info($"Successfully found template with ID '{template.Id}'");

                    ProvisioningTemplateApplyingInformation ptai = new ProvisioningTemplateApplyingInformation
                    {
                        ProgressDelegate = (message, progress, total) =>
                        {
                            log.Info(string.Format("{0:00}/{1:00} - {2}", progress, total, message));
                        }
                    };

                    // Associate file connector for assets..
                    FileSystemConnector connector = new FileSystemConnector(Path.Combine(currentDirectory, "Files"), "");
                    template.Connector = connector;

                    web.ApplyProvisioningTemplate(template, ptai);
                }
            }
            catch (Exception e)
            {
                log.Error("Error when applying PnP template!", e);
                throw;
            }
        }
예제 #18
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestMessage req, TraceWriter log, ExecutionContext context)
        {
            log.Info("C# HTTP trigger function processed a request.");

            try
            {
                var requestBody = await req.Content.ReadAsAsync <ApplyProvisioningInfo>();

                if (requestBody == null)
                {
                    return(req.CreateResponse(HttpStatusCode.BadRequest));
                }

                var ctx = Helper.GetADAppOnlyContext(requestBody.WebUrl, context.FunctionAppDirectory);
                using (ctx)
                {
                    Web web = ctx.Web;
                    ctx.Load(web, w => w.Title);
                    ctx.ExecuteQueryRetry();

                    // Configure the XML file system provider
                    XMLTemplateProvider provider =
                        new XMLFileSystemTemplateProvider(Path.GetTempPath(), "");

                    byte[]       byteArray = Encoding.ASCII.GetBytes(requestBody.Template);
                    MemoryStream stream    = new MemoryStream(byteArray);

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

                    // We can also use Apply-PnPProvisioningTemplate
                    web.ApplyProvisioningTemplate(template);
                }

                return(req.CreateErrorResponse(HttpStatusCode.OK, "Done!"));
            }
            catch (Exception ex)
            {
                return(req.CreateErrorResponse(System.Net.HttpStatusCode.InternalServerError, ex.Message));
            }
        }
예제 #19
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestMessage req, TraceWriter log, ExecutionContext context)
        {
            log.Info("C# HTTP trigger function processed a request.");

            try
            {
                var mprovider = new MultipartMemoryStreamProvider();
                await req.Content.ReadAsMultipartAsync(mprovider);

                var webUrlData = mprovider.Contents.Last();
                var webUrl     = await webUrlData.ReadAsStringAsync();

                var templateFile = mprovider.Contents[1];
                var fileData     = await templateFile.ReadAsStreamAsync();


                var ctx = Helper.GetADAppOnlyContext(webUrl, context.FunctionAppDirectory);
                using (ctx)
                {
                    Web web = ctx.Web;
                    ctx.Load(web, w => w.Title);
                    ctx.ExecuteQueryRetry();

                    // Configure the XML file system provider
                    XMLTemplateProvider provider =
                        new XMLFileSystemTemplateProvider(Path.GetTempPath(), "");

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

                    // We can also use Apply-PnPProvisioningTemplate
                    web.ApplyProvisioningTemplate(template);
                }

                return(req.CreateErrorResponse(HttpStatusCode.OK, "Done!"));
            }
            catch (Exception ex)
            {
                return(req.CreateErrorResponse(System.Net.HttpStatusCode.InternalServerError, ex.Message));
            }
        }
예제 #20
0
        // ===========================================================================================================
        /// <summary>
        /// Applies the current template as a regular XML template on the specified web
        /// </summary>
        /// <param name="web">The <b>Web</b> on which to apply the template</param>
        /// <param name="templateProvider">The <b>XMLTemplateProvider</b> that is mapped to the client's working directory</param>
        // ===========================================================================================================
        private void ApplyRegularXML(Web web, XMLTemplateProvider templateProvider)
        {
            logger.Info("Applying template '{0}' from file '{1}'", this.Name, this.Path);

            // --------------------------------------------------
            // Formats the template's execution rendering
            // --------------------------------------------------
            ProvisioningTemplateApplyingInformation ptai = GetTemplateApplyInfo();

            // --------------------------------------------------
            // Loads the template
            // --------------------------------------------------
            ProvisioningTemplate template = templateProvider.GetTemplate(this.Path);

            template.Connector = templateProvider.Connector;

            // --------------------------------------------------
            // Applies the template
            // --------------------------------------------------
            web.ApplyProvisioningTemplate(template, ptai);
        }
        public static void Run([QueueTrigger("cncprovisioningqueue", Connection = "AzureWebJobsDashboard")] string myQueueItem, TraceWriter log, ExecutionContext executionContext)
        {
            log.Info($"C# Queue trigger function processed: {myQueueItem}");
            var authManager = new AuthenticationManager();

            var clientContext = authManager.GetAppOnlyAuthenticatedContext(myQueueItem, ConfigurationManager.AppSettings["ClientId"], ConfigurationManager.AppSettings["ClientSecret"]);

            string        currentDirectory = executionContext.FunctionDirectory;
            DirectoryInfo dInfo            = new DirectoryInfo(currentDirectory);

            log.Info("Current directory:" + currentDirectory);
            var schemaDir = dInfo.Parent.FullName + "\\PnPSiteSchemas";

            log.Info("schemaDir:" + schemaDir);
            XMLTemplateProvider sitesProvider = new XMLFileSystemTemplateProvider(schemaDir, "");

            ProvisioningTemplate template = sitesProvider.GetTemplate("SiteCollectionSchema.xml");

            Web web = clientContext.Web;

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

            log.Info("Applying Provisioning template to site: " + clientContext.Web.Url);

            ProvisioningTemplateApplyingInformation ptai = new ProvisioningTemplateApplyingInformation
            {
                ProgressDelegate = (message, progress, total) =>
                {
                    log.Info(string.Format("{0:00}/{1:00} - {2}", progress, total, message));
                }
            };

            // Associate file connector for assets
            FileSystemConnector connector = new FileSystemConnector(Path.Combine(currentDirectory, "Files"), "");

            template.Connector = connector;

            web.ApplyProvisioningTemplate(template, ptai);
        }
예제 #22
0
        private static void ApplyProvisioningTemplate(ConsoleColor defaultForeground, string webUrl, string userName, SecureString pwd, ProvisioningTemplate template)
        {
            using (var ctx = new ClientContext(webUrl))
            {
                // ctx.Credentials = new NetworkCredentials(userName, pwd);
                ctx.Credentials    = new SharePointOnlineCredentials(userName, pwd);
                ctx.RequestTimeout = Timeout.Infinite;

                // Just to output the site details
                Web web = ctx.Web;
                ctx.Load(web, w => w.Title);
                ctx.ExecuteQueryRetry();

                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("Your site title is:" + ctx.Web.Title);
                Console.ForegroundColor = defaultForeground;

                // We could potentially also upload the template from file system, but we at least need this for branding file
                //XMLTemplateProvider provider =
                //       new XMLFileSystemTemplateProvider(@"c:\temp\pnpprovisioningdemo", "");
                //template = provider.GetTemplate("PnPProvisioningDemo.xml");

                ProvisioningTemplateApplyingInformation ptai
                    = new ProvisioningTemplateApplyingInformation();
                ptai.ProgressDelegate = delegate(String message, Int32 progress, Int32 total)
                {
                    Console.WriteLine("{0:00}/{1:00} - {2}", progress, total, message);
                };

                // Associate file connector for assets
                FileSystemConnector connector = new FileSystemConnector(@"c:\temp\pnpprovisioningdemo", "");
                template.Connector = connector;



                web.ApplyProvisioningTemplate(template, ptai);
            }
        }
예제 #23
0
 public static void ApplyPnpTemplate(Web web)
 {
     try
     {
         string schemaDir = @"D:\GitHub\SPFx\SiteDesignTemplate\SiteDesignTemplate";
         //XMLTemplateProvider sitesProvider = new XMLFileSystemTemplateProvider(schemaDir, "");
         XMLTemplateProvider sitesProvider = new XMLFileSystemTemplateProvider(schemaDir, "");
         Console.WriteLine("Applying Template to Create the Project site Information List in Modern Sharepoint Site..." + schemaDir);
         ProvisioningTemplate template = sitesProvider.GetTemplate("PnPSiteTemplate.xml");
         ProvisioningTemplateApplyingInformation ptai = new ProvisioningTemplateApplyingInformation
         {
             ProgressDelegate = (message, progress, total) =>
             {
                 Console.WriteLine(string.Format("{0:00}/{1:00} - {2}", progress, total, message));
             }
         };
         web.ApplyProvisioningTemplate(template, ptai);
     }
     catch (Exception ex)
     {
         Console.WriteLine("Exception: " + ex.Message);
     }
 }
        /// <summary>
        /// テンプレートを適用
        /// </summary>
        /// <param name="webUrl">適用先URI</param>
        /// <param name="account">ログインアカウント</param>
        /// <param name="password">ログインパスワード</param>
        /// <param name="log">ログライター</param>
        private static void Apply(Uri webUrl, string account, string password, string azureBlobKey, string azureBlobContainer, string templateFileName, TraceWriter log)
        {
            log.Info($"適用開始");
            using (ClientContext ctx = new ClientContext(webUrl))
            {
                log.Info($"認証情報作成");
                SecureString securePassword = new SecureString();
                foreach (char c in password.ToCharArray())
                {
                    securePassword.AppendChar(c);
                }
                ctx.Credentials = new SharePointOnlineCredentials(account, securePassword);

                log.Info($"テンプレート取得");
                var provider = new XMLAzureStorageTemplateProvider(azureBlobKey, azureBlobContainer);
                var template = provider.GetTemplate(templateFileName);
                log.Info($"リスト数:{ template.Lists?.Count }");
                foreach (var list in template.Lists)
                {
                    log.Info(list.Title);
                }

                log.Info($"テンプレート適用情報作成");
                var templateInfo = new ProvisioningTemplateApplyingInformation();

                templateInfo.ProgressDelegate = delegate(String message, Int32 progress, Int32 total)
                {
                    log.Info($"{progress}/{total} - {message}");
                };

                log.Info($"実行");
                Web web = ctx.Web;
                web.ApplyProvisioningTemplate(template, templateInfo);
            }
            log.Info($"適用終了");
        }
예제 #25
0
        private static async Task Provision(Web web, string rowKey, TextWriter log)
        {
            // pushes notifications to SignalR server
            // SignalR, in turn, redirects them to all connected clients
            var notifier = new SignalRNotifier(_configReader);

            var applyingInformation = new ProvisioningTemplateApplyingInformation
            {
                ProgressDelegate = (message, progress, total) =>
                {
                    log.WriteLine("{0:00}/{1:00} - {2}", progress, total, message);
                    var state = new ProvisioningState
                    {
                        Progress     = progress,
                        Total        = total,
                        Message      = message,
                        PartitionKey = Consts.PartitionKey,
                        Timestamp    = DateTimeOffset.UtcNow,
                        RowKey       = rowKey
                    };
                    _tableManager.InsertEntity(state);

                    Task.Run(async() => await notifier.NotifyProgress(state)).Wait();
                }
            };

            var provider = new XMLAzureStorageTemplateProvider(_storageConnection, "pnp-drone");

            var template = provider.GetTemplate("template.xml");

            template.Connector = new AzureStorageConnector(_storageConnection, "pnp-drone");

            web.ApplyProvisioningTemplate(template, applyingInformation);

            await notifier.NotifyCompleted();
        }
        internal static void UpdateTemplateOnWeb(Web targetWeb, RefreshSitesJob job = null)
        {
            targetWeb.EnsureProperty(w => w.Url);

            var infoJson = targetWeb.GetPropertyBagValueString(PnPPartnerPackConstants.PropertyBag_TemplateInfo, null);
            if (!String.IsNullOrEmpty(infoJson))
            {
                Console.WriteLine($"Updating template for site: {targetWeb.Url}");

                var info = JsonConvert.DeserializeObject<SiteTemplateInfo>(infoJson);

                // If we have the template info
                if (info != null && !String.IsNullOrEmpty(info.TemplateProviderType))
                {
                    ProvisioningTemplate template = null;

                    // Try to retrieve the template
                    var templatesProvider = PnPPartnerPackSettings.TemplatesProviders[info.TemplateProviderType];
                    if (templatesProvider != null)
                    {
                        template = templatesProvider.GetProvisioningTemplate(info.TemplateUri);
                    }

                    // If we have the template
                    if (template != null)
                    {
                        // Configure proper settings for the provisioning engine
                        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 (info.TemplateParameters != null)
                        {
                            foreach (var key in info.TemplateParameters.Keys)
                            {
                                if (info.TemplateParameters.ContainsKey(key))
                                {
                                    template.Parameters[key] = info.TemplateParameters[key];
                                }
                            }
                        }

                        targetWeb.ApplyProvisioningTemplate(template, ptai);

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

                        Console.WriteLine($"Updated template on site: {targetWeb.Url}");

                        // Update (recursively) all the subwebs of the current web
                        targetWeb.EnsureProperty(w => w.Webs);

                        foreach (var subweb in targetWeb.Webs)
                        {
                            UpdateTemplateOnWeb(subweb, job);
                        }
                    }
                }
            }
        }
        private void CreateSubSite(SubSiteProvisioningJob job)
        {
            // Determine the reference URLs and relative paths
            String subSiteUrl        = job.RelativeUrl;
            String siteCollectionUrl = PnPPartnerPackUtilities.GetSiteCollectionRootUrl(job.ParentSiteUrl);
            String parentSiteUrl     = job.ParentSiteUrl;

            Console.WriteLine("Creating Site \"{0}\" as child Site of \"{1}\".", subSiteUrl, parentSiteUrl);

            using (ClientContext context = PnPPartnerPackContextProvider.GetAppOnlyClientContext(parentSiteUrl))
            {
                context.RequestTimeout = Timeout.Infinite;

                // Get a reference to the parent Web
                Web parentWeb = context.Web;

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

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

                    if (template != null)
                    {
                        // Create the new sub site as a new child Web
                        WebCreationInformation newWeb = new WebCreationInformation();
                        newWeb.Description = job.Description;
                        newWeb.Language    = job.Language;
                        newWeb.Title       = job.SiteTitle;
                        newWeb.Url         = subSiteUrl;
                        newWeb.UseSamePermissionsAsParentSite = job.InheritPermissions;

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

                        Web web = parentWeb.Webs.Add(newWeb);
                        context.ExecuteQueryRetry();

                        if (template.ExtensibilityHandlers.Any())
                        {
                            // Clone Context pointing to Sub Site (needed for calling custom Extensibility Providers from the pnp template passing the right ClientContext)
                            string        newWeburl        = web.EnsureProperty(w => w.Url);
                            ClientContext webClientContext = context.Clone(newWeburl);
                            web = webClientContext.Web;
                        }

                        // Create sub-web unique groups
                        if (!job.InheritPermissions)
                        {
                            web.CreateDefaultAssociatedGroups(string.Empty, string.Empty, string.Empty);
                            context.ExecuteQueryRetry();
                        }

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

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

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

                        // Write provisioning steps on console log
                        ptai.MessagesDelegate = (message, type) =>
                        {
                            switch (type)
                            {
                            case ProvisioningMessageType.Warning:
                            {
                                Console.WriteLine("{0} - {1}", type, message);
                                break;
                            }

                            case ProvisioningMessageType.Progress:
                            {
                                var activity = message;
                                if (message.IndexOf("|") > -1)
                                {
                                    var messageSplitted = message.Split('|');
                                    if (messageSplitted.Length == 4)
                                    {
                                        var status            = messageSplitted[0];
                                        var statusDescription = messageSplitted[1];
                                        var current           = double.Parse(messageSplitted[2]);
                                        var total             = double.Parse(messageSplitted[3]);
                                        var percentage        = Convert.ToInt32((100 / total) * current);
                                        Console.WriteLine("{0} - {1} - {2}", percentage, status, statusDescription);
                                    }
                                    else
                                    {
                                        Console.WriteLine(activity);
                                    }
                                }
                                else
                                {
                                    Console.WriteLine(activity);
                                }
                                break;
                            }

                            case ProvisioningMessageType.Completed:
                            {
                                Console.WriteLine(type);
                                break;
                            }
                            }
                        };
                        ptai.ProgressDelegate = (message, step, total) =>
                        {
                            var percentage = Convert.ToInt32((100 / Convert.ToDouble(total)) * Convert.ToDouble(step));
                            Console.WriteLine("{0:00}/{1:00} - {2} - {3}", step, total, percentage, message);
                        };

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

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

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

                        // Replace existing structural navigation on target site
                        if (template.Navigation != null &&
                            template.Navigation.CurrentNavigation != null &&
                            template.Navigation.CurrentNavigation.StructuralNavigation != null &&
                            (template.Navigation.CurrentNavigation.NavigationType == CurrentNavigationType.Structural ||
                             template.Navigation.CurrentNavigation.NavigationType == CurrentNavigationType.StructuralLocal))
                        {
                            template.Navigation.CurrentNavigation.StructuralNavigation.RemoveExistingNodes = true;
                        }

                        // Replace existing Structural Global Navigation on target site
                        if (template.Navigation != null &&
                            template.Navigation.GlobalNavigation != null &&
                            template.Navigation.GlobalNavigation.StructuralNavigation != null &&
                            template.Navigation.GlobalNavigation.NavigationType == GlobalNavigationType.Structural)
                        {
                            template.Navigation.GlobalNavigation.StructuralNavigation.RemoveExistingNodes = true;
                        }

                        // 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);

                                BrandingJobHandler.ApplyBrandingOnWeb(web, brandingSettings, brandingTemplate);

                                // 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);
                    }
                }
            }
        }
        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);
                    }
                }
            }
        }
예제 #29
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 CreateSubSite(SubSiteProvisioningJob job)
        {
            // Determine the reference URLs and relative paths
            String subSiteUrl        = job.RelativeUrl;
            String siteCollectionUrl = PnPPartnerPackUtilities.GetSiteCollectionRootUrl(job.ParentSiteUrl);
            String parentSiteUrl     = job.ParentSiteUrl;

            Console.WriteLine("Creating Site \"{0}\" as child Site of \"{1}\".", subSiteUrl, parentSiteUrl);

            using (ClientContext context = PnPPartnerPackContextProvider.GetAppOnlyClientContext(parentSiteUrl))
            {
                context.RequestTimeout = Timeout.Infinite;

                // Get a reference to the parent Web
                Web parentWeb = context.Web;

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

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

                    if (template != null)
                    {
                        // Create the new sub site as a new child Web
                        WebCreationInformation newWeb = new WebCreationInformation();
                        newWeb.Description = job.Description;
                        newWeb.Language    = job.Language;
                        newWeb.Title       = job.SiteTitle;
                        newWeb.Url         = subSiteUrl;
                        newWeb.UseSamePermissionsAsParentSite = job.InheritPermissions;

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

                        Web web = parentWeb.Webs.Add(newWeb);
                        context.ExecuteQueryRetry();

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

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

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

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

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

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

                        // Fixup Title and Description
                        template.WebSettings.Title       = job.SiteTitle;
                        template.WebSettings.Description = job.Description;

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

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

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

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

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

                                // Fixup Title and Description
                                brandingTemplate.WebSettings.Title       = job.SiteTitle;
                                brandingTemplate.WebSettings.Description = job.Description;

                                BrandingJobHandler.ApplyBrandingOnWeb(web, brandingSettings, brandingTemplate);
                            }
                        }

                        Console.WriteLine("Applyed Provisioning Template \"{0}\" to site.",
                                          job.ProvisioningTemplateUrl);
                    }
                }
            }
        }
예제 #31
0
파일: Template.cs 프로젝트: coupalm/PnP
        // ===========================================================================================================
        /// <summary>
        /// Applies the current template as a regular XML template on the specified web
        /// </summary>
        /// <param name="web">The <b>Web</b> on which to apply the template</param>
        /// <param name="templateProvider">The <b>XMLTemplateProvider</b> that is mapped to the client's working directory</param>
        // ===========================================================================================================
        private void ApplyRegularXML(Web web, XMLTemplateProvider templateProvider)
        {
            logger.Info("Applying template '{0}' from file '{1}'", this.Name, this.Path);

            // --------------------------------------------------
            // Formats the template's execution rendering
            // --------------------------------------------------
            ProvisioningTemplateApplyingInformation ptai = GetTemplateApplyInfo();

            // --------------------------------------------------
            // Loads the template 
            // --------------------------------------------------
            ProvisioningTemplate template = templateProvider.GetTemplate(this.Path);
            template.Connector = templateProvider.Connector;

            // --------------------------------------------------
            // Applies the template 
            // --------------------------------------------------
            web.ApplyProvisioningTemplate(template, ptai);
        }
        private void CreateSubSite(SubSiteProvisioningJob job)
        {
            // Determine the reference URLs and relative paths
            String subSiteUrl        = job.RelativeUrl;
            String siteCollectionUrl = PnPPartnerPackUtilities.GetSiteCollectionRootUrl(job.ParentSiteUrl);
            String parentSiteUrl     = job.ParentSiteUrl;

            Console.WriteLine("Creating Site \"{0}\" as child Site of \"{1}\".", subSiteUrl, parentSiteUrl);

            using (ClientContext context = PnPPartnerPackContextProvider.GetAppOnlyClientContext(parentSiteUrl))
            {
                // Get a reference to the parent Web
                Web parentWeb = context.Web;

                // Create the new sub site as a new child Web
                WebCreationInformation newWeb = new WebCreationInformation();
                newWeb.Description = job.Description;
                newWeb.Language    = job.Language;
                newWeb.Title       = job.SiteTitle;
                newWeb.Url         = subSiteUrl;
                newWeb.UseSamePermissionsAsParentSite = job.InheritPermissions;
                newWeb.WebTemplate = PnPPartnerPackSettings.DefaultSiteTemplate;

                Web web = parentWeb.Webs.Add(newWeb);
                context.ExecuteQueryRetry();

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

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

                // Determine the reference URLs and file names
                String templatesSiteUrl = job.ProvisioningTemplateUrl.Substring(0,
                                                                                job.ProvisioningTemplateUrl.IndexOf(PnPPartnerPackConstants.PnPProvisioningTemplates));
                String templateFileName = job.ProvisioningTemplateUrl.Substring(job.ProvisioningTemplateUrl.LastIndexOf("/") + 1);

                // Configure the XML file system provider
                XMLTemplateProvider provider =
                    new XMLSharePointTemplateProvider(context, templatesSiteUrl,
                                                      PnPPartnerPackConstants.PnPProvisioningTemplates);

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

                // We do intentionally remove taxonomies, which are not supported in the AppOnly Authorization model
                // For further details, see the PnP Partner Pack documentation
                ProvisioningTemplateApplyingInformation ptai =
                    new ProvisioningTemplateApplyingInformation();
                ptai.HandlersToProcess ^=
                    OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.TermGroups;

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

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

                Console.WriteLine("Applyed Provisioning Template \"{0}\" to site.",
                                  job.ProvisioningTemplateUrl);
            }
        }
예제 #33
0
        private string[] ProvisionSPOElements(string directoryName, string fileName, ClientContext context, Web provisioningWeb, ILogger logger)
        {
            logger.LogMessage(Constants.ProvisionElementsAttempt, LogType.Info);
            string[]  files       = new string[0];
            ArrayList directories = new ArrayList();
            ArrayList foundfiles  = new ArrayList();

            directories.Add(directoryName);
            DirectoryInfo baseDir = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);

            string[]      csProjFiles             = System.IO.Directory.GetFiles(baseDir.Parent.Parent.FullName, "*.csproj");
            List <string> includedProjectElements = ReadProjectStructure(csProjFiles.FirstOrDefault(), baseDir.Parent.Parent.FullName);

            while (directories.Count > 0)
            {
                string n = (string)directories[0];

                try
                {
                    if (!System.IO.Directory.Exists(n))
                    {
                        logger.LogMessage(string.Format(Constants.DirectoryNotFound, n), LogType.ErrorAndAbort);
                    }

                    string[] foundfiles1 = System.IO.Directory.GetFiles(n, fileName, SearchOption.TopDirectoryOnly);
                    if (foundfiles1 != null)
                    {
                        XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(String.Format(@"{0}\..\..\", AppDomain.CurrentDomain.BaseDirectory), "");
                        foreach (string templateFile in foundfiles1)
                        {
                            if (!includedProjectElements.Contains(templateFile.ToLowerInvariant()))
                            {
                                continue;
                            }

                            //UpdateTermStoreId(templateFile, logger);
                            //UpdatePnPFileRef(templateFile, logger);
                            DirectoryInfo dirInfo = new DirectoryInfo(string.Format(@"{0}\..\..\", templateFile));
                            logger.LogMessage(string.Format(Constants.ProcessingElement, templateFile), LogType.Info);
                            string siteTitle = dirInfo.FullName.Substring(0, dirInfo.FullName.LastIndexOf('\\'));
                            siteTitle = siteTitle.Substring(siteTitle.LastIndexOf('\\') + 1);

                            if (context.Web.Title != siteTitle)
                            {
                                context.Load(context.Web.Webs);
                                context.ExecuteQuery();
                                foreach (Web webNode in context.Web.Webs)
                                {
                                    if (webNode.Title == siteTitle)
                                    {
                                        provisioningWeb = webNode;
                                        break;
                                    }
                                }
                            }

                            //Apply provision
                            var    template         = provider.GetTemplate(templateFile);
                            string connectionString = ConfigData.RootSiteMappingFolder.ToLowerInvariant();
                            if (!ConfigData.RootSiteMappingFolder.ToLowerInvariant().EndsWith("\\"))
                            {
                                connectionString += "\\";
                            }
                            string container = templateFile.ToLowerInvariant().Replace(connectionString, string.Empty).Replace("template.xml", string.Empty);
                            template.Connector = new FileSystemConnector(connectionString, container);

                            try
                            {
                                ProvisioningTemplateApplyingInformation ptai = new ProvisioningTemplateApplyingInformation();

                                provisioningWeb.ApplyProvisioningTemplate(template);
                                logger.LogMessage(string.Format(Constants.ProvisionSuccess, dirInfo.Name, provisioningWeb.Title), LogType.Success);
                            }
                            catch (Exception ex)
                            {
                                logger.LogMessage(string.Format(Constants.UnknownError, ex.Message), LogType.ErrorAndContinue);
                            }
                        }

                        foundfiles.AddRange(foundfiles1);
                    }
                }
                catch (Exception ex)
                {
                    logger.LogMessage(string.Format(Constants.UnknownError, ex.Message), LogType.ErrorAndContinue);
                }

                try
                {
                    string[] subdirectories = System.IO.Directory.GetDirectories(n);
                    if (subdirectories != null)
                    {
                        string subsitesFolder = RemoveEmptySpaces(n.ToLowerInvariant());
                        if (subsitesFolder.EndsWith("subsites"))
                        {
                            //C:\something\MnS\Subsites\across\
                            DirectoryInfo dirInfo         = new DirectoryInfo(string.Format(@"{0}\..\", n));
                            string        parentSiteTitle = dirInfo.FullName.Substring(0, dirInfo.FullName.LastIndexOf('\\'));
                            parentSiteTitle = parentSiteTitle.Substring(parentSiteTitle.LastIndexOf('\\') + 1);
                            WebCollection subsites = context.Web.Webs;
                            context.Load(subsites);
                            context.ExecuteQuery();
                            foreach (string subsiteDir in subdirectories)
                            {
                                foreach (string item in includedProjectElements)
                                {
                                    if (item.StartsWith(subsiteDir.ToLowerInvariant()))
                                    {
                                        CreateSubsite(context, parentSiteTitle, subsiteDir.Replace(n, string.Empty).Substring(1), subsites, logger);
                                        break;
                                    }
                                }
                            }
                        }

                        directories.AddRange(subdirectories);
                    }
                }
                catch (Exception ex)
                {
                    logger.LogMessage(string.Format(Constants.UnknownError, ex.Message), LogType.ErrorAndContinue);
                }

                directories.RemoveAt(0);
            }

            return((string[])foundfiles.ToArray(typeof(string)));
        }
        public static void ApplyBrandingOnWeb(Web targetWeb, BrandingSettings brandingSettings, ProvisioningTemplate template)
        {
            targetWeb.EnsureProperties(w => w.MasterUrl, w => w.Url);

            // Configure proper settings for the provisioning engine
            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);
            };

            // Include only required handlers
            ptai.HandlersToProcess = Core.Framework.Provisioning.Model.Handlers.ComposedLook |
                Core.Framework.Provisioning.Model.Handlers.Files |
                Core.Framework.Provisioning.Model.Handlers.WebSettings;

            // Check if we really need to apply/update the branding
            var siteBrandingUpdatedOn = targetWeb.GetPropertyBagValueString(
                PnPPartnerPackConstants.PropertyBag_Branding_AppliedOn, null);

            // If the branding updated on date and time are missing
            // or older than the branding update date and time
            if (String.IsNullOrEmpty(siteBrandingUpdatedOn) ||
                DateTime.Parse(siteBrandingUpdatedOn) < brandingSettings.UpdatedOn.Value.ToUniversalTime())
            {
                Console.WriteLine($"Appling branding to site: {targetWeb.Url}");

                // Confirm the master page URL
                template.WebSettings.MasterPageUrl = targetWeb.MasterUrl;

                // Apply the template
                targetWeb.ApplyProvisioningTemplate(template, ptai);

                // Apply a custom JSLink, if any
                if (!String.IsNullOrEmpty(brandingSettings.UICustomActionsUrl))
                {
                    targetWeb.AddJsLink(
                        PnPPartnerPackConstants.BRANDING_SCRIPT_LINK_KEY,
                        brandingSettings.UICustomActionsUrl);
                }

                // Store Property Bag to set the last date and time when we applied the branding
                targetWeb.SetPropertyBagValue(
                    PnPPartnerPackConstants.PropertyBag_Branding_AppliedOn,
                    DateTime.Now.ToUniversalTime().ToString());

                Console.WriteLine($"Applied branding to site: {targetWeb.Url}");
            }

            // Apply branding (recursively) on all the subwebs of the current web
            targetWeb.EnsureProperty(w => w.Webs);

            foreach (var subweb in targetWeb.Webs)
            {
                ApplyBrandingOnWeb(subweb, brandingSettings, template);
            }
        }
예제 #35
0
        public static void ApplyBrandingOnWeb(Web targetWeb, BrandingSettings brandingSettings, ProvisioningTemplate template)
        {
            targetWeb.EnsureProperties(w => w.MasterUrl, w => w.Url);

            // Configure proper settings for the provisioning engine
            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);
            };

            // Include only required handlers
            ptai.HandlersToProcess = Core.Framework.Provisioning.Model.Handlers.ComposedLook |
                                     Core.Framework.Provisioning.Model.Handlers.Files |
                                     Core.Framework.Provisioning.Model.Handlers.WebSettings;

            // Check if we really need to apply/update the branding
            var siteBrandingUpdatedOn = targetWeb.GetPropertyBagValueString(
                PnPPartnerPackConstants.PropertyBag_Branding_AppliedOn, null);

            // If the branding updated on date and time are missing
            // or older than the branding update date and time
            if (String.IsNullOrEmpty(siteBrandingUpdatedOn) ||
                DateTime.Parse(siteBrandingUpdatedOn) < brandingSettings.UpdatedOn.Value.ToUniversalTime())
            {
                Console.WriteLine($"Appling branding to site: {targetWeb.Url}");

                // Confirm the master page URL
                template.WebSettings.MasterPageUrl = targetWeb.MasterUrl;

                // Apply the template
                targetWeb.ApplyProvisioningTemplate(template, ptai);

                // Apply a custom JSLink, if any
                if (!String.IsNullOrEmpty(brandingSettings.UICustomActionsUrl))
                {
                    targetWeb.AddJsLink(
                        PnPPartnerPackConstants.BRANDING_SCRIPT_LINK_KEY,
                        brandingSettings.UICustomActionsUrl);
                }

                // Store Property Bag to set the last date and time when we applied the branding
                targetWeb.SetPropertyBagValue(
                    PnPPartnerPackConstants.PropertyBag_Branding_AppliedOn,
                    DateTime.Now.ToUniversalTime().ToString());

                Console.WriteLine($"Applied branding to site: {targetWeb.Url}");
            }

            // Apply branding (recursively) on all the subwebs of the current web
            targetWeb.EnsureProperty(w => w.Webs);

            foreach (var subweb in targetWeb.Webs)
            {
                ApplyBrandingOnWeb(subweb, brandingSettings, template);
            }
        }