예제 #1
0
        public IMatchProxy InitializeMatchComponent(IApplicationManager appManager)
        {
            IMatchProxy proxy = MatchComponentProxy.Instance;

            ((AbstractComponentProxy)proxy).InitializeComponentAccessPermissions(appManager);
            //((IComponentProxy)proxy).Start();
            return(proxy);
        }
예제 #2
0
        private void CreateInfofWarnCritFatalMatchesFile()
        {
            IMatchProxy matchProxy = ProxyHome.Instance.RetrieveMatchProxy(OutputKeyKeeper.Instance.AccessKey);

            XmlNode infoNode;
            XmlNode warningNode;
            XmlNode criticalNode;
            XmlNode fatalNode;

            XmlDocument infoDoc     = XmlFactory.CreateXmlFile(Ids.XSLT_DIR, Ids.ALL_MATCHES_XSLT_FILE, "Matches", out infoNode);
            XmlDocument warningDoc  = XmlFactory.CreateXmlFile(Ids.XSLT_DIR, Ids.ALL_MATCHES_XSLT_FILE, "Matches", out warningNode);
            XmlDocument criticalDoc = XmlFactory.CreateXmlFile(Ids.XSLT_DIR, Ids.ALL_MATCHES_XSLT_FILE, "Matches", out criticalNode);
            XmlDocument fatalDoc    = XmlFactory.CreateXmlFile(Ids.XSLT_DIR, Ids.ALL_MATCHES_XSLT_FILE, "Matches", out fatalNode);

            infoDoc.AppendChild(infoNode);
            warningDoc.AppendChild(warningNode);
            criticalDoc.AppendChild(criticalNode);
            fatalDoc.AppendChild(fatalNode);

            // <Matches>
            //   <Match />
            // </Matches>
            int num = 1;

            foreach (IMatch match in matchProxy.Matches())
            {
                if (match.Severity == RuleSeverity.Info)
                {
                    infoNode.AppendChild(XmlFactory.CreateMatchXmlNode(infoDoc, num++, match));
                }

                if (match.Severity == RuleSeverity.Warning)
                {
                    warningNode.AppendChild(XmlFactory.CreateMatchXmlNode(warningDoc, num++, match));
                }

                if (match.Severity == RuleSeverity.Critical)
                {
                    criticalNode.AppendChild(XmlFactory.CreateMatchXmlNode(criticalDoc, num++, match));
                }

                if (match.Severity == RuleSeverity.Fatal)
                {
                    fatalNode.AppendChild(XmlFactory.CreateMatchXmlNode(fatalDoc, num++, match));
                }
            }

            XmlFactory.SaveXmlFile(Path.Combine(OutputRootDir, Ids.OUTPUT_DIR, Ids.ALL_INFO_MATCHES_XML_FILE), infoDoc);
            XmlFactory.SaveXmlFile(Path.Combine(OutputRootDir, Ids.OUTPUT_DIR, Ids.ALL_WARNING_MATCHES_XML_FILE), warningDoc);
            XmlFactory.SaveXmlFile(Path.Combine(OutputRootDir, Ids.OUTPUT_DIR, Ids.ALL_CRITICAL_MATCHES_XML_FILE), criticalDoc);
            XmlFactory.SaveXmlFile(Path.Combine(OutputRootDir, Ids.OUTPUT_DIR, Ids.ALL_FATAL_MATCHES_XML_FILE), fatalDoc);
        }
예제 #3
0
        private void GenerateMatch(IMatchProxy matchProxy, IMatchInfoReferences references, IBatch batch, string filename, int startLineNumber, string matchExtract)
        {
            IMatch m = matchProxy.MatchesFactory <IMatch>(typeof(IMatch));

            m.Id    = Guid.NewGuid();
            m.Batch = batch;
            m.ProjectDefinitionRef   = references.ProjectDefinitionReference;
            m.CategoryDeclarationRef = references.CategoryDeclarationReference;
            m.CategoryDefinitionRef  = references.CategoryDefinitionReference;
            m.LanguageDeclarationRef = references.LanguageDeclarationReference;
            m.RuleDeclarationRef     = references.RuleDeclarationReference;
            m.RootDirectoryPath      = @"N/A";
            m.Filename    = filename;
            m.CodeExtract = matchExtract;
            m.LineNumber  = startLineNumber;
            m.Result      = MatchStatus.Match;
            m.Severity    = references.RuleDeclarationReference.Severity;

            matchProxy.AddMatch(m);
        }
