/// <summary>
        /// Builds the project - based on http://msdn.microsoft.com/en-us/library/microsoft.build.buildengine.engine.aspx.
        /// </summary>
        /// <param name="projectPath">The project (csproj) path</param>
        /// <returns>True if builds okay</returns>
        private static bool BuildProject(string projectPath)
        {
            var logPath = Path.Combine(Path.GetDirectoryName(projectPath), "build.log");

            //.Net 4 Microsoft.Build.Evaluation.Project and ProjectCollection
            var engine = new ProjectCollection();

            // Instantiate a new FileLogger to generate build log
            var logger = new Microsoft.Build.Logging.FileLogger();

            // Set the logfile parameter to indicate the log destination
            logger.Parameters = @"logfile=" + logPath;

            // Register the logger with the engine
            engine.RegisterLogger(logger);

            // Build a project file
            bool success = engine.LoadProject(projectPath).Build();
            //Unregister all loggers to close the log file
            engine.UnregisterAllLoggers();

            //if fails, put the log file into the assert statement
            string txt = "Should have built";
            if (!success && File.Exists(logPath))
                txt = File.ReadAllText(logPath);
            Console.WriteLine(txt);

            return success;
        }
Example #2
0
        private static void BuildProject(string projectFile)
        {
            Console.WriteLine("Building Project [" + projectFile + "]");
            var collection = new ProjectCollection {DefaultToolsVersion = "12.0"};
            collection.LoadProject(projectFile);

            collection.RegisterLoggers(new List<ILogger> { new ConsoleLogger(), new FileLogger {Parameters = projectFile + ".build.log"}});

            try
            {
                foreach (var project in collection.LoadedProjects.Where(x => x.IsBuildEnabled))
                {
                    project.SetProperty("Platform", "x64");
                    if (!project.Build())
                        throw new BuildException(projectFile);

                    project.SetProperty("Configuration", "Release");
                    if (!project.Build())
                        throw new BuildException(projectFile);
                }
            }
            finally
            {
                collection.UnregisterAllLoggers();
            }
        }
Example #3
0
    static void Main(string[] args)
    {
        string projectFileName = @"C:\Users\Sandipan\Documents\Visual Studio 2010\Projects\Base64\Base64\Base64.csproj";
        var projectCollection = new ProjectCollection();
        projectCollection.DefaultToolsVersion = "4.0";
        // Console.WriteLine("Available Toolsets: " + string.Join(", ", projectCollection.Toolsets.Select(item => item.ToolsVersion)));
        // Console.WriteLine("Toolset currently being used: " + projectCollection.DefaultToolsVersion);
        Project project = projectCollection.LoadProject(projectFileName);

        // ConsoleLogger logger = new ConsoleLogger();
        MsBuildLogger logger = new MsBuildLogger();
        // logger.Verbosity = LoggerVerbosity.Detailed;
        List<ILogger> loggers = new List<ILogger>();
        loggers.Add(logger);
        projectCollection.RegisterLoggers(loggers);

        // there are a lot of properties here, these map to the MsBuild CLI properties
        //Dictionary<string, string> globalProperties = new Dictionary<string, string>();
        //globalProperties.Add("Configuration", "Debug");
        //globalProperties.Add("Platform", "x86");
        //globalProperties.Add("OutputPath", @"D:\Output");

        //BuildParameters buildParams = new BuildParameters(projectCollection);
        //MsBuildLogger logger = new MsBuildLogger();
        //// logger.Verbosity = LoggerVerbosity.Detailed;
        //List<ILogger> loggers = new List<ILogger>() { logger };
        //buildParams.Loggers = loggers;
        //BuildRequestData buildRequest = new BuildRequestData(projectFileName, globalProperties, "4.0", new string[] { "Build" }, null);
        //BuildResult buildResult = BuildManager.DefaultBuildManager.Build(buildParams, buildRequest); // this is where the magic happens - in process MSBuild

        //buildResult.ResultsByTarget.ToList().ForEach(item => new Action(delegate() {
        //    Console.WriteLine(item.Key + ", " + item.Value.ResultCode.ToString());
        //    Console.WriteLine(string.Join(", ", item.Value.Items.ToList().Select(target => target.ItemSpec)));
        //}).Invoke());
        try {
            project.Build();
        } finally {
            projectCollection.UnregisterAllLoggers();
            Console.WriteLine("TARGETS\n" + string.Join("\n", logger.Targets.Select(item => string.Format("[{0}, {1}]", item.Name, item.Succeeded ? "Succeeded" : "Failed"))));
            Console.WriteLine("ERRORS\n" + string.Join("\n", logger.Errors));
            Console.WriteLine("WARNINGS\n" + string.Join("\n", logger.Warnings));
        }

        Console.ReadKey(true);
    }
