当前位置: 首页>>代码示例>>C#>>正文


C# ProjectCollection.UnregisterAllLoggers方法代码示例

本文整理汇总了C#中Microsoft.Build.Evaluation.ProjectCollection.UnregisterAllLoggers方法的典型用法代码示例。如果您正苦于以下问题:C# ProjectCollection.UnregisterAllLoggers方法的具体用法?C# ProjectCollection.UnregisterAllLoggers怎么用?C# ProjectCollection.UnregisterAllLoggers使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Microsoft.Build.Evaluation.ProjectCollection的用法示例。


在下文中一共展示了ProjectCollection.UnregisterAllLoggers方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: BuildProject

        /// <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;
        }
开发者ID:shiningrise,项目名称:dbschemareader,代码行数:34,代码来源:CodeWriterBuildTest.cs

示例2: BuildProject

        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();
            }
        }
开发者ID:kaylynb,项目名称:Sunflower,代码行数:26,代码来源:Program.cs

示例3: Main

    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);
    }
开发者ID:sobercoder,项目名称:msbuild-api-hacks,代码行数:45,代码来源:Program.cs

示例4: ProcessBuild

        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)

            {
//.........这里部分代码省略.........
开发者ID:danni95,项目名称:Core,代码行数:101,代码来源:SimpleBuildEngine.cs

示例5: Build


//.........这里部分代码省略.........
        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;
    }
开发者ID:asvishnyakov,项目名称:CodeContracts,代码行数:101,代码来源:MSBuild.cs

示例6: ProjectCollectionChangedEvent

        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);
        }
开发者ID:cameron314,项目名称:msbuild,代码行数:85,代码来源:ProjectCollection_Tests.cs

示例7: BuildMyCode

        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

//.........这里部分代码省略.........
开发者ID:danni95,项目名称:Core,代码行数:101,代码来源:Builder.cs

示例8: ExecuteCompil

        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);
            }
        }
开发者ID:uqar-ludic,项目名称:ludic,代码行数:61,代码来源:Compil.cs


注:本文中的Microsoft.Build.Evaluation.ProjectCollection.UnregisterAllLoggers方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。