Пример #1
0
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                var context = web.Context as ClientContext;

                web.EnsureProperties(w => w.ServerRelativeUrl, w => w.Url);

                // Build on the fly the list of additional files coming from the Directories
                var directoryFiles = new List <Model.File>();
                foreach (var directory in template.Directories)
                {
                    var metadataProperties = directory.GetMetadataProperties();
                    directoryFiles.AddRange(directory.GetDirectoryFiles(metadataProperties));
                }

                foreach (var file in template.Files.Union(directoryFiles))
                {
                    var folderName = parser.ParseString(file.Folder);

                    if (folderName.ToLower().StartsWith((web.ServerRelativeUrl.ToLower())))
                    {
                        folderName = folderName.Substring(web.ServerRelativeUrl.Length);
                    }

                    var folder = web.EnsureFolderPath(folderName);

                    File targetFile = null;

                    var checkedOut = false;

                    targetFile = folder.GetFile(template.Connector.GetFilenamePart(file.Src));

                    if (targetFile != null)
                    {
                        if (file.Overwrite)
                        {
                            scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Files_Uploading_and_overwriting_existing_file__0_, file.Src);
                            checkedOut = CheckOutIfNeeded(web, targetFile);

                            targetFile = UploadFile(web, template, file, folder);
                        }
                        else
                        {
                            checkedOut = CheckOutIfNeeded(web, targetFile);
                        }
                    }
                    else
                    {
                        using (var stream = GetFileStream(template, file))
                        {
                            scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Files_Uploading_file__0_, file.Src);
                            targetFile = UploadFile(web, template, file, folder);
                        }

                        checkedOut = CheckOutIfNeeded(web, targetFile);
                    }

                    if (targetFile != null)
                    {
                        if (file.Properties != null && file.Properties.Any())
                        {
                            Dictionary <string, string> transformedProperties = file.Properties.ToDictionary(property => property.Key, property => parser.ParseString(property.Value));
                            SetFileProperties(targetFile, transformedProperties, false);
                        }

                        if (file.WebParts != null && file.WebParts.Any())
                        {
                            targetFile.EnsureProperties(f => f.ServerRelativeUrl);

                            var existingWebParts = web.GetWebParts(targetFile.ServerRelativeUrl);
                            foreach (var webpart in file.WebParts)
                            {
                                // check if the webpart is already set on the page
                                if (existingWebParts.FirstOrDefault(w => w.WebPart.Title == webpart.Title) == null)
                                {
                                    scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Files_Adding_webpart___0___to_page, webpart.Title);
                                    var wpEntity = new WebPartEntity();
                                    wpEntity.WebPartTitle = webpart.Title;
                                    wpEntity.WebPartXml   = parser.ParseString(webpart.Contents).Trim(new[] { '\n', ' ' });
                                    wpEntity.WebPartZone  = webpart.Zone;
                                    wpEntity.WebPartIndex = (int)webpart.Order;
                                    web.AddWebPartToWebPartPage(targetFile.ServerRelativeUrl, wpEntity);
                                }
                            }
                        }

                        if (checkedOut)
                        {
                            if (file.Level != Model.FileLevel.Draft)
                            {
                                Microsoft.SharePoint.Client.FileLevel level = (Microsoft.SharePoint.Client.FileLevel)Enum.Parse(typeof(Microsoft.SharePoint.Client.FileLevel), file.Level.ToString());
                                targetFile.PublishFileToLevel(level);
                            }
                            else
                            {
                                targetFile.CheckIn("", CheckinType.MajorCheckIn);
                            }

                            web.Context.ExecuteQueryRetry();
                        }

                        // Don't set security when nothing is defined. This otherwise breaks on files set outside of a list
                        if (file.Security != null &&
                            (file.Security.ClearSubscopes == true || file.Security.CopyRoleAssignments == true || file.Security.RoleAssignments.Count > 0))
                        {
                            targetFile.ListItemAllFields.SetSecurity(parser, file.Security);
                        }
                    }
                }
            }
            return(parser);
        }
