public static void DoWork()
        {
            string timeStamp      = DateTime.Now.ToString("yyyyMMdd_hhmmss");
            string setupInputFile = string.Empty;

            Logger.OpenLog("DeleteSetupFiles", timeStamp);

            //if (!ShowInformation())
            //    return;

            if (!ReadInputFile(ref setupInputFile))
            {
                System.Console.ForegroundColor = System.ConsoleColor.Red;
                Logger.LogErrorMessage("Setup Files input file is not valid or available. So, Operation aborted!");
                Logger.LogErrorMessage("Please enter path like: E.g. C:\\<Working Directory>\\<InputFile>.csv");
                System.Console.ResetColor();
                return;
            }

            string inputFileSpec = setupInputFile;

            if (System.IO.File.Exists(inputFileSpec))
            {
                Logger.LogInfoMessage(String.Format("Scan starting {0}", DateTime.Now.ToString()), true);
                IEnumerable <MissingSetupFilesInput> objInputMissingSetupFiles = ImportCSV.ReadMatchingColumns <MissingSetupFilesInput>(inputFileSpec, Constants.CsvDelimeter);
                if (objInputMissingSetupFiles != null && objInputMissingSetupFiles.Any())
                {
                    try
                    {
                        string csvFile = Environment.CurrentDirectory + @"\" + Constants.DeleteSetupFileStatus + timeStamp + Constants.CSVExtension;
                        if (System.IO.File.Exists(csvFile))
                        {
                            System.IO.File.Delete(csvFile);
                        }
                        Logger.LogInfoMessage(String.Format("Preparing to delete a total of {0} files ...", objInputMissingSetupFiles.Cast <Object>().Count()), true);

                        foreach (MissingSetupFilesInput missingFile in objInputMissingSetupFiles)
                        {
                            DeleteMissingFile(missingFile, csvFile);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.LogErrorMessage(String.Format("[DeleteSetupFiles: DoWork] failed: Error={0}", ex.Message), true);
                        ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "SetupFile", ex.Message,
                                                    ex.ToString(), "DoWork", ex.GetType().ToString(), "Exception occured while reading input file");
                    }
                }
                else
                {
                    Logger.LogInfoMessage("There is nothing to delete from the '" + inputFileSpec + "' File ", true);
                }
                Logger.LogInfoMessage(String.Format("Scan Completed {0}", DateTime.Now.ToString()), true);
            }
            else
            {
                Logger.LogErrorMessage(String.Format("[DeleteSetupFiles: DoWork]: Input file {0} is not available", inputFileSpec), true);
            }
            Logger.CloseLog();
        }
Пример #2
0
        private static string GetWebPartID(string webPartID)
        {
            string _webPartID = string.Empty;

            try
            {
                string[] tempStr = webPartID.Split('_');

                if (tempStr.Length > 5)
                {
                    _webPartID = webPartID.Remove(0, tempStr[0].Length + 1).Replace('_', '-');
                }
                else
                {
                    _webPartID = webPartID.Replace('_', '-');
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage("[DeleteMissingWebparts: GetWebPartID]. Exception Message: " + ex.Message, true);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "Webpart", ex.Message,
                                            ex.ToString(), "GetWebPartID", ex.GetType().ToString(), Constants.NotApplicable);
            }
            return(_webPartID);
        }
Пример #3
0
        public static string GetWebPartShortTypeName(string webPartType)
        {
            string _webPartType = string.Empty;

            try
            {
                string[] tempWebPartTypeName = webPartType.Split(',');

                string[] tempWebPartType = tempWebPartTypeName[0].Split('.');
                if (tempWebPartType.Length == 1)
                {
                    _webPartType = tempWebPartType[0];
                }
                else
                {
                    _webPartType = tempWebPartType[tempWebPartType.Length - 1];
                }
            }
            catch (Exception ex)
            {
                System.Console.ForegroundColor = System.ConsoleColor.Red;
                Logger.LogErrorMessage("[GetWebPartShortTypeName] Exception Message: " + ex.Message);
                System.Console.ResetColor();
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "GetWebPartShortTypeName", ex.Message, ex.ToString(), "GetWebPartShortTypeName()", ex.GetType().ToString());
            }
            return(_webPartType);
        }
Пример #4
0
        private static bool IsFeatureOnWeb(Guid FeatureID, ClientContext clientContext)
        {
            bool isFeatureAvailable = false;

            try
            {
                FeatureCollection features = clientContext.Web.Features;
                clientContext.Load(features);
                clientContext.ExecuteQuery();

                Feature feature = features.GetById(FeatureID);
                if (feature != null)
                {
                    clientContext.Load(feature);
                    clientContext.ExecuteQuery();
                    if (feature.DefinitionId != null)
                    {
                        isFeatureAvailable = true;
                    }
                }
            }
            catch (Exception ex)
            {
                System.Console.ForegroundColor = System.ConsoleColor.Red;
                Logger.LogErrorMessage("[IsFeatureOnWeb] Exception Message: " + ex.Message);
                System.Console.ResetColor();
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "AddWebPart", ex.Message, ex.ToString(), "IsFeatureOnWeb()", ex.GetType().ToString());
            }


            return(isFeatureAvailable);
        }
