示例#1
0
		public void ItemsAndProperties ()
		{
            string project_xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
  <ItemGroup>
    <X Condition='false' Include='bar.txt' />
    <X Include='foo.txt'>
      <M>m</M>
      <N>=</N>
    </X>
  </ItemGroup>
  <PropertyGroup>
    <P Condition='false'>void</P>
    <P Condition='true'>valid</P>
  </PropertyGroup>
</Project>";
            var xml = XmlReader.Create (new StringReader(project_xml));
            var root = ProjectRootElement.Create (xml);
            var proj = new ProjectInstance (root);
            var item = proj.Items.First ();
			Assert.AreEqual ("foo.txt", item.EvaluatedInclude, "#1");
			var prop = proj.Properties.First (p => p.Name=="P");
			Assert.AreEqual ("valid", prop.EvaluatedValue, "#2");
			Assert.IsNotNull (proj.GetProperty ("MSBuildProjectDirectory"), "#3");
			Assert.AreEqual ("4.0", proj.ToolsVersion, "#4");
		}
示例#2
0
文件: MSBuild.cs 项目: NN---/nuproj
        /// <summary>
        /// Builds a project.
        /// </summary>
        /// <param name="projectInstance">The project to build.</param>
        /// <param name="targetsToBuild">The targets to build. If not specified, the project's default target will be invoked.</param>
        /// <returns>A task whose result is the result of the build.</returns>
        public static async Task<BuildResultAndLogs> ExecuteAsync(ProjectInstance projectInstance, params string[] targetsToBuild)
        {
            targetsToBuild = (targetsToBuild == null || targetsToBuild.Length == 0) ? projectInstance.DefaultTargets.ToArray() : targetsToBuild;

            var logger = new EventLogger();
            var logLines = new List<string>();
            var parameters = new BuildParameters
            {
                Loggers = new List<ILogger>
                {
                    new ConsoleLogger(LoggerVerbosity.Detailed, logLines.Add, null, null),
                    logger,
                },
            };

            BuildResult result;
            using (var buildManager = new BuildManager())
            {
                buildManager.BeginBuild(parameters);
                try
                {
                    var brdFlags = BuildRequestDataFlags.ProvideProjectStateAfterBuild;
                    var requestData = new BuildRequestData(projectInstance, targetsToBuild, null, brdFlags);
                    var submission = buildManager.PendBuildRequest(requestData);
                    result = await submission.ExecuteAsync();
                }
                finally
                {
                    buildManager.EndBuild();
                }
            }

            return new BuildResultAndLogs(result, logger.LogEvents, logLines);
        }
示例#3
0
        public void TestResolveEnvironment() {
            var proj1 = new ProjectInstance(TestData.GetPath(@"TestData\Targets\Environments1.pyproj"));
            Assert.IsTrue(proj1.Build("TestResolveEnvironment", new ILogger[] { new ConsoleLogger(LoggerVerbosity.Detailed) }));

            var proj2 = new ProjectInstance(TestData.GetPath(@"TestData\Targets\Environments2.pyproj"));
            Assert.IsTrue(proj2.Build("TestResolveEnvironment", new ILogger[] { new ConsoleLogger(LoggerVerbosity.Detailed) }));
        }
示例#4
0
		public void OutputPropertyExists ()
		{
			string project_xml = @"
<Project DefaultTargets='Build' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
	<PropertyGroup>
		<C>False</C>
	</PropertyGroup>
	<Target Name='Build' DependsOnTargets='ResolveReferences' />
	<Target Name='Build2' DependsOnTargets='Bar' />
	<Target Name='ResolveReferences' DependsOnTargets='Foo;Bar' />
	<Target Name='Foo'>
		<CreateProperty Value='True'>
			<Output TaskParameter='Value' PropertyName='C' />
		</CreateProperty>
	</Target>
	<Target Name='Bar' Condition='!($(C))' DependsOnTargets='ResolveReferences'>
	</Target>
</Project>";
			var xml = XmlReader.Create (new StringReader(project_xml));
			var root = ProjectRootElement.Create (xml);
			var proj = new ProjectInstance (root);
			Assert.AreEqual (5, proj.Targets.Count, "#1");
			var foo = proj.Targets ["Foo"];
			Assert.IsNotNull (foo, "#2");
			Assert.AreEqual (1, foo.Tasks.Count, "#3");
			var cp = foo.Tasks.First ();
			Assert.AreEqual (1, cp.Outputs.Count, "#4");
			var po = cp.Outputs.First () as ProjectTaskOutputPropertyInstance;
			Assert.IsNotNull (po, "#5");
			Assert.AreEqual ("C", po.PropertyName, "#5");
			proj.Build ("Build", null);
			Assert.AreEqual (string.Empty, foo.Outputs, "#6");
			Assert.AreEqual ("True", proj.GetPropertyValue ("C"), "#7");
		}
    internal static async Task<BuildResult> BuildAsync(this BuildManager buildManager, ITestOutputHelper logger, ProjectCollection projectCollection, ProjectRootElement project, string target, IDictionary<string, string> globalProperties = null, LoggerVerbosity logVerbosity = LoggerVerbosity.Detailed, ILogger[] additionalLoggers = null)
    {
        Requires.NotNull(buildManager, nameof(buildManager));
        Requires.NotNull(projectCollection, nameof(projectCollection));
        Requires.NotNull(project, nameof(project));

        globalProperties = globalProperties ?? new Dictionary<string, string>();
        var projectInstance = new ProjectInstance(project, globalProperties, null, projectCollection);
        var brd = new BuildRequestData(projectInstance, new[] { target }, null, BuildRequestDataFlags.ProvideProjectStateAfterBuild);

        var parameters = new BuildParameters(projectCollection);

        var loggers = new List<ILogger>();
        loggers.Add(new ConsoleLogger(logVerbosity, s => logger.WriteLine(s.TrimEnd('\r', '\n')), null, null));
        loggers.AddRange(additionalLoggers);
        parameters.Loggers = loggers.ToArray();

        buildManager.BeginBuild(parameters);

        var result = await buildManager.BuildAsync(brd);

        buildManager.EndBuild();

        return result;
    }
