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


C# ProjectCollection.LoadProject方法代码示例

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


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

示例1: 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

示例2: 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

示例3: VsProject

 /// <summary>Initializes a new instance of the <see cref="VsProject" /> class.</summary>
 /// <param name="filePath">The file path.</param>
 /// <param name="projectCollection">The project collection.</param>
 /// <exception cref="InvalidProjectFileException">The project file could not be found.</exception>
 private VsProject(string filePath, ProjectCollection projectCollection)
     : base(filePath)
 {
     Project = projectCollection.LoadProject(filePath);
     Solutions = new ObservableCollection<VsSolution>();
     LoadNuSpecFile(filePath);
 }
开发者ID:sggeng,项目名称:MyToolkit,代码行数:11,代码来源:VsProject.cs

示例4: buildProject

        public static bool buildProject(this string projectFile, bool redirectToConsole = false)
        {
            try
            {
                var fileLogger = new FileLogger();
                var logFile = projectFile.directoryName().pathCombine(projectFile.fileName() + ".log");
                fileLogger.field("logFileName", logFile);
                if (logFile.fileExists())
                    logFile.file_Delete();

                var projectCollection = new ProjectCollection();
                var project = projectCollection.LoadProject(projectFile);
                if (project.isNull())
                {
                    "could not load project file: {0}".error(projectFile);
                    return false;
                }
                if (redirectToConsole)
                    projectCollection.RegisterLogger(new ConsoleLogger());

                projectCollection.RegisterLogger(fileLogger);
                var result = project.Build();
                fileLogger.Shutdown();
                return result;
            }
            catch(Exception ex)
            {
                ex.log();
                return false;
            }
        }
开发者ID:njmube,项目名称:FluentSharp,代码行数:31,代码来源:Package_Scripts_ExtensionMethods.cs

示例5: ImportFromExtensionsPathNotFound

        public void ImportFromExtensionsPathNotFound()
        {
            string extnDir1 = null;
            string mainProjectPath = null;

            try {
                extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), GetExtensionTargetsFileContent1());
                mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent());

                var projColln = new ProjectCollection();
                projColln.ResetToolsetsForTests(WriteConfigFileAndGetReader("MSBuildExtensionsPath", extnDir1, Path.Combine("tmp", "nonexistant")));
                var logger = new MockLogger();
                projColln.RegisterLogger(logger);

                Assert.Throws<InvalidProjectFileException>(() => projColln.LoadProject(mainProjectPath));

                logger.AssertLogContains("MSB4226");
            } finally {
                if (mainProjectPath != null)
                {
                    FileUtilities.DeleteNoThrow(mainProjectPath);
                }
                if (extnDir1 != null)
                {
                    FileUtilities.DeleteDirectoryNoThrow(extnDir1, recursive: true);
                }
            }
        }
开发者ID:cdmihai,项目名称:msbuild,代码行数:28,代码来源:ImportFromMSBuildExtensionsPath_Tests.cs

示例6: BuildProjects

        public bool BuildProjects(List<IProject> projects)
        {
            var engine = new ProjectCollection();

            return
                projects.Select(project => Path.Combine(project.ProjectPath, project.ProjectName)).Select(
                    fullProjectPath => engine.LoadProject(fullProjectPath).Build()).All(success => success);
        }
开发者ID:DuncanButler,项目名称:nTestRunner,代码行数:8,代码来源:MSBuild4Engine.cs

示例7: DiscoverTests

        /// <summary>
        /// ITestDiscover, Given a list of test sources this method pulls out the test cases
        /// </summary>
        /// <param name="sources">List of test sources passed from client (Client can be VS or command line)</param>
        /// <param name="discoveryContext">Context and runSettings for current run.  Discoverer pulls out the tests based on current context</param>
        /// <param name="logger">Used to relay messages to registered loggers</param>
        /// <param name="discoverySink">Callback used to notify client upon discovery of test cases</param>
        public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink) {
            ValidateArg.NotNull(sources, "sources");
            ValidateArg.NotNull(discoverySink, "discoverySink");
            ValidateArg.NotNull(logger, "logger");

            using (var buildEngine = new MSBuild.ProjectCollection()) {
                try {
                    // Load all the test containers passed in (.njsproj msbuild files)
                    foreach (string source in sources) {
                        buildEngine.LoadProject(source);
                    }

                    foreach (var proj in buildEngine.LoadedProjects) {

                        var projectHome = Path.GetFullPath(Path.Combine(proj.DirectoryPath, "."));

                        Dictionary<string, List<TestFileEntry>> testItems = new Dictionary<string,List<TestFileEntry>>(StringComparer.OrdinalIgnoreCase);
                        // Provide all files to the test analyzer
                        foreach (var item in proj.Items.Where(item => item.ItemType == "Compile" || item.ItemType == "TypeScriptCompile")) {

                            //Check to see if this is a TestCase
                            string value = item.GetMetadataValue("TestFramework");
                            if (!TestContainerDiscoverer.IsValidTestFramework(value)) {
                                continue;
                            }
                            string fileAbsolutePath = CommonUtils.GetAbsoluteFilePath(projectHome, item.EvaluatedInclude);
                            bool typeScriptTest = TypeScript.TypeScriptHelpers.IsTypeScriptFile(fileAbsolutePath);
                            if(typeScriptTest){
                                fileAbsolutePath = TypeScript.TypeScriptHelpers.GetTypeScriptBackedJavaScriptFile(proj,fileAbsolutePath);
                            } else if (!Path.GetExtension(fileAbsolutePath).Equals(".js", StringComparison.OrdinalIgnoreCase)) {
                                continue;
                            }
                            List<TestFileEntry> fileList;
                            if (!testItems.TryGetValue(value, out fileList)){
                                fileList = new List<TestFileEntry>();
                                testItems.Add(value, fileList);
                            }
                            fileList.Add(new TestFileEntry(fileAbsolutePath,typeScriptTest));
                        }

                        //Debug.Fail("Before Discover");
                        DiscoverTests(testItems, proj, discoverySink, logger);
                    }
                } catch (Exception ex) {
                    logger.SendMessage(TestMessageLevel.Error, ex.Message);
                    throw;
                } finally {
                    // Disposing buildEngine does not clear the document cache in
                    // VS 2013, so manually unload all projects before disposing.
                    buildEngine.UnloadAllProjects();
                }
            }
        }
