//sourceWebPartId - Used to update the content of the wikipage with new web part id [Fix for BugId - 95007]
        public bool AddWebPart(string webUrl, string configuredWebPartFileName, string configuredWebPartXmlFilePath, string webPartZoneIndex, string webPartZoneID, string serverRelativePageUrl, string outPutDirectory, string SharePointOnline_OR_OnPremise = "N/A", string UserName = "******", string Password = "******", string Domain = "N/A", string ActionType = "web", string sourceWebPartId = "")
        {
            bool isWebPartAdded = false;

            WebPartEntity webPart = new WebPartEntity();
            webPart.WebPartIndex = Convert.ToInt32(webPartZoneIndex);
            ClientContext clientContext = new ClientContext(webUrl);
            AuthenticationHelper ObjAuth = new AuthenticationHelper();
            string webPartXml = string.Empty;

            ExceptionCsv.WebUrl = webUrl;
            string exceptionCommentsInfo1 = string.Empty;
            try
            {
                if (ActionType.ToLower() == Constants.ActionType_Web.ToLower())
                {
                    //Initialized Exception and Logger.
                    WebPart_Initialization(outPutDirectory);

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "############## Web Part Trasnformation Utility Execution Started - AddWebPart ##############");
                    Console.WriteLine("############## Web Part Trasnformation Utility Execution Started - AddWebPart ##############");

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

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[AddWebPart] Initiated Logger and Exception Class. Logger and Exception file will be available at path: " + outPutDirectory);
                    Console.WriteLine("[AddWebPart] Initiated Logger and Exception Class. Logger and Exception file will be available at path: " + outPutDirectory);
                }

                //Prepare Exception Comments
                exceptionCommentsInfo1 = "Web Url: " + webUrl + ", Configured Web Part File Name: " + configuredWebPartFileName + " , Page Url: " + serverRelativePageUrl;

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

                if (clientContext != null)
                {
                    Web web = clientContext.Web;
                    clientContext.Load(web);
                    clientContext.ExecuteQuery();

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[AddWebPart] Successful authentication");
                    Console.WriteLine("[AddWebPart] Successful authentication");

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[AddWebPart] Checking for web part in the Web Part Gallery");
                    Console.WriteLine("[AddWebPart] Checking for web part in the Web Part Gallery");

                    //check for the target web part in the gallery
                    bool isWebPartInGallery = CheckWebPartOrAppPartPresenceInSite(clientContext, configuredWebPartFileName, configuredWebPartXmlFilePath);

                    if (isWebPartInGallery)
                    {
                        using (System.IO.FileStream fs = new System.IO.FileStream(configuredWebPartXmlFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                        {
                            StreamReader reader = new StreamReader(fs);
                            webPart.WebPartXml = reader.ReadToEnd();
                        }

                        webPart.WebPartZone = webPartZoneID;

                        List list = GetPageList(ref clientContext);

                        //Boolean to check if a call to Update method is required
                        bool needsUpdate = false;
                        bool forceCheckOut = false;
                        bool enableVersioning = false;
                        bool enableMinorVersions = false;
                        bool enableModeration = false;
                        DraftVisibilityType dVisibility = DraftVisibilityType.Author;

                        if (list != null)
                        {
                            try
                            {
                                #region Remove Versioning in List

                                Logger.AddMessageToTraceLogFile(Constants.Logging,
                                    "[AddWebPart] List Details " + serverRelativePageUrl + ". " +
                                    "Force Check Out: " + forceCheckOut +
                                    "Enable Versioning: " + enableVersioning +
                                    "Enable Minor Versions: " + enableMinorVersions +
                                    "Enable Moderation: " + enableModeration +
                                    "Draft Version Visibility: " + dVisibility);

                                Logger.AddMessageToTraceLogFile(Constants.Logging,
                                    "[AddWebPart] Removing Versioning");

                                if (enableVersioning)
                                {
                                    list.EnableVersioning = false;
                                    needsUpdate = true;
                                }
                                if (forceCheckOut)
                                {
                                    list.ForceCheckout = false;
                                    needsUpdate = true;
                                }
                                if (enableModeration)
                                {
                                    list.EnableModeration = false;
                                    needsUpdate = true;
                                }

                                if (needsUpdate)
                                {
                                    list.Update();
                                    clientContext.ExecuteQuery();
                                }
                                #endregion
                            }
                            catch (Exception ex)
                            {
                                ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "Web Part", ex.Message, ex.ToString(), "AddWebPart", ex.GetType().ToString(), exceptionCommentsInfo1);
                                Logger.AddMessageToTraceLogFile(Constants.Logging, "[EXCEPTION][AddWebPart] Exception Message: " + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1);

                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine("[EXCEPTION][AddWebPart] Exception Message: " + ex.Message);
                                Console.ForegroundColor = ConsoleColor.Gray;

                            }
                        }

                        try
                        {

                            Logger.AddMessageToTraceLogFile(Constants.Logging, "[AddWebPart] Adding web part to the page at " + serverRelativePageUrl);
                            Console.WriteLine("[AddWebPart] Adding web part to the page at " + serverRelativePageUrl);
                            isWebPartAdded = AddWebPart(clientContext.Web, serverRelativePageUrl, webPart, sourceWebPartId);
                        }
                        catch
                        {
                            throw;
                        }
                        finally
                        {
                            if (list != null)
                            {
                                #region Enable Versioning in List
                                //Reset the boolean so that it can used to test if we need to call Update method
                                needsUpdate = false;
                                if (enableVersioning)
                                {
                                    list.EnableVersioning = true;
                                    if (enableMinorVersions)
                                    {
                                        list.EnableMinorVersions = true;
                                    }
                                    if (enableMinorVersions)
                                    {
                                        list.EnableMinorVersions = true;
                                    }
                                    list.DraftVersionVisibility = dVisibility;
                                    needsUpdate = true;
                                }
                                if (enableModeration)
                                {
                                    list.EnableModeration = enableModeration;
                                    needsUpdate = true;
                                }
                                if (forceCheckOut)
                                {
                                    list.ForceCheckout = true;
                                    needsUpdate = true;
                                }
                                if (needsUpdate)
                                {
                                    list.Update();
                                    clientContext.ExecuteQuery();
                                }
                                #endregion
                            }
                        }
                        Logger.AddMessageToTraceLogFile(Constants.Logging, "[AddWebPart] Successfully Added the newly configured WebPart");

                        Console.WriteLine("[AddWebPart] Successfully Added the newly configured WebPart");
                    }
                    else
                    {
                        throw new Exception("Target Webpart should be present in the site for the webpart to be added");
                    }
                }

                if (ActionType.ToLower() == Constants.ActionType_Web.ToLower())
                {
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "############## Web Part Trasnformation Utility Execution Completed for Web - AddWebPart ##############");
                    Console.WriteLine("############## Web Part Trasnformation Utility Execution Completed  for Web - AddWebPart ##############");
                }
            }
            catch (Exception ex)
            {
                ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "Web Part", ex.Message, ex.ToString(), "AddWebPart", ex.GetType().ToString(), exceptionCommentsInfo1);
                Logger.AddMessageToTraceLogFile(Constants.Logging, "[EXCEPTION][AddWebPart] Exception Message: " + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1);
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[EXCEPTION][AddWebPart] Exception Message: " + ex.Message);
                Console.ForegroundColor = ConsoleColor.Gray;
                return isWebPartAdded;
            }
            return isWebPartAdded;
        }
        public string GetWebPartProperties(string pageUrl, string StorageKey, string webUrl, string outPutDirectory, string SharePointOnline_OR_OnPremise = "N/A", string UserName = "******", string Password = "******", string Domain = "N/A", string ActionType = "web")
        {
            string webPartPropertiesFileName = string.Empty;

            AuthenticationHelper ObjAuth = new AuthenticationHelper();
            ClientContext clientContext = new ClientContext(webUrl);

            string webPartXml = string.Empty;
            ExceptionCsv.WebUrl = webUrl;
            string exceptionCommentsInfo1 = string.Empty;

            try
            {
                if (ActionType.ToLower().Trim() == Constants.ActionType_Web.ToLower())
                {
                    //Initialized Exception and Logger.
                    WebPart_Initialization(outPutDirectory);

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "############## Web Part  Trasnformation Utility Execution Started - GetWebPartProperties ##############");
                    Console.WriteLine("############## Web Part  Trasnformation Utility Execution Started - GetWebPartProperties ##############");

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

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

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[GetWebPartProperties] Initiated Logger and Exception Class. Logger and Exception file will be available at path: " + outPutDirectory);
                    Console.WriteLine("[GetWebPartProperties] Initiated Logger and Exception Class. Logger and Exception file will be available at path: " + outPutDirectory);
                }

                string sourceWebPartXmlFilesDir = outPutDirectory + @"\" + Constants.SOURCE_WEBPART_XML_DIR;

                if (!System.IO.Directory.Exists(sourceWebPartXmlFilesDir))
                {
                    System.IO.Directory.CreateDirectory(sourceWebPartXmlFilesDir);
                }

                //Deleted the Web Part Usage File
                DeleteUsageFiles_WebPartHelper(sourceWebPartXmlFilesDir, StorageKey + "_" + Constants.WEBPART_PROPERTIES_FILENAME);

                //Prepare Exception Comments
                exceptionCommentsInfo1 = "Web Url: " + webUrl + ", Page Url: " + pageUrl + ", StorageKey" + StorageKey;

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

                if (clientContext != null)
                {
                    Web web = clientContext.Web;
                    clientContext.Load(web,w => w.Url);

                    clientContext.ExecuteQueryRetry();

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[GetWebPartProperties] Retrieving WebPart Properties for StorageKey: " + StorageKey.ToString() + " in the Page" + pageUrl);
                    Console.WriteLine("[GetWebPartProperties] Retrieving WebPart Properties for StorageKey: " + StorageKey.ToString() + " in the Page" + pageUrl);

                    var service = new Transformation.PowerShell.WebPartPagesService.WebPartPagesWebService();
                    service.Url = clientContext.Web.Url + Constants.WEBPART_SERVICE;

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[GetWebPartProperties] Service Url used to retrieve WebPart Properties : " + service.Url);
                    Console.WriteLine("[GetWebPartProperties] Service Url used to retrieve WebPart Properties : " + service.Url);

                    service.PreAuthenticate = true;

                    service.Credentials = clientContext.Credentials;

                    //For Publishing Pages, Pass - WebPartID
                    //For SitePage or Team Site, Pass - StorageKey.ToGuid()
                    webPartXml = service.GetWebPart2(pageUrl, StorageKey.ToGuid(), Storage.Shared, SPWebServiceBehavior.Version3);

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[GetWebPartProperties] Successfully retreived Web Part Properties");
                    Console.WriteLine("[GetWebPartProperties] Successfully retreived Web Part Properties");

                    webPartPropertiesFileName = sourceWebPartXmlFilesDir + "\\" + StorageKey + "_" + Constants.WEBPART_PROPERTIES_FILENAME;

                    using (StreamWriter fsWebPartProperties = new StreamWriter(webPartPropertiesFileName))
                    {
                        fsWebPartProperties.WriteLine(webPartXml);
                        fsWebPartProperties.Flush();
                    }

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[GetWebPartProperties] WebPart Properties in xml format is exported to the file " + webPartPropertiesFileName);
                    Console.WriteLine("[GetWebPartProperties] WebPart Properties in xml format is exported to the file " + webPartPropertiesFileName);
                }

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

                if (ActionType.ToLower().Trim() == Constants.ActionType_Web.ToLower())
                {
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "############## Web Part Trasnformation Utility Execution Completed for Web - GetWebPartProperties ##############");
                    Console.WriteLine("############## Web Part Trasnformation Utility Execution Completed  for Web - GetWebPartProperties ##############");
                }

            }
            catch (Exception ex)
            {
                ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "Web Part", ex.Message, ex.ToString(), "GetWebPartProperties", ex.GetType().ToString(), exceptionCommentsInfo1);
                Logger.AddMessageToTraceLogFile(Constants.Logging, "[EXCEPTION][GetWebPartProperties] Exception Message: " + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1);
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[EXCEPTION][GetWebPartProperties] Exception Message: " + ex.Message);
                Console.ForegroundColor = ConsoleColor.Gray;
            }

            return webPartPropertiesFileName;
        }
        private void UploadWebPartFile(string webUrl, string fileName, string localFilePath, bool overwriteIfExists, string group, string outPutDirectory, string SharePointOnline_OR_OnPremise = "N/A", string UserName = "******", string Password = "******", string Domain = "N/A")
        {
            ExceptionCsv.WebUrl = webUrl;
            string exceptionCommentsInfo1 = string.Empty;

            ClientContext clientContext = new ClientContext(webUrl);
            AuthenticationHelper ObjAuth = new AuthenticationHelper();
            Web web = clientContext.Web;
            Folder folder = null;
            string webPartXml = string.Empty;

            try
            {
                //Initialized Exception and Logger.
                WebPart_Initialization(outPutDirectory);

                Logger.AddMessageToTraceLogFile(Constants.Logging, "############## Web Part  Trasnformation Utility Execution Started - UploadWebPartFile ##############");
                Console.WriteLine("############## Web Part  Trasnformation Utility Execution Started - UploadWebPartFile ##############");

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

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

                Logger.AddMessageToTraceLogFile(Constants.Logging, "[UploadWebPartFile] Initiated Logger and Exception Class. Logger and Exception file will be available at path: " + outPutDirectory);
                Console.WriteLine("[UploadWebPartFile] Initiated Logger and Exception Class. Logger and Exception file will be available at path: " + outPutDirectory);

                //Prepare Exception Comments
                exceptionCommentsInfo1 = "Web Url: " + webUrl + ", Web Part File Name : " + fileName + ", Group: " + group;

                //SharePoint on-premises / SharePoint Online Dedicated => OP (On-Premises)
                if (SharePointOnline_OR_OnPremise.ToUpper().Equals(Constants.OnPremise.ToUpper()))
                {
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[START][UploadWebPartFile] GetNetworkCredentialAuthenticatedContext for WebUrl: " + webUrl);
                    clientContext = ObjAuth.GetNetworkCredentialAuthenticatedContext(webUrl, UserName, Password, Domain);
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[END][UploadWebPartFile] GetNetworkCredentialAuthenticatedContext for WebUrl: " + webUrl);
                }
                //SharePointOnline  => OL (Online)
                else if (SharePointOnline_OR_OnPremise.ToUpper().Equals(Constants.Online.ToUpper()))
                {
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[START][UploadWebPartFile] GetSharePointOnlineAuthenticatedContextTenant for WebUrl: " + webUrl);
                    clientContext = ObjAuth.GetSharePointOnlineAuthenticatedContextTenant(webUrl, UserName, Password);
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[END][UploadWebPartFile] GetSharePointOnlineAuthenticatedContextTenant for WebUrl: " + webUrl);
                }
                if (clientContext != null)
                {
                    folder = clientContext.Web.Lists.GetByTitle("Web Part Gallery").RootFolder;
                    clientContext.Load(folder);
                    clientContext.ExecuteQuery();

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[UploadWebPartFile] Uploading the File " + fileName);
                    Console.WriteLine("[UploadWebPartFile] Uploading the File " + fileName);

                    FileFolderExtensions.UploadFile(folder, fileName, localFilePath, overwriteIfExists);

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[UploadWebPartFile] Successfully uploaded web part to the web part gallery " + folder);
                    Console.WriteLine("[UploadWebPartFile] Successfully uploaded web part to the web part gallery " + folder);

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[UploadWebPartFile] Updating group of the web parts");
                    Console.WriteLine("[UploadWebPartFile] Updating group of the web parts");

                    List list = clientContext.Web.Lists.GetByTitle("Web Part Gallery");
                    CamlQuery camlQuery = CamlQuery.CreateAllItemsQuery(100);

                    Microsoft.SharePoint.Client.ListItemCollection items = list.GetItems(camlQuery);
                    clientContext.Load(items);
                    clientContext.ExecuteQuery();

                    foreach (ListItem item in items)
                    {
                        if (item["FileLeafRef"].ToString().ToLowerInvariant() == fileName.ToLowerInvariant())
                        {
                            item["Group"] = group;
                            item.Update();
                            clientContext.ExecuteQuery();
                        }
                    }

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[UploadWebPartFile] Successfully updated the group of the web parts");
                    Console.WriteLine("[UploadWebPartFile] Successfully updated the group of the web parts");

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[UploadWebPartFile] Uploaded the Newly configured Web Part at " + folder.ServerRelativeUrl);
                    Console.WriteLine("[UploadWebPartFile] Uploaded the Newly configured Web Part at " + folder.ServerRelativeUrl);

                }

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

                Logger.AddMessageToTraceLogFile(Constants.Logging, "############## Web Part Trasnformation Utility Execution Completed for Web - UploadWebPartFile ##############");
                Console.WriteLine("############## Web Part Trasnformation Utility Execution Completed  for Web - UploadWebPartFile ##############");
            }
            catch (Exception ex)
            {
                ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "Web Part", ex.Message, ex.ToString(), "UploadWebPartFile", ex.GetType().ToString(), exceptionCommentsInfo1);
                Logger.AddMessageToTraceLogFile(Constants.Logging, "[EXCEPTION][UploadWebPartFile] Exception Message: " + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1);
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[EXCEPTION][UploadWebPartFile] Exception Message: " + ex.Message);
                Console.ForegroundColor = ConsoleColor.Gray;
            }
        }
        public bool DeleteWebPart(string webUrl, string pageUrl, string _storageKey, string outPutDirectory, string SharePointOnline_OR_OnPremise = "N/A", string UserName = "******", string Password = "******", string Domain = "N/A", string ActionType = "web")
        {
            ClientContext clientContext = new ClientContext(webUrl);
            AuthenticationHelper ObjAuth = new AuthenticationHelper();
            bool isWebPartDeleted = false;
            string webPartXml = string.Empty;
            ExceptionCsv.WebUrl = webUrl;
            string exceptionCommentsInfo1 = string.Empty;

            try
            {
                //This function is Get Relative URL of the page
                string ServerRelativePageUrl = string.Empty;
                ServerRelativePageUrl = GetPageRelativeURL(webUrl, pageUrl, SharePointOnline_OR_OnPremise, UserName, Password, Domain);

                Guid storageKey = new Guid(GetWebPartID(_storageKey));

                if (ActionType.ToLower().Trim() == Constants.ActionType_Web.ToLower())
                {
                    //Initialized Exception and Logger.
                    WebPart_Initialization(outPutDirectory);

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "############## Web Part Trasnformation Utility Execution Started - DeleteWebPart ##############");
                    Console.WriteLine("############## Web Part  Trasnformation Utility Execution Started - DeleteWebPart ##############");

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

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[DeleteWebPart] Initiated Logger and Exception Class. Logger and Exception file will be available at path: " + outPutDirectory);
                    Console.WriteLine("[DeleteWebPart] Initiated Logger and Exception Class. Logger and Exception file will be available at path: " + outPutDirectory);
                }
                //Prepare Exception Comments
                exceptionCommentsInfo1 = "Web Url: " + webUrl + ", Storage Key : " + storageKey.ToString() + ", Page Url: " + ServerRelativePageUrl;

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

                if (clientContext != null)
                {
                    Web web = clientContext.Web;
                    clientContext.Load(web);
                    clientContext.ExecuteQuery();

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[DeleteWebPart] Successful authentication");
                    Console.WriteLine("[DeleteWebPart] Successful authentication");

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[START][DeleteWebPart] Checking Out File ...");
                    Console.WriteLine("[START][DeleteWebPart] Checking Out File ...");

                    List list = GetPageList(ref clientContext);

                    //Boolean to check if a call to Update method is required
                    bool needsUpdate = false;
                    bool forceCheckOut = false;
                    bool enableVersioning = false;
                    bool enableMinorVersions = false;
                    bool enableModeration = false;
                    DraftVisibilityType dVisibility = DraftVisibilityType.Author;

                    if (list != null)
                    {
                        try
                        {
                            #region Remove Versioning in List
                            forceCheckOut = list.ForceCheckout;
                            enableVersioning = list.EnableVersioning;
                            enableMinorVersions = list.EnableMinorVersions;
                            enableModeration = list.EnableModeration;
                            dVisibility = list.DraftVersionVisibility;

                            Logger.AddMessageToTraceLogFile(Constants.Logging,
                                "[DeleteWebpart] List Details " + ServerRelativePageUrl + ". " +
                                "Force Check Out: " + forceCheckOut +
                                "Enable Versioning: " + enableVersioning +
                                "Enable Minor Versions: " + enableMinorVersions +
                                "Enable Moderation: " + enableModeration +
                                "Draft Version Visibility: " + dVisibility);

                            Logger.AddMessageToTraceLogFile(Constants.Logging,
                                "[DeleteWebpart] Removing Versioning");
                            //Boolean to check if a call to Update method is required
                            needsUpdate = false;

                            if (enableVersioning)
                            {
                                list.EnableVersioning = false;
                                needsUpdate = true;
                            }
                            if (forceCheckOut)
                            {
                                list.ForceCheckout = false;
                                needsUpdate = true;
                            }
                            if (enableModeration)
                            {
                                list.EnableModeration = false;
                                needsUpdate = true;
                            }

                            if (needsUpdate)
                            {
                                list.Update();
                                clientContext.ExecuteQuery();
                            }
                            #endregion
                        }

                        catch (Exception ex)
                        {
                            ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "Web Part", ex.Message, ex.ToString(), "DeleteWebPart", ex.GetType().ToString(), exceptionCommentsInfo1);
                            Logger.AddMessageToTraceLogFile(Constants.Logging, "[EXCEPTION][DeleteWebPart] Exception Message: " + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1);

                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("[EXCEPTION][DeleteWebPart] Exception Message: " + ex.Message);
                            Console.ForegroundColor = ConsoleColor.Gray;

                        }
                    }

                    try
                    {

                        if (DeleteWebPart(clientContext.Web, ServerRelativePageUrl, storageKey))
                        {
                            isWebPartDeleted = true;
                            Logger.AddMessageToTraceLogFile(Constants.Logging, "[DeleteWebPart] Successfully Deleted the WebPart");
                            Console.WriteLine("[DeleteWebPart] Successfully Deleted the WebPart");
                        }
                        else
                        {
                            Logger.AddMessageToTraceLogFile(Constants.Logging, "[DeleteWebPart] WebPart with StorageKey: " + storageKey + " does not exist in the Page: " + ServerRelativePageUrl);
                            Console.WriteLine("[DeleteWebPart] WebPart with StorageKey: " + storageKey + " does not exist in the Page: " + ServerRelativePageUrl);
                        }
                    }
                    catch
                    {
                        throw;
                    }
                    finally
                    {
                        if (list != null)
                        {
                            #region Enable Versioning in List
                            //Reset the boolean so that it can used to test if we need to call Update method
                            needsUpdate = false;
                            if (enableVersioning)
                            {
                                list.EnableVersioning = true;
                                if (enableMinorVersions)
                                {
                                    list.EnableMinorVersions = true;
                                }
                                if (enableMinorVersions)
                                {
                                    list.EnableMinorVersions = true;
                                }

                                list.DraftVersionVisibility = dVisibility;
                                needsUpdate = true;
                            }
                            if (enableModeration)
                            {
                                list.EnableModeration = enableModeration;
                                needsUpdate = true;
                            }
                            if (forceCheckOut)
                            {
                                list.ForceCheckout = true;
                                needsUpdate = true;
                            }
                            if (needsUpdate)
                            {
                                list.Update();
                                clientContext.ExecuteQuery();
                            }
                            #endregion
                        }

                    }
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[END][DeleteWebPart]  File Checked in after successfully deleting the webpart.");
                    Console.WriteLine("[END][DeleteWebPart]  File Checked in after successfully deleting the webpart.");

                }

                if (ActionType.ToLower().Trim() ==  Constants.ActionType_Web.ToLower())
                {
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "############## Web Part Trasnformation Utility Execution Completed for Web - DeleteWebPart ##############");
                    Console.WriteLine("############## Web Part Trasnformation Utility Execution Completed  for Web - DeleteWebPart ##############");
                }

            }
            catch (Exception ex)
            {
                ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "Web Part", ex.Message, ex.ToString(), "DeleteWebPart", ex.GetType().ToString(), exceptionCommentsInfo1);
                Logger.AddMessageToTraceLogFile(Constants.Logging, "[EXCEPTION][DeleteWebPart] Exception Message: " + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1);

                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[EXCEPTION][DeleteWebPart] Exception Message: " + ex.Message);
                Console.ForegroundColor = ConsoleColor.Gray;
            }
            return isWebPartDeleted;
        }
        private string GetPageRelativeURL(string WebUrl, string PageUrl, string SharePointOnline_OR_OnPremise = "N/A", string UserName = "******", string Password = "******", string Domain = "N/A")
        {
            AuthenticationHelper ObjAuth = new AuthenticationHelper();
            ClientContext clientContext = null;
            string _relativePageUrl = string.Empty;

            if (WebUrl != "" || PageUrl != "")
            {
                //SharePoint on-premises / SharePoint Online Dedicated => OP (On-Premises)
                if (SharePointOnline_OR_OnPremise.ToUpper() == Constants.OnPremise)
                {
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[START][GetPageRelativeURL] GetNetworkCredentialAuthenticatedContext for WebUrl: " + WebUrl);
                    clientContext = ObjAuth.GetNetworkCredentialAuthenticatedContext(WebUrl, UserName, Password, Domain);
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[END][GetPageRelativeURL] GetNetworkCredentialAuthenticatedContext for WebUrl: " + WebUrl);
                }
                //SharePointOnline  => OL (Online)
                else if (SharePointOnline_OR_OnPremise.ToUpper() == Constants.Online)
                {
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[START][GetPageRelativeURL] GetSharePointOnlineAuthenticatedContextTenant for WebUrl: " + WebUrl);
                    clientContext = ObjAuth.GetSharePointOnlineAuthenticatedContextTenant(WebUrl, UserName, Password);
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[END][GetPageRelativeURL] GetSharePointOnlineAuthenticatedContextTenant for WebUrl: " + WebUrl);
                }
                if (clientContext != null)
                {
                    Web _Web = clientContext.Web;
                    clientContext.Load(_Web);
                    clientContext.ExecuteQuery();

                    Logger.AddMessageToTraceLogFile(true, "[GetPageRelativeURL] Web.ServerRelativeUrl: " + _Web.ServerRelativeUrl + " And PageUrl: " + PageUrl);

                    //Issue: Found in MARS Retraction Process, the root web ServerRelativeUrl would result "/" only
                    //Hence appending "/" would throw exception for ServerRelativeUrl parameter
                    if (_Web.ServerRelativeUrl.ToString().Equals("/"))
                    {
                        _relativePageUrl = _Web.ServerRelativeUrl.ToString() + PageUrl;
                    }
                    else if (!PageUrl.Contains(_Web.ServerRelativeUrl))
                    {
                        _relativePageUrl = _Web.ServerRelativeUrl.ToString() + "/" + PageUrl;
                    }
                    else
                    {
                        _relativePageUrl = PageUrl;
                    }
                    Logger.AddMessageToTraceLogFile(true, "[GetPageRelativeURL] RelativePageUrl Framed: " + _relativePageUrl);
                }
            }

            return _relativePageUrl;
        }
        private void UploadDisplayTemplateFile(string webUrl, string fileName, string localFilePath, bool overwriteIfExists, string displayTemplateCategory, string outPutDirectory, string SharePointOnline_OR_OnPremise = "N/A", string UserName = "******", string Password = "******", string Domain = "N/A")
        {
            ClientContext clientContext = new ClientContext(webUrl);
            AuthenticationHelper ObjAuth = new AuthenticationHelper();
            string webPartXml = string.Empty;
            Web web = clientContext.Web;
            Folder folder = null;

            ExceptionCsv.WebUrl = webUrl;
            string exceptionCommentsInfo1 = string.Empty;
            try
            {
                //Initialized Exception and Logger.
                WebPart_Initialization(outPutDirectory);

                Logger.AddMessageToTraceLogFile(Constants.Logging, "############## Web Part  Trasnformation Utility Execution Started - UploadDisplayTemplateFile ##############");
                Console.WriteLine("############## Web Part  Trasnformation Utility Execution Started - UploadDisplayTemplateFile ##############");

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

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

                Logger.AddMessageToTraceLogFile(Constants.Logging, "[UploadDisplayTemplateFile] Initiated Logger and Exception Class. Logger and Exception file will be available at path: " + outPutDirectory);
                Console.WriteLine("[UploadDisplayTemplateFile] Initiated Logger and Exception Class. Logger and Exception file will be available at path: " + outPutDirectory);

                //Prepare Exception Comments
                exceptionCommentsInfo1 = "Web Url: " + webUrl + ", Display Template File Name : " + fileName + ", Category: " + displayTemplateCategory;

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

                if (clientContext != null)
                {
                    folder = clientContext.Web.Lists.GetByTitle("Master Page Gallery").RootFolder.ResolveSubFolder("Display Templates").ResolveSubFolder(displayTemplateCategory);

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[UploadDisplayTemplateFile] Resolving the relative path to get the folder to be uploaded");
                    Console.WriteLine("[UploadDisplayTemplateFile] Resolving the relative path to get the folder to be uploaded");

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[UploadDisplayTemplateFile] Uploading the File " + fileName);
                    Console.WriteLine("[UploadDisplayTemplateFile] Uploading the File " + fileName);

                    FileFolderExtensions.UploadFile(folder, fileName, localFilePath, overwriteIfExists);

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[UploadDisplayTemplateFile] Successfully Uploaded File to " + folder.ServerRelativeUrl);
                    Console.WriteLine("[UploadDisplayTemplateFile] Successfully Uploaded File to " + folder.ServerRelativeUrl);
                }

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

                Logger.AddMessageToTraceLogFile(Constants.Logging, "############## Web Part Trasnformation Utility Execution Completed for Web - UploadDisplayTemplateFile ##############");
                Console.WriteLine("############## Web Part Trasnformation Utility Execution Completed  for Web - UploadDisplayTemplateFile ##############");
            }
            catch (Exception ex)
            {
                ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "Web Part", ex.Message, ex.ToString(), "UploadDisplayTemplateFile", ex.GetType().ToString(), exceptionCommentsInfo1);
                Logger.AddMessageToTraceLogFile(Constants.Logging, "[EXCEPTION][UploadDisplayTemplateFile] Exception Message: " + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1);
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[EXCEPTION][UploadDisplayTemplateFile] Exception Message: " + ex.Message);
                Console.ForegroundColor = ConsoleColor.Gray;
            }
        }
        public void UploadAppInAppCatalog(string appCatalogUrl, string fileName, string appFilePath, string outPutDirectory, string SharePointOnline_OR_OnPremise = "N/A", string UserName = "******", string Password = "******", string Domain = "N/A")
        {
            ClientContext clientContext = new ClientContext(appCatalogUrl);
            AuthenticationHelper ObjAuth = new AuthenticationHelper();
            string webPartXml = string.Empty;
            ExceptionCsv.WebUrl = appCatalogUrl;
            string exceptionCommentsInfo1 = string.Empty;

            try
            {
                //Initialized Exception and Logger.
                WebPart_Initialization(outPutDirectory);

                Logger.AddMessageToTraceLogFile(Constants.Logging, "############## Web Part  Trasnformation Utility Execution Started - UploadAppInAppCatalog ##############");
                Console.WriteLine("############## Web Part  Trasnformation Utility Execution Started - UploadAppInAppCatalog ##############");

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

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

                Logger.AddMessageToTraceLogFile(Constants.Logging, "[UploadAppInAppCatalog] Initiated Logger and Exception Class. Logger and Exception file will be available at path: " + outPutDirectory);
                Console.WriteLine("[UploadAppInAppCatalog] Initiated Logger and Exception Class. Logger and Exception file will be available at path: " + outPutDirectory);

                //Prepare Exception Comments
                exceptionCommentsInfo1 = "App File Name : " + fileName + ", App Catalogue: " + appCatalogUrl;

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

                if (clientContext != null)
                {
                    Web web = clientContext.Web;
                    clientContext.Load(web);
                    clientContext.ExecuteQuery();

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[UploadAppInAppCatalog] Successful authentication");
                    Console.WriteLine("[UploadAppInAppCatalog] Successful authentication");

                    ListCollection listCollection = web.Lists;
                    clientContext.Load(listCollection);
                    clientContext.ExecuteQuery();
                    if (IsLibraryExist("Apps for SharePoint", listCollection))
                    {
                        Logger.AddMessageToTraceLogFile(Constants.Logging, "[UploadAppInAppCatalog] App Catalogue: " + appCatalogUrl + " contains list: Apps for SharePoint");
                        Console.WriteLine("[UploadAppInAppCatalog] App Catalogue: " + appCatalogUrl + " contains list: Apps for SharePoint");

                        using (var fs = new FileStream(appFilePath, FileMode.Open))
                        {
                            //Uploading the App to the App Catalogue
                            var fi = new FileInfo(appFilePath);
                            var list = clientContext.Web.Lists.GetByTitle("Apps for SharePoint");
                            clientContext.Load(list.RootFolder);
                            clientContext.ExecuteQuery();

                            Folder folder = list.RootFolder;
                            Logger.AddMessageToTraceLogFile(Constants.Logging, "[START][UploadAppInAppCatalog] UploadFile");
                            Console.WriteLine("[START][UploadAppInAppCatalog] UploadFile");

                            Microsoft.SharePoint.Client.File file = FileFolderExtensions.UploadFile(folder, fileName, appFilePath, true);

                            Logger.AddMessageToTraceLogFile(Constants.Logging, "[END][UploadAppInAppCatalog] UploadFile");
                            Console.WriteLine("[END][UploadAppInAppCatalog] UploadFile ");

                            Logger.AddMessageToTraceLogFile(Constants.Logging, "[UploadAppInAppCatalog] Successfully Upload File to " + appCatalogUrl);
                            Console.WriteLine("[UploadAppInAppCatalog] Successfully Upload File to " + appCatalogUrl);
                        }
                    }
                }

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

            }
            catch (Exception ex)
            {
                ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "Web Part", ex.Message, ex.ToString(), "UploadAppInAppCatalog", ex.GetType().ToString(), exceptionCommentsInfo1);
                Logger.AddMessageToTraceLogFile(Constants.Logging, "[EXCEPTION][UploadAppInAppCatalog] Exception Message: " + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1);
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[EXCEPTION][UploadAppInAppCatalog] Exception Message: " + ex.Message);
                Console.ForegroundColor = ConsoleColor.Gray;
            }
        }
        public void UploadDependencyFile(string webUrl, string folderServerRelativeUrl,string fileName, string localFilePath, bool overwriteIfExists, string outPutDirectory, string SharePointOnline_OR_OnPremise = "N/A", string UserName = "******", string Password = "******", string Domain = "N/A")
        {
            ClientContext clientContext = new ClientContext(webUrl);
            AuthenticationHelper ObjAuth = new AuthenticationHelper();
            string webPartXml = string.Empty;
            Web web = clientContext.Web;
            clientContext.Load(web);
            clientContext.ExecuteQuery();

            ExceptionCsv.WebUrl = web.Url;
            string exceptionCommentsInfo1 = string.Empty;
            try
            {
                //Initialized Exception and Logger.
                WebPart_Initialization(outPutDirectory);

                Logger.AddMessageToTraceLogFile(Constants.Logging, "############## Web Part  Trasnformation Utility Execution Started - UploadDependencyFile ##############");
                Console.WriteLine("############## Web Part  Trasnformation Utility Execution Started - UploadDependencyFile ##############");

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

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

                Logger.AddMessageToTraceLogFile(Constants.Logging, "[UploadDependencyFile] Initiated Logger and Exception Class. Logger and Exception file will be available at path: " + outPutDirectory);
                Console.WriteLine("[UploadDependencyFile] Initiated Logger and Exception Class. Logger and Exception file will be available at path: " + outPutDirectory);

                //SharePoint on-premises / SharePoint Online Dedicated => OP (On-Premises)
                if (SharePointOnline_OR_OnPremise.ToUpper().Equals(Constants.OnPremise.ToUpper()))
                {
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[START][UploadDependencyFile] GetNetworkCredentialAuthenticatedContext for WebUrl: " + web.Url);
                    clientContext = ObjAuth.GetNetworkCredentialAuthenticatedContext(web.Url, UserName, Password, Domain);
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[END][UploadDependencyFile] GetNetworkCredentialAuthenticatedContext for WebUrl: " + web.Url);
                }
                //SharePointOnline  => OL (Online)
                else if (SharePointOnline_OR_OnPremise.ToUpper().Equals(Constants.Online.ToUpper()))
                {
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[START][UploadDependencyFile] GetSharePointOnlineAuthenticatedContextTenant for WebUrl: " + web.Url);
                    clientContext = ObjAuth.GetSharePointOnlineAuthenticatedContextTenant(web.Url, UserName, Password);
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[END][UploadDependencyFile] GetSharePointOnlineAuthenticatedContextTenant for WebUrl: " + web.Url);
                }
                if (clientContext != null)
                {
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[UploadDependencyFile] Successful authentication");
                    Console.WriteLine("[UploadDependencyFile] Successful authentication");

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

                    Folder folder = clientContext.Web.RootFolder;

                    //Prepare Exception Comments
                    exceptionCommentsInfo1 = "Display Template File Name : " + fileName + " , Folder: " + folder;

                    clientContext.Load(folder, f => f.Folders, f => f.ServerRelativeUrl);
                    clientContext.ExecuteQuery();
                    while (folderServerRelativeUrl.Contains(folder.ServerRelativeUrl) && !folderServerRelativeUrl.Equals(folder.ServerRelativeUrl))
                    {
                        foreach (Folder _folder in folder.Folders)
                        {
                            if (folderServerRelativeUrl.Contains(_folder.ServerRelativeUrl))
                            {
                                folder = _folder;
                                break;
                            }
                        }
                        clientContext.Load(folder.Folders);
                        clientContext.ExecuteQuery();
                    }

                    FileFolderExtensions.UploadFile(folder, fileName, localFilePath, overwriteIfExists);

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[END][UploadDependencyFile] UploadFile");
                    Console.WriteLine("[END][UploadDependencyFile] UploadFile ");

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[UploadDependencyFile] Successfully Upload File to " + folder.ServerRelativeUrl);
                    Console.WriteLine("[UploadDependencyFile] Successfully Upload File to " + folder.ServerRelativeUrl);

                }

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

                Logger.AddMessageToTraceLogFile(Constants.Logging, "############## Web Part Trasnformation Utility Execution Completed for Web - UploadDependencyFile ##############");
                Console.WriteLine("############## Web Part Trasnformation Utility Execution Completed  for Web - UploadDependencyFile ##############");
            }
            catch (Exception ex)
            {
                ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "Web Part", ex.Message, ex.ToString(), "UploadDependencyFile", ex.GetType().ToString(), exceptionCommentsInfo1);
                Logger.AddMessageToTraceLogFile(Constants.Logging, "[EXCEPTION][UploadDependencyFile] Exception Message: " + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1);
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[EXCEPTION][UploadDependencyFile] Exception Message: " + ex.Message);
                Console.ForegroundColor = ConsoleColor.Gray;
            }
        }
        public void GetWebPartsByWeb(string WebUrl, string outPutDirectory, string SharePointOnline_OR_OnPremise = "N/A", string UserName = "******", string Password = "******", string Domain = "N/A")
        {
            ClientContext clientContext = new ClientContext(WebUrl);
            AuthenticationHelper ObjAuth = new AuthenticationHelper();

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

            if (clientContext != null)
            {
                clientContext.Load(clientContext.Web);
                clientContext.ExecuteQuery();

                ExceptionCsv.WebUrl = clientContext.Web.Url;
                string exceptionCommentsInfo1 = string.Empty;
                string webPartInfoFileName = outPutDirectory + "\\" + "WebParts.csv";

                try
                {
                    //Initialized Exception and Logger.
                    WebPart_Initialization(outPutDirectory);

                    //Deleted the Web Part Usage File
                    DeleteUsageFiles_WebPartHelper(outPutDirectory, "WebParts.csv");

                    string webUrl = clientContext.Web.Url;
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "############## Web Part  Trasnformation Utility Execution Started ##############");
                    Console.WriteLine("############## Web Part  Trasnformation Utility Execution Started ##############");

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

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

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[GetWebPartsByWeb] Initiated Logger and Exception Class. Logger and Exception file will be available at path: " + outPutDirectory);
                    Console.WriteLine("[GetWebPartsByWeb] Initiated Logger and Exception Class. Logger and Exception file will be available at path: " + outPutDirectory);

                    WebPartInfo webPartInfo = null;

                    List list = GetPageList(ref clientContext);

                    if (list != null)
                    {
                        var items = list.GetItems(CamlQuery.CreateAllItemsQuery());

                        //make sure to include the File on each Item fetched
                        clientContext.Load(items,
                                            i => i.Include(
                                                    item => item.File,
                                                     item => item["EncodedAbsUrl"]));
                        clientContext.ExecuteQuery();

                        bool headerWebPart = false;

                        // Iterate through all available pages in the pages list
                        foreach (var item in items)
                        {
                            Microsoft.SharePoint.Client.File page = item.File;

                            String pageUrl = page.ServerRelativeUrl;// item.FieldValues["EncodedAbsUrl"].ToString();

                            Logger.AddMessageToTraceLogFile(Constants.Logging, "[GetWebPartsByWeb] Checking for the Web Part on the Page: " + page.Name);
                            Console.WriteLine("[GetWebPartsByWeb] Checking for the Web Part on the Page:" + page.Name);

                            // Requires Full Control permissions on the Web
                            LimitedWebPartManager webPartManager = page.GetLimitedWebPartManager(PersonalizationScope.Shared);
                            clientContext.Load(webPartManager,
                                                wpm => wpm.WebParts,
                                                wpm => wpm.WebParts.Include(
                                                                    wp => wp.WebPart.Hidden,
                                                                    wp => wp.WebPart.IsClosed,
                                                                    wp => wp.WebPart.Properties,
                                                                    wp => wp.WebPart.Subtitle,
                                                                    wp => wp.WebPart.Title,
                                                                    wp => wp.WebPart.TitleUrl,
                                                                    wp => wp.WebPart.ZoneIndex));
                            clientContext.ExecuteQuery();

                            foreach (WebPartDefinition webPartDefinition in webPartManager.WebParts)
                            {
                                Microsoft.SharePoint.Client.WebParts.WebPart webPart = webPartDefinition.WebPart;

                                //Prepare Exception Comments
                                exceptionCommentsInfo1 = "Web Url: " + clientContext.Web.Url + ", Web Part Type: " + webPart.GetType().Name;

                                Logger.AddMessageToTraceLogFile(Constants.Logging, "[GetWebPartsByWeb] Found WebPart details for Web Part: " + webPart.Title + " in Web: " + webUrl);
                                Console.WriteLine("[GetWebPartsByWeb] Found WebPart details for Web Part: " + webPart.Title + " in Web: " + webUrl);

                                webPartInfo = new WebPartInfo();
                                webPartInfo.PageUrl = pageUrl;
                                webPartInfo.WebPartID = webPartDefinition.Id.ToString();
                                webPartInfo.WebURL = webUrl;
                                webPartInfo.WebPartTitle = webPart.Title;
                                webPartInfo.ZoneIndex = webPart.ZoneIndex.ToString();
                                webPartInfo.WebPartTitle = webPart.Title;
                                string webPartPropertiesXml = GetWebPartPropertiesServiceCall(clientContext, webPartDefinition.Id.ToString(), pageUrl);

                                string WebPartTypeName = string.Empty;

                                if (webPartPropertiesXml.Contains("WebPart/v2"))
                                {
                                    XmlDataDocument xmldoc = new XmlDataDocument();
                                    xmldoc.LoadXml(webPartPropertiesXml);
                                    WebPartTypeName = xmldoc.DocumentElement.GetElementsByTagName("TypeName").Item(0).FirstChild.Value;
                                    xmldoc = null;
                                }
                                else
                                {
                                    webParts webPartProp = null;
                                    byte[] byteArray = Encoding.UTF8.GetBytes(webPartPropertiesXml);
                                    using (MemoryStream stream = new MemoryStream(byteArray))
                                    {
                                        StreamReader streamReader = new StreamReader(stream);
                                        System.Xml.XmlReader reader = new XmlTextReader(streamReader);
                                        XmlSerializer serializer = new XmlSerializer(typeof(webParts));
                                        webPartProp = (webParts)serializer.Deserialize(reader);
                                        WebPartTypeName = webPartProp.webPart.metaData.type.name;
                                        stream.Flush();
                                    }
                                    byteArray = null;
                                }

                                string actualWebPartType = GetWebPartShortTypeName(WebPartTypeName);

                                webPartInfo.WebPartTypeFullName = actualWebPartType;
                                webPartInfo.IsClosed = webPart.IsClosed;
                                webPartInfo.IsVisible = webPart.GetType().IsVisible;

                                FileUtility.WriteCsVintoFile(webPartInfoFileName, webPartInfo, ref headerWebPart);
                            }
                        }
                    }

                    Console.WriteLine("[GetWebPartsByWeb] WebPart Usage is exported to the file " + webPartInfoFileName);
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[GetWebPartsByWeb] WebPart Usage is exported to the file " + webPartInfoFileName);

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

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

                }
                catch (Exception ex)
                {
                    ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "Web Part", ex.Message, ex.ToString(), "GetWebPartsByWeb", ex.GetType().ToString(), exceptionCommentsInfo1);
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[EXCEPTION][GetWebPartsByWeb] Exception Message: " + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1);
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("[EXCEPTION][GetWebPartsByWeb] Exception Message: " + ex.Message);
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
            }
        }
        public void SetExceptionCSVWebAppSiteColWebUrls(string webUrl, string sharePointOnline_OR_OnPremise, string userName, string password, string domain)
        {
            ClientContext clientContext = null;
            AuthenticationHelper ObjAuth = new AuthenticationHelper();

            //SharePoint on-premises / SharePoint Online Dedicated => OP (On-Premises)
                if (sharePointOnline_OR_OnPremise.ToUpper() == Constants.OnPremise)
                {
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[START][SetExceptionCSVWebAppSiteColWebUrls] GetNetworkCredentialAuthenticatedContext for WebUrl: " + webUrl);
                    clientContext = ObjAuth.GetNetworkCredentialAuthenticatedContext(webUrl, userName, password, domain);
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[END][SetExceptionCSVWebAppSiteColWebUrls] GetNetworkCredentialAuthenticatedContext for WebUrl: " + webUrl);
                }
                //SharePointOnline  => OL (Online)
                else if (sharePointOnline_OR_OnPremise.ToUpper() == Constants.Online)
                {
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[START][SetExceptionCSVWebAppSiteColWebUrls] GetSharePointOnlineAuthenticatedContextTenant for WebUrl: " + webUrl);
                    clientContext = ObjAuth.GetSharePointOnlineAuthenticatedContextTenant(webUrl, userName, password);
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[END][SetExceptionCSVWebAppSiteColWebUrls] GetSharePointOnlineAuthenticatedContextTenant for WebUrl: " + webUrl);
                }
                if (clientContext != null)
                {
                    Web web = clientContext.Web;
                    clientContext.Load(web, w => w.Url,
                                            w => w.ServerRelativeUrl);
                    clientContext.ExecuteQuery();

                    Site site = clientContext.Site;
                    clientContext.Load(site);
                    clientContext.ExecuteQuery();

                    ExceptionCsv.WebApplication = web.Url.Replace(web.ServerRelativeUrl, "");
                    ExceptionCsv.SiteCollection = site.Url;
                    ExceptionCsv.WebUrl = web.Url;

                }
        }
        public void DownloadFileFromHive(string absoluteFilePath, string outPutFolder, string SharePointOnline_OR_OnPremise = Constants.OnPremise, string UserName = "******", string Password = "******", string Domain = "NA")
        {
            bool headerCSVColumns = false;
            string exceptionCommentsInfo1 = string.Empty;

            GhostingAndUnGhosting_Initialization(outPutFolder, "DOWNLOAD");

            Logger.AddMessageToTraceLogFile(Constants.Logging, "############## DownloadFileFromHive - Trasnformation Utility Execution Started - For Web ##############");
            Console.WriteLine("############## DownloadFileFromHive - 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] ::: DownloadFileFromHive");
            Console.WriteLine("[START] ::: DownloadFileFromHive");

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

            try
            {
                exceptionCommentsInfo1 = "FilePath: " + absoluteFilePath;
                string fileName = Path.GetFileName(absoluteFilePath);

                using (WebClient myWebClient = new WebClient())
                {
                    //SharePoint on-premises / SharePoint Online Dedicated => OP (On-Premises)
                    if (SharePointOnline_OR_OnPremise.ToUpper() == Constants.OnPremise)
                    {
                        myWebClient.Credentials = new System.Net.NetworkCredential(UserName, Password, Domain);
                    }
                    //SharePointOnline  => OL (Online)
                    else if (SharePointOnline_OR_OnPremise.ToUpper() == Constants.Online)
                    {
                        AuthenticationHelper ObjAuth = new AuthenticationHelper();
                        var spoPassword = ObjAuth.GetSecureString(Password);
                        myWebClient.Credentials = new SharePointOnlineCredentials(UserName, spoPassword);
                    }
                    myWebClient.Credentials = new System.Net.NetworkCredential(UserName, Password, Domain);
                    myWebClient.DownloadFile(absoluteFilePath, outPutFolder + "\\" + fileName);
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[DownloadFileFromHive] File is downloaded to the Directory : " + outPutFolder);
                    Console.WriteLine("[DownloadFileFromHive] File is downloaded to the Directory : " + outPutFolder);
                }

                DownloadFileBase objDFBase = new DownloadFileBase();
                objDFBase.GivenFilePath = absoluteFilePath;
                objDFBase.FileName = fileName;
                objDFBase.DownloadedFilePath = outPutFolder + "\\" + fileName;

                objDFBase.WebUrl = Constants.NotApplicable;
                objDFBase.SiteCollection = Constants.NotApplicable;
                objDFBase.WebApplication = Constants.NotApplicable;

                if (objDFBase != null)
                {
                    FileUtility.WriteCsVintoFile(outPutFolder + @"\" + Constants.UnGhosting_DownloadFileReport, objDFBase,
                        ref headerCSVColumns);
                }
            }
            catch (Exception ex)
            {
                Logger.AddMessageToTraceLogFile(Constants.Logging, "[Exception] DownloadFileFromHive. Exception Message: " + ex.Message);
                ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "DownloadFileFromHive", ex.Message, ex.ToString(), "DownloadFileFromHive", ex.GetType().ToString(), exceptionCommentsInfo1);
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[Exception] DownloadFileFromHive. Exception Message: " + ex.Message);
                Console.ForegroundColor = ConsoleColor.Gray;
            }

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

            Logger.AddMessageToTraceLogFile(Constants.Logging, "############## DownloadFileFromHive - Trasnformation Utility Execution Completed for Web ##############");
            Console.WriteLine("############## DownloadFileFromHive - Trasnformation Utility Execution Completed for Web ##############");
        }
        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 ##############");
        }
        public List<ListMigrationBase> ListMigration_ForWEB(string outPutFolder, string WebUrl, string old_ListTitle, string old_ListID, string new_ListTitle, string ActionType = "", string SharePointOnline_OR_OnPremise = Constants.OnPremise, string UserName = "******", string Password = "******", string Domain = "NA")
        {
            bool headerCSVColumns = false;
            string exceptionCommentsInfo1 = string.Empty;
            List<ListMigrationBase> objListBase = new List<ListMigrationBase>();

            ExceptionCsv.WebUrl = WebUrl;

            if (ActionType.ToLower().Trim() == Constants.ActionType_Web.ToLower())
            {
                ListMigration_Initialization(outPutFolder);

                Logger.AddMessageToTraceLogFile(Constants.Logging, "############## List Migration - Trasnformation Utility Execution Started - For Web ##############");
                Console.WriteLine("############## List Migration - 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] ::: ListMigration_ForWEB");
                Console.WriteLine("[START] ::: ListMigration_ForWEB");

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

                Logger.AddMessageToTraceLogFile(Constants.Logging, "[ListMigration_ForWEB] WebUrl is " + WebUrl);
                Console.WriteLine("[ListMigration_ForWEB] WebUrl is " + WebUrl);
            }

            try
            {
                AuthenticationHelper ObjAuth = new AuthenticationHelper();
                ClientContext clientContext = null;
                exceptionCommentsInfo1 = "old_ListTitle: " + old_ListTitle + ", old_ListID: " + old_ListID + ", new_ListTitle: " + new_ListTitle;

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

                if (clientContext != null)
                {
                    Web web = clientContext.Web;

                    List objOldList = null;

                    // Old List is present or not in this web ??
                    if (old_ListTitle.ToString() != "")
                    {
                        objOldList = GetListByTitle(clientContext, old_ListTitle);
                    }
                    else if (old_ListID.ToString() != "")
                    {
                        objOldList = GetListByID(clientContext, old_ListID);
                    }

                    if (objOldList != null)
                    {
                        //We found the old List in this Context
                        clientContext.Load(objOldList);
                        clientContext.ExecuteQuery();

                        //[START] Check if the New List does not exist yet
                        var objNewList = GetListByTitle(clientContext, new_ListTitle, "NEWLIST");
                        if (objNewList != null)
                        {
                            // New List exists already, no further action required
                            Logger.AddMessageToTraceLogFile(Constants.Logging, "[ListMigration_ForWEB] New List " + new_ListTitle + " is already exists in this Web: " + WebUrl);
                            Console.WriteLine("[ListMigration_ForWEB] New List " + new_ListTitle + " is already exists in this Web: " + WebUrl);
                            return null;
                        }
                        //[END] Check if the New List does not exist yet

                        //New List Creation
                        List newList = null;

                        //Create List or Library
                        int intListTemplateType = -1;
                        intListTemplateType = Get_ListTemplateID(objOldList.BaseType.ToString(), (int)objOldList.BaseTemplate);

                        //If List Template ID is Valid
                        if(intListTemplateType >=0)
                        {
                            ListCreationInformation creationInformation = new ListCreationInformation();
                            creationInformation.Title = new_ListTitle;
                            creationInformation.TemplateType = intListTemplateType;

                            newList = clientContext.Web.Lists.Add(creationInformation);
                            clientContext.ExecuteQuery();

                            // Add Columns in List/Library
                            AddField_Using_FieldInternalDetails(clientContext, objOldList, newList);

                            Logger.AddMessageToTraceLogFile(Constants.Logging, "[ListMigration_ForWEB] - List/Library " + new_ListTitle + " is created. BaseTemplate is " + objOldList.BaseType.ToString() + " and TemplateType(OLD) = " + (int)objOldList.BaseTemplate + ", TemplateType(NEW) = " + intListTemplateType);
                            Console.WriteLine("[ListMigration_ForWEB] - List/Library " + new_ListTitle + " is created. BaseTemplate is " + objOldList.BaseType.ToString() + " and TemplateType(OLD) = " + (int)objOldList.BaseTemplate + ", TemplateType(NEW) = " + intListTemplateType);

                            Replace_List_and_Library(clientContext, objOldList, newList);

                            newList.Description = objOldList.Description;
                            newList.LastItemModifiedDate = objOldList.LastItemModifiedDate;

                            newList.Update();
                            clientContext.ExecuteQuery();
                        }
                        else
                        {
                             //Invalid List Template
                        }

                        // Write Output in CSV = After Creation and Migration of New List
                        if (newList != null)
                        {
                            clientContext.Load(newList);
                            clientContext.ExecuteQuery();

                            Logger.AddMessageToTraceLogFile(Constants.Logging, "[ListMigration_ForWEB] New List Title :" + newList.Title + ", ListID: " + newList.Id.ToString() + " created successfully in Web: " + WebUrl);
                            Console.WriteLine("[ListMigration_ForWEB] New List Title:" + newList.Title + ", ListID: " + newList.Id.ToString() + " created successfully in Web: " + WebUrl);

                            ListMigrationBase objLMBase = new ListMigrationBase();
                            objLMBase.Old_ListTitle = objOldList.Title;
                            objLMBase.Old_ListID = objOldList.Id.ToString();
                            objLMBase.Old_ListBaseTemplate = objOldList.BaseTemplate.ToString();

                            objLMBase.New_ListTitle = newList.Title.ToString();
                            objLMBase.New_ListID = newList.Id.ToString();
                            objLMBase.New_ListBaseTemplate = newList.BaseTemplate.ToString();

                            objLMBase.WebUrl = WebUrl;
                            objLMBase.SiteCollection = Constants.NotApplicable;
                            objLMBase.WebApplication = Constants.NotApplicable;

                            objListBase.Add(objLMBase);
                        }
                        else
                        {
                            Logger.AddMessageToTraceLogFile(Constants.Logging, "[ListMigration_ForWEB] The new list " + new_ListTitle + " is not created.");
                            Console.WriteLine("[ListMigration_ForWEB] The new list " + new_ListTitle + " is not created.");
                        }

                        //If ==> This is for WEB
                        if (ActionType.ToString().ToLower() == Constants.ActionType_Web.ToLower())
                        {
                            if (objListBase != null)
                            {
                                FileUtility.WriteCsVintoFile(outPutFolder + @"\" + Constants.ListMigration_Output, ref objListBase,
                                    ref headerCSVColumns);

                                Logger.AddMessageToTraceLogFile(Constants.Logging, "[ListMigration_ForWEB] Writing the List Migration Report(Output CSV) file after creating/migrating a new list. Output CSV Path: " + outPutFolder + @"\" + Constants.ListMigration_Output);
                                Console.WriteLine("[ListMigration_ForWEB] Writing the List Migration Report(Output CSV) file after creating/migrating a new list. Output CSV Path: " + outPutFolder + @"\" + Constants.ListMigration_Output);

                                Logger.AddMessageToTraceLogFile(Constants.Logging, "[END] ::: ListMigration_ForWEB for WebUrl: " + WebUrl);
                                Console.WriteLine("[END] ::: ListMigration_ForWEB for WebUrl: " + WebUrl);

                                Logger.AddMessageToTraceLogFile(Constants.Logging, "############## List Migration - Trasnformation Utility Execution Completed for Web ##############");
                                Console.WriteLine("############## List Migration - Trasnformation Utility Execution Completed for Web ##############");
                            }
                        }
                        //If ==> This is for WEB
                    }
                    else
                    {
                        //Old List does not present in this Context
                        Logger.AddMessageToTraceLogFile(Constants.Logging, "[ListMigration_ForWEB] Old List: " + old_ListTitle + " does not exists in this Web: " + WebUrl);
                        Console.WriteLine("[ListMigration_ForWEB] Old List: " + old_ListTitle + " does not exists in this Web: " + WebUrl);
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "ListMigration", ex.Message, ex.ToString(), "ListMigration_ForWEB", ex.GetType().ToString(), exceptionCommentsInfo1);
                Logger.AddMessageToTraceLogFile(Constants.Logging, "[EXCEPTION] [ListMigration_ForWEB] Exception Message: " + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1);

                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[EXCEPTION] [ListMigration_ForWEB] Exception Message: " + ex.Message + ", ExceptionComments: " + exceptionCommentsInfo1);
                Console.ForegroundColor = ConsoleColor.Gray;
            }
            return objListBase;
        }
        public MasterPageBase ChangeMasterPageForWeb(string outPutFolder, string WebUrl, string NewMasterPageURL, string OldMasterPageURL = "N/A", bool CustomMasterUrlStatus = true, bool MasterUrlStatus = true, string ActionType = Constants.ActionType_Web, string SharePointOnline_OR_OnPremise = Constants.OnPremise, string UserName = "******", string Password = "******", string Domain = "N/A")
        {
            bool headerMasterPage = false;
            List<MasterPageBase> _WriteMasterList = null;
            ExceptionCsv.WebUrl = WebUrl;

            ///<ActionType=="Web"> That means this function running only for a web. We have to write the output in this function only
            ///<Action Type=="SiteCollection"> The function will return object MasterPageBase, and consolidated output will be written in SiteCollection function - ChangeMasterPageForSiteCollection

            //If ==> This is for WEB
            if (ActionType.ToString().ToLower() == Constants.ActionType_Web.ToLower())
            {
                MasterPage_Initialization(outPutFolder);
                _WriteMasterList = new List<MasterPageBase>();

                Logger.AddMessageToTraceLogFile(Constants.Logging, "############## Master Page Trasnformation Utility Execution Started - For Web ##############");
                Console.WriteLine("############## Master Page 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] ENTERING IN FUNCTION ::: ChangeMasterPageForWeb");
                Console.WriteLine("[START] ENTERING IN FUNCTION ::: ChangeMasterPageForWeb");

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

                Logger.AddMessageToTraceLogFile(Constants.Logging, "[ChangeMasterPageForWeb] WebUrl is " + WebUrl);
                Console.WriteLine("[ChangeMasterPageForWeb] WebUrl is " + WebUrl);
            }

            string exceptionCommentsInfo1 = string.Empty;
            MasterPageBase objMaster = new MasterPageBase();

            try
            {
                AuthenticationHelper ObjAuth = new AuthenticationHelper();
                ClientContext clientContext = null;

                //SharePoint on-premises / SharePoint Online Dedicated => OP (On-Premises)
                if (SharePointOnline_OR_OnPremise.ToUpper() == Constants.OnPremise)
                {
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[START][ChangeMasterPageForWeb] ENTERING IN FUNCTION GetNetworkCredentialAuthenticatedContext for WebUrl: " + WebUrl);
                    clientContext = ObjAuth.GetNetworkCredentialAuthenticatedContext(WebUrl, UserName, Password, Domain);
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[END][ChangeMasterPageForWeb] EXIT FROM FUNCTION GetNetworkCredentialAuthenticatedContext for WebUrl: " + WebUrl);

                }
                //SharePointOnline  => OL (Online)
                else if (SharePointOnline_OR_OnPremise.ToUpper() == Constants.Online)
                {
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[START][ChangeMasterPageForWeb] ENTERING IN FUNCTION GetSharePointOnlineAuthenticatedContextTenant for WebUrl: " + WebUrl);
                    clientContext = ObjAuth.GetSharePointOnlineAuthenticatedContextTenant(WebUrl, UserName, Password);
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[END][ChangeMasterPageForWeb] EXIT FROM FUNCTION GetSharePointOnlineAuthenticatedContextTenant for WebUrl: " + WebUrl);
                }

                if (clientContext != null)
                {
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[START][ChangeMasterPageForWeb] ChangeMasterPageForWeb for WebUrl: " + WebUrl);
                    Console.WriteLine("[START][ChangeMasterPageForWeb] ChangeMasterPageForWeb for WebUrl: " + WebUrl);
                    Web web = clientContext.Web;

                    //Load Web to get old Master Page details
                    clientContext.Load(web);
                    clientContext.ExecuteQuery();
                    //Load Web to get old Master Page details

                    //Create New Master Page Relative URL
                    string masterPageUrl = string.Empty;
                    masterPageUrl = GetMasterPageRelativeURL(clientContext, NewMasterPageURL);

                    //Create OldMasterPageURL Relative URL
                    string _strOldMasterPageURL = string.Empty;
                    if (OldMasterPageURL.Trim().ToLower() != Constants.Input_Blank && OldMasterPageURL.Trim().ToLower() != Constants.Input_All)
                    {
                        _strOldMasterPageURL = GetMasterPageRelativeURL(clientContext, OldMasterPageURL);
                    }

                    //Prepare Exception Comments
                    exceptionCommentsInfo1 = "New Master URL: " + masterPageUrl + ", OldMasterPageURL="+_strOldMasterPageURL+", CustomMasterUrlStatus: " + CustomMasterUrlStatus + ", MasterUrlStatus: " + MasterUrlStatus;

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[ChangeMasterPageForWeb]: Input Master Page URL(New) was " + NewMasterPageURL + ". After processing Master Page URL(New) is " + masterPageUrl);
                    Console.WriteLine("[ChangeMasterPageForWeb]: Input Master Page URL(New) was " + NewMasterPageURL + ". After processing Master Page URL(New) is " + masterPageUrl);

                    //Check if new master page is available in Gallery
                    if (Check_MasterPageExistsINGallery(clientContext, masterPageUrl))
                    {
                        Logger.AddMessageToTraceLogFile(Constants.Logging, "[ChangeMasterPageForWeb] Check_MasterPageExistsINGallery: This New Master Page is present in Gallery: " + masterPageUrl);
                        Console.WriteLine("[ChangeMasterPageForWeb] Check_MasterPageExistsINGallery: This New Master Page is present in Gallery: " + masterPageUrl);

                        //Added in Output Object <objMaster> - To Write old Master Page details
                        objMaster.OLD_CustomMasterUrl = web.CustomMasterUrl;
                        objMaster.OLD_MasterUrl = web.MasterUrl;
                        //Added in Output Object <objMaster> - To Write old Master Page details

                        //if (OldMasterPageURL.Trim().ToLower() != Constants.Input_Blank && OldMasterPageURL.Trim().ToLower() != Constants.Input_All)
                        if (OldMasterPageURL.Trim().ToLower() != Constants.Input_All)
                        {
                            bool _UpdateMasterPage = false;

                            if (CustomMasterUrlStatus && _strOldMasterPageURL.ToLower().Trim() == web.CustomMasterUrl.ToString().Trim().ToLower())
                            {
                                web.CustomMasterUrl = masterPageUrl;
                                _UpdateMasterPage = true;

                                Logger.AddMessageToTraceLogFile(Constants.Logging, "[ChangeMasterPageForWeb][OldMasterPageURL !=\"\"]: Updated Custom Master Page " + _strOldMasterPageURL + " with new Master Page URL " + masterPageUrl);
                                Console.WriteLine("[ChangeMasterPageForWeb]:[OldMasterPageURL !=\"\"]: Updated Custom Master Page " + _strOldMasterPageURL + " with new Master Page URL " + masterPageUrl);
                            }
                            else
                            {
                                Logger.AddMessageToTraceLogFile(Constants.Logging, "[ChangeMasterPageForWeb][OldMasterPageURL !=\"\"]: [NO Update in CustomMasterUrl] <INPUT> OLD Custom Master Page " + _strOldMasterPageURL.Trim().ToLower() + ", <WEB> OLD Master Page URL " + web.CustomMasterUrl.ToString().Trim().ToLower());
                                Console.WriteLine("[ChangeMasterPageForWeb]:[OldMasterPageURL !=\"\"]: [NO Update in CustomMasterUrl] <INPUT> OLD Custom Master Page " + _strOldMasterPageURL.Trim().ToLower() + ", <WEB> OLD Master Page URL " + web.CustomMasterUrl.ToString().Trim().ToLower());
                            }

                            if (MasterUrlStatus && _strOldMasterPageURL.ToLower().Trim() == web.MasterUrl.ToString().Trim().ToLower())
                            {
                                web.MasterUrl = masterPageUrl;
                                _UpdateMasterPage = true;

                                Logger.AddMessageToTraceLogFile(Constants.Logging, "[ChangeMasterPageForWeb][OldMasterPageURL !=\"\"]: Updated Master Page " + _strOldMasterPageURL + " with new Master Page URL " + masterPageUrl);
                                Console.WriteLine("[ChangeMasterPageForWeb]:[OldMasterPageURL !=\"\"]: Updated Master Page " + _strOldMasterPageURL + " with new Master Page URL " + masterPageUrl);
                            }
                            else
                            {
                                Logger.AddMessageToTraceLogFile(Constants.Logging, "[ChangeMasterPageForWeb][OldMasterPageURL !=\"\"]: [NO Update in MasterUrl] <INPUT> OLD Master Page " + _strOldMasterPageURL.Trim().ToLower() + ", <WEB> OLD Master Page URL " + web.MasterUrl.ToString().Trim().ToLower());
                                Console.WriteLine("[ChangeMasterPageForWeb]:[OldMasterPageURL !=\"\"]: [NO Update in MasterUrl] <INPUT> OLD Master Page " + _strOldMasterPageURL.Trim().ToLower() + ", <WEB> OLD Master Page URL " + web.MasterUrl.ToString().Trim().ToLower());
                            }

                            if (_UpdateMasterPage)
                            {
                                web.Update();

                                clientContext.Load(web);
                                clientContext.ExecuteQuery();

                                Logger.AddMessageToTraceLogFile(Constants.Logging, "[ChangeMasterPageForWeb][OldMasterPageURL !=\"\"] Changed Master Page for - " + WebUrl + ", New Master Page is " + masterPageUrl);
                                Console.WriteLine("[ChangeMasterPageForWeb][OldMasterPageURL !=\"\"]: Changed Master Page for - " + WebUrl + ", New Master Page is " + masterPageUrl);
                            }
                            else
                            {
                                Logger.AddMessageToTraceLogFile(Constants.Logging, "[ChangeMasterPageForWeb][OldMasterPageURL !=\"\"]: The <Input> OLD MasterPage does not match with this site's old <WEB> master page for WEB: " + WebUrl);
                                Console.WriteLine("[ChangeMasterPageForWeb][OldMasterPageURL !=\"\"]: The <Input> OLD MasterPage does not match with this site's old <WEB> master page for WEB: " + WebUrl);
                            }
                        }
                        else
                        {
                            if (CustomMasterUrlStatus)
                            { web.CustomMasterUrl = masterPageUrl; }

                            if (MasterUrlStatus)
                            { web.MasterUrl = masterPageUrl; }

                            //Update Web
                            web.Update();

                            //Load Web to get Updated Details
                            clientContext.Load(web);
                            clientContext.ExecuteQuery();

                            Logger.AddMessageToTraceLogFile(Constants.Logging, "[ChangeMasterPageForWeb][OldMasterPageURL ==\"\"] Changed Master Page for - " + WebUrl + ", New Master Page is " + masterPageUrl);
                            Console.WriteLine("[ChangeMasterPageForWeb][OldMasterPageURL ==\"\"] Changed Master Page for - " + WebUrl + ", New Master Page is " + masterPageUrl);
                        }

                        //Added in Output Object <objMaster>
                        objMaster.CustomMasterUrl = web.CustomMasterUrl;
                        objMaster.MasterUrl = web.MasterUrl;
                        objMaster.WebApplication = Constants.NotApplicable;
                        objMaster.SiteCollection = Constants.NotApplicable;
                        objMaster.WebUrl = web.Url;
                        //Added in Output Object <objMaster>
                    }
                    else
                    {
                        Logger.AddMessageToTraceLogFile(Constants.Logging, "[ChangeMasterPageForWeb] We have not changed the master page because this new Master Page " + masterPageUrl + " is not present in Gallary, for Web " + WebUrl);
                        Console.WriteLine("[ChangeMasterPageForWeb] We have not changed the master page because this new Master Page " + masterPageUrl + " is not present in Gallary, for Web " + WebUrl);
                    }
                }
                else
                {
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[ChangeMasterPageForWeb] Please check if the site exists and the user has required access permissions on this site: " + WebUrl);
                    Console.WriteLine("[ChangeMasterPageForWeb] Please check if the site exists and the user has required access permissions on this site: " + WebUrl);
                }

                Logger.AddMessageToTraceLogFile(Constants.Logging, "[END] [ChangeMasterPageForWeb] EXIT FROM FUNCTION ChangeMasterPageForWeb for WebUrl: " + WebUrl);
                Console.WriteLine("[END] [ChangeMasterPageForWeb] EXIT FROM FUNCTION ChangeMasterPageForWeb for WebUrl: " + WebUrl);

            }
            catch (Exception ex)
            {
                ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "MasterPage", ex.Message, ex.ToString(), "ChangeMasterPageForWeb", ex.GetType().ToString(), exceptionCommentsInfo1);
                Logger.AddMessageToTraceLogFile(Constants.Logging, "[EXCEPTION][ChangeMasterPageForWeb] Exception Message: " + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1);

                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[EXCEPTION][ChangeMasterPageForWeb] Exception Message: " + ex.Message + " for Web:  " + WebUrl);
                Console.ForegroundColor = ConsoleColor.Gray;
            }

            //If ==> This is for WEB
            if (ActionType.ToString().ToLower() == Constants.ActionType_Web.ToLower())
            {
                if (objMaster != null)
                {
                    _WriteMasterList.Add(objMaster);
                }

                FileUtility.WriteCsVintoFile(outPutFolder +@"\" + Constants.MasterPageUsage, ref _WriteMasterList,
                        ref headerMasterPage);

                Logger.AddMessageToTraceLogFile(Constants.Logging, "[ChangeMasterPageForWeb] Writing the Replace Output CSV file after replacing the master page - FileUtility.WriteCsVintoFile");
                Console.WriteLine("[ChangeMasterPageForWeb] Writing the Replace Output CSV file after replacing the master page - FileUtility.WriteCsVintoFile");

                Logger.AddMessageToTraceLogFile(Constants.Logging, "[END][ChangeMasterPageForWeb] EXIT FROM FUNCTION ChangeMasterPageForWeb for WebUrl: " + WebUrl);
                Console.WriteLine("[END][ChangeMasterPageForWeb] EXIT FROM FUNCTION ChangeMasterPageForWeb for WebUrl: " + WebUrl);

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

            return objMaster;
        }
        public void ChangeMasterPageForSiteCollection(string outPutFolder, string SiteCollectionUrl, string NewMasterPageURL, string OldMasterPageURL = "N/A", bool CustomMasterUrlStatus = true, bool MasterUrlStatus = true, string SharePointOnline_OR_OnPremise = "N/A", string UserName = "******", string Password = "******", string Domain = "N/A")
        {
            string exceptionCommentsInfo1 = string.Empty;
            List<MasterPageBase> _WriteMasterList = new List<MasterPageBase>();
            //Initialized Exception and Logger. Deleted the Master Page Replace Usage File

            MasterPage_Initialization(outPutFolder);

            Logger.AddMessageToTraceLogFile(Constants.Logging, "############## Master Page Trasnformation Utility Execution Started - For Site Collection ##############");
            Console.WriteLine("############## Master Page Trasnformation Utility Execution Started - For Site Collection ##############");

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

            Logger.AddMessageToTraceLogFile(Constants.Logging, "[START] ENTERING IN FUNCTION ::: ChangeMasterPageForSiteCollection");
            Console.WriteLine("[START] ENTERING IN FUNCTION ::: ChangeMasterPageForSiteCollection");

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

            Logger.AddMessageToTraceLogFile(Constants.Logging, "[ChangeMasterPageForSiteCollection] SiteCollectionUrl is " + SiteCollectionUrl);
            Console.WriteLine("[ChangeMasterPageForSiteCollection] SiteCollectionUrl is " + SiteCollectionUrl);

            try
            {
                AuthenticationHelper ObjAuth = new AuthenticationHelper();
                ClientContext clientContext = null;

                //SharePoint on-premises / SharePoint Online Dedicated => OP (On-Premises)
                if (SharePointOnline_OR_OnPremise.ToUpper() == Constants.OnPremise)
                {
                    clientContext = ObjAuth.GetNetworkCredentialAuthenticatedContext(SiteCollectionUrl, UserName, Password, Domain);
                }
                //SharePointOnline  => OL (Online)
                else if (SharePointOnline_OR_OnPremise.ToUpper() == Constants.Online)
                {
                    clientContext = ObjAuth.GetSharePointOnlineAuthenticatedContextTenant(SiteCollectionUrl, UserName, Password);
                }

                if (clientContext != null)
                {
                    bool headerMasterPage = false;
                    MasterPageBase objMPBase = new MasterPageBase();

                    Web rootWeb = clientContext.Web;
                    clientContext.Load(rootWeb);
                    clientContext.ExecuteQuery();

                    //This is for Exception Comments:
                    ExceptionCsv.SiteCollection = SiteCollectionUrl;
                    ExceptionCsv.WebUrl = rootWeb.Url.ToString();
                    exceptionCommentsInfo1 = "<Input>New MasterPage Url = " + NewMasterPageURL + ", <Input> OLD MasterUrl: " + OldMasterPageURL + ", WebUrl: " + rootWeb.Url.ToString() + ", CustomMasterUrlStatus" + CustomMasterUrlStatus + "MasterUrlStatus" + MasterUrlStatus;
                    //This is for Exception Comments:

                    //Root Web
                    objMPBase = ChangeMasterPageForWeb(outPutFolder, rootWeb.Url.ToString(), NewMasterPageURL, OldMasterPageURL, CustomMasterUrlStatus, MasterUrlStatus, Constants.ActionType_SiteCollection, SharePointOnline_OR_OnPremise, UserName, Password, Domain);

                    if (objMPBase != null)
                    {
                        _WriteMasterList.Add(objMPBase);
                    }
                    WebCollection webCollection = rootWeb.Webs;
                    clientContext.Load(webCollection);
                    clientContext.ExecuteQuery();

                    foreach (Web webSite in webCollection)
                    {
                        try
                        {
                            //This is for Exception Comments:
                            ExceptionCsv.SiteCollection = SiteCollectionUrl;
                            ExceptionCsv.WebUrl = webSite.Url.ToString();
                            exceptionCommentsInfo1 = "<Input>New MasterPage Url = " + NewMasterPageURL + ", <Input> OLD MasterUrl: " + OldMasterPageURL + ", WebUrl: " + webSite.Url.ToString() + ", CustomMasterUrlStatus" + CustomMasterUrlStatus + "MasterUrlStatus" + MasterUrlStatus;
                            //This is for Exception Comments:

                            //Web
                            objMPBase = ChangeMasterPageForWeb(outPutFolder, webSite.Url, NewMasterPageURL, OldMasterPageURL, CustomMasterUrlStatus, MasterUrlStatus, Constants.ActionType_SiteCollection, SharePointOnline_OR_OnPremise, UserName, Password, Domain);

                            if (objMPBase != null)
                            { _WriteMasterList.Add(objMPBase); }
                        }
                        catch (Exception ex)
                        {
                            ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "MasterPage", ex.Message, ex.ToString(), "ChangeMasterPageForSiteCollection", ex.GetType().ToString(), exceptionCommentsInfo1);
                            Logger.AddMessageToTraceLogFile(Constants.Logging, "[EXCEPTION] [ChangeMasterPageForSiteCollection] ChangeMasterPageForSiteCollection. Exception Message: " + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1);

                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("[Exception] [ChangeMasterPageForSiteCollection]. Exception Message:" + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1);
                            Console.ForegroundColor = ConsoleColor.Gray;
                        }
                    }

                    if (_WriteMasterList != null)
                    {
                        if (_WriteMasterList.Count > 0)
                        {
                            FileUtility.WriteCsVintoFile(outPutFolder + @"\" + Constants.MasterPageUsage, ref _WriteMasterList, ref headerMasterPage);
                        }
                    }
                }

                Logger.AddMessageToTraceLogFile(Constants.Logging, "[END] [ChangeMasterPageForSiteCollection] EXIT FROM FUNCTION ChangeMasterPageForSiteCollection for SiteCollectionUrl: " + SiteCollectionUrl);
                Console.WriteLine("[END] [ChangeMasterPageForSiteCollection] EXIT FROM FUNCTION ChangeMasterPageForSiteCollection for SiteCollectionUrl: " + SiteCollectionUrl);

                Logger.AddMessageToTraceLogFile(Constants.Logging, "############## Master Page Trasnformation Utility Execution Completed - For Site Collection ##############");
                Console.WriteLine("############## Master Page Trasnformation Utility Execution Completed - For Site Collection ##############");
            }
            catch (Exception ex)
            {
                ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "MasterPage", ex.Message, ex.ToString(), "ChangeMasterPageForSiteCollection", ex.GetType().ToString(), exceptionCommentsInfo1);
                Logger.AddMessageToTraceLogFile(Constants.Logging, "[EXCEPTION] [ChangeMasterPageForSiteCollection] Exception Message: " + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1);

                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[Exception] [ChangeMasterPageForSiteCollection]. Exception Message:" + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1);
                Console.ForegroundColor = ConsoleColor.Gray;
            }
        }