public void GetTemplateFromWebTest()
        {
            ProvisioningTemplate template = ProvisioningHelper.GetTemplateFromWeb(web);

            if (template != null)
            {
                var provider = new XMLFileSystemTemplateProvider(string.Format(@"{0}\..\..\", AppDomain.CurrentDomain.BaseDirectory), "");

                provider.SaveAs(template, "Branding.Search.Template.xml");
            }

            Assert.IsNotNull(template);
        }
Example #2
0
        public void GetTemplateForCurrentSiteTest()
        {
            using (ClientContext cc = TestCommon.CreateClientContext())
            {
                using (ClientContext ctx = cc.Clone("https://bertonline.sharepoint.com/sites/temp2/s1"))
                {

                    ProvisioningTemplate p = ctx.Web.GetProvisioningTemplate();

                    Assert.IsNotNull(p);

                    // Save to file system
                    XMLFileSystemTemplateProvider xmlProv = new XMLFileSystemTemplateProvider("c:\\temp", "");
                    xmlProv.SaveAs(p, "test.xml");

                    // Verify that the saved XML is still valid
                    var p2 = xmlProv.GetTemplate("test.xml");
                }
            }
        }
Example #3
0
        public void DumpBaseTemplate_STS0()
        {
            using (ClientContext ctx = TestCommon.CreateClientContext())
            {
                using(ClientContext cc = ctx.Clone("https://bertonline.sharepoint.com/sites/templateSTS0"))
                {
                    // Specify null as base template since we do want "everything" in this case
                    ProvisioningTemplateCreationInformation creationInfo = new ProvisioningTemplateCreationInformation(cc.Web);
                    creationInfo.BaseTemplate = null;

                    ProvisioningTemplate p = cc.Web.GetProvisioningTemplate(creationInfo);
                    p.ID = "STS0template";

                    // Cleanup before saving
                    p.Security.AdditionalAdministrators.Clear();

                    XMLFileSystemTemplateProvider provider = new XMLFileSystemTemplateProvider(".", "");
                    provider.SaveAs(p, "STS0Template.xml");
                }
            }
        }
Example #4
0
        private static ProvisioningTemplate GetProvisioningTemplate(ConsoleColor defaultForeground, string webUrl, string userName, SecureString pwd)
        {
            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;

                ProvisioningTemplateCreationInformation ptci
                        = new ProvisioningTemplateCreationInformation(ctx.Web);

                // Create FileSystemConnector, so that we can store composed files temporarely somewhere 
                ptci.FileConnector = new FileSystemConnector(@"c:\temp\pnpprovisioningdemo", "");
                ptci.PersistComposedLookFiles = true;
                ptci.ProgressDelegate = delegate (String message, Int32 progress, Int32 total)
                {
                    // Only to output progress for console UI
                    Console.WriteLine("{0:00}/{1:00} - {2}", progress, total, message);
                };

                // Execute actual extraction of the tepmplate
                ProvisioningTemplate template = ctx.Web.GetProvisioningTemplate(ptci);

                // We can also serialize this template for future usage if we want, not really needed
                XMLTemplateProvider provider =
                        new XMLFileSystemTemplateProvider(@"c:\temp\pnpprovisioningdemo", "");
                provider.SaveAs(template, "PnPProvisioningDemo.xml");

                return template;
            }
        }
        protected override void ProcessRecord()
        {
            // Determine the output file name and path
            string outFileName = System.IO.Path.GetFileName(Out);
            string outPath = new System.IO.FileInfo(Out).DirectoryName;

            // Determine if it is an .XML or a .PNP file
            var extension = "";
            if (outFileName != null)
            {
                if (outFileName.IndexOf(".", StringComparison.Ordinal) > -1)
                {
                    extension = outFileName.Substring(outFileName.LastIndexOf(".", StringComparison.Ordinal)).ToLower();
                }
                else
                {
                    extension = ".pnp";
                }
            }

            var fileSystemConnector = new FileSystemConnector(outPath, "");

            ITemplateFormatter formatter = XMLPnPSchemaFormatter.LatestFormatter;

            if (extension == ".pnp")
            {
                XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(
                      Out, fileSystemConnector);
                var templateFileName = outFileName.Substring(0, outFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";

                provider.SaveAs(InputInstance, templateFileName, formatter, TemplateProviderExtensions);
            }
            else
            {
                XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(outPath, "");
                provider.SaveAs(InputInstance, Out, formatter, TemplateProviderExtensions);
            }
        }
Example #6
0
        static void Main(string[] args)
        {
            bool interactiveLogin = true;
            string templateSiteUrl = "https://bertonline.sharepoint.com/sites/130049";
            string targetSiteUrl = "https://bertonline.sharepoint.com/sites/pr1";
            // Office 365: [email protected]
            // OnPrem: DOMAIN\Username
            string loginId = "*****@*****.**";

            // Get pwd from environment variable, so that we do to need to show that.
            string pwd = "";
            if (interactiveLogin)
            {
                pwd = GetInput("Password", true);
            }
            else
            {
                pwd = Environment.GetEnvironmentVariable("MSOPWD", EnvironmentVariableTarget.User);
            }

            if (string.IsNullOrEmpty(pwd))
            {
                Console.WriteLine("MSOPWD user environment variable empty or no password was specified, cannot continue. Press any key to abort.");
                Console.ReadKey();
                return;
            }

            // Template 
            ProvisioningTemplate template;

            // Get access to source site
            using (var ctx = new ClientContext(templateSiteUrl))
            {
                //Provide count and pwd for connecting to the source
                ctx.Credentials = GetCredentials(targetSiteUrl, loginId, pwd);

                // Get template from existing site
                template = ctx.Web.GetProvisioningTemplate();
            }

            // Save template using XML provider
            XMLFileSystemTemplateProvider provider = new XMLFileSystemTemplateProvider(@"c:\temp\pnpprovisioningdemo", "");
            string templateName = "template.xml";
            provider.SaveAs(template, templateName);

            // Load the saved model again
            ProvisioningTemplate p2 = provider.GetTemplate(templateName);

            // Get the available, valid templates
            var templates = provider.GetTemplates();
            foreach (var template1 in templates)
            {
                Console.WriteLine("Found template with ID {0}", template1.Id);
            }

            // Get access to target site and apply template
            using (var ctx = new ClientContext(targetSiteUrl))
            {
                //Provide count and pwd for connecting to the source               
                ctx.Credentials = GetCredentials(targetSiteUrl, loginId, pwd);

                // Apply template to existing site
                ctx.Web.ApplyProvisioningTemplate(template);
            }
        }
        private void DumpTemplate(ClientContext ctx, string template, string subSiteTemplate = "", string saveAsTemplate = "")
        {

            Uri devSiteUrl = new Uri(ConfigurationManager.AppSettings["SPODevSiteUrl"]);
            string baseUrl = String.Format("{0}://{1}", devSiteUrl.Scheme, devSiteUrl.DnsSafeHost);

            string siteUrl = "";
            if (subSiteTemplate.Length > 0)
            {
                siteUrl = string.Format("{1}/sites/template{0}/template{2}", template.Replace("#", ""), baseUrl, subSiteTemplate.Replace("#", ""));
#if !CLIENTSDKV15
                var siteCollectionUrl = string.Format("{1}/sites/template{0}", template.Replace("#", ""), baseUrl);
                CreateSiteCollection(template, siteCollectionUrl);
                using (var sitecolCtx = ctx.Clone(siteCollectionUrl))
                {
                    sitecolCtx.Web.Webs.Add(new WebCreationInformation()
                    {
                        Title = string.Format("template{0}", subSiteTemplate),
                        Language = 1033,
                        Url = string.Format("template{0}", subSiteTemplate.Replace("#", "")),
                        UseSamePermissionsAsParentSite = true
                    });
                    sitecolCtx.ExecuteQueryRetry();
                }
#endif
            }
            else
            {
                siteUrl = string.Format("{1}/sites/template{0}", template.Replace("#", ""), baseUrl);
#if !CLIENTSDKV15
                CreateSiteCollection(template, siteUrl);
#endif
            }

            using (ClientContext cc = ctx.Clone(siteUrl))
            {
                // Specify null as base template since we do want "everything" in this case
                ProvisioningTemplateCreationInformation creationInfo = new ProvisioningTemplateCreationInformation(cc.Web);
                creationInfo.BaseTemplate = null;

                // Override the save name. Case is online site collection provisioned using blankinternetcontainer#0 which returns
                // blankinternet#0 as web template using CSOM/SSOM API
                if (saveAsTemplate.Length > 0)
                {
                    template = saveAsTemplate;
                }

                ProvisioningTemplate p = cc.Web.GetProvisioningTemplate(creationInfo);
                if (subSiteTemplate.Length > 0)
                {
                    p.Id = String.Format("{0}template", subSiteTemplate.Replace("#", ""));
                }
                else
                {
                    p.Id = String.Format("{0}template", template.Replace("#", ""));
                }

                // Cleanup before saving
                p.Security.AdditionalAdministrators.Clear();


                XMLFileSystemTemplateProvider provider = new XMLFileSystemTemplateProvider(".", "");
                if (subSiteTemplate.Length > 0)
                {
                    provider.SaveAs(p, String.Format("{0}Template.xml", subSiteTemplate.Replace("#", "")));
                }
                else
                {
                    provider.SaveAs(p, String.Format("{0}Template.xml", template.Replace("#", "")));
                }

#if !CLIENTSDKV15
                using (var tenantCtx = TestCommon.CreateTenantClientContext())
                {
                    Tenant tenant = new Tenant(tenantCtx);
                    Console.WriteLine("Deleting new site {0}", string.Format("{1}/sites/template{0}", template.Replace("#", ""), baseUrl));
                    tenant.DeleteSiteCollection(siteUrl, false);
                }
#endif
            }
        }
        protected override void ProcessRecord()
        {
            // Determine the output file name and path
            string outFileName = System.IO.Path.GetFileName(Out);

            if (!Path.IsPathRooted(Out))
            {
                Out = Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Out);
            }

            bool proceed = false;

            if (System.IO.File.Exists(Out))
            {
                if (Force || ShouldContinue(string.Format(Properties.Resources.File0ExistsOverwrite, Out),
                    Properties.Resources.Confirm))
                {
                    proceed = true;
                }
            }
            else
            {
                proceed = true;
            }

            string outPath = new System.IO.FileInfo(Out).DirectoryName;

            // Determine if it is an .XML or a .PNP file
            var extension = "";
            if (proceed && outFileName != null)
            {
                if (outFileName.IndexOf(".", StringComparison.Ordinal) > -1)
                {
                    extension = outFileName.Substring(outFileName.LastIndexOf(".", StringComparison.Ordinal)).ToLower();
                }
                else
                {
                    extension = ".pnp";
                }
            }

            var fileSystemConnector = new FileSystemConnector(outPath, "");

            ITemplateFormatter formatter = XMLPnPSchemaFormatter.LatestFormatter;

            if (extension == ".pnp")
            {
                XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(
                      Out, fileSystemConnector);
                var templateFileName = outFileName.Substring(0, outFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";

                provider.SaveAs(InputInstance, templateFileName, formatter, TemplateProviderExtensions);
            }
            else
            {
                XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(outPath, "");
                provider.SaveAs(InputInstance, Out, formatter, TemplateProviderExtensions);
            }
        }
        private void ExtractTemplate(XMLPnPSchemaVersion schema, string path, string packageName)
        {
            SelectedWeb.EnsureProperty(w => w.Url);

            var creationInformation = new ProvisioningTemplateCreationInformation(SelectedWeb);

            if (MyInvocation.BoundParameters.ContainsKey("Handlers"))
            {
                creationInformation.HandlersToProcess = Handlers;
            }
            if (MyInvocation.BoundParameters.ContainsKey("ExcludeHandlers"))
            {
                foreach (var handler in (Handlers[])Enum.GetValues(typeof(Handlers)))
                {
                    if (!ExcludeHandlers.Has(handler) && handler != Handlers.All)
                    {
                        Handlers = Handlers | handler;
                    }
                }
                creationInformation.HandlersToProcess = Handlers;
            }

            var extension = "";
            if (packageName != null)
            {
                if (packageName.IndexOf(".", StringComparison.Ordinal) > -1)
                {
                    extension = packageName.Substring(packageName.LastIndexOf(".", StringComparison.Ordinal)).ToLower();
                }
                else
                {
                    packageName += ".pnp";
                    extension = ".pnp";
                }
            }

            var fileSystemConnector = new FileSystemConnector(path, "");
            if (extension == ".pnp")
            {
                creationInformation.FileConnector = new OpenXMLConnector(packageName, fileSystemConnector);
            }
            else
            {
                creationInformation.FileConnector = fileSystemConnector;
            }
#pragma warning disable 618
            creationInformation.PersistBrandingFiles = PersistBrandingFiles || PersistComposedLookFiles;
#pragma warning restore 618
            creationInformation.PersistPublishingFiles = PersistPublishingFiles;
            creationInformation.IncludeNativePublishingFiles = IncludeNativePublishingFiles;
            creationInformation.IncludeSiteGroups = IncludeSiteGroups;
            creationInformation.IncludeTermGroupsSecurity = IncludeTermGroupsSecurity;
#if !SP2013
            creationInformation.PersistMultiLanguageResources = PersistMultiLanguageResources;
            if (!string.IsNullOrEmpty(ResourceFilePrefix))
            {
                creationInformation.ResourceFilePrefix = ResourceFilePrefix;
            }
            else
            {
                if (Out != null)
                {
                    FileInfo fileInfo = new FileInfo(Out);
                    var prefix = fileInfo.Name.Substring(0, fileInfo.Name.LastIndexOf(".", StringComparison.Ordinal));
                    creationInformation.ResourceFilePrefix = prefix;
                }

            }
#endif
            if (ExtensibilityHandlers != null)
            {
                creationInformation.ExtensibilityHandlers = ExtensibilityHandlers.ToList();
            }

#pragma warning disable CS0618 // Type or member is obsolete
            if (NoBaseTemplate)
            {
                creationInformation.BaseTemplate = null;
            }
            else
            {
                creationInformation.BaseTemplate = SelectedWeb.GetBaseTemplate();
            }
#pragma warning restore CS0618 // Type or member is obsolete

            creationInformation.ProgressDelegate = (message, step, total) =>
            {
                WriteProgress(new ProgressRecord(0, $"Extracting Template from {SelectedWeb.Url}", message) { PercentComplete = (100 / total) * step });
            };
            creationInformation.MessagesDelegate = (message, type) =>
            {
                if (type == ProvisioningMessageType.Warning)
                {
                    WriteWarning(message);
                }
            };

            if (IncludeAllTermGroups)
            {
                creationInformation.IncludeAllTermGroups = true;
            }
            else
            {
                if (IncludeSiteCollectionTermGroup)
                {
                    creationInformation.IncludeSiteCollectionTermGroup = true;
                }
            }

            var template = SelectedWeb.GetProvisioningTemplate(creationInformation);

            // Set metadata for template, if any
            SetTemplateMetadata(template, TemplateDisplayName, TemplateImagePreviewUrl, TemplateProperties);

            if (!OutputInstance)
            {
                ITemplateFormatter formatter = null;
                switch (schema)
                {
                    case XMLPnPSchemaVersion.LATEST:
                        {
                            formatter = XMLPnPSchemaFormatter.LatestFormatter;
                            break;
                        }
                    case XMLPnPSchemaVersion.V201503:
                        {
#pragma warning disable CS0618 // Type or member is obsolete
                            formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_03);
#pragma warning restore CS0618 // Type or member is obsolete
                            break;
                        }
                    case XMLPnPSchemaVersion.V201505:
                        {
#pragma warning disable CS0618 // Type or member is obsolete
                            formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_05);
#pragma warning restore CS0618 // Type or member is obsolete
                            break;
                        }
                    case XMLPnPSchemaVersion.V201508:
                        {
#pragma warning disable CS0618 // Type or member is obsolete
                            formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_08);
#pragma warning restore CS0618 // Type or member is obsolete
                            break;
                        }
                    case XMLPnPSchemaVersion.V201512:
                        {
                            formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_12);
                            break;
                        }
                }

                if (extension == ".pnp")
                {
                    XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(

                          creationInformation.FileConnector as OpenXMLConnector);
                    var templateFileName = packageName.Substring(0, packageName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";

                    provider.SaveAs(template, templateFileName, formatter, TemplateProviderExtensions);
                }
                else
                {
                    if (Out != null)
                    {
                        XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(path, "");
                        provider.SaveAs(template, Path.Combine(path, packageName), formatter, TemplateProviderExtensions);
                    }
                    else
                    {
                        var outputStream = formatter.ToFormattedTemplate(template);
                        var reader = new StreamReader(outputStream);

                        WriteObject(reader.ReadToEnd());
                    }
                }
            }
            else
            {
                WriteObject(template);
            }
        }
        private void ProcessBaseTemplates(List<BaseTemplate> templates, bool deleteSites, bool createSites)
        {
            using (var tenantCtx = TestCommon.CreateTenantClientContext())
            {
                tenantCtx.RequestTimeout = Timeout.Infinite;
                Tenant tenant = new Tenant(tenantCtx);

#if !CLIENTSDKV15
                if (deleteSites)
                {
                    // First delete all template site collections when in SPO
                    foreach (var template in templates)
                    {
                        string siteUrl = GetSiteUrl(template);

                        try
                        {
                            Console.WriteLine("Deleting existing site {0}", siteUrl);
                            tenant.DeleteSiteCollection(siteUrl, false);
                        }
                        catch{ }
                    }
                }

                if (createSites)
                {
                    // Create site collections
                    foreach (var template in templates)
                    {
                        string siteUrl = GetSiteUrl(template);

                        Console.WriteLine("Creating site {0}", siteUrl);

                        bool siteExists = false;
                        if (template.SubSiteTemplate.Length > 0)
                        {
                            siteExists = tenant.SiteExists(siteUrl);
                        }

                        if (!siteExists)
                        {
                            tenant.CreateSiteCollection(new Entities.SiteEntity()
                            {
                                Lcid = 1033,
                                TimeZoneId = 4,
                                SiteOwnerLogin = (TestCommon.Credentials as SharePointOnlineCredentials).UserName,
                                Title = "Template Site",
                                Template = template.Template,
                                Url = siteUrl,
                            }, false, true);
                        }

                        if (template.SubSiteTemplate.Length > 0)
                        {
                            using (ClientContext ctx = TestCommon.CreateClientContext())
                            {
                                using (var sitecolCtx = ctx.Clone(siteUrl))
                                {
                                    sitecolCtx.Web.Webs.Add(new WebCreationInformation()
                                    {
                                        Title = string.Format("template{0}", template.SubSiteTemplate),
                                        Language = 1033,
                                        Url = string.Format("template{0}", template.SubSiteTemplate.Replace("#", "")),
                                        UseSamePermissionsAsParentSite = true
                                    });
                                    sitecolCtx.ExecuteQueryRetry();
                                }
                            }
                        }
                    }
                }
#endif
            }

            // Export the base templates
            using (ClientContext ctx = TestCommon.CreateClientContext())
            {
                foreach (var template in templates)
                {
                    string siteUrl = GetSiteUrl(template, false);

                    // Export the base templates
                    using (ClientContext cc = ctx.Clone(siteUrl))
                    {
                        // Specify null as base template since we do want "everything" in this case
                        ProvisioningTemplateCreationInformation creationInfo = new ProvisioningTemplateCreationInformation(cc.Web);
                        creationInfo.BaseTemplate = null;
                        // Do not extract the home page for the base templates
                        creationInfo.HandlersToProcess ^= Handlers.PageContents;

                        // Override the save name. Case is online site collection provisioned using blankinternetcontainer#0 which returns
                        // blankinternet#0 as web template using CSOM/SSOM API
                        string templateName = template.Template;
                        if (template.SaveAsTemplate.Length > 0)
                        {
                            templateName = template.SaveAsTemplate;
                        }

                        ProvisioningTemplate p = cc.Web.GetProvisioningTemplate(creationInfo);
                        if (template.SubSiteTemplate.Length > 0)
                        {
                            p.Id = String.Format("{0}template", template.SubSiteTemplate.Replace("#", ""));
                        }
                        else
                        {
                            p.Id = String.Format("{0}template", templateName.Replace("#", ""));
                        }

                        // Cleanup before saving
                        p.Security.AdditionalAdministrators.Clear();

                        // persist the template using the XML provider
                        XMLFileSystemTemplateProvider provider = new XMLFileSystemTemplateProvider(".", "");
                        if (template.SubSiteTemplate.Length > 0)
                        {
                            provider.SaveAs(p, String.Format("{0}Template.xml", template.SubSiteTemplate.Replace("#", "")));
                        }
                        else
                        {
                            provider.SaveAs(p, String.Format("{0}Template.xml", templateName.Replace("#", "")));
                        }
                    }
                }
            }
        }
        public void XMLFileSystemConvertTemplatesFromV201503toV201505()
        {
            XMLTemplateProvider provider =
                new XMLFileSystemTemplateProvider(
                    String.Format(@"{0}\..\..\Resources",
                    AppDomain.CurrentDomain.BaseDirectory),
                    "Templates");

            var _source1 = provider.GetTemplate("ProvisioningTemplate-2015-03-Sample-01.xml");
            provider.SaveAs(_source1, "ProvisioningTemplate-2015-05-Sample-01.xml", XMLPnPSchemaFormatter.LatestFormatter);

            var _source2 = provider.GetTemplate("ProvisioningTemplate-2015-03-Sample-02.xml");
            provider.SaveAs(_source2, "ProvisioningTemplate-2015-05-Sample-02.xml", XMLPnPSchemaFormatter.LatestFormatter);
        }
        static void Main(string[] args)
        {
            bool interactiveLogin = true;
            string templateSiteUrl = "https://mbakirov367.sharepoint.com/sites/demo4";
            string targetSiteUrl = "https://mbakirov367.sharepoint.com/sites/demo4f";
            string loginId = "*****@*****.**";

            // Get pwd from environment variable, so that we do to need to show that.
            string pwd = "";
            if (interactiveLogin)
            {
                pwd = GetInput("Password", true);
            }
            else
            {
                pwd = System.Environment.GetEnvironmentVariable("MSOPWD", EnvironmentVariableTarget.User);
            }

            if (string.IsNullOrEmpty(pwd))
            {
                System.Console.WriteLine("MSOPWD user environment variable empty or no password was specified, cannot continue. Press any key to abort.");
                System.Console.ReadKey();
                return;
            }

            // Template
            ProvisioningTemplate template;

            // Get access to source site
            using (var ctx = new ClientContext(templateSiteUrl))
            {
                //Provide count and pwd for connecting to the source
                var passWord = new SecureString();
                foreach (char c in pwd.ToCharArray()) passWord.AppendChar(c);
                ctx.Credentials = new SharePointOnlineCredentials(loginId, passWord);

                // Get template from existing site
                template = ctx.Web.GetProvisioningTemplate();
            }

            // Save template using XML provider
            XMLFileSystemTemplateProvider provider = new XMLFileSystemTemplateProvider(@"c:\temp\pnpprovisioningdemo", "");
            string templateName = "template.xml";
            provider.SaveAs(template, templateName);

            // Load the saved model again
            ProvisioningTemplate p2 = provider.GetTemplate(templateName);

            // Get the available, valid templates
            var templates = provider.GetTemplates();
            foreach(var template1 in templates)
            {
                Console.WriteLine("Found template with ID {0}", template1.Id);
            }

            // Get access to target site and apply template
            using (var ctx = new ClientContext(targetSiteUrl))
            {
                //Provide count and pwd for connecting to the source
                var passWord = new SecureString();
                foreach (char c in pwd.ToCharArray()) passWord.AppendChar(c);
                ctx.Credentials = new SharePointOnlineCredentials(loginId, passWord);

                // Apply template to existing site
                ctx.Web.ApplyProvisioningTemplate(template);
            }
        }
        private void DumpTemplate(ClientContext ctx, string template, string subSiteTemplate = "", string saveAsTemplate = "")
        {
            Uri devSiteUrl = new Uri(ConfigurationManager.AppSettings["SPODevSiteUrl"]);
            string baseUrl = String.Format("{0}://{1}", devSiteUrl.Scheme, devSiteUrl.DnsSafeHost);

            string siteUrl = "";
            if (subSiteTemplate.Length > 0)
            {
                siteUrl = (String.Format("{1}/sites/template{0}/template{2}", template, baseUrl, subSiteTemplate));
            }
            else
            {
                siteUrl = (String.Format("{1}/sites/template{0}", template, baseUrl));
            }

            using (ClientContext cc = ctx.Clone(siteUrl))
            {
                // Specify null as base template since we do want "everything" in this case
                ProvisioningTemplateCreationInformation creationInfo = new ProvisioningTemplateCreationInformation(cc.Web);
                creationInfo.BaseTemplate = null;

                // Override the save name. Case is online site collection provisioned using blankinternetcontainer#0 which returns
                // blankinternet#0 as web template using CSOM/SSOM API
                if (saveAsTemplate.Length > 0)
                {
                    template = saveAsTemplate;
                }

                ProvisioningTemplate p = cc.Web.GetProvisioningTemplate(creationInfo);
                if (subSiteTemplate.Length > 0)
                {
                    p.Id = String.Format("{0}template", subSiteTemplate);
                }
                else
                {
                    p.Id = String.Format("{0}template", template);
                }

                // Cleanup before saving
                p.Security.AdditionalAdministrators.Clear();

                XMLFileSystemTemplateProvider provider = new XMLFileSystemTemplateProvider(".", "");
                if (subSiteTemplate.Length > 0)
                {
                    provider.SaveAs(p, String.Format("{0}Template.xml", subSiteTemplate));
                }
                else
                {
                    provider.SaveAs(p, String.Format("{0}Template.xml", template));
                }
            }
        }
        public void XMLEncryptionTest()
        {
            X509Certificate2 certificate = RetrieveCertificateFromStore(new X509Store(StoreLocation.CurrentUser), "PnPTestCertificate");

            if (certificate == null)
            {
                Assert.Inconclusive("Missing certificate with SN=PnPTestCertificate in CurrentUser Certificate Store, so can't test");
            }

            XMLEncryptionTemplateProviderExtension extension =
                new XMLEncryptionTemplateProviderExtension();

            extension.Initialize(certificate);

            ITemplateProviderExtension[] extensions = new ITemplateProviderExtension[] { extension };

            XMLTemplateProvider provider =
                new XMLFileSystemTemplateProvider(
                    String.Format(@"{0}\..\..\Resources",
                    AppDomain.CurrentDomain.BaseDirectory),
                    "Templates");

            var template = provider.GetTemplate("ProvisioningTemplate-2016-05-Sample-01.xml");
            template.DisplayName = "Ciphered template";

            provider.SaveAs(template, "ProvisioningTemplate-2016-05-Ciphered.xml", extensions);
            var result = provider.GetTemplate("ProvisioningTemplate-2016-05-Ciphered.xml", extensions);

            provider.Delete("ProvisioningTemplate-2016-05-Ciphered.xml");

            Assert.IsTrue(result.DisplayName == "Ciphered template");
        }