示例#6
0
 protected virtual IEnumerable <ProjectFileReference> GetProjectReferences(MSB.Execution.ProjectInstance executedProject)
 {
     return(executedProject.GetItems("ProjectReference")
            .Select(reference => new ProjectFileReference(
                        path: reference.EvaluatedInclude,
                        aliases: default(ImmutableArray <string>))));
 }
示例#7
0
            private void GetReferences(
                CSharpCompilerInputs compilerInputs,
                MSB.Execution.ProjectInstance executedProject,
                out IEnumerable <MetadataReference> metadataReferences,
                out IEnumerable <AnalyzerReference> analyzerReferences)
            {
                // use command line parser to do reference translation same as command line compiler

                var args = new List <string>();

                if (compilerInputs.LibPaths != null && compilerInputs.LibPaths.Count > 0)
                {
                    args.Add("/lib:\"" + string.Join(";", compilerInputs.LibPaths) + "\"");
                }

                foreach (var mr in compilerInputs.References)
                {
                    var filePath = GetDocumentFilePath(mr);

                    var aliases = GetAliases(mr);
                    if (aliases.IsDefaultOrEmpty)
                    {
                        args.Add("/r:\"" + filePath + "\"");
                    }
                    else
                    {
                        foreach (var alias in aliases)
                        {
                            args.Add("/r:" + alias + "=\"" + filePath + "\"");
                        }
                    }
                }

                foreach (var ar in compilerInputs.AnalyzerReferences)
                {
                    var filePath = GetDocumentFilePath(ar);
                    args.Add("/a:\"" + filePath + "\"");
                }

                if (compilerInputs.NoStandardLib)
                {
                    args.Add("/nostdlib");
                }

                var commandLineParser = CSharpCommandLineParser.Default;
                var commandLineArgs   = commandLineParser.Parse(args, executedProject.Directory, RuntimeEnvironment.GetRuntimeDirectory());

                var resolver = new MetadataFileReferenceResolver(commandLineArgs.ReferencePaths, commandLineArgs.BaseDirectory);

                metadataReferences = commandLineArgs.ResolveMetadataReferences(new AssemblyReferenceResolver(resolver, _metadataService.GetProvider()));

                var analyzerLoader = _analyzerService.GetLoader();

                foreach (var path in commandLineArgs.AnalyzerReferences.Select(r => r.FilePath))
                {
                    analyzerLoader.AddDependencyLocation(path);
                }
                analyzerReferences = commandLineArgs.ResolveAnalyzerReferences(analyzerLoader);
            }
        public static void AssertPropertyDoesNotExist(ProjectInstance projectInstance, string propertyName)
        {
            ProjectPropertyInstance propertyInstance = projectInstance.GetProperty(propertyName);

            string value = propertyInstance == null ? null : propertyInstance.EvaluatedValue;

            Assert.IsNull(propertyInstance, "Not expecting the property to exist. Property: {0}, Value: {1}", propertyName, value);
        }
示例#9
0
		public BuildRequestData (ProjectInstance projectInstance, string[] targetsToBuild, HostServices hostServices,
				BuildRequestDataFlags flags)
		{
			ProjectInstance = projectInstance;
			TargetNames = targetsToBuild;
			HostServices = hostServices;
			Flags = flags;
		}
示例#10
0
		public void ExplicitToolsVersion ()
		{
            string project_xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' />";
            var xml = XmlReader.Create (new StringReader(project_xml));
            var root = ProjectRootElement.Create (xml);
			var proj = new ProjectInstance (root, null, "4.0", new ProjectCollection ());
			Assert.AreEqual ("4.0", proj.ToolsVersion, "#1");
		}
示例#11
0
		internal ProjectItemInstance (ProjectInstance project, string itemType, IEnumerable<KeyValuePair<string,string>> metadata, string evaluatedInclude)
		{
			this.project = project;
			this.evaluated_include = evaluatedInclude;
			this.item_type = itemType;
			this.metadata = new List<ProjectMetadataInstance> ();
			SetMetadata (metadata);
		}
示例#12
0
		public void DefaultTargetsEmpty ()
		{
            string project_xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
</Project>";
            var xml = XmlReader.Create (new StringReader (project_xml));
            var root = ProjectRootElement.Create (xml);
            var proj = new ProjectInstance (root);
			Assert.AreEqual (new string [0], proj.DefaultTargets, "#1");
		}
示例#13
0
 public virtual string GetConfigurationProperty(string propertyName, bool resetCache)
 {
     if (snapshot == null)
         snapshot = proj.CreateProjectInstance(config, platform);
     ProjectPropertyInstance property = snapshot.GetProperty(propertyName);
     if (property == null)
         return null;
     return property.EvaluatedValue;
 }
