CreateAuthenticatedUserContext() public static method

public static CreateAuthenticatedUserContext ( string domain, string username, SecureString password, string siteUrl ) : ClientContext
domain string
username string
password System.Security.SecureString
siteUrl string
return ClientContext
        public static List <SiteEntity> GetAllSites()
        {
            string url = string.Empty;

            try
            {
                System.Console.ForegroundColor = System.ConsoleColor.Cyan;
                System.Console.WriteLine("Enter any Web/Site Url from the farm for which you want all site collections report:");
                System.Console.ResetColor();
                url = System.Console.ReadLine();
                if (string.IsNullOrEmpty(url))
                {
                    Logger.LogErrorMessage(String.Format("[GenerateSiteCollectionReport] GetAllSites() Url should not be null or empty"), true);
                    ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "SiteCollectionReport", "Url should not be null or empty", "Url should not be null or empty", "GetAllSites()", "NullReferenceException", String.Format("GetAllSites() failed: Error={0}", "Url should not be null or empty"));
                    return(null);
                }
                Logger.LogInfoMessage(String.Format("Preparing to generate report ..."), true);
                using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, url))
                {
                    // Lists all site collections across all web applications...
                    List <SiteEntity> sites = userContext.Web.SiteSearch();
                    return(sites);
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("[GenerateSiteCollectionReport] GetAllSites() failed: Error={0}", ex.Message), true);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "SiteCollectionReport", ex.Message, ex.ToString(), "GetAllSites()", ex.GetType().ToString(), String.Format("GetAllSites() failed: Error={0}", ex.Message));
                return(null);
            }
        }
        /// <summary>
        /// Executes all site collection-level reporting.
        /// Performs special processing for the site collection, then processes all child webs.
        /// </summary>
        /// <param name="siteUrl">URL of the site collection to process</param>
        private static void ProcessSite(string siteUrl, string NonDefMasterFileName)
        {
            try
            {
                Logger.LogInfoMessage(String.Format("Scanning Site: {0} ...", siteUrl), true);

                using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, siteUrl))
                {
                    Site site = userContext.Site;
                    Web  root = userContext.Site.RootWeb;
                    userContext.Load(site);
                    userContext.Load(root);
                    userContext.ExecuteQuery();

                    // Execute processing that is unique to the site and its root web

                    // Execute processing that is common to all webs (including the root web).
                    ProcessWeb(root.Url, true, siteUrl, NonDefMasterFileName);
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("[GenerateNonDefaultMasterPageUsageReport] ProcessSite() failed for {0}: Error={1}", siteUrl, ex.Message), true);
                ExceptionCsv.WriteException(Constants.NotApplicable, siteUrl, Constants.NotApplicable, "NonDefaultMastePageUsageReport", ex.Message, ex.ToString(), "ProcessSite()", ex.GetType().ToString(), String.Format("ProcessSite() failed for {0}: Error={1}", siteUrl, ex.Message));
            }
        }
Beispiel #3
0
        /// <summary>
        /// Executes all web-level transformations related to the custom solution.
        /// Performs special processing for the root web, then recurses through all child webs.
        /// </summary>
        /// <param name="webUrl">Url of web to process</param>
        /// <param name="isRoot">True if this is the root web</param>
        private static void ProcessWeb(string webUrl, bool isRoot, List <ContentTypeSpec> contentTypes, List <SiteColumnSpec> siteColumns)
        {
            try
            {
                Logger.LogInfoMessage(String.Format("Scanning Web: {0} ...", webUrl), false);

                using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, webUrl))
                {
                    Web web = userContext.Web;
                    userContext.Load(web);
                    userContext.ExecuteQuery();

                    ScanWeb(web, contentTypes, siteColumns);

                    ScanLists(web, contentTypes, siteColumns);

                    // Process all child webs
                    web.Context.Load(web.Webs);
                    web.Context.ExecuteQuery();
                    foreach (Web childWeb in web.Webs)
                    {
                        ProcessWeb(childWeb.Url, false, contentTypes, siteColumns);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("ProcessWeb() failed for {0}: Error={1}", webUrl, ex.Message), false);
            }
        }
Beispiel #4
0
        /// <summary>
        /// Testing Method Only
        /// </summary>
        /// <returns></returns>
        public static List <string> GetAllSites2()
        {
            List <string> URL = new List <string>();

            try
            {
                using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, Constants.PortalRootSiteUrl))
                {
                    // Lists all site collections across all web applications...
                    var spoTenant = new Microsoft.Online.SharePoint.TenantAdministration.Tenant(userContext);
                    var getSite   = spoTenant.GetSiteProperties(0, true);
                    userContext.Load(getSite);
                    userContext.ExecuteQuery();
                    foreach (var site in getSite)
                    {
                        URL.Add(site.Url);
                    }
                    return(URL);
                }
            }
            catch
            {
                return(URL);
            }
        }
Beispiel #5
0
        private static void DeleteWebEventReceiver(string webUrl, string eventName, string assemblyName)
        {
            try
            {
                Logger.LogInfoMessage(String.Format("Deleting WEB Event Receiver [{0}] from web {1} ...", eventName, webUrl), true);

                using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, webUrl))
                {
                    Web web = userContext.Web;
                    EventReceiverDefinitionCollection receivers = web.EventReceivers;
                    userContext.Load(web);
                    userContext.Load(receivers);
                    userContext.ExecuteQuery();

                    foreach (EventReceiverDefinition receiver in receivers)
                    {
                        if (receiver.ReceiverName.Equals(eventName, StringComparison.InvariantCultureIgnoreCase) &&
                            receiver.ReceiverAssembly.Equals(assemblyName, StringComparison.InvariantCultureIgnoreCase)
                            )
                        {
                            receiver.DeleteObject();
                            userContext.ExecuteQuery();
                            Logger.LogSuccessMessage(String.Format("Deleted WEB Event Receiver [{0}] from web {1}", eventName, webUrl), false);
                            return;
                        }
                    }
                    Logger.LogErrorMessage(String.Format("DeleteWebEventReceiver() failed for Event Receiver [{0}] on web {1}; Error=Event Receiver not Found.", eventName, webUrl), false);
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("DeleteWebEventReceiver() failed for Event Receiver [{0}] on web {1}; Error={2}", eventName, webUrl, ex.Message), false);
            }
        }
        /// <summary>
        /// Executes all web-level transformations related to the custom solution.
        /// Performs special processing for the root web, then recurses through all child webs.
        /// </summary>
        /// <param name="webUrl">Url of web to process</param>
        /// <param name="isRoot">True if this is the root web</param>
        private static void ProcessWeb(string webUrl, bool isRoot, List <ContentTypeSpec> contentTypes, List <SiteColumnSpec> siteColumns, string siteURL, string CTCFFileName)
        {
            try
            {
                Logger.LogInfoMessage(String.Format("Scanning Web: {0} ...", webUrl), false);

                using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, webUrl))
                {
                    Web web = userContext.Web;
                    userContext.Load(web);
                    userContext.ExecuteQuery();

                    ScanWeb(web, contentTypes, siteColumns, siteURL, CTCFFileName);

                    ScanLists(web, contentTypes, siteColumns, siteURL, CTCFFileName);

                    // Process all child webs
                    web.Context.Load(web.Webs);
                    web.Context.ExecuteQuery();
                    foreach (Web childWeb in web.Webs)
                    {
                        if (childWeb.Url.ToLower().Contains(siteURL.ToLower()))
                        {
                            ProcessWeb(childWeb.Url, false, contentTypes, siteColumns, siteURL, CTCFFileName);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("[GenerateColumnORFieldAndTypeUsageReport] ProcessWeb() failed for {0}: Error={1}", webUrl, ex.Message), false);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, webUrl, "ColumnORFieldAndTypeUsageReport", ex.Message, ex.ToString(), "ProcessWeb()", ex.GetType().ToString(), String.Format("ProcessWeb() failed for {0}: Error={1}", webUrl, ex.Message));
            }
        }
