protected override string GenerateFullPathToTool() { return(ToolLocationHelper.GetPathToSystemFile("cmd.exe")); }
/// <summary> /// Return the path to the tool to execute. /// </summary> override protected string GenerateFullPathToTool() { string pathToTool = ToolLocationHelper.GetPathToBuildToolsFile(ToolName, ToolLocationHelper.CurrentToolsVersion); if (null == pathToTool) { pathToTool = ToolLocationHelper.GetPathToDotNetFrameworkFile(ToolName, TargetDotNetFrameworkVersion.VersionLatest); if (null == pathToTool) { Log.LogErrorWithCodeFromResources("General.FrameworksFileNotFound", ToolName, ToolLocationHelper.GetDotNetFrameworkVersionFolderPrefix(TargetDotNetFrameworkVersion.VersionLatest)); } } return(pathToTool); }
internal static string FindSDKToolUsingToolsLocationHelper(string toolName) { return(ToolLocationHelper.GetPathToDotNetFrameworkSdkFile(toolName, TargetDotNetFrameworkVersion.Version40)); }
public Engine(BuildPropertyGroup globalProperties) : this(ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version20)) { this.global_properties = globalProperties; }
private static XmlElement GetXmlElement(string targetZone, FrameworkNameVersioning fn) { IList <string> paths = ToolLocationHelper.GetPathToReferenceAssemblies(fn); // Is the targeted CLR even installed? if (paths.Count > 0) { // first one is always framework requested. string path = Path.Combine(paths[0], PermissionSetsFolder); // PermissionSets folder doesn't exit if (Directory.Exists(path)) { string[] files = Directory.GetFiles(path, "*.xml"); FileInfo[] filesInfo = new FileInfo[files.Length]; int indexFound = -1; // trim the extension. for (int i = 0; i < files.Length; i++) { filesInfo[i] = new FileInfo(files[i]); string fileInfoNoExt = Path.GetFileNameWithoutExtension(files[i]); if (string.Equals(fileInfoNoExt, targetZone, StringComparison.OrdinalIgnoreCase)) { indexFound = i; break; } } if (indexFound != -1) { string data = string.Empty; FileInfo resultFile = filesInfo[indexFound]; using (FileStream fs = resultFile.OpenRead()) { try { StreamReader sr = new StreamReader(fs); data = sr.ReadToEnd(); // fs.Position value will be the length of the stream. if (!string.IsNullOrEmpty(data)) { XmlDocument doc = new XmlDocument(); XmlReaderSettings xrSettings = new XmlReaderSettings(); xrSettings.DtdProcessing = DtdProcessing.Ignore; // http://msdn.microsoft.com/en-us/library/h2344bs2(v=vs.110).aspx // PermissionSets do not conform to document level, which is the default setting. xrSettings.ConformanceLevel = ConformanceLevel.Auto; try { fs.Position = 0; // Reset to 0 before using this stream in any other reader. using (XmlReader xr = XmlReader.Create(fs, xrSettings)) { doc.Load(xr); return((XmlElement)doc.DocumentElement); } } catch (Exception) { //continue. } } } catch (ArgumentException) { //continue. } } } } } return(GetCurrentCLRPermissions(targetZone)); }
static string GetPathToPEVerify() { return(Path.Combine(ToolLocationHelper.GetPathToDotNetFrameworkSdk(TargetDotNetFrameworkVersion.Version40), @"bin\NETFX 4.0 Tools\peverify.exe")); }
public Engine() : this(ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version20)) { }
public static bool ReferenceAssembliesAreInstalled(TargetDotNetFrameworkVersion targetFrameworkVersion) { var referenceAssemblies = ToolLocationHelper.GetPathToDotNetFrameworkReferenceAssemblies(targetFrameworkVersion); return(referenceAssemblies != null); }
public override bool Execute() { path = ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version20); return(true); }
/// <summary>See <see cref="ToolTask.GenerateFullPathToTool"/>.</summary> protected override string GenerateFullPathToTool() { return(ToolLocationHelper.GetPathToDotNetFrameworkSdkFile(this.ToolName, TargetDotNetFrameworkVersion.VersionLatest)); }
/// <summary> /// Get the SDK. /// </summary> /// <returns>true</returns> public override bool Execute() { // TargetPlatformVersion and TargetPlatformIdentifier are requried to correctly look for SDKs. if (String.IsNullOrEmpty(TargetPlatformVersion) || String.IsNullOrEmpty(TargetPlatformIdentifier)) { Log.LogErrorWithCodeFromResources("GetInstalledSDKs.TargetPlatformInformationMissing"); return(false); } // Dictionary of ESDKs. Each entry is a (location, platform version) tuple IDictionary <string, Tuple <string, string> > installedSDKs = null; try { Log.LogMessageFromResources("GetInstalledSDKs.SearchingForSDKs", _targetPlatformIdentifier, _targetPlatformVersion); Version platformVersion = Version.Parse(TargetPlatformVersion); installedSDKs = ToolLocationHelper.GetPlatformExtensionSDKLocationsAndVersions(SDKDirectoryRoots, SDKExtensionDirectoryRoots, SDKRegistryRoot, TargetPlatformIdentifier, platformVersion); } catch (Exception e) { if (ExceptionHandling.IsCriticalException(e)) { throw; } Log.LogErrorWithCodeFromResources("GetInstalledSDKs.CouldNotGetSDKList", e.Message); } List <ITaskItem> outputItems = new List <ITaskItem>(); if (installedSDKs != null && installedSDKs.Count > 0) { Log.LogMessageFromResources(MessageImportance.Low, "GetInstalledSDKs.FoundSDKs", installedSDKs.Count); Log.LogMessageFromResources(MessageImportance.Low, "GetInstalledSDKs.ListInstalledSDKs"); foreach (KeyValuePair <string, Tuple <string, string> > sdk in installedSDKs) { string sdkInfo = ResourceUtilities.FormatResourceString("GetInstalledSDKs.SDKNameAndLocation", sdk.Key, sdk.Value.Item1); Log.LogMessageFromResources(MessageImportance.Low, "ResolveAssemblyReference.FourSpaceIndent", sdkInfo); TaskItem item = new TaskItem(sdk.Value.Item1); item.SetMetadata("SDKName", sdk.Key); item.SetMetadata("PlatformVersion", sdk.Value.Item2); // Need to stash these so we can unroll the platform via GetMatchingPlatformSDK when we get the reference files for the sdks item.SetMetadata(DirectoryRootsMetadataName, String.Join(";", SDKDirectoryRoots ?? new string[0])); item.SetMetadata(ExtensionDirectoryRootsMetadataName, String.Join(";", SDKExtensionDirectoryRoots ?? new string[0])); item.SetMetadata(RegistryRootMetadataName, SDKRegistryRoot); outputItems.Add(item); } } else { Log.LogWarningWithCodeFromResources("GetInstalledSDKs.NoSDksFound"); } InstalledSDKs = outputItems.ToArray(); // We need to register an object so that at the end of the build we will clear the static toolLocationhelper caches. // this is important because if someone adds an SDK between builds we would not know about it and not be able to use it. // This code is mainly used to deal with the case where msbuild nodes hang around between builds. IBuildEngine4 buildEngine4 = BuildEngine as IBuildEngine4; if (buildEngine4 != null) { object staticCacheDisposer = buildEngine4.GetRegisteredTaskObject(StaticSDKCacheKey, RegisteredTaskObjectLifetime.Build); if (staticCacheDisposer == null) { BuildCacheDisposeWrapper staticDisposer = new BuildCacheDisposeWrapper(new BuildCacheDisposeWrapper.CallDuringDispose(ToolLocationHelper.ClearSDKStaticCache)); buildEngine4.RegisterTaskObject(StaticSDKCacheKey, staticDisposer, RegisteredTaskObjectLifetime.Build, allowEarlyCollection: false); } } return(!Log.HasLoggedErrors); }
[Category("NotWorking")] // this test needs extra xbuild testing settings, as the target framework path is different. public void GetPathToStandardLibraries() { Assert.IsTrue(!string.IsNullOrEmpty(ToolLocationHelper.GetPathToStandardLibraries(".NETFramework", "v4.0", null)), "std path"); Assert.IsTrue(!string.IsNullOrEmpty(ToolLocationHelper.GetPathToStandardLibraries(".NETFramework", "v4.0", string.Empty)), "empty Profile path"); }
///<summary> ///Returns the fully qualified path to the executable file. ///</summary> /// ///<returns> ///The fully qualified path to the executable file. ///</returns> /// protected override string GenerateFullPathToTool() { if (string.IsNullOrEmpty(ToolName)) { throw new InvalidOperationException(string.Format("The tool name must not be empty in the build task.")); } if (string.IsNullOrEmpty(Path.GetExtension(ToolName))) { throw new InvalidOperationException(string.Format("The tool name “{0}” must include the extension.", ToolName)); } // Fetch the tool dir string sToolDir = null; if ((ToolDir != null) && (!string.IsNullOrEmpty(ToolDir.ItemSpec))) // Manual tool dir { Log.LogMessage(MessageImportance.Low, "{0} location is given by the ToolDir property value.", ToolName); sToolDir = ToolDir.ItemSpec; } else if (!string.IsNullOrEmpty(ToolDirEnvName)) // Via env { sToolDir = Environment.GetEnvironmentVariable(ToolDirEnvName); Log.LogMessage(MessageImportance.Low, "{0} location is given by the ToolDirEnvName environment variable (“{1}”).", ToolName, Environment.GetEnvironmentVariable(ToolDirEnvName)); } if (!string.IsNullOrEmpty(sToolDir)) // Use if could be obtained { return(Path.Combine(sToolDir, ToolName)); } // Lookup an SDK file foreach (var action in new Func <string>[] { delegate { return(ToolLocationHelper.GetPathToDotNetFrameworkFile(ToolName, TargetDotNetFrameworkVersion.VersionLatest)); }, delegate { return(ToolLocationHelper.GetPathToDotNetFrameworkSdkFile(ToolName, TargetDotNetFrameworkVersion.VersionLatest)); }, delegate { return(ToolLocationHelper.GetPathToSystemFile(ToolName)); }, delegate { return(ToolLocationHelper.GetPathToDotNetFrameworkFile(ToolName, TargetDotNetFrameworkVersion.Version20)); }, delegate { return(ToolLocationHelper.GetPathToDotNetFrameworkSdkFile(ToolName, TargetDotNetFrameworkVersion.Version20)); }, delegate { return(ToolLocationHelper.GetPathToDotNetFrameworkFile(ToolName, TargetDotNetFrameworkVersion.Version11)); }, delegate { return(ToolLocationHelper.GetPathToDotNetFrameworkSdkFile(ToolName, TargetDotNetFrameworkVersion.Version11)); }, }) { try { string sFullPath = action(); if ((!string.IsNullOrEmpty(sFullPath)) && (File.Exists(sFullPath))) { Log.LogMessage(MessageImportance.Low, "{0} location is given by the ToolLocationHelper (“{1}”).", ToolName, sFullPath); return(sFullPath); } } catch (Exception ex) { Log.LogMessage("Warning when probing for {0}: {1}", ToolName, ex.Message); } } Log.LogMessage(MessageImportance.Low, "{0} location could not be determined, leaving to the shell.", ToolName); return(ToolName); // Fallback to %PATH% on execution }
private string GetTargetPlatformDirectory(string value) { return(ToolLocationHelper.GetPathToDotNetFramework(this.GetTargetPlatform(this.TargetPlatform))); }
internal void InitEvaluation(MSBuildProject project) { this.project = project; // Project file properties properties.Add("MSBuildThisFile", Path.GetFileName(project.FileName)); properties.Add("MSBuildThisFileName", project.FileName.FileNameWithoutExtension); properties.Add("MSBuildThisFileExtension", Path.GetExtension(project.FileName)); properties.Add("MSBuildThisFileFullPath", MSBuildProjectService.ToMSBuildPath(null, project.FileName.FullPath)); string dir = Path.GetDirectoryName(project.FileName) + Path.DirectorySeparatorChar; properties.Add("MSBuildThisFileDirectory", MSBuildProjectService.ToMSBuildPath(null, dir)); properties.Add("MSBuildThisFileDirectoryNoRoot", MSBuildProjectService.ToMSBuildPath(null, dir.Substring(Path.GetPathRoot(dir).Length))); // Properties only set for the root project, not for imported projects if (parentContext == null) { properties.Add("VisualStudioReferenceAssemblyVersion", project.ToolsVersion + ".0.0"); properties.Add("MSBuildProjectDefaultTargets", project.DefaultTargets); properties.Add("MSBuildProjectExtension", Path.GetExtension(project.FileName)); properties.Add("MSBuildProjectFile", project.FileName.FileName); properties.Add("MSBuildProjectFullPath", MSBuildProjectService.ToMSBuildPath(null, project.FileName.FullPath.ToString())); properties.Add("MSBuildProjectName", project.FileName.FileNameWithoutExtension); dir = project.BaseDirectory.IsNullOrEmpty ? Environment.CurrentDirectory : project.BaseDirectory.ToString(); properties.Add("MSBuildProjectDirectory", MSBuildProjectService.ToMSBuildPath(null, dir)); properties.Add("MSBuildProjectDirectoryNoRoot", MSBuildProjectService.ToMSBuildPath(null, dir.Substring(Path.GetPathRoot(dir).Length))); string toolsVersion = project.ToolsVersion; if (string.IsNullOrEmpty(toolsVersion) || Version.Parse(toolsVersion) < new Version("12.0")) { toolsVersion = "12.0"; } string toolsPath = ToolLocationHelper.GetPathToBuildTools("12.0"); var frameworkToolsPath = ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.VersionLatest); properties.Add("MSBuildBinPath", MSBuildProjectService.ToMSBuildPath(null, toolsPath)); properties.Add("MSBuildToolsPath", MSBuildProjectService.ToMSBuildPath(null, toolsPath)); properties.Add("MSBuildToolsRoot", MSBuildProjectService.ToMSBuildPath(null, Path.GetDirectoryName(toolsPath))); properties.Add("MSBuildToolsVersion", toolsVersion); properties.Add("OS", Platform.IsWindows ? "Windows_NT" : "Unix"); properties.Add("MSBuildBinPath32", MSBuildProjectService.ToMSBuildPath(null, toolsPath)); properties.Add("MSBuildFrameworkToolsPath", MSBuildProjectService.ToMSBuildPath(null, frameworkToolsPath)); properties.Add("MSBuildFrameworkToolsPath32", MSBuildProjectService.ToMSBuildPath(null, frameworkToolsPath)); if (!String.IsNullOrEmpty(DefaultExtensionsPath)) { var ep = MSBuildProjectService.ToMSBuildPath(null, extensionsPath); properties.Add("MSBuildExtensionsPath", ep); properties.Add("MSBuildExtensionsPath32", ep); properties.Add("MSBuildExtensionsPath64", ep); } // Environment properties.Add("MSBuildProgramFiles32", MSBuildProjectService.ToMSBuildPath(null, Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86))); } }
public static string GetMsBuildPath() { var getmS = ToolLocationHelper.GetPathToBuildTools(ToolLocationHelper.CurrentToolsVersion); return(getmS); }
/// <summary> /// Create a project using the inputted strings as sources. /// </summary> /// <param name="sources">Classes in the form of strings</param> /// <param name="language">The language the source code is in</param> /// <param name="hasEntrypoint"><c>true</c> to set the compiler in a mode as if it were compiling an exe (as opposed to a dll).</param> /// <param name="includeSDKReferences"><c>true</c> to include VS SDK reference assemblies in the project.</param> /// <returns>A Project created out of the Documents created from the source strings</returns> protected static Project CreateProject(string[] sources, string language = LanguageNames.CSharp, bool hasEntrypoint = false, bool includeSDKReferences = true) { string fileNamePrefix = DefaultFilePathPrefix; string fileExt = language == LanguageNames.CSharp ? CSharpDefaultFileExt : throw new NotSupportedException(); var projectId = ProjectId.CreateNewId(debugName: TestProjectName); var solution = new AdhocWorkspace() .CurrentSolution .AddProject(projectId, TestProjectName, TestProjectName, language) .AddMetadataReference(projectId, CorlibReference) .AddMetadataReference(projectId, SystemReference) .AddMetadataReference(projectId, PresentationFrameworkReference) .AddMetadataReference(projectId, SystemCoreReference) .AddMetadataReference(projectId, MPFReference) .WithProjectCompilationOptions(projectId, new CSharpCompilationOptions( hasEntrypoint ? OutputKind.ConsoleApplication : OutputKind.DynamicallyLinkedLibrary, specificDiagnosticOptions: new Dictionary <string, ReportDiagnostic> { { "CS1701", ReportDiagnostic.Suppress }, // we don't reference mscorlib, which can cause assembly reference ambiguities })) .WithProjectParseOptions(projectId, new CSharpParseOptions(LanguageVersion.CSharp6)); var pathToLibs = ToolLocationHelper.GetPathToStandardLibraries(".NETFramework", "v4.5.1", string.Empty); if (!string.IsNullOrEmpty(pathToLibs)) { var facades = Path.Combine(pathToLibs, "Facades"); if (Directory.Exists(facades)) { var facadesAssemblies = new List <MetadataReference>(); foreach (var path in Directory.EnumerateFiles(facades, "*.dll")) { facadesAssemblies.Add(MetadataReference.CreateFromFile(path)); } solution = solution.AddMetadataReferences(projectId, facadesAssemblies); } } if (includeSDKReferences) { string globalPackagesFolder = Environment.GetEnvironmentVariable("NuGetGlobalPackagesFolder"); string nugetPackageRoot = string.IsNullOrEmpty(globalPackagesFolder) ? Path.Combine( Environment.GetEnvironmentVariable("USERPROFILE"), ".nuget", "packages") : globalPackagesFolder; var vssdkReferences = VSSDKPackageReferences.Select(e => MetadataReference.CreateFromFile(Path.Combine(nugetPackageRoot, e))); solution = solution.AddMetadataReferences(projectId, vssdkReferences); } int count = 0; foreach (var source in sources) { var newFileName = fileNamePrefix + count + "." + fileExt; var documentId = DocumentId.CreateNewId(projectId, debugName: newFileName); solution = solution.AddDocument(documentId, newFileName, SourceText.From(source)); count++; } return(solution.GetProject(projectId)); }
public void GeneratePathToToolX86DoesNotExistAnywhereNoLogging() { string toolPath = SdkToolsPathUtility.GeneratePathToTool(_mockExists.MockFileDoesNotExist, ProcessorArchitecture.X86, _defaultSdkToolsPath, _toolName, _log, false); Assert.Null(toolPath); string comment = ResourceUtilities.FormatResourceString("General.PlatformSDKFileNotFoundSdkToolsPath", _toolName, _defaultSdkToolsPath, _defaultSdkToolsPath); _mockEngine.AssertLogDoesntContain(comment); comment = ResourceUtilities.FormatResourceString("General.SdkToolsPathToolDoesNotExist", _toolName, _defaultSdkToolsPath, ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version45)); _mockEngine.AssertLogDoesntContain(comment); Assert.Equal(0, _mockEngine.Errors); }
internal void InitEvaluation(MSBuildProject project) { this.project = project; // Project file properties properties.Add("MSBuildThisFile", Path.GetFileName(project.FileName)); properties.Add("MSBuildThisFileName", project.FileName.FileNameWithoutExtension); properties.Add("MSBuildThisFileExtension", Path.GetExtension(project.FileName)); properties.Add("MSBuildThisFileFullPath", MSBuildProjectService.ToMSBuildPath(null, project.FileName.FullPath)); string dir = Path.GetDirectoryName(project.FileName) + Path.DirectorySeparatorChar; properties.Add("MSBuildThisFileDirectory", MSBuildProjectService.ToMSBuildPath(null, dir)); properties.Add("MSBuildThisFileDirectoryNoRoot", MSBuildProjectService.ToMSBuildPath(null, dir.Substring(Path.GetPathRoot(dir).Length))); // Properties only set for the root project, not for imported projects if (parentContext == null) { properties.Add("VisualStudioReferenceAssemblyVersion", project.ToolsVersion + ".0.0"); properties.Add("MSBuildProjectDefaultTargets", project.DefaultTargets); properties.Add("MSBuildProjectExtension", Path.GetExtension(project.FileName)); properties.Add("MSBuildProjectFile", project.FileName.FileName); properties.Add("MSBuildProjectFullPath", MSBuildProjectService.ToMSBuildPath(null, project.FileName.FullPath.ToString())); properties.Add("MSBuildProjectName", project.FileName.FileNameWithoutExtension); dir = project.BaseDirectory.IsNullOrEmpty ? Environment.CurrentDirectory : project.BaseDirectory.ToString(); properties.Add("MSBuildProjectDirectory", MSBuildProjectService.ToMSBuildPath(null, dir)); properties.Add("MSBuildProjectDirectoryNoRoot", MSBuildProjectService.ToMSBuildPath(null, dir.Substring(Path.GetPathRoot(dir).Length))); // This MSBuild loader is v15.0 string toolsVersion = "15.0"; properties.Add("MSBuildAssemblyVersion", "15.0"); var toolsPath = Runtime.SystemAssemblyService.DefaultRuntime.GetMSBuildToolsPath(toolsVersion); var frameworkToolsPath = ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.VersionLatest); properties.Add("MSBuildBinPath", MSBuildProjectService.ToMSBuildPath(null, toolsPath)); properties.Add("MSBuildToolsPath", MSBuildProjectService.ToMSBuildPath(null, toolsPath)); properties.Add("MSBuildToolsRoot", MSBuildProjectService.ToMSBuildPath(null, Path.GetDirectoryName(toolsPath))); properties.Add("MSBuildToolsVersion", toolsVersion); properties.Add("OS", Platform.IsWindows ? "Windows_NT" : "Unix"); properties.Add("MSBuildBinPath32", MSBuildProjectService.ToMSBuildPath(null, toolsPath)); properties.Add("MSBuildFrameworkToolsPath", MSBuildProjectService.ToMSBuildPath(null, frameworkToolsPath)); properties.Add("MSBuildFrameworkToolsPath32", MSBuildProjectService.ToMSBuildPath(null, frameworkToolsPath)); if (Platform.IsWindows) { // Taken from MSBuild source: var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); var programFiles32 = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86); if (string.IsNullOrEmpty(programFiles32)) { programFiles32 = programFiles; // 32 bit box } string programFiles64; if (programFiles == programFiles32) { // either we're in a 32-bit window, or we're on a 32-bit machine. // if we're on a 32-bit machine, ProgramW6432 won't exist // if we're on a 64-bit machine, ProgramW6432 will point to the correct Program Files. programFiles64 = Environment.GetEnvironmentVariable("ProgramW6432"); } else { // 64-bit window on a 64-bit machine; %ProgramFiles% points to the 64-bit // Program Files already. programFiles64 = programFiles; } var extensionsPath32 = MSBuildProjectService.ToMSBuildPath(null, Path.Combine(programFiles32, "MSBuild")); properties.Add("MSBuildExtensionsPath32", extensionsPath32); if (programFiles64 != null) { properties.Add("MSBuildExtensionsPath64", MSBuildProjectService.ToMSBuildPath(null, Path.Combine(programFiles64, "MSBuild"))); } // MSBuildExtensionsPath: The way this used to work is that it would point to "Program Files\MSBuild" on both // 32-bit and 64-bit machines. We have a switch to continue using that behavior; however the default is now for // MSBuildExtensionsPath to always point to the same location as MSBuildExtensionsPath32. bool useLegacyMSBuildExtensionsPathBehavior = !String.IsNullOrEmpty(Environment.GetEnvironmentVariable("MSBUILDLEGACYEXTENSIONSPATH")); string extensionsPath; if (useLegacyMSBuildExtensionsPathBehavior) { extensionsPath = Path.Combine(programFiles, "MSBuild"); } else { extensionsPath = extensionsPath32; } properties.Add("MSBuildExtensionsPath", extensionsPath); } else if (!String.IsNullOrEmpty(DefaultExtensionsPath)) { var ep = MSBuildProjectService.ToMSBuildPath(null, extensionsPath); properties.Add("MSBuildExtensionsPath", ep); properties.Add("MSBuildExtensionsPath32", ep); properties.Add("MSBuildExtensionsPath64", ep); } // Environment properties.Add("MSBuildProgramFiles32", MSBuildProjectService.ToMSBuildPath(null, Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86))); } }
public void GeneratePathToToolNullOrEmptySdkToolPathNoLogging() { string toolPath = SdkToolsPathUtility.GeneratePathToTool(_mockExists.MockFileExistsOnlyInX86, ProcessorArchitecture.X86, null, _toolName, _log, false); Assert.Null(toolPath); string comment = ResourceUtilities.FormatResourceString("General.SdkToolsPathNotSpecifiedOrToolDoesNotExist", _toolName, null); _mockEngine.AssertLogDoesntContain(comment); Assert.Equal(0, _mockEngine.Warnings); comment = ResourceUtilities.FormatResourceString("General.SdkToolsPathToolDoesNotExist", _toolName, null, ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version45)); _mockEngine.AssertLogDoesntContain(comment); Assert.Equal(0, _mockEngine.Errors); }
public Engine(ToolsetDefinitionLocations locations) : this(ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version20)) { //toolsetLocations = locations; }
/// <summary> /// When overridden in a derived class, executes the task. /// </summary> /// <returns> /// True if the task successfully executed; otherwise, false. /// </returns> public override bool Execute() { if (!mapToAspNet && String.IsNullOrEmpty(executablePath)) { Log.LogError("You must either specify a value for ExecutablePath, or set MapToAspNet = True."); return(false); } if (mapToAspNet) { executablePath = ToolLocationHelper.GetPathToDotNetFrameworkFile("aspnet_isapi.dll", TargetDotNetFrameworkVersion.VersionLatest); enableScriptEngine = true; } int flags = 0; if (enableScriptEngine) { flags += 1; } if (verifyFileExists) { flags += 4; } if (!extension.StartsWith(".")) { extension = "." + extension; } DirectoryEntry targetDirectory = null; try { Log.LogMessage(MessageImportance.Normal, Properties.Resources.WebDirectoryScriptMapUpdate, Extension, VirtualDirectoryName, ServerName); VerifyIISRoot(); string targetDirectoryPath = (VirtualDirectoryName == "/") ? targetDirectoryPath = IISServerPath : targetDirectoryPath = IISServerPath + "/" + VirtualDirectoryName; targetDirectory = new DirectoryEntry(targetDirectoryPath); try { string directoryExistsTest = targetDirectory.SchemaClassName; } catch (COMException) { Log.LogError(Properties.Resources.WebDirectoryInvalidDirectory, VirtualDirectoryName, ServerName); return(false); } PropertyValueCollection scriptMaps = targetDirectory.Properties["ScriptMaps"]; if (scriptMaps == null) { Log.LogError(Properties.Resources.WebDirectorySettingInvalidSetting, VirtualDirectoryName, ServerName, "ScriptMaps"); return(false); } int extensionIndex = -1; for (int i = 0; i < scriptMaps.Count; i++) { string scriptMap = scriptMaps[i] as string; if (scriptMap == null) { continue; } if (scriptMap.StartsWith(extension + ",", StringComparison.InvariantCultureIgnoreCase)) { extensionIndex = i; break; } } string newVerbs = !String.IsNullOrEmpty(verbs) ? "," + verbs.Replace(';', ',') : String.Empty; string mappingDetails = String.Format("{0},{1},{2}{3}", extension, executablePath, flags.ToString(), newVerbs ); if (extensionIndex >= 0) { scriptMaps[extensionIndex] = mappingDetails; } else { scriptMaps.Add(mappingDetails); } targetDirectory.CommitChanges(); } finally { if (targetDirectory != null) { targetDirectory.Dispose(); } } return(true); }
public Engine(BuildPropertyGroup globalProperties, ToolsetDefinitionLocations locations) : this(ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version20)) { this.global_properties = globalProperties; //toolsetLocations = locations; }
private static IList <string> GetPathToReferenceAssemblies(FrameworkName frameworkName) { return(ToolLocationHelper.GetPathToReferenceAssemblies(frameworkName)); }
protected override string GenerateFullPathToTool() { string path = ToolLocationHelper.GetPathToDotNetFrameworkFile(ToolName, Constants.DefaultFramework); if (path == null) { base.Log.LogErrorWithCodeFromResources("General.FrameworksFileNotFound", ToolName, ToolLocationHelper.GetDotNetFrameworkVersionFolderPrefix(Constants.DefaultFramework)); } return(path); }
public override bool Execute() { FrameworkNameVersioning moniker; FrameworkNameVersioning monikerWithNoProfile = null; // Are we targeting a profile. bool targetingProfile; try { moniker = new FrameworkNameVersioning(TargetFrameworkMoniker); targetingProfile = !String.IsNullOrEmpty(moniker.Profile); // If we are targeting a profile we need to generate a set of reference assembly paths which describe where the full framework // exists, to do so we need to get the reference assembly location without the profile as part of the moniker. if (targetingProfile) { monikerWithNoProfile = new FrameworkNameVersioning(moniker.Identifier, moniker.Version); } #if FEATURE_GAC // This is a very specific "hack" to ensure that when we're targeting certain .NET Framework versions that // WPF gets to rely on .NET FX 3.5 SP1 being installed on the build machine. // This only needs to occur when we are targeting a .NET FX prior to v4.0 if (!BypassFrameworkInstallChecks && moniker.Identifier.Equals(".NETFramework", StringComparison.OrdinalIgnoreCase) && moniker.Version.Major < 4) { // We have not got a value for whether or not the 35 sentinel assembly has been found if (!s_net35SP1SentinelAssemblyFound.HasValue) { // get an assemblyname from the string representation of the sentinel assembly name var sentinelAssemblyName = new AssemblyNameExtension(NET35SP1SentinelAssemblyName); string path = GlobalAssemblyCache.GetLocation(sentinelAssemblyName, SystemProcessorArchitecture.MSIL, runtimeVersion => "v2.0.50727", new Version("2.0.57027"), false, new FileExists(p => FileUtilities.FileExistsNoThrow(p)), GlobalAssemblyCache.pathFromFusionName, GlobalAssemblyCache.gacEnumerator, false); s_net35SP1SentinelAssemblyFound = !String.IsNullOrEmpty(path); } // We did not find the SP1 sentinel assembly in the GAC. Therefore we must assume that SP1 isn't installed if (!s_net35SP1SentinelAssemblyFound.Value) { Log.LogErrorWithCodeFromResources("GetReferenceAssemblyPaths.NETFX35SP1NotIntstalled", TargetFrameworkMoniker); } } #endif } catch (ArgumentException e) { Log.LogErrorWithCodeFromResources("GetReferenceAssemblyPaths.InvalidTargetFrameworkMoniker", TargetFrameworkMoniker, e.Message); return(false); } try { _tfmPaths = GetPaths(RootPath, TargetFrameworkFallbackSearchPaths, moniker); if (_tfmPaths?.Count > 0) { TargetFrameworkMonikerDisplayName = ToolLocationHelper.GetDisplayNameForTargetFrameworkDirectory(_tfmPaths[0], moniker); } // If there is a profile get the paths without the profile. // There is no point in generating the full framework paths if profile path could not be found. if (targetingProfile && _tfmPaths != null) { _tfmPathsNoProfile = GetPaths(RootPath, TargetFrameworkFallbackSearchPaths, monikerWithNoProfile); } // The path with out the profile is just the reference assembly paths. if (!targetingProfile) { _tfmPathsNoProfile = _tfmPaths; } } catch (Exception e) { // The reason we need to do exception E here is because we are in a task and have the ability to log the message and give the user // feedback as to its cause, tasks if at all possible should not have exception leave them. Log.LogErrorWithCodeFromResources("GetReferenceAssemblyPaths.ProblemGeneratingReferencePaths", TargetFrameworkMoniker, e.Message); if (ExceptionHandling.IsCriticalException(e)) { throw; } _tfmPathsNoProfile = null; TargetFrameworkMonikerDisplayName = null; } return(!Log.HasLoggedErrors); }
internal static string GeneratePathToTool(FileExists fileExists, string currentArchitecture, string sdkToolsPath, string toolName, TaskLoggingHelper log, bool logErrorsAndWarnings) { // Null until we combine the toolname with the path. string pathToTool = null; if (!String.IsNullOrEmpty(sdkToolsPath)) { string processorSpecificToolDirectory; try { processorSpecificToolDirectory = currentArchitecture switch { // There may not be an arm directory so we will fall back to the x86 tool location // but if there is then we should try and use it. ProcessorArchitecture.ARM => Path.Combine(sdkToolsPath, "arm"), ProcessorArchitecture.AMD64 => Path.Combine(sdkToolsPath, "x64"), ProcessorArchitecture.IA64 => Path.Combine(sdkToolsPath, "ia64"), _ => sdkToolsPath, }; pathToTool = Path.Combine(processorSpecificToolDirectory, toolName); if (!fileExists(pathToTool)) { // Try falling back to the x86 location if (currentArchitecture != ProcessorArchitecture.X86) { pathToTool = Path.Combine(sdkToolsPath, toolName); } } else { return(pathToTool); } } catch (ArgumentException e) { // Catch exceptions from path.combine log.LogErrorWithCodeFromResources("General.SdkToolsPathError", toolName, e.Message); return(null); } if (fileExists(pathToTool)) { return(pathToTool); } else { if (logErrorsAndWarnings) { // Log an error indicating we could not find it in the processor specific architecture or x86 locations. // We could not find the tool at all, lot a error. log.LogWarningWithCodeFromResources("General.PlatformSDKFileNotFoundSdkToolsPath", toolName, processorSpecificToolDirectory, sdkToolsPath); } } } else { if (logErrorsAndWarnings) { log.LogMessageFromResources(MessageImportance.Low, "General.SdkToolsPathNotSpecifiedOrToolDoesNotExist", toolName, sdkToolsPath); } } // Fall back and see if we can find it with the toolsLocation helper methods. This is not optimal because // the location they are looking at is based on when the Microsoft.Build.Utilities.dll was compiled // but it is better than nothing. if (pathToTool == null || !fileExists(pathToTool)) { pathToTool = FindSDKToolUsingToolsLocationHelper(toolName); if (pathToTool == null && logErrorsAndWarnings) { log.LogErrorWithCodeFromResources("General.SdkToolsPathToolDoesNotExist", toolName, sdkToolsPath, ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Latest, VisualStudioVersion.VersionLatest)); } } return(pathToTool); }
/// <summary> /// MSBuild engine will call this to initialize the factory. This should initialize the factory enough so that the factory can be asked /// whether or not task names can be created by the factory. /// </summary> public bool Initialize(string taskName, IDictionary <string, TaskPropertyInfo> taskParameters, string taskElementContents, IBuildEngine taskFactoryLoggingHost) { ErrorUtilities.VerifyThrowArgumentNull(taskName, "taskName"); ErrorUtilities.VerifyThrowArgumentNull(taskParameters, "taskParameters"); var log = new TaskLoggingHelper(taskFactoryLoggingHost, taskName) { TaskResources = AssemblyResources.PrimaryResources, HelpKeywordPrefix = "MSBuild." }; if (taskElementContents == null) { log.LogErrorWithCodeFromResources("Xaml.MissingTaskBody"); return(false); } TaskElementContents = taskElementContents.Trim(); // Attempt to load the task TaskParser parser = new TaskParser(); bool parseSuccessful = parser.Parse(TaskElementContents, taskName); TaskName = parser.GeneratedTaskName; TaskNamespace = parser.Namespace; var generator = new TaskGenerator(parser); CodeCompileUnit dom = generator.GenerateCode(); string pathToMSBuildBinaries = ToolLocationHelper.GetPathToBuildTools(ToolLocationHelper.CurrentToolsVersion); // create the code generator options // Since we are running msbuild 12.0 these had better load. var compilerParameters = new CompilerParameters ( new[] { "System.dll", Path.Combine(pathToMSBuildBinaries, "Microsoft.Build.Framework.dll"), Path.Combine(pathToMSBuildBinaries, "Microsoft.Build.Utilities.Core.dll"), Path.Combine(pathToMSBuildBinaries, "Microsoft.Build.Tasks.Core.dll") } ) { GenerateInMemory = true, TreatWarningsAsErrors = false }; // create the code provider var codegenerator = CodeDomProvider.CreateProvider("cs"); CompilerResults results; bool debugXamlTask = Environment.GetEnvironmentVariable("MSBUILDWRITEXAMLTASK") == "1"; if (debugXamlTask) { using (var outputWriter = new StreamWriter(taskName + "_XamlTask.cs")) { var options = new CodeGeneratorOptions { BlankLinesBetweenMembers = true, BracingStyle = "C" }; codegenerator.GenerateCodeFromCompileUnit(dom, outputWriter, options); } results = codegenerator.CompileAssemblyFromFile(compilerParameters, taskName + "_XamlTask.cs"); } else { results = codegenerator.CompileAssemblyFromDom(compilerParameters, dom); } try { _taskAssembly = results.CompiledAssembly; } catch (FileNotFoundException) { // This occurs if there is a failure to compile the assembly. We just pass through because we will take care of the failure below. } if (_taskAssembly == null) { var errorList = new StringBuilder(); errorList.AppendLine(); foreach (CompilerError error in results.Errors) { if (error.IsWarning) { continue; } if (debugXamlTask) { errorList.AppendLine(String.Format(Thread.CurrentThread.CurrentUICulture, "({0},{1}) {2}", error.Line, error.Column, error.ErrorText)); } else { errorList.AppendLine(error.ErrorText); } } log.LogErrorWithCodeFromResources("Xaml.TaskCreationFailed", errorList.ToString()); } return(!log.HasLoggedErrors); }
internal static string GeneratePathToTool(Microsoft.Build.Shared.FileExists fileExists, string currentArchitecture, string sdkToolsPath, string toolName, TaskLoggingHelper log, bool logErrorsAndWarnings) { string path = null; if (!string.IsNullOrEmpty(sdkToolsPath)) { string str2 = string.Empty; try { string str4 = currentArchitecture; if (str4 == null) { goto Label_0061; } if (!(str4 == "AMD64")) { if (str4 == "IA64") { goto Label_0053; } if (str4 == "x86") { } goto Label_0061; } str2 = Path.Combine(sdkToolsPath, "x64"); goto Label_0063; Label_0053: str2 = Path.Combine(sdkToolsPath, "ia64"); goto Label_0063; Label_0061: str2 = sdkToolsPath; Label_0063: path = Path.Combine(str2, toolName); if (!fileExists(path)) { if (currentArchitecture != "x86") { path = Path.Combine(sdkToolsPath, toolName); } } else { return(path); } } catch (ArgumentException exception) { log.LogErrorWithCodeFromResources("General.SdkToolsPathError", new object[] { toolName, exception.Message }); return(null); } if (fileExists(path)) { return(path); } if (logErrorsAndWarnings) { log.LogWarningWithCodeFromResources("General.PlatformSDKFileNotFoundSdkToolsPath", new object[] { toolName, str2, sdkToolsPath }); } } else if (logErrorsAndWarnings) { log.LogMessageFromResources(MessageImportance.Low, "General.SdkToolsPathNotSpecifiedOrToolDoesNotExist", new object[] { toolName, sdkToolsPath }); } if ((path == null) || !fileExists(path)) { path = FindSDKToolUsingToolsLocationHelper(toolName); if ((path == null) && logErrorsAndWarnings) { log.LogErrorWithCodeFromResources("General.SdkToolsPathToolDoesNotExist", new object[] { toolName, sdkToolsPath, ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version40) }); } } return(path); }
static void InitEngineProperties(Core.Assemblies.TargetRuntime runtime, Dictionary <string, string> properties, out List <ImportSearchPathExtensionNode> searchPaths) { // This MSBuild loader is v15.0 string toolsVersion = "15.0"; properties.Add("MSBuildAssemblyVersion", toolsVersion); //VisualStudioVersion is a property set by MSBuild itself string visualStudioVersion = toolsVersion; properties.Add("VisualStudioVersion", visualStudioVersion); var toolsPath = (runtime).GetMSBuildToolsPath(toolsVersion); var msBuildBinPath = toolsPath; var msBuildBinPathEscaped = MSBuildProjectService.ToMSBuildPath(null, msBuildBinPath); properties.Add("MSBuildBinPath", msBuildBinPathEscaped); properties.Add("MSBuildToolsPath", msBuildBinPathEscaped); properties.Add("MSBuildBinPath32", msBuildBinPathEscaped); properties.Add("MSBuildToolsRoot", MSBuildProjectService.ToMSBuildPath(null, Path.GetDirectoryName(toolsPath))); properties.Add("MSBuildToolsVersion", toolsVersion); properties.Add("OS", Platform.IsWindows ? "Windows_NT" : "Unix"); var frameworkToolsPath = ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.VersionLatest); var frameworkToolsPathEscaped = MSBuildProjectService.ToMSBuildPath(null, frameworkToolsPath); properties.Add("MSBuildFrameworkToolsPath", frameworkToolsPathEscaped); properties.Add("MSBuildFrameworkToolsPath32", frameworkToolsPathEscaped); searchPaths = MSBuildProjectService.GetProjectImportSearchPaths(runtime, true).ToList(); if (Platform.IsWindows) { //first use extensions path relative to bindir (MSBuild/15.0/Bin). this works for dev15 isolated install. var msBuildExtensionsPath = Path.GetFullPath(Path.Combine(msBuildBinPath, "..", "..")); var msBuildExtensionsPathEscaped = MSBuildProjectService.ToMSBuildPath(null, msBuildExtensionsPath); properties.Add("MSBuildExtensionsPath", msBuildExtensionsPathEscaped); properties.Add("MSBuildExtensionsPath32", msBuildExtensionsPathEscaped); properties.Add("MSBuildExtensionsPath64", msBuildExtensionsPathEscaped); var vsToolsPathEscaped = MSBuildProjectService.ToMSBuildPath(null, Path.Combine(msBuildExtensionsPath, "Microsoft", "VisualStudio", "v" + visualStudioVersion)); properties.Add("VSToolsPath", vsToolsPathEscaped); //like the dev15 toolset, add fallbacks to the old global paths // Taken from MSBuild source: var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); var programFiles32 = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86); if (string.IsNullOrEmpty(programFiles32)) { programFiles32 = programFiles; // 32 bit box } string programFiles64; if (programFiles == programFiles32) { // either we're in a 32-bit window, or we're on a 32-bit machine. // if we're on a 32-bit machine, ProgramW6432 won't exist // if we're on a 64-bit machine, ProgramW6432 will point to the correct Program Files. programFiles64 = Environment.GetEnvironmentVariable("ProgramW6432"); } else { // 64-bit window on a 64-bit machine; %ProgramFiles% points to the 64-bit // Program Files already. programFiles64 = programFiles; } var extensionsPath32Escaped = MSBuildProjectService.ToMSBuildPath(null, Path.Combine(programFiles32, "MSBuild")); searchPaths.Insert(0, new ImportSearchPathExtensionNode { Property = "MSBuildExtensionsPath32", Path = extensionsPath32Escaped }); if (programFiles64 != null) { var extensionsPath64Escaped = MSBuildProjectService.ToMSBuildPath(null, Path.Combine(programFiles64, "MSBuild")); searchPaths.Insert(0, new ImportSearchPathExtensionNode { Property = "MSBuildExtensionsPath64", Path = extensionsPath64Escaped }); } //yes, dev15's toolset has the 64-bit path fall back to the 32-bit one searchPaths.Insert(0, new ImportSearchPathExtensionNode { Property = "MSBuildExtensionsPath64", Path = extensionsPath32Escaped }); // MSBuildExtensionsPath: The way this used to work is that it would point to "Program Files\MSBuild" on both // 32-bit and 64-bit machines. We have a switch to continue using that behavior; however the default is now for // MSBuildExtensionsPath to always point to the same location as MSBuildExtensionsPath32. bool useLegacyMSBuildExtensionsPathBehavior = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("MSBUILDLEGACYEXTENSIONSPATH")); string extensionsPath; if (useLegacyMSBuildExtensionsPathBehavior) { extensionsPath = Path.Combine(programFiles, "MSBuild"); } else { extensionsPath = extensionsPath32Escaped; } searchPaths.Insert(0, new ImportSearchPathExtensionNode { Property = "MSBuildExtensionsPath", Path = extensionsPath }); } else { var msBuildExtensionsPath = runtime.GetMSBuildExtensionsPath(); var msBuildExtensionsPathEscaped = MSBuildProjectService.ToMSBuildPath(null, msBuildExtensionsPath); properties.Add("MSBuildExtensionsPath", msBuildExtensionsPathEscaped); properties.Add("MSBuildExtensionsPath32", msBuildExtensionsPathEscaped); properties.Add("MSBuildExtensionsPath64", msBuildExtensionsPathEscaped); var vsToolsPathEscaped = MSBuildProjectService.ToMSBuildPath(null, Path.Combine(msBuildExtensionsPath, "Microsoft", "VisualStudio", "v" + visualStudioVersion)); properties.Add("VSToolsPath", vsToolsPathEscaped); } // Environment properties.Add("MSBuildProgramFiles32", MSBuildProjectService.ToMSBuildPath(null, Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86))); // Custom override of MSBuildExtensionsPath using an env var var customExtensionsPath = Environment.GetEnvironmentVariable("MSBuildExtensionsPath"); if (!string.IsNullOrEmpty(customExtensionsPath)) { if (IsExternalMSBuildExtensionsPath(customExtensionsPath)) { // This is actually an override of the mono extensions path. Don't replace the default MSBuildExtensionsPath value since // core targets still need to be loaded from there. searchPaths.Insert(0, new ImportSearchPathExtensionNode { Property = "MSBuildExtensionsPath", Path = customExtensionsPath }); } else { properties["MSBuildExtensionsPath"] = MSBuildProjectService.ToMSBuildPath(null, customExtensionsPath); } } }