Пример #1
0
        public static void DoWork()
        {
            string timeStamp = DateTime.Now.ToString("yyyyMMdd_hhmmss");

            outputPath = Environment.CurrentDirectory;
            string webUrl = string.Empty;
            string serverRelativePageUrl = string.Empty;
            string webPartZoneIndex      = string.Empty;
            string webPartZoneID         = string.Empty;
            string webPartFileName       = string.Empty;
            string webPartXmlFilePath    = string.Empty;
            bool   headerAddWebPart      = false;

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

            System.Console.ForegroundColor = System.ConsoleColor.Cyan;
            //System.Console.ResetColor();
            System.Console.WriteLine("Please enter Web Url : ");
            System.Console.ResetColor();
            webUrl = System.Console.ReadLine().ToLower();
            if (string.IsNullOrEmpty(webUrl))
            {
                Logger.LogErrorMessage("[AddWebpart: 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("[AddWebpart: 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 ZoneIndex : ");
            System.Console.ResetColor();
            webPartZoneIndex = System.Console.ReadLine().ToLower();
            if (string.IsNullOrEmpty(webPartZoneIndex))
            {
                Logger.LogErrorMessage("[AddWebpart: DoWork]WebPart ZoneIndex should not be empty or null. Operation aborted...", true);
                return;
            }

            System.Console.ForegroundColor = System.ConsoleColor.Cyan;
            System.Console.WriteLine("Please enter WebPart ZoneID : ");
            System.Console.ResetColor();
            webPartZoneID = System.Console.ReadLine().ToLower();
            if (string.IsNullOrEmpty(webPartZoneID))
            {
                Logger.LogErrorMessage("[AddWebpart: DoWork]WebPart ZoneId should not be empty or null. Operation aborted...", true);
                return;
            }

            System.Console.ForegroundColor = System.ConsoleColor.Cyan;
            System.Console.WriteLine("Please enter WebPart File Name (WebPart must be present in the WebPart gallery) : ");
            System.Console.ResetColor();
            webPartFileName = System.Console.ReadLine().ToLower();
            if (string.IsNullOrEmpty(webPartFileName))
            {
                Logger.LogErrorMessage("[AddWebpart: DoWork]WebPart File Name should not be empty or null. Operation aborted...", true);
                return;
            }

            System.Console.ForegroundColor = System.ConsoleColor.Cyan;
            System.Console.WriteLine("Please enter WebPart XmlFile Path : ");
            System.Console.ResetColor();
            webPartXmlFilePath = System.Console.ReadLine().ToLower();
            if (string.IsNullOrEmpty(webPartXmlFilePath) || !System.IO.File.Exists(webPartXmlFilePath))
            {
                Logger.LogErrorMessage("[AddWebpart: DoWork]WebPart XmlFile Path is not valid or available. Operation aborted...", true);
                return;
            }
            System.Console.ResetColor();
            Logger.LogInfoMessage(String.Format("Process started {0}", DateTime.Now.ToString()), true);
            try
            {
                AddWebPartStatusBase objWPOutputBase = new AddWebPartStatusBase();
                objWPOutputBase.WebApplication    = Constants.NotApplicable;
                objWPOutputBase.SiteCollection    = Constants.NotApplicable;
                objWPOutputBase.WebUrl            = webUrl;
                objWPOutputBase.WebPartFileName   = webPartFileName;
                objWPOutputBase.ZoneID            = webPartZoneID;
                objWPOutputBase.ZoneIndex         = webPartZoneIndex;
                objWPOutputBase.PageUrl           = serverRelativePageUrl;
                objWPOutputBase.ExecutionDateTime = DateTime.Now.ToString();

                if (AddWebPartToPage(webUrl, webPartFileName, webPartXmlFilePath, webPartZoneIndex, webPartZoneID, serverRelativePageUrl, outputPath))
                {
                    System.Console.ForegroundColor = System.ConsoleColor.Green;
                    Logger.LogSuccessMessage("[AddWebPart: DoWork] Successfully Added WebPart and output file is present in the path: " + outputPath, true);
                    System.Console.ResetColor();
                    objWPOutputBase.Status = Constants.Success;
                }
                else
                {
                    Logger.LogInfoMessage("Adding WebPart to the page is failed for the site " + webUrl);
                    objWPOutputBase.Status = Constants.Failure;
                }

                if (!System.IO.File.Exists(outputPath + @"\" + Constants.AddWebPartStatusFileName + timeStamp + Constants.CSVExtension))
                {
                    headerAddWebPart = false;
                }
                else
                {
                    headerAddWebPart = true;
                }

                FileUtility.WriteCsVintoFile(outputPath + @"\" + Constants.AddWebPartStatusFileName + timeStamp + Constants.CSVExtension, objWPOutputBase, ref headerAddWebPart);
            }
            catch (Exception ex)
            {
                System.Console.ForegroundColor = System.ConsoleColor.Red;
                Logger.LogErrorMessage("[AddWebPart: DoWork]. Exception Message: " + ex.Message, true);
                System.Console.ResetColor();
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "AddWebPart", ex.Message, ex.ToString(), "AddWebpart: DoWork()", ex.GetType().ToString());
            }
            Logger.LogInfoMessage(String.Format("Process completed {0}", DateTime.Now.ToString()), true);
            Logger.CloseLog();
        }
        public static void DoWork()
        {
            string timeStamp = DateTime.Now.ToString("yyyyMMdd_hhmmss");
            string eventReceiverInputFile = string.Empty;

            Logger.OpenLog("DeleteEventReceivers", timeStamp);

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

            if (!ReadInputFile(ref eventReceiverInputFile))
            {
                System.Console.ForegroundColor = System.ConsoleColor.Red;
                Logger.LogErrorMessage("Event Receivers 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 = eventReceiverInputFile;

            if (System.IO.File.Exists(inputFileSpec))
            {
                Logger.LogInfoMessage(String.Format("Scan starting {0}", DateTime.Now.ToString()), true);
                //Read Input file
                IEnumerable <MissingEventReceiversInput> objInputMissingEventReceivers = ImportCSV.ReadMatchingColumns <MissingEventReceiversInput>(inputFileSpec, Constants.CsvDelimeter);
                if (objInputMissingEventReceivers != null && objInputMissingEventReceivers.Any())
                {
                    try
                    {
                        string csvFile = Environment.CurrentDirectory + @"/" + Constants.DeleteEventReceiversStatus + 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} event receivers ...", objInputMissingEventReceivers.Cast <Object>().Count()), true);

                        foreach (MissingEventReceiversInput MissingEventReceiver in objInputMissingEventReceivers)
                        {
                            DeleteMissingEventReceiver(MissingEventReceiver, csvFile);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.LogErrorMessage(String.Format("[DeleteMissingEventReceivers: DoWork] failed: Error={0}", ex.Message), true);
                        ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "EventReceiver", 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("[DeleteMissingEventReceivers: DoWork]: Input file {0} is not available", inputFileSpec), true);
            }

            Logger.CloseLog();
        }
Пример #3
0
        /// <summary>
        /// Creating Hyper Links of every component in TOC sheet and adding corresponding description against them.
        /// Also Adding Back To Index links and Source file Name texts in every sheets.
        /// </summary>
        /// <param name="PivotOutputReportFullPath"></param>
        /// <param name="htHyperLinks"></param>
        /// <param name="otherNodes"></param>
        public static void Create_HyperLinks(string PivotOutputReportFullPath, List <Hashtable> htHyperLinks, List <XmlNode> otherNodes)
        {
            // Creates a new Excel Application
            Excel.Application excelApp      = new Excel.Application();
            Excel.Workbook    excelWorkbook = null;
            var workbooks = excelApp.Workbooks;

            XmlNode tocNode    = otherNodes.Find(item => item.Name == "TOC");
            XmlNode sourceNode = otherNodes.Find(item => item.Name == "SourceFile");
            XmlNode style      = otherNodes.Find(item => item.Name == "Style");

            Logger.LogInfoMessage(string.Format("[GeneratePivotReports][Create_HyperLinks] Processing Started to add Links in Table of Content Sheet and Back Links in all output sheets"), false);

            try
            {
                excelWorkbook = workbooks.Open(PivotOutputReportFullPath);
            }
            catch
            {
                //Create a new workbook if the existing workbook failed to open.
                excelWorkbook = excelApp.Workbooks.Add();
            }

            try
            {
                // The following gets the Worksheets collection
                Excel.Sheets excelSheets    = excelWorkbook.Worksheets;
                XmlNode      tocHeading     = tocNode.SelectSingleNode("TOCHeading");
                XmlNode      tocTitle       = tocNode.SelectSingleNode("TOCTitle");
                XmlNode      tocDescription = tocNode.SelectSingleNode("TOCDescription");
                XmlNode      sourceHead     = sourceNode.SelectSingleNode("SourceFileHeading");
                XmlNode      backToIndex    = sourceNode.SelectSingleNode("BackToIndex");

                XmlNode tocHeadStyle        = style.SelectSingleNode("TOCStyle").SelectSingleNode("TOCHeading");
                XmlNode tocTitleStyle       = style.SelectSingleNode("TOCStyle").SelectSingleNode("TOCTitle");
                XmlNode tocDescStyle        = style.SelectSingleNode("TOCStyle").SelectSingleNode("TOCDescription");
                XmlNode tocStyle            = style.SelectSingleNode("TOCStyle").SelectSingleNode("Style");
                XmlNode sourceHeadStyle     = style.SelectSingleNode("SourceFileStyle").SelectSingleNode("SourceFileHeading");
                XmlNode sourceFileNameStyle = style.SelectSingleNode("SourceFileStyle").SelectSingleNode("SourceFileName");
                XmlNode backToIndexStyle    = style.SelectSingleNode("SourceFileStyle").SelectSingleNode("BackToIndex");

                string sheetName          = "";
                string sourceFileNameText = "";

                // The following gets Sheet1 for editing
                string          currentSheet   = tocNode.Name;
                Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);

                //Fixed Table Location
                Excel.Range tRange = excelWorksheet.get_Range("A2", "A22");
                //borders.Weight = 1d;
                int rowNumber = 3;

                foreach (var htRowIndex in htHyperLinks)
                {
                    foreach (DictionaryEntry hyperlink in htRowIndex.Cast <DictionaryEntry>().OrderBy(item => item.Key).ToList())
                    {
                        if (!htRowIndex.Keys.Cast <String>().Contains("SummaryView"))
                        {
                            string[] keyValue = hyperlink.Key.ToString().Split('~');
                            sheetName          = keyValue[0];
                            sourceFileNameText = keyValue[1];
                            //to put the header for the table of contents sheet
                            if (rowNumber == 3)
                            {
                                Excel.Range excelCellRowHeader = (Excel.Range)excelWorksheet.get_Range("A2", "B2");
                                excelCellRowHeader.Merge(Missing.Value);
                                excelCellRowHeader.Value = tocHeading.InnerText;
                                excelCellRowHeader.Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                                excelCellRowHeader.Font.Size  = Convert.ToDouble(CheckAttributes("FontSize", tocHeadStyle, style));
                                excelCellRowHeader.Font.Color = CommonHelper.GetColor(CheckAttributes("FontColor", tocHeadStyle, style));
                                Excel.Borders border = excelCellRowHeader.Borders;
                                border.LineStyle = Excel.XlLineStyle.xlContinuous;
                                excelCellRowHeader.Columns.AutoFit();
                                excelCellRowHeader.Font.Bold      = true;
                                excelCellRowHeader.Font.Underline = true;
                                excelCellRowHeader.Font.Name      = CheckAttributes("FontFamily", tocHeadStyle, style);
                                rowNumber++;
                            }

                            if (rowNumber == 4)
                            {
                                var excelCellRowHeader2 = (Excel.Range)excelWorksheet.get_Range("A3");
                                excelCellRowHeader2.Value      = tocTitle.InnerText;
                                excelCellRowHeader2.Font.Color = CommonHelper.GetColor(CheckAttributes("FontColor", tocTitleStyle, style));
                                Excel.Borders border2 = excelCellRowHeader2.Borders;
                                border2.LineStyle = Excel.XlLineStyle.xlContinuous;
                                excelCellRowHeader2.Columns.AutoFit();
                                excelCellRowHeader2.Font.Bold      = true;
                                excelCellRowHeader2.Font.Size      = Convert.ToDouble(CheckAttributes("FontSize", tocTitleStyle, style));
                                excelCellRowHeader2.Font.Name      = CheckAttributes("FontFamily", tocTitleStyle, style);
                                excelCellRowHeader2.Interior.Color = CommonHelper.GetColor(CheckAttributes("BgColor", tocTitleStyle, style));

                                Excel.Range excelCellRowHeader1 = (Excel.Range)excelWorksheet.get_Range("B3");
                                excelCellRowHeader1.Value = tocDescription.InnerText;

                                excelCellRowHeader1.ColumnWidth = Convert.ToDouble(CheckAttributes("ColumnWidth", tocDescStyle, style));
                                excelCellRowHeader1.Font.Color  = CommonHelper.GetColor(CheckAttributes("FontColor", tocDescStyle, style));
                                Excel.Borders border1 = excelCellRowHeader1.Borders;
                                border1.LineStyle                  = Excel.XlLineStyle.xlContinuous;
                                excelCellRowHeader1.Font.Bold      = true;
                                excelCellRowHeader1.Interior.Color = CommonHelper.GetColor(CheckAttributes("BgColor", tocDescStyle, style));
                                excelCellRowHeader1.Font.Size      = Convert.ToDouble(CheckAttributes("FontSize", tocDescStyle, style));
                                excelCellRowHeader1.Font.Name      = CheckAttributes("FontFamily", tocDescStyle, style);
                                rowNumber++;
                            }
                        }
                        else
                        {
                            sheetName = hyperlink.Key.ToString();
                            rowNumber = 4;
                        }

                        // The following gets cell A1 for editing
                        Excel.Range excelCell = (Excel.Range)excelWorksheet.get_Range("A" + rowNumber);
                        excelWorksheet.Activate();
                        //Add the Text for hyper Link in Table of contents Sheet
                        excelCell.Value = sheetName;
                        //var s = tocStyle.Attributes["BgColor"];
                        //excelCell.Font.Color = CommonHelper.GetColor((tocStyle.Attributes["BgColor"].InnerText == null) ? bgColor : tocStyle.Attributes["BgColor"].InnerText);
                        Excel.Borders borders = excelCell.Borders;
                        borders.LineStyle   = Excel.XlLineStyle.xlContinuous;
                        excelCell.Font.Bold = true;
                        excelWorksheet.Hyperlinks.Add(excelCell, "#" + sheetName + "!A1", Type.Missing, Type.Missing, sheetName);

                        excelWorksheet.Application.Range["A" + rowNumber].Select();
                        //excelApp.Selection.Font;
                        excelWorksheet.Application.Selection.Font.Name = CheckAttributes("FontFamily", tocStyle, style);
                        excelWorksheet.Application.Selection.Font.Size = Convert.ToDouble(CheckAttributes("FontSize", tocStyle, style));

                        Excel.Range excelCell3 = (Excel.Range)excelWorksheet.get_Range("B" + rowNumber);
                        //Add the Text for hyper Link in Table of contents Sheet
                        excelCell3.Value      = hyperlink.Value.ToString().Trim();
                        excelCell3.Font.Color = CommonHelper.GetColor(CheckAttributes("FontColor", tocStyle, style));
                        Excel.Borders borders2 = excelCell3.Borders;
                        borders2.LineStyle   = Excel.XlLineStyle.xlContinuous;
                        excelCell3.Font.Size = Convert.ToDouble(CheckAttributes("FontSize", tocStyle, style));
                        excelCell3.WrapText  = true;

                        Excel.Worksheet excelWorksheet2 = (Excel.Worksheet)excelSheets.get_Item(Convert.ToString(sheetName));
                        excelWorksheet2.Activate();
                        Range Line = (Range)excelWorksheet2.Rows[1];
                        Line.Insert();
                        Excel.Range excelCell2 = (Excel.Range)excelWorksheet2.get_Range(Convert.ToString("A1"));
                        excelCell2.Value = backToIndex.InnerText;
                        excelWorksheet2.Hyperlinks.Add(excelCell2, "#" + currentSheet + "!A1", Type.Missing, Type.Missing, Type.Missing);

                        excelWorksheet2.Application.Range["A1"].Select();
                        //excelApp.Selection.Font;
                        excelWorksheet2.Application.Selection.Font.Name = CheckAttributes("FontFamily", backToIndexStyle, style);
                        excelWorksheet2.Application.Selection.Font.Size = Convert.ToDouble(CheckAttributes("FontSize", backToIndexStyle, style));

                        if (!sheetName.Equals("SummaryView"))
                        {
                            //Get the range of sheet to fill count
                            Excel.Range sourceFileTitle = excelWorksheet2.get_Range("B1", "B1");
                            sourceFileTitle.Value      = sourceHead.InnerText.Trim();
                            sourceFileTitle.Font.Color = CommonHelper.GetColor(CheckAttributes("FontColor", sourceHeadStyle, style));
                            sourceFileTitle.Font.Size  = Convert.ToDouble(CheckAttributes("FontSize", sourceHeadStyle, style));
                            sourceFileTitle.Style.VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignTop;
                            sourceFileTitle.Font.Bold = true;
                            sourceFileTitle.Columns.AutoFit();

                            //Get the range of sheet to fill count
                            Excel.Range sourceFileName = excelWorksheet2.get_Range("C1", "F1");
                            sourceFileName.Merge();
                            sourceFileName.Value      = sourceFileNameText;
                            sourceFileName.Font.Color = CommonHelper.GetColor(CheckAttributes("FontColor", sourceFileNameStyle, style));
                            sourceFileName.Font.Size  = Convert.ToDouble(CheckAttributes("FontSize", sourceFileNameStyle, style));
                            sourceFileName.Style.VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignTop;
                            sourceFileName.Columns.AutoFit();
                        }
                        rowNumber++;
                    }
                }
                tRange.Columns.AutoFit();

                // Close the excel workbook
                excelWorkbook.Close(true, Type.Missing, Type.Missing);
                workbooks.Close();
                excelApp.Application.Quit();
                excelApp.Quit();
                Marshal.ReleaseComObject(excelSheets);
                Marshal.ReleaseComObject(excelWorkbook);
                Marshal.ReleaseComObject(workbooks);

                Logger.LogInfoMessage(string.Format("[GeneratePivotReports][Create_HyperLinks] Process Completed to add Links in Table of Content Sheet and Back Links in all output sheets"), true);
            }
            catch (Exception ex)
            {
                if (excelWorkbook != null)
                {
                    excelWorkbook.Save();
                    excelWorkbook.Close();
                }

                if (excelApp != null)
                {
                    excelApp.Quit();
                    excelApp.Application.Quit();
                }

                Marshal.ReleaseComObject(workbooks);
                Marshal.ReleaseComObject(excelWorkbook);

                Logger.LogErrorMessage(string.Format("[GeneratePivotReports][Create_HyperLinks][Exception]: " + ex.Message + "\n" + ex.StackTrace.ToString()), true);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "Pivot", ex.Message, ex.ToString(),
                                            "[GeneratePivotReports]: Create_HyperLinks", ex.GetType().ToString(), Constants.NotApplicable);
            }
            finally
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                Marshal.ReleaseComObject(excelApp);
            }
        }
Пример #4
0
        public void DownloadFileFromHive(string absoluteFilePath, string outPutFolder, string SharePointOnline_OR_OnPremise = Constants.OnPremise, string UserName = "******", string Password = "******", string Domain = "NA")
        {
            bool   headerCSVColumns       = false;
            string exceptionCommentsInfo1 = string.Empty;

            GhostingAndUnGhosting_Initialization(outPutFolder, "DOWNLOAD");

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

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

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

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

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

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

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

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

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

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

            Logger.AddMessageToTraceLogFile(Constants.Logging, "############## DownloadFileFromHive - Trasnformation Utility Execution Completed for Web ##############");
            Console.WriteLine("############## DownloadFileFromHive - Trasnformation Utility Execution Completed for Web ##############");
        }
Пример #5
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));
            }
        }
Пример #6
0
        /// <summary>
        /// Main method
        /// </summary>
        /// <param name="args">Event Arguments</param>
        public static void Main(string[] args)
        {
            string input  = String.Empty;
            string input1 = string.Empty;
            string input2 = string.Empty;

            GetCredentials();
            //Excception CSV Creation Command
            ExceptionCsv objException = ExceptionCsv.CurrentInstance;

            objException.CreateLogFile(Environment.CurrentDirectory);

            do
            {
                ShowUsage();
                input = System.Console.ReadLine();
                switch (input.ToUpper(System.Globalization.CultureInfo.CurrentCulture))
                {
                case "1":
                    do
                    {
                        System.Console.ForegroundColor = System.ConsoleColor.Green;
                        System.Console.WriteLine("");
                        System.Console.WriteLine("Your selected Operation [1: \"Transformation\"] supports the following operations.");
                        System.Console.WriteLine("Please type an operation number and press [Enter] to execute the specified operation:");
                        System.Console.WriteLine("1. Add OOTB Web Part or App Part to a page");
                        System.Console.WriteLine("2. Replace FTC Web Part with OOTB Web Part or App Part on a page");
                        System.Console.WriteLine("3. Replace MasterPage");
                        System.Console.WriteLine("4. Reset Device Channel Mapping Files");
                        System.Console.WriteLine("5. Manage [Add|Remove] Maintenance Banners");
                        System.Console.WriteLine("6. Exit");
                        System.Console.ResetColor();
                        input1 = System.Console.ReadLine();
                        switch (input1)
                        {
                        case "1":
                            AddWebPart.DoWork();
                            break;

                        case "2":
                            ReplaceWebPart.DoWork();
                            break;

                        case "3":
                            ReplaceMasterPage.DoWork();
                            break;

                        case "4":
                            ResetDeviceChannelMappingFiles.DoWork();
                            break;

                        case "5":
                            ManageMaintenanceBanners.DoWork();
                            break;

                        case "6":
                            break;

                        default:
                            break;
                        }
                    } while (input1.ToUpper(System.Globalization.CultureInfo.CurrentCulture) != "6");
                    break;

                case "2":
                    do
                    {
                        System.Console.ForegroundColor = System.ConsoleColor.Magenta;
                        System.Console.WriteLine("");
                        System.Console.WriteLine("Your selected Operation [2: \"Clean-Up\"] supports the following operations.");
                        System.Console.WriteLine("Please type an operation number and press [Enter] to execute the specified operation:");
                        System.Console.WriteLine("1. Delete Missing Setup Files");
                        System.Console.WriteLine("2. Delete Missing Features");
                        System.Console.WriteLine("3. Delete Missing Event Receivers");
                        System.Console.WriteLine("4. Delete Workflow Associations");
                        System.Console.WriteLine("5. Delete List Templates");
                        System.Console.WriteLine("6. Delete Missing Webparts");
                        System.Console.WriteLine("7. Exit");
                        System.Console.ResetColor();
                        input1 = System.Console.ReadLine();
                        switch (input1)
                        {
                        case "1":
                            DeleteMissingSetupFiles.DoWork();
                            break;

                        case "2":
                            DeleteMissingFeatures.DoWork();
                            break;

                        case "3":
                            DeleteMissingEventReceivers.DoWork();
                            break;

                        case "4":
                            DeleteMissingWorkflowAssociations.DoWork();
                            break;

                        case "5":
                            DownloadAndModifyListTemplate.DeleteListTemplate();
                            break;

                        case "6":
                            DeleteWebparts.DoWork();
                            break;

                        case "7":
                            break;

                        default:
                            break;
                        }
                    } while (input1.ToUpper(System.Globalization.CultureInfo.CurrentCulture) != "7");
                    break;

                case "3":
                    do
                    {
                        System.Console.ForegroundColor = System.ConsoleColor.DarkCyan;
                        System.Console.WriteLine("");
                        System.Console.WriteLine("Your selected Operation [3: \"Self-Service Reports\"] supports the following operations.");
                        System.Console.WriteLine("Please type an operation number and press [Enter] to execute the specified operation:");
                        System.Console.WriteLine("1. Generate List Template Report with FTC Analysis");
                        System.Console.WriteLine("2. Generate Site Template Report with FTC Analysis");
                        System.Console.WriteLine("3. Generate Site Column/Custom Field & Content Type Usage Report");
                        System.Console.WriteLine("4. Generate Non-Default Master Page Usage Report");
                        System.Console.WriteLine("5. Generate Site Collection Report (PPE-Only)");
                        System.Console.WriteLine("6. Generate Web Part Usage Report");
                        System.Console.WriteLine("7. Generate Web Part Properties Report");
                        System.Console.WriteLine("8. Generate Security Group Report");
                        System.Console.WriteLine("9. Generate Pivot Reports ");
                        System.Console.WriteLine("10. Exit ");
                        System.Console.ResetColor();
                        input1 = System.Console.ReadLine();
                        switch (input1)
                        {
                        case "1":
                            DownloadAndModifyListTemplate.DoWork();
                            break;

                        case "2":
                            DownloadAndModifySiteTemplate.DoWork();
                            break;

                        case "3":
                            GenerateColumnAndTypeUsageReport.DoWork();
                            break;

                        case "4":
                            GenerateNonDefaultMasterPageUsageReport.DoWork();
                            break;

                        case "5":
                            System.Console.ForegroundColor = ConsoleColor.Yellow;
                            System.Console.WriteLine("This operation is intended for use only in PPE; use on PROD at your own risk.");
                            System.Console.WriteLine("For PROD, it is safer to generate the report via the o365 Self-Service Admin Portal.");
                            System.Console.ResetColor();
                            System.Console.ForegroundColor = System.ConsoleColor.Cyan;
                            System.Console.WriteLine("Press \"y\" only if you wish to continue.  Press any other key to abort this operation.");
                            System.Console.ResetColor();

                            input2 = System.Console.ReadLine();
                            if (input2.ToUpper(System.Globalization.CultureInfo.CurrentCulture) != "Y")
                            {
                                System.Console.WriteLine("Operation aborted by user.");
                                break;
                            }
                            GenerateSiteCollectionReport.DoWork();
                            break;

                        case "6":
                            WebPartUsage.DoWork();
                            break;

                        case "7":
                            WebPartProperties.DoWork();
                            break;

                        case "8":
                            GenerateSecurityGroupReport.DoWork();
                            break;

                        case "9":
                            GeneratePivotReport.DoWork();
                            break;

                        case "10":
                            break;

                        default:
                            break;
                        }
                    } while (input1.ToUpper(System.Globalization.CultureInfo.CurrentCulture) != "10");
                    break;

                case "4":
                    break;

                default:
                    break;
                }
            }while (input.ToUpper(System.Globalization.CultureInfo.CurrentCulture) != "4");
        }
        public MasterPageBase ChangeMasterPageForWeb(string outPutFolder, string WebUrl, string NewMasterPageURL, string OldMasterPageURL = "N/A", bool CustomMasterUrlStatus = true, bool MasterUrlStatus = true, string ActionType = Constants.ActionType_Web, string SharePointOnline_OR_OnPremise = Constants.OnPremise, string UserName = "******", string Password = "******", string Domain = "N/A")
        {
            bool headerMasterPage = false;
            List <MasterPageBase> _WriteMasterList = null;

            ExceptionCsv.WebUrl = WebUrl;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                            if (_UpdateMasterPage)
                            {
                                web.Update();

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

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

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

                            //Update Web
                            web.Update();

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

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

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

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

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

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

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

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

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

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

            return(objMaster);
        }
        public static void DoWork()
        {
            timeStamp = DateTime.Now.ToString("yyyyMMdd_hhmmss");
            bool   processInputFile       = false;
            bool   processWebUrl          = false;
            bool   replaceMasterUrl       = false;
            bool   replaceCustomMasterUrl = false;
            bool   replaceBothMaserUrls   = false;
            string masterPageInputFile    = string.Empty;
            string webUrl = string.Empty;

            try
            {
                outputPath = Environment.CurrentDirectory;
                Logger.OpenLog("ReplaceMasterPage", timeStamp);

                if (!ReadInputOptions(ref processInputFile, ref processWebUrl))
                {
                    System.Console.ForegroundColor = System.ConsoleColor.Red;
                    Logger.LogErrorMessage("Invalid option selected or Exit option is selected. Operation aborted!");
                    System.Console.ResetColor();
                    return;
                }

                if (processInputFile)
                {
                    if (!ReadInputFile(ref masterPageInputFile))
                    {
                        System.Console.ForegroundColor = System.ConsoleColor.Red;
                        Logger.LogErrorMessage("MasterPage 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;
                    }
                    if (!ReadMasterUrlReplaceOptions(ref replaceMasterUrl, ref replaceCustomMasterUrl, ref replaceBothMaserUrls))
                    {
                        System.Console.ForegroundColor = System.ConsoleColor.Red;
                        Logger.LogErrorMessage("Invalid option selected. Operation aborted!");
                        System.Console.ResetColor();
                        return;
                    }
                    ProcessInputFile(masterPageInputFile, replaceMasterUrl, replaceCustomMasterUrl, replaceBothMaserUrls, outputPath);
                }

                if (processWebUrl)
                {
                    System.Console.ForegroundColor = System.ConsoleColor.Cyan;
                    Logger.LogMessage("Enter WebUrl to replace MasterPage: ");
                    System.Console.ResetColor();
                    webUrl = System.Console.ReadLine();
                    if (string.IsNullOrEmpty(webUrl))
                    {
                        Logger.LogErrorMessage("[ReplaceMasterPage: DoWork]WebUrl should not be empty or null. Operation aborted...", true);
                        return;
                    }
                    if (!ReadMasterUrlReplaceOptions(ref replaceMasterUrl, ref replaceCustomMasterUrl, ref replaceBothMaserUrls))
                    {
                        System.Console.ForegroundColor = System.ConsoleColor.Red;
                        Logger.LogErrorMessage("Invalid option selected. Operation aborted!");
                        System.Console.ResetColor();
                        return;
                    }
                    if (ProcessWebUrl(webUrl, null, replaceMasterUrl, replaceCustomMasterUrl, replaceBothMaserUrls))
                    {
                        System.Console.ForegroundColor = System.ConsoleColor.Green;
                        Logger.LogSuccessMessage("[ReplaceMasterPage: DoWork] Successfully processed given WebUrl and output file is present in the path: "
                                                 + outputPath, true);
                        System.Console.ResetColor();
                    }
                    else
                    {
                        Logger.LogErrorMessage("Replacing Custom Master Page with OOB Master Page is failed for the site " + webUrl);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("[ReplaceMasterPage: DoWork] failed: Error={0}", ex.Message), true);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, webUrl, "ReplaceMasterPage", ex.Message, ex.ToString(), "ReplaceMasterPage: DoWork()", ex.GetType().ToString());
            }
            Logger.CloseLog();
        }
        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);
        }
Пример #10
0
        //public static bool flagXML = false;
        public static void DoWork()
        {
            string PivotConfigXMLFileName = string.Empty;
            bool   Discovery    = false;
            bool   PreMigration = false;

            if (!ReadInputOptions(ref Discovery, ref PreMigration))
            {
                System.Console.ForegroundColor = System.ConsoleColor.Red;
                System.Console.WriteLine("Invalid option selected or Exit option is selected. Operation aborted!");
                System.Console.ResetColor();
                return;
            }

            if (Discovery)
            {
                timeStamp = DateTime.Now.ToString("yyyyMMdd_hhmmss");
                try
                {
                    Environment.CurrentDirectory = outputPath;
                    Logger.OpenLog("DT_GeneratePivotReport", timeStamp);
                    PivotConfigXMLFileName = "Discovery-Pivot.xml";

                    //Reading Usage Files Path
                    ReadInputFilesPath(ref OutputFolderPath, PivotConfigXMLFileName, Constants.DTFileName);
                    if (flag == true)
                    {
                        return;
                    }

                    GeneratePivotReports(OutputFolderPath, PivotConfigXMLFileName, "Component", outputPath);
                }
                catch (Exception ex)
                {
                    Logger.LogErrorMessage(String.Format("[PivotReports: DoWork] failed: Error={0}", ex.Message), true);
                    ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "PivotReports", ex.Message, ex.ToString(), "[PivotReports]: DoWork()", ex.GetType().ToString(), Constants.NotApplicable);
                }
                Logger.CloseLog();
            }

            else if (PreMigration)
            {
                timeStamp = DateTime.Now.ToString("yyyyMMdd_hhmmss");
                try
                {
                    Environment.CurrentDirectory = outputPath;
                    Logger.OpenLog("PreMT_GeneratePivotReport", timeStamp);
                    PivotConfigXMLFileName = "PreMT-Pivot.xml";

                    //Reading Usage Files Path
                    ReadInputFilesPath(ref OutputFolderPath, PivotConfigXMLFileName, Constants.PreMTFileName);
                    if (flag == true)
                    {
                        return;
                    }

                    GeneratePivotReports(OutputFolderPath, PivotConfigXMLFileName, "Component", outputPath);
                }
                catch (Exception ex)
                {
                    Logger.LogErrorMessage(String.Format("[PivotReports: DoWork] failed: Error={0}", ex.Message), true);
                    ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "PivotReports", ex.Message, ex.ToString(), "[PivotReports]: DoWork()", ex.GetType().ToString(), Constants.NotApplicable);
                }
                Logger.CloseLog();
            }
        }