Пример #5
0
        public static void TransformWebPart_UsingCSV(string usageFileName, string sourceWebPartType, string targetWebPartFileName, string targetWebPartXmlFilePath, string outPutDirectory)
        {
            string exceptionCommentsInfo1 = string.Empty;

            try
            {
                WebPart_Initialization(outputPath);

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

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


                //ReplaceWebPart_UsingCSV
                string targetWebPartXmlsDir = outPutDirectory + @"\" + Constants.TARGET_WEBPART_XML_DIR;
                ReplaceWebPart_UsingCSV(sourceWebPartType, targetWebPartXmlFilePath, targetWebPartFileName, targetWebPartXmlsDir, usageFileName, outPutDirectory);
            }
            catch (Exception ex)
            {
                System.Console.ForegroundColor = System.ConsoleColor.Red;
                Logger.LogErrorMessage("[TransformWebPart_UsingCSV] Exception Message: " + ex.Message);
                System.Console.ResetColor();
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "ReplaceWebPart", ex.Message, ex.ToString(), "TransformWebPart_UsingCSV()", ex.GetType().ToString(), exceptionCommentsInfo1);
            }
        }
Пример #6
0
        //sourceWebPartId - Used to update the content of the wikipage with new web part id
        public static bool AddWebPartt(Web web, string serverRelativePageUrl, WebPartEntity webPartEntity, string sourceWebPartId = "")
        {
            bool isWebPartAdded = false;

            try
            {
                Microsoft.SharePoint.Client.File webPartPage = web.GetFileByServerRelativeUrl(serverRelativePageUrl);

                web.Context.Load(webPartPage);
                web.Context.ExecuteQueryRetry();

                LimitedWebPartManager webPartManager = webPartPage.GetLimitedWebPartManager(PersonalizationScope.Shared);

                WebPartDefinition importedWebPart = webPartManager.ImportWebPart(webPartEntity.WebPartXml);
                WebPartDefinition webPart         = webPartManager.AddWebPart(importedWebPart.WebPart, webPartEntity.WebPartZone, webPartEntity.WebPartIndex);
                web.Context.Load(webPart);
                web.Context.ExecuteQuery();

                CheckForWikiFieldOrPublishingPageContentAndUpdate(webPart, web, webPartPage, sourceWebPartId);

                isWebPartAdded = true;
            }
            catch (Exception ex)
            {
                System.Console.ForegroundColor = System.ConsoleColor.Red;
                Logger.LogErrorMessage("[AddWebPartt] Exception Message: " + ex.Message);
                System.Console.ResetColor();
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, web.Url, "AddWebPart", ex.Message, ex.ToString(), "AddWebPartt()", ex.GetType().ToString());
            }

            return(isWebPartAdded);
        }
