public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation) { using (var scope = new PnPMonitoredScope(this.Name)) { // Check if this is not a noscript site as we're not allowed to write to the web property bag is that one bool isNoScriptSite = web.IsNoScriptSite(); 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); } if (SkipFile(isNoScriptSite, file.Src, folderName)) { // add log message scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_Files_SkipFileUpload, file.Src, folderName); continue; } 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); using (var stream = GetFileStream(template, file)) { targetFile = UploadFile(template, file, folder, stream); } } 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(template, file, folder, stream); } 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); } } } switch (file.Level) { case Model.FileLevel.Published: { targetFile.PublishFileToLevel(Microsoft.SharePoint.Client.FileLevel.Published); break; } case Model.FileLevel.Draft: { targetFile.PublishFileToLevel(Microsoft.SharePoint.Client.FileLevel.Draft); break; } default: { if (checkedOut) { targetFile.CheckIn("", CheckinType.MajorCheckIn); web.Context.ExecuteQueryRetry(); } break; } } // 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); }
private static void CommentUDCXFileNode(UdcxReportInput udcxFileInput, List <UdcxReportOutput> _WriteUDCList) { if (udcxFileInput == null) { return; } string siteUrl = udcxFileInput.SiteUrl; string webUrl = udcxFileInput.WebUrl; string dirName = udcxFileInput.DirName; string leafName = udcxFileInput.LeafName; string authentication = udcxFileInput.Authentication; UdcxReportOutput udcxOutput = new UdcxReportOutput(); udcxOutput.SiteUrl = siteUrl; udcxOutput.WebUrl = webUrl; udcxOutput.DirName = dirName; udcxOutput.LeafName = leafName; udcxOutput.Authentication = authentication; if (dirName.EndsWith("/")) { dirName = dirName.TrimEnd(new char[] { '/' }); } if (leafName.StartsWith("/")) { leafName = leafName.TrimStart(new char[] { '/' }); } string serverRelativeFolderPath = "/" + dirName; string serverRelativeFilePath = "/" + dirName + '/' + leafName; try { Logger.LogInfoMessage(String.Format("Processing UCDX File [{0}/{1}] of Web [{2}] ...", dirName, leafName, webUrl), true); // IMPORTANT: Open the webUrl, not the siteUrl, so Folder.Files.Add() can properly process files of child webs using (ClientContext userContext = Helper.CreateClientContextBasedOnAuthMode(Program.UseAppModel, Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, webUrl)) { Web web = userContext.Web; userContext.Load(web); userContext.ExecuteQuery(); XNamespace xns = "http://schemas.microsoft.com/office/infopath/2006/udc"; XDocument doc = null; Logger.LogInfoMessage(String.Format("Getting contents of UCDX File [{0}] from Web [{1}] ...", serverRelativeFilePath, webUrl), false); // Approach to read File contents depends on Auth Model chosen if (Program.UseAppModel == true) { string originalFileContents = SafeGetFileAsString(web, serverRelativeFilePath); if (String.IsNullOrEmpty(originalFileContents)) { Logger.LogErrorMessage(String.Format("Could not get contents of UCDX File"), false); udcxOutput.Status = Constants.ErrorStatus + ": could not get file contents."; _WriteUDCList.Add(udcxOutput); return; } doc = XDocument.Load(new StringReader(originalFileContents)); } else { FileInformation info = Microsoft.SharePoint.Client.File.OpenBinaryDirect(userContext, serverRelativeFilePath); doc = XDocument.Load(XmlReader.Create(info.Stream)); } Logger.LogInfoMessage(String.Format("Got contents of UCDX File"), false); XElement authElem = doc.Root.Element(xns + "ConnectionInfo").Element(xns + "Authentication"); if (authElem != null) { string authData = authElem.ToString(); authData = authData.Replace("<udc:Authentication xmlns:udc=\"" + xns + "\">", "<udc:Authentication>"); authElem.ReplaceWith(new XComment(authData)); string saveUdcxContent = doc.Declaration.ToString() + doc.ToString(); using (MemoryStream contentStream = new MemoryStream()) { StreamWriter writer = new StreamWriter(contentStream); writer.Write(saveUdcxContent); writer.Flush(); contentStream.Position = 0; Logger.LogInfoMessage(String.Format("Saving contents of UCDX File [{0}] to Web [{1}] ...", serverRelativeFilePath, webUrl), false); // Approach to save File contents depends on Auth Model chosen if (Program.UseAppModel == true) { Folder targetFolder = null; // grab the parent folder in preparation for the file upload... Logger.LogInfoMessage(String.Format("Getting folder [{0}] of Web [{1}] ...", serverRelativeFolderPath, webUrl), false); try { targetFolder = web.GetFolderByServerRelativeUrl(serverRelativeFolderPath); userContext.Load(targetFolder); userContext.ExecuteQuery(); Logger.LogInfoMessage(String.Format("Got folder"), false); } catch (Exception ex) { Logger.LogErrorMessage(String.Format("CommentUDCXFileNode() failed for UDCX File [{0}/{1}] of Web [{2}]: Reason={3}; Error={4}", dirName, leafName, webUrl, "Upload Folder was not Found.", "[" + ex.Message + "] | [" + ex.HResult + "] | [" + ex.Source + "] | [" + ex.StackTrace + "] | [" + ex.TargetSite + "]"), false); udcxOutput.Status = Constants.ErrorStatus + ": Upload Folder was not Found."; _WriteUDCList.Add(udcxOutput); return; } // check-out the file (if needed) in preparation for the file upload... try { Logger.LogInfoMessage(String.Format("Checking out file [{0}] ...", leafName), false); web.CheckOutFile(serverRelativeFilePath); Logger.LogInfoMessage(String.Format("Checked out file"), false); } catch (Exception ex) { Logger.LogErrorMessage(String.Format("CommentUDCXFileNode() failed for UDCX File [{0}/{1}] of Web [{2}]: Reason={3}; Error={4}", dirName, leafName, webUrl, "File Checkout failed.", "[" + ex.Message + "] | [" + ex.HResult + "] | [" + ex.Source + "] | [" + ex.StackTrace + "] | [" + ex.TargetSite + "]"), false); udcxOutput.Status = Constants.ErrorStatus + ": File Checkout failed."; _WriteUDCList.Add(udcxOutput); return; } // upload the modified file... Microsoft.SharePoint.Client.File targetFile = null; Logger.LogInfoMessage(String.Format("Uploading file [{0}] ...", leafName), false); try { targetFile = targetFolder.UploadFile(leafName, contentStream, true); Logger.LogInfoMessage(String.Format("Uploaded file"), false); } catch (Exception ex) { Logger.LogErrorMessage(String.Format("CommentUDCXFileNode() failed for UDCX File [{0}/{1}] of Web [{2}]: Reason={3}; Error={4}", dirName, leafName, webUrl, "File Upload failed.", "[" + ex.Message + "] | [" + ex.HResult + "] | [" + ex.Source + "] | [" + ex.StackTrace + "] | [" + ex.TargetSite + "]"), false); udcxOutput.Status = Constants.ErrorStatus + ": File Upload failed."; _WriteUDCList.Add(udcxOutput); return; } // publish the modified file (executes check-in, publish, and approval as needed)... try { Logger.LogInfoMessage(String.Format("Publishing file [{0}] ...", leafName), false); targetFile.PublishFileToLevel(FileLevel.Published); Logger.LogInfoMessage(String.Format("Published file"), false); } catch (Exception ex) { Logger.LogErrorMessage(String.Format("CommentUDCXFileNode() failed for UDCX File [{0}/{1}] of Web [{2}]: Reason={3}; Error={4}", dirName, leafName, webUrl, "File Publish failed.", "[" + ex.Message + "] | [" + ex.HResult + "] | [" + ex.Source + "] | [" + ex.StackTrace + "] | [" + ex.TargetSite + "]"), false); udcxOutput.Status = Constants.ErrorStatus + ": File Publish failed."; _WriteUDCList.Add(udcxOutput); return; } } else { Microsoft.SharePoint.Client.File.SaveBinaryDirect(userContext, serverRelativeFilePath, contentStream, true); } Logger.LogInfoMessage(String.Format("Saved contents of UCDX File [{0}] to Web [{1}]", serverRelativeFilePath, webUrl), false); udcxOutput.Status = Constants.SuccessStatus; Logger.LogSuccessMessage(String.Format("Updated UCDX File [{0}/{1}] of Web [{2}]", dirName, leafName, webUrl), false); } } else { udcxOutput.Status = Constants.NoAuthNodeFound; Logger.LogWarningMessage(String.Format("Skipped UCDX File [{0}/{1}] of Web [{2}]: Reason={3}", dirName, leafName, webUrl, Constants.NoAuthNodeFound), false); } } } catch (Exception ex) { Logger.LogErrorMessage(String.Format("CommentUDCXFileNode() failed for UDCX File [{0}/{1}] of Web [{2}]: Error={3}", dirName, leafName, webUrl, ex.Message), false); udcxOutput.Status = Constants.ErrorStatus; udcxOutput.ErrorDetails = ex.Message; } _WriteUDCList.Add(udcxOutput); }