Exemplo n.º 1
0
        /// <summary>
        /// 复制文档
        /// </summary>
        /// <param name="siteUrl">指定站点地址</param>
        /// <param name="folderName1">指定文档库名称(复制源)</param>
        /// <param name="folderName2">指定文档库名称(复制目标)</param>
        /// <param name="fileName">指定文档名称</param>
        /// <returns>返回操作提示</returns>
        public string CopyFile(string folderName1, string folderName2, string fileName)
        {
            //操作结果提示
            string result = null;

            try
            {
                if (clientContext != null)
                {
                    //创建客户端对象模型
                    using (clientContext)
                    {
                        //设置默认凭据

                        //通过标题获取文档库
                        Microsoft.SharePoint.Client.List documentsList = clientContext.Web.Lists.GetByTitle(folderName1);
                        LoadMethod(documentsList);

                        LoadMethod(documentsList.RootFolder.Files);

                        Microsoft.SharePoint.Client.File file = null;
                        foreach (var item in documentsList.RootFolder.Files)
                        {
                            if (item.Name.Equals(fileName))
                            {
                                file = item;
                            }
                        }
                        //通过标题获取文档库
                        Microsoft.SharePoint.Client.List documentsList2 = clientContext.Web.Lists.GetByTitle(folderName2);
                        LoadMethod(documentsList2);
                        LoadMethod(documentsList2.RootFolder);
                        //获取文档库url
                        var d = documentsList2.RootFolder.ServerRelativeUrl;
                        //string a = d.Replace(documentsList.ParentWebUrl + "/", "");
                        file.CopyTo(d + "/" + fileName, true);
                        clientContext.ExecuteQuery();
                        result = "文档拷贝成功";
                    }
                }
            }
            catch (Exception ex)
            {
                result = "文档拷贝失败";
                MethodLb.CreateLog(this.GetType().FullName, "CopyFile", ex.ToString(), folderName1, folderName2, fileName);
            }
            finally
            {
            }
            return(result);
        }
Exemplo n.º 2
0
        public static void CopyFile(
            [ActivityTrigger] ApprovalStartInfo approvalStartInfo,
            ILogger log,
            ExecutionContext context)
        {
            using (var cc = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(ConfigurationManager.AppSettings["siteUrl"], ConfigurationManager.AppSettings["clientId"], ConfigurationManager.AppSettings["clientSecret"]))
            {
                List     docLib = cc.Web.Lists.GetByTitle("Drafts");
                ListItem item   = docLib.GetItemById(approvalStartInfo.itemId);
                Microsoft.SharePoint.Client.File file = item.File;

                cc.Load(file);
                cc.Load(item);

                cc.ExecuteQuery();
                string dest = ConfigurationManager.AppSettings["siteUrl"] + "Published/" + file.Name;
                file.CopyTo(dest, true);
                cc.ExecuteQuery();
            };
        }
Exemplo n.º 3
0
        protected override void ExecuteCmdlet()
        {
#pragma warning disable CS0618 // Type or member is obsolete
            SourceUrl = SourceUrl ?? ServerRelativeUrl;
#pragma warning restore CS0618 // Type or member is obsolete
            var webServerRelativeUrl = SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl);

            if (!SourceUrl.StartsWith("/"))
            {
                SourceUrl = UrlUtility.Combine(webServerRelativeUrl, SourceUrl);
            }
            if (!TargetUrl.StartsWith("/"))
            {
                TargetUrl = UrlUtility.Combine(webServerRelativeUrl, TargetUrl);
            }

            Uri currentContextUri = new Uri(ClientContext.Url);
            Uri sourceUri         = new Uri(currentContextUri, SourceUrl);
            Uri sourceWebUri      = Microsoft.SharePoint.Client.Web.WebUrlFromFolderUrlDirect(ClientContext, sourceUri);
            Uri targetUri         = new Uri(currentContextUri, TargetUrl);
            Uri targetWebUri      = Microsoft.SharePoint.Client.Web.WebUrlFromFolderUrlDirect(ClientContext, targetUri);

            _sourceContext = ClientContext;
            if (!currentContextUri.AbsoluteUri.Equals(sourceWebUri.AbsoluteUri, StringComparison.InvariantCultureIgnoreCase))
            {
                _sourceContext = ClientContext.Clone(sourceWebUri);
            }

            bool isFile      = true;
            bool srcIsFolder = false;

            File   file   = null;
            Folder folder = null;

            try
            {
#if ONPREMISES
                file = _sourceContext.Web.GetFileByServerRelativeUrl(SourceUrl);
#else
                file = _sourceContext.Web.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(SourceUrl));
