Пример #1
0
        public static string UploadDeviceChannelMappingFile(Web web, string serverRelativeMappingFilePath, string fileContents, string description)
        {
            try
            {
                Logger.LogInfoMessage(String.Format("Uploading Device Channel Mapping File: {0} ...", serverRelativeMappingFilePath), false);

                // grab a reference to the MP Gallery where the device channel mapping file resides.
                List   mpGallery     = web.GetCatalog((int)ListTemplateType.MasterPageCatalog);
                Folder mpGalleryRoot = mpGallery.RootFolder;
                web.Context.Load(mpGallery);
                web.Context.Load(mpGalleryRoot);
                web.Context.ExecuteQuery();

                // get the file and check-out if necessary
                File dcmFile = GetFileFromWeb(web, serverRelativeMappingFilePath);
                if (dcmFile != null)
                {
                    web.CheckOutFile(serverRelativeMappingFilePath);
                }

                // prepare the file contents for upload
                Byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(fileContents);

                // Use CSOM to upload the file
                FileCreationInformation newFile = new FileCreationInformation();
                newFile.Content   = fileBytes;
                newFile.Overwrite = true;
                newFile.Url       = serverRelativeMappingFilePath;

                File uploadFile = mpGalleryRoot.Files.Add(newFile);
                web.Context.Load(uploadFile);
                web.Context.ExecuteQuery();

                // check-in and approve as necessary
                if (mpGallery.ForceCheckout || mpGallery.EnableVersioning)
                {
                    web.CheckInFile(uploadFile.ServerRelativeUrl, CheckinType.MajorCheckIn, description);
                    if (mpGallery.EnableModeration)
                    {
                        web.ApproveFile(uploadFile.ServerRelativeUrl, description);
                    }
                }

                Logger.LogSuccessMessage(String.Format("Uploaded Device Channel Mapping File: {0}", uploadFile.ServerRelativeUrl), false);
                return(uploadFile.ServerRelativeUrl);
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("UploadDeviceChannelMappingFile() failed for {0}: Error={1}", serverRelativeMappingFilePath, ex.Message), false);
                return(String.Empty);
            }
        }
Пример #2
0
        private void UploadAndPublishSingleFile(ClientContext context, Web web, string configRootFolder, ShContentFolder contentFolder, string uploadTargetFolder, Folder rootFolder, List <ShFileProperties> filePropertiesCollection, string filePath)
        {
            var pathToFileFromRootFolder = filePath.Replace(configRootFolder.TrimEnd(new[] { '\\' }) + "\\", "");
            var fileName = Path.GetFileName(pathToFileFromRootFolder);

            pathToFileFromRootFolder = pathToFileFromRootFolder.Replace("\\", "/");

            if (!string.IsNullOrEmpty(contentFolder.PropertiesFile) && contentFolder.PropertiesFile == fileName)
            {
                Log.DebugFormat("Skipping file upload of {0} since it's used as a configuration file", fileName);
                return;
            }

            ShFileProperties fileProperties = null;

            if (filePropertiesCollection != null)
            {
                fileProperties = filePropertiesCollection.SingleOrDefault(f => f.Path == pathToFileFromRootFolder);
            }

            Log.DebugFormat("Uploading file {0} to {1}", fileName, contentFolder.ListUrl);
            var fileUrl = GetFileUrl(uploadTargetFolder, pathToFileFromRootFolder, fileProperties);

            web.CheckOutFile(fileUrl);

            if (fileProperties == null || fileProperties.ReplaceContent)
            {
                var newFile = GetFileCreationInformation(context, fileUrl, filePath, pathToFileFromRootFolder, fileProperties);

                File uploadFile = rootFolder.Files.Add(newFile);

                context.Load(uploadFile);
                context.ExecuteQuery();
            }
            var reloadedFile = web.GetFileByServerRelativeUrl(fileUrl);

            context.Load(reloadedFile);
            context.ExecuteQuery();

            ApplyFileProperties(context, fileProperties, reloadedFile);

            try
            {
                reloadedFile.PublishFileToLevel(FileLevel.Published);
            }
            catch
            {
                Log.Warn("Couldn't publish file " + fileUrl);
            }
        }
