Example #1
0
        /// <summary>
        /// The main entrypoint to the application.
        /// </summary>
        /// <param name="args">The arguments passed to the executable.</param>
        public static void Main(string[] args)
        {
            int    iterations = 10;
            string file       = null;

            if (args.Length > 0)
            {
                int index = 0;

                if (args[0].StartsWith("-n:", StringComparison.Ordinal))
                {
                    iterations = int.Parse(args[0].Substring(3, args[0].Length - 3));
                    ++index;
                }

                if (args.Length > index)
                {
                    file = args[index];
                }
            }

            if (!string.IsNullOrEmpty(file))
            {
                if (!File.Exists(file))
                {
                    Console.WriteLine("The file " + file + " does not exist");
                    file = null;
                }
            }

            if (!string.IsNullOrEmpty(file))
            {
                DateTime start = DateTime.Now;
                Console.WriteLine("Start time: " + start.ToLongTimeString());

                for (int i = 0; i < iterations; ++i)
                {
                    Console.WriteLine("Iteration " + (i + 1));

                    StyleCopConsole console = new StyleCopConsole(null, false, null, null, true, "Perf");

                    Configuration configuration = new Configuration(new string[] { });
                    CodeProject   project       = new CodeProject(0, Environment.CurrentDirectory, configuration);
                    console.Core.Environment.AddSourceCode(project, file, null);

                    console.Start(new CodeProject[] { project }, true);
                }

                DateTime end = DateTime.Now;
                Console.WriteLine("End time: " + end.ToLongTimeString());
                Console.WriteLine();

                TimeSpan elapsedTime = end - start;
                Console.WriteLine("Elapsed time: " + elapsedTime);
            }
            else
            {
                Console.WriteLine("Usage: StyleCopPerfHarness {-n:X} FileToTest.cs");
            }
        }
Example #2
0
 public void Destroy()
 {
     _project = null;
     _scConsole.ViolationEncountered -= scConsole_ViolationEncontered;
     _scConsole.OutputGenerated      -= scConsole_OutputGenerated;
     _scConsole = null;
 }
Example #3
0
        private static int ProcessFolder(string settings, string projectPath, string outputFile, SearchOption searchOption, string rule)
        {
            var console = new StyleCopConsole(settings, false, outputFile, null, true);
            var project = new CodeProject(0, projectPath, new Configuration(null));

            foreach (var file in Directory.EnumerateFiles(projectPath, "*.cs", searchOption))
            {
                //TODO: This is pretty hacky. Have to figure out a better way to exclude packages and/or make this configurable.
                if (file.Contains("\\packages\\"))
                {
                    continue;
                }

                console.Core.Environment.AddSourceCode(project, file, null);
            }

            var violationEncounteredFilter = new EventHandler <ViolationEventArgs>(delegate(Object sender, ViolationEventArgs args)
            {
                if (string.IsNullOrEmpty(rule) || rule.Equals(args.Violation.Rule.CheckId))
                {
                    OnViolationEncountered(sender, args);
                }
            });

            console.OutputGenerated      += OnOutputGenerated;
            console.ViolationEncountered += violationEncounteredFilter;
            console.Start(new[] { project }, true);
            console.OutputGenerated      -= OnOutputGenerated;
            console.ViolationEncountered -= violationEncounteredFilter;

            return(_encounteredViolations > 0 ? (int)ExitCode.Failed : (int)ExitCode.Passed);
        }
Example #4
0
        public void Run(ModData modData, string[] args)
        {
            var relativePath = args[1];
            var projectPath  = Path.GetFullPath(relativePath);

            var console = new StyleCopConsole(null, false, null, null, true);
            var project = new CodeProject(0, projectPath, new Configuration(null));

            foreach (var filePath in Directory.GetFiles(projectPath, "*.cs", SearchOption.AllDirectories))
            {
                console.Core.Environment.AddSourceCode(project, filePath, null);
            }

            console.ViolationEncountered += OnViolationEncountered;
            console.Start(new[] { project }, true);

            if (violationCount > 0)
            {
                Environment.Exit(1);
            }
            else
            {
                Console.WriteLine("No violations encountered in {0}.".F(relativePath));
            }
        }
Example #5
0
        private static int ProcessFileOrFolder(string settings, string path, string outputFile, SearchOption searchOption)
        {
            var console = new StyleCopConsole(settings, false, outputFile, null, true);
            var project = new CodeProject(0, path, new Configuration(null));

            if (Path.GetExtension(path) == ".cs")
            {
                console.Core.Environment.AddSourceCode(project, path, null);
            }
            else
            {
                foreach (var file in Directory.EnumerateFiles(path, "*.cs", searchOption))
                {
                    //TODO: This is pretty hacky. Have to figure out a better way to exclude packages and/or make this configurable.
                    if (file.Contains("\\packages\\"))
                    {
                        continue;
                    }

                    console.Core.Environment.AddSourceCode(project, file, null);
                }
            }

            console.OutputGenerated      += OnOutputGenerated;
            console.ViolationEncountered += OnViolationEncountered;
            console.Start(new[] { project }, true);
            console.OutputGenerated      -= OnOutputGenerated;
            console.ViolationEncountered -= OnViolationEncountered;

            return(_encounteredViolations > 0 ? (int)ExitCode.Failed : (int)ExitCode.Passed);
        }
Example #6
0
        /// <summary>
        /// 更新项目信息信息
        /// </summary>
        /// <param name="dtos">包含更新信息的项目信息DTO信息</param>
        /// <returns>业务操作结果</returns>
        public async Task <OperationResult> UpdateCodeProjects(params CodeProjectInputDto[] dtos)
        {
            List <string> names = new List <string>();

            UnitOfWork.EnableTransaction();
            foreach (var dto in dtos)
            {
                dto.Validate();
                if (await CheckCodeProjectExists(m => m.Name == dto.Name, dto.Id))
                {
                    return(new OperationResult(OperationResultType.Error, $"名称为“{dto.Name}”的项目信息已存在"));
                }

                CodeProject existing = await ProjectRepository.GetAsync(dto.Id);

                existing = dto.MapTo(existing);
                int count = await ProjectRepository.UpdateAsync(existing);

                if (count > 0)
                {
                    names.Add(dto.Name);
                }
            }

            await UnitOfWork.CommitAsync();

            return(names.Count > 0
                ? new OperationResult(OperationResultType.Success, $"项目“{names.ExpandAndToString()}”更新成功")
                : OperationResult.NoChanged);
        }
Example #7
0
        public static ProjectViewModel ToViewModel(this CodeProject project)
        {
            ProjectViewModel model = IoC.Get <ProjectViewModel>();

            model = project.MapTo(model);
            return(model);
        }
Example #8
0
        /// <summary>
        /// 生成项目所有代码
        /// </summary>
        /// <param name="templates">要处理的代码配置集合</param>
        /// <param name="project">代码项目信息</param>
        /// <returns>输出的代码文件信息集合</returns>
        public async Task <CodeFile[]> GenerateCodes(CodeTemplate[] templates, CodeProject project)
        {
            List <CodeFile> codeFiles = new List <CodeFile>();

            CodeModule[] modules  = project.Modules.ToArray();
            CodeEntity[] entities = modules.SelectMany(m => m.Entities).ToArray();

            CodeTemplate[] templates2 = templates.Where(m => m.MetadataType == MetadataType.Entity).ToArray();
            foreach (CodeTemplate template in templates2)
            {
                foreach (CodeEntity entity in entities)
                {
                    codeFiles.Add(await GenerateCode(template, entity));
                }
            }

            templates2 = templates.Where(m => m.MetadataType == MetadataType.Module).ToArray();
            foreach (CodeTemplate template in templates2)
            {
                foreach (CodeModule module in modules)
                {
                    codeFiles.Add(await GenerateCode(template, module));
                }
            }

            templates2 = templates.Where(m => m.MetadataType == MetadataType.Project).ToArray();
            foreach (CodeTemplate template in templates2)
            {
                codeFiles.Add(await GenerateCode(template, project));
            }

            return(codeFiles.OrderBy(m => m.FileName).ToArray());
        }
        void IUtilityCommand.Run(Utility utility, string[] args)
        {
            var relativePath = args[1];
            var projectPath  = Path.GetFullPath(relativePath);

            // HACK: The engine code assumes that Game.modData is set.
            Game.ModData = utility.ModData;

            var console = new StyleCopConsole(null, false, null, null, true);
            var project = new CodeProject(0, projectPath, new Configuration(null));

            foreach (var filePath in Directory.GetFiles(projectPath, "*.cs", SearchOption.AllDirectories))
            {
                console.Core.Environment.AddSourceCode(project, filePath, null);
            }

            console.ViolationEncountered += OnViolationEncountered;
            console.Start(new[] { project }, true);

            if (violationCount > 0)
            {
                Environment.Exit(1);
            }
            else
            {
                Console.WriteLine("No violations encountered in {0}.".F(relativePath));
            }
        }