示例#14
0
			static ProjectInstance[] sortByBuildOrder(ProjectInstance[] instances)
			{
				var rootProjects = instances.ToDictionary(getProjectGuid);

				var ordered = 
					rootProjects.Keys.SortTopologicallyReverse(
						g1 => getDependentProjectGuids(rootProjects[g1]).Where(rootProjects.ContainsKey));

				return ordered.Select(g => rootProjects[g]).ToArray();
			}
示例#15
0
 public Microsoft.Expression.Project.Build.BuildResult Build(IEnumerable <ILogger> loggers, params string[] targetNames)
 {
     Microsoft.Build.Execution.ProjectInstance projectInstance = new Microsoft.Build.Execution.ProjectInstance(this.CreateProject());
     string[] strArrays = new string[] { "ResolveReferences", "MarkupCompilePass1" };
     if (projectInstance.Build(strArrays, loggers))
     {
         return(Microsoft.Expression.Project.Build.BuildResult.Succeeded);
     }
     return(Microsoft.Expression.Project.Build.BuildResult.Failed);
 }
示例#16
0
		public void DefaultTargetsFromAttribute ()
		{
            string project_xml = @"<Project DefaultTargets='Foo Bar Baz;Foo' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
</Project>";
            var xml = XmlReader.Create (new StringReader (project_xml));
            var root = ProjectRootElement.Create (xml);
            var proj = new ProjectInstance (root);
			string [] expected = {"Foo Bar Baz", "Foo"};
			Assert.AreEqual (expected, proj.DefaultTargets, "#1");
		}
		public void ToStringOverride ()
		{
			var xml = XmlReader.Create (new StringReader (project_xml));
			string path = Path.GetFullPath ("foo.xml");
			var root = ProjectRootElement.Create (xml);
			var proj = new ProjectInstance (root);
			var item = proj.Items.First ();
			Assert.AreEqual ("M=m", item.Metadata.First ().ToString (), "#1");
			Assert.AreEqual ("N==", item.Metadata.Last ().ToString (), "#2"); // haha
		}
示例#18
0
		public BuildRequestData (ProjectInstance projectInstance, string[] targetsToBuild, HostServices hostServices,
				BuildRequestDataFlags flags)
		{
			if (targetsToBuild == null)
				throw new ArgumentNullException ("targetsToBuild");
			ProjectInstance = projectInstance;
			TargetNames = targetsToBuild;
			HostServices = hostServices;
			Flags = flags;
		}
            private IEnumerable<ProjectFileReference> GetProjectReferencesCore(ProjectInstance executedProject)
            {
                foreach (var projectReference in GetProjectReferenceItems(executedProject))
                {
                    var filePath = projectReference.EvaluatedInclude;
                    var aliases = GetAliases(projectReference);

                    yield return new ProjectFileReference(filePath, aliases);
                }
            }
示例#20
0
		public ExpressionEvaluator (ProjectInstance project, string replacementForMissingPropertyAndItem)
		{
			ReplacementForMissingPropertyAndItem = replacementForMissingPropertyAndItem;
			ProjectInstance = project;
			/*
			GetItems = (name) => project.GetItems (name).Select (i => new KeyValuePair<string,string> (i.ItemType, i.EvaluatedInclude));
			GetProperty = (name) => {
				var prop = project.GetProperty (name);
				return new KeyValuePair<string,string> (prop != null ? prop.Name : null, prop != null ? prop.EvaluatedValue : null);
				};
			*/
		}
		public void NullTargetsToBuild ()
		{
			string project_xml = @"<Project DefaultTargets='Foo' xmlns='http://schemas.microsoft.com/developer/msbuild/2003' />";
			var xml = XmlReader.Create (new StringReader (project_xml));
			var root = ProjectRootElement.Create (xml);
			root.FullPath = "BuildRequestDataTest.NullTargetsToBuild.proj";
			var pc = new ProjectCollection ();
			var sw = new StringWriter ();
			pc.RegisterLogger (new ConsoleLogger (LoggerVerbosity.Diagnostic, sw.WriteLine, null, null));
			var proj = new ProjectInstance (root);
			new BuildRequestData (proj, null);
		}
示例#22
0
		public void BuildDoesNotIncreaseCollectionContent ()
		{
			string empty_project_xml = "<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' />";
			var xml = XmlReader.Create (new StringReader (empty_project_xml));
			var root = ProjectRootElement.Create (xml);
			var coll = new ProjectCollection ();
			var inst = new ProjectInstance (root, null, null, coll);
			root.FullPath = "ProjectCollectionTest.BuildDoesNotIncreaseCollectionContent.proj";
			Assert.AreEqual (0, coll.Count, "#1");
			inst.Build ();
			Assert.AreEqual (0, coll.Count, "#2");
		}
示例#23
0
		public void ResultBeforeExecute ()
		{
			string empty_project_xml = "<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' />";
			var path = "file://localhost/foo.xml";
			var xml = XmlReader.Create (new StringReader (empty_project_xml), null, path);
			var root = ProjectRootElement.Create (xml);
			var proj = new ProjectInstance (root);
			var bm = new BuildManager ();
			bm.BeginBuild (new BuildParameters ());
			var sub = bm.PendBuildRequest (new BuildRequestData (proj, new string [0]));
			Assert.IsNull (sub.BuildResult, "#1");
		}