Пример #11
0
        /// <summary>
        /// Iterating through all the components for slicers, pivot, row fields, and value columns and collecting them in Hash Tables
        /// Passing them to other method wherein all the pivot tables, slicers, and row fields, filters are created based on values from
        /// their hashTables.
        /// </summary>
        /// <param name="InputCSVFolderPath"></param>
        /// <param name="component"></param>
        /// <param name="PivotOutputReportFullPath"></param>
        /// <param name="dSummaryViewComponents"></param>
        /// <param name="htHyperLinks"></param>
        /// <param name="otherNodes"></param>
        private static void GeneratePivotReportForMultipleFiles(
            string InputCSVFolderPath,
            XmlNode component, string PivotOutputReportFullPath,
            ref Dictionary <string, string[]> dSummaryViewComponents,
            ref Hashtable htHyperLinks,
            List <XmlNode> otherNodes)
        {
            StringBuilder exceptionCommentsInfo = new StringBuilder();
            int           numberOfFilesCount    = 1;
            string        sheetName             = string.Empty;

            try
            {
                //Pivot Report - RowFields
                Hashtable htRowPivotfields;
                //Pivot Report - PageFilters
                Hashtable htPivotPageFilters;
                //Pivot Report - PageSlicers
                Hashtable htPageSlicers;

                //Slicers and Dicers HashTables
                Hashtable htComponentSliceandDiceViews = new Hashtable();

                int RowPivotfieldCount = 1, PivotPageFiltersCount = 1;
                int sliceandDiceViewsCount = 1;

                //Get the Components Lists by Reading the Component Tags and Attribute.
                //Example Content Types, Master Pages, etc from Pivot Config XML
                string componentName     = component.Attributes["Name"].InnerText;
                string InputFileName     = component.Attributes["InputFileName"].InnerText;
                string summaryViewColumn = component.Attributes["SummaryViewColumn"].InnerText;
                string description       = component.SelectSingleNode("Description").InnerText;
                string componentSliceAndDiceSheetname = "";

                //Exception Comments
                exceptionCommentsInfo.Append("ComponentName: " + componentName + ", InputFileName: " + InputFileName + ", SummaryViewColumn: " + summaryViewColumn);

                //Read All The INput File CSV for a Component. If Any Components has the multiple Usage or Input File, we are reading all files
                //Example: If Content Type Usage Files are - ContentType_Usage.csv, ContentType_Usage_03112016_035049.csv
                string searchpattern = System.IO.Path.GetFileNameWithoutExtension(InputCSVFolderPath + "\\" + InputFileName);
                searchpattern = searchpattern + "*.csv";
                string[] files = FileUtility.FindAllFilewithSearchPattern(InputCSVFolderPath, searchpattern);

                //Null Check
                if (files != null)
                {
                    if (files.Count() > 0)
                    {
                        foreach (string filePath in files)
                        {
                            string inputCSVFile  = filePath;
                            string inputFileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);

                            htRowPivotfields   = new Hashtable();
                            htPivotPageFilters = new Hashtable();
                            htPageSlicers      = new Hashtable();

                            if (System.IO.File.Exists(inputCSVFile))
                            {
                                //Get Data InputDataSheetName
                                string inputDataSheetName = System.IO.Path.GetFileNameWithoutExtension(filePath);

                                //Deleting columns from csv
                                if (inputDataSheetName == "CThavingFeatureIDTag_Definition_Usage" || inputDataSheetName == "ListTemplates_Usage" || inputDataSheetName == "PreMT_CThavingFeatureIDTag_Definition")
                                {
                                    deleteColumnFromCSV(inputDataSheetName, InputCSVFolderPath, inputCSVFile, inputFileName);
                                }

                                exceptionCommentsInfo.Clear();
                                exceptionCommentsInfo.Append(", InputDataSheetName: " + inputDataSheetName);

                                Excel.Application oApp;
                                Excel.Worksheet   oSheet;
                                Excel.Workbook    oBook = null;

                                oApp = new Excel.Application();

                                try
                                {
                                    oBook = oApp.Workbooks.Open(inputCSVFile);
                                    if (inputDataSheetName.Length >= Constants.SheetNameMaxLength)
                                    {
                                        oSheet = (Excel.Worksheet)oBook.Sheets.get_Item(1);
                                    }
                                    else
                                    {
                                        oSheet = (Excel.Worksheet)oBook.Sheets.get_Item(inputDataSheetName);
                                    }

                                    // Now capture range of the first sheet
                                    Excel.Range oRange = oSheet.UsedRange;

                                    if (oRange.Rows.Count > 1)
                                    {
                                        if (files.Count() > 1)
                                        {
                                            sheetName = componentName + "_" + numberOfFilesCount;
                                            //SliceAndDiceSheet
                                            componentSliceAndDiceSheetname = componentName + "_" + numberOfFilesCount + Constants.SliceAndDiceSheet_Suffix;
                                        }
                                        else
                                        {
                                            sheetName = componentName;
                                            componentSliceAndDiceSheetname = componentName + Constants.SliceAndDiceSheet_Suffix;
                                        }

                                        dSummaryViewComponents.Add(sheetName, new string[] { inputCSVFile, summaryViewColumn });

                                        string pivotCountField = string.Empty; string pivotSliceandDiceCountField = string.Empty;
                                        string slicerStyle = string.Empty;

                                        //Read Item Tags inside the Component Tag, to generate - Pivot and Slice and Dice View
                                        foreach (XmlNode ItemNode in component.SelectNodes("Item"))
                                        {
                                            string itemType = ItemNode.Attributes["Type"].InnerText;

                                            //Create Pivot View
                                            if (itemType == "PivotView")
                                            {
                                                var count = ItemNode.SelectSingleNode("ValueColumn");
                                                pivotCountField = count.Attributes["Name"].InnerText;

                                                var slicerstyle = ItemNode.SelectSingleNode("SlicersStyling");
                                                slicerStyle = slicerstyle.Attributes["Style"].InnerText;

                                                //Row Filter
                                                foreach (XmlNode RowFieldRoot in ItemNode.SelectNodes("Rows"))
                                                {
                                                    foreach (XmlNode rowFeild in RowFieldRoot.ChildNodes)
                                                    {
                                                        string rowPageFieldName = rowFeild.Attributes["Column"].InnerText;
                                                        string rowPageLabel     = rowFeild.Attributes["Label"].InnerText;
                                                        htRowPivotfields.Add(RowPivotfieldCount, rowPageFieldName + "~" + rowPageLabel);
                                                        RowPivotfieldCount++;
                                                    }
                                                }

                                                //Page Filters
                                                foreach (XmlNode FilterFeildRoot in ItemNode.SelectNodes("Filters"))
                                                {
                                                    foreach (XmlNode filterFeild in FilterFeildRoot.ChildNodes)
                                                    {
                                                        string filterName = filterFeild.InnerText;
                                                        htPivotPageFilters.Add(PivotPageFiltersCount, filterName);
                                                        PivotPageFiltersCount++;
                                                    }
                                                }

                                                //Slicers
                                                foreach (XmlNode SlicersRoot in ItemNode.SelectNodes("Slicers"))
                                                {
                                                    int i = 0;
                                                    i = SlicersRoot.ChildNodes.Count - 1;
                                                    foreach (XmlNode SlicersRootFeild in SlicersRoot.ChildNodes)
                                                    {
                                                        string slicerName = SlicersRootFeild.InnerText;
                                                        htPageSlicers.Add(i, slicerName + "~" + slicerStyle);
                                                        i--;
                                                    }
                                                }
                                            }

                                            //Create Slice and Dice View Sheet
                                            if (itemType == "SliceDiceView")
                                            {
                                                //Loop views for each Component
                                                foreach (XmlNode viewsNode in ItemNode.SelectNodes("Views"))
                                                {
                                                    foreach (XmlNode viewNode in viewsNode.ChildNodes)
                                                    {
                                                        htComponentSliceandDiceViews.Add(inputDataSheetName + sliceandDiceViewsCount, viewNode.OuterXml);
                                                        sliceandDiceViewsCount++;
                                                    }
                                                }
                                            }
                                        }

                                        //Pivot Sheet
                                        string componentPivotSheetName = sheetName;
                                        //Length of Sheet Name Should be less than 31 Char
                                        if (componentPivotSheetName.Length >= Constants.SheetNameMaxLength)
                                        {
                                            componentPivotSheetName = componentPivotSheetName.Substring(0, Constants.SheetNameMaxLength);
                                        }


                                        //Length of Sheet Name Should be less than 31 Char
                                        if (componentSliceAndDiceSheetname.Length >= Constants.SheetNameMaxLength)
                                        {
                                            componentSliceAndDiceSheetname = componentSliceAndDiceSheetname.Substring(0, Constants.SheetNameMaxLength);
                                        }

                                        //Create Pivot View and Slicer View Sheet
                                        PivotViewHelper.GeneratePivotAndSlicersView(inputCSVFile, PivotOutputReportFullPath, ref componentPivotSheetName, inputDataSheetName, componentPivotSheetName, htRowPivotfields, htPivotPageFilters, htPageSlicers, pivotCountField, component, numberOfFilesCount, otherNodes);

                                        htHyperLinks.Add(sheetName + "~" + inputFileName, description);

                                        RowPivotfieldCount     = 1;
                                        PivotPageFiltersCount  = 1;
                                        htPageSlicers          = null;
                                        htPivotPageFilters     = null;
                                        htRowPivotfields       = null;
                                        sliceandDiceViewsCount = 1;
                                        numberOfFilesCount    += 1;
                                    }
                                    else
                                    {
                                        Logger.LogInfoMessage(string.Format("[GeneratePivotReports][GeneratePivotReportForMultipleFiles]" + " No records available for the component " + componentName + " in file " + inputDataSheetName), true);
                                    }

                                    object misValue = System.Reflection.Missing.Value;
                                    oBook.Close(false, misValue, misValue);

                                    oApp.Application.Quit();
                                    oApp.Quit();

                                    Marshal.ReleaseComObject(oSheet);
                                    Marshal.ReleaseComObject(oBook);
                                }
                                catch (Exception ex)
                                {
                                    if (oBook != null)
                                    {
                                        oBook.Close();
                                    }

                                    if (oApp != null)
                                    {
                                        oApp.Quit();
                                        oApp.Application.Quit();
                                    }

                                    Marshal.ReleaseComObject(oBook);

                                    Logger.LogErrorMessage(string.Format("[GeneratePivotReports][GeneratePivotReportForMultipleFiles][Exception]: " + ex.Message), true);
                                    ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "Pivot", ex.Message, ex.ToString(),
                                                                "[GeneratePivotReports]: GeneratePivotReportForMultipleFiles", ex.GetType().ToString(), "ExceptionCommentsInfo: " + exceptionCommentsInfo);
                                }
                                finally
                                {
                                    Marshal.ReleaseComObject(oApp);
                                    oApp = null;

                                    GC.Collect();
                                    GC.WaitForPendingFinalizers();
                                }

                                if (inputDataSheetName == "CThavingFeatureIDTag_Definition_Usage" || inputDataSheetName == "ListTemplates_Usage" || inputDataSheetName == "PreMT_CThavingFeatureIDTag_Definition")
                                {
                                    string path1 = InputCSVFolderPath + @"\" + "Backup";
                                    //copy file to backup folder
                                    string destCSVFile1 = path1 + @"\" + inputFileName;
                                    System.IO.File.Copy(destCSVFile1, inputCSVFile, true);

                                    DeleteFolderAndFiles(path1);
                                }
                            }
                            else
                            {
                                string ErrorMessage = "[GeneratePivotReports][GeneratePivotReportForMultipleFiles] File Not Found Error: Input CSV file is not present in path:" + inputCSVFile + ", ExceptionCommentsInfo: " + exceptionCommentsInfo;

                                Logger.LogErrorMessage(ErrorMessage, true);
                                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "Pivot", "File Not Found", ErrorMessage,
                                                            "[GeneratePivotReports]: GeneratePivotReportForMultipleFiles", "File Not Found", "Input CSV File (" + inputCSVFile + ")");
                            }
                        }
                    }
                    else
                    {
                        string ErrorMessage = "[GeneratePivotReports][GeneratePivotReportForMultipleFiles] File Not Found Error: Input CSV file is not present in path:" + InputCSVFolderPath + "\\" + InputFileName + ", " + exceptionCommentsInfo;
                        Logger.LogErrorMessage(ErrorMessage, true);
                        ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "Pivot", "File Not Found", ErrorMessage,
                                                    "[GeneratePivotReports]: GeneratePivotReportForMultipleFiles", "File Not Found", "Input CSV File (" + InputCSVFolderPath + "\\" + InputFileName + ")");
                    }
                }
                else
                {
                    string ErrorMessage = "[GeneratePivotReports][GeneratePivotReportForMultipleFiles] File Not Found Error: Input CSV file is not present in path InputCSVFolderPath: " + InputCSVFolderPath + ", SearchPattern: " + searchpattern + ", " + exceptionCommentsInfo;
                    Logger.LogErrorMessage(ErrorMessage, true);
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(string.Format("[GeneratePivotReports][GeneratePivotReportForMultipleFiles][Exception]: " + ex.Message + ", ExceptionCommentsInfo: " + exceptionCommentsInfo), true);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "Pivot", ex.Message, ex.ToString(),
                                            "[GeneratePivotReports]: GeneratePivotReportForMultipleFiles", ex.GetType().ToString(), exceptionCommentsInfo.ToString());
            }
        }
Пример #12
0
        public static XmlNodeList LoadPivotConfigXML(string PivotConfigXMLFilePath, string masterXMLrootNode, string OutputFolderPath, ref string PivotOutputReportFullPath, ref List <XmlNode> otherNodes, string outputPath)
        {
            XmlNodeList Components = null;

            try
            {
                //[START] Read/Load Pivot XML Config File
                Logger.LogInfoMessage(string.Format("[GeneratePivotReports][LoadPivotConfigXML] Pivot Config XML(" + PivotConfigXMLFilePath + ") loading process has been initiated"), false);
                var xDoc = new XmlDocument();
                xDoc.Load(PivotConfigXMLFilePath);

                var root = xDoc.DocumentElement;

                if (root != null)
                {
                    Components = root.SelectNodes(masterXMLrootNode);

                    if (Components != null)
                    {
                        //Pivot Output Report File Name
                        var    PivotReportOutput         = root.SelectSingleNode("PivotReportOutput");
                        string PivotOutputReportFileName = PivotReportOutput.InnerText;

                        PivotOutputReportFullPath = outputPath + @"\" + PivotOutputReportFileName;

                        otherNodes.Add(root.SelectSingleNode("SummaryView"));
                        otherNodes.Add(root.SelectSingleNode("TOC"));
                        otherNodes.Add(root.SelectSingleNode("Style"));
                        otherNodes.Add(root.SelectSingleNode("SourceFile"));

                        //Delete OLD/Existing Pivot Report
                        if (System.IO.File.Exists(PivotOutputReportFullPath))
                        {
                            System.IO.File.Delete(PivotOutputReportFullPath);
                        }
                        //Delete OLD/Existing Pivot Report

                        Excel.Application excelApplication = new Excel.Application();
                        Excel.Workbook    excelWorkBook    = excelApplication.Workbooks.Add();

                        try
                        {
                            //Creating TOC Sheet - Table Of Content
                            Excel.Worksheet excelWorkSheet = (Excel.Worksheet)excelWorkBook.ActiveSheet;
                            excelWorkSheet.Name = otherNodes.Find(item => item.Name == "TOC").Name;
                            excelApplication.SheetsInNewWorkbook = 1;
                            excelWorkBook.SaveAs(PivotOutputReportFullPath, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value, Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange, Excel.XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
                            excelWorkBook.Close();

                            excelApplication.Application.Quit();
                            excelApplication.Quit();

                            Marshal.ReleaseComObject(excelWorkSheet);
                            Marshal.ReleaseComObject(excelWorkBook);
                            Marshal.ReleaseComObject(excelApplication);

                            excelApplication = null;
                        }
                        catch (Exception ex)
                        {
                            if (excelWorkBook != null)
                            {
                                excelWorkBook.Close();
                            }

                            if (excelApplication != null)
                            {
                                excelApplication.Quit();
                                excelApplication.Application.Quit();
                            }

                            Marshal.ReleaseComObject(excelWorkBook);

                            Logger.LogErrorMessage(string.Format("[GeneratePivotReports][LoadPivotConfigXML][Exception]: " + ex.Message + "\n" + ex.StackTrace.ToString()), true);
                            ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "Pivot", ex.Message, ex.ToString(),
                                                        "[GeneratePivotReports]: LoadPivotConfigXML", ex.GetType().ToString(), "PivotConfigXMLFilePath: " + PivotConfigXMLFilePath);
                        }
                        finally
                        {
                            GC.Collect();
                            GC.WaitForPendingFinalizers();
                            GC.Collect();
                            GC.WaitForPendingFinalizers();
                            Marshal.ReleaseComObject(excelWorkBook);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(string.Format("[GeneratePivotReports][LoadPivotConfigXML][Exception]: " + ex.Message), true);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "Pivot", ex.Message, ex.ToString(),
                                            "[GeneratePivotReports]: GeneratePivotAndSlicersView", ex.GetType().ToString(), "PivotConfigXMLFilePath: " + PivotConfigXMLFilePath);
            }

            Logger.LogInfoMessage(string.Format("[GeneratePivotReports][LoadPivotConfigXML] Pivot Config XML(" + PivotConfigXMLFilePath + ") loading process has been completed"), true);

            return(Components);
        }
Пример #13
0
        private static bool CheckWebPartOrAppPartPresenceInSite(ClientContext clientContext, string targetWebPartXmlFileName, string targetWebPartXmlFilePath)
        {
            bool isWebPartInSite = false;

            webParts targetWebPart = null;

            string webPartPropertiesXml = string.Empty;

            string webPartType = string.Empty;

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

            ExceptionCsv.WebUrl = clientContext.Web.Url;
            string exceptionCommentsInfo1 = string.Empty;

            try
            {
                //Prepare Exception Comments
                exceptionCommentsInfo1 = "Web Url: " + clientContext.Web.Url + ", Target Web Part File Name: " + targetWebPartXmlFileName + " , Target WebPart Xml File Path: " + targetWebPartXmlFilePath;

                using (System.IO.FileStream fs = new System.IO.FileStream(targetWebPartXmlFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    System.IO.StreamReader reader = new System.IO.StreamReader(fs);
                    webPartPropertiesXml = reader.ReadToEnd();
                }

                Logger.LogInfoMessage("[CheckWebPartOrAppPartPresenceInSite] Checking for web part schema version");


                if (webPartPropertiesXml.Contains("WebPart/v2"))
                {
                    Logger.LogInfoMessage("[CheckWebPartOrAppPartPresenceInSite] Web part schema version is V2");


                    XmlDataDocument xmldoc = new XmlDataDocument();
                    xmldoc.LoadXml(webPartPropertiesXml);
                    webPartType = GetWebPartShortTypeName(xmldoc.DocumentElement.GetElementsByTagName("TypeName").Item(0).FirstChild.Value);

                    Logger.LogInfoMessage("[CheckWebPartOrAppPartPresenceInSite] Web part Type: " + webPartType);

                    xmldoc = null;
                }
                else
                {
                    Logger.LogInfoMessage("[CheckWebPartOrAppPartPresenceInSite] Web part schema version is V3");

                    using (System.IO.FileStream fs = new System.IO.FileStream(targetWebPartXmlFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                    {
                        XmlReader     reader     = new XmlTextReader(fs);
                        XmlSerializer serializer = new XmlSerializer(typeof(webParts));
                        targetWebPart = (webParts)serializer.Deserialize(reader);
                        if (targetWebPart != null)
                        {
                            webPartType = GetWebPartShortTypeName(targetWebPart.webPart.metaData.type.name);

                            Logger.LogInfoMessage("[CheckWebPartOrAppPartPresenceInSite] Web part Type: " + webPartType);
                        }
                    }
                }

                if (webPartType.Equals("ClientWebPart", StringComparison.CurrentCultureIgnoreCase))
                {
                    foreach (var item in targetWebPart.webPart.data.properties)
                    {
                        if (item.name.Equals("FeatureId", StringComparison.CurrentCultureIgnoreCase))
                        {
                            Guid featureID = new Guid(item.Value);
                            isWebPartInSite = IsFeatureOnWeb(featureID, clientContext);
                            break;
                        }
                    }
                }
                else
                {
                    Web web = clientContext.Site.RootWeb;
                    clientContext.Load(web, w => w.Url);
                    clientContext.ExecuteQuery();

                    //List list = web.Lists.GetByTitle("Web Part Gallery");
                    //WebPartCatalog, Web Part gallery. Value = 113.

                    List list = null;
                    IEnumerable <List> libraries = clientContext.LoadQuery(web.Lists.Where(l => l.BaseTemplate == 113));
                    clientContext.ExecuteQuery();

                    if (libraries.Any() && libraries.Count() > 0)
                    {
                        list = libraries.First();
                    }

                    clientContext.Load(list);
                    clientContext.ExecuteQueryRetry();

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

                    foreach (ListItem item in items)
                    {
                        if (item["FileLeafRef"].ToString().Equals(targetWebPartXmlFileName, StringComparison.CurrentCultureIgnoreCase))
                        {
                            isWebPartInSite = true;
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Console.ForegroundColor = System.ConsoleColor.Red;
                Logger.LogErrorMessage("[CheckWebPartOrAppPartPresenceInSite] Exception Message: " + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1);
                System.Console.ResetColor();
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, ExceptionCsv.WebUrl, "AddWebPart", ex.Message, ex.ToString(), "CheckWebPartOrAppPartPresenceInSite()", ex.GetType().ToString(), exceptionCommentsInfo1);
                return(isWebPartInSite);
            }

            return(isWebPartInSite);
        }
Пример #14
0
        public static List GetPageList(ref ClientContext clientContext)
        {
            List list = null;

            try
            {
                Web web = clientContext.Web;

                // Get a few properties from the web
                clientContext.Load(web,
                                   w => w.Url,
                                   w => w.ServerRelativeUrl,
                                   w => w.AllProperties,
                                   w => w.WebTemplate);

                clientContext.ExecuteQueryRetry();

                string pagesListID      = string.Empty;
                bool   _IsPublishingWeb = IsPublishingWeb(clientContext, web);

                if (_IsPublishingWeb)
                {
                    Logger.LogInfoMessage("[GetPageList] Web:  + web.Url  is a publishing web");
                    pagesListID = web.AllProperties["__PagesListId"] as string;
                    list        = web.Lists.GetById(new Guid(pagesListID));


                    clientContext.Load(list, l => l.ForceCheckout,
                                       l => l.EnableVersioning,
                                       l => l.EnableMinorVersions,
                                       l => l.EnableModeration,
                                       l => l.Title,
                                       l => l.DraftVersionVisibility,
                                       l => l.DefaultViewUrl);

                    clientContext.ExecuteQueryRetry();
                }
                else
                {
                    clientContext.Load(web.Lists);

                    clientContext.ExecuteQueryRetry();

                    try
                    {
                        //list = web.Lists.GetByTitle(Constants.TEAMSITE_PAGES_LIBRARY);
                        //WebPageLibrary, Wiki Page Library. Value = 119.
                        IEnumerable <List> libraries = clientContext.LoadQuery(web.Lists.Where(l => l.BaseTemplate == 119));
                        clientContext.ExecuteQuery();

                        if (libraries.Any() && libraries.Count() > 0)
                        {
                            list = libraries.First();
                        }

                        clientContext.Load(list);
                        clientContext.ExecuteQueryRetry();
                    }
                    catch
                    {
                        list = null;
                    }
                }
            }
            catch (Exception ex)
            {
                System.Console.ForegroundColor = System.ConsoleColor.Red;
                Logger.LogErrorMessage("[GetPageList] Exception Message: " + ex.Message);
                System.Console.ResetColor();
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "GetPageList", ex.Message, ex.ToString(), "GetPageList()", ex.GetType().ToString());
            }
            return(list);
        }
Пример #15
0
        /// <summary>
        /// Draws Chart or Graph for given component.
        /// </summary>
        /// <param name="componentName"></param>
        /// <param name="oSummarySheet"></param>
        /// <param name="webAppUrlColumn"></param>
        /// <param name="componentColumnCount"></param>
        /// <param name="counter"></param>
        /// <param name="row"></param>
        /// <param name="chartType"></param>
        /// <param name="chartWidth"></param>
        /// <param name="chartHeight"></param>
        /// <param name="chartStyle"></param>
        /// <param name="CellIndex"></param>
        public static void DrawGraph(string componentName, Excel.Worksheet oSummarySheet, string webAppUrlColumn, int componentColumnCount, int counter,
                                     int row, string chartType, int chartWidth, int chartHeight, int chartStyle, char CellIndex)
        {
            //Create chart object
            Excel.Shape _Shape = oSummarySheet.Shapes.AddChart2();

            //Specify type of chart
            if (chartType.Equals("pie"))
            {
                _Shape.Chart.ChartType = Excel.XlChartType.xlPie;
            }
            else if (chartType.Equals("3dpie"))
            {
                _Shape.Chart.ChartType = Excel.XlChartType.xl3DPie;
            }
            else if (chartType.Equals("line"))
            {
                _Shape.Chart.ChartType = Excel.XlChartType.xlLine;
            }
            else if (chartType.Equals("3dline"))
            {
                _Shape.Chart.ChartType = Excel.XlChartType.xl3DLine;
            }
            else if (chartType.Equals("3dcolumn"))
            {
                _Shape.Chart.ChartType = Excel.XlChartType.xl3DColumn;
            }
            else if (chartType.Equals("clusteredcolumn"))
            {
                _Shape.Chart.ChartType = Excel.XlChartType.xlColumnClustered;
            }
            else if (chartType.Equals("3dclusteredcolumn"))
            {
                _Shape.Chart.ChartType = Excel.XlChartType.xl3DColumnClustered;
            }

            //Series object for the graph
            Excel.Series series           = null;
            string       exceptionComment = "[DrawGraph] Processing for Component :" + componentName;

            Logger.LogInfoMessage(String.Format("[GeneratePivotReports][DrawGraph] Processing Started for (" + componentName + ")"), false);

            try
            {
                //Get Series Column from SummaryView table
                string componentColumn = ((Char)(Convert.ToUInt16(CellIndex) + componentColumnCount)).ToString();

                //Set Series column for the Graph
                series = _Shape.Chart.SeriesCollection().Add(oSummarySheet.Range[componentColumn + row + ":"
                                                                                 + componentColumn + (counter).ToString()]);
                //Set Categories column for the graph
                series.XValues = oSummarySheet.Range[webAppUrlColumn + (row + 1).ToString() + ":"
                                                     + webAppUrlColumn + (counter).ToString()];

                //Apply data labels for the graph
                _Shape.Chart.ApplyDataLabels(Excel.XlDataLabelsType.xlDataLabelsShowBubbleSizes);
                //Apply legend for the graph
                _Shape.Chart.HasLegend = true;
                //apply style to chart
                _Shape.Chart.ChartStyle = chartStyle;

                //Hide Display Labels when their value is zero (0)
                Excel.SeriesCollection oSeriesCollection = (Excel.SeriesCollection)_Shape.Chart.SeriesCollection(Type.Missing);
                for (int j = 1; j <= oSeriesCollection.Count; j++)
                {
                    Excel.Series oSeries = (Excel.Series)oSeriesCollection.Item(j);
                    System.Array Values  = (System.Array)((object)oSeries.Values);
                    //Array Values = (Array)oSeries.Values;
                    for (int k = 1; k <= Values.Length; k++)
                    {
                        Excel.DataLabel oDataLabel = (Excel.DataLabel)oSeries.DataLabels(k);
                        string          caption    = oDataLabel.Caption.ToString();
                        if (caption.Equals("0"))
                        {
                            oDataLabel.ShowValue = false;
                        }
                    }
                }

                //Set the Size of the Chart
                _Shape.Width  = chartWidth;
                _Shape.Height = chartHeight;

                //Calculations for the position of Chart
                int columnIndex = counter + 3;
                if (componentColumnCount > 3 && (componentColumnCount / 3 > 0))
                {
                    columnIndex = (counter + 3) + (((componentColumnCount - 1) / 3) * 16);
                }

                string charPositionColumn = webAppUrlColumn;

                if (componentColumnCount % 3 == 2)
                {
                    charPositionColumn = ((Char)(Convert.ToUInt16(CellIndex) + 7)).ToString();
                }

                if (componentColumnCount % 3 == 0)
                {
                    charPositionColumn = ((Char)(Convert.ToUInt16(CellIndex) + 14)).ToString();
                }

                _Shape.Left = (float)oSummarySheet.get_Range(charPositionColumn + columnIndex.ToString()).Left;
                _Shape.Top  = (float)oSummarySheet.get_Range(charPositionColumn + columnIndex.ToString()).Top;

                Logger.LogInfoMessage(String.Format("[GeneratePivotReports][DrawGraph] Process Completed for (" + componentName + ")"), true);
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("[GeneratePivotReports][DrawGraph][Exception]: " + ex.Message + ", " + exceptionComment), true);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "Pivot", ex.Message, ex.ToString(),
                                            "[GeneratePivotReports]: DrawGraph", ex.GetType().ToString(), exceptionComment);
            }
            finally
            {
                _Shape        = null;
                series        = null;
                oSummarySheet = null;
            }
        }
Пример #16
0
        public static ClientContext CreateAuthenticatedUserContext(string domain, string username, SecureString password, string siteUrl)
        {
            ClientContext userContext = new ClientContext(siteUrl);

            try
            {
                if (String.IsNullOrEmpty(domain))
                {
                    // use o365 authentication (SPO-MT or vNext)
                    userContext.Credentials = new SharePointOnlineCredentials(username, password);
                }
                else
                {
                    // use Windows authentication (SPO-D or On-Prem)
                    userContext.Credentials = new NetworkCredential(username, password, domain);
                }

                Web web = userContext.Web;
                userContext.Load(web);
                userContext.ExecuteQuery();
                contextCount      = 0;
                alreadyAuthorized = true;
                return(userContext);
            }
            catch (System.Net.WebException exc)
            {
                if (exc.Message.ToLower().Contains("unauthorized") && alreadyAuthorized == false)
                {
                    contextCount++;
                    if (contextCount == 1)
                    {
                        Logger.LogMessage(String.Format("\n"), true);
                        Logger.LogErrorMessage(String.Format("Attempt [{0}]: You have entered an invalid username or password. The maximum retry attempts allowed for login are 3. You have 2 more attempts.", contextCount, 3 - contextCount), true);
                        ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, siteUrl, "Authentication", exc.Message, exc.ToString(), "CreateAuthenticatedUserContext()", exc.GetType().ToString());
                    }
                    else if (contextCount == 2)
                    {
                        Logger.LogMessage(String.Format("\n"), true);
                        Logger.LogErrorMessage(String.Format("Attempt [{0}]: Incorrect login credentials twice. You have one more attempt. If you fail to enter correct credentials this time, application would be terminated.", contextCount, 3 - contextCount), true);
                        //Logger.LogErrorMessage(String.Format("\nWrong user credentials given for {0} time. {1} attemps remained", contextCount, 3 - contextCount), true);
                        ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, siteUrl, "Authentication", exc.Message, exc.ToString(), "CreateAuthenticatedUserContext()", exc.GetType().ToString());
                    }
                    else if (contextCount == 3)
                    {
                        Logger.LogErrorMessage(String.Format("\n"), true);
                        Logger.LogErrorMessage(String.Format("Attempt [{0}]: You have entered an invalid username or password. Press any key to terminate the application!!", contextCount, 3 - contextCount), true);
                        ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, siteUrl, "Authentication", exc.Message, exc.ToString(), "CreateAuthenticatedUserContext()", exc.GetType().ToString());

                        System.Console.ReadKey();
                        Environment.Exit(0);
                    }

                    Program.GetCredentials();
                    userContext = CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, siteUrl);
                }
            }
            catch (System.ArgumentNullException exc)
            {
                contextCount++;
                if (contextCount == 1)
                {
                    Logger.LogMessage(String.Format("\n"), true);
                    Logger.LogErrorMessage(String.Format("Attempt [{0}]: You have entered an invalid username or password. The maximum retry attempts allowed for login are 3. You have 2 more attempts.", contextCount, 3 - contextCount), true);
                    ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, siteUrl, "Authentication", exc.Message, exc.ToString(), "CreateAuthenticatedUserContext()", exc.GetType().ToString());
                }
                else if (contextCount == 2)
                {
                    Logger.LogMessage(String.Format("\n"), true);
                    Logger.LogErrorMessage(String.Format("Attempt [{0}]: Incorrect login credentials twice. You have one more attempt. If you fail to enter correct credentials this time, application would be terminated.", contextCount, 3 - contextCount), true);
                    //Logger.LogErrorMessage(String.Format("\nWrong user credentials given for {0} time. {1} attemps remained", contextCount, 3 - contextCount), true);
                    ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, siteUrl, "Authentication", exc.Message, exc.ToString(), "CreateAuthenticatedUserContext()", exc.GetType().ToString());
                }
                else if (contextCount == 3)
                {
                    Logger.LogErrorMessage(String.Format("\n"), true);
                    Logger.LogErrorMessage(String.Format("Attempt [{0}]: You have entered an invalid username or password. Press any key to terminate the application!!", contextCount, 3 - contextCount), true);
                    ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, siteUrl, "Authentication", exc.Message, exc.ToString(), "CreateAuthenticatedUserContext()", exc.GetType().ToString());

                    System.Console.ReadKey();
                    Environment.Exit(0);
                }

                Program.GetCredentials();
                userContext = CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, siteUrl);
            }

            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("\nCreateAuthenticatedUserContext() failed for {0}: Error={1}", siteUrl, ex.Message), false);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, siteUrl, "Authentication", ex.Message, ex.ToString(), "CreateAuthenticatedUserContext()", ex.GetType().ToString());
            }

            return(userContext);
        }
        /// <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));
            }
        }