Beispiel #7
0
        /// <summary>
        /// Executes all site collection-level reporting.
        /// Performs special processing for the site collection, then processes all child webs.
        /// </summary>
        /// <param name="siteUrl">URL of the site collection to process</param>
        private static void ProcessSite(string siteUrl)
        {
            try
            {
                Logger.LogInfoMessage(String.Format("Scanning Site: {0} ...", siteUrl), true);

                using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, siteUrl))
                {
                    Site site = userContext.Site;
                    Web  root = userContext.Site.RootWeb;
                    userContext.Load(site);
                    userContext.Load(root);
                    userContext.ExecuteQuery();

                    // Execute processing that is unique to the site and its root web

                    // Execute processing that is common to all webs (including the root web).
                    ProcessWeb(root.Url, true);
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("ProcessSite() failed for {0}: Error={1}", siteUrl, ex.Message), false);
            }
        }
        private static bool DeleteListEventReceiver(string webUrl, string hostId, string eventName, string assemblyName)
        {
            try
            {
                Logger.LogInfoMessage(String.Format("Deleting LIST Event Receiver [{0}] from list [{1}] on web {2} ...", eventName, hostId, webUrl), true);

                using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, webUrl))
                {
                    Web web = userContext.Web;
                    userContext.Load(web);
                    userContext.ExecuteQuery();

                    //ListCollection lists = web.Lists;
                    //userContext.Load(lists);

                    Guid listId = new Guid(hostId);
                    List list   = web.Lists.GetById(listId);
                    userContext.Load(list);
                    userContext.ExecuteQuery();
                    if (list == null)
                    {
                        Logger.LogErrorMessage(String.Format("[DeleteMissingEventReceivers: DeleteListEventReceiver] failed for Event Receiver [{0}] on list [{1}] of web {2}; Error=List not Found.", eventName, hostId, webUrl), true);
                        return(false);
                    }

                    EventReceiverDefinitionCollection receivers = list.EventReceivers;
                    userContext.Load(receivers);
                    userContext.ExecuteQuery();

                    foreach (EventReceiverDefinition receiver in receivers)
                    {
                        if (receiver.ReceiverName.Equals(eventName, StringComparison.InvariantCultureIgnoreCase) &&
                            receiver.ReceiverAssembly.Equals(assemblyName, StringComparison.InvariantCultureIgnoreCase)
                            )
                        {
                            receiver.DeleteObject();
                            userContext.ExecuteQuery();
                            Logger.LogSuccessMessage(String.Format("[DeleteMissingEventReceivers: DeleteListEventReceiver] Deleted LIST Event Receiver [{0}] from list [{1}] on web {2} and output file is present in the path: {3}", eventName, list.Title, webUrl, Environment.CurrentDirectory), true);
                            return(true);
                        }
                    }
                    Logger.LogErrorMessage(String.Format("[DeleteMissingEventReceivers: DeleteListEventReceiver] failed for Event Receiver [{0}] on list [{1}] of web {2}; Error=Event Receiver not Found.", eventName, list.Title, webUrl), true);
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.ToLower().Contains("list does not exist"))
                {
                    Logger.LogErrorMessage(String.Format("[DeleteMissingEventReceivers: DeleteListEventReceiver] failed for Event Receiver [{0}] on list [{1}] of web {2}; Error=List not Found.", eventName, hostId, webUrl), true);
                    ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, webUrl, "EventReceiver", ex.Message, ex.ToString(), "DeleteListEventReceiver",
                                                ex.GetType().ToString(), String.Format("DeleteListEventReceiver() failed for Event Receiver [{0}] on list [{1}] of web {2}; Error=List not Found.", eventName, hostId, webUrl));
                    return(false);
                }
                Logger.LogErrorMessage(String.Format("[DeleteMissingEventReceivers: DeleteListEventReceiver] failed for Event Receiver [{0}] on list [{1}] of web {2}; Error={3}", eventName, hostId, webUrl, ex.Message), true);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, webUrl, "EventReceiver", ex.Message, ex.ToString(), "DeleteListEventReceiver",
                                            ex.GetType().ToString(), String.Format("DeleteListEventReceiver() failed for Event Receiver [{0}] on list [{1}] of web {2}; Error={3}", eventName, hostId, webUrl, ex.Message));
            }
            return(false);
        }
Beispiel #9
0
        private static void DeleteListEventReceiver(string webUrl, string hostId, string eventName, string assemblyName)
        {
            try
            {
                Logger.LogInfoMessage(String.Format("Deleting LIST Event Receiver [{0}] from list [{1}] on web {2} ...", eventName, hostId, webUrl), true);

                using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, webUrl))
                {
                    Web web = userContext.Web;
                    userContext.Load(web);
                    userContext.ExecuteQuery();

                    //ListCollection lists = web.Lists;
                    //userContext.Load(lists);

                    Guid listId = new Guid(hostId);
                    List list   = web.Lists.GetById(listId);
                    userContext.Load(list);
                    userContext.ExecuteQuery();
                    if (list == null)
                    {
                        Logger.LogErrorMessage(String.Format("DeleteListEventReceiver() failed for Event Receiver [{0}] on list [{1}] of web {2}; Error=List not Found.", eventName, hostId, webUrl), false);
                        return;
                    }

                    EventReceiverDefinitionCollection receivers = list.EventReceivers;
                    userContext.Load(receivers);
                    userContext.ExecuteQuery();

                    foreach (EventReceiverDefinition receiver in receivers)
                    {
                        if (receiver.ReceiverName.Equals(eventName, StringComparison.InvariantCultureIgnoreCase) &&
                            receiver.ReceiverAssembly.Equals(assemblyName, StringComparison.InvariantCultureIgnoreCase)
                            )
                        {
                            receiver.DeleteObject();
                            userContext.ExecuteQuery();
                            Logger.LogSuccessMessage(String.Format("Deleted LIST Event Receiver [{0}] from list [{1}] on web {2}", eventName, list.Title, webUrl), false);
                            return;
                        }
                    }
                    Logger.LogErrorMessage(String.Format("DeleteListEventReceiver() failed for Event Receiver [{0}] on list [{1}] of web {2}; Error=Event Receiver not Found.", eventName, list.Title, webUrl), false);
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.ToLower().Contains("list does not exist"))
                {
                    Logger.LogErrorMessage(String.Format("DeleteListEventReceiver() failed for Event Receiver [{0}] on list [{1}] of web {2}; Error=List not Found.", eventName, hostId, webUrl), false);
                    return;
                }
                Logger.LogErrorMessage(String.Format("DeleteListEventReceiver() failed for Event Receiver [{0}] on list [{1}] of web {2}; Error={3}", eventName, hostId, webUrl, ex.Message), false);
            }
        }
Beispiel #10
0
        /// <summary>
        /// Testing Method Only
        /// </summary>
        /// <returns></returns>
        public static List <SiteEntity> GetAllSites3()
        {
            try
            {
                using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, Constants.PortalRootSiteUrl))
                {
                    // Lists all site collections across all web applications...

                    //WebTemplateCollection wtc= userContext.Web.GetAvailableWebTemplates(1033, true);

                    WebTemplateCollection wtc = userContext.Site.GetWebTemplates(1033, 0);


                    userContext.Load(wtc);
                    userContext.ExecuteQuery();
                    List <string> template = new List <string>();

                    foreach (WebTemplate wt in wtc)
                    {
                        template.Add(wt.Name);
                    }

                    List <SiteEntity> sites = new List <SiteEntity>();
                    foreach (string templateKeyword in template)
                    {
                        try
                        {
                            sites.AddRange(userContext.Web.SiteSearch(templateKeyword, true));
                        }
                        catch (Exception ex)
                        {
                            Logger.LogErrorMessage(String.Format("GetAllSites() failed: Error={0}", ex.Message), false);
                        }
                    }

                    List <string> siteurl = new List <string>();
                    foreach (SiteEntity site in sites)
                    {
                        if (!siteurl.Contains(site.Url))
                        {
                            siteurl.Add(site.Url);
                        }
                    }
                    //List<SiteEntity> sites = userContext.Web.SiteSearch();
                    return(sites);
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("GetAllSites() failed: Error={0}", ex.Message), false);
                return(null);
            }
        }