Пример #7
0
        private static void ReadWebPartUsageCSV(string sourceWebPartType, string usageFilePath, string outPutFolder, out IEnumerable <WebPartDiscoveryInput> objWPDInput)
        {
            string exceptionCommentsInfo1 = string.Empty;

            Logger.LogInfoMessage("[ReadWebPartUsageCSV] [START] Calling function ImportCsv.ReadMatchingColumns<WebPartDiscoveryInput>");

            objWPDInput = null;
            objWPDInput = ImportCSV.ReadMatchingColumns <WebPartDiscoveryInput>(usageFilePath, Constants.CsvDelimeter);

            Logger.LogInfoMessage("[ReadWebPartUsageCSV] [END] Read all the WebParts Usage Details from Discovery Usage File and saved in List - out IEnumerable<WebPartDiscoveryInput> objWPDInput, for processing.");

            try
            {
                if (objWPDInput.Any())
                {
                    Logger.LogInfoMessage("[START] ReadWebPartUsageCSV - After Loading InputCSV ");

                    objWPDInput = from p in objWPDInput
                                  where p.WebPartType.ToLower() == sourceWebPartType.ToLower()
                                  select p;
                    exceptionCommentsInfo1 = objWPDInput.ToString();

                    Logger.LogInfoMessage("[END] ReadWebPartUsageCSV - After Loading InputCSV");
                }
            }
            catch (Exception ex)
            {
                System.Console.ForegroundColor = System.ConsoleColor.Red;
                Logger.LogErrorMessage("[ReadWebPartUsageCSV] Exception Message: " + ex.Message + ", Exception Comments:" + exceptionCommentsInfo1);
                System.Console.ResetColor();
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "ReplaceWebPart", ex.Message, ex.ToString(), "ReadWebPartUsageCSV()", ex.GetType().ToString(), exceptionCommentsInfo1);
            }
        }
        /// <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));
            }
        }
 /// <summary>
 /// Fills GrandTotal of WebApplicationUrls of given component column
 /// </summary>
 /// <param name="oSummarySheet"></param>
 /// <param name="componentColumn"></param>
 /// <param name="grandTotal"></param>
 /// <param name="fontSize"></param>
 /// <param name="fontName"></param>
 /// <param name="bgColor"></param>
 /// <param name="fontColor"></param>
 public static void FillGrandTotal(Excel.Worksheet oSummarySheet, string componentColumn, string grandTotal,
                                   int fontSize, string fontName, string bgColor, string fontColor)
 {
     try
     {
         //Get the Range where to fill total value
         var grandTotalRange = oSummarySheet.get_Range(componentColumn, componentColumn);
         grandTotalRange.Interior.Color = CommonHelper.GetColor(bgColor);
         grandTotalRange.Borders.Color  = XlRgbColor.rgbBlack;
         grandTotalRange.Font.Bold      = true;
         grandTotalRange.Font.Size      = fontSize;
         grandTotalRange.Font.Name      = fontName;
         grandTotalRange.Font.Color     = CommonHelper.GetColor(fontColor);
         grandTotalRange.Value2         = grandTotal;
     }
     catch (Exception ex)
     {
         Logger.LogErrorMessage(string.Format("[GeneratePivotReports][ComponentsSummaryView][FillGrandTotal][Exception]: " + ex.Message + "\n" + ex.StackTrace.ToString()), true);
         ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "Pivot", ex.Message, ex.ToString(),
                                     "[GeneratePivotReports]: FillGrandTotal", ex.GetType().ToString(), Constants.NotApplicable);
     }
     finally
     {
         oSummarySheet = null;
     }
 }
 /// <summary>
 /// Creates header for component
 /// </summary>
 /// <param name="row"></param>
 /// <param name="col"></param>
 /// <param name="htext"></param>
 /// <param name="cell"></param>
 /// <param name="mergeColumns"></param>
 /// <param name="backgroundColor"></param>
 /// <param name="bold"></param>
 /// <param name="fontSize"></param>
 /// <param name="fcolor"></param>
 /// <param name="oSummarySheet"></param>
 public static void CreateHeaders(int row, int col, string htext, string cell,
                                  string backgroundColor, bool bold, int fontSize, string fcolor, string fontName, Excel.Worksheet oSummarySheet)
 {
     try
     {
         oSummarySheet.Cells[row, col] = htext;
         Excel.Range workSheet_range = null;
         workSheet_range = oSummarySheet.get_Range(cell, cell);
         workSheet_range.Borders.Color = XlRgbColor.rgbBlack;
         workSheet_range.Font.Bold     = bold;
         workSheet_range.Font.Size     = fontSize;
         workSheet_range.Font.Name     = fontName;
         //set background color
         workSheet_range.Interior.Color = CommonHelper.GetColor(backgroundColor);
         //set font color
         workSheet_range.Font.Color = CommonHelper.GetColor(fcolor);
     }
     catch (Exception ex)
     {
         Logger.LogErrorMessage(string.Format("[GeneratePivotReports][ComponentsSummaryView][CreateHeaders][Exception]: " + ex.Message + "\n" + ex.StackTrace.ToString()), true);
         ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "Pivot", ex.Message, ex.ToString(),
                                     "[GeneratePivotReports]: CreateHeaders", ex.GetType().ToString(), Constants.NotApplicable);
     }
     finally
     {
         oSummarySheet = null;
     }
 }
        /// <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));
            }
        }
        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);
            }
        }
Пример #13
0
        private static void ReadWebPartUsageCSV(string sourceWebPartType, string usageFilePath, out IEnumerable <WebpartInput> objWPDInput)
        {
            objWPDInput = null;
            objWPDInput = ImportCSV.ReadMatchingColumns <WebpartInput>(usageFilePath, Constants.CsvDelimeter);

            try
            {
                if (objWPDInput.Any())
                {
                    objWPDInput = from p in objWPDInput
                                  where p.WebPartType.Equals(sourceWebPartType, StringComparison.OrdinalIgnoreCase)
                                  select p;

                    if (objWPDInput.Any())
                    {
                        Logger.LogInfoMessage("Number of Webparts found with WebpartType '" + sourceWebPartType + "' are " + objWPDInput.Count());
                    }
                    else
                    {
                        Logger.LogInfoMessage("No Webparts found with WebpartType '" + sourceWebPartType + "'");
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage("[DeleteMissingWebparts: ReadWebPartUsageCSV]. Exception Message: " + ex.Message
                                       + ", Exception Comments: Exception occured while rading input file ", true);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "Webpart", ex.Message,
                                            ex.ToString(), "ReadWebPartUsageCSV", ex.GetType().ToString(), "Exception occured while rading input file");
            }
        }
        private static bool RemoveFeatureFromSite(ClientContext userContext, Guid featureDefinitionId)
        {
            try
            {
                FeatureCollection features = userContext.Site.Features;
                ClearObjectData(features);

                userContext.Load(features);
                userContext.ExecuteQuery();

                //DumpFeatures(features, "site");

                Feature targetFeature = features.GetById(featureDefinitionId);
                targetFeature.EnsureProperties(f => f.DefinitionId);

                if (targetFeature == null || !targetFeature.IsPropertyAvailable("DefinitionId") || targetFeature.ServerObjectIsNull.Value)
                {
                    Logger.LogInfoMessage(String.Format("Could not delete Feature {0}; feature not found in site.Features", featureDefinitionId.ToString()), false);
                    return(false);
                }
                features.Remove(featureDefinitionId, true);

                // commit the changes
                userContext.Load(features);
                userContext.ExecuteQuery();
                return(true);
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("[DeleteMissingFeatures: RemoveFeatureFromSite] failed for Feature {0} on site {1}; Error={2}", featureDefinitionId.ToString(), userContext.Site.Url, ex.Message), true);
                ExceptionCsv.WriteException(Constants.NotApplicable, userContext.Site.Url, Constants.NotApplicable, "Feature", ex.Message, ex.ToString(), "RemoveFeatureFromSite",
                                            ex.GetType().ToString(), String.Format("RemoveFeatureFromSite() failed for Feature {0} on site {1}", featureDefinitionId.ToString(), userContext.Site.Url));
                return(false);
            }
        }
