예제 #1
0
        /// <summary>
        /// Will first try to find the file based on container/filename from the mapped file names.
        /// As a fallback it will try to find by container/filename in the pnp file structure, which was the original format.
        /// </summary>
        private PnPFileInfo GetFileFromInsidePackage(string fileName, string container)
        {
            string      mappedPath = Path.Combine(container, fileName).Replace('\\', '/');
            PnPFileInfo file       = null;

            if (pnpInfo.FilesMap != null)
            {
                file = (from item in pnpInfo.FilesMap.Map
                        where item.Value.Equals(mappedPath, StringComparison.InvariantCultureIgnoreCase)
                        select pnpInfo.Files.FirstOrDefault(f => f.InternalName == item.Key)).FirstOrDefault();
            }
            if (file != null)
            {
                return(file);
            }
            return(pnpInfo.Files.FirstOrDefault(f => f.OriginalName.Equals(fileName, StringComparison.InvariantCultureIgnoreCase) && f.Folder.Equals(container, StringComparison.InvariantCultureIgnoreCase)));
        }
예제 #2
0
        private byte[] CreatePnPPackageFile(string ctId)
        {
            PnPInfo info = new PnPInfo
            {
                Manifest = new PnPManifest()
                {
                    Type = PackageType.Full
                },
                Properties = new PnPProperties()
                {
                    Generator = PnP.Framework.Utilities.PnPCoreUtilities.PnPCoreVersionTag,
                    Author    = string.Empty,
                },
                Files = new List <PnPFileInfo>()
            };
            DirectoryInfo dirInfo          = new DirectoryInfo(Path.GetFullPath(Folder));
            string        templateFileName = Path.GetFileNameWithoutExtension(Out) + ".xml";
            var           xml          = CreateXmlAsStringFrom(ctId);
            PnPFileInfo   templateInfo = new PnPFileInfo
            {
                InternalName = templateFileName.AsInternalFilename(),
                OriginalName = templateFileName,
                Folder       = "",
                Content      = System.Text.Encoding.UTF8.GetBytes(xml)
            };

            info.Files.Add(templateInfo);

            foreach (var currentFile in dirInfo.GetFiles("*.*", SearchOption.AllDirectories))
            {
                var         folder   = GetFolderName(currentFile, dirInfo);
                PnPFileInfo fileInfo = new PnPFileInfo
                {
                    InternalName = currentFile.Name.AsInternalFilename(),
                    OriginalName = currentFile.Name,
                    Folder       = folder,
                    Content      = System.IO.File.ReadAllBytes(currentFile.FullName)
                };
                WriteVerbose("Adding file:" + currentFile.Name + " - " + folder);
                info.Files.Add(fileInfo);
            }
            byte[] pack = info.PackTemplate().ToArray();
            return(pack);
        }
        private byte[] CreatePnPPackageFile()
        {
            PnPInfo info = new PnPInfo
            {
                Manifest = new PnPManifest()
                {
                    Type = PackageType.Full
                },
                Properties = new PnPProperties()
                {
                    Generator = OfficeDevPnP.Core.Utilities.PnPCoreUtilities.PnPCoreVersionTag,
                    Author    = string.Empty,
                },
                Files = new List <PnPFileInfo>()
            };
            DirectoryInfo dirInfo             = new DirectoryInfo(Path.GetFullPath(Folder));
            string        templateFileName    = Path.GetFileNameWithoutExtension(Out) + ".xml";
            bool          templateFileMissing = dirInfo.GetFiles(templateFileName, SearchOption.TopDirectoryOnly).Length == 0;

            if (templateFileMissing)
            {
                throw new InvalidOperationException("You need an xml template file (" + templateFileName + ") with the same name as the .pnp outfile in order to pack a folder to a .pnp package file.");
            }

            info.Properties.TemplateFileName = templateFileName;

            foreach (var currentFile in dirInfo.GetFiles("*.*", SearchOption.AllDirectories))
            {
                var         folder   = GetFolderName(currentFile, dirInfo);
                PnPFileInfo fileInfo = new PnPFileInfo
                {
                    InternalName = currentFile.Name.AsInternalFilename(),
                    OriginalName = currentFile.Name,
                    Folder       = folder,
                    Content      = File.ReadAllBytes(currentFile.FullName)
                };
                WriteVerbose("Adding file:" + currentFile.Name + " - " + folder);
                info.Files.Add(fileInfo);
            }
            byte[] pack = info.PackTemplate().ToArray();
            return(pack);
        }
        public PnPFileInfo GetPnPTemplateFileFromSite(CreatePnPTemplateRequest request)
        {
            var pnpPackageInfo = new PnPFileInfo();

            try
            {
                using (var context = TokenHelper.GetClientContextWithAccessToken(request.SiteUrl, request.AccessToken))
                {
                    var web = context.Web;
                    context.Load(web, w => w.Title, w => w.ServerRelativeUrl, w => w.Url);
                    context.ExecuteQuery();

                    var siteUrl = new Uri(request.SiteUrl);

                    var pnpFileName = "";

                    if (string.IsNullOrEmpty(request.PnpPackageName))
                    {
                        pnpFileName = BuildPnPPackageName(siteUrl);
                    }
                    else
                    {
                        pnpFileName = request.PnpPackageName;
                        if (pnpFileName.ToLower().EndsWith(".pnp"))
                        {
                            pnpFileName = pnpFileName.Substring(0, pnpFileName.Length - 4);
                        }
                    }
                    var pnpTemplatePath = HostingEnvironment.MapPath($"~/{TemplateFolder}");

                    var ptci = new ProvisioningTemplateCreationInformation(context.Web);
                    var fileSystemConnector = new FileSystemConnector(pnpTemplatePath, "");

                    ptci.PersistBrandingFiles          = true;
                    ptci.PersistPublishingFiles        = true;
                    ptci.PersistMultiLanguageResources = true;
                    ptci.FileConnector = new OpenXMLConnector($"{pnpFileName}.pnp", fileSystemConnector);

                    ptci.ProgressDelegate = delegate(String message, Int32 progress, Int32 total)
                    {
                        Console.WriteLine(@"{0:00}/{1:00} - {2}", progress, total, message);
                    };
                    ProvisioningTemplate template = new ProvisioningTemplate();
                    try
                    {
                        template = web.GetProvisioningTemplate(ptci);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("PnP engine failed to extract template. Error: {0}", ex.Message);
                    }

                    try
                    {
                        PageProvisionManager pageProvisionManager = new PageProvisionManager();
                        var pagesTemplate = pageProvisionManager.Extract(context, ptci);
                        foreach (var theFile in pagesTemplate.Files)
                        {
                            var existingFile =
                                template.Files.FirstOrDefault(
                                    f => f.Src.Equals(theFile.Src, StringComparison.InvariantCultureIgnoreCase));
                            if (existingFile == null)
                            {
                                template.Files.Add(theFile);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Failed to extract Pages. Error: {0}", ex.Message);
                    }
                    if (web.IsSubSite())
                    {
                        try
                        {
                            var siteColumnsTemplate = new SiteColumnProvisionManager().Extract(web, ptci);
                            foreach (var col in siteColumnsTemplate.SiteFields)
                            {
                                if (!template.SiteFields.Contains(col))
                                {
                                    template.SiteFields.Add(col);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Failed to extract Site Columns. Error: {0}", ex.Message);
                        }
                        try
                        {
                            var siteCTTemplate = new ContentTypeProvisionManager().Extract(web, ptci);
                            foreach (var ct in siteCTTemplate.ContentTypes)
                            {
                                if (!template.ContentTypes.Contains(ct))
                                {
                                    template.ContentTypes.Add(ct);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Failed to extract Site Content Types. Error: {0}", ex.Message);
                        }
                    }

                    XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider((OpenXMLConnector)ptci.FileConnector);
                    provider.SaveAs(template, $"{pnpFileName}.xml");
                    string fileLocation = $"{pnpTemplatePath}\\{pnpFileName}.pnp";
                    var    file         = new FileInfo(fileLocation);

                    fileStorageManager.SaveFile($"{TemplateFolder}\\{pnpFileName}.pnp", System.IO.File.ReadAllBytes(fileLocation));

                    pnpPackageInfo = new PnPFileInfo()
                    {
                        Name = $"{pnpFileName}.pnp",
                        Size = file.Length / 1024.0m
                    };
                    if (file.Exists)
                    {
                        file.Delete();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(pnpPackageInfo);
        }