Пример #3
0
        public void UploadFilesInFolder(ClientContext context, Web web, ShContentFolder contentFolder)
        {
            Log.Info("Uploading files from contentfolder " + contentFolder.FolderName);

            string uploadTargetFolder;
            Folder rootFolder;

            web.Lists.EnsureSiteAssetsLibrary();
            context.Load(web.Lists);
            context.ExecuteQuery();

            if (!string.IsNullOrEmpty(contentFolder.ListUrl))
            {
                context.Load(web, w => w.ServerRelativeUrl);
                context.ExecuteQuery();

                var rootFolderServerRelativeUrl = Url.Combine(web.ServerRelativeUrl, contentFolder.ListUrl);
                rootFolder = web.GetFolderByServerRelativeUrl(rootFolderServerRelativeUrl);
                context.Load(rootFolder);
                context.ExecuteQuery();

                uploadTargetFolder = Url.Combine(rootFolderServerRelativeUrl, contentFolder.FolderUrl);                
            } else if (!string.IsNullOrEmpty(contentFolder.ListName)) 
            {
                var assetLibrary = web.Lists.GetByTitle(contentFolder.ListName);
                context.Load(assetLibrary, l => l.Title, l => l.RootFolder);
                context.ExecuteQuery();
                rootFolder = assetLibrary.RootFolder;
                uploadTargetFolder = Url.Combine(assetLibrary.RootFolder.ServerRelativeUrl, contentFolder.FolderUrl);
            }
            else
            {
                Log.ErrorFormat("You need to specify either ListName or ListUrl for the Content Folder {0}", contentFolder.FolderName);
                return;
            }

            var configRootFolder = Path.Combine(_contentDirectoryPath, contentFolder.FolderName);

            if (!web.DoesFolderExists(uploadTargetFolder))
            {
                web.Folders.Add(uploadTargetFolder);
            }
            context.ExecuteQuery();

            foreach (string folder in Directory.GetDirectories(configRootFolder, "*", SearchOption.AllDirectories))
            {
                var folderName = Url.Combine(uploadTargetFolder, folder.Replace(configRootFolder, "").Replace("\\", "/"));
                if (!web.DoesFolderExists(folderName))
                {
                    web.Folders.Add(folderName);
                }
            }
            context.ExecuteQuery();

            List<ShFileProperties> filePropertiesCollection = null;
            if (!string.IsNullOrEmpty(contentFolder.PropertiesFile))
            {
                var propertiesFilePath = Path.Combine(configRootFolder, contentFolder.PropertiesFile);
                var filePersistanceProvider = new FilePersistanceProvider<List<ShFileProperties>>(propertiesFilePath);
                filePropertiesCollection = filePersistanceProvider.Load();
            }

            context.Load(context.Site, site => site.ServerRelativeUrl);
            context.Load(context.Web, w => w.ServerRelativeUrl, w => w.Language);
            context.ExecuteQuery();

            String[] excludedFileExtensions = { };
            if (!string.IsNullOrEmpty(contentFolder.ExcludeExtensions))
            {
                excludedFileExtensions = contentFolder.ExcludeExtensions.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            }
            var files = Directory.GetFiles(configRootFolder, "*", SearchOption.AllDirectories)
                .Where(file => !excludedFileExtensions.Contains(Path.GetExtension(file).ToLower())).ToList();

            if (IncrementalUpload)
            {
                files = files.Where(f =>!LastUpload.ContainsKey(contentFolder.FolderName) || new FileInfo(f).LastWriteTimeUtc > LastUpload[contentFolder.FolderName]).ToList();
            }

            int filesUploaded = 0;
            foreach (string filePath in files)
            {
                var pathToFileFromRootFolder = filePath.Replace(configRootFolder.TrimEnd(new []{'\\'}) + "\\", "");
                var fileName = Path.GetFileName(pathToFileFromRootFolder);

                if (!string.IsNullOrEmpty(contentFolder.PropertiesFile) && contentFolder.PropertiesFile == fileName)
                {
                    Log.DebugFormat("Skipping file upload of {0} since it's used as a configuration file", fileName);
                    continue;
                }
                Log.DebugFormat("Uploading file {0} to {1}", fileName, contentFolder.ListUrl);
                var fileUrl = GetFileUrl(uploadTargetFolder, pathToFileFromRootFolder, filePropertiesCollection);
                web.CheckOutFile(fileUrl);

                var newFile = new FileCreationInformation
                {
                    Content = System.IO.File.ReadAllBytes(filePath),
                    Url = fileUrl,
                    Overwrite = true
                };
                File uploadFile = rootFolder.Files.Add(newFile);

                context.Load(uploadFile);
                context.Load(uploadFile.ListItemAllFields.ParentList, l => l.ForceCheckout, l => l.EnableMinorVersions, l => l.EnableModeration);
                context.ExecuteQuery();

                ApplyFileProperties(context, filePropertiesCollection, uploadFile);
                uploadFile.PublishFileToLevel(FileLevel.Published);
                context.ExecuteQuery();

                filesUploaded++;
            }

            if (filesUploaded == 0)
            {
                Log.Info("No files updated since last upload.");
            }
            else
            {
                Log.InfoFormat("{0} file(s) uploaded", filesUploaded);
            }

            if (LastUpload.ContainsKey(contentFolder.FolderName))
            {
                LastUpload[contentFolder.FolderName] = DateTime.UtcNow;
            }
            else
            {
                LastUpload.Add(contentFolder.FolderName, DateTime.UtcNow);
            }

        }
Пример #4
0
        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);
        }