예제 #4
0
        private void CreateAllMatchesFile()
        {
            IMatchProxy matchProxy = ProxyHome.Instance.RetrieveMatchProxy(OutputKeyKeeper.Instance.AccessKey);

            XmlNode     node;
            XmlDocument doc = XmlFactory.CreateXmlFile(Ids.XSLT_DIR, Ids.ALL_MATCHES_XSLT_FILE, "Matches", out node);


            // <Matches>
            //   <Match />
            // </Matches>
            int num = 1;

            foreach (IMatch match in matchProxy.Matches())
            {
                node.AppendChild(XmlFactory.CreateMatchXmlNode(doc, num++, match));
            }
            doc.AppendChild(node);

            XmlFactory.SaveXmlFile(Path.Combine(OutputRootDir, Ids.OUTPUT_DIR, Ids.ALL_MATCHES_XML_FILE), doc);
        }
예제 #5
0
        public override void GenerateOutput(string outputRootDir)
        {
            #region Input validation
            if (string.IsNullOrWhiteSpace(outputRootDir))
            {
                throw new ArgumentNullException(nameof(outputRootDir));
            }

            if (!Directory.Exists(outputRootDir))
            {
                throw new ArgumentException($"Unable to find directory {outputRootDir}.");
            }
            #endregion

            #region Create output DIR and file
            OutputDir = Path.Combine(outputRootDir, Ids.EXCEL_DIR);
            if (!Directory.Exists(Directory.CreateDirectory(OutputDir).FullName))
            {
                throw new OutputComponentException($"Unable to create output directory {OutputDir}.");
            }

            OutputFile = Path.Combine(outputRootDir, Ids.EXCEL_DIR, Ids.EXCEL_FILE);
            FileInfo newFile = new FileInfo(OutputFile);
            #endregion

            IMatchProxy matchProxy = ProxyHome.Instance.RetrieveMatchProxy(OutputKeyKeeper.Instance.AccessKey);

            using (ExcelPackage pck = new ExcelPackage(newFile))
            {
                var wsData = pck.Workbook.Worksheets.Add("Matches");

                var dataRange = wsData.Cells["A1"].LoadFromCollection(
                    from m in ConvertMatchesToExcelFormat(matchProxy.Matches())
                    orderby m.Timestamp
                    select m,
                    true, OfficeOpenXml.Table.TableStyles.Medium2);

                wsData.Cells[2, 2, dataRange.End.Row, 2].Style.Numberformat.Format = "dd-mm-yyyy - hh:mm:ss";

                dataRange.AutoFitColumns();

                //var wsPivot = pck.Workbook.Worksheets.Add("PivotSimple");
                //var pivotTable1 = wsPivot.PivotTables.Add(wsPivot.Cells["A1"], dataRange, "PerEmploee");

                //pivotTable1.RowFields.Add(pivotTable1.Fields[4]);
                //var dataField = pivotTable1.DataFields.Add(pivotTable1.Fields[6]);
                //dataField.Format="#,##0";
                //pivotTable1.DataOnRows = true;

                //var chart = wsPivot.Drawings.AddChart("PivotChart", eChartType.Pie, pivotTable1);
                //chart.SetPosition(1, 0, 4, 0);
                //chart.SetSize(600, 400);

                //var wsPivot2 = pck.Workbook.Worksheets.Add("PivotDateGrp");
                //var pivotTable2 = wsPivot2.PivotTables.Add(wsPivot2.Cells["A3"], dataRange, "PerEmploeeAndQuarter");

                //pivotTable2.RowFields.Add(pivotTable2.Fields["Name"]);

                ////Add a rowfield
                //var rowField = pivotTable2.RowFields.Add(pivotTable2.Fields["OrderDate"]);
                ////This is a date field so we want to group by Years and quaters. This will create one additional field for years.
                //rowField.AddDateGrouping(eDateGroupBy.Years | eDateGroupBy.Quarters);
                ////Get the Quaters field and change the texts
                //var quaterField = pivotTable2.Fields.GetDateGroupField(eDateGroupBy.Quarters);
                //quaterField.Items[0].Text = "<"; //Values below min date, but we use auto so its not used
                //quaterField.Items[1].Text = "Q1";
                //quaterField.Items[2].Text = "Q2";
                //quaterField.Items[3].Text = "Q3";
                //quaterField.Items[4].Text = "Q4";
                //quaterField.Items[5].Text = ">"; //Values above max date, but we use auto so its not used

                ////Add a pagefield
                //var pageField = pivotTable2.PageFields.Add(pivotTable2.Fields["Title"]);

                ////Add the data fields and format them
                //dataField = pivotTable2.DataFields.Add(pivotTable2.Fields["SubTotal"]);
                //dataField.Format = "#,##0";
                //dataField = pivotTable2.DataFields.Add(pivotTable2.Fields["Tax"]);
                //dataField.Format = "#,##0";
                //dataField = pivotTable2.DataFields.Add(pivotTable2.Fields["Freight"]);
                //dataField.Format = "#,##0";

                ////We want the datafields to appear in columns
                //pivotTable2.DataOnRows = false;

                pck.Save();
            }
        }