示例#24
0
 private void CreateProject()
 {
     try
     {
         _projectInstance = new ProjectInstance(_file.FullName);
         _project = _projects.LoadProject(_file.FullName);
     }
     catch (Exception error)
     {
         throw new BuildFileLoadException("Error parsing MSBuild project", error);
     }
 }
示例#25
0
        public Assembly CompileProject(string projectFilename, string configuration = "Debug")
        {
            var mgr = new BuildManager();
            var parms = new BuildParameters();
            var proj = new ProjectInstance(projectFilename);

            var req = new BuildRequestData(proj, new string[] {configuration});

            BuildResult result = mgr.Build(parms, req);
            Console.WriteLine("Overall build result: {0}", result.OverallResult);

            throw new NotImplementedException("Not fully implemented yet");
        }
示例#26
0
        static RelativeFileSet GetProjectFileSet(FilePath ProjectFile)
        {
            var isSqlProj = ProjectFile.Extension == "sqlproj";

            var project = new MSE.ProjectInstance(ProjectFile);
            var items   = isSqlProj
                ? project.FindItems(StandardItemTypes.Build, StandardItemTypes.None)
                : project.FindItems(StandardItemTypes.Compile, StandardItemTypes.None);

            var files = items.Map(item => new RelativePath(item.EvaluatedInclude));

            return(new RelativeFileSet(ProjectFile.Folder, files));
        }
        public void IntTargets_TempFolderIsNotSet()
        {
            // Arrange
            string rootInputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");
            ProjectRootElement projectRoot = BuildUtilities.CreateValidProjectRoot(this.TestContext, rootInputFolder, null);

            // Act
            ProjectInstance projectInstance = new ProjectInstance(projectRoot.FullPath);
            
            // Assert
            BuildAssertions.AssertPropertyDoesNotExist(projectInstance, TargetProperties.SonarQubeOutputPath);
            BuildAssertions.AssertPropertyDoesNotExist(projectInstance, TargetProperties.SonarQubeConfigPath);
        }
            private ProjectFileInfo CreateProjectFileInfo(VisualBasicProjectFileLoader.VisualBasicProjectFile.VisualBasicCompilerInputs compilerInputs, ProjectInstance executedProject)
            {
                string outputPath = Path.Combine(this.GetOutputDirectory(), compilerInputs.OutputFileName);
                string assemblyName = this.GetAssemblyName();

                return new ProjectFileInfo(
                    outputPath,
                    assemblyName,
                    compilerInputs.CommandLineArgs,
                    this.GetDocuments(compilerInputs.Sources, executedProject),
                    this.GetDocuments(compilerInputs.AdditionalFiles, executedProject),
                    base.GetProjectReferences(executedProject));
            }
示例#29
0
		// FIXME:
		// While we are not faced to implement those features, there are some modern task execution requirements.
		//
		// This will have to be available for "out of process" nodes (see NodeAffinity).
		// NodeAffinity is set per project file at BuildManager.HostServices.
		// When NodeAffinity is set to OutOfProc, it should probably launch different build host
		// that runs separate build tasks. (.NET has MSBuildTaskHost.exe which I guess is about that.)
		//
		// Also note that the complete implementation has to support LoadInSeparateAppDomainAttribute
		// (which is most likely derived from AppDomainIsolatedBuildTask) that marks a task to run
		// in separate AppDomain.
		//
		public void BuildProject (Func<bool> checkCancel, BuildResult result, ProjectInstance project, IEnumerable<string> targetNames, IDictionary<string,string> globalProperties, IDictionary<string,string> targetOutputs, string toolsVersion)
		{
			if (toolsVersion == null)
				throw new ArgumentNullException ("toolsVersion");
			
			var parameters = submission.BuildManager.OngoingBuildParameters;
			var toolset = parameters.GetToolset (toolsVersion);
			if (toolset == null)
				throw new InvalidOperationException (string.Format ("Toolset version '{0}' was not resolved to valid toolset", toolsVersion));
			LogMessageEvent (new BuildMessageEventArgs (string.Format ("Using Toolset version {0}.", toolsVersion), null, null, MessageImportance.Low));
			var buildTaskFactory = new BuildTaskFactory (BuildTaskDatabase.GetDefaultTaskDatabase (toolset), new BuildTaskDatabase (this, submission.BuildRequest.ProjectInstance));
			BuildProject (new InternalBuildArguments () { CheckCancel = checkCancel, Result = result, Project = project, TargetNames = targetNames, GlobalProperties = globalProperties, TargetOutputs = targetOutputs, ToolsVersion = toolsVersion, BuildTaskFactory = buildTaskFactory });
		}
		public void PropertiesCopiesValues ()
		{
			var xml = XmlReader.Create (new StringReader (project_xml));
			string path = Path.GetFullPath ("foo.xml");
			var root = ProjectRootElement.Create (xml);
			var proj = new ProjectInstance (root);
			var item = proj.Items.First ();
			var md = item.Metadata.First ();
			Assert.AreEqual ("m", item.Metadata.First ().EvaluatedValue, "#1");
			Assert.AreEqual ("m", root.ItemGroups.First ().Items.First ().Metadata.First ().Value, "#2");
			root.ItemGroups.First ().Items.First ().Metadata.First ().Value = "X";
			Assert.AreEqual ("m", item.Metadata.First ().EvaluatedValue, "#3");
		}
        private void OnProjectOpened(IVsHierarchy vsHierarchy)
        {
            // Register pipe url so that MSBuild can transfer it
            var vsProject = vsHierarchy as IVsProject;
            if (vsProject != null)
            {
                var dteProject = VsHelper.ToDteProject(vsProject);

                // We will only deal with .csproj files for now
                // Should we support C++/CLI .vcxproj as well?
                if (!dteProject.FileName.EndsWith(".csproj"))
                    return;

                // Find current project active configuration
                var configManager = dteProject.ConfigurationManager;
                if (configManager == null)
                    return;

                EnvDTE.Configuration activeConfig;
                try
                {
                    activeConfig = configManager.ActiveConfiguration;
                }
                catch (Exception)
                {
                    if (configManager.Count == 0)
                        return;

                    activeConfig = configManager.Item(1);
                }

                // Get global parameters for Configuration and Platform
                var globalProperties = new Dictionary<string, string>();
                globalProperties["Configuration"] = activeConfig.ConfigurationName;
                globalProperties["Platform"] = activeConfig.PlatformName == "Any CPU" ? "AnyCPU" : activeConfig.PlatformName;

                // Check if project matches: Condition="'$(SiliconStudioCurrentPackagePath)' != '' and '$(SiliconStudioIsExecutable)' == 'true'"
                var projectInstance = new ProjectInstance(dteProject.FileName, globalProperties, null);
                var packagePathProperty = projectInstance.Properties.FirstOrDefault(x => x.Name == "SiliconStudioCurrentPackagePath");
                var isExecutableProperty = projectInstance.Properties.FirstOrDefault(x => x.Name == "SiliconStudioIsExecutable");
                if (packagePathProperty == null || isExecutableProperty == null || isExecutableProperty.EvaluatedValue.ToLowerInvariant() != "true")
                    return;

                var buildProjects = ProjectCollection.GlobalProjectCollection.GetLoadedProjects(dteProject.FileName);
                foreach (var buildProject in buildProjects)
                {
                    buildProject.SetGlobalProperty("SiliconStudioBuildEngineLogPipeUrl", logPipeUrl);
                }
            }
        }
