Example #1
0
        private static File UploadFile(Microsoft.SharePoint.Client.Folder folder, Stream stream, string fileName, bool overwrite)
        {
            if (folder == null)
            {
                throw new ArgumentNullException(nameof(folder));
            }
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            File targetFile = null;

            try
            {
                targetFile = folder.UploadFile(fileName, stream, overwrite);
            }
            catch (ServerException ex)
            {
                if (ex.ServerErrorCode != -2130575306) //Error code: -2130575306 = The file is already checked out.
                {
                    //The file name might contain encoded characters that prevent upload. Decode it and try again.
                    fileName = WebUtility.UrlDecode(fileName);
                    try
                    {
                        targetFile = folder.UploadFile(fileName, stream, overwrite);
                    }
                    catch (Exception)
                    {
                        //unable to Upload file, just ignore
                    }
                }
            }
            return(targetFile);
        }
Example #2
0
        private static File UploadFile(ProvisioningTemplate template, Model.File file, Microsoft.SharePoint.Client.Folder folder, Stream stream)
        {
            File targetFile = null;
            var  fileName   = !String.IsNullOrEmpty(file.TargetFileName) ? file.TargetFileName : template.Connector.GetFilenamePart(file.Src);

            try
            {
                targetFile = folder.UploadFile(fileName, stream, file.Overwrite);
            }
            catch (ServerException ex)
            {
                if (ex.ServerErrorCode != -2130575306) //Error code: -2130575306 = The file is already checked out.
                {
                    //The file name might contain encoded characters that prevent upload. Decode it and try again.
                    fileName = WebUtility.UrlDecode(fileName);
                    try
                    {
                        targetFile = folder.UploadFile(fileName, stream, file.Overwrite);
                    }
                    catch (Exception)
                    {
                        //unable to Upload file, just ignore
                    }
                }
            }
            return(targetFile);
        }
Example #3
0
        private static File UploadFile(ProvisioningTemplate template, Model.File file, Microsoft.SharePoint.Client.Folder folder, Stream stream)
        {
            File targetFile = null;
            var  fileName   = template.Connector.GetFilenamePart(file.Src);

            try
            {
                targetFile = folder.UploadFile(fileName, stream, file.Overwrite);
            }
            catch (Exception)
            {
                //The file name might contain encoded characters that prevent upload. Decode it and try again.
                fileName   = WebUtility.UrlDecode(fileName);
                targetFile = folder.UploadFile(fileName, stream, file.Overwrite);
            }
            return(targetFile);
        }
