private static async Task<LoadedProjectInfo> LoadProjectAsync(string path, IDictionary<string, string> globalProperties, CancellationToken cancellationToken) { var properties = new Dictionary<string, string>(globalProperties ?? ImmutableDictionary<string, string>.Empty); properties["DesignTimeBuild"] = "true"; // this will tell msbuild to not build the dependent projects properties["BuildingInsideVisualStudio"] = "true"; // this will force CoreCompile task to execute even if all inputs and outputs are up to date try { var xmlReader = XmlReader.Create(await ReadFileAsync(path, cancellationToken).ConfigureAwait(false), s_xmlSettings); var collection = new MSB.Evaluation.ProjectCollection(); var xml = MSB.Construction.ProjectRootElement.Create(xmlReader, collection); // When constructing a project from an XmlReader, MSBuild cannot determine the project file path. Setting the // path explicitly is necessary so that the reserved properties like $(MSBuildProjectDirectory) will work. xml.FullPath = path; return new LoadedProjectInfo( new MSB.Evaluation.Project(xml, properties, toolsVersion: null, projectCollection: collection), errorMessage: null); } catch (Exception e) { return new LoadedProjectInfo(project: null, errorMessage: e.Message); } }
private static async Task <LoadedProjectInfo> LoadProjectAsync(string path, IDictionary <string, string> globalProperties, CancellationToken cancellationToken) { var properties = new Dictionary <string, string>(globalProperties ?? ImmutableDictionary <string, string> .Empty); properties["DesignTimeBuild"] = "true"; // this will tell msbuild to not build the dependent projects properties["BuildingInsideVisualStudio"] = "true"; // this will force CoreCompile task to execute even if all inputs and outputs are up to date try { var xmlReader = XmlReader.Create(await ReadFileAsync(path, cancellationToken).ConfigureAwait(false), s_xmlSettings); var collection = new MSB.Evaluation.ProjectCollection(); var xml = MSB.Construction.ProjectRootElement.Create(xmlReader, collection); // When constructing a project from an XmlReader, MSBuild cannot determine the project file path. Setting the // path explicitly is necessary so that the reserved properties like $(MSBuildProjectDirectory) will work. xml.FullPath = path; return(new LoadedProjectInfo( new MSB.Evaluation.Project(xml, properties, toolsVersion: null, projectCollection: collection), errorMessage: null)); } catch (Exception e) { return(new LoadedProjectInfo(project: null, errorMessage: e.Message)); } }
public PackageTestEnvironment() { // Create the project project = new ProjectTestClass(new ProjectTestPackage()); // Site the project services = Microsoft.VsSDK.UnitTestLibrary.OleServiceProvider.CreateOleServiceProviderWithBasicServices(); LocalRegistryMock localRegistry = new LocalRegistryMock(); localRegistry.RegistryRoot = @"Software\Microsoft\VisualStudio\9.0"; services.AddService(typeof(SLocalRegistry), localRegistry, true); BaseMock mockConfiguration = new GenericMockFactory("MockConfiguration", new[] { typeof(Configuration) }).GetInstance(); mockConfiguration.AddMethodReturnValues(string.Format("{0}.{1}", typeof(Configuration).FullName, "ConfigurationName"), new[] { "Debug" }); mockConfiguration.AddMethodReturnValues(string.Format("{0}.{1}", typeof(Configuration).FullName, "PlatformName"), new[] { "AnyCPU" }); BaseMock mockConfigMgr = ConfigurationManagerFactory.GetInstance(); mockConfigMgr.AddMethodReturnValues(string.Format("{0}.{1}", typeof(ConfigurationManager).FullName, ""), new[] { mockConfiguration }); BaseMock extensibility = ExtensibilityFactory.GetInstance(); extensibility.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsExtensibility3).FullName, "GetConfigMgr"), new object[] { 0, null, null, mockConfigMgr }); services.AddService(typeof(IVsExtensibility), extensibility, false); project.SetSite(services); // Init the msbuild engine Microsoft.Build.Evaluation.ProjectCollection engine = VisualStudio.Project.Utilities.InitializeMsBuildEngine(null, services); Assert.IsNotNull(engine, "MSBuild Engine could not be initialized"); // Retrieve the project file content, load it and save it string fullpath = Path.Combine(new DirectoryInfo(Assembly.GetExecutingAssembly().Location).Parent.FullName, "TestProject.proj"); if (string.IsNullOrEmpty(projectXml)) { projectXml = Properties.Resources.TestProject; using (TextWriter writer = new StreamWriter(fullpath)) { writer.Write(projectXml); } } // Init the msbuild project Microsoft.Build.Evaluation.Project buildProject = VisualStudio.Project.Utilities.InitializeMsBuildProject(engine, fullpath); Assert.IsNotNull(buildProject, "MSBuild project not initialized correctly in InitializeMsBuildProject"); //Verify that we can set the build project on the projectnode project.BuildProject = buildProject; // Now the project is opened, so we can update its internal variable. if (null == projectOpened) { projectOpened = typeof(VisualStudio.Project.ProjectNode).GetField("projectOpened", BindingFlags.Instance | BindingFlags.NonPublic); } projectOpened.SetValue(project, true); }
public void StartBatchBuild(IDictionary <string, string> globalProperties = null) { if (_batchBuildStarted) { throw new InvalidOperationException(); } globalProperties = globalProperties ?? ImmutableDictionary <string, string> .Empty; var allProperties = s_defaultGlobalProperties.AddRange(globalProperties); _batchBuildProjectCollection = new MSB.Evaluation.ProjectCollection(allProperties); _batchBuildLogger = new MSBuildDiagnosticLogger() { Verbosity = MSB.Framework.LoggerVerbosity.Normal }; var buildParameters = new MSB.Execution.BuildParameters(_batchBuildProjectCollection) { Loggers = new MSB.Framework.ILogger[] { _batchBuildLogger } }; MSB.Execution.BuildManager.DefaultBuildManager.BeginBuild(buildParameters); _batchBuildStarted = true; }
/// <summary> /// Retrieves the version from the vsix manifest file and sets the same to the global collection /// </summary> private void SetDominoPackageVersion(Microsoft.Build.Evaluation.ProjectCollection globalcollection) { var versionRegex = new Regex("<Identity\\s*" + "Id=\"(?<GUID>.*)\"\\s*" + "Version=\"(?<VERSION>.*)\"\\s*" + "Language=\"en-US\"\\s*" + "Publisher=\"Microsoft\"\\s*/>"); string source_extension = null; using (var sr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("BuildXL.VsPackage.source.extension.vsixmanifest"))) { source_extension = sr.ReadToEnd(); } var match = versionRegex.Match(source_extension); if (!match.Success) { OutputMessage(Strings.IncorrectManifestFile); return; } // Ensure that the same version number is mentioned in source.extension.vsixmanifest and Support\BuildXL.Task.targets var version = match.Groups["VERSION"].Value.Trim(); globalcollection.SetGlobalProperty(Constants.DominoPackageVersion, version); }
/// <summary> /// This method finds a compatible version of MSBuild and set environment variables so that Microsoft classes can asset it. /// It is needed since Microsoft regression introduced in VS15.2. Hopefully this code can be removed in the future. /// </summary> public static bool FindAndSetMSBuildVersion() { // Find a compatible version of MSBuild with the required workloads var buildTools = VisualStudioVersions.AvailableBuildTools .Where(x => x.Version >= new Version("15.0")).OrderByDescending(x => x.Version) .FirstOrDefault(x => { // FIXME: factorize with SiliconStudio.Xenko.PackageInstall.Program // FIXME: ideally prompt to install the missing prerequisites if (x.PackageVersions.ContainsKey("Microsoft.VisualStudio.Workload.ManagedDesktop")) { return(true); } if (x.PackageVersions.ContainsKey("Microsoft.VisualStudio.Workload.MSBuildTools") && x.PackageVersions.ContainsKey("Microsoft.Net.Component.4.6.1.TargetingPack")) { return(true); } return(false); }); if (buildTools != null) { Environment.SetEnvironmentVariable("VSINSTALLDIR", buildTools.InstallationPath); Environment.SetEnvironmentVariable("VisualStudioVersion", @"15.0"); } // Check that we can create a project var projectCollection = new Microsoft.Build.Evaluation.ProjectCollection(); return(projectCollection.GetToolset("15.0") != null); }
public bool Initialize() { if (NeedsInitialization) { if (VSPackage.CoreDte.ItemOperations.PromptToSave == EnvDTE.vsPromptResult.vsPromptResultCancelled) { return(false); } else { UnloadProject(FullName); using (var projectCollection = new Microsoft.Build.Evaluation.ProjectCollection()) { var buildProject = projectCollection.LoadProject(FullName); var targets = buildProject.Xml.Targets; if (!targets.Any(t => t.Name == "SetParametersDeploy")) { var target = buildProject.Xml.CreateTargetElement("SetParametersDeploy"); buildProject.Xml.AppendChild(target); target.AfterTargets = "Package"; target.AddTask("MakeDir").SetParameter("Directories", "$(PackageLocation)"); var copyTask = target.AddTask("Copy"); copyTask.SetParameter("SourceFiles", "@(Parameterization)"); copyTask.SetParameter("DestinationFolder", "$(PackageLocation)"); buildProject.Xml.Save(); } } ReloadProject(FullName); } } return(true); }
private void ResolveForNamespace(string projectDir, string projectFileName) { string proj_full_path = Path.Combine(projectDir, projectFileName); try { Microsoft.Build.Evaluation.ProjectCollection projCollection = new Microsoft.Build.Evaluation.ProjectCollection(); var proj = projCollection.LoadProject(proj_full_path); foreach (var item in proj.Properties) { if (item.Name == "RootNamespace") { this.txtNamespace.Text = item.EvaluatedValue; break; } } } catch (Exception ex) { string ns = ReadNamespaceFromProjectXml(proj_full_path); if (string.IsNullOrEmpty(ns)) { LogText(string.Format("{0}{1}{5} 错误信息:{2}{3},堆栈信息:{4}", Environment.NewLine, DateTime.Now.ToString(), ex.Message, Environment.NewLine, ex.StackTrace, proj_full_path)); } else { this.txtNamespace.Text = ns; } } }
internal static void UnloadProject(MSBuild.Evaluation.ProjectCollection projectCollection, MSBuild.Evaluation.Project project) { lock (SolutionProjectCollectionLock) { projectCollection.UnloadProject(project); } }
/// <summary> /// Saves a .props file for the specified package, containing the xenko version (only Major.Minor) /// used to compile the package. /// </summary> /// <param name="package">The package.</param> public static void SaveProperties(Package package) { // Props file is in the same folder as the xkpkg file, just with a ".props" extension. var packagePath = package.FullPath; var propsFilePath = UPath.Combine(packagePath.GetParent(), (UFile)(packagePath.GetFileNameWithoutExtension() + ".props")); var projectCollection = new Microsoft.Build.Evaluation.ProjectCollection(); var project = new Microsoft.Build.Evaluation.Project(projectCollection); var commonPropertyGroup = project.Xml.AddPropertyGroup(); var dependencies = package.FindDependencies(false, false, true); // Add Xenko version var xkVersion = dependencies.FirstOrDefault(d => d.Meta.Name == "Xenko"); if (xkVersion != null) { var versionText = xkVersion.Meta.Version.Version.Major + "." + xkVersion.Meta.Version.Version.Minor; commonPropertyGroup.AddProperty("SiliconStudioPackageXenkoVersion", versionText); } if (File.Exists(propsFilePath)) { File.Delete(propsFilePath); } project.Save(propsFilePath); }
/// <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) { var globalProperties = new Dictionary <string, string>() { { "FSharpCompilerPath", Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) } }; buildProject = buildEngine.LoadProject(fullProjectPath, globalProperties, null); buildProject.IsBuildEnabled = true; } return(buildProject); }
public void UnavailableEnvironments() { var collection = new Microsoft.Build.Evaluation.ProjectCollection(); try { var service = new MockInterpreterOptionsService(); var proj = collection.LoadProject(TestData.GetPath(@"TestData\Environments\Unavailable.pyproj")); using (var provider = new MSBuildProjectInterpreterFactoryProvider(service, proj)) { try { provider.DiscoverInterpreters(); Assert.Fail("Expected InvalidDataException in DiscoverInterpreters"); } catch (InvalidDataException ex) { AssertUtil.AreEqual(ex.Message .Replace(TestData.GetPath("TestData\\Environments\\"), "$") .Split('\r', '\n') .Where(s => !string.IsNullOrEmpty(s)) .Select(s => s.Trim()), "Some project interpreters failed to load:", @"Interpreter $env\ has invalid value for 'Id': INVALID ID", @"Interpreter $env\ has invalid value for 'Version': INVALID VERSION", @"Base interpreter $env\ has invalid value for 'BaseInterpreter': INVALID BASE", @"Interpreter $env\ has invalid value for 'InterpreterPath': INVALID<>PATH", @"Interpreter $env\ has invalid value for 'WindowsInterpreterPath': INVALID<>PATH", @"Interpreter $env\ has invalid value for 'LibraryPath': INVALID<>PATH", @"Base interpreter $env\ has invalid value for 'BaseInterpreter': {98512745-4ac7-4abb-9f33-120af32edc77}" ); } var factories = provider.GetInterpreterFactories().ToList(); foreach (var fact in factories) { Console.WriteLine("{0}: {1}", fact.GetType().FullName, fact.Description); } foreach (var fact in factories) { Assert.IsInstanceOfType( fact, typeof(MSBuildProjectInterpreterFactoryProvider.NotFoundInterpreterFactory), string.Format("{0} was not correct type", fact.Description) ); Assert.IsFalse(provider.IsAvailable(fact), string.Format("{0} was not unavailable", fact.Description)); } AssertUtil.AreEqual(factories.Select(f => f.Description), "Invalid BaseInterpreter (unavailable)", "Invalid InterpreterPath (unavailable)", "Invalid WindowsInterpreterPath (unavailable)", "Invalid LibraryPath (unavailable)", "Absent BaseInterpreter (unavailable)", "Unknown Python 2.7" ); } } finally { collection.UnloadAllProjects(); collection.Dispose(); } }
private static MSB.Evaluation.Project FindProject( string path, IDictionary <string, string> globalProperties, MSB.Evaluation.ProjectCollection projectCollection, CancellationToken cancellationToken) { var loadedProjects = projectCollection.GetLoadedProjects(path); if (loadedProjects == null || loadedProjects.Count == 0) { return(null); } // We need to walk through all of the projects that have been previously loaded from this path and // find the one that has the given set of global properties, plus the default global properties that // we load every project with. globalProperties = globalProperties ?? ImmutableDictionary <string, string> .Empty; var totalGlobalProperties = projectCollection.GlobalProperties.Count + globalProperties.Count; foreach (var loadedProject in loadedProjects) { cancellationToken.ThrowIfCancellationRequested(); // If this project has a different number of global properties than we expect, it's not the // one we're looking for. if (loadedProject.GlobalProperties.Count != totalGlobalProperties) { continue; } // Since we loaded all of them, the projects in this collection should all have the default // global properties (i.e. the ones in _projectCollection.GlobalProperties). So, we just need to // check the extra global properties. var found = true; foreach (var(key, value) in globalProperties) { // MSBuild escapes the values of a project's global properties, so we must too. var escapedValue = MSB.Evaluation.ProjectCollection.Escape(value); if (!loadedProject.GlobalProperties.TryGetValue(key, out var actualValue) || !string.Equals(actualValue, escapedValue, StringComparison.Ordinal)) { found = false; break; } } if (found) { return(loadedProject); } } // We couldn't find a project with this path and the set of global properties we expect. return(null); }
public static Microsoft.Build.Evaluation.ProjectCollection InitializeMsBuildEngine(Microsoft.Build.Evaluation.ProjectCollection existingEngine) { if (existingEngine == null) { Microsoft.Build.Evaluation.ProjectCollection buildEngine = Microsoft.Build.Evaluation.ProjectCollection.GlobalProjectCollection; return(buildEngine); } return(existingEngine); }
public void UnavailableEnvironments() { var collection = new Microsoft.Build.Evaluation.ProjectCollection(); try { var service = new MockInterpreterOptionsService(); var proj = collection.LoadProject(TestData.GetPath(@"TestData\Environments\Unavailable.pyproj")); var contextProvider = new MockProjectContextProvider(proj); var logger = new MockLogger(); using (var provider = new MSBuildProjectInterpreterFactoryProvider( new[] { new Lazy <IProjectContextProvider>(() => contextProvider) }, null, new[] { new Lazy <IInterpreterLog>(() => logger) })) { var configs = provider.GetInterpreterConfigurations().ToArray(); // force the load... AssertUtil.AreEqual( logger.Errors.ToString() .Replace(TestData.GetPath("TestData\\Environments\\"), "$") .Split('\r', '\n') .Where(s => !string.IsNullOrEmpty(s)) .Select(s => s.Trim()), @"Interpreter $env\ has invalid value for 'Id':", @"Interpreter $env\ has invalid value for 'Version': INVALID VERSION", @"Interpreter $env\ has invalid value for 'InterpreterPath': INVALID<>PATH", @"Interpreter $env\ has invalid value for 'WindowsInterpreterPath': INVALID<>PATH" ); var factories = provider.GetInterpreterFactories().ToList(); foreach (var fact in factories) { Console.WriteLine("{0}: {1}", fact.GetType().FullName, fact.Configuration.Description); } foreach (var fact in factories) { Assert.IsInstanceOfType( fact, typeof(NotFoundInterpreterFactory), string.Format("{0} was not correct type", fact.Configuration.Description) ); Assert.IsFalse(fact.Configuration.IsAvailable(), string.Format("{0} was not unavailable", fact.Configuration.Description)); } AssertUtil.AreEqual(factories.Select(f => f.Configuration.Description), "Invalid InterpreterPath (unavailable)", "Invalid WindowsInterpreterPath (unavailable)" ); } } finally { collection.UnloadAllProjects(); collection.Dispose(); } }
internal static ProjectInstance LoadProjectInstance(MSBuild.Evaluation.ProjectCollection projectCollection, ProjectRootElement rootElement, IDictionary <string, string> globalProps) { lock (SolutionProjectCollectionLock) { string toolsVersion = rootElement.ToolsVersion; if (string.IsNullOrEmpty(toolsVersion)) { toolsVersion = projectCollection.DefaultToolsVersion; } return(new ProjectInstance(rootElement, globalProps, toolsVersion, projectCollection)); } }
private static void CheckMSBuildToolset() { // Check that we can create a project using (var projectCollection = new Microsoft.Build.Evaluation.ProjectCollection()) { if (projectCollection.GetToolset("15.0") == null) { throw new InvalidOperationException("Could not find MSBuild toolset 15.0"); } } }
private static void CheckMSBuildToolset() { // Check that we can create a project using (var projectCollection = new Microsoft.Build.Evaluation.ProjectCollection()) { if (projectCollection.GetToolset("Current") == null) // VS 2019+ (https://github.com/Microsoft/msbuild/issues/3778) { throw new InvalidOperationException("Could not find a supported MSBuild toolset version (expected 16.0 or later)"); } } }
public void VisitInstallTargetsCommand(InstallTargetsToVSProjectFileOptions options) { _Logger.LogInfo(string.Format("Installing targets to: {0}", options.ProjectName)); Microsoft.Build.Evaluation.ProjectCollection collection = new Microsoft.Build.Evaluation.ProjectCollection(); Microsoft.Build.Evaluation.Project project = new Microsoft.Build.Evaluation.Project(options.ProjectName, null, null, collection, Microsoft.Build.Evaluation.ProjectLoadSettings.IgnoreMissingImports); var installHelper = new InstallTargetsHelper(_Logger); var toolsDir = options.ToolsPath.TrimEnd(new char[] { '\\', '/' }); this.Success = installHelper.Install(project, toolsDir); }
public void Stop() { if (!_started) { throw new InvalidOperationException(); } MSB.Execution.BuildManager.DefaultBuildManager.EndBuild(); // unload project so collection will release global strings _projectCollection.UnloadAllProjects(); _projectCollection = null; _logger = null; _started = false; }
private static bool CheckMSBuildToolset() { // Check that we can create a project try { using (var projectCollection = new Microsoft.Build.Evaluation.ProjectCollection()) { return(projectCollection.GetToolset("15.0") != null); } } catch { return(false); } }
private MSB.Evaluation.Project EvaluateProjectFileCore(string filePath, IReadOnlyDictionary <string, string> projectConfigurationsInSolution = null) { var localProperties = new Dictionary <string, string>(_globalProperties); if (projectConfigurationsInSolution != null && localProperties.TryGetValue(PropertyNames.Configuration, out string solutionConfiguration)) { if (!localProperties.TryGetValue(PropertyNames.Platform, out string solutionPlatform)) { solutionPlatform = "Any CPU"; } var solutionSelector = $"{solutionConfiguration}|{solutionPlatform}.ActiveCfg"; _logger.LogDebug($"Found configuration `{solutionSelector}` in solution for '{filePath}'."); if (projectConfigurationsInSolution.TryGetValue(solutionSelector, out string projectSelector)) { var splitted = projectSelector.Split('|'); if (splitted.Length == 2) { var projectConfiguration = splitted[0]; localProperties[PropertyNames.Configuration] = projectConfiguration; // NOTE: Solution often defines configuration as `Any CPU` whereas project relies on `AnyCPU` var projectPlatform = splitted[1].Replace("Any CPU", "AnyCPU"); localProperties[PropertyNames.Platform] = projectPlatform; _logger.LogDebug($"Using configuration from solution: `{projectConfiguration}|{projectPlatform}`"); } } } // Evaluate the MSBuild project var projectCollection = new MSB.Evaluation.ProjectCollection(localProperties); var toolsVersion = _options.ToolsVersion; if (string.IsNullOrEmpty(toolsVersion) || Version.TryParse(toolsVersion, out _)) { toolsVersion = projectCollection.DefaultToolsVersion; } toolsVersion = GetLegalToolsetVersion(toolsVersion, projectCollection.Toolsets); var project = projectCollection.LoadProject(filePath, toolsVersion); SetTargetFrameworkIfNeeded(project); return(project); }
private static void addReference(string projectFile, string filename) { using (var collection = new Microsoft.Build.Evaluation.ProjectCollection()) { collection.LoadProject(projectFile); var project = collection.LoadedProjects.FirstOrDefault(o => o.FullPath == projectFile); var items = project.GetItems("Compile"); if (!items.Any(o => o.EvaluatedInclude == filename || o.UnevaluatedInclude == filename)) { project.AddItem("Compile", filename); project.Save(); } collection.UnloadProject(project); } }
private MSB.Evaluation.Project EvaluateProjectFileCore(string filePath) { // Evaluate the MSBuild project var projectCollection = new MSB.Evaluation.ProjectCollection(_globalProperties); var toolsVersion = _options.ToolsVersion; if (string.IsNullOrEmpty(toolsVersion) || Version.TryParse(toolsVersion, out _)) { toolsVersion = projectCollection.DefaultToolsVersion; } toolsVersion = GetLegalToolsetVersion(toolsVersion, projectCollection.Toolsets); return(projectCollection.LoadProject(filePath, toolsVersion)); }
/// <summary> /// Loads a project file for the file. If the build project exists and it was loaded with a different file then it is unloaded first. /// </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> /// <param name="exitingBuildProject">An Existing build project that will be reloaded.</param> /// <returns>A loaded msbuild project.</returns> public static Microsoft.Build.Evaluation.Project ReinitializeMsBuildProject(Microsoft.Build.Evaluation.ProjectCollection buildEngine, string fullProjectPath, Microsoft.Build.Evaluation.Project exitingBuildProject) { // If we have a build project that has been loaded with another file unload it. try { if (exitingBuildProject != null && exitingBuildProject.ProjectCollection != null) // TODO && !NativeMethods.IsSamePath(exitingBuildProject.FullFileName, fullProjectPath)) { MSBuildProject.FullyUnloadProject(buildEngine, exitingBuildProject); } } // We catch Invalid operation exception because if the project was unloaded while we touch the ParentEngine the msbuild API throws. // Is there a way to figure out that a project was unloaded? catch (InvalidOperationException) { } return(Utilities.InitializeMsBuildProject(buildEngine, fullProjectPath)); }
private static async Task CleanIntermediateAsset(DTE2 dte, Project project) { if (project.FileName == null || Path.GetExtension(project.FileName) != ".csproj") { return; } // Find current project active configuration var configManager = project.ConfigurationManager; var activeConfig = configManager.ActiveConfiguration; // Get global parameters for Configuration and Platform var globalProperties = new Dictionary <string, string>(); globalProperties["Configuration"] = activeConfig.ConfigurationName; globalProperties["Platform"] = activeConfig.PlatformName == "Any CPU" ? "AnyCPU" : activeConfig.PlatformName; // Check if project has a StrideCurrentPackagePath var projectInstance = new ProjectInstance(project.FileName, globalProperties, null); var packagePathProperty = projectInstance.Properties.FirstOrDefault(x => x.Name == "StrideCurrentPackagePath"); if (packagePathProperty == null) { return; } // Prepare build request var request = new BuildRequestData(project.FileName, globalProperties, null, new[] { "StrideCleanAsset" }, null); var pc = new Microsoft.Build.Evaluation.ProjectCollection(); var buildParameters = new BuildParameters(pc); var buildLogger = new IDEBuildLogger(GetOutputPane(), new TaskProvider(ServiceProvider), VsHelper.ToHierarchy(project)); buildParameters.Loggers = new[] { buildLogger }; // Trigger async build buildLogger.OutputWindowPane.OutputStringThreadSafe(string.Format("Cleaning assets for project {0}...\r\n", project.Name)); BuildManager.DefaultBuildManager.BeginBuild(buildParameters); var submission = BuildManager.DefaultBuildManager.PendBuildRequest(request); BuildResult buildResult = await submission.ExecuteAsync(); BuildManager.DefaultBuildManager.EndBuild(); buildLogger.OutputWindowPane.OutputStringThreadSafe("Done\r\n"); }
public Task <(MSB.Evaluation.Project?project, DiagnosticLog log)> LoadProjectAsync( string path, CancellationToken cancellationToken) { if (_batchBuildStarted) { return(LoadProjectAsync(path, _batchBuildProjectCollection, cancellationToken)); } else { var projectCollection = new MSB.Evaluation.ProjectCollection(AllGlobalProperties); try { return(LoadProjectAsync(path, projectCollection, cancellationToken)); } finally { // unload project so collection will release global strings projectCollection.UnloadAllProjects(); } } }
static void CallMSBuild(string newProjName, string configuration, string platform) { var pc = new Microsoft.Build.Evaluation.ProjectCollection(); var param = new BuildParameters(pc); param.Loggers = new[] { new ConsoleLogger() { ShowSummary = true, Verbosity = Microsoft.Build.Framework.LoggerVerbosity.Minimal, SkipProjectStartedText = true, } }; var pros = new Dictionary <string, string>(); pros["Platform"] = platform; pros["Configuration"] = configuration; var request = new BuildRequestData(newProjName, pros, null, new string[] { "Build" }, null); var result = BuildManager.DefaultBuildManager.Build(param, request); }
static bool TryLoadProjectFromCsproj(string csprojFullPath, out Microsoft.Build.Evaluation.Project project, out string projectName, out Context.ProjectType projectType, out Context.ProjectOutputType projectOutputType) { try { Microsoft.Build.Evaluation.ProjectCollection collection = new Microsoft.Build.Evaluation.ProjectCollection(); collection.DefaultToolsVersion = "4.0"; Microsoft.Build.Evaluation.Project theProject = collection.LoadProject(csprojFullPath); string projectTypeGuids = theProject.GetPropertyValue("ProjectTypeGuids"); //cf. https://github.com/Microsoft/visualfsharp/blob/master/vsintegration/src/FSharp.ProjectSystem.Base/Project/ProjectFactory.cs string isSilverlightApplicationString = theProject.GetPropertyValue("SilverlightApplication"); // Get the project name: projectName = System.IO.Path.GetFileNameWithoutExtension(csprojFullPath); // Get the Project Type: projectType = GetProjectType(projectTypeGuids); // Get the project Output Type: Func <string, string> functionToGetAProjectProperty = (string propertyName) => { return(theProject.GetPropertyValue(propertyName)); }; projectOutputType = GetProjectOutputType(projectType, functionToGetAProjectProperty, functionToGetAProjectProperty); // Return the project itself as well: project = theProject; return(true); } catch (Exception ex) { MessageBox.Show(ex.ToString()); project = null; projectName = null; projectType = Context.ProjectType.Other; projectOutputType = Context.ProjectOutputType.Unknown; return(false); } }
public void Start() { if (_started) { throw new InvalidOperationException(); } _projectCollection = new MSB.Evaluation.ProjectCollection(s_defaultGlobalProperties); _logger = new MSBuildDiagnosticLogger() { Verbosity = MSB.Framework.LoggerVerbosity.Normal }; var buildParameters = new MSB.Execution.BuildParameters(_projectCollection) { Loggers = new MSB.Framework.ILogger[] { _logger } }; MSB.Execution.BuildManager.DefaultBuildManager.BeginBuild(buildParameters); _started = true; }
private string GetAttributeFromProject( string attributeName, string filePath, Configuration config, Project project) { Dictionary <string, string> dictionary = new Dictionary <string, string> { { "Configuration", config.ConfigurationName }, { "Platform", config.PlatformName }, { "BuildingSolutionFile", "true" }, { "BuildingInsideVisualStudio", "true" } }; using (Microsoft.Build.Evaluation.ProjectCollection projectCollection = new Microsoft.Build.Evaluation.ProjectCollection((IDictionary <string, string>)CreatePropertyDict(_dte.Solution.FullName))) { Microsoft.Build.Evaluation.Project project2 = new Microsoft.Build.Evaluation.Project(Microsoft.Build.Construction.ProjectRootElement.Open(project.FullName, projectCollection), (IDictionary <string, string>)dictionary, (string)null, projectCollection); foreach (var allEvaluatedItem in project2.AllEvaluatedItems) { if (allEvaluatedItem.ItemType == "ClCompile") { var evaluated = Path.Combine(project2.DirectoryPath, allEvaluatedItem.EvaluatedInclude); try { evaluated = Path.GetFullPath(evaluated); } catch (Exception) { } if (evaluated.ToLower() == filePath.ToLower()) { var attribute = allEvaluatedItem.GetMetadataValue(attributeName); return(attribute); } } } } throw new Exception(String.Format("tried to find attribute {0} but failed", attributeName)); }
/// <summary> /// Disposes the project node object. /// </summary> /// <param name="disposing">Flag determining ehether it was deterministic or non deterministic clean up.</param> protected override void Dispose(bool disposing) { if (this.isDisposed) { return; } try { try { this.UnRegisterProject(); } finally { try { this.RegisterClipboardNotifications(false); } finally { try { if (this.projectEventsProvider != null) { this.projectEventsProvider.AfterProjectFileOpened -= this.OnAfterProjectOpen; } if (this.taskProvider != null) { this.taskProvider.Tasks.Clear(); this.taskProvider.Refresh(); this.taskProvider.Dispose(); this.taskProvider = null; } if (buildLogger != null) { buildLogger = null; } this.site = null; } finally { if (this.buildEngine != null) { this.buildEngine.UnregisterAllLoggers(); this.buildEngine = null; } } } } if (this.buildProject != null) { //this.projectInstance = null; MSBuildProject.FullyUnloadProject(this.buildProject.ProjectCollection, this.buildProject); SetBuildProject(null); } if (null != imageHandler) { imageHandler.Close(); imageHandler = null; } } finally { base.Dispose(disposing); this.isDisposed = true; } }
public ProjectFactory(Microsoft.VisualStudio.Shell.Package package) { this.package = package; this.site = package; this.buildEngine = Utilities.InitializeMsBuildEngine(this.buildEngine); }
public virtual void Load(string fileName, string location, string name, uint flags, ref Guid iidProject, out int canceled) { try { this.disableQueryEdit = true; // set up internal members and icons canceled = 0; this.ProjectMgr = this; this.isNewProject = false; // We need to set the project guid before we check the project for security. if ((flags & (uint)__VSCREATEPROJFLAGS.CPF_CLONEFILE) == (uint)__VSCREATEPROJFLAGS.CPF_CLONEFILE) { // we need to generate a new guid for the project this.projectIdGuid = Guid.NewGuid(); } else { this.SetProjectGuidFromProjectFile(); } // This is almost a No op if the engine has already been instantiated in the factory. this.buildEngine = Utilities.InitializeMsBuildEngine(this.buildEngine, this.Site); // based on the passed in flags, this either reloads/loads a project, or tries to create a new one // now we create a new project... we do that by loading the template and then saving under a new name // we also need to copy all the associated files with it. if ((flags & (uint)__VSCREATEPROJFLAGS.CPF_CLONEFILE) == (uint)__VSCREATEPROJFLAGS.CPF_CLONEFILE) { Debug.Assert(!String.IsNullOrEmpty(fileName) && File.Exists(fileName), "Invalid filename passed to load the project. A valid filename is expected"); this.isNewProject = true; // This should be a very fast operation if the build project is already initialized by the Factory. SetBuildProject(Utilities.ReinitializeMsBuildProject(this.buildEngine, fileName, this.buildProject, this.Site)); // Compute the file name // We try to solve two problems here. When input comes from a wizzard in case of zipped based projects // the parameters are different. // In that case the filename has the new filename in a temporay path. // First get the extension from the template. // Then get the filename from the name. // Then create the new full path of the project. string extension = Path.GetExtension(fileName); string tempName = String.Empty; // We have to be sure that we are not going to loose data here. If the project name is a.b.c then for a project that was based on a zipped template(the wizzard calls us) GetFileNameWithoutExtension will suppress "c". // We are going to check if the parameter "name" is extension based and the extension is the same as the one from the "filename" parameter. string tempExtension = Path.GetExtension(name); if (!String.IsNullOrEmpty(tempExtension)) { bool isSameExtension = (String.Compare(tempExtension, extension, StringComparison.OrdinalIgnoreCase) == 0); if (isSameExtension) { tempName = Path.GetFileNameWithoutExtension(name); } // If the tempExtension is not the same as the extension that the project name comes from then assume that the project name is a dotted name. else { tempName = Path.GetFileName(name); } } else { tempName = Path.GetFileName(name); } Debug.Assert(!String.IsNullOrEmpty(tempName), "Could not compute project name"); string tempProjectFileName = tempName + extension; this.filename = Path.Combine(location, tempProjectFileName); // Initialize the common project properties. this.InitializeProjectProperties(); ErrorHandler.ThrowOnFailure(this.Save(this.filename, 1, 0)); // now we do have the project file saved. we need to create embedded files. foreach (var item in MSBuildProject.GetStaticAndVisibleItemsInOrder(this.buildProject)) { // Ignore the item if it is a reference or folder if (this.FilterItemTypeToBeAddedToHierarchy(MSBuildItem.GetItemType(item))) { continue; } // MSBuilds tasks/targets can create items (such as object files), // such items are not part of the project per say, and should not be displayed. // so ignore those items. if (!this.IsItemTypeFileType(item.ItemType)) { continue; } string strRelFilePath = MSBuildItem.GetEvaluatedInclude(item); string basePath = Path.GetDirectoryName(fileName); string strPathToFile; string newFileName; // taking the base name from the project template + the relative pathname, // and you get the filename strPathToFile = Path.Combine(basePath, strRelFilePath); // the new path should be the base dir of the new project (location) + the rel path of the file newFileName = Path.Combine(location, strRelFilePath); // now the copy file AddFileFromTemplate(strPathToFile, newFileName); } } else { this.filename = fileName; } // now reload to fix up references this.Reload(); } finally { this.disableQueryEdit = false; } }
public void UnavailableEnvironments() { var collection = new Microsoft.Build.Evaluation.ProjectCollection(); try { var service = new MockInterpreterOptionsService(); var proj = collection.LoadProject(TestData.GetPath(@"TestData\Environments\Unavailable.pyproj")); var contextProvider = new MockProjectContextProvider(proj); var logger = new MockLogger(); using (var provider = new MSBuildProjectInterpreterFactoryProvider( new[] { new Lazy<IProjectContextProvider>(() => contextProvider) }, null, new[] { new Lazy<IInterpreterLog>(() => logger) })) { var configs = provider.GetInterpreterConfigurations().ToArray(); // force the load... AssertUtil.AreEqual( logger.Errors.ToString() .Replace(TestData.GetPath("TestData\\Environments\\"), "$") .Split('\r', '\n') .Where(s => !string.IsNullOrEmpty(s)) .Select(s => s.Trim()), @"Interpreter $env\ has invalid value for 'Id':", @"Interpreter $env\ has invalid value for 'Version': INVALID VERSION", @"Interpreter $env\ has invalid value for 'InterpreterPath': INVALID<>PATH", @"Interpreter $env\ has invalid value for 'WindowsInterpreterPath': INVALID<>PATH" ); var factories = provider.GetInterpreterFactories().ToList(); foreach (var fact in factories) { Console.WriteLine("{0}: {1}", fact.GetType().FullName, fact.Configuration.Description); } foreach (var fact in factories) { Assert.IsInstanceOfType( fact, typeof(NotFoundInterpreterFactory), string.Format("{0} was not correct type", fact.Configuration.Description) ); Assert.IsFalse(fact.Configuration.IsAvailable(), string.Format("{0} was not unavailable", fact.Configuration.Description)); } AssertUtil.AreEqual(factories.Select(f => f.Configuration.Description), "Invalid InterpreterPath (unavailable)", "Invalid WindowsInterpreterPath (unavailable)" ); } } finally { collection.UnloadAllProjects(); collection.Dispose(); } }
public void UnavailableEnvironments() { var collection = new Microsoft.Build.Evaluation.ProjectCollection(); try { var service = new MockInterpreterOptionsService(); var proj = collection.LoadProject(TestData.GetPath(@"TestData\Environments\Unavailable.pyproj")); using (var provider = new MSBuildProjectInterpreterFactoryProvider(service, proj)) { try { provider.DiscoverInterpreters(); Assert.Fail("Expected InvalidDataException in DiscoverInterpreters"); } catch (InvalidDataException ex) { AssertUtil.AreEqual(ex.Message .Replace(TestData.GetPath("TestData\\Environments\\"), "$") .Split('\r', '\n') .Where(s => !string.IsNullOrEmpty(s)) .Select(s => s.Trim()), "Some project interpreters failed to load:", @"Interpreter $env\ has invalid value for 'Id': INVALID ID", @"Interpreter $env\ has invalid value for 'Version': INVALID VERSION", @"Interpreter $env\ has invalid value for 'BaseInterpreter': INVALID BASE", @"Interpreter $env\ has invalid value for 'InterpreterPath': INVALID<>PATH", @"Interpreter $env\ has invalid value for 'WindowsInterpreterPath': INVALID<>PATH", @"Interpreter $env\ has invalid value for 'LibraryPath': INVALID<>PATH", @"Interpreter $env\ has invalid value for 'BaseInterpreter': {98512745-4ac7-4abb-9f33-120af32edc77}" ); } var factories = provider.GetInterpreterFactories().ToList(); foreach (var fact in factories) { Console.WriteLine("{0}: {1}", fact.GetType().FullName, fact.Description); } foreach (var fact in factories) { Assert.IsInstanceOfType( fact, typeof(MSBuildProjectInterpreterFactoryProvider.NotFoundInterpreterFactory), string.Format("{0} was not correct type", fact.Description) ); Assert.IsFalse(provider.IsAvailable(fact), string.Format("{0} was not unavailable", fact.Description)); } AssertUtil.AreEqual(factories.Select(f => f.Description), "Invalid BaseInterpreter (unavailable)", "Invalid InterpreterPath (unavailable)", "Invalid WindowsInterpreterPath (unavailable)", "Invalid LibraryPath (unavailable)", "Absent BaseInterpreter (unavailable)", "Unknown Python 2.7" ); } } finally { collection.UnloadAllProjects(); collection.Dispose(); } }
/// <summary> /// Saves a .props file for the specified package, containing the paradox version (only Major.Minor) /// used to compile the package. /// </summary> /// <param name="package">The package.</param> public static void SaveProperties(Package package) { // Props file is in the same folder as the pdxpkg file, just with a ".props" extension. var packagePath = package.FullPath; var propsFilePath = UPath.Combine(packagePath.GetParent(), (UFile)(packagePath.GetFileName() + ".props")) ; var projectCollection = new Microsoft.Build.Evaluation.ProjectCollection(); var project = new Microsoft.Build.Evaluation.Project(projectCollection); var commonPropertyGroup = project.Xml.AddPropertyGroup(); var dependencies = package.FindDependencies(false, false, true); // Add Paradox version var pdxVersion = dependencies.FirstOrDefault(d => d.Meta.Name == "Paradox"); if (pdxVersion != null) { var versionText = pdxVersion.Meta.Version.Version.Major + "." + pdxVersion.Meta.Version.Version.Minor; commonPropertyGroup.AddProperty("SiliconStudioPackageParadoxVersion", versionText); } if (File.Exists(propsFilePath)) { File.Delete(propsFilePath); } project.Save(propsFilePath); }
public void TestTargetFrameworkVersionGreaterThan4() { string tmpFileName = FileUtilities.GetTemporaryFile(); File.Delete(tmpFileName); string projectFilePath = tmpFileName + ".sln"; string solutionFileContents = @" Microsoft Visual Studio Solution File, Format Version 11.00 # Visual Studio 2010 Project('{E24C65DC-7377-472B-9ABA-BC803B73C61A}') = 'WebSite1', '..\WebSite1\', '{6B8F98F2-C976-4029-9321-5CCD73A174DA}' ProjectSection(WebsiteProperties) = preProject TargetFrameworkMoniker = '.NETFramework,Version=v4.34' Debug.AspNetCompiler.VirtualPath = '/WebSite1' Debug.AspNetCompiler.PhysicalPath = '..\WebSite1\' Debug.AspNetCompiler.TargetPath = 'PrecompiledWeb\WebSite1\' Debug.AspNetCompiler.Updateable = 'true' Debug.AspNetCompiler.ForceOverwrite = 'true' Debug.AspNetCompiler.FixedNames = 'false' Debug.AspNetCompiler.Debug = 'True' Release.AspNetCompiler.VirtualPath = '/WebSite1' Release.AspNetCompiler.PhysicalPath = '..\WebSite1\' Release.AspNetCompiler.TargetPath = 'PrecompiledWeb\WebSite1\' Release.AspNetCompiler.Updateable = 'true' Release.AspNetCompiler.ForceOverwrite = 'true' Release.AspNetCompiler.FixedNames = 'false' Release.AspNetCompiler.Debug = 'False' VWDPort = '45602' DefaultWebSiteLanguage = 'Visual Basic' EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {6B8F98F2-C976-4029-9321-5CCD73A174DA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {6B8F98F2-C976-4029-9321-5CCD73A174DA}.Debug|Any CPU.Build.0 = Debug|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal "; try { MockLogger logger = new MockLogger(); Dictionary<string, string> globalProperties = new Dictionary<string, string>(); globalProperties["Configuration"] = "Release"; globalProperties["SkipInvalidConfigurations"] = "true"; SolutionFile solution = SolutionFile_Tests.ParseSolutionHelper(solutionFileContents.Replace('\'', '"')); ProjectCollection collection = new ProjectCollection(); collection.RegisterLogger(logger); ProjectInstance[] instances = SolutionProjectGenerator.Generate(solution, globalProperties, null, BuildEventContext.Invalid, collection.LoggingService); Version ver = new Version("4.34"); string message = ResourceUtilities.FormatResourceString("AspNetCompiler.TargetingHigherFrameworksDefaultsTo40", solution.ProjectsInOrder[0].ProjectName, ver.ToString()); logger.AssertLogContains(message); } finally { File.Delete(projectFilePath); } }