示例#32
0
        public virtual void Invalidate()
        {
            // property cache will need to be updated
            this.currentConfig     = null;
            this.currentUserConfig = null;

            // Signal the output groups that something is changed
            foreach (OutputGroup group in this.OutputGroups)
            {
                group.InvalidateGroup();
            }

            this._project.SetProjectFileDirty(true);
        }
示例#33
0
        private MSBuildExecution.ProjectInstance GetCurrentConfig(bool resetCache = false)
        {
            if (resetCache || currentConfig == null)
            {
                // Get properties for current configuration from project file and cache it
                project.SetConfiguration(ConfigName);
                project.BuildProject.ReevaluateIfNecessary();
                // Create a snapshot of the evaluated project in its current state
                currentConfig = project.BuildProject.CreateProjectInstance();

                // Restore configuration
                project.SetCurrentConfiguration();
            }
            return(currentConfig);
        }
示例#34
0
		public void DefaultTargetsFromElements ()
		{
			string [] defaultTargetAtts = {string.Empty, "DefaultTargets=''"};
			
			for (int i = 0; i < defaultTargetAtts.Length; i++) {
				string project_xml = string.Format (@"<Project {0} xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
	<Target Name='Foo' />
	<Target Name='Bar' />
</Project>", defaultTargetAtts [i]);
	            var xml = XmlReader.Create (new StringReader (project_xml));
	            var root = ProjectRootElement.Create (xml);
	            var proj = new ProjectInstance (root);
				string [] expected = {"Foo"}; // Bar is not included
				Assert.AreEqual (expected, proj.DefaultTargets, "#1-" + i);
			}
		}
示例#35
0
        protected string GetItemString(MSB.Execution.ProjectInstance executedProject, string itemType)
        {
            string text = "";

            foreach (var item in executedProject.GetItems(itemType))
            {
                if (text.Length > 0)
                {
                    text = text + " ";
                }

                text = text + item.EvaluatedInclude;
            }

            return(text);
        }
            private IEnumerable<ProjectFileReference> GetProjectReferencesCore(ProjectInstance executedProject)
            {
                foreach (var projectReference in GetProjectReferenceItems(executedProject))
                {
                    Guid guid;
                    if (!Guid.TryParse(projectReference.GetMetadataValue("Project"), out guid))
                    {
                        continue;
                    }

                    var filePath = projectReference.EvaluatedInclude;
                    var aliases = GetAliases(projectReference);

                    yield return new ProjectFileReference(guid, filePath, aliases);
                }
            }
示例#37
0
        public virtual void SetConfigurationProperty(string propertyName, string propertyValue)
        {
            if (!this.project.QueryEditProjectFile(false))
            {
                throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
            }

            string condition = String.Format(CultureInfo.InvariantCulture, ConfigProvider.configString, this.ConfigName);

            SetPropertyUnderCondition(propertyName, propertyValue, condition);

            // property cache will need to be updated
            this.currentConfig = null;

            return;
        }
示例#38
0
 public IReadOnlyList <FilePath> GetProjectFiles(FilePath ProjectFile)
 {
     try
     {
         var project     = new MSEX.ProjectInstance(ProjectFile);
         var evaluations = project.Items.Map(item => (item.ItemType, item.EvaluatedInclude));
         var paths       = evaluations.Where(e => e.Item1 == "Build")
                           .Select(x => ProjectFile.Folder.GetCombinedFilePath(x.Item2)).Where(f => f.Exists()).ToList();
         return(paths);
     }
     catch (Exception e)
     {
         Notify(error($"Error occurred during evaluation of {ProjectFile}: {e}"));
         return(metacore.rolist <FilePath>());
     }
 }
示例#39
0
 /// <summary>
 /// Factory for intrinsic tasks.
 /// </summary>
 /// <param name="taskInstance">The task instance object.</param>
 /// <param name="loggingContext">The logging context.</param>
 /// <param name="projectInstance">The project instance.</param>
 /// <returns>An instantiated intrinsic task.</returns>
 internal static IntrinsicTask InstantiateTask(ProjectTargetInstanceChild taskInstance, TargetLoggingContext loggingContext, ProjectInstance projectInstance, bool logTaskInputs)
 {
     if (taskInstance is ProjectPropertyGroupTaskInstance)
     {
         return new PropertyGroupIntrinsicTask(taskInstance as ProjectPropertyGroupTaskInstance, loggingContext, projectInstance, logTaskInputs);
     }
     else if (taskInstance is ProjectItemGroupTaskInstance)
     {
         return new ItemGroupIntrinsicTask(taskInstance as ProjectItemGroupTaskInstance, loggingContext, projectInstance, logTaskInputs);
     }
     else
     {
         ErrorUtilities.ThrowInternalError("Unhandled intrinsic task type {0}", taskInstance.GetType().BaseType);
         return null;
     }
 }
示例#40
0
        protected string ReadPropertyString(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
        {
            var executedProperty = executedProject.GetProperty(executedPropertyName);

            if (executedProperty != null)
            {
                return(executedProperty.EvaluatedValue);
            }

            var evaluatedProperty = _loadedProject.GetProperty(evaluatedPropertyName);

            if (evaluatedProperty != null)
            {
                return(evaluatedProperty.EvaluatedValue);
            }

            return(null);
        }
示例#41
0
        public Option <string> BuildSolution(FilePath SolutionPath)
        {
            var manager = MSEX.BuildManager.DefaultBuildManager;
            var project = new MSEX.ProjectInstance(SolutionPath);

            var logPath      = SolutionPath.ChangeExtension("binlog");
            var buildRequest = new MSEX.BuildRequestData(project, array("Build"));
            var result       = manager.Build
                               (
                new MSEX.BuildParameters
            {
                Loggers = metacore.roitems <ILogger>(new MSL.ConsoleLogger())
            },
                buildRequest
                               );

            var targetResults = result.ResultsByTarget["Build"];

            return(targetResults.ResultCode.ToString());
        }
示例#42
0
        protected virtual MSBuildExecution.ProjectPropertyInstance GetMsBuildProperty(string propertyName, _PersistStorageType storageType, bool resetCache)
        {
            MSBuildExecution.ProjectInstance requestedConfig = storageType == _PersistStorageType.PST_PROJECT_FILE ? currentConfig : currentUserConfig;
            if (resetCache || requestedConfig == null)
            {
                // Get properties for current configuration from project file and cache it
                this._project.SetConfiguration(this.ConfigName, this.Platform);
                this._project.BuildProject.ReevaluateIfNecessary();
                if (this._project.UserBuildProject != null)
                {
                    this._project.UserBuildProject.ReevaluateIfNecessary();
                }

                // Create a snapshot of the evaluated project in its current state
                this.currentConfig = this._project.BuildProject.CreateProjectInstance();
                if (this._project.UserBuildProject != null)
                {
                    this.currentUserConfig = this._project.UserBuildProject.CreateProjectInstance();
                }

                requestedConfig = storageType == _PersistStorageType.PST_PROJECT_FILE ? currentConfig : currentUserConfig;

                // Restore configuration
                _project.SetCurrentConfiguration();
            }

            if (requestedConfig == null)
            {
                if (storageType == _PersistStorageType.PST_PROJECT_FILE)
                {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.FailedToRetrieveProperties, CultureInfo.CurrentUICulture), propertyName));
                }

                // user build projects aren't essential
                return(null);
            }

            // return property asked for
            return(requestedConfig.GetProperty(propertyName));
        }