Пример #18
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);
        }
        public void ChangeMasterPageForSiteCollection(string outPutFolder, string SiteCollectionUrl, string NewMasterPageURL, string OldMasterPageURL = "N/A", bool CustomMasterUrlStatus = true, bool MasterUrlStatus = true, string SharePointOnline_OR_OnPremise = "N/A", string UserName = "******", string Password = "******", string Domain = "N/A")
        {
            string exceptionCommentsInfo1          = string.Empty;
            List <MasterPageBase> _WriteMasterList = new List <MasterPageBase>();

            //Initialized Exception and Logger. Deleted the Master Page Replace Usage File

            MasterPage_Initialization(outPutFolder);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[Exception] [ChangeMasterPageForSiteCollection]. Exception Message:" + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1);
                Console.ForegroundColor = ConsoleColor.Gray;
            }
        }
Пример #20
0
        public static void DeleteWebPart_UsingCSV(string webPartType, string webPartsInputFile, string csvFile)
        {
            string exceptionCommentsInfo1 = string.Empty;

            try
            {
                //Reading Input File
                IEnumerable <WebpartInput> objWPDInput;
                ReadWebPartUsageCSV(webPartType, webPartsInputFile, out objWPDInput);

                bool headerTransformWebPart = false;

                if (objWPDInput.Any())
                {
                    Logger.LogInfoMessage(String.Format("Preparing to delete a total of {0} webparts with webpart type {1} ...", objWPDInput.Count(), webPartType), true);
                    for (int i = 0; i < objWPDInput.Count(); i++)
                    {
                        WebpartInput            objInput        = objWPDInput.ElementAt(i);
                        WebpartDeleteOutputBase objWPOutputBase = new WebpartDeleteOutputBase();

                        try
                        {
                            bool status = DeleteWebPart(objInput.WebUrl, objInput.PageUrl.ToString(), objInput.StorageKey);

                            if (status)
                            {
                                objWPOutputBase.Status         = Constants.Success;
                                System.Console.ForegroundColor = System.ConsoleColor.Green;
                                Logger.LogSuccessMessage("Successfully Deleted WebPart with Webpart Type " + objInput.WebPartType + " and with StorageKey " + objInput.StorageKey + "and output file is present in the path: " + Environment.CurrentDirectory, true);
                                System.Console.ResetColor();
                            }
                            else
                            {
                                objWPOutputBase.Status         = Constants.Failure;
                                System.Console.ForegroundColor = System.ConsoleColor.Gray;
                                Logger.LogErrorMessage("Failed to Delete WebPart with Webpart Type " + objInput.WebPartType + " and with StorageKey " + objInput.StorageKey, true);
                                System.Console.ResetColor();
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.LogInfoMessage("Failed to Deleted WebPart with Webpart Type " + objInput.WebPartType + " and with StorageKey " + objInput.StorageKey);
                            Logger.LogErrorMessage("[DeleteMissingWebparts: DeleteWebPart_UsingCSV]. Exception Message: " + ex.Message, true);
                            ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "Webpart", ex.Message,
                                                        ex.ToString(), "DeleteWebPart_UsingCSV", ex.GetType().ToString(), "Failed to Deleted WebPart with Webpart Type");
                        }

                        objWPOutputBase.WebPartType       = objInput.WebPartType;
                        objWPOutputBase.PageUrl           = objInput.PageUrl;
                        objWPOutputBase.WebUrl            = objInput.WebUrl;
                        objWPOutputBase.StorageKey        = objInput.StorageKey;
                        objWPOutputBase.ExecutionDateTime = DateTime.Now.ToString();

                        if (System.IO.File.Exists(csvFile))
                        {
                            headerTransformWebPart = true;
                        }
                        FileUtility.WriteCsVintoFile(csvFile, objWPOutputBase, ref headerTransformWebPart);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage("[DeleteMissingWebparts: DeleteWebPart_UsingCSV]. Exception Message: " + ex.Message, true);
            }
        }
        public void ChangeMasterPageForDiscoveryOutPut_ReadMasterPagesCSV(string outPutFolder, string MasterPageUsagePath, out IEnumerable <MasterPageInput> objMPInput, string New_MasterPageDetails = "N/A", string Old_MasterPageDetails = "N/A", string SharePointOnline_OR_OnPremise = Constants.OnPremise, string UserName = "******", string Password = "******", string Domain = "N/A")
        {
            string exceptionCommentsInfo1          = string.Empty;
            List <MasterPageBase> _WriteMasterList = new List <MasterPageBase>();

            Logger.AddMessageToTraceLogFile(Constants.Logging, "[START] ::: ChangeMasterPageForDiscoveryOutPut_ReadMasterPagesCSV");
            Logger.AddMessageToTraceLogFile(Constants.Logging, "[ChangeMasterPageForDiscoveryOutPut_ReadMasterPagesCSV] [START] Calling function ImportCsv.ReadMatchingColumns<MasterPageInput>. Master Page Input CSV file is available at " + MasterPageUsagePath);
            Console.WriteLine("[ChangeMasterPageForDiscoveryOutPut_ReadMasterPagesCSV] [START] Calling function ImportCsv.ReadMatchingColumns<MasterPageInput>. Master Page Input CSV file is available at " + MasterPageUsagePath);

            objMPInput = null;
            //objMPInput = ImportCsv.Read<MasterPageInput>(outPutFolder + @"\" + Transformation.PowerShell.Common.Constants.MasterPageInput, Transformation.PowerShell.Common.Constants.CsvDelimeter);
            objMPInput = ImportCsv.ReadMatchingColumns <MasterPageInput>(MasterPageUsagePath, Transformation.PowerShell.Common.Constants.CsvDelimeter);

            Logger.AddMessageToTraceLogFile(Constants.Logging, "[ChangeMasterPageForDiscoveryOutPut_ReadMasterPagesCSV] [END] Read all the INPUT from Master Page and saved in List - out IEnumerable<MasterPageInput> objMpInput, for processing.");
            Console.WriteLine("[ChangeMasterPageForDiscoveryOutPut_ReadMasterPagesCSV] [END] Read all the INPUT from Master Page and saved in List - out IEnumerable<MasterPageInput> objMpInput, for processing.");

            try
            {
                if (objMPInput.Any())
                {
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[START] ChangeMasterPageForDiscoveryOutPut_ReadMasterPagesCSV - After Loading InputCSV ");
                    Console.WriteLine("[START] ChangeMasterPageForDiscoveryOutPut_ReadMasterPagesCSV - After Loading InputCSV");

                    bool headerMasterPage = false;

                    foreach (MasterPageInput objInput in objMPInput)
                    {
                        //This is for Exception Comments:
                        ExceptionCsv.WebUrl         = objInput.WebUrl;
                        ExceptionCsv.SiteCollection = objInput.SiteCollectionUrl;
                        ExceptionCsv.WebApplication = objInput.WebApplicationUrl;
                        exceptionCommentsInfo1      = "<Input>New MasterPage Url = " + New_MasterPageDetails + ", <Input> OLD MasterUrl: " + Old_MasterPageDetails + ", WebUrl: " + objInput.WebUrl + ", CustomMasterUrlStatus" + objInput.CustomMasterUrlStatus + "MasterUrlStatus" + objInput.MasterUrlStatus;
                        //This is for Exception Comments:

                        MasterPageBase objMPBase = new MasterPageBase();
                        //if (Old_MasterPageDetails.Trim().ToLower() != Constants.Input_Blank && Old_MasterPageDetails.Trim().ToLower() != Constants.Input_All)
                        if (Old_MasterPageDetails.Trim().ToLower() != Constants.Input_All)
                        {
                            objMPBase = ChangeMasterPageForWeb(outPutFolder, objInput.WebUrl, New_MasterPageDetails, Old_MasterPageDetails, Convert.ToBoolean(objInput.CustomMasterUrlStatus), Convert.ToBoolean(objInput.MasterUrlStatus), Constants.ActionType_CSV, SharePointOnline_OR_OnPremise, UserName, Password, Domain);
                        }
                        else
                        {
                            objMPBase = ChangeMasterPageForWeb(outPutFolder, objInput.WebUrl, New_MasterPageDetails, Old_MasterPageDetails, true, Convert.ToBoolean(objInput.MasterUrlStatus), Constants.ActionType_CSV, SharePointOnline_OR_OnPremise, UserName, Password, Domain);
                        }

                        if (objMPBase != null)
                        {
                            _WriteMasterList.Add(objMPBase);
                        }
                    }

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

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[END] ChangeMasterPageForDiscoveryOutPut_ReadMasterPagesCSV - After Loading InputCSV. Updated the Master Pages.");
                    Console.WriteLine("[END] ChangeMasterPageForDiscoveryOutPut_ReadMasterPagesCSV - After Loading InputCSV. Updated the Master Pages.");
                }
            }
            catch (Exception ex)
            {
                ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "MasterPage", ex.Message, ex.ToString(), "ChangeMasterPageForDiscoveryOutPut_ReadMasterPagesCSV", ex.GetType().ToString(), exceptionCommentsInfo1);
                Logger.AddMessageToTraceLogFile(Constants.Logging, "[Exception] ChangeMasterPageForDiscoveryOutPut_ReadMasterPagesCSV. Exception Message:" + ex.Message);

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

            Logger.AddMessageToTraceLogFile(Constants.Logging, "[END] ::: ChangeMasterPageForDiscoveryOutPut_ReadMasterPagesCSV");
            Console.WriteLine("[END] ::: ChangeMasterPageForDiscoveryOutPut_ReadMasterPagesCSV");
        }
Пример #22
0
        public static void DoWork()
        {
            outputPath = Environment.CurrentDirectory;
            string webPartsInputFile = string.Empty;
            string webpartType       = string.Empty;
            IEnumerable <WebpartInput> objWPDInput;
            string timeStamp = DateTime.Now.ToString("yyyyMMdd_hhmmss");

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

            if (!ReadInputFile(ref webPartsInputFile))
            {
                System.Console.ForegroundColor = System.ConsoleColor.Red;
                Logger.LogErrorMessage("Webparts 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;
            }

            System.Console.ForegroundColor = System.ConsoleColor.Cyan;
            Logger.LogMessage("Please enter Webpart Type (enter 'all' to delete all webparts):");
            System.Console.ResetColor();
            webpartType = System.Console.ReadLine().ToLower();

            try
            {
                string csvFile = outputPath + @"/" + Constants.DeleteWebpartStatus + timeStamp + Constants.CSVExtension;
                if (System.IO.File.Exists(csvFile))
                {
                    System.IO.File.Delete(csvFile);
                }

                if (System.IO.File.Exists(webPartsInputFile))
                {
                    if (String.Equals(Constants.WebpartType_All, webpartType, StringComparison.CurrentCultureIgnoreCase))
                    {
                        //Reading Input File
                        objWPDInput = ImportCSV.ReadMatchingColumns <WebpartInput>(webPartsInputFile, Constants.CsvDelimeter);

                        if (objWPDInput.Any())
                        {
                            IEnumerable <string> webPartTypes = objWPDInput.Select(x => x.WebPartType);

                            webPartTypes = webPartTypes.Distinct();
                            Logger.LogInfoMessage(String.Format("Preparing to delete a total of {0} webparts ...", webPartTypes.Count()), true);

                            foreach (string webPartType in webPartTypes)
                            {
                                try
                                {
                                    DeleteWebPart_UsingCSV(webPartType, webPartsInputFile, csvFile);
                                }
                                catch (Exception ex)
                                {
                                    Logger.LogErrorMessage("[DeleteMissingWebparts: DoWork]. Exception Message: " + ex.Message, true);
                                    ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "Webpart", ex.Message,
                                                                ex.ToString(), "DoWork", ex.GetType().ToString(), Constants.NotApplicable);
                                }
                            }
                            webPartTypes = null;
                        }
                        else
                        {
                            Logger.LogInfoMessage("There is nothing to delete from the '" + webPartsInputFile + "' File ", true);
                        }
                    }
                    else
                    {
                        DeleteWebPart_UsingCSV(webpartType, webPartsInputFile, csvFile);
                    }
                    Logger.LogInfoMessage("Processing input file has been comepleted...");
                }
                else
                {
                    Logger.LogErrorMessage("[DeleteMissingWebparts: DoWork]The input file " + webPartsInputFile + " is not present", true);
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage("[DeleteMissingWebparts: DoWork]. Exception Message: " + ex.Message, true);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "Webpart", ex.Message,
                                            ex.ToString(), "DoWork", ex.GetType().ToString(), Constants.NotApplicable);
            }
            finally
            {
                objWPDInput = null;
            }

            Logger.CloseLog();
        }
Пример #23
0
        public void UnGhostFile(string absoluteFilePath, string outPutFolder, string OperationType, string SharePointOnline_OR_OnPremise = Constants.OnPremise, string UserName = "******", string Password = "******", string Domain = "NA")
        {
            string fileName               = string.Empty;
            string newFileName            = string.Empty;
            string directoryName          = string.Empty;
            bool   headerCSVColumns       = false;
            string exceptionCommentsInfo1 = string.Empty;

            GhostingAndUnGhosting_Initialization(outPutFolder, "UNGHOST");

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

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

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

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

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

                Uri fileUrl = new Uri(absoluteFilePath);

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

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

                ExceptionCsv.WebUrl = siteUrl.ToString();

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

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

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

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

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

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

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

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

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

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

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

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

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

            Logger.AddMessageToTraceLogFile(Constants.Logging, "############## UnGhostFile - Trasnformation Utility Execution Completed for Web ##############");
            Console.WriteLine("############## UnGhostFile - Trasnformation Utility Execution Completed for Web ##############");
        }
Пример #24
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);
        }
        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), false);
                ExceptionCsv.WriteException(
                    webAppUrl, siteUrl, webUrl,
                    "MappingFile",
                    ex.Message, ex.ToString(), "ResetMappingFile", ex.GetType().ToString(),
                    String.Format("ResetMappingFile() failed for file {0}", targetFilePath)
                    );
            }
        }