Пример #2
0
        private void GetPage(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo, string pageUrl)
        {
            try
            {
                var pageFullUrl = UrlUtility.Combine(web.ServerRelativeUrl, pageUrl);

                var file = web.GetFileByServerRelativeUrl(pageFullUrl);
                web.Context.Load(file, f => f.Name, f => f.CheckOutType, f => f.ListItemAllFields.ParentList.ForceCheckout, f => f.Level);
                web.Context.ExecuteQueryRetry();
                FileLevel fileLevel  = file.Level;
                var       checkedOut = CheckOutIfNeeded(web, file);
                try
                {
                    var listItem = file.EnsureProperty(f => f.ListItemAllFields);
                    if (listItem != null)
                    {
                        if (listItem.FieldValues.ContainsKey("WikiField"))
                        {
                            #region Wiki page

                            var fullUri = new Uri(UrlUtility.Combine(web.Url, web.RootFolder.WelcomePage));

                            var folderPath =
                                fullUri.Segments.Take(fullUri.Segments.Count() - 1)
                                .ToArray()
                                .Aggregate((i, x) => i + x)
                                .TrimEnd('/');
                            var fileName = fullUri.Segments[fullUri.Segments.Count() - 1];

                            var homeFile = web.GetFileByServerRelativeUrl(pageFullUrl);

                            LimitedWebPartManager limitedWPManager =
                                homeFile.GetLimitedWebPartManager(PersonalizationScope.Shared);

                            web.Context.Load(limitedWPManager);

                            var webParts = web.GetWebParts(pageFullUrl);

                            var page = new Page()
                            {
                                Layout    = WikiPageLayout.Custom,
                                Overwrite = true,
                                Url       = Tokenize(fullUri.PathAndQuery, web.Url),
                            };
                            var pageContents = listItem.FieldValues["WikiField"].ToString();

                            Regex regexClientIds = new Regex(@"id=\""div_(?<ControlId>(\w|\-)+)");
                            if (regexClientIds.IsMatch(pageContents))
                            {
                                foreach (Match webPartMatch in regexClientIds.Matches(pageContents))
                                {
                                    String serverSideControlId = webPartMatch.Groups["ControlId"].Value;

                                    try
                                    {
                                        String serverSideControlIdToSearchFor = String.Format("g_{0}",
                                                                                              serverSideControlId.Replace("-", "_"));

                                        WebPartDefinition webPart =
                                            limitedWPManager.WebParts.GetByControlId(serverSideControlIdToSearchFor);
                                        web.Context.Load(webPart,
                                                         wp => wp.Id,
                                                         wp => wp.WebPart.Title,
                                                         wp => wp.WebPart.ZoneIndex
                                                         );
                                        web.Context.ExecuteQueryRetry();

                                        var webPartxml = TokenizeWebPartXml(web,
                                                                            web.GetWebPartXml(webPart.Id, pageFullUrl));

                                        page.WebParts.Add(new OfficeDevPnP.Core.Framework.Provisioning.Model.WebPart()
                                        {
                                            Title    = webPart.WebPart.Title,
                                            Contents = webPartxml,
                                            Order    = (uint)webPart.WebPart.ZoneIndex,
                                            Row      = 1,
                                            // By default we will create a onecolumn layout, add the webpart to it, and later replace the wikifield on the page to position the webparts correctly.
                                            Column = 1
                                                     // By default we will create a onecolumn layout, add the webpart to it, and later replace the wikifield on the page to position the webparts correctly.
                                        });

                                        pageContents = Regex.Replace(pageContents, serverSideControlId,
                                                                     string.Format("{{webpartid:{0}}}", webPart.WebPart.Title),
                                                                     RegexOptions.IgnoreCase);
                                    }
                                    catch (ServerException)
                                    {
                                        Console.WriteLine(
                                            "Found a WebPart ID which is not available on the server-side. ID: {0}",
                                            serverSideControlId);
                                    }
                                }
                            }

                            page.Fields.Add("WikiField", pageContents);
                            template.Pages.Add(page);

                            // Set the homepage
                            if (template.WebSettings == null)
                            {
                                template.WebSettings = new WebSettings();
                            }
                            //template.WebSettings.WelcomePage = homepageUrl;

                            #endregion
                        }
                        else
                        {
                            if (web.Context.HasMinimalServerLibraryVersion(Constants.MINIMUMZONEIDREQUIREDSERVERVERSION))
                            {
                                // Not a wikipage
                                template = GetFileContents(web, template, pageFullUrl, creationInfo, pageUrl);
                            }
                            else
                            {
                                Console.WriteLine(
                                    string.Format(
                                        "Page content export requires a server version that is newer than the current server. Server version is {0}, minimal required is {1}",
                                        web.Context.ServerLibraryVersion, Constants.MINIMUMZONEIDREQUIREDSERVERVERSION),
                                    ProvisioningMessageType.Warning);
                                Console.WriteLine(
                                    "Page content export requires a server version that is newer than the current server. Server version is {0}, minimal required is {1}",
                                    web.Context.ServerLibraryVersion, Constants.MINIMUMZONEIDREQUIREDSERVERVERSION);
                            }
                        }
                    }
                }
                catch (ServerException ex)
                {
                    if (ex.ServerErrorCode != -2146232832)
                    {
                        throw;
                    }
                    else
                    {
                        if (web.Context.HasMinimalServerLibraryVersion(Constants.MINIMUMZONEIDREQUIREDSERVERVERSION))
                        {
                            // Page does not belong to a list, extract the file as is
                            template = GetFileContents(web, template, pageFullUrl, creationInfo, pageUrl);
                        }
                        else
                        {
                            Console.WriteLine(
                                string.Format(
                                    "Page content export requires a server version that is newer than the current server. Server version is {0}, minimal required is {1}",
                                    web.Context.ServerLibraryVersion, Constants.MINIMUMZONEIDREQUIREDSERVERVERSION),
                                ProvisioningMessageType.Warning);
                            Console.WriteLine(
                                "Page content export requires a server version that is newer than the current server. Server version is {0}, minimal required is {1}",
                                web.Context.ServerLibraryVersion, Constants.MINIMUMZONEIDREQUIREDSERVERVERSION);
                        }
                    }
                }
                switch (fileLevel)
                {
                case Microsoft.SharePoint.Client.FileLevel.Published:
                {
                    file.PublishFileToLevel(Microsoft.SharePoint.Client.FileLevel.Published);
                    break;
                }

                case Microsoft.SharePoint.Client.FileLevel.Draft:
                {
                    file.PublishFileToLevel(Microsoft.SharePoint.Client.FileLevel.Draft);
                    break;
                }

                default:
                {
                    if (checkedOut)
                    {
                        file.CheckIn("", CheckinType.MajorCheckIn);
                        web.Context.ExecuteQueryRetry();
                    }
                    break;
                }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }