private static string CheckForCompileErrors(string fileName)
        {
            var f = new FileInfo(fileName);

            if (!f.Exists)
            {
                return("Could not find the file.");
            }

            var codeFixer = new CodeFixer(new StreamReader(f.OpenRead()).ReadToEnd());

            var provider       = new CSharpCodeProvider();
            var compilerparams = new CompilerParameters
            {
                ReferencedAssemblies = { "wServer.exe", "db.dll" },
                GenerateExecutable   = false,
                GenerateInMemory     = true
            };
            var cleanSource = codeFixer.GetFixed();
            var results     = provider.CompileAssemblyFromSource(compilerparams, cleanSource);

            if (!results.Errors.HasErrors)
            {
                return("No Compile errors found.\nSuccess.");
            }
            var errors = new StringBuilder("Compiler Errors :\r\n");

            foreach (CompilerError error in results.Errors)
            {
                errors.AppendFormat("Line {0},{1}\t: {2}\n", error.Line, error.Column, error.ErrorText);
            }

            throw new Exception(errors.ToString());
        }
Example #2
0
        internal static async Task <CommandResult> FixAsync(
            ProjectOrSolution projectOrSolution,
            IEnumerable <string> analyzerAssemblies,
            CodeFixerOptions codeFixerOptions,
            IFormatProvider formatProvider      = null,
            CancellationToken cancellationToken = default)
        {
            if (projectOrSolution.IsProject)
            {
                Project project = projectOrSolution.AsProject();

                Solution solution = project.Solution;

                var codeFixer = new CodeFixer(solution, SyntaxFactsServiceFactory.Instance, analyzerAssemblies: analyzerAssemblies, formatProvider: formatProvider, options: codeFixerOptions);

                WriteLine($"Fix '{project.Name}'", ConsoleColor.Cyan, Verbosity.Minimal);

                await codeFixer.FixProjectAsync(project, cancellationToken);
            }
            else
            {
                Solution solution = projectOrSolution.AsSolution();

                var codeFixer = new CodeFixer(solution, SyntaxFactsServiceFactory.Instance, analyzerAssemblies: analyzerAssemblies, options: codeFixerOptions);

                await codeFixer.FixSolutionAsync(cancellationToken);
            }

            return(CommandResult.Success);
        }
Example #3
0
        internal static async Task <CommandResult> FixAsync(
            ProjectOrSolution projectOrSolution,
            IEnumerable <AnalyzerAssembly> analyzerAssemblies,
            CodeFixerOptions codeFixerOptions,
            IFormatProvider formatProvider      = null,
            CancellationToken cancellationToken = default)
        {
            if (projectOrSolution.IsProject)
            {
                Project project = projectOrSolution.AsProject();

                Solution solution = project.Solution;

                CodeFixer codeFixer = GetCodeFixer(solution);

                WriteLine($"Fix '{project.Name}'", ConsoleColor.Cyan, Verbosity.Minimal);

                Stopwatch stopwatch = Stopwatch.StartNew();

                await codeFixer.FixProjectAsync(project, cancellationToken);

                stopwatch.Stop();

                WriteLine($"Done fixing project '{project.FilePath}' in {stopwatch.Elapsed:mm\\:ss\\.ff}", Verbosity.Minimal);
            }
            else
            {
                Solution solution = projectOrSolution.AsSolution();

                CodeFixer codeFixer = GetCodeFixer(solution);

                await codeFixer.FixSolutionAsync(cancellationToken);
            }

            return(CommandResult.Success);

            CodeFixer GetCodeFixer(Solution solution)
            {
                return(new CodeFixer(
                           solution,
                           analyzerAssemblies: analyzerAssemblies,
                           formatProvider: formatProvider,
                           options: codeFixerOptions));
            }
        }