Пример #15
0
        private static bool DeleteWebPart(Web web, string serverRelativePageUrl, Guid storageKey)
        {
            bool isWebPartDeleted = false;
            LimitedWebPartManager limitedWebPartManager = null;

            try
            {
                var webPartPage = web.GetFileByServerRelativeUrl(serverRelativePageUrl);

                web.Context.Load(webPartPage);
                web.Context.ExecuteQueryRetry();

                limitedWebPartManager = webPartPage.GetLimitedWebPartManager(PersonalizationScope.Shared);
                web.Context.Load(limitedWebPartManager.WebParts, wps => wps.Include(wp => wp.Id));
                web.Context.ExecuteQueryRetry();

                if (limitedWebPartManager.WebParts.Count >= 0)
                {
                    foreach (WebPartDefinition webpartDef in limitedWebPartManager.WebParts)
                    {
                        Microsoft.SharePoint.Client.WebParts.WebPart oWebPart = null;
                        try
                        {
                            oWebPart = webpartDef.WebPart;
                            if (webpartDef.Id.Equals(storageKey))
                            {
                                webpartDef.DeleteWebPart();
                                web.Context.ExecuteQueryRetry();
                                isWebPartDeleted = true;
                                break;
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.LogErrorMessage("[DeleteMissingWebparts: DeleteWebPart]. Exception Message: " + ex.Message
                                                   + ", Exception Comments: Exception occured while deleting the webpart", true);
                            ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, web.Url, "Webpart", ex.Message,
                                                        ex.ToString(), "DeleteWebPart", ex.GetType().ToString(), Constants.NotApplicable);
                        }
                        finally
                        {
                            oWebPart = null;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage("[DeleteMissingWebparts: DeleteWebPart]. Exception Message: "
                                       + ex.Message + ", Exception Comments: Exception occure while fetching webparts using LimitedWebPartManager", true);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, web.Url, "Webpart", ex.Message,
                                            ex.ToString(), "DeleteWebPart", ex.GetType().ToString(), Constants.NotApplicable);
            }
            finally
            {
                limitedWebPartManager = null;
            }
            return(isWebPartDeleted);
        }
        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);
        }
        public static void DoWork()
        {
            string timeStamp = DateTime.Now.ToString("yyyyMMdd_hhmmss");

            csvOutputFileSpec      = Environment.CurrentDirectory + "\\ResetDeviceChannelMappingFiles-" + timeStamp + Constants.CSVExtension;
            csvOutputFileHasHeader = System.IO.File.Exists(csvOutputFileSpec);

            Logger.OpenLog("ResetDeviceChannelMappingFiles", timeStamp);
            Logger.LogInfoMessage(String.Format("Scan starting {0}", DateTime.Now.ToString()), true);

            string inputFileSpec = String.Empty;

            if (!ReadInputFile(ref inputFileSpec))
            {
                System.Console.ForegroundColor = System.ConsoleColor.Red;
                Logger.LogErrorMessage(String.Format("Input file [{0}] does not exist.", inputFileSpec), true);
                Logger.LogInfoMessage(String.Format("Scan aborted {0}", DateTime.Now.ToString()), true);
                Logger.CloseLog();
                System.Console.ResetColor();
                return;
            }

            // The Locked Master Pages input file is essentially a filtered instance of the Missing Setup Files input file.
            IEnumerable <LockedMasterPageFilesInput> objInputLockedMasterPageFiles = ImportCSV.ReadMatchingColumns <LockedMasterPageFilesInput>(inputFileSpec, Constants.CsvDelimeter);

            if (objInputLockedMasterPageFiles == null || objInputLockedMasterPageFiles.Count() == 0)
            {
                System.Console.ForegroundColor = System.ConsoleColor.Red;
                Logger.LogErrorMessage(String.Format("Input file [{0}] is empty.", inputFileSpec), true);
                Logger.LogInfoMessage(String.Format("Scan aborted {0}", DateTime.Now.ToString()), true);
                Logger.CloseLog();
                System.Console.ResetColor();
                return;
            }

            Logger.LogInfoMessage(String.Format("Preparing to process a total of {0} master page files ...", objInputLockedMasterPageFiles.Count()), true);
            try
            {
                foreach (LockedMasterPageFilesInput masterPageFile in objInputLockedMasterPageFiles)
                {
                    ResetMappingFile(masterPageFile);
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("ResetDeviceChannelMappingFiles() failed: Error={0}", ex.Message), true);
                ExceptionCsv.WriteException(
                    Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable,
                    "MappingFile",
                    ex.Message, ex.ToString(), "DoWork", ex.GetType().ToString(),
                    "Exception occured while processing input file."
                    );
            }

            Logger.LogInfoMessage(String.Format("Scan completed {0}", DateTime.Now.ToString()), true);
            Logger.CloseLog();
        }
        private static void ReportContentTypeUsage(Web web, List list, string targetContentTypeId, string targetContentTypeName, string siteColUrl, string CTCFFileName)
        {
            try
            {
                ContentTypeCustomFieldOutput objCTCFOutput3 = new ContentTypeCustomFieldOutput();
                objCTCFOutput3.ComponentName = Constants.ContentTypes;
                objCTCFOutput3.ListId        = list.Id.ToString();
                objCTCFOutput3.ListTitle     = list.Title;
                objCTCFOutput3.ContentTypeOrCustomFieldId   = targetContentTypeId.ToString();
                objCTCFOutput3.ContentTypeOrCustomFieldName = targetContentTypeName;
                objCTCFOutput3.WebUrl         = web.Url;
                objCTCFOutput3.SiteCollection = siteColUrl;

                list.EnsureProperty(l => l.ContentTypesEnabled);

                if (!list.ContentTypesEnabled)
                {
                    return;
                }

                ContentTypeCollection ctCol = list.ContentTypes;
                list.Context.Load(ctCol);
                list.Context.ExecuteQuery();

                foreach (ContentType ct in ctCol)
                {
                    try
                    {
                        string contentTypeId = ct.Id.StringValue;
                        if (contentTypeId.StartsWith(targetContentTypeId, StringComparison.InvariantCultureIgnoreCase))
                        {
                            if (ct.Name.Equals(targetContentTypeName, StringComparison.InvariantCultureIgnoreCase))
                            {
                                Logger.LogSuccessMessage(String.Format("FOUND: Content Type [{2}] on LIST [{0}] of WEB: {1}", list.Title, web.Url, targetContentTypeName), true);
                                FileUtility.WriteCsVintoFile(CTCFFileName, objCTCFOutput3, ref headerContentType);
                            }
                            else
                            {
                                Logger.LogSuccessMessage(String.Format("FOUND: Child Content Type [{3}] of [{2}] on LIST [{0}] of WEB: {1}", list.Title, web.Url, targetContentTypeName, ct.Name), true);
                                FileUtility.WriteCsVintoFile(CTCFFileName, objCTCFOutput3, ref headerContentType);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.LogErrorMessage(String.Format("ReportContentTypeUsage() failed on a Content Type of LIST [{0}] of WEB {1}: Error={2}", list.Title, web.Url, ex.Message), false);
                        ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, web.Url, "ColumnORFieldAndTypeUsageReport", ex.Message, ex.ToString(), "ReportContentTypeUsage()", ex.GetType().ToString(), String.Format("ReportContentTypeUsage() failed on a Content Type of LIST [{0}] of WEB {1}: Error={2}", list.Title, web.Url, ex.Message));
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("ReportContentTypeUsage() failed for LIST [{0}] of WEB {1}: Error={2}", list.Title, web.Url, ex.Message), false);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, web.Url, "ColumnORFieldAndTypeUsageReport", ex.Message, ex.ToString(), "ReportContentTypeUsage()", ex.GetType().ToString(), String.Format("ReportContentTypeUsage() failed for LIST [{0}] of WEB {1}: Error={2}", list.Title, web.Url, ex.Message));
            }
        }
        /// <summary>
        /// Returns list of WebApplicationUrls
        /// </summary>
        /// <param name="range">Used range of component input file sheet</param>
        /// <param name="summaryViewColumnText"></param>
        /// <returns></returns>
        public static List <string> GetWebApplicationUrls(Excel.Range range, string summaryViewColumnText)
        {
            List <string> lstWebApplicationUrls = null;

            try
            {
                if (range.Rows.Count > 1)
                {
                    for (int i = 1; i <= range.Columns.Count; i++)
                    {
                        try
                        {
                            string str = (string)(range.Cells[1, i] as Excel.Range).Value2;
                            //Find for WebApplicationUrl column name
                            if (str.Equals(summaryViewColumnText))
                            {
                                Excel.Range ctRange2 = range.Columns[i];
                                //Get all WebApplicationUrl values into array
                                System.Array ctWebAppValue = (System.Array)ctRange2.Cells.Value;
                                //Convert array into List<string>
                                lstWebApplicationUrls = ctWebAppValue.OfType <object>().Select(o => o.ToString()).ToList();
                                //Remove header name 'WebApplicationUrl'
                                lstWebApplicationUrls.Remove(lstWebApplicationUrls.First());
                                List <string> lstNewWebAppUrls = new List <string>();
                                //Trim '/' character when WebApplication ends with '/'
                                lstNewWebAppUrls = lstWebApplicationUrls.Select(item => item.EndsWith("/") ? item.TrimEnd('/') : item).ToList();

                                return(lstNewWebAppUrls);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.LogErrorMessage(string.Format("[GeneratePivotReports][ComponentsSummaryView][GetWebApplicationUrls][Exception]: " + ex.Message + "\n" + ex.StackTrace.ToString()), true);
                            ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "Pivot", ex.Message, ex.ToString(),
                                                        "[GeneratePivotReports]: GetWebApplicationUrls", ex.GetType().ToString(), Constants.NotApplicable);
                        }
                    }
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(string.Format("[GeneratePivotReports][ComponentsSummaryView][GetWebApplicationUrls][Exception]: " + ex.Message + "\n" + ex.StackTrace.ToString()), true);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "Pivot", ex.Message, ex.ToString(),
                                            "[GeneratePivotReports]: GetWebApplicationUrls", ex.GetType().ToString(), Constants.NotApplicable);
            }
            finally
            {
                range = null;
            }
            return(lstWebApplicationUrls);
        }
Пример #20
0
        private static void DeleteJsLinks(ClientContext context, Site site)
        {
            var existingActions = site.UserCustomActions;

            context.Load(existingActions);
            context.ExecuteQuery();

            var actions = existingActions.ToArray();

            if (actions.Count() == 0)
            {
                Logger.LogInfoMessage(String.Format("No ScriptLink Action [{0}] items are present on site [{1}]...", Constants.ScriptLinkDescription, site.Url), false);
                return;
            }

            Logger.LogInfoMessage(String.Format("Removing all existing ScriptLink Action [{0}] items from site [{1}]...", Constants.ScriptLinkDescription, site.Url), false);

            foreach (var action in actions)
            {
                if (action.Description.Equals(Constants.ScriptLinkDescription, StringComparison.InvariantCultureIgnoreCase) &&
                    action.Location.Equals(Constants.ScriptLinkLocation, StringComparison.InvariantCultureIgnoreCase)
                    )
                {
                    ManageMaintenanceBannersOutput csvObject = new ManageMaintenanceBannersOutput();
                    csvObject.BannerOperation   = "Remove Banner";
                    csvObject.SiteCollectionUrl = site.Url;
                    csvObject.ScriptLinkName    = Constants.ScriptLinkDescription;
                    csvObject.ScriptLinkFile    = "N/A";

                    try
                    {
                        action.DeleteObject();
                        context.ExecuteQuery();

                        csvObject.Status = Constants.Success;
                        FileUtility.WriteCsVintoFile(csvOutputFileSpec, csvObject, ref csvOutputFileHasHeader);

                        Logger.LogInfoMessage(String.Format("ScriptLink Action [{0}] removed from site [{1}]", Constants.ScriptLinkDescription, site.Url), false);
                    }
                    catch (Exception ex)
                    {
                        csvObject.Status = Constants.Failure;
                        FileUtility.WriteCsVintoFile(csvOutputFileSpec, csvObject, ref csvOutputFileHasHeader);

                        Logger.LogErrorMessage(String.Format("DeleteJsLinks() failed to remove ScriptLink Action [{0}] from site [{1}]: Error={2}", Constants.ScriptLinkDescription, site.Url, ex.Message), false);
                        ExceptionCsv.WriteException(
                            "N/A", site.Url, "N/A",
                            "MaintenanceBanner",
                            ex.Message, ex.ToString(), "DeleteJsLinks", ex.GetType().ToString(),
                            String.Format("DeleteJsLinks() failed to remove ScriptLink Action [{0}] from site [{1}]", Constants.ScriptLinkDescription, site.Url)
                            );
                    }
                }
            }
        }
Пример #21
0
        public static void DoWork()
        {
            outputPath = Environment.CurrentDirectory;
            string webUrl = string.Empty;
            string serverRelativePageUrl = string.Empty;
            string webPartID             = string.Empty;
            string timeStamp             = DateTime.Now.ToString("yyyyMMdd_hhmmss");

            //Trace Log TXT File Creation Command
            Logger.OpenLog("WebpartProperties", timeStamp);

            System.Console.ForegroundColor = System.ConsoleColor.Cyan;
            System.Console.WriteLine("Please enter Web Url : ");
            System.Console.ResetColor();
            webUrl = System.Console.ReadLine().ToLower();
            if (string.IsNullOrEmpty(webUrl))
            {
                Logger.LogErrorMessage("[WebpartProperties: DoWork]WebUrl should not be empty or null. Operation aborted...", true);
                return;
            }

            System.Console.ForegroundColor = System.ConsoleColor.Cyan;
            System.Console.WriteLine("Please enter Server Relative PageUrl (E:g- /sites/DTTesting/SitePages/WebPartPage.aspx): ");
            System.Console.ResetColor();
            serverRelativePageUrl = System.Console.ReadLine().ToLower();
            if (string.IsNullOrEmpty(serverRelativePageUrl))
            {
                Logger.LogErrorMessage("[WebpartProperties: DoWork]ServerRelative PageUrl should not be empty or null. Operation aborted...", true);
                return;
            }

            System.Console.ForegroundColor = System.ConsoleColor.Cyan;
            System.Console.WriteLine("Please enter WebPart ID : ");
            System.Console.ResetColor();
            webPartID = System.Console.ReadLine().ToLower();
            if (string.IsNullOrEmpty(webPartID))
            {
                Logger.LogErrorMessage("[WebpartProperties: DoWork]WebPart ID should not be empty or null. Operation aborted...", true);
                return;
            }
            Logger.LogInfoMessage(String.Format("Process started {0}", DateTime.Now.ToString()), true);
            try
            {
                GetWebPartProperties(serverRelativePageUrl, webPartID, webUrl, outputPath);
            }
            catch (Exception ex)
            {
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "WebPartProperties", ex.Message, ex.ToString(), "WebPartProperties: DoWork()", ex.GetType().ToString());
                System.Console.ForegroundColor = System.ConsoleColor.Red;
                Logger.LogErrorMessage("[WebpartProperties: DoWork]. Exception Message: " + ex.Message, true);
                System.Console.ResetColor();
            }
            Logger.LogInfoMessage(String.Format("Process completed {0}", DateTime.Now.ToString()), true);
            Logger.CloseLog();
        }
        private static void ProcessInputFile(string masterPageInputFile, bool replaceMasterUrl, bool replaceCustomMasterUrl, bool replaceBothMaserUrls, string outputDirectory)
        {
            DataTable dtMasterPagesInput = new DataTable();

            try
            {
                dtMasterPagesInput = ImportCSV.Read(masterPageInputFile, Constants.CsvDelimeter);

                List <string> lstWebUrls = dtMasterPagesInput.AsEnumerable()
                                           .Select(r => r.Field <string>("WebUrl"))
                                           .ToList();
                lstWebUrls = lstWebUrls.Distinct().ToList();
                foreach (string webUrl in lstWebUrls)
                {
                    string webApplicationUrl = string.Empty;
                    try
                    {
                        Logger.LogInfoMessage("[ReplaceMasterPage: ProcessInputFile] Processing the Site: " + webUrl, true);
                        if (ProcessWebUrl(webUrl, null, replaceMasterUrl, replaceCustomMasterUrl, replaceBothMaserUrls))
                        {
                            Logger.LogSuccessMessage("[ReplaceMasterPage:ProcessInputFile]successfully replaced master page for the site " + webUrl + "  and output file is present in the path: " + outputDirectory, true);
                        }
                        else
                        {
                            Logger.LogErrorMessage("[ReplaceMasterPage: ProcessInputFile] Replacing Custom Master Page with OOB Master Page is failed for the site " + webUrl);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.LogErrorMessage("[ReplaceMasterPage: ProcessInputFile]. Exception Message: " + ex.Message, true);
                        ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "ReplaceMasterPage", ex.Message, ex.ToString(), "ProcessInputFile()", ex.GetType().ToString());
                    }
                }
                System.Console.ForegroundColor = System.ConsoleColor.Green;
                Logger.LogSuccessMessage("[ReplaceMasterPage: DoWork] Successfully processed all sites and output file is present in the path: "
                                         + outputPath, true);
                System.Console.ResetColor();
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage("[ReplaceMasterpage: ProcessInputFile]. Exception Message: " + ex.Message, true);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "ReplaceMasterPage", ex.Message, ex.ToString(), "ProcessInputFile()", ex.GetType().ToString());
            }
            finally
            {
                dtMasterPagesInput.Dispose();
            }
        }