예제 #6
0
        public void GenerateOutput_Backup(string outputRootDir)
        {
            #region Input validation
            if (string.IsNullOrWhiteSpace(outputRootDir))
            {
                throw new ArgumentNullException(nameof(outputRootDir));
            }

            if (!Directory.Exists(outputRootDir))
            {
                throw new ArgumentException($"Unable to find directory {outputRootDir}.");
            }
            #endregion


            #region Create output DIR and file
            OutputDir = Path.Combine(outputRootDir, Ids.EXCEL_DIR);
            if (!Directory.Exists(Directory.CreateDirectory(OutputDir).FullName))
            {
                throw new OutputComponentException($"Unable to create output directory {OutputDir}.");
            }

            OutputFile = Path.Combine(outputRootDir, Ids.EXCEL_DIR, Ids.EXCEL_FILE);
//			File.Create(OutputFile);
//			if (!File.Exists(OutputFile))
//				throw new OutputComponentException($"Unable to create output file {OutputFile}.");
            #endregion


            #region Define row 'n' columns values...
            int columns = 13;

            int firstHeaderRow  = 0;
            int secondHeaderRow = firstHeaderRow + 1;
            int timestampRow    = secondHeaderRow + 1;
            int tableHeaderRow  = 0;
            int row             = tableHeaderRow + 1;
            int freezeRow       = tableHeaderRow + 1;
            #endregion


            #region Create the Excel xml workbook...
            // Create a instance...
            ExcelXmlWorkbook book = new ExcelXmlWorkbook();

            // Many such properties exist. Details can be found in the documentation
            // The author of the document
            book.Properties.Author = "Code Analyzer";

            // This returns the first worksheet.
            // Note that we have not declared a instance of a new worksheet
            // All the dirty work is done by the library.
            Worksheet dashboardSheet = book[0];
            Worksheet matchesSheet   = book[1];

            // Name is the name of the sheet. If not set, the default name
            // style is "sheet" + sheet number, like sheet1, sheet2
            dashboardSheet.Name = "Dashboard";
            matchesSheet.Name   = "Matches";

            // More on this in documentation
            matchesSheet.FreezeTopRows = freezeRow;

            // and this too...
            dashboardSheet.PrintOptions.Orientation = PageOrientation.Landscape;
            dashboardSheet.PrintOptions.SetMargins(0.5, 0.4, 0.5, 0.4);
            #endregion


            #region Creating the header...
            // Text for the header...
            dashboardSheet[0, firstHeaderRow].Value  = "Octopus | Code Analyzer";
            dashboardSheet[0, secondHeaderRow].Value = "The Octopus Code Analyzer - the simple way to keep track of your code base";

            // Setting the background color for the header...
            new Range(dashboardSheet[0, firstHeaderRow], dashboardSheet[30, firstHeaderRow]).Interior.Color     = Color.FromArgb(22, 54, 92);
            new Range(dashboardSheet[0, secondHeaderRow], dashboardSheet[30, secondHeaderRow]).Interior.Color   = Color.FromArgb(22, 54, 92);
            new Range(dashboardSheet[0, secondHeaderRow], dashboardSheet[30, secondHeaderRow]).Border.Sides     = BorderSides.Bottom;
            new Range(dashboardSheet[0, secondHeaderRow], dashboardSheet[30, secondHeaderRow]).Border.LineStyle = Borderline.Double;
            new Range(dashboardSheet[0, secondHeaderRow], dashboardSheet[30, secondHeaderRow]).Border.Color     = Color.FromArgb(255, 255, 255);
            new Range(dashboardSheet[0, secondHeaderRow], dashboardSheet[30, secondHeaderRow]).Border.Weight    = 1;

            // Setting the foreground color for the header text...
            new Range(dashboardSheet[0, firstHeaderRow], dashboardSheet[8, firstHeaderRow]).Font.Color   = Color.FromArgb(255, 255, 255);
            new Range(dashboardSheet[0, secondHeaderRow], dashboardSheet[8, secondHeaderRow]).Font.Color = Color.FromArgb(255, 255, 255);

            // Setting the font for the header text...
            new Range(dashboardSheet[0, firstHeaderRow], dashboardSheet[8, firstHeaderRow]).Font.Size   = 18;
            new Range(dashboardSheet[0, firstHeaderRow], dashboardSheet[8, firstHeaderRow]).Font.Bold   = true;
            new Range(dashboardSheet[0, secondHeaderRow], dashboardSheet[8, secondHeaderRow]).Font.Size = 8;
            new Range(dashboardSheet[0, secondHeaderRow], dashboardSheet[8, secondHeaderRow]).Font.Bold = true;

            dashboardSheet[0, timestampRow].Value     = "Exported on: " + DateTime.Now.ToShortDateString();
            dashboardSheet[0, timestampRow].Font.Bold = true;
            dashboardSheet[0, timestampRow].Font.Size = 8;
            #endregion


            #region Create the table header for all the data...
            // Setting the width of the columns...
            matchesSheet.Columns(0).Width  = 100;
            matchesSheet.Columns(1).Width  = 100;
            matchesSheet.Columns(2).Width  = 100;
            matchesSheet.Columns(3).Width  = 100;
            matchesSheet.Columns(4).Width  = 100;
            matchesSheet.Columns(5).Width  = 100;
            matchesSheet.Columns(6).Width  = 100;
            matchesSheet.Columns(7).Width  = 100;
            matchesSheet.Columns(8).Width  = 100;
            matchesSheet.Columns(9).Width  = 100;
            matchesSheet.Columns(10).Width = 100;
            matchesSheet.Columns(11).Width = 100;
            matchesSheet.Columns(12).Width = 100;
            matchesSheet.Columns(13).Width = 900;

            // Inserting headers and setting them to bold...
            matchesSheet[0, tableHeaderRow].Value  = "BatchId Id";
            matchesSheet[1, tableHeaderRow].Value  = "Timestamp";
            matchesSheet[2, tableHeaderRow].Value  = "Match Id";
            matchesSheet[3, tableHeaderRow].Value  = "Severity";
            matchesSheet[4, tableHeaderRow].Value  = "Project";
            matchesSheet[5, tableHeaderRow].Value  = "Language";
            matchesSheet[6, tableHeaderRow].Value  = "Category";
            matchesSheet[7, tableHeaderRow].Value  = "Category description";
            matchesSheet[8, tableHeaderRow].Value  = "Rule";
            matchesSheet[9, tableHeaderRow].Value  = "Rule description";
            matchesSheet[10, tableHeaderRow].Value = "Rule Expression";
            matchesSheet[11, tableHeaderRow].Value = "File name";
            matchesSheet[12, tableHeaderRow].Value = "Match on line";
            matchesSheet[13, tableHeaderRow].Value = "Code extract";

            new Range(matchesSheet[0, tableHeaderRow], matchesSheet[columns, tableHeaderRow]).Font.Bold = true;
            new Range(matchesSheet[0, tableHeaderRow], matchesSheet[columns, tableHeaderRow]).AutoFilter();
            new Range(matchesSheet[0, tableHeaderRow], matchesSheet[columns, tableHeaderRow]).Border.Sides     = BorderSides.Bottom;
            new Range(matchesSheet[0, tableHeaderRow], matchesSheet[columns, tableHeaderRow]).Border.LineStyle = Borderline.Continuous;
            new Range(matchesSheet[0, tableHeaderRow], matchesSheet[columns, tableHeaderRow]).Border.Weight    = 2;
            #endregion


            #region Insert data...
            // Insert data...
            IMatchProxy matchProxy = ProxyHome.Instance.RetrieveMatchProxy(OutputKeyKeeper.Instance.AccessKey);

            foreach (IMatch match in matchProxy.Matches())
            {
                if ((row % 2) == 0)
                {
                    new Range(matchesSheet[0, row], matchesSheet[columns, row]).Interior.Color = Color.FromArgb(220, 230, 241);
                }
                else
                {
                    new Range(matchesSheet[0, row], matchesSheet[columns, row]).Interior.Color = Color.FromArgb(197, 217, 241);
                }

                matchesSheet[0, row].Value  = match.Batch.Id;
                matchesSheet[1, row].Value  = $"{match.Batch.TimeStamp.ToShortDateString()} - {match.Batch.TimeStamp.ToShortTimeString()}";
                matchesSheet[2, row].Value  = match.Id;
                matchesSheet[3, row].Value  = $"{RuleSeverityMapper.Int2RuleSeverity((int)match.Severity)}";
                matchesSheet[4, row].Value  = match.ProjectDefinitionRef.Name;
                matchesSheet[5, row].Value  = match.LanguageDeclarationRef.Name;
                matchesSheet[6, row].Value  = match.CategoryDeclarationRef.Name;
                matchesSheet[7, row].Value  = match.CategoryDeclarationRef.Description;
                matchesSheet[8, row].Value  = match.RuleDeclarationRef.Name;
                matchesSheet[9, row].Value  = match.RuleDeclarationRef.Description;
                matchesSheet[10, row].Value = match.RuleDeclarationRef.Expression;
                matchesSheet[11, row].Value = match.Filename;
                matchesSheet[12, row].Value = match.LineNumber;
                matchesSheet[13, row].Value = match.CodeExtract;
                row++;
            }
            #endregion


            #region Export the Excel xml workbook...
            book.Export(OutputFile);
            #endregion
        }