Example #4
0
        private void ProcessBuild(IBuildable build)
        {
            //http://www.odewit.net/ArticleContent.aspx?id=MsBuildApi4&format=html

            var assemblyExecutionPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            var logFilePath = assemblyExecutionPath.Remove(assemblyExecutionPath.LastIndexOf("\\") + 1) + "build.log";
            var sln = Path.GetFullPath(build.SolutionDirectory.FullName);
            var OutputHeaderRow = new List<string>();
            var OutputItemRow = new List<string>();

            try
            {
                var logger = new FileLogger();
                var pc = new ProjectCollection();
                var GlobalProperty = new Dictionary<string, string>();

                logger.Parameters = @"logfile=" + logFilePath;
                GlobalProperty.Add("Configuration", "Release");
                GlobalProperty.Add("Platform", "Any CPU");

                var buildRequest = new BuildRequestData(sln, GlobalProperty, null, new string[] { "Build" }, null);
                var bp = new BuildParameters(pc);

                bp.Loggers = new List<Microsoft.Build.Framework.ILogger> { logger }.AsEnumerable();

                //build solution

                var buildResult = BuildManager.DefaultBuildManager.Build(bp, buildRequest);

                pc.UnregisterAllLoggers();

                //read lines from log file having project build output details

                string[] solutionBuildOutputs = File.ReadAllLines(logFilePath);

                //write the result of solution build to html report

                OutputHeaderRow.Add("Artifact;Build Result");

                //split the contents of logger file to retrieve project build details

                string[] splitter = { "__________________________________________________" };

                string loggerOutput = File.ReadAllText(logFilePath);

                string[] projectResults = loggerOutput.Split(splitter, StringSplitOptions.None);

                foreach (string projectBuildDetails in projectResults)

                {

                    if (projectBuildDetails.Contains("(default targets):"))

                    {

                        if (projectBuildDetails.Contains("Done building project \""))

                        {

                            //write the result of failed projects build to html report

                            string[] lines = projectBuildDetails.Split("\n".ToCharArray());

                            string buildFailedProjectName = lines.Where(x => x.Contains("Done building project \"")).FirstOrDefault();

                            buildFailedProjectName = buildFailedProjectName.Replace("Done building project ", string.Empty).Trim();

                            buildFailedProjectName = buildFailedProjectName.Replace("\"", string.Empty);

                            buildFailedProjectName = buildFailedProjectName.Replace(" -- FAILED.", string.Empty);

                            OutputItemRow.Add(buildFailedProjectName + ";FAILED");

                        }

                        else

                        {

                            //write the result of successfully built projects to html report

                            string[] lines = projectBuildDetails.Split("\n".ToCharArray());

                            string buildSuccededProjectName = lines.Where(x => x.Contains(" (default targets):")).FirstOrDefault().Replace("\" (default targets):", "");

                            string finalProjectName = buildSuccededProjectName.Substring(buildSuccededProjectName.LastIndexOf("\\") + 1);

                            OutputItemRow.Add(finalProjectName + ";SUCCEEDED");

                        }

                    }

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }

            finally

            {

                //delete log file

                File.Delete(logFilePath);

            }
        }
Example #5
0
    public bool Build(IEnumerable<string> ProjectsPath, string versionName, string outputPrefix)
    {
      var ret = false;

      try
      {
        // Properties passed to MSBUILD (the ones of the .target file)
        var globalProperties = new Dictionary<string, string>();

        // INFERENCE off
        globalProperties.Add("CodeContractsInferRequires", "false");
        globalProperties.Add("CodeContractsInferEnsures", "false");
        globalProperties.Add("CodeContractsInferObjectInvariants", "false");
        // SUGGESTIONS off
        globalProperties.Add("CodeContractsSuggestAssumptions", "false");
        globalProperties.Add("CodeContractsSuggestRequires", "false");
        globalProperties.Add("CodeContractsSuggestEnsures", "false");
        globalProperties.Add("CodeContractsSuggestObjectInvariants", "false");

        // WARNINGS
        globalProperties.Add("CodeContractsRunCodeAnalysis", "true");
        globalProperties.Add("CodeContractsAnalysisWarningLevel", "3");
        globalProperties.Add("CodeContractsNonNullObligations", "true");
        globalProperties.Add("CodeContractsBoundsObligations", "true");
        globalProperties.Add("CodeContractsArithmeticObligations", "true");
        globalProperties.Add("CodeContractsEnumObligations", "true");

        globalProperties.Add("CodeContractsRedundantAssumptions", "false");
        globalProperties.Add("CodeContractsMissingPublicRequiresAsWarnings", "false");

        globalProperties.Add("CodeContractsRunInBackground", "false"); // get output
        globalProperties.Add("CodeContractsEnableRuntimeChecking", "false"); // speedup
        globalProperties.Add("CodeContractsReferenceAssembly", "Build"); // make sure we have it
        //globalProperties.Add("CodeContractsUseBaseLine", "true");
        //globalProperties.Add("CodeContractsBaseLineFile", "base.xml");
        //globalProperties.Add("CodeContractsExtraAnalysisOptions", "-repro");

        globalProperties.Add("CodeContractsCacheAnalysisResults", "true");
        globalProperties.Add("CodeContractsSQLServerOption", "cloudotserver");

        var extraOptions = this.ExtraOptions == null ? "" : this.ExtraOptions;
        extraOptions += " -sortwarns:false -stats:perMethod -show:progress -trace:cache";

        if (this.SaveSemanticBaseline)
        {
          extraOptions += String.Format(" -saveSemanticBaseline:{0}", versionName);
        }
        else
        {
          extraOptions += String.Format(" -useSemanticBaseline:{0}", versionName);
        }
        globalProperties.Add("CodeContractsExtraAnalysisOptions", extraOptions);
        //globalProperties.Add("CodeContractsCacheVersion", VersionId.ToString());
        //globalProperties.Add("CodeContractsCacheMaxSize", Int32.MaxValue.ToString());

        globalProperties.Add("DeployExtension", "false"); // avoid vsix deployment

        // It does not work: The log file is empty
        var logFileName = "buildlog." + versionName + "." + outputPrefix + (this.SaveSemanticBaseline ? ".save.txt" : ".use.txt");
        var fileLogger = new FileLogger();
        fileLogger.Parameters = "logfile=" + Path.Combine(this.SourceDirectory, logFileName);
        fileLogger.Verbosity = Microsoft.Build.Framework.LoggerVerbosity.Normal;
        var consoleLogger = new ConsoleLogger();
        consoleLogger.Verbosity = Microsoft.Build.Framework.LoggerVerbosity.Normal;
        var overallLoggers = new[] { fileLogger, consoleLogger };
        // with this version, loggers don't work (log files are created but empty), why?

        var loggers = new FileLogger[0];

        using (var projectCollection = new ProjectCollection(globalProperties, loggers, ToolsetDefinitionLocations.Registry))
        {
          // The only way to communicate to msbuild is to create an xml file, and pass it to msbuild
          XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
          var xmlTarget = new XElement(ns + "Target", new XAttribute("Name", "Build"));

          var properties = "";

          foreach (var projectPath in ProjectsPath)
          {
            Contract.Assert(projectPath != null);
            xmlTarget.Add(new XElement(ns + "MSBuild",
              new XAttribute("Projects", Path.Combine(this.SourceDirectory, projectPath)),
              new XAttribute("Targets", "Rebuild"),  // ensures the project will be rebuilt from scratch (is it needed?)
              new XAttribute("UseResultsCache", "false"),
              new XAttribute("UnloadProjectsOnCompletion", "true"),
              new XAttribute("ContinueOnError", "true"),
              new XAttribute("StopOnFirstFailure", "false"),
              new XAttribute("Properties", properties)));
          }

          // create the project
          var xmlProject = new XElement(ns + "Project", xmlTarget);

          // now read the project
          var project = projectCollection.LoadProject(xmlProject.CreateReader());

          // create an instance of the project
          var projectInstance = project.CreateProjectInstance();

          // create the parameters for the build
          var buildParameters = new BuildParameters(projectCollection);
          buildParameters.EnableNodeReuse = false;
          buildParameters.ResetCaches = true;
          buildParameters.Loggers = overallLoggers;
          buildParameters.MaxNodeCount = Environment.ProcessorCount;
          // Ask a build on this project
          var buildRequestData = new BuildRequestData(projectInstance, new string[] { "Build" });

          // we need to create a new BuildManager each time, otherwise it wrongly caches project files
          var buildManager = new BuildManager();

          // now do the build!
          var buildResult = buildManager.Build(buildParameters, buildRequestData);
          ret = buildResult.OverallResult == BuildResultCode.Success;

#if WITH_LOG
          logger.Shutdown();
#endif

          // now cleanup - it seems it does not improve
          projectCollection.UnregisterAllLoggers();
          projectCollection.UnloadAllProjects();
        }

        #region Version using the default BuildManager (disabled)
#if false
        // First version. It does not work, because msbuild keeps a cache of the projects, and so it compiles the new files with the old project 
        // The Log works
        Microsoft.Build.Execution.BuildManager.DefaultBuildManager.ResetCaches(); // ensures MSBuild doesn't use cached version of project files (it handles very badly versions changing!), not sure it works

        XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
        var xmlTarget = new XElement(ns + "Target", new XAttribute("Name", "Build"));

        var properties = "";
        properties += ";CodeContractsCacheDirectory=" + OutputDirectory;
        properties += ";CodeContractsCacheAnalysisResults=true";
        properties += ";CodeContractsCacheVersion=" + VersionId;

        foreach (var projectPath in ProjectsPath)
        {
          Contract.Assume(projectPath != null);
          xmlTarget.Add(new XElement(ns + "MSBuild",
            new XAttribute("Projects", Path.Combine(this.WorkingDirectory, projectPath)),
            new XAttribute("Targets", "Rebuild"),  // ensures the project will be rebuilt from scratch (is it needed?)
            new XAttribute("UseResultsCache", "false"),
            new XAttribute("UnloadProjectsOnCompletion", "true"),
            new XAttribute("ContinueOnError", "true"),
            new XAttribute("StopOnFirstFailure", "false"),
            new XAttribute("Properties", properties)));
        }

        var xmlProject = new XElement(ns + "Project", xmlTarget);

        var project = new Project(xmlProject.CreateReader());

        var logFileName = "build." + VersionId + ".log";
        var logger = new Microsoft.Build.Logging.FileLogger();
        logger.Parameters = "logfile=" + Path.Combine(OutputDirectory, logFileName);
        ret = project.Build(logger);
#endif
        #endregion
      }
      catch
      {
        ret = false;
      }

      return ret;
    }
Example #6
0
    public bool Build(IEnumerable<string> ProjectsPath, long VersionId, string OutputDirectory)
    {
      var ret = false;

      try
      {
        // Properties passed to MSBUID (the ones of the .target file)
        var globalProperties = new Dictionary<string, string>();
        globalProperties.Add("CodeContractsCacheDirectory", OutputDirectory);
        globalProperties.Add("CodeContractsCacheAnalysisResults", "true");
        globalProperties.Add("CodeContractsCacheVersion", VersionId.ToString());
        globalProperties.Add("CodeContractsCacheMaxSize", Int32.MaxValue.ToString());
        

#if WITH_LOG
        // It does not work: The log file is empty
        var logFileName = "build." + VersionId + ".log";
        var logger = new FileLogger();
        logger.Parameters = "logfile=" + Path.Combine(OutputDirectory, logFileName);
        logger.Verbosity = Microsoft.Build.Framework.LoggerVerbosity.Diagnostic;
        var loggers = new FileLogger[]{ logger };
        // with this version, loggers don't work (log files are created but empty), why?
#else
        var loggers = new FileLogger[0];
#endif

        using (var projectCollection = new ProjectCollection(globalProperties, loggers, ToolsetDefinitionLocations.Registry))
        {
          // The only way to communicate to msbuild is to create an xml file, and pass it to msbuild
          XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
          var xmlTarget = new XElement(ns + "Target", new XAttribute("Name", "Build"));

          var properties = "";

          foreach (var projectPath in ProjectsPath)
          {
            Contract.Assert(projectPath != null);
            xmlTarget.Add(new XElement(ns + "MSBuild",
              new XAttribute("Projects", Path.Combine(this.SourceDirectory, projectPath)),
              new XAttribute("Targets", "Rebuild"),  // ensures the project will be rebuilt from scratch (is it needed?)
              new XAttribute("UseResultsCache", "false"),
              new XAttribute("UnloadProjectsOnCompletion", "true"),
              new XAttribute("ContinueOnError", "true"),
              new XAttribute("StopOnFirstFailure", "false"),
              new XAttribute("Properties", properties)));
          }

          // create the project
          var xmlProject = new XElement(ns + "Project", xmlTarget);

          // now read the project
          var project = projectCollection.LoadProject(xmlProject.CreateReader());

          // create an instance of the project
          var projectInstance = project.CreateProjectInstance();

          // create the parameters for the build
          var buildParameters = new BuildParameters(projectCollection);
          buildParameters.EnableNodeReuse = false;
          buildParameters.ResetCaches = true;

          // Ask a build on this project
          var buildRequestData = new BuildRequestData(projectInstance, new string[] { "Build" });

          // we need to create a new BuildManager each time, otherwise it wrongly caches project files
          var buildManager = new BuildManager();

          // now do the build!
          var buildResult = buildManager.Build(buildParameters, buildRequestData);

          ret = buildResult.OverallResult == BuildResultCode.Success;

#if WITH_LOG
          logger.Shutdown();
#endif

          // now cleanup - it seems it does not improve
          projectCollection.UnregisterAllLoggers();
          projectCollection.UnloadAllProjects();
        }

        #region Version using the default BuildManager (disabled)
#if false
        // First version. It does not work, because msbuild keeps a cache of the projects, and so it compiles the new files with the old project 
        // The Log works
        Microsoft.Build.Execution.BuildManager.DefaultBuildManager.ResetCaches(); // ensures MSBuild doesn't use cached version of project files (it handles very badly versions changing!), not sure it works

        XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
        var xmlTarget = new XElement(ns + "Target", new XAttribute("Name", "Build"));

        var properties = "";
        properties += ";CodeContractsCacheDirectory=" + OutputDirectory;
        properties += ";CodeContractsCacheAnalysisResults=true";
        properties += ";CodeContractsCacheVersion=" + VersionId;

        foreach (var projectPath in ProjectsPath)
        {
          Contract.Assume(projectPath != null);
          xmlTarget.Add(new XElement(ns + "MSBuild",
            new XAttribute("Projects", Path.Combine(this.WorkingDirectory, projectPath)),
            new XAttribute("Targets", "Rebuild"),  // ensures the project will be rebuilt from scratch (is it needed?)
            new XAttribute("UseResultsCache", "false"),
            new XAttribute("UnloadProjectsOnCompletion", "true"),
            new XAttribute("ContinueOnError", "true"),
            new XAttribute("StopOnFirstFailure", "false"),
            new XAttribute("Properties", properties)));
        }

        var xmlProject = new XElement(ns + "Project", xmlTarget);

        var project = new Project(xmlProject.CreateReader());

        var logFileName = "build." + VersionId + ".log";
        var logger = new Microsoft.Build.Logging.FileLogger();
        logger.Parameters = "logfile=" + Path.Combine(OutputDirectory, logFileName);
        ret = project.Build(logger);
        #endif
        #endregion
      }
      catch
      {
        ret = false;
      }

      return ret;
    }
        public void ProjectCollectionChangedEvent()
        {
            ProjectCollection collection = new ProjectCollection();
            bool dirtyRaised = false;
            ProjectCollectionChangedState expectedChange = ProjectCollectionChangedState.Loggers;
            collection.ProjectCollectionChanged +=
                (sender, e) =>
                {
                    Assert.Same(collection, sender);
                    Assert.Equal(expectedChange, e.Changed);
                    dirtyRaised = true;
                };
            Assert.False(dirtyRaised);

            expectedChange = ProjectCollectionChangedState.DisableMarkDirty;
            dirtyRaised = false;
            collection.DisableMarkDirty = true; // LEAVE THIS TRUE for rest of the test, to verify it doesn't suppress these events
            Assert.True(dirtyRaised);

            expectedChange = ProjectCollectionChangedState.IsBuildEnabled;
            dirtyRaised = false;
            collection.IsBuildEnabled = !collection.IsBuildEnabled;
            Assert.True(dirtyRaised);

            expectedChange = ProjectCollectionChangedState.OnlyLogCriticalEvents;
            dirtyRaised = false;
            collection.OnlyLogCriticalEvents = !collection.OnlyLogCriticalEvents;
            Assert.True(dirtyRaised);

            expectedChange = ProjectCollectionChangedState.SkipEvaluation;
            dirtyRaised = false;
            collection.SkipEvaluation = !collection.SkipEvaluation;
            Assert.True(dirtyRaised);

            expectedChange = ProjectCollectionChangedState.GlobalProperties;
            dirtyRaised = false;
            collection.SetGlobalProperty("a", "b");
            Assert.True(dirtyRaised);

            expectedChange = ProjectCollectionChangedState.GlobalProperties;
            dirtyRaised = false;
            collection.RemoveGlobalProperty("a");
            Assert.True(dirtyRaised);

            // Verify HostServices changes raise the event.
            expectedChange = ProjectCollectionChangedState.HostServices;
            dirtyRaised = false;
            collection.HostServices = new Execution.HostServices();
            Assert.True(dirtyRaised);

            expectedChange = ProjectCollectionChangedState.Loggers;
            dirtyRaised = false;
            collection.RegisterLogger(new MockLogger());
            Assert.True(dirtyRaised);

            expectedChange = ProjectCollectionChangedState.Loggers;
            dirtyRaised = false;
            collection.RegisterLoggers(new Microsoft.Build.Framework.ILogger[] { new MockLogger(), new MockLogger() });
            Assert.True(dirtyRaised);

            expectedChange = ProjectCollectionChangedState.Loggers;
            dirtyRaised = false;
            collection.UnregisterAllLoggers();
            Assert.True(dirtyRaised);

            expectedChange = ProjectCollectionChangedState.Toolsets;
            dirtyRaised = false;
            collection.AddToolset(new Toolset("testTools", Path.GetTempPath(), collection, Path.GetTempPath()));
            Assert.True(dirtyRaised);

            expectedChange = ProjectCollectionChangedState.DefaultToolsVersion;
            dirtyRaised = false;
            collection.DefaultToolsVersion = "testTools";
            Assert.True(dirtyRaised);

            expectedChange = ProjectCollectionChangedState.Toolsets;
            dirtyRaised = false;
            collection.RemoveToolset("testTools");
            Assert.True(dirtyRaised);

            expectedChange = ProjectCollectionChangedState.Toolsets;
            dirtyRaised = false;
            collection.RemoveAllToolsets();
            Assert.True(dirtyRaised);
        }
Example #8
0
        public void BuildMyCode()
        {
            //retrieve assembly execution path

            string assemblyExecutionPath = System.Reflection.Assembly.GetExecutingAssembly().Location;

            string logFilePath = assemblyExecutionPath.Remove(assemblyExecutionPath.LastIndexOf("\\") + 1) + "build.log";

            var sln = @"C:\Users\Danni\Desktop\FarExo Prototypes\BuildTester\FarExoCD.sln";

            var OutputHeaderRow = new List<string>();

            var OutputItemRow = new List<string>();

            try

            {

                // Instantiate a new FileLogger to generate build log

                FileLogger logger = new FileLogger();

                // Set the logfile parameter to indicate the log destination

                logger.Parameters = @"logfile=" + logFilePath;

                ProjectCollection pc = new ProjectCollection();

                Dictionary<string, string> GlobalProperty = new Dictionary<string, string>();

                GlobalProperty.Add("Configuration", "Release");

                GlobalProperty.Add("Platform", "Any CPU");

                BuildRequestData buildRequest = new BuildRequestData(sln, GlobalProperty, null, new string[] { "Build" }, null);

                //register file logger using BuildParameters

                BuildParameters bp = new BuildParameters(pc);

                bp.Loggers = new List<Microsoft.Build.Framework.ILogger> { logger }.AsEnumerable();

                //build solution

                BuildResult buildResult = BuildManager.DefaultBuildManager.Build(bp, buildRequest);

                //Unregister all loggers to close the log file

                pc.UnregisterAllLoggers();

                //read lines from log file having project build output details

                string[] solutionBuildOutputs = File.ReadAllLines(logFilePath);

                //write the result of solution build to html report

                OutputHeaderRow.Add("Artifact;Build Result");

                //split the contents of logger file to retrieve project build details

                string[] splitter = { "__________________________________________________" };

                string loggerOutput = File.ReadAllText(logFilePath);

                string[] projectResults = loggerOutput.Split(splitter, StringSplitOptions.None);

                foreach (string projectBuildDetails in projectResults)

                {

                    if (projectBuildDetails.Contains("(default targets):"))

                    {

                        if (projectBuildDetails.Contains("Done building project \""))

                        {

                            //write the result of failed projects build to html report

                            string[] lines = projectBuildDetails.Split("\n".ToCharArray());

                            string buildFailedProjectName = lines.Where(x => x.Contains("Done building project \"")).FirstOrDefault();

                            buildFailedProjectName = buildFailedProjectName.Replace("Done building project ", string.Empty).Trim();

                            buildFailedProjectName = buildFailedProjectName.Replace("\"", string.Empty);

                            buildFailedProjectName = buildFailedProjectName.Replace(" -- FAILED.", string.Empty);

                            OutputItemRow.Add(buildFailedProjectName + ";FAILED");

                        }

                        else

                        {

                            //write the result of successfully built projects to html report

                            string[] lines = projectBuildDetails.Split("\n".ToCharArray());

                            string buildSuccededProjectName = lines.Where(x => x.Contains(" (default targets):")).FirstOrDefault().Replace("\" (default targets):", "");

                            string finalProjectName = buildSuccededProjectName.Substring(buildSuccededProjectName.LastIndexOf("\\") + 1);

                            OutputItemRow.Add(finalProjectName + ";SUCCEEDED");

                        }

                    }

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }

            finally

            {

                //delete log file

                File.Delete(logFilePath);

            }
        }
Example #9
0
        public static void ExecuteCompil(string pathSln, string pathLog)
        {
            string logFilePath = pathLog;
            List<string> OutputHeaderRow = new List<string>();
            List<string> OutputItemRow = new List<string>();
            string artifactPath = pathSln;

            try
            {
                //Create a new FileLogger with the path given as parameter
                FileLogger logger = new FileLogger();
                logger.Parameters = @"logfile=" + logFilePath;

                //Generate the ProjectCollection with the sln's path given as parameter
                ProjectCollection pc = new ProjectCollection();
                Dictionary<string, string> GlobalProperty = new Dictionary<string, string>() { { "Configuration", "Debug" }, { "Platform", "Any CPU" } };
                BuildRequestData buildRequest = new BuildRequestData(artifactPath, GlobalProperty, null, new string[] { "Build" }, null);

                //Set the ProjectCollection as BuildParameter
                BuildParameters bp = new BuildParameters(pc);
                bp.Loggers = new List<Microsoft.Build.Framework.ILogger> { logger }.AsEnumerable();

                //Build the solution
                BuildResult buildResult = BuildManager.DefaultBuildManager.Build(bp, buildRequest);

                pc.UnregisterAllLoggers();

                //Create output for the build with the FileLogger informations
                string[] solutionBuildOutputs = File.ReadAllLines(logFilePath);
                OutputHeaderRow.Add("Artifact;Build Result");
                string[] splitter = { "__________________________________________________" };
                string loggerOutput = File.ReadAllText(logFilePath);
                string[] projectResults = loggerOutput.Split(splitter, StringSplitOptions.None);
                foreach (string projectBuildDetails in projectResults)
                    if (projectBuildDetails.Contains("(default targets):"))
                        if (projectBuildDetails.Contains("Done building project \""))
                        {
                            string[] lines = projectBuildDetails.Split("\n".ToCharArray());
                            string buildFailedProjectName = lines.Where(x => x.Contains("Done building project \"")).FirstOrDefault();
                            buildFailedProjectName = buildFailedProjectName.Replace("Done building project ", string.Empty).Trim();
                            buildFailedProjectName = buildFailedProjectName.Replace("\"", string.Empty);
                            buildFailedProjectName = buildFailedProjectName.Replace(" -- FAILED.", string.Empty);
                            OutputItemRow.Add(buildFailedProjectName + ";FAILED");
                        }
                        else
                        {
                            string[] lines = projectBuildDetails.Split("\n".ToCharArray());
                            string buildSuccededProjectName = lines.Where(x => x.Contains(" (default targets):")).FirstOrDefault().Replace("\" (default targets):", "");
                            string finalProjectName = buildSuccededProjectName.Substring(buildSuccededProjectName.LastIndexOf("\\") + 1);
                            OutputItemRow.Add(finalProjectName + ";SUCCEEDED");
                        }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                //File.Delete(logFilePath);
            }
        }