Пример #23
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);
        }
Пример #24
0
        public static void GeneratePivotReports(string OutputFolderPath, string PivotConfigXMLFileName, string masterXMLrootNode, string outputPath)
        {
            try
            {
                //Formatting of Output Directory
                FileUtility.ValidateDirectory(ref OutputFolderPath);

                Logger.LogInfoMessage(string.Format("Pivot Report Utility Execution Started for XML: " + PivotConfigXMLFileName), true);

                string PivotConfigXMLFilePath = OutputFolderPath + @"\" + PivotConfigXMLFileName;

                string PivotOutputReportFullPath = String.Empty;

                //XmlNodeList otherNodes = null;
                List <XmlNode> otherNodes = new List <XmlNode>();

                if (System.IO.File.Exists(PivotConfigXMLFilePath))
                {
                    //Load Pivot Config Xml
                    XmlNodeList Components = LoadPivotConfigXML(PivotConfigXMLFilePath, masterXMLrootNode, OutputFolderPath, ref PivotOutputReportFullPath, ref otherNodes, outputPath);

                    if (Components != null)
                    {
                        GeneratePivotReportsUsingCSVFiles(Components, OutputFolderPath, PivotOutputReportFullPath, otherNodes);
                    }
                }
                else
                {
                    string ErrorMessage = "[GeneratePivotReports] File Not Found Error: XML file (" + PivotConfigXMLFileName + ") is not present in path:" + PivotConfigXMLFilePath;
                    Logger.LogErrorMessage(ErrorMessage, true);
                    ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "Pivot", ErrorMessage, Constants.NotApplicable,
                                                "GeneratePivotReports", Constants.NotApplicable, ErrorMessage);
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(string.Format("[GeneratePivotReports][Exception]: " + ex.Message), true);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "Pivot", ex.Message, ex.ToString(),
                                            "GeneratePivotReports", ex.GetType().ToString(), Constants.NotApplicable);
            }
            finally
            {
                System.Console.ForegroundColor = System.ConsoleColor.Green;
                Logger.LogSuccessMessage(string.Format("Pivot Report Utility Execution Completed Successfully & Logger, Exception and Output files are saved in path: " + outputPath), true);
                System.Console.ResetColor();
            }
        }
 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);
     }
 }