Example #4
0
        private static File UploadFile(Web web, ProvisioningTemplate template, Model.File file, Microsoft.SharePoint.Client.Folder folder)
        {
            File targetFile = null;
            var  fileName   = template.Connector.GetFilenamePart(file.Src);

            try
            {
                // Replace tokens in aspx files before uploading
                if (fileName.EndsWith(".aspx") || fileName.EndsWith(".master") || fileName.EndsWith(".js"))
                {
                    string fileString = template.Connector.GetFile(file.Src);
                    fileString = Tokenize(web, fileString);

                    using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(fileString)))
                    {
                        targetFile = folder.UploadFile(fileName, stream, file.Overwrite);
                    }
                }
                else
                {
                    using (var stream = template.Connector.GetFileStream(file.Src))
                    {
                        targetFile = folder.UploadFile(fileName, stream, file.Overwrite);
                    }
                }
            }
            catch (Exception)
            {
                //The file name might contain encoded characters that prevent upload. Decode it and try again.
                fileName = WebUtility.UrlDecode(fileName);
                using (var stream = template.Connector.GetFileStream(file.Src))
                {
                    targetFile = folder.UploadFile(fileName, stream, file.Overwrite);
                }
            }
            return(targetFile);
        }
        //public ProvisioningTemplateInformation[] GetGlobalProvisioningTemplates(TargetScope scope)
        //{
        //    return (GetLocalProvisioningTemplates(PnPPartnerPackSettings.InfrastructureSiteUrl, scope));
        //}

        //public ProvisioningTemplateInformation[] GetLocalProvisioningTemplates(string siteUrl, TargetScope scope)
        //{
        //    List<ProvisioningTemplateInformation> result =
        //        new List<ProvisioningTemplateInformation>();

        //    // Retrieve the Root Site Collection URL
        //    siteUrl = PnPPartnerPackUtilities.GetSiteCollectionRootUrl(siteUrl);

        //    // Connect to the Infrastructural Site Collection
        //    using (var context = PnPPartnerPackContextProvider.GetAppOnlyClientContext(siteUrl))
        //    {
        //        // Get a reference to the target library
        //        Web web = context.Web;

        //        try
        //        {
        //            List list = web.Lists.GetByTitle(PnPPartnerPackConstants.PnPProvisioningTemplates);

        //            // Get only Provisioning Templates documents with the specified Scope
        //            CamlQuery query = new CamlQuery();
        //            query.ViewXml =
        //                @"<View>
        //                <Query>
        //                    <Where>
        //                        <And>
        //                            <Eq>
        //                                <FieldRef Name='PnPProvisioningTemplateScope' />
        //                                <Value Type='Choice'>" + scope.ToString() + @"</Value>
        //                            </Eq>
        //                            <Eq>
        //                                <FieldRef Name='ContentType' />
        //                                <Value Type=''Computed''>PnPProvisioningTemplate</Value>
        //                            </Eq>
        //                        </And>
        //                    </Where>
        //                </Query>
        //                <ViewFields>
        //                    <FieldRef Name='Title' />
        //                    <FieldRef Name='PnPProvisioningTemplateScope' />
        //                    <FieldRef Name='PnPProvisioningTemplateSourceUrl' />
        //                </ViewFields>
        //            </View>";

        //            ListItemCollection items = list.GetItems(query);
        //            context.Load(items,
        //                includes => includes.Include(i => i.File,
        //                i => i[PnPPartnerPackConstants.PnPProvisioningTemplateScope],
        //                i => i[PnPPartnerPackConstants.PnPProvisioningTemplateSourceUrl]));
        //            context.ExecuteQueryRetry();

        //            web.EnsureProperty(w => w.Url);

        //            foreach (ListItem item in items)
        //            {
        //                // Configure the XML file system provider
        //                XMLTemplateProvider provider =
        //                    new XMLSharePointTemplateProvider(context, web.Url,
        //                        PnPPartnerPackConstants.PnPProvisioningTemplates);

        //                item.File.EnsureProperties(f => f.Name, f => f.ServerRelativeUrl);

        //                ProvisioningTemplate template = provider.GetTemplate(item.File.Name);

        //                result.Add(new ProvisioningTemplateInformation
        //                {
        //                    Scope = (TargetScope)Enum.Parse(typeof(TargetScope), (String)item[PnPPartnerPackConstants.PnPProvisioningTemplateScope], true),
        //                    TemplateSourceUrl = item[PnPPartnerPackConstants.PnPProvisioningTemplateSourceUrl] != null ? ((FieldUrlValue)item[PnPPartnerPackConstants.PnPProvisioningTemplateSourceUrl]).Url : null,
        //                    TemplateFileUri = String.Format("{0}/{1}/{2}", web.Url, PnPPartnerPackConstants.PnPProvisioningTemplates, item.File.Name),
        //                    TemplateImageUrl = template.ImagePreviewUrl,
        //                    DisplayName = template.DisplayName,
        //                    Description = template.Description,
        //                });
        //            }
        //        }
        //        catch (ServerException)
        //        {
        //            // In case of any issue, ignore the local templates
        //        }
        //    }

        //    return (result.ToArray());
        //}

        ///// <summary>
        ///// Saves a Provisioning Template into the target Global repository
        ///// </summary>
        ///// <param name="job">The Provisioning Template to save</param>
        //public void SaveGlobalProvisioningTemplate(GetProvisioningTemplateJob job)
        //{
        //    // Connect to the Infrastructural Site Collection
        //    using (var context = PnPPartnerPackContextProvider.GetAppOnlyClientContext(job.SourceSiteUrl))
        //    {
        //        SaveProvisioningTemplateInternal(context, job, true);
        //    }
        //}

        ///// <summary>
        ///// Saves a Provisioning Template into the target Local repository
        ///// </summary>
        ///// <param name="siteUrl">The local Site Collection to save to</param>
        ///// <param name="template">The Provisioning Template to save</param>
        //public void SaveLocalProvisioningTemplate(string siteUrl, GetProvisioningTemplateJob job)
        //{
        //    // Connect to the Local Site Collection
        //    using (var context = PnPPartnerPackContextProvider.GetAppOnlyClientContext(siteUrl))
        //    {
        //        PnPPartnerPackUtilities.EnablePartnerPackInfrastructureOnSite(siteUrl);
        //        SaveProvisioningTemplateInternal(context, job, false);
        //    }
        //}

        private void SaveProvisioningTemplateInternal(ClientContext context, GetProvisioningTemplateJob job, Boolean globalRepository = true)
        {
            // Get a reference to the target web site
            Web web = context.Web;

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

            // Prepare the support variables
            ClientContext repositoryContext = null;
            Web           repositoryWeb     = null;

            // Define whether we need to use the global infrastructural repository or the local one
            if (globalRepository)
            {
                // Get a reference to the global repository web site and context
                repositoryContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext(PnPPartnerPackSettings.InfrastructureSiteUrl);
            }
            else
            {
                // Get a reference to the local repository web site and context
                repositoryContext = web.Context.GetSiteCollectionContext();
            }

            using (repositoryContext)
            {
                repositoryWeb = repositoryContext.Site.RootWeb;
                repositoryContext.Load(repositoryWeb, w => w.Url);
                repositoryContext.ExecuteQueryRetry();

                // Configure the XML SharePoint provider for the Infrastructural Site Collection
                XMLTemplateProvider provider =
                    new XMLSharePointTemplateProvider(repositoryContext, repositoryWeb.Url,
                                                      PnPPartnerPackConstants.PnPProvisioningTemplates);

                ProvisioningTemplateCreationInformation ptci =
                    new ProvisioningTemplateCreationInformation(web);
                ptci.FileConnector                  = provider.Connector;
                ptci.IncludeAllTermGroups           = job.IncludeAllTermGroups;
                ptci.IncludeSearchConfiguration     = job.IncludeSearchConfiguration;
                ptci.IncludeSiteCollectionTermGroup = job.IncludeSiteCollectionTermGroup;
                ptci.IncludeSiteGroups              = job.IncludeSiteGroups;
                ptci.PersistBrandingFiles           = job.PersistComposedLookFiles;

                // We do intentionally remove taxonomies, which are not supported
                // in the AppOnly Authorization model
                // For further details, see the PnP Partner Pack documentation
                ptci.HandlersToProcess ^= Handlers.TermGroups;

                // Extract the current template
                ProvisioningTemplate templateToSave = web.GetProvisioningTemplate(ptci);

                templateToSave.Description = job.Description;
                templateToSave.DisplayName = job.Title;

                // Save template image preview in folder
                Microsoft.SharePoint.Client.Folder templatesFolder = repositoryWeb.GetFolderByServerRelativeUrl(PnPPartnerPackConstants.PnPProvisioningTemplates);
                repositoryContext.Load(templatesFolder, f => f.ServerRelativeUrl, f => f.Name);
                repositoryContext.ExecuteQueryRetry();

                // Fix the job filename if it is missing the .xml extension
                if (!job.FileName.ToLower().EndsWith(".xml"))
                {
                    job.FileName += ".xml";
                }

                // If there is a preview image
                if (job.TemplateImageFile != null)
                {
                    String previewImageFileName = job.FileName.ToLower().Replace(".xml", "_preview.png");
                    templatesFolder.UploadFile(previewImageFileName,
                                               job.TemplateImageFile.ToStream(), true);

                    // And store URL in the XML file
                    templateToSave.ImagePreviewUrl = String.Format("{0}/{1}/{2}",
                                                                   repositoryWeb.Url, templatesFolder.Name, previewImageFileName);
                }

                // And save it on the file system
                provider.SaveAs(templateToSave, job.FileName);

                Microsoft.SharePoint.Client.File templateFile = templatesFolder.GetFile(job.FileName);
                ListItem item = templateFile.ListItemAllFields;

                item[PnPPartnerPackConstants.ContentTypeIdField]               = PnPPartnerPackConstants.PnPProvisioningTemplateContentTypeId;
                item[PnPPartnerPackConstants.TitleField]                       = job.Title;
                item[PnPPartnerPackConstants.PnPProvisioningTemplateScope]     = job.Scope.ToString();
                item[PnPPartnerPackConstants.PnPProvisioningTemplateSourceUrl] = job.SourceSiteUrl;

                item.Update();

                repositoryContext.ExecuteQueryRetry();
            }
        }