开发者ID:munyirik,项目名称:nodejstools,代码行数:60,代码来源:TestDiscoverer.cs

示例8: Analyze

        public void Analyze(string projectFilePath)
        {
            if (string.IsNullOrEmpty(projectFilePath)) { throw new ArgumentNullException("projectFilePath"); }
            if (!File.Exists(projectFilePath)) {
                string message = string.Format("Project file not found at [{0}]", projectFilePath);
                throw new FileNotFoundException(message);
            }

            ProjectCollection pc = new ProjectCollection();
            Project project = pc.LoadProject(projectFilePath);
            this.Analyze(project);
        }
开发者ID:sayedihashimi,项目名称:msbuild-analyzer,代码行数:12,代码来源:TargetAnalyzer.cs

示例9: Clean

        public static void Clean(string file)
        {
            try
            {
                BeforeClean();

                LogService.WriteStatus("Arquivo: " + file);

                var engine = new ProjectCollection { DefaultToolsVersion = "4.0" };
                var csproj = engine.LoadProject(file);
                var quantidadeDuplicatas = 0;

                if (csproj.Items.Count == 0)
                    return;

                var currentReferences = new HashSet<string>();
                var itensToRemove = new List<ProjectItem>();

                foreach (var projectItem in csproj.Items.Where(projectItem => projectItem.ItemType == "Content" || projectItem.ItemType == "Compile"))
                {
                    if (!currentReferences.Contains(projectItem.Xml.Include))
                    {
                        currentReferences.Add(projectItem.Xml.Include);
                        continue;
                    }

                    itensToRemove.Add(projectItem);
                    quantidadeDuplicatas ++;
                }

                itensToRemove.ForEach(x => csproj.RemoveItem(x));

                if (!ResolveIfNoDuplicatedItens(quantidadeDuplicatas)) return;

                UpdateCsprojFile(file, csproj);
            }
            catch (UnauthorizedAccessException uaEx)
            {
                LogService.WriteError(uaEx.Message);
            }
            catch (PathTooLongException pathEx)
            {
                LogService.WriteError(pathEx.Message);
            }
            catch(Exception e)
            {
                LogService.WriteError(e.Message);
            }
            finally
            {
                AfterClean();
            }
        }
开发者ID:igorquintaes,项目名称:Csproj-Cleaner,代码行数:53,代码来源:ProjectService.cs

示例10: GetFile

        internal static MSBuildFile GetFile(FileInfo file)
        {
            using (ProjectCollection loadedProjects = new ProjectCollection())
            {
                Project currentProject = loadedProjects.GetLoadedProjects(file.FullName).FirstOrDefault();

                if (currentProject != null)
                {
                    loadedProjects.UnloadProject(currentProject);
                }

                loadedProjects.LoadProject(file.FullName);
                currentProject = loadedProjects.GetLoadedProjects(file.FullName).FirstOrDefault();

                MSBuildFile m = new MSBuildFile(currentProject);
                if (currentProject.Targets != null)
                {
                    SortedDictionary<string, ProjectTargetInstance> sortedTargets = new SortedDictionary<string, ProjectTargetInstance>(currentProject.Targets);
                    foreach (var t in sortedTargets)
                    {
                        ProjectTargetInstance pti = t.Value;
                        m.Targets.Add(new MSBuildTarget(pti, currentProject, m));
                    }
                }

                foreach (var us in currentProject.Xml.UsingTasks)
                {
                    m.Usings.Add(new MSBuildUsing(currentProject, us));
                }

                foreach (ResolvedImport import in currentProject.Imports)
                {
                    m.Imports.Add(new MSBuildImport(import));
                }

                foreach (var property in currentProject.Properties)
                {
                    m.Properties.Add(new MSBuildProperties(property));
                }

                if (currentProject.AllEvaluatedItems != null)
                {
                    foreach (var item in currentProject.AllEvaluatedItems)
                    {
                        m.Items.Add(new MSBuildItems(item.ItemType, item.UnevaluatedInclude, item.EvaluatedInclude, item.IsImported));
                    }
                }

                return m;
            }
        }