Beispiel #11
0
        private static string GetPageRelativeURL(string WebUrl, string PageUrl)
        {
            ClientContext clientContext    = null;
            string        _relativePageUrl = string.Empty;
            Web           web = null;

            try
            {
                if (WebUrl != "" || PageUrl != "")
                {
                    using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, WebUrl))
                    {
                        web = userContext.Web;
                        userContext.Load(web);
                        userContext.ExecuteQuery();
                        clientContext = userContext;

                        Logger.LogInfoMessage("[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.LogInfoMessage("[GetPageRelativeURL] RelativePageUrl Framed: " + _relativePageUrl);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Console.ForegroundColor = System.ConsoleColor.Red;
                Logger.LogErrorMessage("[GetPageRelativeURL] Exception Message: " + ex.Message);
                System.Console.ResetColor();
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, WebUrl, "ReplaceWebPart", ex.Message, ex.ToString(), "GetPageRelativeURL()", ex.GetType().ToString());
            }

            return(_relativePageUrl);
        }
Beispiel #12
0
 public static List <SiteEntity> GetAllSites(string webAppUrl)
 {
     try
     {
         using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, webAppUrl))
         {
             // Lists all site collections across all web applications...
             List <SiteEntity> sites = userContext.Web.SiteSearch();
             return(sites);
         }
     }
     catch (Exception ex)
     {
         Logger.LogErrorMessage(String.Format("GetAllSites() failed: Error={0}", ex.Message), false);
         return(null);
     }
 }
 public static List <SiteEntity> GetAllSites(string webAppUrl)
 {
     try
     {
         using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, webAppUrl))
         {
             // Lists all site collections across all web applications...
             List <SiteEntity> sites = userContext.Web.SiteSearch();
             return(sites);
         }
     }
     catch (Exception ex)
     {
         Logger.LogErrorMessage(String.Format("[GenerateSiteCollectionReport] GetAllSites() failed: Error={0}", ex.Message), false);
         ExceptionCsv.WriteException(webAppUrl, Constants.NotApplicable, Constants.NotApplicable, "SiteCollectionReport", ex.Message, ex.ToString(), "GetAllSites()", ex.GetType().ToString(), String.Format("GetAllSites() failed: Error={0}", ex.Message));
         return(null);
     }
 }
Beispiel #14
0
        private static string GetPageRelativeURL(string WebUrl, string PageUrl, string UserName = "******", string Password = "******", string Domain = "N/A")
        {
            string _relativePageUrl = string.Empty;

            try
            {
                if (WebUrl != "" || PageUrl != "")
                {
                    using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, WebUrl))
                    {
                        Web _Web = userContext.Web;
                        userContext.Load(_Web);
                        userContext.ExecuteQuery();

                        Logger.LogInfoMessage("Web.ServerRelativeUrl: " + _Web.ServerRelativeUrl + " And PageUrl: " + PageUrl, true);

                        //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.LogInfoMessage("RelativePageUrl Framed: " + _relativePageUrl, false);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage("[DeleteMissingWebparts: GetPageRelativeURL]. Exception Message: " + ex.Message
                                       + ", Exception Comments: Exception occured while reading page relive url", true);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, WebUrl, "Webpart", ex.Message,
                                            ex.ToString(), "GetPageRelativeURL", ex.GetType().ToString(), Constants.NotApplicable);
            }

            return(_relativePageUrl);
        }
Beispiel #15
0
        private static void ProcessSite(string siteUrl, BannerOperation operationToPerform, string cdnAbsoluteUrl)
        {
            try
            {
                Logger.LogInfoMessage(String.Format("Processing Site: {0} ...", siteUrl), true);

                using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, siteUrl))
                {
                    Site site = userContext.Site;
                    Web  root = userContext.Site.RootWeb;
                    userContext.Load(site);
                    userContext.Load(root);
                    userContext.ExecuteQuery();

                    switch (operationToPerform)
                    {
                    case BannerOperation.Add:
                        // We remove any existing items before adding the new one
                        DeleteJsLinks(userContext, site);
                        AddJsLinks(userContext, site, cdnAbsoluteUrl);
                        break;

                    case BannerOperation.Remove:
                        DeleteJsLinks(userContext, site);
                        break;

                    case BannerOperation.None:
                    default:
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("ProcessSite() failed for site [{0}]: Error={1}", siteUrl, ex.Message), false);
                ExceptionCsv.WriteException(
                    "N/A", siteUrl, "N/A",
                    "MaintenanceBanner",
                    ex.Message, ex.ToString(), "ProcessSite", ex.GetType().ToString(),
                    String.Format("ProcessSite() failed for site [{0}]", siteUrl)
                    );
            }
        }
Beispiel #16
0
        public static void SetExceptionCSVWebAppSiteColWebUrls(string webUrl)
        {
            ClientContext clientContext = null;
            Web           web           = null;

            using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, webUrl))
            {
                web = userContext.Web;
                userContext.Load(web, w => w.Url,
                                 w => w.ServerRelativeUrl);
                userContext.ExecuteQuery();
                clientContext = userContext;

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

                ExceptionCsv.WebApplication = web.Url.Replace(web.ServerRelativeUrl, "");
                ExceptionCsv.SiteCollection = site.Url;
                ExceptionCsv.WebUrl         = web.Url;
            }
        }
        private static bool DeleteSiteEventReceiver(string siteUrl, string eventName, string assemblyName)
        {
            try
            {
                Logger.LogInfoMessage(String.Format("Deleting SITE Event Receiver [{0}] from site {1} ...", eventName, siteUrl), true);

                using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, siteUrl))
                {
                    Site site = userContext.Site;
                    EventReceiverDefinitionCollection receivers = site.EventReceivers;
                    userContext.Load(site);
                    userContext.Load(receivers);
                    userContext.ExecuteQuery();

                    foreach (EventReceiverDefinition receiver in receivers)
                    {
                        if (receiver.ReceiverName.Equals(eventName, StringComparison.InvariantCultureIgnoreCase) &&
                            receiver.ReceiverAssembly.Equals(assemblyName, StringComparison.InvariantCultureIgnoreCase)
                            )
                        {
                            receiver.DeleteObject();
                            userContext.ExecuteQuery();
                            Logger.LogSuccessMessage(String.Format("[DeleteMissingEventReceivers: DeleteSiteEventReceiver] Deleted SITE Event Receiver [{0}] from site {1} and output file is present in the path: {2}", eventName, siteUrl, Environment.CurrentDirectory), true);
                            return(true);
                        }
                    }
                    Logger.LogErrorMessage(String.Format("[DeleteMissingEventReceivers: DeleteSiteEventReceiver] DeleteSiteEventReceiver() failed for Event Receiver [{0}] on site {1}; Error=Event Receiver not Found.", eventName, siteUrl), true);
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("[DeleteMissingEventReceivers: DeleteSiteEventReceiver] failed for Event Receiver [{0}] on site {1}; Error={2}", eventName, siteUrl, ex.Message), true);
                ExceptionCsv.WriteException(Constants.NotApplicable, siteUrl, Constants.NotApplicable, "EventReceiver", ex.Message, ex.ToString(), "DeleteSiteEventReceiver",
                                            ex.GetType().ToString(), String.Format("[DeleteMissingEventReceivers: DeleteSiteEventReceiver] failed for Event Receiver [{0}] on site {1}", eventName, siteUrl));
                return(false);
            }
            return(false);
        }
        /// <summary>
        /// Executes all site collection-level reporting.
        /// Performs special processing for the site collection, then processes all child webs.
        /// </summary>
        /// <param name="siteUrl">URL of the site collection to process</param>
        private static void ProcessSite(string siteUrl, List <ContentTypeSpec> contentTypes, List <SiteColumnSpec> siteColumns, string CTCFFileName)
        {
            try
            {
                Logger.LogInfoMessage(String.Format("Scanning Site: {0} ...", siteUrl), true);

                using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, siteUrl))
                {
                    Site site = userContext.Site;
                    Web  root = userContext.Site.RootWeb;
                    userContext.Load(site);
                    userContext.Load(root);
                    userContext.ExecuteQuery();

                    // Execute processing that is common to all webs (including the root web).
                    ProcessWeb(root.Url, true, contentTypes, siteColumns, siteUrl, CTCFFileName);
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("[GenerateColumnORFieldAndTypeUsageReport] ProcessSite() failed for {0}: Error={1}", siteUrl, ex.Message), false);
                ExceptionCsv.WriteException(Constants.NotApplicable, siteUrl, Constants.NotApplicable, "ColumnORFieldAndTypeUsageReport", ex.Message, ex.ToString(), "ProcessSite()", ex.GetType().ToString(), String.Format("ProcessSite() failed for {0}: Error={1}", siteUrl, ex.Message));
            }
        }