#endif
                file.EnsureProperties(f => f.Name, f => f.Exists);
                isFile = file.Exists;
            }
            catch
            {
                isFile = false;
            }

            if (!isFile)
            {
#if ONPREMISES
                folder = _sourceContext.Web.GetFolderByServerRelativeUrl(SourceUrl);
#else
                folder = _sourceContext.Web.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(SourceUrl));
#endif

#if !SP2013
                folder.EnsureProperties(f => f.Name, f => f.Exists);
                srcIsFolder = folder.Exists;
#else
                folder.EnsureProperties(f => f.Name);

                try
                {
                    folder.EnsureProperties(f => f.ItemCount); //Using ItemCount as marker if this is a file or folder
                    srcIsFolder = true;
                }
                catch
                {
                    srcIsFolder = false;
                }
#endif
            }

            if (Force || ShouldContinue(string.Format(Resources.CopyFile0To1, SourceUrl, TargetUrl), Resources.Confirm))
            {
                var srcWeb = _sourceContext.Web;
                srcWeb.EnsureProperty(s => s.Url);

                _targetContext = ClientContext.Clone(targetWebUri.AbsoluteUri);
                var dstWeb = _targetContext.Web;
                dstWeb.EnsureProperties(s => s.Url, s => s.ServerRelativeUrl);
                if (srcWeb.Url == dstWeb.Url)
                {
                    try
                    {
                        var targetFile = UrlUtility.Combine(TargetUrl, file?.Name);
                        // If src/dst are on the same Web, then try using CopyTo - backwards compability
#if ONPREMISES
                        file?.CopyTo(targetFile, OverwriteIfAlreadyExists);
#else
                        file?.CopyToUsingPath(ResourcePath.FromDecodedUrl(targetFile), OverwriteIfAlreadyExists);
#endif
                        _sourceContext.ExecuteQueryRetry();
                        return;
                    }
                    catch
                    {
                        SkipSourceFolderName = true; // target folder exist
                        //swallow exception, in case target was a lib/folder which exists
                    }
                }

                //different site/site collection
                Folder targetFolder       = null;
                string fileOrFolderName   = null;
                bool   targetFolderExists = false;
                try
                {
#if ONPREMISES
                    targetFolder = _targetContext.Web.GetFolderByServerRelativeUrl(TargetUrl);
#else
                    targetFolder = _targetContext.Web.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(TargetUrl));
#endif
#if !SP2013
                    targetFolder.EnsureProperties(f => f.Name, f => f.Exists);
                    if (!targetFolder.Exists)
                    {
                        throw new Exception("TargetUrl is an existing file, not folder");
                    }
                    targetFolderExists = true;
#else
                    targetFolder.EnsureProperties(f => f.Name);
                    try
                    {
                        targetFolder.EnsureProperties(f => f.ItemCount); //Using ItemCount as marker if this is a file or folder
                        targetFolderExists = true;
                    }
                    catch
                    {
                        targetFolderExists = false;
                    }
                    if (!targetFolderExists)
                    {
                        throw new Exception("TargetUrl is an existing file, not folder");
                    }
#endif
                }
                catch (Exception)
                {
                    targetFolder = null;
                    Expression <Func <List, object> > expressionRelativeUrl = l => l.RootFolder.ServerRelativeUrl;
                    var query = _targetContext.Web.Lists.IncludeWithDefaultProperties(expressionRelativeUrl);
                    var lists = _targetContext.LoadQuery(query);
                    _targetContext.ExecuteQueryRetry();
                    lists = lists.OrderByDescending(l => l.RootFolder.ServerRelativeUrl); // order descending in case more lists start with the same
                    foreach (List targetList in lists)
                    {
                        if (!TargetUrl.StartsWith(targetList.RootFolder.ServerRelativeUrl, StringComparison.InvariantCultureIgnoreCase))
                        {
                            continue;
                        }
                        fileOrFolderName = Regex.Replace(TargetUrl, _targetContext.Web.ServerRelativeUrl, "", RegexOptions.IgnoreCase).Trim('/');
                        targetFolder     = srcIsFolder
                            ? _targetContext.Web.EnsureFolderPath(fileOrFolderName)
                            : targetList.RootFolder;
                        //fileOrFolderName = Regex.Replace(TargetUrl, targetList.RootFolder.ServerRelativeUrl, "", RegexOptions.IgnoreCase).Trim('/');
                        //targetFolder = srcIsFolder ? targetList.RootFolder.EnsureFolder(fileOrFolderName) : targetList.RootFolder;
                        break;
                    }
                }
                if (targetFolder == null)
                {
                    throw new Exception("Target does not exist");
                }
                if (srcIsFolder)
                {
                    if (!SkipSourceFolderName && targetFolderExists)
                    {
                        targetFolder = targetFolder.EnsureFolder(folder.Name);
                    }
                    CopyFolder(folder, targetFolder);
                }
                else
                {
                    UploadFile(file, targetFolder, fileOrFolderName);
                }
            }
        }