Example #10
0
        private static int AnalyzeSubversion()
        {
            var fileMap = SaveCommittedFilesToTemp();

            // Run StyleCop

            var styleCop = new StyleCopConsole(_options.Settings, false, null, null, true);

            var rootPath = GetRootPath(fileMap.Keys.ToList());
            var project  = new CodeProject(0, rootPath, new Configuration(null));

            foreach (var file in fileMap.Keys.ToList())
            {
                styleCop.Core.Environment.AddSourceCode(project, file, null);
            }

            styleCop.OutputGenerated += OnOutputGenerated;

            var violationCount = 0;

            styleCop.ViolationEncountered += (sender, e) =>
            {
                Console.Error.WriteLine("{0}({1}): {2} {3}",
                                        fileMap[e.SourceCode.Path], e.LineNumber, e.Violation.Rule.CheckId, e.Message);

                violationCount += 1;
            };

            styleCop.Start(new[] { project }, true);

            Console.Error.WriteLine("");
            Console.Error.WriteLine("{0} Violations found", violationCount);

            return(violationCount > 0 ? 2 : 0);
        }
Example #11
0
        private static async void Method11()
        {
            Console.WriteLine("请输入代码模板:");
            string       input    = Console.ReadLine();
            CodeProject  project  = null;
            CodeTemplate template = null;
            await _provider.ExecuteScopedWorkAsync(provider =>
            {
                IDataContract contract = provider.GetRequiredService <IDataContract>();
                CodeProject[] projects = contract.GetCodeProject(m => true);
                project  = projects[0];
                template = contract.CodeTemplates.FirstOrDefault(m => m.Name == input);
                return(Task.CompletedTask);
            });

            if (template == null)
            {
                Console.WriteLine($"模板 {input} 不存在");
                return;
            }
            ICodeGenerator generator = _provider.GetService <ICodeGenerator>();

            //var model = project.Modules.First().Entities.First();
            //var model = project.Modules.First();
            var      model = project;
            CodeFile file  = await generator.GenerateCode(template, model);

            File.WriteAllText(@"D:\Temp\11.txt", file.SourceCode);
            Console.WriteLine(file.SourceCode);
        }