Beispiel #19
0
        /// <summary>
        /// Executes all web-level transformations related to the custom solution.
        /// Performs special processing for the root web, then recurses through all child webs.
        /// </summary>
        /// <param name="webUrl">Url of web to process</param>
        /// <param name="isRoot">True if this is the root web</param>
        private static void ProcessWeb(string webUrl, bool isRoot)
        {
            try
            {
                Logger.LogInfoMessage(String.Format("Scanning Web: {0} ...", webUrl), false);

                using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, webUrl))
                {
                    Web web = userContext.Web;
                    userContext.Load(web);
                    userContext.Load(web.AllProperties);
                    userContext.ExecuteQuery();

                    if (web.MasterUrl.ToLowerInvariant().Contains("seattle.master") == false)
                    {
                        Logger.LogSuccessMessage(String.Format("FOUND: System Master Page setting (Prop=MasterUrl) of web {0} is {1}", web.Url, web.MasterUrl), true);
                    }
                    if (web.CustomMasterUrl.ToLowerInvariant().Contains("seattle.master") == false)
                    {
                        Logger.LogSuccessMessage(String.Format("FOUND: Site Master Page setting (Prop=CustomMasterUrl) of web {0} is {1}", web.Url, web.CustomMasterUrl), true);
                    }

                    // Process all child webs
                    web.Context.Load(web.Webs);
                    web.Context.ExecuteQuery();
                    foreach (Web childWeb in web.Webs)
                    {
                        ProcessWeb(childWeb.Url, false);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("ProcessWeb() failed for {0}: Error={1}", webUrl, ex.Message), false);
            }
        }
Beispiel #20
0
        private static void DeleteMissingFeature(MissingFeaturesInput missingFeature)
        {
            if (missingFeature == null)
            {
                return;
            }

            string featureId = missingFeature.FeatureId;
            string targetUrl = string.Empty;;

            if (missingFeature.Scope == "Site")
            {
                targetUrl = missingFeature.SiteCollection;
            }
            else
            {
                targetUrl = missingFeature.WebUrl;
            }

            if (targetUrl.IndexOf("http", StringComparison.InvariantCultureIgnoreCase) < 0)
            {
                // ignore the header row in case it is still present
                return;
            }

            Guid featureDefinitionId = new Guid(featureId);

            try
            {
                Logger.LogInfoMessage(String.Format("Processing Feature {0} on {1} {2} ...", featureId, missingFeature.Scope, targetUrl), true);

                using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, targetUrl))
                {
                    //RemoveFeature(userContext, featureDefinitionId);
                    switch (missingFeature.Scope.ToLower())
                    {
                    case "site":
                        userContext.Load(userContext.Site);
                        userContext.ExecuteQuery();
                        if (RemoveFeatureFromSite(userContext, featureDefinitionId))
                        {
                            Logger.LogSuccessMessage(String.Format("Deleted Feature {0} from site {1}", featureDefinitionId.ToString(), userContext.Site.Url), false);
                        }
                        else
                        {
                            Logger.LogErrorMessage(String.Format("Could not delete site Feature {0}; feature not found", featureDefinitionId.ToString()), false);
                        }
                        break;

                    case "web":
                        userContext.Load(userContext.Web);
                        userContext.ExecuteQuery();
                        if (RemoveFeatureFromWeb(userContext, featureDefinitionId))
                        {
                            Logger.LogSuccessMessage(String.Format("Deleted Feature {0} from web {1}", featureDefinitionId.ToString(), userContext.Web.Url), false);
                        }
                        else
                        {
                            Logger.LogErrorMessage(String.Format("Could not delete web Feature {0}; feature not found", featureDefinitionId.ToString()), false);
                        }
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("DeleteMissingFeature() failed for Feature {0} on {1} {2}; Error={3}", featureDefinitionId.ToString(), missingFeature.Scope, targetUrl, ex.Message), false);
            }
        }
        public static bool AddWebPartToPage(string webUrl, string configuredWebPartFileName, string configuredWebPartXmlFilePath, string webPartZoneIndex, string webPartZoneID, string serverRelativePageUrl, string outPutDirectory, string sourceWebPartId = "")
        {
            bool          isWebPartAdded = false;
            Web           web            = null;
            WebPartEntity webPart        = new WebPartEntity();
            ClientContext clientContext  = null;
            string        webPartXml     = string.Empty;

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

            try
            {
                using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, webUrl))
                {
                    web = userContext.Web;
                    userContext.Load(web);
                    userContext.ExecuteQuery();
                    clientContext = userContext;

                    webPart.WebPartIndex = Convert.ToInt32(webPartZoneIndex);

                    Logger.LogInfoMessage("[AddWebPartToPage] Successful authentication", false);

                    Logger.LogInfoMessage("[AddWebPartToPage] Checking Out File ...", false);

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

                    Logger.LogInfoMessage("[AddWebPartToPage] Successful authentication", Constants.Logging);

                    Logger.LogInfoMessage("[AddWebPartToPage] Checking for web part in the Web Part Gallery", Constants.Logging);

                    //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.LogInfoMessage(
                                    "[AddWebPart] List Details " + serverRelativePageUrl + ". " +
                                    "Force Check Out: " + forceCheckOut +
                                    "Enable Versioning: " + enableVersioning +
                                    "Enable Minor Versions: " + enableMinorVersions +
                                    "Enable Moderation: " + enableModeration +
                                    "Draft Version Visibility: " + dVisibility);

                                Logger.LogInfoMessage(
                                    "[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)
                            {
                                System.Console.ForegroundColor = System.ConsoleColor.Red;
                                Logger.LogErrorMessage("[AddWebPartToPage] Exception Message: " + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1);
                                System.Console.ResetColor();
                                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, ExceptionCsv.WebUrl, "AddWebPart", ex.Message, ex.ToString(), "AddWebPartToPage()", ex.GetType().ToString(), exceptionCommentsInfo1);
                            }
                        }


                        try
                        {
                            Logger.LogInfoMessage("[AddWebPartToPage] Adding web part to the page at " + serverRelativePageUrl);
                            isWebPartAdded = AddWebPartt(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
                            }
                        }
                    }

                    else
                    {
                        Logger.LogInfoMessage("[AddWebPartToPage]. Target Webpart should be present in the site for the webpart to be added", Constants.Logging);
                        throw new Exception("Target Webpart should be present in the site for the webpart to be added");
                    }
                }
            }
            catch (Exception ex)
            {
                System.Console.ForegroundColor = System.ConsoleColor.Red;
                Logger.LogErrorMessage("[AddWebPartToPage] Exception Message: " + ex.Message);
                System.Console.ResetColor();
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, ExceptionCsv.WebUrl, "AddWebPart", ex.Message, ex.ToString(), "AddWebPartToPage()", ex.GetType().ToString());
                return(isWebPartAdded);
            }
            return(isWebPartAdded);
        }
