public Project(Solution solution, string title, string fileName) { AssembliesResolved = false; ReferencedAssemblies = new List<string>(); CompilerSettings = new CompilerSettings(); ReferencedProjects = new List<string>(); Files = new List<File>(); Solution = solution; Title = title; FileName = Path.GetFullPath(fileName); ProjectCollection.GlobalProjectCollection.UnloadAllProjects(); MsBuildProject = new Microsoft.Build.Evaluation.Project(fileName); AssemblyName = MsBuildProject.GetPropertyValue("AssemblyName"); CompilerSettings.AllowUnsafeBlocks = MsBuildProject.GetPropertyAsBoolean("AllowUnsafeBlocks"); CompilerSettings.CheckForOverflow = MsBuildProject.GetPropertyAsBoolean("CheckForOverflowUnderflow"); var defineConstants = MsBuildProject.GetPropertyValue("DefineConstants"); foreach (string symbol in defineConstants.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { CompilerSettings.ConditionalSymbols.Add(symbol.Trim()); } foreach (var sourceCodeFile in MsBuildProject.GetItems("Compile")) { Files.Add(new File(this, Path.Combine(MsBuildProject.DirectoryPath, sourceCodeFile.EvaluatedInclude))); } foreach (var projectReference in MsBuildProject.GetItems("ProjectReference")) { string referencedFileName = Path.GetFullPath(Path.Combine(MsBuildProject.DirectoryPath, projectReference.EvaluatedInclude)); ReferencedProjects.Add(referencedFileName); } }
public Project(Solution solution, string title, string fileName) { AssembliesResolved = false; ReferencedAssemblies = new List <string>(); CompilerSettings = new CompilerSettings(); ReferencedProjects = new List <string>(); Files = new List <File>(); Solution = solution; Title = title; FileName = Path.GetFullPath(fileName); ProjectCollection.GlobalProjectCollection.UnloadAllProjects(); MsBuildProject = new Microsoft.Build.Evaluation.Project(fileName); AssemblyName = MsBuildProject.GetPropertyValue("AssemblyName"); CompilerSettings.AllowUnsafeBlocks = MsBuildProject.GetPropertyAsBoolean("AllowUnsafeBlocks"); CompilerSettings.CheckForOverflow = MsBuildProject.GetPropertyAsBoolean("CheckForOverflowUnderflow"); var defineConstants = MsBuildProject.GetPropertyValue("DefineConstants"); foreach (string symbol in defineConstants.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { CompilerSettings.ConditionalSymbols.Add(symbol.Trim()); } foreach (var sourceCodeFile in MsBuildProject.GetItems("Compile")) { Files.Add(new File(this, Path.Combine(MsBuildProject.DirectoryPath, sourceCodeFile.EvaluatedInclude))); } foreach (var projectReference in MsBuildProject.GetItems("ProjectReference")) { string referencedFileName = Path.GetFullPath(Path.Combine(MsBuildProject.DirectoryPath, projectReference.EvaluatedInclude)); ReferencedProjects.Add(referencedFileName); } }
public static MSbuildResult BuildProject(MsBuildSettings settings, string projectFileName, DirectoryInfo dir) { var result = new MSbuildResult(); var path = Path.Combine(dir.FullName, projectFileName); var project = new Project(path, null, null, new ProjectCollection()); project.SetProperty("CscToolPath", settings.CompilerDirectory.FullName); var includes = new HashSet<string>( project.AllEvaluatedItems .Where(i => i.ItemType == "None" || i.ItemType == "Content") .Select(i => Path.GetFileName(i.EvaluatedInclude.ToLowerInvariant()))); foreach (var dll in settings.WellKnownLibsDirectory.GetFiles("*.dll")) if (!includes.Contains(dll.Name.ToLowerInvariant())) project.AddItem("None", dll.FullName); project.Save(); using (var stringWriter = new StringWriter()) { var logger = new ConsoleLogger(LoggerVerbosity.Minimal, stringWriter.Write, color => { }, () => { }); result.Success = SyncBuild(project, logger); if (result.Success) result.PathToExe = Path.Combine(project.DirectoryPath, project.GetPropertyValue("OutputPath"), project.GetPropertyValue("AssemblyName") + ".exe"); else result.ErrorMessage = stringWriter.ToString(); return result; } }
static void AddSolutionConfiguration(string projectFile, Dictionary<string, string> properties) { var collection = new ProjectCollection(properties); var toolsVersion = default(string); var project = new Project(projectFile, properties, toolsVersion, collection); var config = project.GetPropertyValue("Configuration"); var platform = project.GetPropertyValue("Platform"); var xml = new XElement("SolutionConfiguration"); xml.Add(new XElement("ProjectConfiguration", new XAttribute("Project", project.GetPropertyValue("ProjectGuid")), new XAttribute("AbsolutePath", project.FullPath), new XAttribute("BuildProjectInSolution", "true")) { Value = $"{config}|{platform}" }); foreach (var reference in GetProjectReferences(project)) { xml.Add(new XElement("ProjectConfiguration", new XAttribute("Project", reference.GetPropertyValue("ProjectGuid")), new XAttribute("AbsolutePath", reference.FullPath), new XAttribute("BuildProjectInSolution", "false")) { Value = $"{config}|{platform}" }); } properties["CurrentSolutionConfigurationContents"] = xml.ToString(SaveOptions.None); }
private ArrayList GetProjectReferences(string slnFilePath, ref string csprojFilePath) { ArrayList refList = new ArrayList(); csprojFilePath = FindProject(slnFilePath, slnFilePath.Substring(slnFilePath.LastIndexOf(@"\") + 1)); // Load the csproj file using msbuild and get the list of added references. // We need this list to generate the list of pe files. _BE.Project prj = new _BE.Project(csprojFilePath); char[] splitChar = { ',' }; foreach (_BE.ProjectItem item in prj.GetItems("Reference")) { string[] referenceItem = item.EvaluatedInclude.Split(splitChar, StringSplitOptions.RemoveEmptyEntries); if (!refList.Contains(referenceItem[0].Trim())) { refList.Add(referenceItem[0].Trim()); } if (item.HasMetadata("HintPath")) { string hint = item.GetMetadataValue("HintPath"); RecurseProjDep(hint, ref refList); } else { string output = Environment.GetEnvironmentVariable("BUILD_TREE_CLIENT") + "\\dll\\" + referenceItem[0] + ".dll"; if (File.Exists(output)) { RecurseProjDep(output, ref refList); } } } // Set the assembly name. m_assemblyName = prj.GetPropertyValue("AssemblyName"); // Determine if the test is a desktop test. string value = prj.GetPropertyValue("ProjectTypeGuids"); m_currentAppType = string.IsNullOrEmpty(value) ? TestType.Desktop:TestType.Device; // Determine the desktop app if this is a device-desktop test. foreach (_BE.ProjectItem item in prj.Items) { if (item.ItemType.ToLower().Contains("content")) { m_desktopXmlFile = item.EvaluatedInclude; m_currentAppType = TestType.DeviceDesktop; } } return(refList); }
private bool IsApplication(Microsoft.Build.Evaluation.Project project) { var isAndroidApp = project.GetPropertyValue("AndroidApplication")?.Equals("true", StringComparison.OrdinalIgnoreCase) ?? false; var isiOSApp = project.GetPropertyValue("ProjectTypeGuids")?.Equals("{FEACFBD2-3405-455C-9665-78FE426C6842};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}", StringComparison.OrdinalIgnoreCase) ?? false; var ismacOSApp = project.GetPropertyValue("ProjectTypeGuids")?.Equals("{A3F8F2AB-B479-4A4A-A458-A89E7DC349F1};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}", StringComparison.OrdinalIgnoreCase) ?? false; var isExe = project.GetPropertyValue("OutputType")?.Equals("Exe", StringComparison.OrdinalIgnoreCase) ?? false; var isWasm = project.GetPropertyValue("WasmHead")?.Equals("true", StringComparison.OrdinalIgnoreCase) ?? false; return(isAndroidApp || (isiOSApp && isExe) || (ismacOSApp && isExe) || isWasm); }
public static FileInfo GetOutputFile(this Project project, string ext = ".dll") { var e = project.GetPropertyValue("TargetExt") ?? ext; if (e == "*Undefined*") { e = ext; } var outputPath = project.GetOutputPath(); var assemblyName = project.GetPropertyValue("AssemblyName") + e; return(new FileInfo(Path.Combine(Path.GetDirectoryName(project.FullPath), outputPath, assemblyName))); }
public static ProcessStartInfo GetExecutable(this Project project) { var userProject = project.FindUserProject(); var startupAction = userProject?.Xml.GetPropertyValue("StartAction"); if (!string.IsNullOrEmpty(startupAction)) { var exe = userProject.Xml.GetPropertyValue("StartProgram"); var args = userProject.Xml.GetPropertyValue("StartArguments"); if (File.Exists(exe)) { return(new ProcessStartInfo(exe, args)); } } startupAction = project.GetPropertyValue("StartAction"); if (!string.IsNullOrEmpty(startupAction)) { var exe = project.GetPropertyValue("StartProgram"); var args = project.GetPropertyValue("StartArguments"); if (File.Exists(exe)) { return(new ProcessStartInfo(exe, args)); } } var startupObject = project.GetPropertyValue("StartupObject"); if (!string.IsNullOrEmpty(startupObject) && File.Exists(startupObject)) { return(new ProcessStartInfo(startupObject, string.Empty)); } var outputFile = Check.TryCatch <FileInfo, Exception>(() => project.GetOutputFile(".exe")); if (outputFile != null && outputFile.Extension == ".exe" && outputFile.Exists) { return(new ProcessStartInfo(outputFile.FullName, string.Empty)); } //else //{ // string path = project.GetPropertyValue("OutputPath"); // if (!string.IsNullOrEmpty(path)) // { // } //} return(null); }
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 string GetEvaluatedProperty(string propertyName) { string originalPropertyName = propertyName; if (overloadedProperties.ContainsKey(propertyName)) { return(overloadedProperties[propertyName] as string); } string propertyValue = null; if (m_project != null) { propertyValue = m_project.GetPropertyValue(propertyName); } if (!string.IsNullOrEmpty(propertyValue)) { BuildTaskUtility.RegexProperties( ref propertyValue, PropertyMatch); } return(propertyValue); }
public static bool GetPropertyAsBoolean(this MSBuild.Project project, string propertyName) { var propertyValue = project.GetPropertyValue(propertyName); bool boolCastResult; return(bool.TryParse(propertyValue, out boolCastResult) ? true : false); }
public static string GetOutputFilePath(Project project) { if (project != null) { string extension = project.GetPropertyValue("OutputType").ToLower() == "exe" ? ".exe" : (project.GetPropertyValue("OutputType").ToLower() == "library" ? ".dll" : string.Empty); string pathDir = Path.GetDirectoryName(project.FullPath); if (!string.IsNullOrWhiteSpace(extension) && !string.IsNullOrWhiteSpace(pathDir)) { return(Path.Combine(pathDir, project.GetPropertyValue("OutputPath")) + (project.GetPropertyValue("AssemblyName") + extension)); } } return(string.Empty); }
public bool IsPackagingTargetsInstalled(string projectFilePath) { var loggers = new IMSBuildLogger[] { new ConsoleLogger(LoggerVerbosity.Quiet) }; var project = new MSBuild.Project(projectFilePath); if (!project.Build("Restore", loggers)) { Console.Error.WriteLine($"Failed to restore '{Path.GetFileName(projectFilePath)}'. Please run dotnet restore, and try again."); return(false); } var projectAssetsPath = project.GetPropertyValue("ProjectAssetsFile"); // NuGet has a LockFileUtilities.GetLockFile API which provides direct access to this file format, // but loading NuGet in the same process as MSBuild creates dependency conflicts. LockFile lockFile = null; using (StreamReader reader = File.OpenText(projectAssetsPath)) using (JsonReader jsonReader = new JsonTextReader(reader)) { JsonSerializer serializer = new JsonSerializer(); lockFile = serializer.Deserialize <LockFile>(jsonReader); } if (!lockFile.Libraries.Any(l => l.Key.StartsWith("Packaging.Targets/"))) { Console.Error.WriteLine($"The project '{Path.GetFileName(projectFilePath)}' doesn't have a PackageReference to Packaging.Targets."); Console.Error.WriteLine($"Please run 'dotnet {this.commandName} install', and try again."); return(false); } return(true); }
public static string ThreadSafeGetPropertyValue(this Microsoft.Build.Evaluation.Project thisp, string property) { lock (thisp) { return(thisp.GetPropertyValue(property)); } }
public static Guid GetProjectGuid(Microsoft.Build.Evaluation.Project project) { if (project == null) { throw new ArgumentNullException("project"); } return(Guid.Parse(project.GetPropertyValue("ProjectGuid"))); }
public IReadOnlyList <string> GetMsBuildPropertyValues(string propertyName) { ProjectCollection projectCollection = new ProjectCollection(); Microsoft.Build.Evaluation.Project project = projectCollection.LoadProject(_hierarchy.GetProjectFullPath()); string[] propertyValues = project.GetPropertyValue(propertyName)?.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries); return(propertyValues != null?propertyValues.ToList() : null); }
private Project LoadAndInitProject(CSharpSolution solution, string fileName) { var globalProperties = new Dictionary<string, string>(); globalProperties.Add("SolutionDir", solution.Directory); var msbuildProject = new Project(fileName, globalProperties, null, ProjectCollection.GlobalProjectCollection, ProjectLoadSettings.IgnoreMissingImports); AssemblyName = msbuildProject.GetPropertyValue("AssemblyName"); CompilerSettings.AllowUnsafeBlocks = GetBoolProperty(msbuildProject, "AllowUnsafeBlocks") ?? false; CompilerSettings.CheckForOverflow = GetBoolProperty(msbuildProject, "CheckForOverflowUnderflow") ?? false; var defineConstants = msbuildProject.GetPropertyValue("DefineConstants"); foreach (var symbol in defineConstants.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries)) CompilerSettings.ConditionalSymbols.Add(symbol.Trim()); return msbuildProject; }
private string GetKeyFile(Build.Project project, string outputPath) { string keyFilePath = project.GetPropertyValue("AssemblyOriginatorKeyFile"); if (string.IsNullOrEmpty(keyFilePath)) { return(null); } return(PathUtils.MakeAbsolutePath(keyFilePath, outputPath)); }
/// <summary> /// Retrives the list of project guids from the project file. /// If you don't want your project to be flavorable, override /// to only return your project factory Guid: /// return this.GetType().GUID.ToString("B"); /// </summary> /// <param name="file">Project file to look into to find the Guid list</param> /// <returns>List of semi-colon separated GUIDs</returns> protected override string ProjectTypeGuids(string file) { // Load the project so we can extract the list of GUIDs this.buildProject = Utilities.ReinitializeMsBuildProject(this.buildEngine, file, this.buildProject); // Retrieve the list of GUIDs, if it is not specify, make it our GUID string guids = buildProject.GetPropertyValue(ProjectFileConstants.ProjectTypeGuids); if(String.IsNullOrEmpty(guids)) guids = this.GetType().GUID.ToString("B"); return guids; }
static bool?GetBoolProperty(Microsoft.Build.Evaluation.Project p, string propertyName) { string val = p.GetPropertyValue(propertyName); bool result; if (bool.TryParse(val, out result)) { return(result); } else { return(null); } }
public ProjectFactory(Project project) { _project = project; ProjectProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); AddSolutionDir(); _settings = null; // Get the target framework of the project string targetFrameworkMoniker = _project.GetPropertyValue("TargetFrameworkMoniker"); if (!String.IsNullOrEmpty(targetFrameworkMoniker)) { TargetFramework = new FrameworkName(targetFrameworkMoniker); } }
private bool IsSilverlightApplication(Microsoft.Build.Evaluation.Project project) { if (project == null) { return(false); } string propertyValue = project.GetPropertyValue("SilverlightApplication"); if (propertyValue == null) { return(false); } return(propertyValue.Equals("true", StringComparison.OrdinalIgnoreCase)); }
#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}"); } }
/// <summary> /// Gets the value from current project. /// </summary> /// <param name="sharePointProject">The share point project.</param> /// <param name="projectPropertyName">Name of the project property.</param> /// <returns></returns> public static List <string> GetValueFromCurrentProject(ISharePointProject sharePointProject, string projectPropertyName) { List <string> value = null; Microsoft.Build.Evaluation.Project project = GetCurrentProject(sharePointProject.FullPath); if (project != null) { string rawValue = project.GetPropertyValue(projectPropertyName); if (!String.IsNullOrEmpty(rawValue)) { value = rawValue.Split(';').ToList(); } } return(value); }
private bool GetBoolProperty(Build.Project project, string name) { string s = project.GetPropertyValue(name); if (string.IsNullOrEmpty(s)) { return(false); } bool result; if (!bool.TryParse(s, out result)) { return(false); } return(true); }
private static T?GetEnumFromProperty <T>(Microsoft.Build.Evaluation.Project project, string propertyName) where T : struct { if (project == null) { throw new ArgumentNullException("project"); } if (propertyName == null) { throw new ArgumentNullException("propertyName"); } var value = project.GetPropertyValue(propertyName); if (string.IsNullOrEmpty(value)) { return(null); } return((T)Enum.Parse(typeof(T), value)); }
public bool IsPackagingTargetsInstalled() { var projectFilePath = Directory.GetFiles(Environment.CurrentDirectory, "*.csproj").SingleOrDefault(); if (projectFilePath == null) { Console.Error.WriteLine($"Failed to find a .csproj file in '{Environment.CurrentDirectory}'. dotnet {this.commandName} only works if"); Console.Error.WriteLine($"you have exactly one .csproj file in your directory. For advanced scenarios, please use 'dotnet msbuild /t:{this.msbuildTarget}'"); return(false); } var loggers = new IMSBuildLogger[] { new ConsoleLogger(LoggerVerbosity.Quiet) }; var project = new MSBuild.Project(projectFilePath); if (!project.Build("Restore", loggers)) { Console.Error.WriteLine($"Failed to restore '{Path.GetFileName(projectFilePath)}'. Please run dotnet restore, and try again."); return(false); } var projectAssetsPath = project.GetPropertyValue("ProjectAssetsFile"); // NuGet has a LockFileUtilities.GetLockFile API which provides direct access to this file format, // but loading NuGet in the same process as MSBuild creates dependency conflicts. LockFile lockFile = null; using (StreamReader reader = File.OpenText(projectAssetsPath)) using (JsonReader jsonReader = new JsonTextReader(reader)) { JsonSerializer serializer = new JsonSerializer(); lockFile = serializer.Deserialize <LockFile>(jsonReader); } if (!lockFile.Libraries.Any(l => l.Key.StartsWith("Packaging.Targets/"))) { Console.Error.WriteLine($"The project '{Path.GetFileName(projectFilePath)}' doesn't have a PackageReference to Packaging.Targets."); Console.Error.WriteLine($"Please run 'dotnet {this.commandName} install', and try again."); return(false); } return(true); }
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 ImportDoesNotExistIgnoreMissingImports() { ProjectRootElement xml = ProjectRootElement.Create(); xml.AddProperty("p", "1"); xml.AddImport("__nonexistent__"); xml.AddProperty("q", "$(p)"); Project project = new Project(xml, null, null, new ProjectCollection(), ProjectLoadSettings.IgnoreMissingImports); // Make sure some evaluation did occur Assert.Equal("1", project.GetPropertyValue("q")); }
public void ChooseOtherwise() { string content = ObjectModelHelpers.CleanupFileContents(@" <Project xmlns='msbuildnamespace' > <Choose> <When Condition='false'> <PropertyGroup> <p>v1</p> </PropertyGroup> <ItemGroup> <i Include='i1' /> </ItemGroup> </When> <Otherwise> <PropertyGroup> <p>v2</p> </PropertyGroup> <ItemGroup> <i Include='i2' /> </ItemGroup> </Otherwise> </Choose> </Project> "); Project project = new Project(XmlReader.Create(new StringReader(content))); Assert.Equal("v2", project.GetPropertyValue("p")); Assert.Equal("i2", Helpers.MakeList(project.GetItems("i"))[0].EvaluatedInclude); }
public void ChooseTwoPasses() { string content = ObjectModelHelpers.CleanupFileContents(@" <Project xmlns='msbuildnamespace' > <Choose> <When Condition='true'> <ItemGroup> <i Include='$(p)_$(p2)' /> </ItemGroup> <PropertyGroup> <p>@(i);v1</p> </PropertyGroup> </When> </Choose> <PropertyGroup> <p2>v2</p2> </PropertyGroup> <Choose> <When Condition='false'/> <Otherwise> <ItemGroup> <j Include='$(q)_$(q2)' /> </ItemGroup> <PropertyGroup> <q>@(j);v1</q> </PropertyGroup> </Otherwise> </Choose> <PropertyGroup> <q2>v2</q2> </PropertyGroup> </Project> "); Project project = new Project(XmlReader.Create(new StringReader(content))); Assert.Equal("@(i);v1", project.GetPropertyValue("p")); Assert.Equal("@(j);v1", project.GetPropertyValue("q")); Assert.Equal("v1_v2", project.GetItems("i").ElementAt(0).EvaluatedInclude); Assert.Equal(1, project.GetItems("i").Count()); Assert.Equal("v1_v2", project.GetItems("j").ElementAt(0).EvaluatedInclude); Assert.Equal(1, project.GetItems("j").Count()); }
/// <summary> /// Call to find interpreters in the associated project. Separated from /// the constructor to allow exceptions to be handled without causing /// the project node to be invalid. /// </summary> /// <exception cref="InvalidDataException"> /// One or more interpreters failed to load. The error message should be /// presented to the user, but can otherwise be ignored. /// </exception> public void DiscoverInterpreters() { // <Interpreter Include="InterpreterDirectory"> // <Id>guid</Id> // <BaseInterpreter>guid</BaseInterpreter> // <Version>...</Version> // <InterpreterPath>...</InterpreterPath> // <WindowsInterpreterPath>...</WindowsInterpreterPath> // <LibraryPath>...</LibraryPath> // <PathEnvironmentVariable>...</PathEnvironmentVariable> // <Description>...</Description> // </Interpreter> var errors = new StringBuilder(); errors.AppendLine("Some project interpreters failed to load:"); bool anyChange = false, anyError = false; var projectHome = CommonUtils.GetAbsoluteDirectoryPath(_project.DirectoryPath, _project.GetPropertyValue("ProjectHome")); var factories = new Dictionary <IPythonInterpreterFactory, FactoryInfo>(); foreach (var item in _project.GetItems(InterpreterItem)) { IPythonInterpreterFactory fact; Guid id, baseId; // Errors in these options are fatal, so we set anyError and // continue with the next entry. var dir = item.EvaluatedInclude; if (!CommonUtils.IsValidPath(dir)) { errors.AppendLine(string.Format("Interpreter has invalid path: {0}", dir ?? "(null)")); anyError = true; continue; } dir = CommonUtils.GetAbsoluteDirectoryPath(projectHome, dir); var value = item.GetMetadataValue(IdKey); if (string.IsNullOrEmpty(value) || !Guid.TryParse(value, out id)) { errors.AppendLine(string.Format("Interpreter {0} has invalid value for '{1}': {2}", dir, IdKey, value)); anyError = true; continue; } if (factories.Keys.Any(f => f.Id == id)) { errors.AppendLine(string.Format("Interpreter {0} has a non-unique id: {1}", dir, id)); continue; } var verStr = item.GetMetadataValue(VersionKey); Version ver; if (string.IsNullOrEmpty(verStr) || !Version.TryParse(verStr, out ver)) { errors.AppendLine(string.Format("Interpreter {0} has invalid value for '{1}': {2}", dir, VersionKey, verStr)); anyError = true; continue; } // The rest of the options are non-fatal. We create an instance // of NotFoundError with an amended description, which will // allow the user to remove the entry from the project file // later. bool hasError = false; var description = item.GetMetadataValue(DescriptionKey); if (string.IsNullOrEmpty(description)) { description = CommonUtils.CreateFriendlyDirectoryPath(projectHome, dir); } value = item.GetMetadataValue(BaseInterpreterKey); PythonInterpreterFactoryWithDatabase baseInterp = null; if (!string.IsNullOrEmpty(value) && Guid.TryParse(value, out baseId)) { // It's a valid GUID, so find a suitable base. If we // don't find one now, we'll try and figure it out from // the pyvenv.cfg/orig-prefix.txt files later. // Using an empty GUID will always go straight to the // later lookup. if (baseId != Guid.Empty) { baseInterp = _service.FindInterpreter(baseId, ver) as PythonInterpreterFactoryWithDatabase; } } var path = item.GetMetadataValue(InterpreterPathKey); if (!CommonUtils.IsValidPath(path)) { errors.AppendLine(string.Format("Interpreter {0} has invalid value for '{1}': {2}", dir, InterpreterPathKey, path)); hasError = true; } else if (!hasError) { path = CommonUtils.GetAbsoluteFilePath(dir, path); } var winPath = item.GetMetadataValue(WindowsPathKey); if (!CommonUtils.IsValidPath(winPath)) { errors.AppendLine(string.Format("Interpreter {0} has invalid value for '{1}': {2}", dir, WindowsPathKey, winPath)); hasError = true; } else if (!hasError) { winPath = CommonUtils.GetAbsoluteFilePath(dir, winPath); } var libPath = item.GetMetadataValue(LibraryPathKey); if (string.IsNullOrEmpty(libPath)) { libPath = "lib"; } if (!CommonUtils.IsValidPath(libPath)) { errors.AppendLine(string.Format("Interpreter {0} has invalid value for '{1}': {2}", dir, LibraryPathKey, libPath)); hasError = true; } else if (!hasError) { libPath = CommonUtils.GetAbsoluteDirectoryPath(dir, libPath); } var pathVar = item.GetMetadataValue(PathEnvVarKey); if (string.IsNullOrEmpty(pathVar)) { if (baseInterp != null) { pathVar = baseInterp.Configuration.PathEnvironmentVariable; } else { pathVar = "PYTHONPATH"; } } string arch = null; if (baseInterp == null) { arch = item.GetMetadataValue(ArchitectureKey); if (string.IsNullOrEmpty(arch)) { arch = "x86"; } } if (baseInterp == null && !hasError) { // Only thing missing is the base interpreter, so let's try // to find it using paths baseInterp = DerivedInterpreterFactory.FindBaseInterpreterFromVirtualEnv(dir, libPath, _service) as PythonInterpreterFactoryWithDatabase; if (baseInterp == null) { errors.AppendLine(string.Format("Interpreter {0} has invalid value for '{1}': {2}", dir, BaseInterpreterKey, value ?? "(null)")); hasError = true; } } if (hasError) { fact = new NotFoundInterpreterFactory( id, ver, string.Format("{0} (unavailable)", description), Directory.Exists(dir) ? dir : null ); } else if (baseInterp != null) { MigrateOldDerivedInterpreterFactoryDatabase(id, baseInterp.Configuration.Version, dir); fact = new DerivedInterpreterFactory( baseInterp, new InterpreterFactoryCreationOptions { LanguageVersion = baseInterp.Configuration.Version, Id = id, Description = description, InterpreterPath = path, WindowInterpreterPath = winPath, LibraryPath = libPath, PrefixPath = dir, PathEnvironmentVariableName = pathVar, Architecture = baseInterp.Configuration.Architecture, WatchLibraryForNewModules = true } ); } else { fact = InterpreterFactoryCreator.CreateInterpreterFactory(new InterpreterFactoryCreationOptions { LanguageVersion = ver, Id = id, Description = description, InterpreterPath = path, WindowInterpreterPath = winPath, LibraryPath = libPath, PrefixPath = dir, PathEnvironmentVariableName = pathVar, ArchitectureString = arch, WatchLibraryForNewModules = true }); } var existing = FindInterpreter(id, ver); if (existing != null && existing.IsEqual(fact)) { factories[existing] = new FactoryInfo(item, factories[existing].Owned); var disposable = fact as IDisposable; if (disposable != null) { disposable.Dispose(); } } else { _rootPaths[id] = dir; factories[fact] = new FactoryInfo(item, true); anyChange = true; } } // <InterpreterReference Include="{guid};{version}" /> foreach (var item in _project.GetItems(InterpreterReferenceItem)) { var match = InterpreterReferencePath.Match(item.EvaluatedInclude); if (match == null || !match.Success || !match.Groups.Cast <Group>().All(g => g.Success)) { errors.AppendLine(string.Format("Interpreter reference has invalid path: {0}", item.EvaluatedInclude)); anyError = true; continue; } Guid id; var value = match.Groups["id"]; if (string.IsNullOrEmpty(value.Value) || !Guid.TryParse(value.Value, out id)) { errors.AppendLine(string.Format("Interpreter reference has invalid id: {0}", value.Value ?? "(null)")); anyError = true; continue; } Version ver; value = match.Groups["version"]; if (string.IsNullOrEmpty(value.Value) || !Version.TryParse(value.Value, out ver)) { errors.AppendLine(string.Format("Interpreter reference has invalid version: {0}", value.Value ?? "(null)")); anyError = true; continue; } bool owned = false; var fact = _service.FindInterpreter(id, ver); if (fact == null) { owned = true; fact = new NotFoundInterpreterFactory(id, ver); } var existing = FindInterpreter(id, ver); if (existing != null) { factories[existing] = new FactoryInfo(item, factories[existing].Owned); if (owned) { ((PythonInterpreterFactoryWithDatabase)fact).Dispose(); } } else { factories[fact] = new FactoryInfo(item, owned); anyChange = true; } } if (anyChange || _factories == null || factories.Count != _factories.Count) { // Lock here mainly to ensure that any searches complete before // we trigger the changed event. lock (_factoriesLock) { _factories = factories; } OnInterpreterFactoriesChanged(); UpdateActiveInterpreter(); } if (anyError) { throw new InvalidDataException(errors.ToString()); } }
public void ImportedXmlModified() { string path = null; try { path = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile(); ProjectRootElement import = ProjectRootElement.Create(path); import.Save(); Project project = new Project(); int last = project.EvaluationCounter; project.Xml.AddImport(path); project.ReevaluateIfNecessary(); Assert.NotEqual(project.EvaluationCounter, last); last = project.EvaluationCounter; project.ReevaluateIfNecessary(); Assert.Equal(project.EvaluationCounter, last); import.AddProperty("p", "v"); Assert.Equal(true, project.IsDirty); project.ReevaluateIfNecessary(); Assert.NotEqual(project.EvaluationCounter, last); last = project.EvaluationCounter; Assert.Equal("v", project.GetPropertyValue("p")); project.ReevaluateIfNecessary(); Assert.Equal(project.EvaluationCounter, last); } finally { File.Delete(path); } }
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 ChangeEnvironmentProperty() { Project project = new Project(); project.SetProperty("computername", "v1"); Assert.Equal("v1", project.GetPropertyValue("computername")); Assert.Equal(true, project.IsDirty); project.ReevaluateIfNecessary(); Assert.Equal("v1", project.GetPropertyValue("computername")); }
/// <summary> /// Retrives the list of project guids from the project file. /// If you don't want your project to be flavorable, override /// to only return your project factory Guid: /// return this.GetType().GUID.ToString("B"); /// </summary> /// <param name="file">Project file to look into to find the Guid list</param> /// <returns>List of semi-colon separated GUIDs</returns> protected override string ProjectTypeGuids(string file) { // Load the project so we can extract the list of GUIDs this.buildProject = Utilities.ReinitializeMsBuildProject(this.buildEngine, file, this.buildProject); // Retrieve the list of GUIDs, if it is not specify, make it our GUID string guids = buildProject.GetPropertyValue(ProjectFileConstants.ProjectTypeGuids); if(String.IsNullOrEmpty(guids)) guids = this.GetType().GUID.ToString("B"); return guids; }
public void MSBuildToolsVersionProperty() { if (ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version20) == null) { // "Requires 2.0 to be installed" return; } Project project = new Project(); project.Xml.ToolsVersion = "2.0"; project.ReevaluateIfNecessary(); // ... and after all that, we end up defaulting to the current ToolsVersion instead. There's a way // to turn this behavior (new in Dev12) off, but it requires setting an environment variable and // clearing some internal state to make sure that the update environment variable is picked up, so // there's not a good way of doing it from these deliberately public OM only tests. Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, project.GetPropertyValue("msbuildtoolsversion")); project.Xml.ToolsVersion = "4.0"; // Still current Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, project.GetPropertyValue("msbuildtoolsversion")); project.ReevaluateIfNecessary(); // Still current Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, project.GetPropertyValue("msbuildtoolsversion")); }
private IEnumerable<ProcessPath> ProcessProjectFile(ProcessPath process, ScanResult result) { List<ProcessPath> newFiles = new List<ProcessPath>(); // If this project is not processed already, read through it all. ScannedProject scannedProject; string key = ScannedProject.CalculateKey(process.Path, process.Properties); if (!result.ProjectFiles.TryGetValue(key, out scannedProject)) { Project project = new Project(process.Path, process.Properties, null); string projectFolder = Path.GetDirectoryName(project.FullPath); string type = project.GetPropertyValue("OutputType"); scannedProject = new ScannedProject(type, project.FullPath, process.Properties, null); ICollection<ProjectItem> projectReferences = project.GetItemsIgnoringCondition("ProjectReference"); if (this.RecurseProjects && projectReferences != null) { foreach (ProjectItem projectReference in projectReferences) { // TODO: process Property metadata. string include = Path.Combine(projectFolder, projectReference.EvaluatedInclude); newFiles.Add(new ProcessPath(include) { Project = scannedProject }); } } ICollection<ProjectItem> compiles = project.GetItemsIgnoringCondition("Compile"); if (compiles != null) { foreach (ProjectItem item in compiles) { // TODO: process DefineConstants property. string include = Path.Combine(projectFolder, item.EvaluatedInclude); newFiles.Add(new ProcessPath(include) { Project = scannedProject }); } } Debug.Assert(key == scannedProject.Key, String.Format("{0} should equal {1}", key, scannedProject.Key)); result.ProjectFiles.Add(scannedProject.Key, scannedProject); } // If there is a parent project, create a reference between the two projects. if (process.Project != null) { process.Project.TargetProjects.Add(scannedProject); scannedProject.SourceProjects.Add(process.Project); //result.ProjectToProjectReferences.Add(new ScannedProjectProjectReference() { SourceProject = process.Project, TargetProject = scannedProject }); } return newFiles; }
public static String GetEvaluatedProperty(Microsoft.Build.Evaluation.Project project, String name) { return(project.GetPropertyValue(name)); }
private void DiscoverTests(Dictionary <string, HashSet <TestFileEntry> > testItems, MSBuild.Project proj, ITestCaseDiscoverySink discoverySink, IMessageLogger logger) { var result = new List <NodejsTestInfo>(); var projectHome = Path.GetFullPath(Path.Combine(proj.DirectoryPath, ".")); var projSource = proj.FullPath; var nodeExePath = Nodejs.GetAbsoluteNodeExePath( projectHome, proj.GetPropertyValue(NodeProjectProperty.NodeExePath)); if (!File.Exists(nodeExePath)) { logger.SendMessage(TestMessageLevel.Error, "Node.exe was not found. Please install Node.js before running tests."); return; } var testCount = 0; foreach (var testFx in testItems.Keys) { var testFramework = FrameworkDiscoverer.Instance.Get(testFx); if (testFramework == null) { logger.SendMessage(TestMessageLevel.Warning, $"Ignoring unsupported test framework '{testFx}'."); continue; } var fileList = testItems[testFx]; var files = string.Join(";", fileList.Select(p => p.FullPath)); logger.SendMessage(TestMessageLevel.Informational, string.Format(CultureInfo.CurrentCulture, "Processing: {0}", files)); var discoveredTestCases = testFramework.FindTests(fileList.Select(p => p.FullPath), nodeExePath, logger, projectRoot: projectHome); testCount += discoveredTestCases.Count(); foreach (var discoveredTest in discoveredTestCases) { var qualifiedName = discoveredTest.FullyQualifiedName; const string indent = " "; logger.SendMessage(TestMessageLevel.Informational, $"{indent}Creating TestCase:{qualifiedName}"); //figure out the test source info such as line number var filePath = discoveredTest.TestPath; var entry = fileList.First(p => StringComparer.OrdinalIgnoreCase.Equals(p.FullPath, filePath)); FunctionInformation fi = null; if (entry.IsTypeScriptTest) { fi = SourceMapper.MaybeMap(new FunctionInformation(string.Empty, discoveredTest.TestName, discoveredTest.SourceLine, entry.FullPath)); } var testcase = new TestCase(qualifiedName, NodejsConstants.ExecutorUri, projSource) { CodeFilePath = fi?.Filename ?? filePath, LineNumber = fi?.LineNumber ?? discoveredTest.SourceLine, DisplayName = discoveredTest.TestName }; testcase.SetPropertyValue(JavaScriptTestCaseProperties.TestFramework, testFx); testcase.SetPropertyValue(JavaScriptTestCaseProperties.NodeExePath, nodeExePath); testcase.SetPropertyValue(JavaScriptTestCaseProperties.ProjectRootDir, projectHome); testcase.SetPropertyValue(JavaScriptTestCaseProperties.WorkingDir, projectHome); testcase.SetPropertyValue(JavaScriptTestCaseProperties.TestFile, filePath); discoverySink.SendTestCase(testcase); } logger.SendMessage(TestMessageLevel.Informational, string.Format(CultureInfo.CurrentCulture, "Processing finished for framework '{0}'.", testFx)); } }
public static ProjectData Create(MSB.Evaluation.Project project) { var guid = PropertyConverter.ToGuid(project.GetPropertyValue(PropertyNames.ProjectGuid)); var name = project.GetPropertyValue(PropertyNames.ProjectName); var assemblyName = project.GetPropertyValue(PropertyNames.AssemblyName); var targetPath = project.GetPropertyValue(PropertyNames.TargetPath); var outputPath = project.GetPropertyValue(PropertyNames.OutputPath); var intermediateOutputPath = project.GetPropertyValue(PropertyNames.IntermediateOutputPath); var projectAssetsFile = project.GetPropertyValue(PropertyNames.ProjectAssetsFile); var configuration = project.GetPropertyValue(PropertyNames.Configuration); var platform = project.GetPropertyValue(PropertyNames.Platform); var defaultNamespace = project.GetPropertyValue(PropertyNames.RootNamespace); var targetFramework = new FrameworkName(project.GetPropertyValue(PropertyNames.TargetFrameworkMoniker)); var targetFrameworkValue = project.GetPropertyValue(PropertyNames.TargetFramework); var targetFrameworks = PropertyConverter.SplitList(project.GetPropertyValue(PropertyNames.TargetFrameworks), ';'); if (!string.IsNullOrWhiteSpace(targetFrameworkValue) && targetFrameworks.Length == 0) { targetFrameworks = ImmutableArray.Create(targetFrameworkValue); } var languageVersion = PropertyConverter.ToLanguageVersion(project.GetPropertyValue(PropertyNames.LangVersion)); var allowUnsafeCode = PropertyConverter.ToBoolean(project.GetPropertyValue(PropertyNames.AllowUnsafeBlocks), defaultValue: false); var checkForOverflowUnderflow = PropertyConverter.ToBoolean(project.GetPropertyValue(PropertyNames.CheckForOverflowUnderflow), defaultValue: false); var outputKind = PropertyConverter.ToOutputKind(project.GetPropertyValue(PropertyNames.OutputType)); var nullableContextOptions = PropertyConverter.ToNullableContextOptions(project.GetPropertyValue(PropertyNames.Nullable)); var documentationFile = project.GetPropertyValue(PropertyNames.DocumentationFile); var preprocessorSymbolNames = PropertyConverter.ToPreprocessorSymbolNames(project.GetPropertyValue(PropertyNames.DefineConstants)); var suppressedDiagnosticIds = PropertyConverter.ToSuppressedDiagnosticIds(project.GetPropertyValue(PropertyNames.NoWarn)); var warningsAsErrors = PropertyConverter.SplitList(project.GetPropertyValue(PropertyNames.WarningsAsErrors), ','); var warningsNotAsErrors = PropertyConverter.SplitList(project.GetPropertyValue(PropertyNames.WarningsNotAsErrors), ','); var signAssembly = PropertyConverter.ToBoolean(project.GetPropertyValue(PropertyNames.SignAssembly), defaultValue: false); var assemblyOriginatorKeyFile = project.GetPropertyValue(PropertyNames.AssemblyOriginatorKeyFile); var treatWarningsAsErrors = PropertyConverter.ToBoolean(project.GetPropertyValue(PropertyNames.TreatWarningsAsErrors), defaultValue: false); var runAnalyzers = PropertyConverter.ToBoolean(project.GetPropertyValue(PropertyNames.RunAnalyzers), defaultValue: true); var runAnalyzersDuringLiveAnalysis = PropertyConverter.ToBoolean(project.GetPropertyValue(PropertyNames.RunAnalyzersDuringLiveAnalysis), defaultValue: true); return(new ProjectData( guid, name, assemblyName, targetPath, outputPath, intermediateOutputPath, projectAssetsFile, configuration, platform, targetFramework, targetFrameworks, outputKind, languageVersion, nullableContextOptions, allowUnsafeCode, checkForOverflowUnderflow, documentationFile, preprocessorSymbolNames, suppressedDiagnosticIds, warningsAsErrors, warningsNotAsErrors, signAssembly, assemblyOriginatorKeyFile, treatWarningsAsErrors, defaultNamespace, runAnalyzers, runAnalyzersDuringLiveAnalysis, ruleset: null)); }
public void ChangeGlobalPropertiesInitiallyFromProjectCollection() { Dictionary<string, string> initial = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); initial.Add("p0", "v0"); initial.Add("p1", "v1"); ProjectCollection collection = new ProjectCollection(initial, null, ToolsetDefinitionLocations.ConfigurationFile); Project project = new Project(collection); ProjectPropertyElement propertyElement = project.Xml.AddProperty("pp", "vv"); propertyElement.Condition = "'$(p0)'=='v0' and '$(p1)'=='v1b'"; project.ReevaluateIfNecessary(); Assert.Equal(String.Empty, project.GetPropertyValue("pp")); project.SetGlobalProperty("p1", "v1b"); Assert.Equal(true, project.IsDirty); project.ReevaluateIfNecessary(); Assert.Equal("vv", project.GetPropertyValue("pp")); Assert.Equal("v0", collection.GlobalProperties["p0"]); Assert.Equal("v1", collection.GlobalProperties["p1"]); }
public void BasicFromXmlFollowImport() { string importContent = ObjectModelHelpers.CleanupFileContents(@" <Project xmlns='msbuildnamespace'> <PropertyGroup> <p2>v3</p2> </PropertyGroup> <ItemGroup> <i Include='i4'/> </ItemGroup> <Target Name='t2'> <task/> </Target> </Project>"); string importPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.targets", importContent); string projectFileContent = ObjectModelHelpers.CleanupFileContents(@" <Project xmlns='msbuildnamespace'> <PropertyGroup Condition=""'$(Configuration)'=='Foo'""> <p>v1</p> </PropertyGroup> <PropertyGroup Condition=""'$(Configuration)'!='Foo'""> <p>v2</p> </PropertyGroup> <PropertyGroup> <p2>X$(p)</p2> </PropertyGroup> <ItemGroup> <i Condition=""'$(Configuration)'=='Foo'"" Include='i0'/> <i Include='i1'/> <i Include='$(p)X;i3'/> </ItemGroup> <Target Name='t'> <task/> </Target> <Import Project='{0}'/> </Project>"); projectFileContent = String.Format(projectFileContent, importPath); ProjectRootElement xml = ProjectRootElement.Create(XmlReader.Create(new StringReader(projectFileContent))); Project project = new Project(xml); Assert.Equal("v3", project.GetPropertyValue("p2")); List<ProjectItem> items = Helpers.MakeList(project.GetItems("i")); Assert.Equal(4, items.Count); Assert.Equal("i1", items[0].EvaluatedInclude); Assert.Equal("v2X", items[1].EvaluatedInclude); Assert.Equal("i3", items[2].EvaluatedInclude); Assert.Equal("i4", items[3].EvaluatedInclude); IList<ResolvedImport> imports = project.Imports; Assert.Equal(1, imports.Count); Assert.Equal(true, Object.ReferenceEquals(imports.First().ImportingElement, xml.Imports.ElementAt(0))); // We can take advantage of the fact that we will get the same ProjectRootElement from the cache if we try to // open it with a path; get that and then compare it to what project.Imports gave us. Assert.Equal(true, Object.ReferenceEquals(imports.First().ImportedProject, ProjectRootElement.Open(importPath))); // Test the logical project iterator List<ProjectElement> logicalElements = new List<ProjectElement>(project.GetLogicalProject()); Assert.Equal(18, logicalElements.Count); ObjectModelHelpers.DeleteTempProjectDirectory(); }
public void MSBuildToolsVersionProperty40() { Project project = new Project(); Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, project.GetPropertyValue("msbuildtoolsversion")); }
public void ChangeGlobalProperties() { Project project = new Project(); ProjectPropertyElement propertyElement = project.Xml.AddProperty("p", "v0"); propertyElement.Condition = "'$(g)'=='v1'"; project.ReevaluateIfNecessary(); Assert.Equal(String.Empty, project.GetPropertyValue("p")); Assert.Equal(true, project.SetGlobalProperty("g", "v1")); Assert.Equal(true, project.IsDirty); project.ReevaluateIfNecessary(); Assert.Equal("v0", project.GetPropertyValue("p")); Assert.Equal("v1", project.GlobalProperties["g"]); }
public void GetSubToolsetVersion_FromEnvironment() { string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion"); try { Environment.SetEnvironmentVariable("VisualStudioVersion", "ABCD"); Project p = new Project(GetSampleProjectRootElement(), null, "4.0", new ProjectCollection()); Assert.Equal("4.0", p.ToolsVersion); Assert.Equal("ABCD", p.SubToolsetVersion); Assert.Equal("ABCD", p.GetPropertyValue("VisualStudioVersion")); } finally { Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion); } }
public void SkipEvaluation() { Project project = new Project(); project.SetGlobalProperty("p", "v1"); project.ReevaluateIfNecessary(); Assert.Equal("v1", project.GetPropertyValue("p")); project.SkipEvaluation = true; ProjectPropertyElement propertyElement = project.Xml.AddProperty("p1", "v0"); propertyElement.Condition = "'$(g)'=='v1'"; project.SetGlobalProperty("g", "v1"); project.ReevaluateIfNecessary(); Assert.Equal(String.Empty, project.GetPropertyValue("p1")); project.SkipEvaluation = false; project.SetGlobalProperty("g", "v1"); project.ReevaluateIfNecessary(); Assert.Equal("v0", project.GetPropertyValue("p1")); }
public void GetSubToolsetVersion_FromConstructor() { string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion"); try { Environment.SetEnvironmentVariable("VisualStudioVersion", "ABC"); IDictionary<string, string> globalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); globalProperties.Add("VisualStudioVersion", "ABCD"); IDictionary<string, string> projectCollectionGlobalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); projectCollectionGlobalProperties.Add("VisualStudioVersion", "ABCDE"); Project p = new Project(GetSampleProjectRootElement(), globalProperties, "4.0", "ABCDEF", new ProjectCollection(projectCollectionGlobalProperties), ProjectLoadSettings.Default); Assert.Equal("4.0", p.ToolsVersion); Assert.Equal("ABCDEF", p.SubToolsetVersion); Assert.Equal("ABCDEF", p.GetPropertyValue("VisualStudioVersion")); } finally { Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion); } }
public void ChangeGlobalPropertiesPreexisting() { Dictionary<string, string> initial = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); initial.Add("p0", "v0"); initial.Add("p1", "v1"); Project project = new Project(ProjectRootElement.Create(), initial, null); ProjectPropertyElement propertyElement = project.Xml.AddProperty("pp", "vv"); propertyElement.Condition = "'$(p0)'=='v0' and '$(p1)'=='v1b'"; project.ReevaluateIfNecessary(); Assert.Equal(String.Empty, project.GetPropertyValue("pp")); project.SetGlobalProperty("p1", "v1b"); Assert.Equal(true, project.IsDirty); project.ReevaluateIfNecessary(); Assert.Equal("vv", project.GetPropertyValue("pp")); Assert.Equal("v0", project.GlobalProperties["p0"]); Assert.Equal("v1b", project.GlobalProperties["p1"]); }
private void DiscoverTests(Dictionary <string, List <TestFileEntry> > testItems, MSBuild.Project proj, ITestCaseDiscoverySink discoverySink, IMessageLogger logger) { var result = new List <TestFrameworks.NodejsTestInfo>(); var projectHome = Path.GetFullPath(Path.Combine(proj.DirectoryPath, ".")); var projSource = proj.FullPath; var nodeExePath = Nodejs.GetAbsoluteNodeExePath( projectHome, proj.GetPropertyValue(NodeProjectProperty.NodeExePath)); if (!File.Exists(nodeExePath)) { logger.SendMessage(TestMessageLevel.Error, string.Format(CultureInfo.CurrentCulture, "Node.exe was not found. Please install Node.js before running tests.")); return; } var testCount = 0; foreach (var testFx in testItems.Keys) { var testFramework = GetTestFrameworkObject(testFx); if (testFramework == null) { logger.SendMessage(TestMessageLevel.Warning, string.Format(CultureInfo.CurrentCulture, "Ignoring unsupported test framework {0}", testFx)); continue; } var fileList = testItems[testFx]; var files = string.Join(";", fileList.Select(p => p.File)); logger.SendMessage(TestMessageLevel.Informational, string.Format(CultureInfo.CurrentCulture, "Processing: {0}", files)); var discoveredTestCases = testFramework.FindTests(fileList.Select(p => p.File), nodeExePath, logger, projectHome); testCount += discoveredTestCases.Count; foreach (var discoveredTest in discoveredTestCases) { var qualifiedName = discoveredTest.FullyQualifiedName; logger.SendMessage(TestMessageLevel.Informational, string.Format(CultureInfo.CurrentCulture, " " /*indent*/ + "Creating TestCase:{0}", qualifiedName)); //figure out the test source info such as line number var filePath = discoveredTest.ModulePath; var entry = fileList.Find(p => p.File.Equals(filePath, StringComparison.OrdinalIgnoreCase)); FunctionInformation fi = null; if (entry.IsTypeScriptTest) { fi = SourceMapper.MaybeMap(new FunctionInformation(string.Empty, discoveredTest.TestName, discoveredTest.SourceLine, entry.File)); } discoverySink.SendTestCase( new TestCase(qualifiedName, TestExecutor.ExecutorUri, projSource) { CodeFilePath = (fi != null) ? fi.Filename : filePath, LineNumber = (fi != null && fi.LineNumber.HasValue) ? fi.LineNumber.Value : discoveredTest.SourceLine, DisplayName = discoveredTest.TestName }); } logger.SendMessage(TestMessageLevel.Informational, string.Format(CultureInfo.CurrentCulture, "Processing finished for framework of {0}", testFx)); } if (testCount == 0) { logger.SendMessage(TestMessageLevel.Warning, string.Format(CultureInfo.CurrentCulture, "Discovered 0 testcases.")); } }
public void RemoveGlobalProperties() { Project project = new Project(); ProjectPropertyElement propertyElement = project.Xml.AddProperty("p", "v0"); propertyElement.Condition = "'$(g)'==''"; project.SetGlobalProperty("g", "v1"); project.ReevaluateIfNecessary(); Assert.Equal(String.Empty, project.GetPropertyValue("p")); bool existed = project.RemoveGlobalProperty("g"); Assert.Equal(true, existed); Assert.Equal(true, project.IsDirty); project.ReevaluateIfNecessary(); Assert.Equal("v0", project.GetPropertyValue("p")); Assert.Equal(false, project.GlobalProperties.ContainsKey("g")); }
public void SetPropertyWithPropertyExpression() { Project project = new Project(); project.SetProperty("p0", "v0"); project.SetProperty("p1", "$(p0)"); Assert.Equal("v0", project.GetPropertyValue("p1")); }
public void SetIceHome(string value) { if (string.IsNullOrEmpty(value)) { // // Remove all registry settings. // Registry.SetValue(IceBuilderKey, IceHomeValue, "", RegistryValueKind.String); Registry.SetValue(IceBuilderKey, IceVersionValue, "", RegistryValueKind.String); Registry.SetValue(IceBuilderKey, IceIntVersionValue, "", RegistryValueKind.String); Registry.SetValue(IceBuilderKey, IceVersionMMValue, "", RegistryValueKind.String); TryRemoveAssemblyFoldersExKey(); return; } else { string props = new string[] { Path.Combine(value, "config", "ice.props"), Path.Combine(value, "cpp", "config", "ice.props"), Path.Combine(value, "config", "icebuilder.props") }.FirstOrDefault(path => File.Exists(path)); if (!string.IsNullOrEmpty(props)) { Microsoft.Build.Evaluation.Project p = new Microsoft.Build.Evaluation.Project( props, new Dictionary <string, string>() { { "ICE_HOME", value } }, null); Registry.SetValue(IceBuilderKey, IceHomeValue, value, RegistryValueKind.String); string version = p.GetPropertyValue(IceVersionValue); Registry.SetValue(IceBuilderKey, IceVersionValue, version, RegistryValueKind.String); string intVersion = p.GetPropertyValue(IceIntVersionValue); Registry.SetValue(IceBuilderKey, IceIntVersionValue, intVersion, RegistryValueKind.String); string mmVersion = p.GetPropertyValue(IceVersionMMValue); Registry.SetValue(IceBuilderKey, IceVersionMMValue, mmVersion, RegistryValueKind.String); Registry.SetValue(IceCSharpAssembleyKey, "", GetAssembliesDir(), RegistryValueKind.String); ICollection <Microsoft.Build.Evaluation.Project> projects = ProjectCollection.GlobalProjectCollection.GetLoadedProjects(props); if (projects.Count > 0) { ProjectCollection.GlobalProjectCollection.UnloadProject(p); } } else { Version v = null; try { string compiler = GetSliceCompilerVersion(value); if (string.IsNullOrEmpty(compiler)) { string err = "Unable to find a valid Ice installation in `" + value + "'"; MessageBox.Show(err, "Ice Builder", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); return; } else { v = Version.Parse(compiler); } } catch (Exception ex) { string err = "Failed to run Slice compiler using Ice installation from `" + value + "'" + "\n" + ex.ToString(); MessageBox.Show(err, "Ice Builder", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); return; } Registry.SetValue(IceBuilderKey, IceHomeValue, value, RegistryValueKind.String); Registry.SetValue(IceBuilderKey, IceVersionValue, v.ToString(), RegistryValueKind.String); string iceIntVersion = String.Format("{0}{1:00}{2:00}", v.Major, v.Minor, v.Build); Registry.SetValue(IceBuilderKey, IceIntVersionValue, iceIntVersion, RegistryValueKind.String); string iceVersionMM = string.Format("{0}.{1}", v.Major, v.Minor); Registry.SetValue(IceBuilderKey, IceVersionMMValue, iceVersionMM, RegistryValueKind.String); Registry.SetValue(IceCSharpAssembleyKey, "", GetAssembliesDir(), RegistryValueKind.String); } } }
public void SetPropertyWithItemExpression() { Project project = new Project(); project.AddItem("i", "i1"); project.SetProperty("p1", "x@(i)x%(m)x"); Assert.Equal("x@(i)x%(m)x", project.GetPropertyValue("p1")); }
public void EvaluateSamePropertiesInOrder () { // used in Microsoft.Common.targets string project_xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <PropertyGroup> <BaseIntermediateOutputPath Condition=""'$(BaseIntermediateOutputPath)' == ''"">obj\</BaseIntermediateOutputPath> </PropertyGroup> </Project>"; var xml = XmlReader.Create (new StringReader (project_xml)); var root = ProjectRootElement.Create (xml); var proj = new Project (root); Assert.AreEqual ("obj" + Path.DirectorySeparatorChar, proj.GetPropertyValue ("BaseIntermediateOutputPath"), "#1"); }
public void SetNewPropertyAfterEquivalentsParentRemoved() { Project project = new Project(); var property = project.SetProperty("p", "v1"); property.Xml.Parent.Parent.RemoveAllChildren(); project.SetProperty("p", "v2"); Assert.Equal(1, project.Xml.Properties.Count()); project.ReevaluateIfNecessary(); Assert.Equal("v2", project.GetPropertyValue("p")); }
private static bool? GetBoolProperty(Project p, string propertyName) { var val = p.GetPropertyValue(propertyName); bool result; if (bool.TryParse(val, out result)) return result; else return null; }
internal static string GetTypeScriptBackedJavaScriptFile(MSBuild.Project project, string pathToFile) { var typeScriptOutDir = project.GetPropertyValue(NodeProjectProperty.TypeScriptOutDir); return(GetTypeScriptBackedJavaScriptFile(project.DirectoryPath, typeScriptOutDir, pathToFile)); }
public override string GetPropertyValue(string name) { return(Project.GetPropertyValue(name)); }
public void SetPropertyOriginatingInImport() { ProjectRootElement xml = ProjectRootElement.Create(); xml.AddImport("$(msbuildtoolspath)\\microsoft.common.targets"); Project project = new Project(xml); // This property certainly exists in that imported file project.SetProperty("OutDir", "foo"); // should not throw Assert.Equal("foo", project.GetPropertyValue("OutDir")); Assert.Equal(1, Helpers.MakeList(xml.Properties).Count); }