예제 #7
0
        private void StartSearch()
        {
            IConfigurationProxy cfgProxy = ProxyHome.Instance.RetrieveConfigurationProxy(EngineKeyKeeper.Instance.AccessKey);

            List <LinkFile2Language> bindedProj2LanguageFileType = null;

            // Retrieve project definitions from the Configuration component.
            Dictionary <int, IProjectDefinition> projects = cfgProxy.Projects();

            // Let's run through all the projects and do our thing.
            foreach (KeyValuePair <int, IProjectDefinition> pair in projects)
            {
                IProjectDefinition project = pair.Value;
                if (!project.Enabled)
                {
                    continue; // Project definition was disabled.
                }
                // Here we create the language file type containers for all the languages
                // that are in play for the current project.
                bindedProj2LanguageFileType = BindProjectLanguagesToFileTypes(project);


                // Find all files associated with the language file extension in
                // the current file container 'linkFile2Language'.
                foreach (LinkFile2Language linkFile2Language in bindedProj2LanguageFileType)
                {
                    foreach (IDirectoryDefinition dir in project.Directories)
                    {
                        if (!dir.Enabled)
                        {
                            continue;
                        }

                        if (!Directory.Exists(dir.Path))
                        {
                            string s = string.Format("No directory found ({0})", dir.Path);
                            throw new IOException(s);
                        }

                        IRootDirectoryStatistics rds = ProxyHome.Instance.RetrieveStatisticsProxy(EngineKeyKeeper.Instance.AccessKey).CreateRootDirectory(project.Id);
                        rds.RootDirectory = dir.Path;

                        FileSearchEngine fileSearchEngine = new FileSearchEngine(dir, linkFile2Language.Language.Extension);
                        fileSearchEngine.ExcludeDirs            = project.ExcludedDirectories.Select(d => d).ToList();
                        fileSearchEngine.IncludeSubDirsInSearch = true;
                        fileSearchEngine.Search();

                        // Adding all the files found with the extention given by
                        // 'linkFile2Language.Language.Extension' to the file container 'linkFile2Language'.
                        linkFile2Language.Filenames.AddRange(fileSearchEngine.FileFoundDuringSearch);

                        // Adding all the files found to the StatisticsComponentProxy.
                        ProxyHome.Instance.RetrieveStatisticsProxy(EngineKeyKeeper.Instance.AccessKey).IncrementCounter(CounterIds.Files, fileSearchEngine.FileCount);
                        rds.Filenames.AddRange(fileSearchEngine.FileFoundDuringSearch);
                    }
                }


                TimeTracker tt = new TimeTracker("Execution of regular expression on each file.");
                tt.Start();


                IMatchProxy matchProxy = ProxyHome.Instance.RetrieveMatchProxy(EngineKeyKeeper.Instance.AccessKey);

                // Let's execute each regular expression from each rule that are enabled
                // and should be applied to the current language.
                foreach (LinkFile2Language linkFile2Language in bindedProj2LanguageFileType)
                {
                    foreach (KeyValuePair <int, ICategoryDefinition> categoryDefinition in project.Categories)
                    {
                        if (!categoryDefinition.Value.Enabled)
                        {
                            continue;
                        }


                        foreach (KeyValuePair <int, IRuleDefinition> ruleDefinition in categoryDefinition.Value.Rules)
                        {
                            if (!ruleDefinition.Value.Enabled)
                            {
                                continue;
                            }


                            // Let's check whether or not the current 'rule' is associated with the current 'language'?
                            IRuleDeclaration ruleDeclaration = cfgProxy.RuleDeclarationFromCategoryIdAndRuleId(categoryDefinition.Value.CategoryDeclarationReferenceId, ruleDefinition.Value.RuleDeclarationReferenceId);
                            foreach (KeyValuePair <int, ILanguageDeclaration> languageRef in ruleDeclaration.Languages)
                            {
                                if (languageRef.Key == linkFile2Language.Language.Id)
                                {
                                    // The language reference on the current rule is identical to the current 'linkFile2Language'
                                    // meaning that we should execute the regular expression from the current rule on all the
                                    // files placed in the 'linkFile2Language':
                                    IMatchInfoReferences references = matchProxy.MatchesFactory <IMatchInfoReferences>(typeof(IMatchInfoReferences));

                                    references.ProjectDefinitionReference   = project;
                                    references.CategoryDeclarationReference = cfgProxy.CategoryDeclaration(categoryDefinition.Value.CategoryDeclarationReferenceId);
                                    references.CategoryDefinitionReference  = categoryDefinition.Value;
                                    references.RuleDeclarationReference     = ruleDeclaration;
                                    references.RuleDefinitionReference      = ruleDefinition.Value;
                                    references.LanguageDeclarationReference = languageRef.Value;

                                    Parallel.ForEach(linkFile2Language.Filenames, file => ExecuteRegularExpressionsOnBuffer(file, references, ruleDeclaration));
                                }
                            }
                        }
                    }
                }

                tt.Stop("We are done.");
                tt.ToLog(Log);
            }
        }