示例#43
0
        private MSBuildExecution.ProjectPropertyInstance GetMsBuildProperty(string propertyName, bool resetCache)
        {
            if (resetCache || this.currentConfig == null)
            {
                // Get properties for current configuration from project file and cache it
                this.project.SetConfiguration(this.ConfigName);
                this.project.BuildProject.ReevaluateIfNecessary();
                // Create a snapshot of the evaluated project in its current state
                this.currentConfig = this.project.BuildProject.CreateProjectInstance();

                // Restore configuration
                project.SetCurrentConfiguration();
            }

            if (this.currentConfig == null)
            {
                throw new Exception("Failed to retrieve properties");
            }

            // return property asked for
            return(this.currentConfig.GetProperty(propertyName));
        }
        public virtual void SetConfigurationProperty(string propertyName, string propertyValue)
        {
            if (!this.project.QueryEditProjectFile(false))
            {
                throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
            }
            // Старое значение строки формата: ConfigProvider.configString
            string condition = MakeMSBuildCondition(ConfigurationName, PlatformName);

            SetPropertyUnderCondition(propertyName, propertyValue, condition);

            // property cache will need to be updated
            this.currentConfig = null;

            // Signal the output groups that something is changed
            foreach (OutputGroup group in this.OutputGroups)
            {
                group.InvalidateGroup();
            }
            this.project.SetProjectFileDirty(true);

            return;
        }