Example #4
0
        internal static async Task <CommandResult> FixAsync(
            ProjectOrSolution projectOrSolution,
            IEnumerable <string> analyzerAssemblies,
            CodeFixerOptions codeFixerOptions,
            IFormatProvider formatProvider      = null,
            CancellationToken cancellationToken = default)
        {
            if (projectOrSolution.IsProject)
            {
                Project project = projectOrSolution.AsProject();

                Solution solution = project.Solution;

                CodeFixer codeFixer = GetCodeFixer(solution);

                WriteLine($"Fix '{project.Name}'", ConsoleColor.Cyan, Verbosity.Minimal);

                await codeFixer.FixProjectAsync(project, cancellationToken);
            }
            else
            {
                Solution solution = projectOrSolution.AsSolution();

                CodeFixer codeFixer = GetCodeFixer(solution);

                await codeFixer.FixSolutionAsync(cancellationToken);
            }

            return(CommandResult.Success);

            CodeFixer GetCodeFixer(Solution solution)
            {
                return(new CodeFixer(
                           solution,
                           analyzerAssemblies: AnalyzerAssemblyLoader.LoadFiles(analyzerAssemblies),
                           formatProvider: formatProvider,
                           options: codeFixerOptions));
            }
        }
Example #5
0
        private static async Task <int> FixAsync(FixCommandLineOptions options)
        {
            var cts = new CancellationTokenSource();

            Console.CancelKeyPress += (sender, e) =>
            {
                e.Cancel = true;
                cts.Cancel();
            };

            CancellationToken cancellationToken = cts.Token;

            if (options.MSBuildPath != null)
            {
                MSBuildLocator.RegisterMSBuildPath(options.MSBuildPath);
            }
            else
            {
                VisualStudioInstance instance = MSBuildLocator.QueryVisualStudioInstances()
                                                .OrderBy(f => f.Version)
                                                .LastOrDefault();

                if (instance == null)
                {
                    WriteLine("MSBuild location not found. Use option '--msbuild-path' to specify MSBuild location", ConsoleColor.Red);
                    return(1);
                }

                WriteLine($"MSBuild location is '{instance.MSBuildPath}'");

                MSBuildLocator.RegisterInstance(instance);
            }

            var properties = new Dictionary <string, string>();

            foreach (string property in options.Properties)
            {
                int index = property.IndexOf("=");

                if (index == -1)
                {
                    WriteLine($"Unable to parse property '{property}'", ConsoleColor.Red);
                    return(1);
                }

                string key = property.Substring(0, index);

                properties[key] = property.Substring(index + 1);
            }

            if (properties.Count > 0)
            {
                WriteLine("Add MSBuild properties");

                int maxLength = properties.Max(f => f.Key.Length);

                foreach (KeyValuePair <string, string> kvp in properties)
                {
                    WriteLine($"  {kvp.Key.PadRight(maxLength)} = {kvp.Value}");
                }
            }

            // https://github.com/Microsoft/MSBuildLocator/issues/16
            if (!properties.ContainsKey("AlwaysCompileMarkupFilesInSeparateDomain"))
            {
                properties["AlwaysCompileMarkupFilesInSeparateDomain"] = bool.FalseString;
            }

            using (MSBuildWorkspace workspace = MSBuildWorkspace.Create(properties))
            {
                workspace.WorkspaceFailed += (o, e) => WriteLine(e.Diagnostic.Message, ConsoleColor.Yellow);

                string solutionPath = options.SolutionPath;

                WriteLine($"Load solution '{solutionPath}'", ConsoleColor.Cyan);

                try
                {
                    Solution solution;

                    try
                    {
                        solution = await workspace.OpenSolutionAsync(solutionPath, new ConsoleProgressReporter(), cancellationToken);
                    }
                    catch (Exception ex)
                    {
                        if (ex is FileNotFoundException ||
                            ex is InvalidOperationException)
                        {
                            WriteLine(ex.ToString(), ConsoleColor.Red);
                            return(1);
                        }
                        else
                        {
                            throw;
                        }
                    }

                    WriteLine($"Done loading solution '{solutionPath}'", ConsoleColor.Green);

                    var codeFixerOptions = new CodeFixerOptions(
                        ignoreCompilerErrors: options.IgnoreCompilerErrors,
                        ignoreAnalyzerReferences: options.IgnoreAnalyzerReferences,
                        ignoredDiagnosticIds: options.IgnoredDiagnostics,
                        ignoredCompilerDiagnosticIds: options.IgnoredCompilerDiagnostics,
                        ignoredProjectNames: options.IgnoredProjects,
                        batchSize: options.BatchSize);

                    var codeFixer = new CodeFixer(workspace, analyzerAssemblies: options.AnalyzerAssemblies, options: codeFixerOptions);

                    await codeFixer.FixAsync(cancellationToken);
                }
                catch (OperationCanceledException)
                {
                    WriteLine("Fixing was canceled.");
                }
            }

            return(0);
        }