Пример #26
0
        private static List GetPageList(ClientContext clientContext)
        {
            List list = null;
            Web  web  = null;

            try
            {
                web = clientContext.Web;

                // Get a few properties from the web
                clientContext.Load(web,
                                   w => w.Url,
                                   w => w.ServerRelativeUrl,
                                   w => w.AllProperties,
                                   w => w.WebTemplate);

                clientContext.ExecuteQueryRetry();

                string pagesListID      = string.Empty;
                bool   _IsPublishingWeb = IsPublishingWeb(clientContext, web);

                if (_IsPublishingWeb)
                {
                    Logger.LogInfoMessage("Web: " + web.Url + "is a publishing web", false);
                    pagesListID = web.AllProperties["__PagesListId"] as string;
                    list        = web.Lists.GetById(new Guid(pagesListID));


                    clientContext.Load(list, l => l.ForceCheckout,
                                       l => l.EnableVersioning,
                                       l => l.EnableMinorVersions,
                                       l => l.EnableModeration,
                                       l => l.Title,
                                       l => l.DraftVersionVisibility,
                                       l => l.DefaultViewUrl);

                    clientContext.ExecuteQueryRetry();
                }
                else
                {
                    Logger.LogInfoMessage("Web: " + web.Url + "is not a publishing web", false);
                    clientContext.Load(web.Lists);

                    clientContext.ExecuteQueryRetry();

                    try
                    {
                        //list = web.Lists.GetByTitle(Constants.TEAMSITE_PAGES_LIBRARY);
                        //WebPageLibrary, Wiki Page Library. Value = 119.
                        IEnumerable <List> libraries = clientContext.LoadQuery(web.Lists.Where(l => l.BaseTemplate == 119));
                        clientContext.ExecuteQuery();

                        if (libraries.Any() && libraries.Count() > 0)
                        {
                            list = libraries.First();
                        }

                        clientContext.Load(list);
                        clientContext.ExecuteQueryRetry();
                    }
                    catch
                    {
                        list = null;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage("[DeleteMissingWebparts: GetPageList]. Exception Message: " + ex.Message
                                       + ", Exception Comments: Exception occured while finding page list", true);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "Webpart", ex.Message,
                                            ex.ToString(), "GetPageList", ex.GetType().ToString(), "Exception occured while finding page list");
            }
            finally
            {
                clientContext.Dispose();
                web = null;
            }
            return(list);
        }
        private static void DeleteMissingEventReceiver(MissingEventReceiversInput MissingEventReceiver, string csvFile)
        {
            bool headerEROP = false;
            MissingEventReceiversOutput objEROP = new MissingEventReceiversOutput();

            if (MissingEventReceiver == null)
            {
                return;
            }

            string assemblyName = MissingEventReceiver.Assembly;
            string eventName    = MissingEventReceiver.EventName;
            string hostId       = MissingEventReceiver.HostId;
            string hostTypeInfo = MissingEventReceiver.HostType;
            string siteUrl      = MissingEventReceiver.SiteCollection;
            string webUrl       = MissingEventReceiver.WebUrl;

            objEROP.Assembly          = assemblyName;
            objEROP.EventName         = eventName;
            objEROP.HostId            = hostId;
            objEROP.HostType          = hostTypeInfo;
            objEROP.SiteCollection    = siteUrl;
            objEROP.WebUrl            = webUrl;
            objEROP.WebApplication    = MissingEventReceiver.WebApplication;
            objEROP.ExecutionDateTime = DateTime.Now.ToString();

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

            try
            {
                Logger.LogInfoMessage(String.Format(" Processing Event Receiver [{0}] of Assembly [{1}] ...", eventName, assemblyName), true);

                //Logger.LogInfoMessage(String.Format("-assemblyName= {0}", assemblyName), false);
                //Logger.LogInfoMessage(String.Format("-eventName= {0}", eventName), false);
                //Logger.LogInfoMessage(String.Format("-hostId= {0}", hostId), false);
                //Logger.LogInfoMessage(String.Format("-hostTypeInfo= {0}", hostTypeInfo), false);
                //Logger.LogInfoMessage(String.Format("-siteUrl= {0}", siteUrl), false);
                //Logger.LogInfoMessage(String.Format("-webUrl= {0}", webUrl), false);

                int hostType = -1;
                if (Int32.TryParse(hostTypeInfo, out hostType) == false)
                {
                    Logger.LogErrorMessage(String.Format("[DeleteMissingEventReceivers: DeleteMissingEventReceiver] failed for Event Receiver [{0}]: Error= Unknown HostType value [{1}] ", eventName, hostTypeInfo), false);
                    return;
                }

                switch (hostType)
                {
                case 0:
                    if (DeleteSiteEventReceiver(siteUrl, eventName, assemblyName))
                    {
                        objEROP.Status = Constants.Success;
                    }
                    else
                    {
                        objEROP.Status = Constants.Failure;
                    }
                    break;

                case 1:
                    if (DeleteWebEventReceiver(webUrl, eventName, assemblyName))
                    {
                        objEROP.Status = Constants.Success;
                    }
                    else
                    {
                        objEROP.Status = Constants.Failure;
                    }
                    break;

                case 2:
                    if (DeleteListEventReceiver(webUrl, hostId, eventName, assemblyName))
                    {
                        objEROP.Status = Constants.Success;
                    }
                    else
                    {
                        objEROP.Status = Constants.Failure;
                    }
                    break;

                default:
                    Logger.LogErrorMessage(String.Format("[DeleteMissingEventReceivers: DeleteMissingEventReceiver] failed for Event Receiver [{0}] of Assembly [{1}]: Error= Unknown HostType value [{2}] ", eventName, assemblyName, hostTypeInfo), false);
                    objEROP.Status = Constants.Failure;
                    return;
                }

                if (System.IO.File.Exists(csvFile))
                {
                    headerEROP = true;
                }
                FileUtility.WriteCsVintoFile(csvFile, objEROP, ref headerEROP);
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("[DeleteMissingEventReceivers: DeleteMissingEventReceiver] failed for Event Receiver [{0}] of Assembly [{1}]: Error={2}", eventName, assemblyName, ex.Message), true);
                ExceptionCsv.WriteException(MissingEventReceiver.WebApplication, siteUrl, webUrl, "EventReceiver", ex.Message, ex.ToString(), "DeleteMissingEventReceiver",
                                            ex.GetType().ToString(), String.Format("[DeleteMissingEventReceivers: DeleteMissingEventReceiver] failed for Event Receiver [{0}] of Assembly [{1}]: Error={2}", eventName, assemblyName, ex.Message));
            }
        }