示例#45
0
        public virtual void SetConfigurationProperty(string propertyName, string propertyValue)
        {
            if (!this.project.QueryEditProjectFile(false))
            {
                throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
            }

            string condition = String.Format(CultureInfo.InvariantCulture, ConfigProvider.configString, this.ConfigName);

            SetPropertyUnderCondition(propertyName, propertyValue, condition);

            // property cache will need to be updated
            this.currentConfig = null;

            // Signal the output groups that something is changed
            foreach (OutputGroup group in this.OutputGroups)
            {
                group.InvalidateGroup();
            }
            this.project.SetProjectFileDirty(true);

            return;
        }
示例#46
0
        public void TestConfigChange()
        {
            UIThreadInvoker.Invoke((ThreadInvoker) delegate()
            {
                //Get the global service provider and the dte
                IServiceProvider sp = VsIdeTestHostContext.ServiceProvider;
                DTE dte             = (DTE)sp.GetService(typeof(DTE));

                string destination  = Path.Combine(TestContext.TestDir, TestContext.TestName);
                ProjectNode project = Utilities.CreateMyNestedProject(sp, dte, TestContext.TestName, destination, true);

                EnvDTE.Property property = dte.Solution.Properties.Item("ActiveConfig");

                // Now change the active config that should trigger a project config change event and the global property should be thus updated.
                property.Value = "Release|Any CPU";

                MSBuildExecution.ProjectInstance buildProject = project.CurrentConfig;
                string activeConfig = null;
                buildProject.GlobalProperties.TryGetValue(GlobalProperty.Configuration.ToString(), out activeConfig);

                Assert.AreEqual("Release", activeConfig);
            });
        }
示例#47
0
 protected bool ReadPropertyBool(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
 {
     return(ConvertToBool(ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName)));
 }
示例#48
0
 protected virtual IEnumerable <MSB.Framework.ITaskItem> GetDocumentsFromModel(MSB.Execution.ProjectInstance executedProject)
 {
     return(executedProject.GetItems("Compile"));
 }
