Example #1
0
        /// <summary>
        /// 移动文档
        /// </summary>
        /// <param name="siteUrl">指定站点地址</param>
        /// <param name="folderName1">指定文档库名称(移动源)</param>
        /// <param name="folderName2">指定文档库名称(移动目标)</param>
        /// <param name="fileName">指定文档名称</param>
        /// <returns>返回操作提示</returns>
        public string MoveFile(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;
                        file.MoveTo(d + "/" + fileName, MoveOperations.Overwrite);
                        clientContext.ExecuteQuery();
                        result = "文档移动成功";
                    }
                }
            }
            catch (Exception ex)
            {
                result = "文档移动失败";
                MethodLb.CreateLog(this.GetType().FullName, "MoveFile", ex.ToString(), folderName1, folderName2, fileName);
            }
            finally
            {
            }
            return(result);
        }
Example #2
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 ##############");
        }
Example #3
0
        public static bool Move(string currentLCU,
                                string newLCU,
                                ModuleName moduleName,
                                int moduleId,
                                string geographicRegionCd,
                                string sharepointCountryCd,
                                string customerNbr,
                                string fileName,
                                string newGeographicRegionCd, string newSharepointCountryCd, string newCustomerNbr)
        {
            bool          result    = false;
            var           _region   = geographicRegionCd;
            var           _country  = sharepointCountryCd;
            var           clientNbr = customerNbr;
            string        region    = string.Empty;
            string        newRegion = string.Empty;
            StringBuilder finalUri  = new StringBuilder("");

            if (_region == "EL")
            {
                region = "EME";
            }
            if (_region == "AP")
            {
                region = "APA";
            }
            if (_region != "EL" && _region != "AP")
            {
                region = "AMR";
            }

            _region = newGeographicRegionCd;
            if (_region == "EL")
            {
                newRegion = "EME";
            }
            if (_region == "AP")
            {
                newRegion = "APA";
            }
            if (_region != "EL" && _region != "AP")
            {
                newRegion = "AMR";
            }

            if (webUrl.Substring(webUrl.Length - 1, 1) != "/")
            {
                webUrl = webUrl + "/";
            }

            try
            {
                string uri              = webUrl + region + @"/" + sharepointCountryCd;
                string newUri           = webUrl + newRegion + @"/" + newSharepointCountryCd;
                var    newClientContext = new ClientContext(newUri);
                Web    newWeb           = newClientContext.Web;
                //newClientContext.Credentials = new NetworkCredential(userName, passWord, domain);
                CredentialCache cc = new CredentialCache();
                cc.Add(new Uri(webUrl),
                       "NTLM", new NetworkCredential(userName, passWord, domain));
                newClientContext.Credentials        = cc;
                newClientContext.AuthenticationMode = ClientAuthenticationMode.Default;
                newClientContext.Load(newWeb);
                newClientContext.ExecuteQuery();
                using (ClientContext context = new ClientContext(uri))
                {
                    Web web = context.Web;
                    //context.Credentials = new NetworkCredential(userName, passWord, domain);
                    CredentialCache ccs = new CredentialCache();
                    cc.Add(new Uri(webUrl),
                           "NTLM", new NetworkCredential(userName, passWord, domain));
                    context.Credentials        = ccs;
                    context.AuthenticationMode = ClientAuthenticationMode.Default;
                    context.Load(web);
                    context.ExecuteQuery();

                    string destinationUrl = EnsureParentFolder(newLCU, moduleId.ToString(), moduleName, newGeographicRegionCd, newSharepointCountryCd, newCustomerNbr, newClientContext);

                    finalUri.Append("/sites");
                    finalUri.Append("/");
                    finalUri.Append(region);
                    finalUri.Append("/");
                    finalUri.Append(sharepointCountryCd);
                    finalUri.Append("/");
                    finalUri.Append(docLib);
                    finalUri.Append("/");
                    finalUri.Append(clientNbr);
                    finalUri.Append("/");
                    finalUri.Append(currentLCU);
                    finalUri.Append("/");
                    finalUri.Append(moduleName.ToString());
                    finalUri.Append("/");
                    finalUri.Append(moduleId);
                    finalUri.Append("/");

                    string destUrl = finalUri.ToString() + fileName;
                    Microsoft.SharePoint.Client.File loadUrl = web.GetFileByServerRelativeUrl(destUrl);
                    if (region == newRegion)
                    {
                        loadUrl.MoveTo(destinationUrl + fileName, MoveOperations.Overwrite);
                        context.ExecuteQuery();
                        result = true;
                    }
                    if (region != newRegion)
                    {
                        var setMetadata = loadUrl.ListItemAllFields;
                        context.Load(setMetadata);
                        context.ExecuteQuery();
                        SharePointMetaData spModel = new SharePointMetaData();

                        spModel.operatingGrpCode     = (string)setMetadata["OperatingGroupCd"];
                        spModel.operatingGrp         = (string)setMetadata["OperatingGroupNm"];
                        spModel.operatingUnitCode    = (string)setMetadata["OperatingUnitCd"];
                        spModel.operatingUnit        = (string)setMetadata["OperatingUnitNm"];
                        spModel.clientServiceGrpCode = (string)setMetadata["OperatingUnitNm"];
                        spModel.clientServiceGrp     = (string)setMetadata["ClientServiceGroupDesc"];
                        spModel.clientName           = (string)setMetadata["CustomerNm"];
                        spModel.clientNumber         = (string)setMetadata["CustomerNbr"];
                        spModel.contractNumber       = (string)setMetadata["ContractNbr"];
                        spModel.strLCUId             = (string)setMetadata["LCUId"];
                        spModel.moduleName           = (string)setMetadata["ModuleNm"];
                        spModel.moduleId             = (string)setMetadata["ModuleId"];
                        spModel.userId           = (string)setMetadata["UserId"];
                        spModel.fileTypeCode     = (string)setMetadata["FileTypeCd"];
                        spModel.fileType         = (string)setMetadata["FileTypeNm"];
                        spModel.documentTypeCode = (string)setMetadata["DocumentTypeCd"];
                        spModel.documentType     = (string)setMetadata["DocumentTypeNm"];
                        spModel.documentName     = (string)setMetadata["DocumentNm"];

                        string          newDestUrl = destinationUrl + fileName;
                        FileInformation loadStream = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, destUrl);

                        Microsoft.SharePoint.Client.File.SaveBinaryDirect(newClientContext, destinationUrl + fileName, loadStream.Stream, true);

                        SetMeta(spModel, newUri, newDestUrl);

                        loadUrl.DeleteObject();
                        context.ExecuteQuery();

                        result = true;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(result);
        }