Beispiel #22
0
        private static void DeleteMissingFile(MissingWorkflowAssociationsInput missingFile, string csvFile)
        {
            bool headerWAOP = false;
            MissingWorkflowAssociationsOutput objWFOP = new MissingWorkflowAssociationsOutput();

            if (missingFile == null)
            {
                return;
            }

            string wfFileDirName = missingFile.DirName;
            string wfFileName    = missingFile.LeafName;
            string webAppUrl     = missingFile.WebApplication;
            string webUrl        = missingFile.WebUrl;

            objWFOP.DirName           = wfFileDirName;
            objWFOP.LeafName          = wfFileName;
            objWFOP.WebApplication    = webAppUrl;
            objWFOP.WebUrl            = webUrl;
            objWFOP.SiteCollection    = missingFile.SiteCollection;
            objWFOP.ExecutionDateTime = DateTime.Now.ToString();

            if (webUrl.IndexOf("http", StringComparison.InvariantCultureIgnoreCase) < 0)
            {
                // ignore the header row in case it is still present
                return;
            }

            // clean the inputs
            if (wfFileDirName.EndsWith("/"))
            {
                wfFileDirName = wfFileDirName.TrimEnd(new char[] { '/' });
            }
            if (!wfFileDirName.StartsWith("/"))
            {
                wfFileDirName = "/" + wfFileDirName;
            }
            if (wfFileName.StartsWith("/"))
            {
                wfFileName = wfFileName.TrimStart(new char[] { '/' });
            }
            if (webUrl.EndsWith("/"))
            {
                webUrl = webUrl.TrimEnd(new char[] { '/' });
            }
            if (webAppUrl.EndsWith("/"))
            {
                webAppUrl = webAppUrl.TrimEnd(new char[] { '/' });
            }

            // e.g., "https://ppeTeams.contoso.com/sites/test/_catalogs/masterpage/Sample.master"
            string serverRelativeFilePath = wfFileDirName + '/' + wfFileName;

            try
            {
                Logger.LogInfoMessage(String.Format("\n\n[DeleteMissingWorkflowAssociations: DeleteMissingFile] Processing Workflow Association File: {0} ...", webAppUrl + serverRelativeFilePath), true);

                // we have to open the web because Helper.DeleteFileByServerRelativeUrl() needs to update the web in order to commit the change
                using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, webUrl))
                {
                    Web web = userContext.Web;
                    userContext.Load(web);
                    userContext.ExecuteQuery();

                    if (Helper.DeleteFileByServerRelativeUrl(web, serverRelativeFilePath))
                    {
                        Logger.LogInfoMessage(wfFileName + " deleted successfully and output file is present in the path: " + Environment.CurrentDirectory);
                        objWFOP.Status = Constants.Success;
                    }
                    else
                    {
                        objWFOP.Status = Constants.Failure;
                    }
                    //Logger.LogInfoMessage(targetFile.Name + " deleted successfully");
                }

                if (System.IO.File.Exists(csvFile))
                {
                    headerWAOP = true;
                }
                FileUtility.WriteCsVintoFile(csvFile, objWFOP, ref headerWAOP);
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("[DeleteMissingWorkflowAssociations: DeleteMissingFile] failed for {0}: Error={1}", serverRelativeFilePath, ex.Message), true);
                ExceptionCsv.WriteException(webAppUrl, Constants.NotApplicable, webUrl, "WorkflowAssociations", ex.Message, ex.ToString(), "DeleteMissingFile",
                                            ex.GetType().ToString(), String.Format("DeleteMissingWorkflowAssociationFile() failed for {0}: Error={1}", serverRelativeFilePath, ex.Message));
            }
        }
        public static bool ProcessWebUrl(string webUrl, DataRow drMasterPage, bool replaceMasterUrl, bool replaceCustomMasterUrl, bool replaceBothMaserUrls)
        {
            bool   result            = false;
            string customMasterPage  = string.Empty;
            string oobMasterPage     = string.Empty;
            string serverRelativeUrl = string.Empty;
            Site   site;
            Web    web;
            bool   header = false;

            try
            {
                ReadCustomOOBMasterPages(ref customMasterPage, ref oobMasterPage);
                if (string.IsNullOrEmpty(customMasterPage) || string.IsNullOrEmpty(oobMasterPage))
                {
                    result = false;
                }
                else
                {
                    if (!customMasterPage.EndsWith(".master"))
                    {
                        customMasterPage = string.Empty;
                        Logger.LogErrorMessage("Invalid extension of Custom Master Page.");
                        result = false;
                    }
                    if (!oobMasterPage.EndsWith(".master"))
                    {
                        oobMasterPage = string.Empty;
                        Logger.LogErrorMessage("Invalid extension of OOB Master Page.");
                        result = false;
                    }
                    else
                    {
                        using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, webUrl))
                        {
                            try
                            {
                                site = userContext.Site;
                                web  = userContext.Web;
                                userContext.Load(site);
                                userContext.Load(web);
                                userContext.ExecuteQuery();
                                serverRelativeUrl = site.ServerRelativeUrl;

                                if (web.MasterUrl.ToLower().Contains(customMasterPage) || web.CustomMasterUrl.ToLower().Contains(customMasterPage))
                                {
                                    result = ReplaceMasterUrl(userContext, oobMasterPage, serverRelativeUrl, replaceMasterUrl, replaceCustomMasterUrl, replaceBothMaserUrls);
                                }
                            }
                            catch (Exception ex)
                            {
                                Logger.LogErrorMessage("[ReplaceMasterpage: ProcessWebUrl]. Exception Message: " + ex.Message, true);
                                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, webUrl, "ReplaceMasterPage", ex.Message, ex.ToString(), "ProcessWebUrl()", ex.GetType().ToString());
                            }
                        }
                    }
                }
                ReplaceMasterPageStatusBase objOutputBase = new ReplaceMasterPageStatusBase();
                objOutputBase.WebApplication    = Constants.NotApplicable;
                objOutputBase.SiteCollection    = Constants.NotApplicable;
                objOutputBase.WebUrl            = webUrl;
                objOutputBase.ExecutionDateTime = DateTime.Now.ToString();

                if (!string.IsNullOrEmpty(customMasterPage))
                {
                    objOutputBase.CustomMasterPageUrl = customMasterPage;
                }
                else
                {
                    objOutputBase.CustomMasterPageUrl = Constants.NotApplicable;
                }

                if (!string.IsNullOrEmpty(oobMasterPage))
                {
                    objOutputBase.OOTBMasterPageUrl = oobMasterPage;
                }
                else
                {
                    objOutputBase.OOTBMasterPageUrl = Constants.NotApplicable;
                }

                if (result)
                {
                    objOutputBase.Status = Constants.Success;
                }
                else
                {
                    objOutputBase.Status = Constants.Failure;
                }

                if (!System.IO.File.Exists(outputPath + @"\" + Constants.ReplaceMasterPageFileName + timeStamp + Constants.CSVExtension))
                {
                    header = false;
                }
                else
                {
                    header = true;
                }
                FileUtility.WriteCsVintoFile(outputPath + @"\" + Constants.ReplaceMasterPageFileName + timeStamp + Constants.CSVExtension, objOutputBase, ref header);
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage("[ReplaceMasterpage: ProcessWebUrl]. Exception Message: " + ex.Message, true);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, webUrl, "ReplaceMasterPage", ex.Message, ex.ToString(), "ProcessWebUrl()", ex.GetType().ToString());
            }
            finally
            {
                site = null;
                web  = null;
            }
            return(result);
        }
        /// <summary>
        /// Executes all web-level transformations related to the custom solution.
        /// Performs special processing for the root web, then recurses through all child webs.
        /// </summary>
        /// <param name="webUrl">Url of web to process</param>
        /// <param name="isRoot">True if this is the root web</param>
        private static void ProcessWeb(string webUrl, bool isRoot, string SiteURL, string NonDefMasterFileName)
        {
            try
            {
                string masterUrl         = string.Empty;
                string customMasterurl   = string.Empty;
                string WebUrl            = string.Empty;
                bool   IsMasterUrl       = false;
                bool   IsCustomMasterUrl = false;

                NonDefaultMasterpageOutput objMasterPageOutput = new NonDefaultMasterpageOutput();

                Logger.LogInfoMessage(String.Format("Scanning Web: {0} ...", webUrl), false);

                using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, webUrl))
                {
                    Web web = userContext.Web;
                    userContext.Load(web);
                    userContext.Load(web.AllProperties);
                    userContext.ExecuteQuery();

                    if (web.MasterUrl.ToLowerInvariant().Contains("seattle.master") == false)
                    {
                        Logger.LogSuccessMessage(String.Format("FOUND: System Master Page setting (Prop=MasterUrl) of web {0} is {1}", web.Url, web.MasterUrl), true);
                        IsMasterUrl = true;
                    }
                    else
                    {
                        IsMasterUrl = false;
                    }

                    if (web.CustomMasterUrl.ToLowerInvariant().Contains("seattle.master") == false)
                    {
                        Logger.LogSuccessMessage(String.Format("FOUND: Site Master Page setting (Prop=CustomMasterUrl) of web {0} is {1}", web.Url, web.CustomMasterUrl), true);
                        IsCustomMasterUrl = true;
                    }
                    else
                    {
                        IsCustomMasterUrl = false;
                    }

                    objMasterPageOutput.MasterUrl       = web.MasterUrl;
                    objMasterPageOutput.CustomMasterUrl = web.CustomMasterUrl;
                    objMasterPageOutput.WebUrl          = web.Url;
                    objMasterPageOutput.SiteCollection  = SiteURL;

                    if (IsMasterUrl || IsCustomMasterUrl)
                    {
                        FileUtility.WriteCsVintoFile(NonDefMasterFileName, objMasterPageOutput, ref headermasterPage);
                    }

                    // Process all child webs
                    web.Context.Load(web.Webs);
                    web.Context.ExecuteQuery();
                    foreach (Web childWeb in web.Webs)
                    {
                        if (childWeb.Url.ToLower().Contains(SiteURL.ToLower()))
                        {
                            ProcessWeb(childWeb.Url, false, SiteURL, NonDefMasterFileName);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("[GenerateNonDefaultMasterPageUsageReport] ProcessWeb() failed for {0}: Error={1}", webUrl, ex.Message), false);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, webUrl, "NonDefaultMastePageUsageReport", ex.Message, ex.ToString(), "ProcessWeb()", ex.GetType().ToString(), String.Format("ProcessWeb() failed for {0}: Error={1}", webUrl, ex.Message));
            }
        }