Exemplo n.º 4
0
        public void UnGhostFile(string absoluteFilePath, string outPutFolder, string OperationType, string SharePointOnline_OR_OnPremise = Constants.OnPremise, string UserName = "******", string Password = "******", string Domain = "NA")
        {
            string fileName               = string.Empty;
            string newFileName            = string.Empty;
            string directoryName          = string.Empty;
            bool   headerCSVColumns       = false;
            string exceptionCommentsInfo1 = string.Empty;

            GhostingAndUnGhosting_Initialization(outPutFolder, "UNGHOST");

            Logger.AddMessageToTraceLogFile(Constants.Logging, "############## Un Ghosting - Trasnformation Utility Execution Started - For Web ##############");
            Console.WriteLine("############## Un Ghosting - Trasnformation Utility Execution Started - For Web ##############");

            Logger.AddMessageToTraceLogFile(Constants.Logging, "[DATE TIME] " + Logger.CurrentDateTime());
            Console.WriteLine("[DATE TIME] " + Logger.CurrentDateTime());

            Logger.AddMessageToTraceLogFile(Constants.Logging, "[START] ::: UnGhostFile");
            Console.WriteLine("[START] ::: UnGhostFile");

            Logger.AddMessageToTraceLogFile(Constants.Logging, "[UnGhostFile] Initiated Logger and Exception Class. Logger and Exception file will be available in path " + outPutFolder);
            Console.WriteLine("[UnGhostFile] Initiated Logger and Exception Class. Logger and Exception file will be available in path" + outPutFolder);

            try
            {
                exceptionCommentsInfo1 = "FilePath: " + absoluteFilePath;
                AuthenticationHelper ObjAuth       = new AuthenticationHelper();
                ClientContext        clientContext = null;

                Uri fileUrl = new Uri(absoluteFilePath);

                clientContext = new ClientContext(fileUrl.GetComponents(UriComponents.SchemeAndServer, UriFormat.UriEscaped));
                Uri siteUrl = Web.WebUrlFromPageUrlDirect(clientContext, fileUrl);
                clientContext = new ClientContext(siteUrl);

                Logger.AddMessageToTraceLogFile(Constants.Logging, "[UnGhostFile] WebUrl is " + siteUrl.ToString());
                Console.WriteLine("[UnGhostFile] WebUrl is " + siteUrl.ToString());

                ExceptionCsv.WebUrl = siteUrl.ToString();

                //SharePoint on-premises / SharePoint Online Dedicated => OP (On-Premises)
                if (SharePointOnline_OR_OnPremise.ToUpper() == Constants.OnPremise)
                {
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[START][UnGhostFile] GetNetworkCredentialAuthenticatedContext for WebUrl: " + siteUrl.ToString());
                    clientContext = ObjAuth.GetNetworkCredentialAuthenticatedContext(siteUrl.ToString(), UserName, Password, Domain);
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[END][UnGhostFile] GetNetworkCredentialAuthenticatedContext for WebUrl: " + siteUrl.ToString());
                }
                //SharePointOnline  => OL (Online)
                else if (SharePointOnline_OR_OnPremise.ToUpper() == Constants.Online)
                {
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[START][UnGhostFile] GetSharePointOnlineAuthenticatedContextTenant for WebUrl: " + siteUrl.ToString());
                    clientContext = ObjAuth.GetSharePointOnlineAuthenticatedContextTenant(siteUrl.ToString(), UserName, Password);
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[END][UnGhostFile] GetSharePointOnlineAuthenticatedContextTenant for WebUrl: " + siteUrl.ToString());
                }

                if (clientContext != null)
                {
                    Microsoft.SharePoint.Client.File file = clientContext.Web.GetFileByServerRelativeUrl(fileUrl.AbsolutePath);
                    clientContext.Load(file);
                    clientContext.ExecuteQuery();
                    directoryName = GetLibraryName(fileUrl.ToString(), siteUrl.ToString(), fileName);

                    Folder folder = clientContext.Web.GetFolderByServerRelativeUrl(directoryName);
                    clientContext.Load(folder);
                    clientContext.ExecuteQuery();

                    fileName    = file.Name;
                    newFileName = GetNextFileName(fileName);
                    string path = System.IO.Directory.GetCurrentDirectory();
                    string downloadedFilePath = path + "\\" + newFileName;

                    using (WebClient myWebClient = new WebClient())
                    {
                        myWebClient.Credentials = CredentialCache.DefaultNetworkCredentials;
                        myWebClient.DownloadFile(absoluteFilePath, downloadedFilePath);
                    }

                    Microsoft.SharePoint.Client.File uploadedFile = FileFolderExtensions.UploadFile(folder, newFileName, downloadedFilePath, true);
                    if (uploadedFile.CheckOutType.Equals(CheckOutType.Online))
                    {
                        uploadedFile.CheckIn("File is UnGhotsed and Updated", CheckinType.MinorCheckIn);
                    }
                    clientContext.Load(uploadedFile);
                    clientContext.ExecuteQuery();

                    bool UnGhostFile_Status = false;
                    if (OperationType.ToUpper().Trim().Equals("MOVE"))
                    {
                        uploadedFile.MoveTo(directoryName + fileName, MoveOperations.Overwrite);
                        clientContext.ExecuteQuery();

                        Logger.AddMessageToTraceLogFile(Constants.Logging, "[UnGhostFile] Created the new version of the file " + fileName + " using MOVE operation");
                        Console.WriteLine("[UnGhostFile] Created the new version of the file " + fileName + " using MOVE operation");
                        UnGhostFile_Status = true;
                    }
                    else if (OperationType.ToUpper().Trim().Equals("COPY"))
                    {
                        uploadedFile.CopyTo(directoryName + fileName, true);
                        clientContext.ExecuteQuery();

                        Logger.AddMessageToTraceLogFile(Constants.Logging, "[UnGhostFile] Created the new version of the file " + fileName + " using COPY operation");
                        Console.WriteLine("[UnGhostFile] Created the new version of the file " + fileName + " using COPY operation");
                        UnGhostFile_Status = true;
                    }
                    else
                    {
                        Logger.AddMessageToTraceLogFile(Constants.Logging, "[UnGhostFile] The Operation input in not provided to unghost the file " + fileName + "");
                        Console.WriteLine("[UnGhostFile] The Operation input in not provided to unghost the file " + fileName + "");
                    }

                    //If Un-Ghost File Operation is Successful
                    if (UnGhostFile_Status)
                    {
                        GhostingAndUnGhostingBase objUGBase = new GhostingAndUnGhostingBase();
                        objUGBase.FileName       = fileName;
                        objUGBase.FilePath       = absoluteFilePath;
                        objUGBase.WebUrl         = siteUrl.ToString();
                        objUGBase.SiteCollection = Constants.NotApplicable;
                        objUGBase.WebApplication = Constants.NotApplicable;

                        if (objUGBase != null)
                        {
                            FileUtility.WriteCsVintoFile(outPutFolder + @"\" + Constants.UnGhosting_Output, objUGBase,
                                                         ref headerCSVColumns);
                        }

                        //Deleting the files, which is downloaded to Un-Ghost the file
                        if (System.IO.File.Exists(downloadedFilePath))
                        {
                            System.IO.File.Delete(downloadedFilePath);
                        }
                        //Deleting the files, which is downloaded to Un-Ghost the file
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.AddMessageToTraceLogFile(Constants.Logging, "[Exception] UnGhostFile. Exception Message: " + ex.Message);
                ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "UnGhost", ex.Message, ex.ToString(), "UnGhostFile", ex.GetType().ToString(), exceptionCommentsInfo1);
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[Exception] UnGhostFile. Exception Message: " + ex.Message);
                Console.ForegroundColor = ConsoleColor.Gray;
            }

            Logger.AddMessageToTraceLogFile(Constants.Logging, "[END] ::: UnGhostFile");
            Console.WriteLine("[END] ::: UnGhostFile");

            Logger.AddMessageToTraceLogFile(Constants.Logging, "############## UnGhostFile - Trasnformation Utility Execution Completed for Web ##############");
            Console.WriteLine("############## UnGhostFile - Trasnformation Utility Execution Completed for Web ##############");
        }