开发者ID:nagyist,项目名称:MSBuildExplorer,代码行数:51,代码来源:MSBuildHelper.cs

示例11: BuildProject

        /// <summary>
        /// Builds a project (.csproj, .vbproj, etc)
        /// </summary>
        /// <param name="projectFileName">Physical path to project file</param>
        /// <param name="configuration">Configuration to build in (usually "Debug" or "Release")</param>
        /// <param name="logFilePath">Physical path to write a build log file to</param>
        /// <param name="targets">The build target(s) to build. Usually "Build," "Rebuild," "Clean," etc</param>
        /// <returns>True if the project compiled successfully</returns>
        public static bool BuildProject(string projectFileName, string configuration, string logFilePath, string[] targets)
        {
            var projects = new ProjectCollection(ToolsetDefinitionLocations.Registry);

            var logger = new FileLogger();

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

            projects.RegisterLogger(logger);
            projects.DefaultToolsVersion = "4.0";
            projects.SetGlobalProperty("Configuration", configuration);

            return projects.LoadProject(projectFileName).Build(targets);
        }
开发者ID:BerserkerDotNet,项目名称:Synthesis,代码行数:22,代码来源:BuildUtility.cs

示例12: TeamCityMessageTaskProject_RunsBuildTarget_OutputsTeamCityMessageInLog

        public void TeamCityMessageTaskProject_RunsBuildTarget_OutputsTeamCityMessageInLog()
        {
            var props = new Dictionary<string, string>();
            props.Add("TeamCityTasksPath", Environment.CurrentDirectory + @"\");

            var logger = new LoggerMock();

            var projects = new ProjectCollection();
            var project = projects.LoadProject(@"IntegrationTests\MessageTask.targets", props, "4.0");
            var result = project.Build(logger);

            Assert.True(result);
            CollectionAssert.Contains(logger.LoggedMessages, "##teamcity[message text='Reporting a message to TeamCity build log.']");
        }
开发者ID:jozefizso,项目名称:msbuild-teamcity-interactions,代码行数:14,代码来源:TeamCityMessageTaskProjectTests.cs

示例13: TeamCitySetParameterTaskProject_RunsBuildTarget_OutputsSetParameterMessageInLog

        public void TeamCitySetParameterTaskProject_RunsBuildTarget_OutputsSetParameterMessageInLog()
        {
            var props = new Dictionary<string, string>();
            props.Add("TeamCityTasksPath", Environment.CurrentDirectory + @"\");

            var logger = new LoggerMock();

            var projects = new ProjectCollection();
            var project = projects.LoadProject(@"IntegrationTests\SetParameterTask.targets", props, "4.0");
            var result = project.Build(logger);

            Assert.True(result);
            CollectionAssert.Contains(logger.LoggedMessages, "##teamcity[setParameter name='BuildTag' value='MyApp_v1.0.0']");
        }
开发者ID:jozefizso,项目名称:msbuild-teamcity-interactions,代码行数:14,代码来源:SetParameterTaskProjectTests.cs

示例14: Main

        static void Main(string[] args)
        {
            if (args == null || args.Length < 1 || string.IsNullOrWhiteSpace(args[0]))
                Console.WriteLine("Specify csproj to rewrite");

            var collection = new ProjectCollection();
            var project = collection.LoadProject(args[0]);

            Cleanup(project, "Content");

            Cleanup(project, "None");
            
            project.Save();
        }
开发者ID:exira,项目名称:csproj-rewriter,代码行数:14,代码来源:Program.cs

示例15: Init

        public void Init()
        {
            var solution = new Solution(this.Solution.DirectoryName + Path.DirectorySeparatorChar + this.Solution.SolutionName);

            Trace.TraceInformation("Processing solution <"+solution.SolutionName+">");

            using (var pc = new ProjectCollection())
            {
                foreach (ProjectInSolution prj in solution.Projects.Where(p => !p.IsSolutionFolder))
                {
                    var project = new ProjectProcessor(pc.LoadProject(Path.Combine(solution.DirectoryName, prj.RelativePath)));
                    project.Init();
                }
            }
        }
开发者ID:tomgrv,项目名称:PA.InnoSetupProcessor,代码行数:15,代码来源:SolutionProcessor.cs


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