Пример #26
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);
        }
Пример #27
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)
                    );
            }
        }
Пример #28
0
        public static void KillSpecificProcess(string processName, string userName = "")
        {
            try
            {
                var processes = from p in Process.GetProcessesByName(processName)
                                select p;

                foreach (Process process in processes)
                {
                    try
                    {
                        if (!string.IsNullOrEmpty(userName) == true)
                        {
                            string ownerName = GetProcessOwner(process.Id);
                            if (userName.Equals(ownerName, StringComparison.InvariantCultureIgnoreCase))
                            {
                                process.Kill();
                                Logger.LogInfoMessage(string.Format("[KillSpecificProcess]" + " Process Name : " + processName + ", User Name : " + userName + " killed successfully "), true);
                            }
                        }
                        else
                        {
                            process.Kill();
                            Logger.LogInfoMessage(string.Format("[KillSpecificProcess]" + " Process Name : " + processName + " killed successfully "), true);
                        }
                    }
                    catch (Exception ex)
                    {
                        ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "Pivot", ex.Message, ex.ToString(),
                                                    "KillSpecificProcess", ex.GetType().ToString(), Constants.NotApplicable);
                        Logger.LogErrorMessage(string.Format("[KillSpecificProcess][Exception]: " + ex.Message), true);
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "Pivot", ex.Message, ex.ToString(),
                                            "KillSpecificProcess", ex.GetType().ToString(), Constants.NotApplicable);
                Logger.LogErrorMessage(string.Format("[KillSpecificProcess][Exception]: " + ex.Message), true);
            }
        }
        /// <summary>
        /// Fills WebApplicationUrl count of component for given webApplicaitonUrl value
        /// </summary>
        /// <param name="lstComponentWebAppUrls">Contains list of WebApplicationUrls of the component</param>
        /// <param name="oSummaryViewSheet">sheet object in which the count to fill</param>
        /// <param name="webAppUrl">WebApplicationUrl value for the count</param>
        /// <param name="componentColumn">Column name/index where to fill the count value</param>
        /// <param name="fontSize"></param>
        /// <param name="fontName"></param>
        public static void FillWebApplicationCount(List <string> lstComponentWebAppUrls, Excel.Worksheet oSummaryViewSheet,
                                                   string webAppUrl, string componentColumn, int fontSize, string fontName)
        {
            try
            {
                //Get the range of sheet to fill count
                var ctWebAppCountRange = oSummaryViewSheet.get_Range(componentColumn, componentColumn);
                if (lstComponentWebAppUrls != null)
                {
                    //Check whether list containing given WebApplicationUrl, if not fill with value 0
                    if (lstComponentWebAppUrls.Contains(webAppUrl, StringComparer.CurrentCultureIgnoreCase))
                    {
                        //Get the count of WebApplicationUrl
                        int curWebAppCTCount = lstComponentWebAppUrls.Where(o => o.ToString().Equals(webAppUrl.ToString())).Count();

                        ctWebAppCountRange.Value2 = curWebAppCTCount.ToString();
                    }
                    else
                    {
                        ctWebAppCountRange.Value2 = "0";
                    }
                }
                else
                {
                    ctWebAppCountRange.Value2 = "0";
                }
                ctWebAppCountRange.Font.Size = fontSize;
                ctWebAppCountRange.Font.Name = fontName;
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage("[GeneratePivotReports][ComponentsSummaryView][FillWebApplicationCount][Exception]: " + ex.Message + "\n" + ex.StackTrace.ToString(), true);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "Pivot", ex.Message, ex.ToString(),
                                            "[GeneratePivotReports]: FillWebApplicationCount", ex.GetType().ToString(), Constants.NotApplicable);
            }
            finally
            {
                lstComponentWebAppUrls = null;
                oSummaryViewSheet      = null;
            }
        }
        public void ChangeMasterPageForDiscoveryOutPut(string DiscoveryUsage_OutPutFolder, string MasterPageUsagePath, string New_MasterPageDetails = "N/A", string Old_MasterPageDetails = "N/A", string SharePointOnline_OR_OnPremise = "N/A", string UserName = "******", string Password = "******", string Domain = "N/A")
        {
            string exceptionCommentsInfo1 = string.Empty;

            try
            {
                //Initialized Exception and Logger. Deleted the Master Page Replace Usage File
                MasterPage_Initialization(DiscoveryUsage_OutPutFolder);

                Logger.AddMessageToTraceLogFile(Constants.Logging, "############## Master Page Trasnformation Utility Execution Started : Using InputCSV ##############");
                Console.WriteLine("############## Master Page Trasnformation Utility Execution Started : Using InputCSV ##############");

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

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

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

                //Reading Master Page Input File
                IEnumerable <MasterPageInput> objMPInput;
                ChangeMasterPageForDiscoveryOutPut_ReadMasterPagesCSV(DiscoveryUsage_OutPutFolder, MasterPageUsagePath, out objMPInput, New_MasterPageDetails, Old_MasterPageDetails, SharePointOnline_OR_OnPremise, UserName, Password, Domain);

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

                Logger.AddMessageToTraceLogFile(Constants.Logging, "############## Master Page Trasnformation Utility Execution Completed : Using InputCSV ##############");
                Console.WriteLine("############## Master Page Trasnformation Utility Execution Completed : Using InputCSV ##############");
            }
            catch (Exception ex)
            {
                Logger.AddMessageToTraceLogFile(Constants.Logging, "[Exception] ChangeMasterPageForDiscoveryOutPut. Exception Message: " + ex.Message);
                ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "MasterPage", ex.Message, ex.ToString(), "ChangeMasterPageForDiscoveryOutPut", ex.GetType().ToString());

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