Beispiel #25
0
        public static string GetWebPartProperties(string pageUrl, string StorageKey, string webUrl, string outPutDirectory)
        {
            string webPartPropertiesFileName = string.Empty;

            ClientContext clientContext = new ClientContext(webUrl);

            string webPartXml = string.Empty;

            ExceptionCsv.WebUrl = webUrl;
            string exceptionCommentsInfo1 = string.Empty;
            Web    web = null;

            try
            {
                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;


                using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, webUrl))
                {
                    web = userContext.Web;
                    userContext.Load(web);
                    userContext.ExecuteQuery();
                    clientContext = userContext;

                    Logger.LogInfoMessage("[GetWebPartProperties] Retrieving WebPart Properties for StorageKey: " + StorageKey.ToString() + " in the Page" + pageUrl);

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

                    Logger.LogInfoMessage("[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.LogSuccessMessage("[GetWebPartProperties] Successfully retreived Web Part Properties", true);

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

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

                    Logger.LogSuccessMessage("[GetWebPartProperties] WebPart Properties in xml format is exported to the file " + webPartPropertiesFileName, true);
                }
            }
            catch (Exception ex)
            {
                System.Console.ForegroundColor = System.ConsoleColor.Red;
                Logger.LogErrorMessage("[GetWebPartProperties] Exception Message: " + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1);
                System.Console.ResetColor();
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, ExceptionCsv.WebUrl, "WebPartProperties", ex.Message, ex.ToString(), "GetWebPartProperties()", ex.GetType().ToString());
            }

            return(webPartPropertiesFileName);
        }
Beispiel #26
0
        private static void DeleteMissingFile(MissingSetupFilesInput missingFile)
        {
            if (missingFile == null)
            {
                return;
            }

            string setupFileDirName = missingFile.SetupFileDirName;
            string setupFileName    = missingFile.SetupFileName;
            string webAppUrl        = missingFile.WebApplication;
            string webUrl           = missingFile.WebUrl;

            if (webUrl.IndexOf("http", StringComparison.InvariantCultureIgnoreCase) < 0)
            {
                // ignore the header row in case it is still present
                return;
            }

            // clean the inputs
            if (setupFileDirName.EndsWith("/"))
            {
                setupFileDirName = setupFileDirName.TrimEnd(new char[] { '/' });
            }
            if (setupFileName.StartsWith("/"))
            {
                setupFileName = setupFileName.TrimStart(new char[] { '/' });
            }
            if (webUrl.EndsWith("/"))
            {
                webUrl = webUrl.TrimEnd(new char[] { '/' });
            }
            if (webAppUrl.EndsWith("/"))
            {
                webAppUrl = webAppUrl.TrimEnd(new char[] { '/' });
            }

            // e.g., "https://ppeTeams.contoso.com/sites/test/_catalogs/masterpage/Sample.master"
            string targetFilePath = setupFileDirName + '/' + setupFileName;

            // e.g., "/_catalogs/masterpage/Sample.master"
            // e.g., "/_catalogs/masterpage/folder/Sample.master"
            // e.g., "/sites/testSite/_catalogs/masterpage/Sample.master"
            // e.g., "/sites/testSite/_catalogs/masterpage/folder/Sample.master"
            // e.g., "/sites/testSite/childWeb/_catalogs/masterpage/Sample.master"
            // e.g., "/sites/testSite/childWeb/_catalogs/masterpage/folder/Sample.master"
            string serverRelativeFilePath = targetFilePath.Substring(webAppUrl.Length);

            try
            {
                Logger.LogInfoMessage(String.Format("Processing File: {0} ...", targetFilePath), true);

                //Logger.LogInfoMessage(String.Format("-setupFileDirName= {0}", setupFileDirName), false);
                //Logger.LogInfoMessage(String.Format("-setupFileName= {0}", setupFileName), false);
                //Logger.LogInfoMessage(String.Format("-targetFilePath= {0}", targetFilePath), false);
                //Logger.LogInfoMessage(String.Format("-webAppUrl= {0}", webAppUrl), false);
                //Logger.LogInfoMessage(String.Format("-webUrl= {0}", webUrl), false);
                //Logger.LogInfoMessage(String.Format("-serverRelativeFilePath= {0}", serverRelativeFilePath), false);

                // we have to open the web because Helper.DeleteFileByServerRelativeUrl() needs to update the web in order to commit the change
                using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, webUrl))
                {
                    Web web = userContext.Web;
                    userContext.Load(web);
                    userContext.ExecuteQuery();

                    Helper.DeleteFileByServerRelativeUrl(web, serverRelativeFilePath);
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("DeleteMissingFile() failed for {0}: Error={1}", targetFilePath, ex.Message), false);
            }
        }