예제 #8
0
        private void ExecuteRegularExpressionsOnBuffer(string filename, IMatchInfoReferences references, IRuleDeclaration ruleDeclaration)
        {
            const string summary = "summary";

            string buffer = LoadFile(filename);

            if (string.IsNullOrEmpty(buffer))
            {
                return;
            }

            int lastLineNum;

            string[] lines = buffer.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
            lastLineNum = (lines != null && lines.Length >= 1) ? lines.Length - 1 : 0;


            #region Statistics: update/increment the total number of lines and total number of whitespace lines in tested/scanned files.
            if (!ProxyHome.Instance.CheckCache(filename))
            {
                ProxyHome.Instance.RetrieveStatisticsProxy(EngineKeyKeeper.Instance.AccessKey).IncrementCounter(CounterIds.TotalNumberOfLinesInFiles, lastLineNum);
                ProxyHome.Instance.RetrieveStatisticsProxy(EngineKeyKeeper.Instance.AccessKey).IncrementCounter(CounterIds.TotalNumberOfWhitespaceLinesInFiles, lines.Count(string.IsNullOrWhiteSpace));
                ProxyHome.Instance.InsertInCache(filename);
            }
            #endregion


            string correctedRegExp = "(?<" + summary + ">" + ruleDeclaration.Expression + ")";


            IMatchProxy matchProxy = ProxyHome.Instance.RetrieveMatchProxy(EngineKeyKeeper.Instance.AccessKey);
            IBatch      batch      = ProxyHome.Instance.RetrieveExecutionIdentification(EngineKeyKeeper.Instance.AccessKey);

            MatchCollection matches = Regex.Matches(buffer, correctedRegExp, RegexOptions.IgnoreCase);
            foreach (System.Text.RegularExpressions.Match match in matches)
            {
                int startIndx = match.Index;
                int endIndx   = startIndx + match.Groups[summary].Value.Length;

                int accumulation    = 0;
                int startLineNumber = 0;
                int endLineNumber   = 0;
                foreach (string line in lines)
                {
                    if (accumulation < startIndx)
                    {
                        // This is for finding the line number where the match starts...
                        accumulation += line.Length + Environment.NewLine.Length;
                        endLineNumber = startLineNumber++;
                    }
                    else
                    {
                        if (accumulation < endIndx)
                        {
                            // This is for finding the line number where the match ends...
                            accumulation += line.Length + Environment.NewLine.Length;

                            if ((endLineNumber + 1) < lastLineNum)
                            {
                                endLineNumber++;
                            }
                            else
                            {
                                endLineNumber = lastLineNum;

                                // Extract the code from the actual file...
                                string matchExtract = ExtractTheMatchAndSurroundings(lines, buffer.Length, ++startLineNumber, ++endLineNumber);

                                // Create the match and insert it into the MatchProxy...
                                GenerateMatch(matchProxy, references, batch, filename, startLineNumber, matchExtract);

                                // Let's update the statistics manager about the match we just found.
                                ProxyHome.Instance.RetrieveStatisticsProxy(EngineKeyKeeper.Instance.AccessKey).IncrementCounter(RuleSeverityMapper.Severity2CounterId((RuleSeverity)ruleDeclaration.Severity));
                            }
                        }
                        else
                        {
                            // Extract the code from the actual file...
                            string matchExtract = ExtractTheMatchAndSurroundings(lines, buffer.Length, ++startLineNumber, ++endLineNumber);

                            // Create the match and insert it into the MatchProxy...
                            GenerateMatch(matchProxy, references, batch, filename, startLineNumber, matchExtract);

                            // Let's update the statistics manager about the match we just found.
                            ProxyHome.Instance.RetrieveStatisticsProxy(EngineKeyKeeper.Instance.AccessKey).IncrementCounter(RuleSeverityMapper.Severity2CounterId((RuleSeverity)ruleDeclaration.Severity));
                            break;
                        }
                    }
                }
            }
        }
예제 #9
0
        private void GenerateMatch(IMatchProxy matchProxy, IMatchInfoReferences references, IBatch batch, string filename, int startLineNumber, string matchExtract)
        {
            IMatch m = matchProxy.MatchesFactory<IMatch>(typeof(IMatch));
            m.Id                     = Guid.NewGuid();
            m.Batch                  = batch;
            m.ProjectDefinitionRef   = references.ProjectDefinitionReference;
            m.CategoryDeclarationRef = references.CategoryDeclarationReference;
            m.CategoryDefinitionRef  = references.CategoryDefinitionReference;
            m.LanguageDeclarationRef = references.LanguageDeclarationReference;
            m.RuleDeclarationRef     = references.RuleDeclarationReference;
            m.RootDirectoryPath      = @"N/A";
            m.Filename               = filename;
            m.CodeExtract            = matchExtract;
            m.LineNumber             = startLineNumber;
            m.Result                 = MatchStatus.Match;
            m.Severity               = references.RuleDeclarationReference.Severity;

            matchProxy.AddMatch(m);
        }