Пример #28
0
        private static void AddJsLinks(ClientContext context, Site site, string cdnAbsoluteUrl)
        {
            ManageMaintenanceBannersOutput csvObject = new ManageMaintenanceBannersOutput();

            csvObject.BannerOperation   = "Add Banner";
            csvObject.SiteCollectionUrl = site.Url;
            csvObject.ScriptLinkName    = Constants.ScriptLinkDescription;
            csvObject.ScriptLinkFile    = "N/A";

            try
            {
                string revision = Guid.NewGuid().ToString().Replace("-", "");

                string embedJsLink = string.Format("{0}/{1}?rev={2}", cdnAbsoluteUrl, Constants.EmbedJsFileName, revision);
                csvObject.ScriptLinkFile = embedJsLink;

                StringBuilder scripts = new StringBuilder(@"
                    var headID = document.getElementsByTagName('head')[0]; 
                    var");

                scripts.AppendFormat(@"
                    newScript = document.createElement('script');
                    newScript.type = 'text/javascript';
                    newScript.src = '{0}';
                    headID.appendChild(newScript);", embedJsLink);

                string scriptBlock = scripts.ToString();

                var existingActions = site.UserCustomActions;
                context.Load(existingActions);
                context.ExecuteQuery();
                var actions = existingActions.ToArray();

                Logger.LogInfoMessage(String.Format("Adding ScriptLink Action [{0}] to site [{1}]...", Constants.ScriptLinkDescription, site.Url), false);
                Logger.LogInfoMessage(String.Format("-embedJsLink = [{0}]", embedJsLink), false);

                var newAction = existingActions.Add();
                newAction.Description = Constants.ScriptLinkDescription;
                newAction.Location    = Constants.ScriptLinkLocation;

                newAction.ScriptBlock = scriptBlock;
                newAction.Update();
                context.Load(site, s => s.UserCustomActions);
                context.ExecuteQuery();

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

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

                Logger.LogErrorMessage(String.Format("AddJsLink() failed to add ScriptLink Action [{0}] to site [{1}]: Error={2}", Constants.ScriptLinkDescription, site.Url, ex.Message), false);
                ExceptionCsv.WriteException(
                    "N/A", site.Url, "N/A",
                    "MaintenanceBanner",
                    ex.Message, ex.ToString(), "AddJsLinks", ex.GetType().ToString(),
                    String.Format("AddJsLink() failed to add ScriptLink Action [{0}] to site [{1}]", Constants.ScriptLinkDescription, site.Url)
                    );
            }
        }
Пример #29
0
        public static void GetWebPartUsage_DefaultPages(string webPartType, ClientContext clientContext, string outPutDirectory)
        {
            ExceptionCsv.WebUrl = clientContext.Web.Url;
            string exceptionCommentsInfo1 = string.Empty;
            string webPartUsageFileName   = outPutDirectory + "\\" + Constants.WEBPART_USAGE_ENTITY_FILENAME + timeStamp + Constants.CSVExtension;

            bool headerWebPart = false;
            bool isfound       = false;

            try
            {
                string webUrl = clientContext.Web.Url;

                Logger.LogInfoMessage("[START][GetWebPartUsage_DefaultPages]");
                Logger.LogInfoMessage("[GetWebPartUsage_DefaultPages] Finding WebPartUsage details for Web Part: " + webPartType + " in Web: " + webUrl);

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

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

                    foreach (Microsoft.SharePoint.Client.File page in clientContext.Web.RootFolder.Files)
                    {
                        exceptionCommentsInfo1 = "Web Url: " + clientContext.Web.Url + ", Web Part Type: " + webPartType + ", PageTitle: " + page.ServerRelativeUrl;

                        try
                        {
                            if (Path.GetExtension(page.ServerRelativeUrl).Equals(".aspx", StringComparison.CurrentCultureIgnoreCase))
                            {
                                String pageUrl = page.ServerRelativeUrl;

                                Logger.LogInfoMessage("[GetWebPartUsage_DefaultPages] 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_DefaultPages] Found WebPart: " + webPartType + " in Page: " + page.Name + ", " + page.ServerRelativeUrl);

                                        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_DefaultPages()", ex.GetType().ToString(), exceptionCommentsInfo1);
                            Logger.LogErrorMessage("[GetWebPartUsage_DefaultPages] Exception Message: " + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1);
                            System.Console.ForegroundColor = System.ConsoleColor.Red;
                            Logger.LogErrorMessage("[GetWebPartUsage_DefaultPages] Exception Message: " + ex.Message);
                            System.Console.ResetColor();
                        }
                    }
                }

                if (isfound)
                {
                    Logger.LogInfoMessage("[GetWebPartUsage_DefaultPages] Default Pages WebPart Usage is exported to the file " + webPartUsageFileName);
                }

                Logger.LogInfoMessage("[END][GetWebPartUsage_DefaultPages]");
            }
            catch (Exception ex)
            {
                System.Console.ForegroundColor = System.ConsoleColor.Red;
                Logger.LogErrorMessage("[GetWebPartUsage_DefaultPages] Exception Message: " + ex.Message);
                System.Console.ResetColor();
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, ExceptionCsv.WebUrl, "WebPartUsage", ex.Message, ex.ToString(), "GetWebPartUsage_DefaultPages()", ex.GetType().ToString(), exceptionCommentsInfo1);
            }
        }
Пример #30
0
        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);
        }