Beispiel #27
0
        public static bool DeleteWebPart(string webUrl, string pageUrl, string _storageKey)
        {
            bool   isWebPartDeleted       = false;
            string webPartXml             = string.Empty;
            string exceptionCommentsInfo1 = string.Empty;
            Web    web  = null;
            List   list = null;

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

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

                using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, webUrl))
                {
                    web = userContext.Web;
                    userContext.Load(web);
                    userContext.ExecuteQuery();

                    Logger.LogInfoMessage("Successful authentication", false);

                    Logger.LogInfoMessage("Checking Out File ...", false);

                    list = GetPageList(userContext);

                    //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
                        {
                            userContext.Load(list, l => l.ForceCheckout,
                                             l => l.EnableVersioning,
                                             l => l.EnableMinorVersions,
                                             l => l.EnableModeration,
                                             l => l.Title,
                                             l => l.DraftVersionVisibility,
                                             l => l.DefaultViewUrl);

                            userContext.ExecuteQueryRetry();

                            #region Remove Versioning in List
                            forceCheckOut       = list.ForceCheckout;
                            enableVersioning    = list.EnableVersioning;
                            enableMinorVersions = list.EnableMinorVersions;
                            enableModeration    = list.EnableModeration;
                            dVisibility         = list.DraftVersionVisibility;

                            Logger.LogInfoMessage("Removing Versioning", false);
                            //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();
                                userContext.ExecuteQuery();
                            }
                            #endregion
                        }
                        catch (Exception ex)
                        {
                            Logger.LogErrorMessage("[DeleteMissingWebparts: DeleteWebPart]. Exception Message: " + ex.Message
                                                   + ", Exception Comments: Exception while removing Version to the list", true);
                            ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, webUrl, "Webpart", ex.Message,
                                                        ex.ToString(), "DeleteWebPart", ex.GetType().ToString(), "Exception while removing Version to the list");
                        }
                    }

                    try
                    {
                        if (DeleteWebPart(userContext.Web, ServerRelativePageUrl, storageKey))
                        {
                            isWebPartDeleted = true;
                            Logger.LogSuccessMessage("Successfully Deleted the WebPart", true);
                        }
                        else
                        {
                            Logger.LogErrorMessage("WebPart with StorageKey: " + storageKey + " does not exist in the Page: " + ServerRelativePageUrl, true);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.LogErrorMessage("[DeleteMissingWebparts: DeleteWebPart]. Exception Message: " + ex.Message, true);
                        ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, webUrl, "Webpart", ex.Message,
                                                    ex.ToString(), "DeleteWebPart", ex.GetType().ToString(), Constants.NotApplicable);
                    }
                    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();
                                userContext.ExecuteQuery();
                            }
                            #endregion
                        }
                        web  = null;
                        list = null;
                    }
                    Logger.LogInfoMessage("File Checked in after successfully deleting the webpart.", false);
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage("[DeleteMissingWebparts: DeleteWebPart]. Exception Message: " + ex.Message, true);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, webUrl, "Webpart", ex.Message,
                                            ex.ToString(), "DeleteWebPart", ex.GetType().ToString(), Constants.NotApplicable);
            }
            return(isWebPartDeleted);
        }
        public static void GetWebPartUsage(string webPartType, string webUrl, string outPutDirectory)
        {
            string        exceptionCommentsInfo1 = string.Empty;
            ClientContext clientContext          = null;
            bool          headerWebPart          = false;
            Web           web     = null;
            bool          isfound = false;
            string        webPartUsageFileName = outPutDirectory + "\\" + Constants.WEBPART_USAGE_ENTITY_FILENAME + timeStamp + Constants.CSVExtension;

            try
            {
                Logger.LogInfoMessage("[GetWebPartUsage] Finding WebPartUsage details for Web Part: " + webPartType + " in Web: " + webUrl);
                using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, webUrl))
                {
                    web = userContext.Web;
                    userContext.Load(web);
                    userContext.ExecuteQuery();
                    clientContext = userContext;

                    WebPartUsageEntity        webPartUsageEntity = null;
                    List <WebPartUsageEntity> webPartUsage       = new List <WebPartUsageEntity>();

                    //Prepare Exception Comments
                    exceptionCommentsInfo1 = "Web Url: " + clientContext.Web.Url + ", Web Part Type: " + webPartType;

                    if (clientContext != null)
                    {
                        List list = AddWebPart.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();

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

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

                                    Logger.LogInfoMessage("[GetWebPartUsage] 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;

                                        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 = AddWebPart.GetWebPartShortTypeName(WebPartTypeName);

                                        // only modify if we find the old web part
                                        if (actualWebPartType.Equals(webPartType, StringComparison.CurrentCultureIgnoreCase))
                                        {
                                            Logger.LogInfoMessage("[GetWebPartUsage] Found WebPart: " + webPartType + " in Page: " + page.Name);

                                            webPartUsageEntity              = new WebPartUsageEntity();
                                            webPartUsageEntity.PageUrl      = pageUrl;
                                            webPartUsageEntity.WebPartID    = webPartDefinition.Id.ToString();
                                            webPartUsageEntity.WebURL       = webUrl;
                                            webPartUsageEntity.WebPartTitle = webPart.Title;
                                            webPartUsageEntity.ZoneIndex    = webPart.ZoneIndex.ToString();
                                            webPartUsageEntity.WebPartType  = actualWebPartType;

                                            FileUtility.WriteCsVintoFile(webPartUsageFileName, webPartUsageEntity, ref headerWebPart);
                                            isfound = true;
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, webUrl, "WebPartUsage", ex.Message, ex.ToString(), "GetWebPartUsage()", ex.GetType().ToString(), exceptionCommentsInfo1);
                                    Logger.LogErrorMessage("[GetWebPartUsage] Exception Message: " + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1);
                                    System.Console.ForegroundColor = System.ConsoleColor.Red;
                                    Logger.LogErrorMessage("[GetWebPartUsage] Exception Message: " + ex.Message);
                                    System.Console.ResetColor();
                                }
                            }
                        }
                    }
                    //Default Pages
                    GetWebPartUsage_DefaultPages(webPartType, clientContext, outPutDirectory);
                    //Default Pages

                    if (isfound)
                    {
                        Logger.LogSuccessMessage("[GetWebPartUsage] WebPart Usage is exported to the file " + webPartUsageFileName, true);
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, webUrl, "WebPartUsage", ex.Message, ex.ToString(), "GetWebPartUsage()", ex.GetType().ToString(), exceptionCommentsInfo1);
                Logger.LogErrorMessage("[GetWebPartUsage] Exception Message: " + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1);
                System.Console.ForegroundColor = System.ConsoleColor.Red;
                Logger.LogErrorMessage("[GetWebPartUsage] Exception Message: " + ex.Message);
                System.Console.ResetColor();
            }
        }
        private static void ResetMappingFile(LockedMasterPageFilesInput masterPageFile)
        {
            if (masterPageFile == null)
            {
                return;
            }

            string setupFileDirName   = masterPageFile.SetupFileDirName;
            string setupFileName      = masterPageFile.SetupFileName;
            string setupFileExtension = masterPageFile.SetupFileExtension;
            string siteUrl            = masterPageFile.SiteCollection;
            string webAppUrl          = masterPageFile.WebApplication;
            string webUrl             = masterPageFile.WebUrl;

            LockedMasterPageFilesOutput csvObject = new LockedMasterPageFilesOutput();

            csvObject.SetupFileDirName  = setupFileDirName;
            csvObject.SetupFileName     = setupFileName;
            csvObject.WebApplication    = webAppUrl;
            csvObject.WebUrl            = webUrl;
            csvObject.ExecutionDateTime = DateTime.Now.ToString();
            csvObject.Status            = Constants.Success;

            // clean the inputs
            if (setupFileDirName.EndsWith("/"))
            {
                setupFileDirName = setupFileDirName.TrimEnd(new char[] { '/' });
            }
            if (setupFileName.StartsWith("/"))
            {
                setupFileName = setupFileName.TrimStart(new char[] { '/' });
            }
            if (webUrl.EndsWith("/"))
            {
                webUrl = webUrl.TrimEnd(new char[] { '/' });
            }
            if (webAppUrl.EndsWith("/"))
            {
                webAppUrl = webAppUrl.TrimEnd(new char[] { '/' });
            }

            // e.g., "https://ppeTeams.contoso.com/sites/test/_catalogs/masterpage/Sample.master"
            string targetFilePath = setupFileDirName + '/' + setupFileName;

            // e.g., "https://ppeTeams.contoso.com/sites/test/_catalogs/masterpage/__DeviceChannelMappings.aspx"
            string mappingFilePath = setupFileDirName + '/' + Constants.DeviceChannelMappingFileName;

            // e.g., "/_catalogs/masterpage/Sample.master"
            // e.g., "/_catalogs/masterpage/folder/Sample.master"
            // e.g., "/sites/testSite/_catalogs/masterpage/Sample.master"
            // e.g., "/sites/testSite/_catalogs/masterpage/folder/Sample.master"
            // e.g., "/sites/testSite/childWeb/_catalogs/masterpage/Sample.master"
            // e.g., "/sites/testSite/childWeb/_catalogs/masterpage/folder/Sample.master"
            string serverRelativeMappingFilePath = mappingFilePath.Substring(webAppUrl.Length);

            if (setupFileExtension.Equals("master", StringComparison.InvariantCultureIgnoreCase) == false)
            {
                // ignore anything that is not a master page file
                Logger.LogWarningMessage(String.Format("Skipping file [not a Master Page]: {0}", targetFilePath), true);
                return;
            }

            try
            {
                Logger.LogInfoMessage(String.Format("Processing File: {0} ...", targetFilePath), true);

                Logger.LogInfoMessage(String.Format(" setupFileDirName= {0} ...", setupFileDirName), false);
                Logger.LogInfoMessage(String.Format(" setupFileName= {0} ...", setupFileName), false);
                Logger.LogInfoMessage(String.Format(" targetFilePath= {0} ...", targetFilePath), false);
                Logger.LogInfoMessage(String.Format(" mappingFilePath= {0} ...", mappingFilePath), false);
                Logger.LogInfoMessage(String.Format(" serverRelativeFilePath= {0} ...", serverRelativeMappingFilePath), false);
                Logger.LogInfoMessage(String.Format(" webAppUrl= {0} ...", webAppUrl), false);
                Logger.LogInfoMessage(String.Format(" webUrl= {0} ...", webUrl), false);

                using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, webUrl))
                {
                    Web web = userContext.Web;
                    userContext.Load(web);
                    userContext.ExecuteQuery();

                    // Get Device Channel Mapping File
                    string originalFileContents = Helper.SafeGetFileAsString(web, serverRelativeMappingFilePath);
                    if (String.IsNullOrEmpty(originalFileContents))
                    {
                        // bail if Mapping file not found..
                        Logger.LogWarningMessage(String.Format("Skipping file: [{0}]; Mapping File not found: [{1}]", targetFilePath, serverRelativeMappingFilePath), true);
                        return;
                    }

                    string tempFileContents = originalFileContents.ToLower();
                    if (tempFileContents.Contains(setupFileName.ToLower()) == false)
                    {
                        // bail if MP file not referenced in Mapping file..
                        Logger.LogWarningMessage(String.Format("Skipping file: [{0}]; Mapping File does not reference the master page file: [{1}]", targetFilePath, serverRelativeMappingFilePath), true);
                        return;
                    }

                    // grab the current master page settings for the web.
                    Helper.MasterPageInfo mpi         = Helper.GetMasterPageInfo(web);
                    string currentCustomMasterPageUrl = mpi.CustomMasterPageUrl;
                    string currentCustomMasterPage    = currentCustomMasterPageUrl.Substring(currentCustomMasterPageUrl.LastIndexOf("/") + 1);

                    // Edit Device Channel Mapping File so it now references the correct/current master page files.
                    // TODO: this is a case-sensitive operation; add case-insensitive logic if it becomes necessary...
                    string updatedFileContents = originalFileContents.Replace(setupFileName, currentCustomMasterPage);

                    // Did the case-sensitive replacement operation fail?
                    tempFileContents = updatedFileContents.ToLower();
                    if (tempFileContents.Contains(setupFileName.ToLower()) == true)
                    {
                        // bail if replacement operation failed due to case-sensitivity
                        Logger.LogErrorMessage(String.Format("ResetMappingFile() failed for file {0}: Error={1}",
                                                             targetFilePath, "Casing of Master Page References in Mapping File does not match the casing of the Master Page [" + setupFileName + "] specified in the input file"),
                                               true
                                               );
                        Logger.LogWarningMessage(String.Format("Update the casing of the Master Page entry [{0}] of the input file to match the casing used in the Mapping File [Contents={1}]", setupFileName, originalFileContents), false);
                        return;
                    }

                    Logger.LogInfoMessage(String.Format("Reset Mapping File [{0}] to reference [{1}]", serverRelativeMappingFilePath, currentCustomMasterPage), true);

                    // Upload Modified Device Channel Mapping File
                    Helper.UploadDeviceChannelMappingFile(web, serverRelativeMappingFilePath, updatedFileContents, "File reset by Transformation Console");

                    // Backup Original Device Channel Mapping File
                    Helper.UploadDeviceChannelMappingFile(web, serverRelativeMappingFilePath + ".bak", originalFileContents, "Backup created by Transformation Console");

                    csvObject.MappingFile          = serverRelativeMappingFilePath;
                    csvObject.MappingBackup        = serverRelativeMappingFilePath + ".bak";
                    csvObject.MappingMasterPageRef = currentCustomMasterPage;
                    csvObject.Status = Constants.Success;
                    FileUtility.WriteCsVintoFile(csvOutputFileSpec, csvObject, ref csvOutputFileHasHeader);
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("ResetMappingFile() failed for file {0}: Error={1}", targetFilePath, ex.Message), true);
                ExceptionCsv.WriteException(
                    webAppUrl, siteUrl, webUrl,
                    "MappingFile",
                    ex.Message, ex.ToString(), "ResetMappingFile", ex.GetType().ToString(),
                    String.Format("ResetMappingFile() failed for file {0}", targetFilePath)
                    );
            }
        }
        private static void ProcessSite(string siteUrl, string [] securityGroups)
        {
            try
            {
                Logger.LogInfoMessage(String.Format("Processing Site: {0} ...", siteUrl), true);

                using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, siteUrl))
                {
                    Web root = userContext.Site.RootWeb;
                    userContext.Load(root);
                    userContext.ExecuteQuery();

                    // Looking for only the Security Groups present on the site
                    var groups = userContext.LoadQuery(root.SiteUsers.Where(u => (u.PrincipalType == Microsoft.SharePoint.Client.Utilities.PrincipalType.SecurityGroup)));
                    userContext.ExecuteQuery();

                    Logger.LogInfoMessage(String.Format("There are [{0}] Security Groups to check...", groups.Count()), false);
                    foreach (User g in groups)
                    {
                        try
                        {
                            // The User.Title property is generally in "domain\alias" format for on-prem/SPO-D: (e.g., orion\joeUser)
                            // other values you might see:
                            //  Everyone
                            //  All Users (windows)
                            //  NT AUTHORITY\authenticated users
                            Logger.LogInfoMessage(String.Format("Checking Security Group [{0}] for significance...", g.Title), false);

                            // We could also compare the User.LoginName property, but we would need the SID in order to build a string in the following format:
                            //  c:0+.w|s-1-5-21-1485757101-1923125180-2349192791-514
                            if (securityGroups.Any(x => x.Equals(g.Title, StringComparison.InvariantCultureIgnoreCase)))
                            {
                                GenerateSecurityGroupOutput csvObject = new GenerateSecurityGroupOutput();
                                csvObject.SecurityGroupName = g.Title;
                                csvObject.SiteCollectionUrl = siteUrl;

                                Logger.LogSuccessMessage(String.Format("Significant Security Group [{0}] found on site [{1}]", g.Title, siteUrl), true);
                                FileUtility.WriteCsVintoFile(csvOutputFileSpec, csvObject, ref csvOutputFileHasHeader);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.LogErrorMessage(String.Format("ProcessSite() failed for Security Group [{0}]: Error={1}", g.Title, ex.Message), false);
                            ExceptionCsv.WriteException(
                                "N/A", siteUrl, "N/A",
                                "SecurityGroup",
                                ex.Message, ex.ToString(), "ProcessSite", ex.GetType().ToString(),
                                String.Format("ProcessSite() failed for Security Group [{0}]", g.Title)
                                );
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("ProcessSite() failed for site [{0}]: Error={1}", siteUrl, ex.Message), false);
                ExceptionCsv.WriteException(
                    "N/A", siteUrl, "N/A",
                    "SecurityGroup",
                    ex.Message, ex.ToString(), "ProcessSite", ex.GetType().ToString(),
                    String.Format("ProcessSite() failed for site [{0}]", siteUrl)
                    );
            }
        }