public bool Exec() { int result = 0; foreach (KeyValuePair <string, Project> project in _projects) { Project proj = project.Value; ProjectProperty property = proj.GetProperty("OutputType"); if (property.EvaluatedValue == "Exe") { ProjectProperty output = proj.GetProperty("OutputPath"); ProjectProperty asm = proj.GetProperty("AssemblyName"); string exe = proj.DirectoryPath + Path.DirectorySeparatorChar + output.EvaluatedValue + asm.EvaluatedValue + ".exe"; Process.Start(new ProcessStartInfo(exe) { WorkingDirectory = Path.GetDirectoryName(exe) }); result++; } } if (result == 0) { MessageBox.Show("Not Found Exe Project"); return(false); } return(true); }
public ProjectModel CreateProjectModel(Microsoft.Build.Evaluation.Project buildProject) { string projectPath = buildProject.ProjectFileLocation.File; string guidStr = buildProject.GetProperty("ProjectGuid")?.EvaluatedValue; Guid projectGuid = Guid.Empty; if (!string.IsNullOrEmpty(guidStr)) { projectGuid = new Guid(buildProject.GetProperty("ProjectGuid").EvaluatedValue); } string projectName = buildProject.GetProperty("AssemblyName").EvaluatedValue; var references = buildProject.GetItems("Reference").ToList(); bool isBsipa = buildProject.GetItems("Reference").Any(i => i.EvaluatedInclude.StartsWith("IPA.Loader")); var bsDirProp = buildProject.GetProperty("BeatSaberDir"); var projCap = Models.ProjectCapabilities.None; ProjectOptions projOptions = ProjectOptions.None; if (bsDirProp != null) { projCap |= Models.ProjectCapabilities.BeatSaberDir; projOptions |= ProjectOptions.BeatSaberDir; } var projectModel = new ProjectModel(projectGuid, projectName, projectPath, isBsipa, projOptions, projOptions, projCap); return(projectModel); }
private Compilation CreateCompilation(Project project) { var outputPath = project.GetProperty("OutputPath").EvaluatedValue; if (!Path.IsPathRooted(outputPath)) { outputPath = Path.Combine(Environment.CurrentDirectory, outputPath); } var searchPaths = ReadOnlyArray.OneOrZero(outputPath); var resolver = new DiskFileResolver(searchPaths, searchPaths, Environment.CurrentDirectory, arch => true, System.Globalization.CultureInfo.CurrentCulture); var metadataFileProvider = new MetadataFileProvider(); // just grab a list of references (if they're null, ignore) var list = project.GetItems("Reference").Select(item => { var include = item.EvaluatedInclude; var path = resolver.ResolveAssemblyName(include); if (path == null) return null; return metadataFileProvider.GetReference(path); }).Where(x => x != null); return Compilation.Create(project.GetPropertyValue("AssemblyName"), syntaxTrees: project.GetItems("Compile").Select(c => SyntaxTree.ParseFile(c.EvaluatedInclude)), references: list); }
public void SimpleImportAndSemanticValues () { string xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <Import Project='test_imported.proj' /> </Project>"; string imported = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <PropertyGroup> <A>x</A> <B>y</B> </PropertyGroup> <ItemGroup> <X Include=""included.txt"" /> </ItemGroup> </Project>"; using (var ts = File.CreateText (temp_file_name)) ts.Write (imported); try { var reader = XmlReader.Create (new StringReader (xml)); var root = ProjectRootElement.Create (reader); Assert.AreEqual (temp_file_name, root.Imports.First ().Project, "#1"); var proj = new Project (root); var prop = proj.GetProperty ("A"); Assert.IsNotNull (prop, "#2"); Assert.IsTrue (prop.IsImported, "#3"); var item = proj.GetItems ("X").FirstOrDefault (); Assert.IsNotNull (item, "#4"); Assert.AreEqual ("included.txt", item.EvaluatedInclude, "#5"); } finally { File.Delete (temp_file_name); } }
public void CheckReferences(string projectPath, IEnumerable <string> references, string framework) { using var projectCollection = new ProjectCollection(); var project = new MSBuildProject(Path.Combine(_projectPath, projectPath), new Dictionary <string, string>(), null, projectCollection); var targetFrameworksValue = project.GetProperty("TargetFrameworks")?.EvaluatedValue ?? project.GetPropertyValue("TargetFramework"); foreach (var targetFramework in targetFrameworksValue.Split(";", StringSplitOptions.RemoveEmptyEntries).Select(framework => framework.Trim())) { project.SetGlobalProperty("TargetFramework", targetFramework); project.ReevaluateIfNecessary(); var items = project.GetItems("ProjectReference"); var referenceItems = items.Select(item => item.EvaluatedInclude).Select(NormalizePaths); if (targetFramework == framework) { Assert.All(references, reference => Assert.Contains(reference, referenceItems)); Assert.All(references, reference => Assert.Equal("slnmerge", items.FirstOrDefault(item => NormalizePaths(item.EvaluatedInclude) == reference)?.GetMetadataValue("Origin"))); } else { Assert.All(references, reference => Assert.DoesNotContain(reference, referenceItems)); } } }
private string GetValue(bool finalValue, IList <ProjectConfig> configs, bool booleanValue) { MSBuild.Project buildProject = this.PerUser ? this.project.UserBuildProject : this.project.BuildProject; if (buildProject == null) { return(null); } string value; if (this.PerConfig) { if (configs == null || configs.Count == 0) { configs = new ProjectConfig[] { this.project.CurrentConfig }; } value = this.GetPerConfigValue(buildProject, finalValue, configs, booleanValue); } else { MSBuild.ProjectProperty buildProperty = buildProject.GetProperty(this.propertyName); value = this.GetBuildPropertyValue(buildProperty, finalValue); if (booleanValue && String.IsNullOrEmpty(value)) { value = Boolean.FalseString; } } return(value); }
public static ProjectProperty ThreadSafeGetProperty(this Microsoft.Build.Evaluation.Project thisp, string property) { lock (thisp) { return(thisp.GetProperty(property)); } }
public static ProjectProperty ShouldCountainProperty(this Project project, string name, string because = "", params object[] becauseArgs) { return(project.GetProperty(name) .Should() .NotBeNull(because, becauseArgs) .And .Subject .As <ProjectProperty>()); }
public static String GetProperty(Microsoft.Build.Evaluation.Project project, String name) { ProjectProperty property = project.GetProperty(name); if (property != null) { return(property.UnevaluatedValue); } return(String.Empty); }
public static IReadOnlyCollection <string> GetTargetFrameworks(this Microsoft.Build.Evaluation.Project project) { var targetFrameworkProperty = project.GetProperty("TargetFramework"); if (targetFrameworkProperty != null) { return new[] { targetFrameworkProperty.EvaluatedValue } } ; var targetFrameworksProperty = project.GetProperty("TargetFrameworks"); if (targetFrameworksProperty != null) { return(targetFrameworksProperty.EvaluatedValue.Split(';')); } return(new string[0]); } }
/// <summary> /// Looks for a matching global property. /// </summary> /// <remarks> /// The reason we do this and not just look at project.GlobalProperties is /// that when the project is being loaded, the GlobalProperties collection is already populated. When we do our /// evaluation, we may attempt to add some properties, such as environment variables, to the master Properties /// collection. As GlobalProperties are supposed to override these and thus be added last, we can't check against /// the GlobalProperties collection as they are being added. The correct behavior is to always check against the /// collection which is accumulating properties as we go, which is the Properties collection. Once the project has /// been fully populated, this method will also ensure that further properties do not attempt to override global /// properties, as those will have the global property flag set. /// </remarks> /// <param name="project">The project to compare with.</param> /// <param name="propertyName">The property name to look up</param> /// <returns>True if there is a matching global property, false otherwise.</returns> private static bool ProjectHasMatchingGlobalProperty(Project project, string propertyName) { ProjectProperty property = project.GetProperty(propertyName); if (property != null && property.IsGlobalProperty && !project.GlobalPropertiesToTreatAsLocal.Contains(propertyName)) { return(true); } return(false); }
#pragma warning disable VSTHRD100 // Avoid async void methods public async void OnProjectLoaded(Microsoft.Build.Evaluation.Project project, ProjectModel projectModel) #pragma warning restore VSTHRD100 // Avoid async void methods { try { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); if (projectModel.IsBSIPAProject) { BsipaProjectInSolution = true; } Microsoft.Build.Evaluation.Project userProj = null; try { userProj = EnvUtils.GetProject(project.FullPath + ".user"); if (userProj == null) { return; } } catch (InvalidOperationException) { return; } var installPath = BSMTSettingsManager.Instance.CurrentSettings.ChosenInstallPath; var projBeatSaberDir = project.GetPropertyValue("BeatSaberDir"); var userBeatSaberDir = userProj.GetPropertyValue("BeatSaberDir"); if (BSMTSettingsManager.Instance.CurrentSettings.GenerateUserFileOnExisting && !string.IsNullOrEmpty(BSMTSettingsManager.Instance.CurrentSettings.ChosenInstallPath) && projectModel.IsBSIPAProject) { Utilities.EnvUtils.SetReferencePaths(userProj, projectModel, project, null); if (!string.IsNullOrEmpty(userBeatSaberDir) && userBeatSaberDir != BSMTSettingsManager.Instance.CurrentSettings.ChosenInstallPath) { var prop = userProj.GetProperty("BeatSaberDir"); string message = $"Overriding BeatSaberDir in {projectModel.ProjectName} to \n{prop?.EvaluatedValue}\n(Old path: {userBeatSaberDir})"; VsShellUtilities.ShowMessageBox( this.package, message, $"{projectModel.ProjectName}: Auto Set BeatSaberDir", OLEMSGICON.OLEMSGICON_INFO, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST); } } } catch (Exception ex) { _ = Helpers.ShowErrorAsync("OnProjectLoaded", $"Error in OnProjectLoaded: {ex.Message}\n{ex}"); } }
/// <inheritdoc cref="IProject.GetPropertyValue"/> public string GetPropertyValue(string propertyName, bool raw) { var property = _MsProject.GetProperty(propertyName); if (property == null) { return(null); } if (raw) { return(property.UnevaluatedValue); } return(property.EvaluatedValue); }
public bool TryGetOutputDirectory(string configuration, string platform, out DirectoryInfo outputDirectory) { _evaluatedProject.SetGlobalProperty("Configuration", configuration); _evaluatedProject.SetGlobalProperty("Platform", platform); _evaluatedProject.ReevaluateIfNecessary(); var outputPathProperty = _evaluatedProject.GetProperty("OutputPath"); if (outputPathProperty != null) { var absolutePath = Path.Combine(Directory.FullName, outputPathProperty.EvaluatedValue); outputDirectory = new DirectoryInfo(absolutePath); return(true); } outputDirectory = null; return(false); }
/// <summary> /// Creates a DecisionTreeClassifier.exe from a decision tree, returning the file path of the new exe /// </summary> public static string CompileClassifier(TreeNode decisionTree) { var assemblyLocation = Assembly.GetExecutingAssembly().Location; var assemblyDirectory = new FileInfo(assemblyLocation).DirectoryName ?? ""; var classifierDir = Path.Combine(assemblyDirectory, "DecisionTreeClassifier"); var projFullPath = Path.Combine(classifierDir, "DecisionTreeClassifier.csproj"); var mainFullPath = Path.Combine(classifierDir, "Program.cs"); ReplaceSerializedTreeLine(mainFullPath, decisionTree); // load up the classifier project var proj = new Project(projFullPath); // set project to compile special DecisionTree config proj.SetProperty("Configuration", "DecisionTree"); // set the output path proj.SetProperty("DecisionTreeOutputPath", assemblyDirectory); // make a logger to catch possible build errors var logger = new SimpleBuildLogger(); // if we failed to build the classifier, we're screwed if (!proj.Build(logger)) { var sb = new StringBuilder(); sb.AppendLine("***************************************"); sb.AppendLine("**** Failed To Compile Classifier! ****"); sb.AppendLine("***************************************"); foreach (var error in logger.Errors) { sb.AppendLine(error.Message + " " + error.File + ": " + error.LineNumber); } throw new Exception(sb.ToString()); } // return the executable name var exeFileName = proj.GetProperty("AssemblyName").EvaluatedValue + ".exe"; return Path.Combine(assemblyDirectory, exeFileName); }
public void OnProjectLoaded(Microsoft.Build.Evaluation.Project project, ProjectModel projectModel) { if (projectModel.IsBSIPAProject) { BsipaProjectInSolution = true; } Microsoft.Build.Evaluation.Project userProj = null; try { userProj = EnvUtils.GetProject(project.FullPath + ".user"); if (userProj == null) { return; } } catch (InvalidOperationException) { return; } var installPath = BSMTSettingsManager.Instance.CurrentSettings.ChosenInstallPath; var projBeatSaberDir = project.GetPropertyValue("BeatSaberDir"); var userBeatSaberDir = userProj.GetPropertyValue("BeatSaberDir"); if (BSMTSettingsManager.Instance.CurrentSettings.GenerateUserFileOnExisting && !string.IsNullOrEmpty(BSMTSettingsManager.Instance.CurrentSettings.ChosenInstallPath) && projectModel.IsBSIPAProject) { Utilities.EnvUtils.SetReferencePaths(userProj, projectModel, project, null); if (!string.IsNullOrEmpty(userBeatSaberDir) && userBeatSaberDir != BSMTSettingsManager.Instance.CurrentSettings.ChosenInstallPath) { var prop = userProj.GetProperty("BeatSaberDir"); string message = $"Overriding BeatSaberDir in {projectModel.ProjectName} to \n{prop?.EvaluatedValue}\n(Old path: {userBeatSaberDir})"; VsShellUtilities.ShowMessageBox( this.package, message, $"{projectModel.ProjectName}: Auto Set BeatSaberDir", OLEMSGICON.OLEMSGICON_INFO, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST); } } }
public void Choose () { string project_xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <Choose> <When Condition="" '$(DebugSymbols)' != '' ""> <PropertyGroup> <DebugXXX>True</DebugXXX> </PropertyGroup> </When> <Otherwise> <PropertyGroup> <DebugXXX>False</DebugXXX> </PropertyGroup> </Otherwise> </Choose> </Project>"; var xml = XmlReader.Create (new StringReader (project_xml)); var root = ProjectRootElement.Create (xml); root.FullPath = "ProjectTest.Choose.proj"; var proj = new Project (root); var p = proj.GetProperty ("DebugXXX"); Assert.IsNotNull (p, "#1"); Assert.AreEqual ("False", p.EvaluatedValue, "#2"); }
static internal void MakeTemplateReplacements(bool isAProject, bool creatingProject, string rootNamespace, string sourceFileName, _BE.Project proj) { if (isAProject) { if (!string.IsNullOrEmpty(rootNamespace)) { _BE.ProjectProperty prop; string name; name = "StartupObject"; prop = proj.GetProperty(name); if (prop != null) { proj.SetProperty(name, prop.UnevaluatedValue.Replace(rootNamespace + ".", "$safeprojectname$.")); } name = "DocumentationFile"; prop = proj.GetProperty(name); if (prop != null) { proj.SetProperty(name, prop.UnevaluatedValue.Replace(rootNamespace + ".", "$safeprojectname$.")); } name = "RootNamespace"; prop = proj.GetProperty(name); if (prop != null) { proj.SetProperty(name, prop.UnevaluatedValue.Replace(rootNamespace, "$safeprojectname$")); } name = "AssemblyName"; prop = proj.GetProperty(name); if (prop != null) { proj.SetProperty(name, prop.UnevaluatedValue.Replace(rootNamespace, "$safeprojectname$")); } } } else { if (creatingProject == true) { //Exporting the entire project ... replace projectname only; this may not work as desired for Web projects, //we don't have any so we don't care. WordReplace(proj, rootNamespace, "$safeprojectname$"); } else { //Exporting a single item from a project. Replace root name space (if given) //and item name if (!string.IsNullOrEmpty(rootNamespace)) { WordReplace(proj, rootNamespace, "$rootnamespace$"); } string itemName = Path.GetFileNameWithoutExtension(sourceFileName); int iDotIndex = itemName.LastIndexOf("."); if (iDotIndex != -1) { //This is intended to fix the foo.designer.vb case (GetFileNameWithoutExtension() //returns foo.designer, and we want to replace just foo itemName = itemName.Substring(0, iDotIndex); } WordReplace(proj, itemName, "$safeitemname$"); } } }
public List<CsProjFile> GetProjects() { UnloadAllProjects(); var response = new List<CsProjFile>(); var files = new List<string>(); getCsProjFiles(ref files, SolutionFolder); foreach (var file in files) { var project = new Project(file); var name = Path.GetFileName(file).Replace(".csproj", ""); var csproj = new CsProjFile { AbsolutePath = file, GuidString = project.GetProperty("ProjectGuid").EvaluatedValue, Name = name, PathToSolution = @".." + Path.GetDirectoryName(file).ToLower().Replace(SolutionFolder.ToLower(), "") + @"\" + name + ".csproj" }; response.Add(csproj); } UnloadAllProjects(); return response; }
public void ChangeGlobalPropertyAfterReevaluation() { Project project = new Project(); project.SetGlobalProperty("p", "v1"); project.ReevaluateIfNecessary(); project.SetGlobalProperty("p", "v2"); Assert.Equal("v2", project.GetPropertyValue("p")); Assert.Equal(true, project.GetProperty("p").IsGlobalProperty); }
public void ExternallyMarkDirty() { Project project = new Project(); project.SetProperty("p", "v"); project.ReevaluateIfNecessary(); Assert.Equal(false, project.IsDirty); ProjectProperty property1 = project.GetProperty("p"); project.MarkDirty(); Assert.Equal(true, project.IsDirty); project.ReevaluateIfNecessary(); Assert.Equal(false, project.IsDirty); ProjectProperty property2 = project.GetProperty("p"); Assert.Equal(false, Object.ReferenceEquals(property1, property2)); // different object indicates reevaluation occurred }
public void RemoveProperty() { Project project = new Project(); int environmentPropertyCount = Helpers.MakeList(project.Properties).Count; project.SetProperty("p1", "v1"); project.ReevaluateIfNecessary(); project.RemoveProperty(project.GetProperty("p1")); string expected = ObjectModelHelpers.CleanupFileContents(@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"" />"); Helpers.VerifyAssertProjectContent(expected, project.Xml); Assert.Equal(null, project.GetProperty("p1")); ProjectInstance instance = project.CreateProjectInstance(); Assert.Equal(String.Empty, instance.GetPropertyValue("p1")); Assert.Equal(0, Helpers.Count(project.Properties) - environmentPropertyCount); }
public void SetPropertyImported() { Assert.Throws<InvalidOperationException>(() => { string file = null; try { file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile(); Project import = new Project(); import.SetProperty("p", "v0"); import.Save(file); ProjectRootElement xml = ProjectRootElement.Create(); xml.AddImport(file); Project project = new Project(xml); ProjectProperty property = project.GetProperty("p"); property.UnevaluatedValue = "v1"; } finally { File.Delete(file); } } ); }
private async Task CopyProjectToTemplateAsync(string projectFolder) { var from = Path.GetDirectoryName(_projectTemplateInfo.FileName); if (File.Exists(_projectTemplateInfo.DestinationFileName)) { //Debugger.Break(); return; } File.Copy(_projectTemplateInfo.FileName, _projectTemplateInfo.DestinationFileName); Project project = new Project(_projectTemplateInfo.DestinationFileName); var x = project.GetProperty("ProjectGuid"); x.UnevaluatedValue = "{$guid1$}"; x = project.GetProperty("RootNamespace"); var rootNamespace = x.EvaluatedValue; x.UnevaluatedValue = "$safeprojectname$"; x = project.GetProperty("AssemblyName"); x.UnevaluatedValue = "$safeprojectname$"; foreach (var item in project.Items.ToList()) { string newFileName = null; switch (item.ItemType) { case "ProjectReference": FixReference(item); break; case "Compile": case "None": case "Page": case "ApplicationDefinition": case "EmbeddedResource": case "Content": case "AppxManifest": case "Service": case "SDKReference": case "Resource": newFileName = CopyProjectItem(item, from, projectFolder); break; } if (string.IsNullOrWhiteSpace(newFileName)) { continue; } ProjectItemTemplateGenerator fileGenerator = null; var ext = Path.GetExtension(newFileName); switch (ext) { case ".cs": case ".config": fileGenerator = new CSFileGenerator(newFileName, rootNamespace, _projects); break; case ".xaml": fileGenerator = new XamlFileGenerator(newFileName, rootNamespace, _projects); break; } fileGenerator?.Process(); } project.Save(); }
public void PlatformPropertyEmptyByDefault () { 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 Project (root); Assert.IsNull (proj.GetProperty ("PLATFORM"), "#1"); }
public ProjectProperty GetProperty(string name) => _project.GetProperty(name);
void ImportAndPropertyOverrides (string label, string condition, string valueA, string valueB, string valueAPredecessor, bool existsC) { using (var ts = File.CreateText (temp_file_name)) ts.Write (import_overrides_test_imported); try { string xml = string.Format (import_overrides_test_xml, condition); var reader = XmlReader.Create (new StringReader (xml)); var root = ProjectRootElement.Create (reader); var proj = new Project (root); var a = proj.GetProperty ("A"); Assert.IsNotNull (a, label + "#2"); Assert.AreEqual (valueA, a.EvaluatedValue, label + "#3"); if (valueAPredecessor == null) Assert.IsNull (a.Predecessor, label + "#3.1"); else { Assert.IsNotNull (a.Predecessor, label + "#3.2"); Assert.AreEqual (valueAPredecessor, a.Predecessor.EvaluatedValue, label + "#3.3"); } var b = proj.GetProperty ("B"); Assert.IsNotNull (b, label + "#4"); Assert.AreEqual (valueB, b.EvaluatedValue, label + "#5"); var c = proj.GetProperty ("C"); // yes it can be retrieved. if (existsC) { Assert.IsNotNull (c, label + "#6"); Assert.AreEqual ("c", c.EvaluatedValue, label + "#7"); } else Assert.IsNull (c, label + "#8"); } finally { File.Delete (temp_file_name); } }
public void InvalidSetValueBuiltInProperty() { Project project = new Project(); ProjectProperty property = project.GetProperty("MSBuildProjectDirectory"); property.UnevaluatedValue = "v"; }
public void EvaluateMSBuildThisFileProperty () { string xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <PropertyGroup> <A>$(MSBuildThisFile)</A> </PropertyGroup> <Import Project='test_imported.proj' /> </Project>"; string imported = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <PropertyGroup> <B>$(MSBuildThisFile)</B> </PropertyGroup> </Project>"; using (var ts = File.CreateText (temp_file_name)) ts.Write (imported); try { var reader = XmlReader.Create (new StringReader (xml)); var root = ProjectRootElement.Create (reader); var proj = new Project (root); var a = proj.GetProperty ("A"); Assert.AreEqual (string.Empty, a.EvaluatedValue, "#1"); var b = proj.GetProperty ("B"); Assert.AreEqual (temp_file_name, b.EvaluatedValue, "#2"); var pi = new ProjectInstance (root); var ai = pi.GetProperty ("A"); Assert.AreEqual (string.Empty, ai.EvaluatedValue, "#3"); var bi = pi.GetProperty ("B"); Assert.AreEqual (temp_file_name, bi.EvaluatedValue, "#4"); } finally { File.Delete (temp_file_name); } }
public void IsReservedProperty() { Project project = new Project(); project.FullPath = @"c:\x"; project.ReevaluateIfNecessary(); Assert.Equal(false, project.GetProperty("MSBuildProjectFile").IsEnvironmentProperty); Assert.Equal(false, project.GetProperty("MSBuildProjectFile").IsGlobalProperty); Assert.Equal(true, project.GetProperty("MSBuildProjectFile").IsReservedProperty); Assert.Equal(false, project.GetProperty("MSBuildProjectFile").IsImported); }
public static string GetProperty(Microsoft.Build.Evaluation.Project project, string name) { ProjectProperty property = project.GetProperty(name); return(property != null ? property.UnevaluatedValue : string.Empty); }
/// <summary> /// Get the property named "p" in the project provided /// </summary> private static ProjectProperty GetFirstProperty(string content) { ProjectRootElement projectXml = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); Project project = new Project(projectXml); ProjectProperty property = project.GetProperty("p"); return property; }
public void ProjectFactoryAppliesGlobalProperties() { // Arrange var testAssembly = Assembly.GetExecutingAssembly(); var projectXml = @"<?xml version=""1.0"" encoding=""utf-8""?> <Project ToolsVersion=""4.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <PropertyGroup> <ProjectGuid>{F879F274-EFA0-4157-8404-33A19B4E6AEC}</ProjectGuid> <OutputType>Library</OutputType> <RootNamespace>NuGet.Test</RootNamespace> <AssemblyName>" + testAssembly.GetName().Name + @"</AssemblyName> <TargetFrameworkProfile Condition="" '$(TargetFrameworkVersion)' == 'v4.0' "">Client</TargetFrameworkProfile> <OutputPath>.</OutputPath> <!-- Force it to look for the assembly in the base path --> </PropertyGroup> <ItemGroup> <Compile Include=""..\..\Dummy.cs""> <Link>Dummy.cs</Link> </Compile> </ItemGroup> <Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" /> <Import Project=""C:\DoesNotExist.targets"" Condition="" '$(MyGlobalProperty)' != 'true' "" /> </Project>"; // Set base path to the currently assembly's folder so that it will find the test assembly var basePath = Path.GetDirectoryName(testAssembly.CodeBase); var cmdLineProperties = new Dictionary<string, string> { { "MyGlobalProperty", "true" } }; var project = new Project(XmlReader.Create(new StringReader(projectXml)), cmdLineProperties, null); project.FullPath = Path.Combine(project.DirectoryPath, "test.csproj"); // Act var factory = new ProjectFactory(project) { Build = false }; factory.ProjectProperties.Add("MyGlobalProperty", "false"); // This shouldn't be applied factory.ProjectProperties.Add("TestProperty", "true"); // This should be applied var packageBuilder = factory.CreateBuilder(basePath); // Assert Assert.True(project.GetProperty("MyGlobalProperty").IsGlobalProperty); Assert.False(project.GetProperty("TestProperty").IsGlobalProperty); Assert.Equal("true", project.GetProperty("MyGlobalProperty").UnevaluatedValue, StringComparer.OrdinalIgnoreCase); Assert.Equal("true", project.GetProperty("TestProperty").UnevaluatedValue, StringComparer.OrdinalIgnoreCase); }
public void RemovePropertyWithSibling() { Project project = new Project(); project.SetProperty("p1", "v1"); project.SetProperty("p2", "v2"); project.ReevaluateIfNecessary(); project.RemoveProperty(project.GetProperty("p1")); string expected = ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace""> <PropertyGroup> <p2>v2</p2> </PropertyGroup> </Project>"); Helpers.VerifyAssertProjectContent(expected, project.Xml); }
//private void UnzipShell() //{ // var shell = new Shell(); // var srcFlder = shell.NameSpace(Paths.MooegeDownloadPath); // var destFlder = shell.NameSpace(Paths.RepositoriesPath); // var items = srcFlder.Items(); // destFlder.CopyHere(items, 20); //} private bool Compile() { LocalRevision = LastRevision; var path = Path.Combine(Paths.RepositoriesPath, Name, "src", "Mooege", "Mooege-VS2010.csproj"); var project = new Project(path); project.SetProperty("Configuration", Configuration.MadCow.CompileAsDebug ? "Debug" : "Release"); project.SetProperty("Platform", "x86"); //project.SetProperty("OutputPath", Path.Combine(Paths.RepositoriesPath, Name, "compiled")); //project.SetProperty("TargetDir", Path.Combine(Paths.RepositoriesPath, Name, "compiled")); project.SetProperty("OutDir", Path.Combine(Paths.RepositoriesPath, Name, "compiled")); var p = project.GetProperty("OutputPath"); return project.Build(new FileLogger()); }
/// <summary> /// Check the items and properties from the sample project /// </summary> private void VerifyContentOfSampleProject(Project project) { Assert.Equal("v2", project.GetProperty("p").UnevaluatedValue); Assert.Equal("Xv2", project.GetProperty("p2").EvaluatedValue); Assert.Equal("X$(p)", project.GetProperty("p2").UnevaluatedValue); IList<ProjectItem> items = Helpers.MakeList(project.GetItems("i")); Assert.Equal(3, items.Count); Assert.Equal("i1", items[0].EvaluatedInclude); Assert.Equal("v2X", items[1].EvaluatedInclude); Assert.Equal("$(p)X;i3", items[1].UnevaluatedInclude); Assert.Equal("i3", items[2].EvaluatedInclude); }
public static async Task <Project> CreateAsync(string filepath, Solution parent, IOutputWriter outputWriter) { filepath = Path.GetFullPath(filepath, Path.GetDirectoryName(parent.Filepath)); if (!File.Exists(filepath)) { throw new FileReadException(FileReadExceptionType.Csproj, filepath, parent.Filepath); } using var projectCollection = new ProjectCollection(); var msbuildProject = new Microsoft.Build.Evaluation.Project(filepath, new Dictionary <string, string>(), null, projectCollection, ProjectLoadSettings.IgnoreInvalidImports | ProjectLoadSettings.IgnoreMissingImports); var usingSdk = msbuildProject.Properties.FirstOrDefault(prop => prop.Name == "UsingMicrosoftNETSdk")?.EvaluatedValue.Equals("true", StringComparison.InvariantCultureIgnoreCase) ?? false; var targetFrameworks = Array.Empty <string>(); if (usingSdk) { targetFrameworks = msbuildProject.GetProperty("TargetFrameworks") switch { ProjectProperty pp => pp.EvaluatedValue.Split(';', StringSplitOptions.RemoveEmptyEntries).Select(val => val.Trim()).ToArray(), null => new[] { msbuildProject.GetPropertyValue("TargetFramework") } }; } else { targetFrameworks = new[] { msbuildProject.GetPropertyValue("TargetFrameworkVersion") .Replace("v", "net") .Replace(".", "") }; } var packageReferences = new Dictionary <string, Reference>(); var projectReferences = new Dictionary <string, Reference>(); foreach (var targetFramework in targetFrameworks) { msbuildProject.SetGlobalProperty("TargetFramework", targetFramework); msbuildProject.ReevaluateIfNecessary(); foreach (var include in GetItems(msbuildProject, "PackageReference")) { if (!packageReferences.TryGetValue(include, out var reference)) { reference = new Reference { Include = include }; packageReferences.Add(include, reference); } reference.Frameworks.Add(targetFramework); } foreach (var item in msbuildProject.GetItems("ProjectReference")) { var include = ConvertPathSeparators(item.EvaluatedInclude); if (!projectReferences.TryGetValue(include, out var reference)) { reference = new Reference { Include = include, Origin = item.GetMetadataValue("Origin") }; projectReferences.Add(include, reference); } reference.Frameworks.Add(targetFramework); } } var packageId = await GetPackageId(filepath, msbuildProject); return(new Project(filepath, packageId, packageReferences.Values.ToList(), projectReferences.Values.ToList(), targetFrameworks, outputWriter, parent, !usingSdk)); }
public static bool UpgradeProjectProperties(Microsoft.Build.Evaluation.Project project, bool cpp) { bool modified = false; string outputDir = null; string headerOutputDir = null; string baseDirectoryForGeneratedInclude = null; string value = project.GetProperty(PropertyNames.Old.OutputDir, false); if (!string.IsNullOrEmpty(value)) { project.RemovePropertyWithName(PropertyNames.Old.OutputDir); value = value.Replace("$(IceBuilder", "%("); project.SetItemMetadata(ItemMetadataNames.OutputDir, value); modified = true; outputDir = value; } else if (cpp) { // The default output directory for C++ generated items was changed to $(IntDir) // but we keep the old default when converted projects by setting it in the project // file project.SetItemMetadata(ItemMetadataNames.OutputDir, "generated"); } value = project.GetProperty(PropertyNames.Old.IncludeDirectories, false); if (!string.IsNullOrEmpty(value)) { project.RemovePropertyWithName(PropertyNames.Old.IncludeDirectories); value = value.Replace("$(IceHome)\\slice", ""); value = value.Replace("$(IceHome)/slice", ""); value = value.Trim(';'); value = value.Replace("$(IceBuilder", "%("); if (!string.IsNullOrEmpty(value)) { project.SetItemMetadata(ItemMetadataNames.IncludeDirectories, value); } modified = true; } value = project.GetProperty(PropertyNames.Old.HeaderOutputDir, false); if (!string.IsNullOrEmpty(value)) { project.RemovePropertyWithName(PropertyNames.Old.HeaderOutputDir); value = value.Replace("$(IceBuilder", "%("); project.SetItemMetadata(ItemMetadataNames.HeaderOutputDir, value); modified = true; headerOutputDir = value; } value = project.GetProperty(PropertyNames.Old.HeaderExt, false); if (!string.IsNullOrEmpty(value)) { project.RemovePropertyWithName(PropertyNames.Old.HeaderExt); project.SetItemMetadata(ItemMetadataNames.HeaderExt, value); modified = true; } value = project.GetProperty(PropertyNames.Old.BaseDirectoryForGeneratedInclude, false); if (!string.IsNullOrEmpty(value)) { project.RemovePropertyWithName(PropertyNames.Old.BaseDirectoryForGeneratedInclude); project.SetItemMetadata(ItemMetadataNames.BaseDirectoryForGeneratedInclude, value); modified = true; baseDirectoryForGeneratedInclude = value; } value = project.GetProperty(PropertyNames.Old.SourceExt, false); if (!string.IsNullOrEmpty(value)) { project.RemovePropertyWithName(PropertyNames.Old.SourceExt); project.SetItemMetadata(ItemMetadataNames.SourceExt, value); modified = true; } value = project.GetProperty(PropertyNames.Old.AllowIcePrefix, false); string additionalOptions = project.GetProperty(PropertyNames.Old.AdditionalOptions, false); if (!string.IsNullOrEmpty(additionalOptions)) { project.RemovePropertyWithName(PropertyNames.Old.AdditionalOptions); modified = true; } if (!string.IsNullOrEmpty(value)) { if (value.Equals("yes", StringComparison.CurrentCultureIgnoreCase) || value.Equals("true", StringComparison.CurrentCultureIgnoreCase)) { additionalOptions = String.Format("{0} --ice", additionalOptions).Trim(); } project.RemovePropertyWithName(PropertyNames.Old.AllowIcePrefix); modified = true; } value = project.GetProperty(PropertyNames.Old.Underscore, false); if (!string.IsNullOrEmpty(value)) { if (value.Equals("yes", StringComparison.CurrentCultureIgnoreCase) || value.Equals("true", StringComparison.CurrentCultureIgnoreCase)) { additionalOptions = String.Format("{0} --underscore", additionalOptions).Trim(); } project.RemovePropertyWithName(PropertyNames.Old.Underscore); modified = true; } value = project.GetProperty(PropertyNames.Old.Stream, false); if (!string.IsNullOrEmpty(value)) { if (value.Equals("yes", StringComparison.CurrentCultureIgnoreCase) || value.Equals("true", StringComparison.CurrentCultureIgnoreCase)) { additionalOptions = String.Format("{0} --stream ", additionalOptions).Trim(); } project.RemovePropertyWithName(PropertyNames.Old.Stream); modified = true; } value = project.GetProperty(PropertyNames.Old.DLLExport, false); if (!string.IsNullOrEmpty(value)) { additionalOptions = String.Format("{0} --dll-export {1}", additionalOptions, value).Trim(); project.RemovePropertyWithName(PropertyNames.Old.DLLExport); modified = true; } value = project.GetProperty(PropertyNames.Old.Checksum, false); if (!string.IsNullOrEmpty(value)) { additionalOptions = String.Format("{0} --checksum", additionalOptions).Trim(); project.RemovePropertyWithName(PropertyNames.Old.Checksum); modified = true; } value = project.GetProperty(PropertyNames.Old.Tie, false); if (!string.IsNullOrEmpty(value)) { additionalOptions = String.Format("{0} --tie", additionalOptions).Trim(); project.RemovePropertyWithName(PropertyNames.Old.Tie); modified = true; } if (!string.IsNullOrEmpty(additionalOptions)) { additionalOptions = additionalOptions.Replace("IceBuilder", "SliceCompile"); project.SetItemMetadata(ItemMetadataNames.AdditionalOptions, additionalOptions); } if (string.IsNullOrEmpty(baseDirectoryForGeneratedInclude)) { if (!string.IsNullOrEmpty(headerOutputDir)) { project.SetClCompileAdditionalIncludeDirectories(headerOutputDir); } else { project.SetClCompileAdditionalIncludeDirectories(outputDir); } } value = project.GetProperty("ProjectTypeGuids", false); if (!string.IsNullOrEmpty(value)) { value = value.Replace(Package.IceBuilderOldFlavor, Package.IceBuilderNewFlavor); project.SetProperty("ProjectTypeGuids", value, ""); modified = true; } return(modified); }
public void InvalidSetValueBuiltInProperty() { Assert.Throws<InvalidOperationException>(() => { Project project = new Project(); ProjectProperty property = project.GetProperty("MSBuildProjectDirectory"); property.UnevaluatedValue = "v"; } ); }
public void EvaluationOrderPropertiesPrecedesItems () { string project_xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ItemGroup> <Bar Include='$(Foo)' /> </ItemGroup> <PropertyGroup> <Foo Condition=""'A;B'=='A;B'"">'A;B'</Foo> </PropertyGroup> </Project>"; var xml = XmlReader.Create (new StringReader (project_xml)); var root = ProjectRootElement.Create (xml); var proj = new Project (root); // at this state property is parsed without error i.e. Condition evaluates fine. var prop = proj.GetProperty ("Foo"); Assert.AreEqual ("'A;B'", prop.EvaluatedValue, "#1"); var items = proj.GetItems ("Bar"); Assert.AreEqual ("'A", items.First ().EvaluatedInclude, "#2"); Assert.AreEqual ("$(Foo)", items.First ().UnevaluatedInclude, "#3"); Assert.AreEqual (2, items.Count, "#4"); Assert.AreEqual ("B'", items.Last ().EvaluatedInclude, "#5"); Assert.AreEqual ("$(Foo)", items.Last ().UnevaluatedInclude, "#6"); Assert.IsTrue (items.First ().Xml == items.Last ().Xml, "#7"); }
public void SetValueEnvironmentProperty() { Project project = new Project(); ProjectProperty property = project.GetProperty("Username"); property.UnevaluatedValue = "v"; Assert.Equal("v", property.EvaluatedValue); Assert.Equal("v", property.UnevaluatedValue); project.ReevaluateIfNecessary(); property = project.GetProperty("Username"); Assert.Equal("v", property.UnevaluatedValue); }
public void IsEnvironmentVariable() { Project project = new Project(); Assert.Equal(true, project.GetProperty("username").IsEnvironmentProperty); Assert.Equal(false, project.GetProperty("username").IsGlobalProperty); Assert.Equal(false, project.GetProperty("username").IsReservedProperty); Assert.Equal(false, project.GetProperty("username").IsImported); }
public void IsGlobalProperty() { Dictionary<string, string> globalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); globalProperties["g"] = String.Empty; Project project = new Project(globalProperties, null, ProjectCollection.GlobalProjectCollection); Assert.Equal(false, project.GetProperty("g").IsEnvironmentProperty); Assert.Equal(true, project.GetProperty("g").IsGlobalProperty); Assert.Equal(false, project.GetProperty("g").IsReservedProperty); Assert.Equal(false, project.GetProperty("g").IsImported); }
/// <summary> /// Gets the test property. /// </summary> /// <param name="project">The test project.</param> /// <returns>The test property.</returns> private ProjectProperty GetProperty(Project project) { ProjectProperty property = project.GetProperty(PropertyName); Assert.AreEqual(importFilename, property.Xml.ContainingProject.FullPath, "Property was not found in the imported project."); Assert.IsTrue(property.IsImported, "IsImported property was not set."); return property; }
/// <summary> /// Gets the test property. /// </summary> /// <param name="project">The test project.</param> /// <returns>The test property.</returns> private ProjectProperty GetProperty(Project project) { ProjectProperty property = project.GetProperty(PropertyName); Assert.Equal(_importFilename, property.Xml.ContainingProject.FullPath); // "Property was not found in the imported project." Assert.True(property.IsImported); // "IsImported property was not set." return property; }