public async Task <ImmutableArray <ProjectFileInfo> > GetProjectFileInfosAsync(CancellationToken cancellationToken) { var targetFrameworkValue = _loadedProject.GetPropertyValue(PropertyNames.TargetFramework); var targetFrameworksValue = _loadedProject.GetPropertyValue(PropertyNames.TargetFrameworks); if (string.IsNullOrEmpty(targetFrameworkValue) && !string.IsNullOrEmpty(targetFrameworksValue)) { // This project has a <TargetFrameworks> property, but does not specify a <TargetFramework>. // In this case, we need to iterate through the <TargetFrameworks>, set <TargetFramework> with // each value, and build the project. var hasTargetFrameworkProp = _loadedProject.GetProperty(PropertyNames.TargetFramework) != null; var targetFrameworks = targetFrameworksValue.Split(';'); var results = ImmutableArray.CreateBuilder <ProjectFileInfo>(targetFrameworks.Length); foreach (var targetFramework in targetFrameworks) { _loadedProject.SetProperty(PropertyNames.TargetFramework, targetFramework); _loadedProject.ReevaluateIfNecessary(); var projectFileInfo = await BuildProjectFileInfoAsync(cancellationToken).ConfigureAwait(false); results.Add(projectFileInfo); } // Remove the <TargetFramework> property if it didn't exist in the file before we set it. // Otherwise, set it back to it's original value. if (!hasTargetFrameworkProp) { var targetFrameworkProp = _loadedProject.GetProperty(PropertyNames.TargetFramework); _loadedProject.RemoveProperty(targetFrameworkProp); } else { _loadedProject.SetProperty(PropertyNames.TargetFramework, targetFrameworkValue); } _loadedProject.ReevaluateIfNecessary(); return(results.ToImmutable()); } else { var projectFileInfo = await BuildProjectFileInfoAsync(cancellationToken).ConfigureAwait(false); return(ImmutableArray.Create(projectFileInfo)); } }
private static void SetMsBuildProjectProperty(MsBuildProject buildProject, string name, string value) { if (!value.Equals(buildProject.GetPropertyValue(name), StringComparison.OrdinalIgnoreCase)) { buildProject.SetProperty(name, value); } }
/// <summary> /// Initializes the in memory project. Sets BuildEnabled on the project to true. /// </summary> /// <param name="buildEngine">The build engine to use to create a build project.</param> /// <param name="fullProjectPath">The full path of the project.</param> /// <returns>A loaded msbuild project.</returns> public static Microsoft.Build.Evaluation.Project InitializeMsBuildProject(Microsoft.Build.Evaluation.ProjectCollection buildEngine, string fullProjectPath) { if (buildEngine == null) { throw new ArgumentNullException("buildEngine"); } if (String.IsNullOrEmpty(fullProjectPath)) { throw new ArgumentException(SR.GetString(SR.InvalidParameter, CultureInfo.CurrentUICulture), "fullProjectPath"); } // Check if the project already has been loaded with the fullProjectPath. If yes return the build project associated to it. var prjs = new List <Microsoft.Build.Evaluation.Project>(buildEngine.GetLoadedProjects(fullProjectPath)); System.Diagnostics.Debug.Assert(prjs.Count <= 1, string.Format("more than one loaded project with same filename '{0}'", fullProjectPath)); Microsoft.Build.Evaluation.Project buildProject = prjs.Count == 0 ? null : prjs[0]; if (buildProject == null) { buildProject = buildEngine.LoadProject(fullProjectPath); buildProject.IsBuildEnabled = true; } buildProject.SetProperty("FSharpTargetsPath", Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Microsoft.FSharp.targets")); return(buildProject); }
IEnumerable <string> ResolveAssemblyReferences(Microsoft.Build.Evaluation.Project project) { // Use MSBuild to figure out the full path of the referenced assemblies var projectInstance = project.CreateProjectInstance(); projectInstance.SetProperty("BuildingProject", "false"); project.SetProperty("DesignTimeBuild", "true"); projectInstance.Build("ResolveAssemblyReferences", new [] { new ConsoleLogger(LoggerVerbosity.Minimal) }); var items = projectInstance.GetItems("_ResolveAssemblyReferenceResolvedFiles"); string baseDirectory = Path.GetDirectoryName(this.FileName); return(items.Select(i => Path.Combine(baseDirectory, i.GetMetadataValue("Identity")))); }
protected override Microsoft.Build.Evaluation.Project Load(string path, IDictionary <string, string> properties) { try { return(base.Load(path, properties)); } catch (Exception ex) { LSender._.send(this, $"MBE. Found problem when new Project('{path}'): '{ex.Message}'", Message.Level.Debug); var prj = new Microsoft.Build.Evaluation.Project(); prj.SetProperty(ERR_MSG, ex.Message); return(prj); } }
private static void SetTargetFrameworkIfNeeded(MSB.Evaluation.Project evaluatedProject) { var targetFramework = evaluatedProject.GetPropertyValue(PropertyNames.TargetFramework); var targetFrameworks = PropertyConverter.SplitList(evaluatedProject.GetPropertyValue(PropertyNames.TargetFrameworks), ';'); // If the project supports multiple target frameworks and specific framework isn't // selected, we must pick one before execution. Otherwise, the ResolveReferences // target might not be available to us. if (string.IsNullOrWhiteSpace(targetFramework) && targetFrameworks.Length > 0) { // For now, we'll just pick the first target framework. Eventually, we'll need to // do better and potentially allow OmniSharp hosts to select a target framework. targetFramework = targetFrameworks[0]; evaluatedProject.SetProperty(PropertyNames.TargetFramework, targetFramework); evaluatedProject.ReevaluateIfNecessary(); } }
IEnumerable <string> ResolveAssemblyReferences(Microsoft.Build.Evaluation.Project project) { // Use MSBuild to figure out the full path of the referenced assemblies var projectInstance = project.CreateProjectInstance(); projectInstance.SetProperty("BuildingProject", "false"); project.SetProperty("DesignTimeBuild", "true"); projectInstance.Build("ResolveAssemblyReferences", new [] { new ConsoleLogger(LoggerVerbosity.Minimal) }); var items = projectInstance.GetItems("_ResolveAssemblyReferenceResolvedFiles"); string baseDirectory = Path.GetDirectoryName(this.FileName); var result = items.Select(i => Path.Combine(baseDirectory, i.GetMetadataValue("Identity"))).ToList(); if (!result.Any(t => t.Contains("mscorlib") || t.Contains("System.Runtime"))) { result.Add(typeof(object).Assembly.Location); } return(result); }
private static void MigrateRuntimes(PackageSpec packageSpec, Microsoft.Build.Evaluation.Project buildProject) { ThreadHelper.ThrowIfNotOnUIThread(); var runtimes = packageSpec.RuntimeGraph.Runtimes; var supports = packageSpec.RuntimeGraph.Supports; var runtimeIdentifiers = new List <string>(); var runtimeSupports = new List <string>(); if (runtimes != null && runtimes.Count > 0) { runtimeIdentifiers.AddRange(runtimes.Keys); } if (supports != null && supports.Count > 0) { runtimeSupports.AddRange(supports.Keys); } var union = string.Join(";", runtimeIdentifiers.Union(runtimeSupports)); buildProject.SetProperty("RuntimeIdentifiers", union); }
public List <String> FindOutputPaths() { //TODO: Move to a new class (OutputPathResolver?) Console.WriteLine("Attempting to parse configuration output paths."); Console.WriteLine("Project File: " + Options.TargetPath); try { Microsoft.Build.Evaluation.Project proj = new Microsoft.Build.Evaluation.Project(Options.TargetPath); List <string> outputPaths = new List <string>(); List <string> configurations; proj.ConditionedProperties.TryGetValue("Configuration", out configurations); if (configurations == null) { configurations = new List <string>(); } foreach (var config in configurations) { proj.SetProperty("Configuration", config); proj.ReevaluateIfNecessary(); var path = proj.GetPropertyValue("OutputPath"); var fullPath = PathUtil.Combine(proj.DirectoryPath, path); outputPaths.Add(fullPath); Console.WriteLine("Found path: " + fullPath); } Microsoft.Build.Evaluation.ProjectCollection.GlobalProjectCollection.UnloadProject(proj); Console.WriteLine($"Found {outputPaths.Count} paths."); return(outputPaths); } catch (Exception e) { Console.WriteLine("Skipping configuration output paths."); return(new List <string>() { }); } }
public override void Generate(ProjectType projectType, Microsoft.Build.Evaluation.Project project) { project.SetProperty(Name, Value + projectType.CodeExtension); }
protected override byte[] GenerateCode(string inputFileName, string inputFileContent) { // Get active project // TODO: Instead of a custom code generator, we should have a context command or something like that. // This should also allow generation of multiple files var lines = Regex.Split(inputFileContent, "\r\n|\r|\n"); if (lines.Length == 0 || lines[0].Length == 0) { throw new InvalidOperationException("Source should contain project filename."); } var projectFullName = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(inputFileName), lines[0])); if (!File.Exists(projectFullName)) { throw new InvalidOperationException("Project file doesn't exist."); } string assemblyOutput, intermediateAssembly; // Get Evaluation Project Microsoft.Build.Evaluation.Project msbuildProject = Microsoft.Build.Evaluation.ProjectCollection.GlobalProjectCollection.GetLoadedProjects(projectFullName).First(); // Set ParadoxBuildStep variable and change IntermediateOutputPath var property1 = msbuildProject.SetProperty("ParadoxBuildStep", "StepData"); var property2 = msbuildProject.SetProperty("IntermediateOutputPath", @"obj\StepData\"); // Reevaluate dependent properties msbuildProject.ReevaluateIfNecessary(); try { var outputPane = GetOutputPane(); // Create logger var buildLogger = new IDEBuildLogger(outputPane, new TaskProvider(GlobalServiceProvider), VsHelper.GetCurrentHierarchy(GlobalServiceProvider)); buildLogger.Verbosity = Microsoft.Build.Framework.LoggerVerbosity.Diagnostic; var evaluatedProperties = new Dictionary <string, Microsoft.Build.Evaluation.ProjectProperty>(); foreach (var evaluatedProperty in msbuildProject.AllEvaluatedProperties) { evaluatedProperties[evaluatedProperty.Name] = evaluatedProperty; } // Output properties foreach (var evaluatedProperty in evaluatedProperties) { outputPane.OutputStringThreadSafe(string.Format( "$({0}) = {1} was evaluated as {2}\n", evaluatedProperty.Key, evaluatedProperty.Value.UnevaluatedValue, evaluatedProperty.Value.EvaluatedValue)); } // Compile project (only intermediate assembly) // Dependencies will be built as well //var manager = BuildManager.DefaultBuildManager; using (var manager = new BuildManager()) { var pc = new Microsoft.Build.Evaluation.ProjectCollection(); var globalProperties = new Dictionary <string, string>(); globalProperties["SolutionName"] = evaluatedProperties["SolutionName"].EvaluatedValue; globalProperties["SolutionDir"] = evaluatedProperties["SolutionDir"].EvaluatedValue; var projectInstance = new ProjectInstance(projectFullName, globalProperties, null); var buildResult = manager.Build( new BuildParameters(pc) { Loggers = new[] { buildLogger }, DetailedSummary = true, }, new BuildRequestData(projectInstance, new[] { "Compile" }, null)); if (buildResult.OverallResult == BuildResultCode.Failure) { throw new InvalidOperationException(string.Format("Build of {0} failed.", projectFullName)); } } // Get TargetPath and IntermediateAssembly assemblyOutput = msbuildProject.AllEvaluatedProperties.Last(x => x.Name == "TargetPath").EvaluatedValue; intermediateAssembly = msbuildProject.AllEvaluatedItems.First(x => x.ItemType == "IntermediateAssembly").EvaluatedInclude; } finally { msbuildProject.RemoveProperty(property1); msbuildProject.RemoveProperty(property2); } // Defer execution to current Paradox VS package plugin try { var remoteCommands = ParadoxCommandsProxy.GetProxy(); return(remoteCommands.GenerateDataClasses(assemblyOutput, projectFullName, intermediateAssembly)); } catch (Exception ex) { GeneratorError(4, ex.ToString(), 0, 0); return(new byte[0]); } }
private void AddProperty(Microsoft.Build.Evaluation.Project project, string propertyName, string propertyValue) { project.SetProperty(propertyName, propertyValue); }
private static void UpdateTargetFramework(Microsoft.Build.Evaluation.Project buildProject) { buildProject.SetProperty("TargetFramework", "net5.0"); }
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"); 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); }
private static void SetMsBuildProjectProperty(Project project, MsBuildProject buildProject, string name, string value) { buildProject.SetProperty(name, value); project.Save(); }