Example #12
0
        private static int ProcessFolder(string settings, string projectPath, SearchOption searchOption)
        {
            Log($"Using Stylecop settings located at '{settings}'");
            Log($"Checking folder: {new FileInfo(projectPath).FullName}");
            var console = new StyleCopConsole(settings, false, null, null, true);
            var project = new CodeProject(0, projectPath, new Configuration(null));

            var files = Directory.EnumerateFiles(projectPath, "*.cs", searchOption).ToList();

            files = GetCSharpFiles(files);
            Log($"Checking {files.Count} files");


            foreach (var file in files)
            {
                console.Core.Environment.AddSourceCode(project, file, null);
            }

            console.OutputGenerated      += OnOutputGenerated;
            console.ViolationEncountered += OnViolationEncountered;
            console.Start(new[] { project }, true);
            console.OutputGenerated      -= OnOutputGenerated;
            console.ViolationEncountered -= OnViolationEncountered;

            if (_encounteredViolations > 0)
            {
                Log($"Finished with {_encounteredViolations} errors");
                return((int)ExitCode.Failed);
            }

            Log("Success");
            return((int)ExitCode.Passed);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="StringBasedSourceCode"/> class.
        /// </summary>
        /// <param name="project">
        /// The project.
        /// </param>
        /// <param name="parser">
        /// The parser.
        /// </param>
        /// <param name="path">
        /// The path.
        /// </param>
        /// <param name="source">
        /// The source.
        /// </param>
        public StringBasedSourceCode(CodeProject project, SourceParser parser, string path, string source)
            : base(project, parser)
        {
            this.source = source;

            this.path = path;

            // Strip out the name of the file.
            int index = path.LastIndexOf(@"\", StringComparison.Ordinal);
            if (-1 == index)
            {
                this.name = this.path;
            }
            else
            {
                this.name = path.Substring(index + 1, path.Length - index - 1);
            }

            // Strip out the file extension.
            index = this.name.LastIndexOf(".", StringComparison.Ordinal);
            if (-1 == index)
            {
                this.fileType = string.Empty;
            }
            else
            {
                this.fileType = this.name.Substring(index + 1, this.name.Length - index - 1).ToUpperInvariant();
            }
        }
Example #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StringBasedSourceCode"/> class.
        /// </summary>
        /// <param name="project">
        /// The project.
        /// </param>
        /// <param name="parser">
        /// The parser.
        /// </param>
        /// <param name="path">
        /// The path.
        /// </param>
        /// <param name="source">
        /// The source.
        /// </param>
        public StringBasedSourceCode(CodeProject project, SourceParser parser, string path, string source)
            : base(project, parser)
        {
            this.source = source;

            this.path = path;

            // Strip out the name of the file.
            int index = path.LastIndexOf(@"\", StringComparison.Ordinal);

            if (-1 == index)
            {
                this.name = this.path;
            }
            else
            {
                this.name = path.Substring(index + 1, path.Length - index - 1);
            }

            // Strip out the file extension.
            index = this.name.LastIndexOf(".", StringComparison.Ordinal);
            if (-1 == index)
            {
                this.fileType = string.Empty;
            }
            else
            {
                this.fileType = this.name.Substring(index + 1, this.name.Length - index - 1).ToUpperInvariant();
            }
        }
        /// <summary>
        /// 获取项目代码输出文件名
        /// </summary>
        public string GetCodeFileName(CodeProject project)
        {
            string fileName = OutputFileFormat.Replace("{Project.NamespacePrefix}", project.NamespacePrefix)
                              .Replace("{Project.Name:Lower}", project.Name.UpperToLowerAndSplit())
                              .Replace("{Project.Name}", project.Name);

            return(fileName);
        }
Example #16
0
 public void Initialaze()
 {
     _scConsole  = new StyleCopConsole(TestProjectPath, true, null, null, true, null);
     _project    = new CodeProject(1, TestProjectPath, new Configuration(new string[0]));
     _violations = new List <Violation>();
     _scConsole.ViolationEncountered += scConsole_ViolationEncontered;
     _scConsole.OutputGenerated      += scConsole_OutputGenerated;
 }
Example #17
0
        /// <summary>
        /// Add given Visual C# source file to given code project.
        /// </summary>
        /// <param name="sourceFile">
        /// CSharpSourceFile representing Visual C# source file to add.
        /// </param>
        /// <param name="codeProject">
        /// Code project to add Visual C# source file to.
        /// </param>
        static void AddSourceFile(CSharpSourceFile sourceFile,
                                  CodeProject codeProject)
        {
            sourceFile.Load();

            Analyzer.Core.Environment.AddSourceCode(codeProject,
                                                    sourceFile.FilePath, null);
        }
        public static void Execute(ICakeContext context, FilePath solutionFile, FilePath settingsFile)
        {
            if (solutionFile == null)
            {
                throw new ArgumentNullException(nameof(solutionFile), "Solution file path is null.");
            }

            var solutionParser = new SolutionParser(context.FileSystem, context.Environment);
            var projectParser  = new ProjectParser(context.FileSystem, context.Environment);

            var stylecopSettingsFile = settingsFile == null ? null : settingsFile.ToString();

            var projectPath = Cake.Common.IO.DirectoryAliases.Directory(context, solutionFile.MakeAbsolute(context.Environment).GetDirectory().FullPath);

            Cake.Common.Diagnostics.LoggingAliases.Information(context, string.Format("Project Path: {0}", projectPath.Path.FullPath));

            var styleCopConsole = new StyleCop.StyleCopConsole(
                stylecopSettingsFile,
                false, /* Input Cache Result */
                null,  /* Output file */
                null,
                true);

            var styleCopProjects = new List <CodeProject>();

            var solution = solutionParser.Parse(solutionFile);

            foreach (var solutionProject in solution.Projects)
            {
                var project         = projectParser.Parse(solutionProject.Path);
                var styleCopProject = new CodeProject(0, solutionProject.Path.GetDirectory().ToString(), new Configuration(null));
                styleCopProjects.Add(styleCopProject);

                foreach (var projectFile in project.Files)
                {
                    if (projectFile.FilePath.GetExtension() == ".cs")
                    {
                        styleCopConsole.Core.Environment.AddSourceCode(
                            styleCopProject,
                            projectFile.FilePath.ToString(),
                            null);
                    }
                }
            }

            var handler = new StylecopHandlers(context);

            styleCopConsole.OutputGenerated      += handler.OnOutputGenerated;
            styleCopConsole.ViolationEncountered += handler.ViolationEncountered;
            styleCopConsole.Start(styleCopProjects.ToArray(), true);
            styleCopConsole.OutputGenerated      -= handler.OnOutputGenerated;
            styleCopConsole.ViolationEncountered -= handler.ViolationEncountered;

            if (handler.TotalViolations > 0)
            {
                throw new Exception(string.Format("{0} StyleCop violations encountered.", handler.TotalViolations));
            }
        }
        /// <summary>
        /// Retrieves a <see cref="SourceCode"/> object corresponding to the given path.
        /// </summary>
        /// <param name="path">
        /// The path to the source code object.
        /// </param>
        /// <param name="project">
        /// The project which contains the source code object.
        /// </param>
        /// <param name="parser">
        /// The parser for the source code type.
        /// </param>
        /// <param name="context">
        /// Optional context.
        /// </param>
        /// <returns>
        /// Returns the source code object.
        /// </returns>
        private SourceCode SourceCodeFactory(string path, CodeProject project, SourceParser parser, object context)
        {
            Param.Ignore(path, project, parser, context);

            int index = (int)context;
            Assert.IsTrue(index >= 0 && index < StaticSource.Sources.Length, "The index is out of range.");

            return new ObjectBasedSourceCode(project, parser, index);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ObjectBasedSourceCode"/> class.
        /// </summary>
        /// <param name="project">
        /// The project.
        /// </param>
        /// <param name="parser">
        /// The parser.
        /// </param>
        /// <param name="index">
        /// The index.
        /// </param>
        public ObjectBasedSourceCode(CodeProject project, SourceParser parser, int index)
            : base(project, parser)
        {
            Param.Ignore(project);
            Param.Ignore(parser);
            Param.AssertValueBetween(index, 0, StaticSource.Sources.Length - 1, "Out of range.");

            this.index = index;
        }
Example #21
0
        private async Task RunCombinedPackages()
        {
            var packages = CodeProjects.SelectMany(cp => cp.PackageStatuses);
            var grouped  = packages.GroupBy(p => p.Id);

            _logger.LogInformation($"Found {grouped.Count()} different package Id's\n");


            // Update CodeProject list
            var cps = new List <CodeProject>();

            cps.Add(new CodeProject()
            {
                Name = "Dependency Report"
            });


            // Iterate trough packages grouped by Id
            foreach (var packageGroup in grouped)
            {
                var distincted = packageGroup
                                 .Select(g => g)
                                 .Distinct(new IdAndInstalledVersionComparer());

                _logger.LogInformation($"Checking package {distincted.First().Id}");

                if (distincted.Count() == 1)
                {
                    // Check status for normal package
                    var p       = distincted.First();
                    var package = await GetPackageStatus(p.Id, p.InstalledVersion);

                    cps[0].PackageStatuses.Add(package);
                }
                else
                {
                    // Check status for double packages
                    var cp = new CodeProject()
                    {
                        Name = distincted.First().Id
                    };

                    foreach (var p in distincted)
                    {
                        var package = await GetPackageStatus(p.Id, p.InstalledVersion);

                        package.Id = p.DefinedInFile;
                        cp.PackageStatuses.Add(package);
                    }
                    cps.Add(cp);
                }
                _logger.LogInformation(string.Empty);
            }

            CodeProjects.Clear();
            CodeProjects.AddRange(cps);
        }
Example #22
0
        public override IDocumentView CreateDefaultView()
        {
            PerformanceUtility.StartPerformanceSequence(PerformanceEvent.CreateCodeEditor);
            CodeProject.EnsureResolverCachePruned(this.codeProject.ProjectResolver);
            IDocumentView documentView = (IDocumentView) new CodeView((IDocument)this, this.codeProject, this.codeProjectService.MessageDisplayService, this.viewService, this.codeOptionsModel, this.windowService);

            PerformanceUtility.EndPerformanceSequence(PerformanceEvent.CreateCodeEditor);
            return(documentView);
        }
Example #23
0
        /// <summary>
        /// The create.
        /// </summary>
        /// <param name="path">
        /// The path.
        /// </param>
        /// <param name="project">
        /// The project.
        /// </param>
        /// <param name="parser">
        /// The parser.
        /// </param>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// A new StringBasedSourceCode object.
        /// </returns>
        public SourceCode Create(string path, CodeProject project, SourceParser parser, object context)
        {
            StyleCopTrace.In();

            string source = (string)context;

            StyleCopTrace.Out();

            return(new StringBasedSourceCode(project, parser, path, source));
        }
Example #24
0
        /// <summary>
        /// The create.
        /// </summary>
        /// <param name="path">
        /// The path.
        /// </param>
        /// <param name="project">
        /// The project.
        /// </param>
        /// <param name="parser">
        /// The parser.
        /// </param>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// A new StringBasedSourceCode object.
        /// </returns>
        public SourceCode Create(string path, CodeProject project, SourceParser parser, object context)
        {
            StyleCopTrace.In();

            string source = (string)context;

            SourceCode sourceCode = source == null ? (SourceCode) new CodeFile(path, project, parser) : new StringBasedSourceCode(project, parser, path, source);

            return(StyleCopTrace.Out(sourceCode));
        }
        /// <summary>
        /// The create.
        /// </summary>
        /// <param name="path">
        /// The path.
        /// </param>
        /// <param name="project">
        /// The project.
        /// </param>
        /// <param name="parser">
        /// The parser.
        /// </param>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// A new StringBasedSourceCode object.
        /// </returns>
        public SourceCode Create(string path, CodeProject project, SourceParser parser, object context)
        {
            StyleCopTrace.In();

            string source = (string)context;

            StyleCopTrace.Out();

            return new StringBasedSourceCode(project, parser, path, source);
        }
        /// <summary>
        /// The create.
        /// </summary>
        /// <param name="path">
        /// The path.
        /// </param>
        /// <param name="project">
        /// The project.
        /// </param>
        /// <param name="parser">
        /// The parser.
        /// </param>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// A new StringBasedSourceCode object.
        /// </returns>
        public SourceCode Create(string path, CodeProject project, SourceParser parser, object context)
        {
            StyleCopTrace.In();

            string source = (string)context;

            SourceCode sourceCode = source == null ? (SourceCode)new CodeFile(path, project, parser) : new StringBasedSourceCode(project, parser, path, source);

            return StyleCopTrace.Out(sourceCode);
        }
 /// <summary>
 /// Adds the source code files.
 /// </summary>
 /// <param name="files">The files.</param>
 /// <param name="console">The console.</param>
 /// <param name="project">The project.</param>
 private static void AddSourceCodeFiles(
     IEnumerable <string> files,
     StyleCopConsole console,
     CodeProject project)
 {
     foreach (var file in files)
     {
         console.Core.Environment.AddSourceCode(project, file, null);
     }
 }
        public void Setup()
        {
            Violations = new List <Violation>();
            Output     = new List <string>();

            var    configuration = new Configuration(new string[0]);
            string location      = Path.GetFullPath(StyleCopSettingsFilePath);

            _project = new CodeProject(Guid.NewGuid().GetHashCode(), location, configuration);
        }
        /// <summary>
        /// 更新项目模板信息信息
        /// </summary>
        /// <param name="dtos">包含更新信息的项目模板信息DTO信息</param>
        /// <returns>业务操作结果</returns>
        public async Task <OperationResult> UpdateCodeProjectTemplates(params CodeProjectTemplateInputDto[] dtos)
        {
            string        pName = null;
            List <string> names = new List <string>();

            UnitOfWork.EnableTransaction();
            foreach (CodeProjectTemplateInputDto dto in dtos)
            {
                dto.Validate();
                CodeProject project = await ProjectRepository.GetAsync(dto.ProjectId);

                if (project == null)
                {
                    throw new OsharpException($"编号为“{dto.ProjectId}”的项目信息不存在");
                }

                pName ??= project.Name;
                CodeTemplate template = await TemplateRepository.GetAsync(dto.TemplateId);

                if (template == null)
                {
                    throw new OsharpException($"编号为“{dto.TemplateId}”的模板信息不存在");
                }

                if (await CheckCodeProjectTemplateExists(m => m.ProjectId == dto.ProjectId && m.TemplateId == dto.TemplateId, dto.Id))
                {
                    throw new OsharpException($"项目“{project.Name}”中模板“{template.Name}”已存在,不能重复添加");
                }

                int count = 0;
                if (dto.Id == default)
                {
                    CodeProjectTemplate projectTemplate = dto.MapTo <CodeProjectTemplate>();
                    count = await ProjectTemplateRepository.InsertAsync(projectTemplate);
                }
                else
                {
                    CodeProjectTemplate projectTemplate = await ProjectTemplateRepository.GetAsync(dto.Id);

                    projectTemplate = dto.MapTo(projectTemplate);
                    count           = await ProjectTemplateRepository.UpdateAsync(projectTemplate);
                }

                if (count > 0)
                {
                    names.Add(template.Name);
                }
            }

            await UnitOfWork.CommitAsync();

            return(names.Count > 0
                ? new OperationResult(OperationResultType.Success, $"项目“{pName}”设置模板“{names.ExpandAndToString()}”成功")
                : OperationResult.NoChanged);
        }
Example #30
0
        public Source(CodeProject project, SourceParser parser, string source, string sourceName)
            : base(project, parser)
        {
            Param.Ignore(project);
            Param.Ignore(parser);
            Param.AssertNotNull(source, "source");
            Param.AssertNotNull(sourceName, "sourceName");

            this.source     = source;
            this.sourceName = sourceName;
        }
        public void Setup()
        {
            this.Violations = new List <Violation>();
            this.Output     = new List <string>();

            var configuration = new Configuration(new string[0]);

            string location = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Settings.StyleCop");

            this.project = new CodeProject(Guid.NewGuid().GetHashCode(), location, configuration);
        }
Example #32
0
        private static AnalysisThread CreateAnalysisThread(bool isFull)
        {
            StyleCopCore       core            = new StyleCopCore();
            List <CodeProject> projects        = new List <CodeProject>();
            Mock <CodeProject> mockCodeProject = new Mock <CodeProject>();
            CodeProject        codeProject     = new CodeProject(0, "test", new Configuration(new string[0]));

            projects.Add(codeProject);

            AnalysisThread target = new AnalysisThread(isFull, projects, core);

            return(target);
        }
Example #33
0
        private static AnalysisThread CreateAnalysisThread(bool isFull)
        {
            var core            = new StyleCopCore();
            var projects        = new List <CodeProject>();
            var mockCodeProject = new Mock <CodeProject>(MockBehavior.Strict);
            var codeProject     = new CodeProject(0, "test", new Configuration(new string[0]));

            projects.Add(codeProject);

            var target = new AnalysisThread(isFull, projects, core);

            return(target);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="StringBasedSourceCode"/> class.
        /// </summary>
        /// <param name="project">
        /// The project.
        /// </param>
        /// <param name="parser">
        /// The parser.
        /// </param>
        /// <param name="path">
        /// The path.
        /// </param>
        /// <param name="source">
        /// The source.
        /// </param>
        public StringBasedSourceCode(CodeProject project, SourceParser parser, string path, string source)
            : base(project, parser)
        {
            this.source = source;

            this.path = path;

            // Strip out the name of the file.
            int index = path.LastIndexOf(@"\", StringComparison.Ordinal);
            if (-1 == index)
            {
                this.name = this.path;
            }
            else
            {
                this.name = path.Substring(index + 1, path.Length - index - 1);
                this.folder = path.Substring(0, index);

                if (this.folder != null)
                {
                    // Trim the path and convert it to lowercase characters
                    // so that we can do string matches and find other files and
                    // projects under the same path.
                    this.folder = CleanPath(this.folder);
                }
            }

            // Strip out the file extension.
            index = this.name.LastIndexOf(".", StringComparison.Ordinal);
            if (-1 == index)
            {
                this.fileType = string.Empty;
            }
            else
            {
                this.fileType = this.name.Substring(index + 1, this.name.Length - index - 1).ToUpperInvariant();
            }
        }
Example #35
0
        private static int ProcessFolder(string settings, string projectPath, SearchOption searchOption)
        {
            var console = new StyleCopConsole(settings, false, null, null, true);
            var project = new CodeProject(0, projectPath, new Configuration(null));

            foreach (var file in Directory.EnumerateFiles(projectPath, "*.cs", SearchOption.AllDirectories))
            {
                //TODO: This is pretty hacky. Have to figure out a better way to exclude packages and/or make this configurable.
                if (file.Contains("\\packages\\"))
                {
                    continue;
                }

                console.Core.Environment.AddSourceCode(project, file, null);
            }

            console.OutputGenerated += OnOutputGenerated;
            console.ViolationEncountered += OnViolationEncountered;
            console.Start(new[] {project}, true);
            console.OutputGenerated -= OnOutputGenerated;
            console.ViolationEncountered -= OnViolationEncountered;

            return _encounteredViolations > 0 ? (int) ExitCode.Failed : (int) ExitCode.Passed;
        }
Example #36
0
        /// <summary>
        /// Creates the list of project files to be analyzed.
        /// </summary>
        /// <param name="core"><see cref="T:StyleCopCore">Core object</see> that hosts the environment.</param>
        /// <param name="type">The analyze type being performed.</param>
        /// <returns>Returns the list of projects.</returns>
        internal static IList<CodeProject> GetProjectList(StyleCopCore core, AnalysisType type)
        {
            Param.AssertNotNull(core, "core");
            Param.Ignore(type);

            // Create a list to store the list of code projects to be analyzed.
            List<CodeProject> codeProjects = new List<CodeProject>();

            DTE applicationObject = GetDTE();

            if (type == AnalysisType.Solution || type == AnalysisType.Project)
            {
                // Create a project enumerator for the correct VS project list.
                ProjectCollection enumerator = new ProjectCollection();

                if (type == AnalysisType.Solution)
                {
                    enumerator.SolutionProjects = applicationObject.Solution.Projects;
                }
                else
                {
                    enumerator.SelectedProjects = (System.Collections.IEnumerable)applicationObject.ActiveSolutionProjects;
                }

                // Enumerate through the VS projects.
                foreach (Project project in enumerator)
                {
                    if (project != null)
                    {
                        EnumerateProject(
                            project,
                            new ProjectInvoker(AddCodeProject),
                            new ProjectItemInvoker(AddFileToProject),
                            codeProjects,
                            null);
                    }
                }
            }
            else if (type == AnalysisType.Item || type == AnalysisType.Folder)
            {
                GetSelectedItemFiles(codeProjects);
            }
            else if (type == AnalysisType.File)
            {
                Document document = applicationObject.ActiveDocument;
                if (document != null)
                {
                    CodeProject codeProject = null;

                    string projectPath = GetProjectPath(document.ProjectItem.ContainingProject);
                    if (projectPath != null)
                    {
                        codeProject = new CodeProject(
                            projectPath.GetHashCode(),
                            projectPath,
                            GetProjectConfiguration(document.ProjectItem.ContainingProject));
                    }
                    else if (document.FullName != null && document.FullName.Length > 0)
                    {
                        codeProject = new CodeProject(
                            document.FullName.GetHashCode(),
                            Path.GetDirectoryName(document.FullName),
                            new StyleCop.Configuration(null));
                    }

                    if (codeProject != null)
                    {
                        core.Environment.AddSourceCode(codeProject, document.FullName, document);
                        codeProjects.Add(codeProject);
                    }
                }
            }
            else
            {
                Debug.Fail("Unknown analysis type requested.");
            }

            return codeProjects;
        }
Example #37
0
        /// <summary>
        /// Adds a code project to the given list.
        /// </summary>
        /// <param name="project">The project to add.</param>
        /// <param name="projectKey">The unique key for the project.</param>
        /// <param name="path">The path to the project.</param>
        /// <param name="projectContext">Must contain a list of code projects.</param>
        /// <param name="fileContext">The context that will be passed to the file enumerator.</param>
        /// <returns>Always returns null so that enumeration will continue.</returns>
        private static object AddCodeProject(
            Project project, int projectKey, string path, ref object projectContext, ref object fileContext)
        {
            Param.AssertNotNull(project, "project");
            Param.Ignore(projectKey);
            Param.AssertValidString(path, "path");
            Param.AssertNotNull(projectContext, "projectContext");
            Param.Ignore(fileContext);

            // Get the list of code projects.
            List<CodeProject> codeProjects = (List<CodeProject>)projectContext;

            // Create a new CodeProject for this project.
            CodeProject codeProject = new CodeProject(
                projectKey,
                path,
                ProjectUtilities.GetProjectConfiguration(project));

            // Set this new CodeProject as the outgoing file context.
            fileContext = codeProject;

            // Add the new CodeProject to the list.
            codeProjects.Add(codeProject);

            return null;
        }
        /// <summary>
        /// Create a separate CodeProject for a specified .csproj file
        /// </summary>
        /// <param name="projectFilePath">File path to a .csproj file</param>
        /// <param name="console">Reference to our master console</param>
        /// <param name="configuration">Configuration from the commandline</param>
        /// <returns>Newly constructed CodeProject instance</returns>
        private CodeProject CreateProject(string projectFilePath, StyleCopConsole console, Configuration configuration)
        {
            string directory = Path.GetDirectoryName(projectFilePath);

            CodeProject project = new CodeProject(projectFilePath.GetHashCode(), projectFilePath, configuration);
            XDocument projectFile = XDocument.Load(projectFilePath);

            foreach (XElement x in projectFile.Descendants().Where(x => x.Name.LocalName.Equals("Compile")))
            {
                string file = x.Attribute("Include").Value;
                string filePath = Path.Combine(directory, file);
                console.Core.Environment.AddSourceCode(project, filePath, null);
            }

            return project;
        }
        /// <summary>
        /// Creates the list of project files to be analyzed.
        /// </summary>
        /// <param name="core"><see cref="T:StyleCopCore">Core object</see> that hosts the environment.</param>
        /// <param name="type">The analyze type being performed.</param>
        /// <param name="analysisFilePath">The path to the initial file we are analyzing.</param>
        /// <param name="analysisHelper">The analysis helper.</param>
        /// <returns>Returns the list of projects.</returns>
        internal static IList<CodeProject> GetProjectList(StyleCopCore core, AnalysisType type, out string analysisFilePath, AnalysisHelper analysisHelper)
        {
            Param.AssertNotNull(core, "core");
            Param.Ignore(type);

            // Create a list to store the list of code projects to be analyzed.
            List<CodeProject> codeProjects = new List<CodeProject>();

            DTE applicationObject = GetDTE();

            analysisFilePath = null;

            switch (type)
            {
                case AnalysisType.Project:
                case AnalysisType.Solution:
                    // Create a project enumerator for the correct VS project list.
                    ProjectCollection enumerator = new ProjectCollection();

                    if (type == AnalysisType.Solution)
                    {
                        enumerator.SolutionProjects = applicationObject.Solution.Projects;
                    }
                    else
                    {
                        enumerator.SelectedProjects = (IEnumerable)applicationObject.ActiveSolutionProjects;
                    }

                    // Enumerate through the VS projects.
                    foreach (Project project in enumerator)
                    {
                        // We continue if we know the project type or if its a misc item or a solution folder
                        if (project != null && (IsKnownProjectType(project, analysisHelper) ||
                            project.Kind == Constants.vsProjectKindMisc ||
                            project.Kind == Constants.vsProjectKindSolutionItems))
                        {
                            EnumerateProject(project, AddCodeProject, AddFileToProject, codeProjects, null);
                        }
                    }

                    break;

                case AnalysisType.Folder:
                case AnalysisType.Item:
                    analysisFilePath = GetSelectedItemFiles(codeProjects);
                    break;

                case AnalysisType.File:
                    var document = applicationObject.ActiveDocument;
                    if (document != null)
                    {
                        CodeProject codeProject = null;

                        string projectPath = GetProjectPath(document.ProjectItem.ContainingProject);
                        if (projectPath != null)
                        {
                            codeProject = new CodeProject(projectPath.GetHashCode(), projectPath, GetProjectConfiguration(document.ProjectItem.ContainingProject), TargetFrameworkVersion(document.ProjectItem.ContainingProject));
                        }
                        else if (!string.IsNullOrEmpty(document.FullName))
                        {
                            codeProject = new CodeProject(document.FullName.GetHashCode(), Path.GetDirectoryName(document.FullName), new StyleCop.Configuration(null));
                        }

                        if (codeProject != null)
                        {
                            // If this is a designer.cs file (and so a dependant of another file) then we need to add it but also its parent and siblings.
                            analysisFilePath = document.FullName;

                            var allFilesForProjectItem = GetAllFilesForProjectItem(document.ProjectItem);

                            foreach (var path in allFilesForProjectItem)
                            {
                                core.Environment.AddSourceCode(codeProject, path, null);
                            }

                            codeProjects.Add(codeProject);
                        }
                    }

                    break;
                default:
                    Debug.Fail("Unknown analysis type requested.");
                    break;
            }

            return codeProjects;
        }
    /// <summary>
    /// Create a list with StyleCop code project based on the MonoDevelop projects and files in <paramref name="fromMonoDevelopProjects"/>.
    /// </summary>
    /// <param name="fromMonoDevelopProjects">MonoDevelop projects with files.</param>
    /// <returns>A list containing all possible StyleCop code projects.</returns>
    internal List<CodeProject> CreateStyleCopCodeProjects(Dictionary<Project, HashSet<ProjectFile>> fromMonoDevelopProjects)
    {
      List<CodeProject> resultList = new List<CodeProject>();

      if (fromMonoDevelopProjects != null)
      {
        foreach (var projectKvP in fromMonoDevelopProjects)
        {
          // If the value is null get the code project from our cached projects.
          if (projectKvP.Value == null)
          {
            resultList.Add(this.CachedProjects.CreateStyleCopCodeProject(projectKvP.Key));
          }
          else
          {
            CodeProject newStyleCopProject = new CodeProject(projectKvP.Key.BaseDirectory.GetHashCode(), projectKvP.Key.BaseDirectory, new Configuration(null));
            foreach (var file in projectKvP.Value)
            {
              ProjectUtilities.Instance.Core.Environment.AddSourceCode(newStyleCopProject, file.FilePath, null);
            }

            resultList.Add(newStyleCopProject);
          }
        }
      }

      return resultList;
    }
        /// <summary>
        /// Returns an array of <see cref="CodeProject"/> which are required to fulfill the
        /// StyleCopCore.Analyze(IList{CodeProject}) method contract to parse the
        /// current file.
        /// </summary>
        /// <param name="core">
        /// StyleCopCore which performs the Source Analysis.
        /// </param>
        /// <param name="projectFile">
        /// The project file we are checking.
        /// </param>
        /// <param name="document">
        /// The document.
        /// </param>
        /// <returns>
        /// Returns an array of <see cref="CodeProject"/>.
        /// </returns>
        public static CodeProject[] GetProjects(StyleCopCore core, IProjectFile projectFile, IDocument document)
        {
            StyleCopTrace.In(core);

            // TODO We should load the configuration values for the project not just DEBUG and TRACE
            Configuration configuration = new Configuration(new[] { "DEBUG", "TRACE" });

            IList<IProjectFile> projectFiles = GetAllFilesForFile(projectFile);

            CodeProject[] codeProjects = new CodeProject[projectFiles.Count];
            int i = 0;

            foreach (IProjectFile projectfile in projectFiles)
            {
                string path = projectfile.Location.FullPath;

                CodeProject codeProject = new CodeProject(projectfile.GetHashCode(), path, configuration);

                string documentTextToPass = i == 0 ? document.GetText() : null;
                core.Environment.AddSourceCode(codeProject, path, documentTextToPass);

                codeProjects[i++] = codeProject;
            }

            return StyleCopTrace.Out(codeProjects);
        }
    /// <summary>
    /// Create a StyleCop compatible code project from MonoDevelop project.
    /// </summary>
    /// <param name="projectToUse">MonoDevelop project to use for StyleCop code project creation.</param>
    /// <returns>A StyleCop code project or null if something failed or the MonoDevelop project type is incompatible.</returns>
    public CodeProject CreateStyleCopCodeProject(Project projectToUse)
    {
      Param.AssertNotNull(projectToUse, "projectToUse");

      if (projectToUse != null)
      {
        this.CacheWholeProject(projectToUse);

        // Only go on if the project was cached successfully.
        if (this.IsWholeProjectCached(projectToUse))
        {
          CodeProject newStyleCopProject = new CodeProject(projectToUse.BaseDirectory.GetHashCode(), projectToUse.BaseDirectory, new Configuration(null));
          foreach (var currentFile in this.projectCache[projectToUse])
          {
            ProjectUtilities.Instance.Core.Environment.AddSourceCode(newStyleCopProject, currentFile.FilePath, null);
          }

          return newStyleCopProject;
        }
      }

      return null;
    }
        private void Scan()
        {
            this.LogTaskMessage("Performing StyleCop scan...");
            if (File.Exists(this.SettingsFile.GetMetadata("FullPath")) == false)
            {
                Log.LogError(string.Format(CultureInfo.CurrentCulture, "The Settings file was not found: {0}", this.SettingsFile.GetMetadata("FullPath")));
                return;
            }

            this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "SourceFiles count is: {0}", this.SourceFiles.Length));
            List<string> addinPaths = new List<string>();
            StyleCopConsole console = new StyleCopConsole(this.SettingsFile.GetMetadata("FullPath"), this.CacheResults, this.OutputFile == null ? null : this.OutputFile.GetMetadata("FullPath"), addinPaths, true);
            
            Configuration configuration = new Configuration(new string[0]);
            CodeProject project = new CodeProject(DateTime.Now.ToLongTimeString().GetHashCode(), null, configuration);
            foreach (ITaskItem item2 in this.SourceFiles)
            {
                if (this.ShowOutput)
                {
                    this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Adding file: {0}", item2.ItemSpec));
                }

                if (!console.Core.Environment.AddSourceCode(project, item2.ItemSpec, null))
                {
                    Log.LogError(string.Format(CultureInfo.CurrentCulture, "Failed to add file: {0}", item2.ItemSpec));
                    return;
                }
            }

            try
            {
                if (this.ShowOutput)
                {
                    console.OutputGenerated += this.OnOutputGenerated;
                }

                console.ViolationEncountered += this.OnViolationEncountered;
                CodeProject[] projects = new[] { project };
                console.Start(projects, this.ForceFullAnalysis);
            }
            finally
            {
                if (this.ShowOutput)
                {
                    console.OutputGenerated -= this.OnOutputGenerated;
                }

                console.ViolationEncountered -= this.OnViolationEncountered;
            }

            // log the results to disk if there have been failures AND LogFile is specified
            if (this.LogFile != null && this.Succeeded == false)
            {
                using (StreamWriter streamWriter = new StreamWriter(this.LogFile.GetMetadata("FullPath"), false, Encoding.UTF8))
                {
                    foreach (ITaskItem i in this.FailedFiles)
                    {
                        string checkid = i.GetMetadata("CheckId") ?? "NoCheckIdFound";
                        string message = i.GetMetadata("Message") ?? "NoMessageFound";
                        string linenumber = i.GetMetadata("LineNumber") ?? "NoLineNumberFound";
                        streamWriter.WriteLine(i.ItemSpec + " (" + checkid + ": " + message + " Line: " + linenumber + ")");
                    }
                }
            }

            // set the ViolationCount
            this.ViolationCount = this.failedFiles.Count;
        }
        public override bool Execute()
        {
            // Clear the violation count and set the violation limit for the project.
            this.violationCount = 0;
            this.violationLimit = 0;

            if (this.maxViolationCount != null)
            {
                int.TryParse(this.maxViolationCount.ItemSpec, out this.violationLimit);
            }

            if (this.violationLimit == 0)
            {
                this.violationLimit = DefaultViolationLimit;
            }

            Log.LogMessage(MessageImportance.Low, "ViolationLimit: '{0}'", this.violationLimit);

            // Get settings files (if null or empty use null filename so it uses right default).
            string overrideSettingsFileName = null;
            if (this.inputOverrideSettingsFile != null && this.inputOverrideSettingsFile.ItemSpec.Length > 0)
            {
                overrideSettingsFileName = this.inputOverrideSettingsFile.ItemSpec;
            }

            Log.LogMessage(MessageImportance.Low, "OverrideSettingsFile: '{0}'", overrideSettingsFileName ?? "(none)");

            Log.LogMessage(MessageImportance.Low, "CacheResults: '{0}'", CacheResults);

            var outputFile = OutputFile == null ? null : OutputFile.ItemSpec;
            Log.LogMessage(MessageImportance.Low, "OutputFile: '{0}'", outputFile ?? "(none)");

            // Get addin paths.
            List<string> addinPaths = new List<string>();
            foreach (ITaskItem addinPath in this.inputAdditionalAddinPaths)
            {
                addinPaths.Add(addinPath.GetMetadata("FullPath"));
            }

            if (addinPaths.Count > 0)
            {
                Log.LogMessage(MessageImportance.Low, "AdditionalAddins:");
                foreach (var addinPath in addinPaths)
                {
                    Log.LogMessage(MessageImportance.Low, "\t'{0}'", addinPath);
                }
            }

            if (this.IgnoreVoluntaryRules)
            {
                Log.LogMessage(MessageImportance.Low, "IgnoreVoluntaryRules: True");
            }

            if (this.AlwaysIgnoredRuleIds != null)
            {
                Log.LogMessage(MessageImportance.Low, "AlwaysIgnoredRuleIds:");
                foreach (var ruleId in this.AlwaysIgnoredRuleIds)
                {
                    Log.LogMessage(MessageImportance.Low, "\t'{0}'", ruleId);
                }
            }

            if (this.MandatoryRuleIds != null)
            {
                Log.LogMessage(MessageImportance.Low, "MandatoryRuleIds:");
                foreach (var ruleId in this.MandatoryRuleIds)
                {
                    Log.LogMessage(MessageImportance.Low, "\t'{0}'", ruleId);
                }
            }

            // Create the StyleCop console.
            StyleCopConsole console = new StyleCopConsole(
                overrideSettingsFileName,
                this.inputCacheResults,
                this.outputFile == null ? null : this.outputFile.ItemSpec,
                addinPaths,
                true);

            // Create the configuration.
            Configuration configuration = new Configuration(this.inputDefineConstants);

            Log.LogMessage(MessageImportance.Low, "ProjectFullPath: '{0}'", ProjectFullPath == null ? "(null)" : ProjectFullPath.ItemSpec ?? "(none)");

            if (this.inputProjectFullPath != null && this.inputProjectFullPath.ItemSpec != null)
            {
                // Add each source file to this project.
                if (SourceFiles != null && SourceFiles.Length > 0)
                {
                    Log.LogMessage(MessageImportance.Low, "SourceFiles:");
                    foreach (var sourceFile in SourceFiles)
                    {
                        Log.LogMessage(
                            MessageImportance.Low,
                            "\t'{0}'",
                            sourceFile == null ? "(null)" : sourceFile.ItemSpec ?? "(none)");
                    }
                }

                Log.LogMessage(MessageImportance.Low, "ForceFullAnalysis: '{0}'", ForceFullAnalysis);

                // Create a CodeProject object for these files.
                CodeProject project = new CodeProject(
                    this.inputProjectFullPath.ItemSpec.GetHashCode(),
                    this.inputProjectFullPath.ItemSpec,
                    configuration);

                // Add each source file to this project.
                if (SourceFiles != null)
                {
                    foreach (ITaskItem inputSourceFile in this.inputSourceFiles)
                    {
                        console.Core.Environment.AddSourceCode(project, inputSourceFile.ItemSpec, null);
                    }
                }

                try
                {
                    // Subscribe to events
                    console.OutputGenerated += this.OnOutputGenerated;
                    console.ViolationEncountered += this.OnViolationEncountered;

                    // Analyze the source files
                    CodeProject[] projects = new CodeProject[] { project };
                    console.Start(projects, this.inputForceFullAnalysis);
                }
                catch (Exception exception)
                {
                    Log.LogError(string.Format("{0}", exception.Message));

                    if (ThrowOnError) throw;

                    return false;
                }
                finally
                {
                    // Unsubscribe from events
                    console.OutputGenerated -= this.OnOutputGenerated;
                    console.ViolationEncountered -= this.OnViolationEncountered;
                }
            }

            return this.succeeded;
        }
Example #45
0
        /// <summary>
        /// Gets the selected item files.
        /// </summary>
        /// <param name="codeProjects">The list of projects.</param>
        internal static void GetSelectedItemFiles(IList<CodeProject> codeProjects)
        {
            Param.AssertNotNull(codeProjects, "codeProjects");

            DTE applicationObject = GetDTE();

            // Check whether there are any selected files.
            if (applicationObject.SelectedItems.Count > 0)
            {
                Dictionary<Project, CodeProject> cachedProjects = new Dictionary<Project, CodeProject>();

                Project project = null;
                CodeProject codeProject = null;

                foreach (SelectedItem selectedItem in applicationObject.SelectedItems)
                {
                    if (selectedItem.ProjectItem != null && selectedItem.ProjectItem.ContainingProject != null)
                    {
                        if (selectedItem.ProjectItem.ContainingProject != project)
                        {
                            project = selectedItem.ProjectItem.ContainingProject;

                            if (!cachedProjects.TryGetValue(project, out codeProject))
                            {
                                string projectPath = GetProjectPath(project);
                                if (projectPath != null)
                                {
                                    codeProject = new CodeProject(
                                        projectPath.GetHashCode(),
                                        projectPath,
                                        GetProjectConfiguration(project));

                                    codeProjects.Add(codeProject);
                                    cachedProjects.Add(project, codeProject);
                                }
                            }
                        }

                        if (codeProject != null && project != null)
                        {
                            EnumerateProjectItem(
                                selectedItem.ProjectItem,
                                project.Name,
                                new ProjectInvoker(AddCodeProject),
                                new ProjectItemInvoker(AddFileToProject),
                                codeProjects,
                                codeProject);
                        }
                    }
                    else if (selectedItem.Project != null)
                    {
                        EnumerateProject(
                            selectedItem.Project,
                            new ProjectInvoker(AddCodeProject),
                            new ProjectItemInvoker(AddFileToProject),
                            codeProjects,
                            null);
                    }
                }
            }
        }
Example #46
0
        /// <summary>
        /// Executes the task.
        /// </summary>
        /// <returns>A value indicating whether the execution was successfuly or not.</returns>
        public override bool Execute()
        {
            string settings = null;

            if ((this.inputOverrideSettingsFile != null) && (this.inputOverrideSettingsFile.ItemSpec.Length > 0))
            {
                settings = this.inputOverrideSettingsFile.ItemSpec;
            }

            List<string> addinPaths = new List<string>();

            foreach (ITaskItem item in this.inputAdditionalAddinPaths)
            {
                addinPaths.Add(item.GetMetadata("FullPath"));
            }

            string location = Assembly.GetExecutingAssembly().Location;
            addinPaths.Add(Path.GetDirectoryName(location));
            SourceAnalysisConsole console = new SourceAnalysisConsole(settings, this.inputCacheResults, this.OutputFile, addinPaths, false);
            Configuration configuration = new Configuration(this.inputDefineConstants);
            CodeProject project = new CodeProject(this.inputProjectFullPath.ItemSpec.GetHashCode(), this.inputProjectFullPath.ItemSpec, configuration);

            foreach (ITaskItem item2 in this.inputSourceFiles)
            {
                console.Core.Environment.AddSourceCode(project, item2.ItemSpec, null);
            }

            try
            {
                console.OutputGenerated += new EventHandler<OutputEventArgs>(this.OnOutputGenerated);
                console.ViolationEncountered += new EventHandler<ViolationEventArgs>(this.OnViolationEncountered);
                CodeProject[] projects = new CodeProject[] { project };
                console.Start(projects, this.inputForceFullAnalysis);
            }
            finally
            {
                console.OutputGenerated -= new EventHandler<OutputEventArgs>(this.OnOutputGenerated);
                console.ViolationEncountered -= new EventHandler<ViolationEventArgs>(this.OnViolationEncountered);
            }

            return this.succeeded;
        }
        /// <summary>
        /// Execute StyleCop as configured by this Helper instance
        /// </summary>
        public void Execute()
        {
            StyleCopConsole console = new StyleCopConsole(SettingsFile, CacheResults, null, mAdditionalAddInPaths, true);
            Configuration configuration = new Configuration(DefineConstants.ToArray());

            List<CodeProject> projects = new List<CodeProject>();

            CodeProject defaultProject = new CodeProject(ProjectFile.GetHashCode(), ProjectFile, configuration);
            projects.Add(defaultProject);

            foreach (string s in SourceFiles)
            {
                string file = Path.GetFullPath(s);
                string extension = Path.GetExtension(file);

                if (extension.Equals(".csproj", StringComparison.InvariantCultureIgnoreCase))
                {
                    CodeProject p = CreateProject(file, console, configuration);
                    projects.Add(p);
                }
                else
                {
                    console.Core.Environment.AddSourceCode(defaultProject, s, null);
                }
            }

            try
            {
                console.OutputGenerated += new EventHandler<OutputEventArgs>(ConsoleOutput);
                console.ViolationEncountered += new EventHandler<ViolationEventArgs>(ViolationEncountered);
                console.Start(projects.ToArray(), true);
            }
            finally
            {
                console.OutputGenerated -= new EventHandler<OutputEventArgs>(ConsoleOutput);
                console.ViolationEncountered -= new EventHandler<ViolationEventArgs>(ViolationEncountered);
            }

            SaveToXml();
        }
    /// <summary>
    /// Creates the list of StyleCop CodeProjects to be analyzed of the cached MonoDevelop files.
    /// </summary>
    /// <returns>Returns the list of StyleCop CodeProjects to be analyzed.</returns>
    internal IList<CodeProject> GetProjectList()
    {
      List<CodeProject> codeProjects = new List<CodeProject>();

      if (this.CachedFiles != null && this.CachedFiles.Count > 0)
      {
        foreach (var kvp in this.CachedFiles)
        {
          Project currentProject = kvp.Key;
          var projectFiles = kvp.Value;

          Configuration activeProjectConfiguration = new Configuration(null);
          if (projectFiles.Values.Count > 0)
          {
            CodeProject codeProject = new CodeProject(currentProject.BaseDirectory.GetHashCode(), currentProject.BaseDirectory, activeProjectConfiguration);

            foreach (var currentFile in projectFiles.Values)
            {
              this.Core.Environment.AddSourceCode(codeProject, currentFile.FilePath, null);
            }

            codeProjects.Add(codeProject);
          }
        }
      }

      return codeProjects;
    }
        /// <summary>
        /// Gets the selected item files.
        /// </summary>
        /// <param name="codeProjects">The list of projects.</param>
        /// <returns>The path to the first file actually selected. Null if we were on a selected folder.</returns>
        internal static string GetSelectedItemFiles(IList<CodeProject> codeProjects)
        {
            Param.AssertNotNull(codeProjects, "codeProjects");

            string analysisFilePath = null;

            DTE applicationObject = GetDTE();

            // Check whether there are any selected files.
            if (applicationObject.SelectedItems.Count > 0)
            {
                var cachedProjects = new Dictionary<Project, CodeProject>();

                Project project = null;
                CodeProject codeProject = null;

                foreach (SelectedItem selectedItem in applicationObject.SelectedItems)
                {
                    if (selectedItem.ProjectItem != null && selectedItem.ProjectItem.ContainingProject != null)
                    {
                        if (selectedItem.ProjectItem.ContainingProject != project)
                        {
                            project = selectedItem.ProjectItem.ContainingProject;

                            if (!cachedProjects.TryGetValue(project, out codeProject))
                            {
                                string projectPath = GetProjectPath(project);
                                if (projectPath != null)
                                {
                                    codeProject = new CodeProject(projectPath.GetHashCode(), projectPath, GetProjectConfiguration(project), TargetFrameworkVersion(project));

                                    codeProjects.Add(codeProject);
                                    cachedProjects.Add(project, codeProject);
                                }
                            }
                        }

                        if (codeProject != null)
                        {
                            EnumerateProjectItem(selectedItem.ProjectItem, project.Name, AddCodeProject, AddFileToProject, codeProjects, codeProject);
                        }
                    }
                    else if (selectedItem.Project != null)
                    {
                        EnumerateProject(selectedItem.Project, AddCodeProject, AddFileToProject, codeProjects, null);
                    }
                }
            }

            // Not always null because of the delegates. Leave this here.
            return analysisFilePath;
        }
Example #50
0
        private void Scan()
        {
            // Clear the violation count and set the violation limit for the project.
            this.violations = new List<string>();
            this.violationLimit = 0;

            if (this.MaximumViolationCount.Get(this.ActivityContext) != 0)
            {
                this.violationLimit = this.MaximumViolationCount.Get(this.ActivityContext);
            }

            if (this.violationLimit == 0)
            {
                this.violationLimit = DefaultViolationLimit;
            }

            // Get settings files (if null or empty use null filename so it uses default).
            string settingsFileName = string.Empty;
            if (string.IsNullOrEmpty(this.SettingsFile.Get(this.ActivityContext)) == false)
            {
                settingsFileName = this.SettingsFile.Get(this.ActivityContext);
            }

            // Get addin paths.
            List<string> addinPaths = new List<string>();
            if (this.AdditionalAddInPaths.Get(this.ActivityContext) != null)
            {
                addinPaths.AddRange(this.AdditionalAddInPaths.Get(this.ActivityContext));
            }

            // Create the StyleCop console. But do not initialise the addins as this can cause modal dialogs to be shown on errors
            var console = new StyleCopConsole(settingsFileName, this.CacheResults.Get(this.ActivityContext), this.XmlOutputFile.Get(this.ActivityContext), null, false);

            // make sure the UI is not dispayed on error
            console.Core.DisplayUI = false;

            // declare the add-ins to load
            console.Core.Initialize(addinPaths, true);

            // Create the configuration.
            Configuration configuration = new Configuration(new string[0]);

            // Create a CodeProject object for these files. we use a time stamp for the key and the current directory for the cache location
            CodeProject project = new CodeProject(DateTime.Now.ToLongTimeString().GetHashCode(), @".\", configuration);

            // Add each source file to this project.
            if (this.SourceFiles.Get(this.ActivityContext) != null)
            {
                foreach (var inputSourceLocation in this.SourceFiles.Get(this.ActivityContext))
                {
                    // could be a path or a file
                    if (System.IO.File.Exists(inputSourceLocation))
                    {
                        if (this.ShowOutput.Get(this.ActivityContext))
                        {
                            this.LogBuildMessage(string.Format(CultureInfo.CurrentCulture, "Adding file to check [{0}", inputSourceLocation) + "]", BuildMessageImportance.Low);
                        }

                        console.Core.Environment.AddSourceCode(project, inputSourceLocation, null);
                    }
                    else if (System.IO.Directory.Exists(inputSourceLocation))
                    {
                        foreach (var fileInDirectory in System.IO.Directory.GetFiles(inputSourceLocation, "*.cs", SearchOption.AllDirectories))
                        {
                            if (this.ShowOutput.Get(this.ActivityContext))
                            {
                                this.LogBuildMessage(string.Format(CultureInfo.CurrentCulture, "Adding file to check [{0}", fileInDirectory) + "]", BuildMessageImportance.Low);
                            }

                            console.Core.Environment.AddSourceCode(project, fileInDirectory, null);
                        }
                    }
                    else
                    {
                        this.LogBuildMessage(string.Format(CultureInfo.CurrentCulture, "Cannot add file to check [{0}", inputSourceLocation) + "]", BuildMessageImportance.Low);
                    }
                }

                try
                {
                    // Subscribe to events
                    console.OutputGenerated += this.OnOutputGenerated;
                    console.ViolationEncountered += this.OnViolationEncountered;

                    // Analyze the source files
                    CodeProject[] projects = new[] { project };
                    console.Start(projects, this.ForceFullAnalysis.Get(this.ActivityContext));
                }
                finally
                {
                    // Unsubscribe from events
                    console.OutputGenerated -= this.OnOutputGenerated;
                    console.ViolationEncountered -= this.OnViolationEncountered;
                }
            }

            // log the results to disk as a simple list if there have been failures AND LogFile is specified
            if (string.IsNullOrEmpty(this.LogFile.Get(this.ActivityContext)) == false && this.exitCode == false)
            {
                using (StreamWriter streamWriter = new StreamWriter(this.LogFile.Get(this.ActivityContext), false, Encoding.UTF8))
                {
                    foreach (string i in this.violations)
                    {
                        streamWriter.WriteLine(i);
                    }
                }
            }

            this.Succeeded.Set(this.ActivityContext, this.exitCode);
            this.ViolationCount.Set(this.ActivityContext, this.violations.Count);
        }
 void downloader_ProgressChanged(object sender, CodeProject.Downloader.DownloadEventArgs e)
 {
     // Sometimes we may get events fired even after we're done downloading.
     // Don't react to them.
     if (this.state != InstallState.Downloading)
         return;
     this.Invoke(new EventHandler(delegate
     {
         if (e.PercentDone <= 100)
         {
             this.progressBar.Value = e.PercentDone;
             UpdateProgressLabel(e);
         }
     }));
 }