示例#49
0
 protected virtual IEnumerable <MSB.Framework.ITaskItem> GetMetadataReferencesFromModel(MSB.Execution.ProjectInstance executedProject)
 {
     return(executedProject.GetItems("ReferencePath"));
 }
            private ProjectFileInfo CreateProjectFileInfo(CSharpCompilerInputs compilerInputs, MSB.Execution.ProjectInstance executedProject)
            {
                string projectDirectory   = executedProject.Directory;
                string directorySeparator = Path.DirectorySeparatorChar.ToString();

                if (!projectDirectory.EndsWith(directorySeparator, StringComparison.OrdinalIgnoreCase))
                {
                    projectDirectory += directorySeparator;
                }

                var docs = compilerInputs.Sources
                           .Where(s => !Path.GetFileName(s.ItemSpec).StartsWith("TemporaryGeneratedFile_", StringComparison.Ordinal))
                           .Select(s => MakeDocumentFileInfo(projectDirectory, s))
                           .ToImmutableArray();

                var additionalDocs = compilerInputs.AdditionalSources
                                     .Select(s => MakeDocumentFileInfo(projectDirectory, s))
                                     .ToImmutableArray();

                var outputPath   = Path.Combine(this.GetOutputDirectory(), compilerInputs.OutputFileName);
                var assemblyName = this.GetAssemblyName();

                return(new ProjectFileInfo(
                           outputPath,
                           assemblyName,
                           compilerInputs.CommandLineArgs,
                           docs,
                           additionalDocs,
                           this.GetProjectReferences(executedProject)));
            }
            private void InitializeFromModel(CSharpCompilerInputs compilerInputs, MSB.Execution.ProjectInstance executedProject)
            {
                compilerInputs.BeginInitialization();

                compilerInputs.SetAllowUnsafeBlocks(this.ReadPropertyBool(executedProject, "AllowUnsafeBlocks"));
                compilerInputs.SetApplicationConfiguration(this.ReadPropertyString(executedProject, "AppConfigForCompiler"));
                compilerInputs.SetBaseAddress(this.ReadPropertyString(executedProject, "BaseAddress"));
                compilerInputs.SetCheckForOverflowUnderflow(this.ReadPropertyBool(executedProject, "CheckForOverflowUnderflow"));
                compilerInputs.SetCodePage(this.ReadPropertyInt(executedProject, "CodePage"));
                compilerInputs.SetDebugType(this.ReadPropertyString(executedProject, "DebugType"));
                compilerInputs.SetDefineConstants(this.ReadPropertyString(executedProject, "DefineConstants"));
                compilerInputs.SetFeatures(this.ReadPropertyString(executedProject, "Features"));

                var delaySignProperty = this.GetProperty("DelaySign");

                compilerInputs.SetDelaySign(delaySignProperty != null && !string.IsNullOrEmpty(delaySignProperty.EvaluatedValue), this.ReadPropertyBool(executedProject, "DelaySign"));

                compilerInputs.SetDisabledWarnings(this.ReadPropertyString(executedProject, "NoWarn"));
                compilerInputs.SetDocumentationFile(this.GetItemString(executedProject, "DocFileItem"));
                compilerInputs.SetEmitDebugInformation(this.ReadPropertyBool(executedProject, "DebugSymbols"));
                compilerInputs.SetErrorReport(this.ReadPropertyString(executedProject, "ErrorReport"));
                compilerInputs.SetFileAlignment(this.ReadPropertyInt(executedProject, "FileAlignment"));
                compilerInputs.SetGenerateFullPaths(this.ReadPropertyBool(executedProject, "GenerateFullPaths"));
                compilerInputs.SetHighEntropyVA(this.ReadPropertyBool(executedProject, "HighEntropyVA"));

                bool signAssembly = this.ReadPropertyBool(executedProject, "SignAssembly");

                if (signAssembly)
                {
                    compilerInputs.SetKeyContainer(this.ReadPropertyString(executedProject, "KeyContainerName"));
                    compilerInputs.SetKeyFile(this.ReadPropertyString(executedProject, "KeyOriginatorFile", "AssemblyOriginatorKeyFile"));
                }

                compilerInputs.SetLangVersion(this.ReadPropertyString(executedProject, "LangVersion"));

                compilerInputs.SetMainEntryPoint(null, this.ReadPropertyString(executedProject, "StartupObject"));
                compilerInputs.SetModuleAssemblyName(this.ReadPropertyString(executedProject, "ModuleAssemblyName"));
                compilerInputs.SetNoStandardLib(this.ReadPropertyBool(executedProject, "NoCompilerStandardLib"));
                compilerInputs.SetOptimize(this.ReadPropertyBool(executedProject, "Optimize"));
                compilerInputs.SetOutputAssembly(this.GetItemString(executedProject, "IntermediateAssembly"));
                compilerInputs.SetPdbFile(this.ReadPropertyString(executedProject, "PdbFile"));

                if (this.ReadPropertyBool(executedProject, "Prefer32Bit"))
                {
                    compilerInputs.SetPlatformWith32BitPreference(this.ReadPropertyString(executedProject, "PlatformTarget"));
                }
                else
                {
                    compilerInputs.SetPlatform(this.ReadPropertyString(executedProject, "PlatformTarget"));
                }

                compilerInputs.SetSubsystemVersion(this.ReadPropertyString(executedProject, "SubsystemVersion"));
                compilerInputs.SetTargetType(this.ReadPropertyString(executedProject, "OutputType"));

                // Decode the warning options from RuleSet file prior to reading explicit settings in the project file, so that project file settings prevail for duplicates.
                compilerInputs.SetRuleSet(this.ReadPropertyString(executedProject, "RuleSet"));
                compilerInputs.SetTreatWarningsAsErrors(this.ReadPropertyBool(executedProject, "TreatWarningsAsErrors"));
                compilerInputs.SetWarningLevel(this.ReadPropertyInt(executedProject, "WarningLevel"));
                compilerInputs.SetWarningsAsErrors(this.ReadPropertyString(executedProject, "WarningsAsErrors"));
                compilerInputs.SetWarningsNotAsErrors(this.ReadPropertyString(executedProject, "WarningsNotAsErrors"));

                compilerInputs.SetReferences(this.GetMetadataReferencesFromModel(executedProject).ToArray());
                compilerInputs.SetAnalyzers(this.GetAnalyzerReferencesFromModel(executedProject).ToArray());
                compilerInputs.SetAdditionalFiles(this.GetAdditionalFilesFromModel(executedProject).ToArray());
                compilerInputs.SetSources(this.GetDocumentsFromModel(executedProject).ToArray());

                string errorMessage;
                int    errorCode;

                compilerInputs.EndInitialization(out errorMessage, out errorCode);
            }
示例#52
0
 protected virtual IEnumerable <MSB.Framework.ITaskItem> GetAnalyzerReferencesFromModel(MSB.Execution.ProjectInstance executedProject)
 {
     return(executedProject.GetItems("Analyzer"));
 }
示例#53
0
 protected IEnumerable <MSB.Framework.ITaskItem> GetTaskItems(MSB.Execution.ProjectInstance executedProject, string itemType)
 {
     return(executedProject.GetItems(itemType));
 }
示例#54
0
 internal BuildResult(MSB.Execution.BuildResult result, MSB.Execution.ProjectInstance instance)
 {
     this.Result   = result;
     this.Instance = instance;
 }
示例#55
0
 protected TEnum?ReadPropertyEnum <TEnum>(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
     where TEnum : struct
 {
     return(ConvertToEnum <TEnum>(ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName)));
 }
示例#56
0
 protected ulong ReadPropertyULong(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
 {
     return(ConvertToULong(this.ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName)));
 }
示例#57
0
 protected ulong ReadPropertyULong(MSB.Execution.ProjectInstance executedProject, string propertyName)
 {
     return(ConvertToULong(ReadPropertyString(executedProject, propertyName)));
 }
示例#58
0
 protected string ReadPropertyString(MSB.Execution.ProjectInstance executedProject, string propertyName)
 {
     return(this.ReadPropertyString(executedProject, propertyName, propertyName));
 }
示例#59
0
 protected int ReadPropertyInt(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
 {
     return(ConvertToInt(ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName)));
 }
示例#60
0
 protected virtual IEnumerable <MSB.Framework.ITaskItem> GetAdditionalFilesFromModel(MSB.Execution.ProjectInstance executedProject)
 {
     return(executedProject.GetItems("AdditionalFiles"));
 }