/// <summary> /// Given a string of semi-colon delimited name=value pairs, this method parses it and creates /// a hash table containing the property names as keys and the property values as values. /// </summary> /// <param name="log"></param> /// <param name="propertyList"></param> /// <param name="propertiesTable"></param> /// <returns>true on success, false on failure.</returns> static internal bool GetTable(TaskLoggingHelper log, string parameterName, string[] propertyList, out Hashtable propertiesTable) { propertiesTable = null; if (propertyList != null) { propertiesTable = new Hashtable(StringComparer.OrdinalIgnoreCase); // Loop through the array. Each string in the array should be of the form: // MyPropName=MyPropValue foreach (string propertyNameValuePair in propertyList) { string propertyName = String.Empty; string propertyValue = String.Empty; // Find the first '=' sign in the string. int indexOfEqualsSign = propertyNameValuePair.IndexOf('='); // If we found one, then grab the stuff before it and put it into "propertyName", // and grab the stuff after it and put it into "propertyValue". But trim the // whitespace from beginning and end of both name and value. (When authoring a // project/targets file, people like to use whitespace and newlines to pretty up // the file format.) if (indexOfEqualsSign != -1) { propertyName = propertyNameValuePair.Substring(0, indexOfEqualsSign).Trim(); propertyValue = propertyNameValuePair.Substring(indexOfEqualsSign + 1).Trim(); } // Make sure we have a property name and property value (though the value is allowed to be blank). if (propertyName.Length == 0) { // No equals sign? No property name? That's no good to us. if (log != null) { log.LogErrorWithCodeFromResources("General.InvalidPropertyError", parameterName, propertyNameValuePair); } return false; } // Bag the property and its value. Trim whitespace from beginning and end of // both name and value. (When authoring a project/targets file, people like to // use whitespace and newlines to pretty up the file format.) propertiesTable[propertyName] = propertyValue; } } return true; }
/// <summary> /// Writes the contents of this object out to the specified file. /// </summary> /// <param name="stateFile"></param> override internal void SerializeCache(string stateFile, TaskLoggingHelper log) { base.SerializeCache(stateFile, log); isDirty = false; }
public FixAbstractMethodsStep(DirectoryAssemblyResolver resolver, TypeDefinitionCache cache, TaskLoggingHelper logger) : base(cache) { this.resolver = resolver; this.logger = logger; }
public MSBuildLogger(TaskLoggingHelper log) => _log = log;
static bool ValidateAotConfiguration(TaskLoggingHelper log, AndroidTargetArch arch, bool enableLLVM) { return(true); }
public RedirectLogger(TaskLoggingHelper taskLogger) { this.taskLogger = taskLogger; }
public static void Join(TaskLoggingHelper log, IEnumerable <ITaskItem> models, ITaskItem output, string orderBy = null, string orderByDescending = null, int?skip = null, int?take = null, TypeCode orderByTypeCodeEnum = TypeCode.Int32) { }
public static void LogTaskName(this TaskLoggingHelper log, string taskName) { log.LogMessage(TaskPropertyImportance, "{0} Task", taskName); }
public MSBuildLogger(TaskLoggingHelper taskloggingHelper) { m_TaskloggingHelper = taskloggingHelper ?? throw new ArgumentNullException(nameof(taskloggingHelper)); }
internal XamlTask() { LoggingHelper = new TaskLoggingHelper(this); }
/// <summary> /// Returns true if the provided item list contains duplicate items, false otherwise. /// </summary> /// <param name="itemList"></param> /// <param name="disambiguatingMetadataName">Optional name of metadata that may legitimately disambiguate items. May be null.</param> /// <param name="parameterName"></param> /// <param name="log"></param> private static bool ListHasNoDuplicateItems(ITaskItem[] itemList, string parameterName, string disambiguatingMetadataName, TaskLoggingHelper log) { if (itemList == null || itemList.Length == 0) { return(true); } var alreadySeen = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); foreach (ITaskItem item in itemList) { string key; string disambiguatingMetadataValue = null; if (disambiguatingMetadataName != null) { disambiguatingMetadataValue = item.GetMetadata(disambiguatingMetadataName); } if (disambiguatingMetadataName == null || string.IsNullOrEmpty(disambiguatingMetadataValue)) { key = item.ItemSpec; } else { key = item.ItemSpec + ":" + disambiguatingMetadataValue; } if (alreadySeen.ContainsKey(key)) { if (disambiguatingMetadataName == null || string.IsNullOrEmpty(disambiguatingMetadataValue)) { log.LogErrorWithCodeFromResources("General_DuplicateItemsNotSupported", item.ItemSpec, parameterName); } else { log.LogErrorWithCodeFromResources("General_DuplicateItemsNotSupportedWithMetadata", item.ItemSpec, parameterName, disambiguatingMetadataValue, disambiguatingMetadataName); } return(false); } else { alreadySeen[key] = string.Empty; } } return(true); }
/// <summary> /// Returns true if the provided item list contains duplicate items, false otherwise. /// </summary> internal static bool ListHasNoDuplicateItems(ITaskItem[] itemList, string parameterName, TaskLoggingHelper log) { return(ListHasNoDuplicateItems(itemList, parameterName, null, log)); }
public MsBuildSharpGenLogger(TaskLoggingHelper log) { this.log = log; }
public bool Initialize(string taskName, IDictionary <string, TaskPropertyInfo> taskParameters, string taskElementContents, IBuildEngine taskFactoryLoggingHost) { _nameOfTask = taskName; _log = new TaskLoggingHelper(taskFactoryLoggingHost, taskName) { TaskResources = AssemblyResources.PrimaryResources, HelpKeywordPrefix = "MSBuild." }; XmlNode taskContent = ExtractTaskContent(taskElementContents); if (taskContent == null) { // Just return false because we have already logged the error in ExtractTaskContents return(false); } bool validatedTaskNode = ValidateTaskNode(); if (!validatedTaskNode) { return(false); } if (taskContent.Attributes["Type"] != null) { _type = taskContent.Attributes["Type"].Value; if (_type.Length == 0) { _log.LogErrorWithCodeFromResources("CodeTaskFactory.AttributeEmpty", "Type"); return(false); } } if (taskContent.Attributes["Language"] != null) { _language = taskContent.Attributes["Language"].Value; if (_language.Length == 0) { _log.LogErrorWithCodeFromResources("CodeTaskFactory.AttributeEmpty", "Language"); return(false); } } if (taskContent.Attributes["Source"] != null) { _sourcePath = taskContent.Attributes["Source"].Value; if (_sourcePath.Length == 0) { _log.LogErrorWithCodeFromResources("CodeTaskFactory.AttributeEmpty", "Source"); return(false); } if (_type == null) { _type = "Class"; } } _referencedAssemblies = ExtractReferencedAssemblies(); if (_log.HasLoggedErrors) { return(false); } _usingNamespaces = ExtractUsingNamespaces(); if (_log.HasLoggedErrors) { return(false); } _sourceCode = taskContent.InnerText; if (_type == null) { _type = "Fragment"; } if (_language == null) { _language = "cs"; } if (String.Equals(_type, "Fragment", StringComparison.OrdinalIgnoreCase)) { _typeIsFragment = true; _typeIsMethod = false; } else if (String.Equals(_type, "Method", StringComparison.OrdinalIgnoreCase)) { _typeIsFragment = false; _typeIsMethod = true; } _taskParameterTypeInfo = taskParameters; _compiledAssembly = CompileInMemoryAssembly(); // If it wasn't compiled, it logged why. // If it was, continue. if (_compiledAssembly != null) { // Now go find the type int he compiled assembly. Type[] exportedTypes = _compiledAssembly.GetExportedTypes(); Type fullNameMatch = null; Type partialNameMatch = null; foreach (Type exportedType in exportedTypes) { string exportedTypeName = exportedType.FullName; if (exportedTypeName.Equals(_nameOfTask, StringComparison.OrdinalIgnoreCase)) { fullNameMatch = exportedType; break; } else if (partialNameMatch == null && exportedTypeName.EndsWith(_nameOfTask, StringComparison.OrdinalIgnoreCase)) { partialNameMatch = exportedType; } } TaskType = fullNameMatch ?? partialNameMatch; if (TaskType == null) { _log.LogErrorWithCodeFromResources("CodeTaskFactory.CouldNotFindTaskInAssembly", _nameOfTask); } } return(!_log.HasLoggedErrors); }
/// <summary> /// Given a string of semi-colon delimited name=value pairs, this method parses it and creates /// a hash table containing the property names as keys and the property values as values. /// This method escapes any special characters found in the property values, in case they /// are going to be passed to a method (such as that expects the appropriate escaping to have happened /// already. /// </summary> /// <param name="log"></param> /// <param name="propertyList"></param> /// <param name="propertiesTable"></param> /// <returns>true on success, false on failure.</returns> static internal bool GetTableWithEscaping(TaskLoggingHelper log, string parameterName, string syntaxName, string[] propertyNameValueStrings, out Hashtable finalPropertiesTable) { finalPropertiesTable = null; if (propertyNameValueStrings != null) { finalPropertiesTable = new Hashtable(StringComparer.OrdinalIgnoreCase); List<PropertyNameValuePair> finalPropertiesList = new List<PropertyNameValuePair>(); // Loop through the array. Each string in the array should be of the form: // MyPropName=MyPropValue foreach (string propertyNameValueString in propertyNameValueStrings) { // Find the first '=' sign in the string. int indexOfEqualsSign = propertyNameValueString.IndexOf('='); if (indexOfEqualsSign != -1) { // If we found one, then grab the stuff before it and put it into "propertyName", // and grab the stuff after it and put it into "propertyValue". But trim the // whitespace from beginning and end of both name and value. (When authoring a // project/targets file, people like to use whitespace and newlines to pretty up // the file format.) string propertyName = propertyNameValueString.Substring(0, indexOfEqualsSign).Trim(); string propertyValue = EscapingUtilities.Escape(propertyNameValueString.Substring(indexOfEqualsSign + 1).Trim()); // Make sure we have a property name and property value (though the value is allowed to be blank). if (propertyName.Length == 0) { // No property name? That's no good to us. if (log != null) { log.LogErrorWithCodeFromResources("General.InvalidPropertyError", syntaxName, propertyNameValueString); } return false; } // Store the property in our list. finalPropertiesList.Add(new PropertyNameValuePair(propertyName, propertyValue)); } else { // There's no '=' sign in the string. When this happens, we treat this string as basically // an appendage on the value of the previous property. For example, if the project file contains // // <PropertyGroup> // <WarningsAsErrors>1234;5678;9999</WarningsAsErrors> // </PropertyGroup> // <Target Name="Build"> // <MSBuild Projects="ConsoleApplication1.csproj" // Properties="WarningsAsErrors=$(WarningsAsErrors)"/> // </Target> // // , then this method (GetTableWithEscaping) will see this: // // propertyNameValueStrings[0] = "WarningsAsErrors=1234" // propertyNameValueStrings[1] = "5678" // propertyNameValueStrings[2] = "9999" // // And what we actually want to end up with in our final hashtable is this: // // NAME VALUE // =================== ================================ // WarningsAsErrors 1234;5678;9999 // if (finalPropertiesList.Count > 0) { // There was a property definition previous to this one. Append the current string // to that previous value, using semicolon as a separator. string propertyValue = EscapingUtilities.Escape(propertyNameValueString.Trim()); finalPropertiesList[finalPropertiesList.Count - 1].Value.Append(';'); finalPropertiesList[finalPropertiesList.Count - 1].Value.Append(propertyValue); } else { // No equals sign in the very first property? That's a problem. if (log != null) { log.LogErrorWithCodeFromResources("General.InvalidPropertyError", syntaxName, propertyNameValueString); } return false; } } } // Convert the data in the List to a Hashtable, because that's what the MSBuild task eventually // needs to pass onto the engine. if (log != null) { log.LogMessageFromText(parameterName, MessageImportance.Low); } foreach (PropertyNameValuePair propertyNameValuePair in finalPropertiesList) { string propertyValue = OpportunisticIntern.StringBuilderToString(propertyNameValuePair.Value); finalPropertiesTable[propertyNameValuePair.Name] = propertyValue; if (log != null) { log.LogMessageFromText(String.Format(CultureInfo.InvariantCulture, " {0}={1}", propertyNameValuePair.Name, propertyValue), MessageImportance.Low); } } } return true; }
/// <summary> /// This method will take a sdkToolsPath and a toolName and return the path to the tool if it is found and exists. /// /// First the method will try and find the tool under the sdkToolsPath taking into account the current processor architecture /// If the tool could not be found the method will try and find the tool under the sdkToolsPath (which should point to the x86 sdk directory). /// /// Finally if the method has not found the tool yet it will fallback and use the toolslocation helper method to try and find the tool. /// </summary> /// <returns>Path including the toolName of the tool if found, null if it is not found</returns> 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 = String.Empty; try { switch (currentArchitecture) { // 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. case ProcessorArchitecture.ARM: processorSpecificToolDirectory = Path.Combine(sdkToolsPath, "arm"); break; case ProcessorArchitecture.AMD64: processorSpecificToolDirectory = Path.Combine(sdkToolsPath, "x64"); break; case ProcessorArchitecture.IA64: processorSpecificToolDirectory = Path.Combine(sdkToolsPath, "ia64"); break; case ProcessorArchitecture.X86: default: processorSpecificToolDirectory = sdkToolsPath; break; } 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 (null == pathToTool || !fileExists(pathToTool)) { pathToTool = FindSDKToolUsingToolsLocationHelper(toolName); if (pathToTool == null && logErrorsAndWarnings) { log.LogErrorWithCodeFromResources("General.SdkToolsPathToolDoesNotExist", toolName, sdkToolsPath, ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Latest, VisualStudioVersion.VersionLatest)); } } return(pathToTool); }
public DiagnosticMessageVisitor(TaskLoggingHelper log, string assemblyDisplayName, bool showDiagnostics) { this.log = log; this.assemblyDisplayName = assemblyDisplayName; this.showDiagnostics = showDiagnostics; }
public static void LogCodedWarning(this TaskLoggingHelper log, string code, string message, params object [] messageArgs) { log.LogWarning(string.Empty, code, string.Empty, string.Empty, 0, 0, 0, 0, message, messageArgs); }
/// <summary> /// Creates an MSBuild error following our MTErrors convention.</summary> /// <remarks> /// For every new error we need to update "docs/website/mtouch-errors.md" and "tools/mtouch/error.cs".</remarks> /// <param name="errorCode">In the 7xxx range for MSBuild error.</param> /// <param name="message">The error's message to be displayed in the error pad.</param> /// <param name="filePath">Path to the known guilty file or MSBuild by default so we display something nice in the error pad.</param> public static void MTError(this TaskLoggingHelper log, int errorCode, string message, string filePath = "MSBuild") { log.LogError(null, $"MT{errorCode}", null, filePath, 0, 0, 0, 0, message); }
public static void FixupResourceFilenameAndLogCodedWarning(this TaskLoggingHelper log, string code, string message, string file, string resourceDir, Dictionary <string, string> resourceNameCaseMap) { var targetfile = FixupResourceFilename(file, resourceDir, resourceNameCaseMap); log.LogCodedWarning(code, file: targetfile, lineNumber: 0, message: message); }
protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands) { if (ProvideCommandLineArgs) { CommandLineArgs = GetArguments(commandLineCommands, responseFileCommands) .Select(arg => new TaskItem(arg)).ToArray(); } if (SkipCompilerExecution) { return(0); } try { var workingDir = CurrentDirectoryToUse(); string?tempDir = BuildServerConnection.GetTempPath(workingDir); if (!UseSharedCompilation || HasToolBeenOverridden || !BuildServerConnection.IsCompilerServerSupported) { return(base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands)); } using (_sharedCompileCts = new CancellationTokenSource()) { CompilerServerLogger.Log($"CommandLine = '{commandLineCommands}'"); CompilerServerLogger.Log($"BuildResponseFile = '{responseFileCommands}'"); var clientDir = Path.GetDirectoryName(PathToManagedTool); if (clientDir is null || tempDir is null) { return(base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands)); } // Note: we can't change the "tool path" printed to the console when we run // the Csc/Vbc task since MSBuild logs it for us before we get here. Instead, // we'll just print our own message that contains the real client location Log.LogMessage(ErrorString.UsingSharedCompilation, clientDir); var buildPaths = new BuildPathsAlt( clientDir: clientDir, // MSBuild doesn't need the .NET SDK directory sdkDir: null, workingDir: workingDir, tempDir: tempDir); // Note: using ToolArguments here (the property) since // commandLineCommands (the parameter) may have been mucked with // (to support using the dotnet cli) var responseTask = BuildServerConnection.RunServerCompilationAsync( Language, RoslynString.IsNullOrEmpty(SharedCompilationId) ? null : SharedCompilationId, GetArguments(ToolArguments, responseFileCommands).ToList(), buildPaths, keepAlive: null, libEnvVariable: LibDirectoryToUse(), cancellationToken: _sharedCompileCts.Token); responseTask.Wait(_sharedCompileCts.Token); var response = responseTask.Result; if (response != null) { ExitCode = HandleResponse(response, pathToTool, responseFileCommands, commandLineCommands); } else { CompilerServerLogger.LogError($"Server compilation failed, falling back to {pathToTool}"); Log.LogMessage(ErrorString.SharedCompilationFallback, pathToTool); ExitCode = base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands); } } } catch (OperationCanceledException) { ExitCode = 0; } catch (Exception e) { var util = new TaskLoggingHelper(this); util.LogErrorWithCodeFromResources("Compiler_UnexpectedException"); util.LogErrorFromException(e, showStackTrace: true, showDetail: true, file: null); ExitCode = -1; } return(ExitCode); }
/// <summary>See <see cref="Task.Execute"/>.</summary> public override bool Execute() { TaskLoggingHelper log = base.Log; ITaskItem targetManifestResource = this._targetManifestResource; ITaskItem[] mergeResources = this._mergeResources; this._outputResource = null; if (mergeResources.Length <= 0) { // If we don't have any resources to merge, then we have already succeeded at (not) merging them. return(true); } FileInfo targetManifestResourceFileInfo = new FileInfo(targetManifestResource.GetMetadata("FullPath")); if (!targetManifestResourceFileInfo.Exists) { log.LogError("The specified manifest resource file (\"{0}\") does not exist.", targetManifestResource.ItemSpec); return(false); } // UNDONE: In all of the IO in this method, we aren't doing any handling of situations where the file changes between when we initially // look at its size and when we actually read the content. // Get all of the new resources and their values. Dictionary <string, byte[]> mergeResourcesValues = new Dictionary <string, byte[]>(mergeResources.Length, StringComparer.Ordinal); foreach (ITaskItem mergeResource in mergeResources) { System.Diagnostics.Debug.Assert(string.Equals(mergeResource.GetMetadata("MergeTarget"), targetManifestResource.ItemSpec, StringComparison.OrdinalIgnoreCase), "Trying to emit a resource into a different manifest resource than the one specified for MergeTarget."); FileInfo mergeResourceFileInfo = new FileInfo(mergeResource.GetMetadata("FullPath")); if (!mergeResourceFileInfo.Exists) { log.LogError("The specified resource file to merge (\"{0}\") does not exist.", mergeResource.ItemSpec); return(false); } byte[] mergeResourceBytes = new byte[mergeResourceFileInfo.Length]; using (FileStream mergeResourceFileStream = new FileStream(mergeResourceFileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.Read, mergeResourceBytes.Length, FileOptions.SequentialScan)) { mergeResourceFileStream.Read(mergeResourceBytes, 0, mergeResourceBytes.Length); } string resourceName = mergeResource.GetMetadata("ResourceName"); if (string.IsNullOrEmpty(resourceName)) { log.LogError("The specified resource file to merge (\"{0}\") is missing a ResourceName metadata value.", mergeResource.ItemSpec); return(false); } if (mergeResourcesValues.ContainsKey(resourceName)) { log.LogError("The specified resource file to merge (\"{0}\") has a duplicate ResourceName metadata value (\"{2}\").", mergeResource.ItemSpec, resourceName); return(false); } mergeResourcesValues.Add(resourceName, mergeResourceBytes); } // Read the existing .resources file into a byte array. byte[] originalResourcesBytes = new byte[targetManifestResourceFileInfo.Length]; using (FileStream originalResourcesFileStream = new FileStream(targetManifestResourceFileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.Read, originalResourcesBytes.Length, FileOptions.SequentialScan)) { originalResourcesFileStream.Read(originalResourcesBytes, 0, originalResourcesBytes.Length); } // The FileMode.Truncate on the next line is to make the .resources file zero-length so that we don't have to worry about any excess being left behind. using (ResourceWriter resourceWriter = new ResourceWriter(new FileStream(targetManifestResourceFileInfo.FullName, FileMode.Truncate, FileAccess.ReadWrite, FileShare.None, originalResourcesBytes.Length + (mergeResources.Length * 1024), FileOptions.SequentialScan))) { // Copy the resources from the original .resources file (now stored in the byte array) into the new .resources file. using (ResourceReader resourceReader = new ResourceReader(new MemoryStream(originalResourcesBytes, 0, originalResourcesBytes.Length, false, false))) { foreach (System.Collections.DictionaryEntry entry in resourceReader) { string resourceName = (string)entry.Key; string resourceType; byte[] resourceData; resourceReader.GetResourceData(resourceName, out resourceType, out resourceData); if (mergeResourcesValues.ContainsKey(resourceName)) { log.LogMessage(MessageImportance.Normal, "Skipping copying resource \"{0}\" of type \"{1}\" to new manifest resource file \"{2}\". A new resource with this name will be merged.", resourceName, resourceType, targetManifestResource.ItemSpec); } else { resourceWriter.AddResourceData(resourceName, resourceType, resourceData); log.LogMessage(MessageImportance.Low, "Copied resource \"{0}\" of type \"{1}\" to new manifest resource file \"{2}\".", resourceName, resourceType, targetManifestResource.ItemSpec); } } } // Add each of the new resources into the new .resources file. foreach (KeyValuePair <string, byte[]> mergeResourceValue in mergeResourcesValues) { resourceWriter.AddResource(mergeResourceValue.Key, mergeResourceValue.Value); log.LogMessage(MessageImportance.Low, "Added new resource \"{0}\" to new manifest resource file \"{1}\".", mergeResourceValue.Key, targetManifestResource.ItemSpec); } } this._outputResource = targetManifestResource; return(true); }
/// <summary>See <see cref="Task.Execute"/>.</summary> public override bool Execute() { const string VsSdkInstallDirEnvironmentVariable = "VsSDKInstall"; const string VsSdkVersionsRegistryPath = @"SOFTWARE\Microsoft\VisualStudio\VSIP"; const string VsSdkInstallDirRegistryValue = "InstallDir"; const string VsSdkIncludeFilesSubdirectory = @"VisualStudioIntegration\Common\Inc"; const string VsSdkToolsSubdirectory = @"VisualStudioIntegration\Tools\Bin"; const string VsSdkRedistributablesSubdirectory = @"VisualStudioIntegration\Redistributables"; TaskLoggingHelper log = base.Log; // Try to find the VsSDK installation directory by first checking the environment variable, and then by checking the specified version listed in the registry. string installDir = Environment.GetEnvironmentVariable(VsSdkInstallDirEnvironmentVariable); if (!string.IsNullOrEmpty(installDir)) { log.LogMessage(MessageImportance.Low, "Using Visual Studio SDK installation directory from \"" + VsSdkInstallDirEnvironmentVariable + "\" environment variable: \"{0}\"", installDir); } else { using (RegistryKey vsipRegistryKey = Registry.LocalMachine.OpenSubKey(VsSdkVersionsRegistryPath, RegistryKeyPermissionCheck.ReadSubTree)) { if (vsipRegistryKey != null) { string requestedVersionSubKeyName = this.RequestedVersion; using (RegistryKey requestedVersionRegistryKey = vsipRegistryKey.OpenSubKey(requestedVersionSubKeyName, RegistryKeyPermissionCheck.ReadSubTree)) { if (requestedVersionRegistryKey != null) { installDir = requestedVersionRegistryKey.GetValue(VsSdkInstallDirRegistryValue, null) as string; log.LogMessage(MessageImportance.Low, "Using Visual Studio SDK installation directory from registry for version \"{0}\": \"{1}\"", requestedVersionSubKeyName, installDir); } else if (requestedVersionSubKeyName == "8.0") { // Fallback on the 9.0 SDK, enabling a VS2005 build with a 2008SDK install // and minimal additional files. requestedVersionSubKeyName = "9.0"; using (RegistryKey requestedVersionRegistryKeyFallback = vsipRegistryKey.OpenSubKey(requestedVersionSubKeyName, RegistryKeyPermissionCheck.ReadSubTree)) { if (requestedVersionRegistryKeyFallback != null) { installDir = requestedVersionRegistryKeyFallback.GetValue(VsSdkInstallDirRegistryValue, null) as string; log.LogMessage(MessageImportance.Low, "Using Visual Studio SDK installation directory from registry for version \"{0}\": \"{1}\"", requestedVersionSubKeyName, installDir); } } } } } } if (string.IsNullOrEmpty(installDir)) { // if the install has not been found try vswhere // according to https://github.com/Microsoft/vswhere/wiki the install path will be maintained string vsWherePath = Environment.ExpandEnvironmentVariables(@"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe"); if (!File.Exists(vsWherePath)) { vsWherePath = Environment.ExpandEnvironmentVariables(@"%ProgramFiles%\Microsoft Visual Studio\Installer\vswhere.exe"); if (!File.Exists(vsWherePath)) { vsWherePath = null; } } if (string.IsNullOrEmpty(vsWherePath)) { log.LogError("Unable to find vswhere."); } else { #if VISUALSTUDIO_17_0 string versionParameter = "-version [17.0,16.0)"; #elif VISUALSTUDIO_16_0 string versionParameter = "-version [16.0,17.0)"; #elif VISUALSTUDIO_15_0 string versionParameter = "-version [15.0,16.0)"; #else string versionParameter = "-latest"; #endif System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(vsWherePath, versionParameter + " -property installationPath"); startInfo.RedirectStandardOutput = true; startInfo.UseShellExecute = false; startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; using (System.Diagnostics.Process p = System.Diagnostics.Process.Start(startInfo)) { string paths = p.StandardOutput.ReadToEnd(); p.WaitForExit(); string[] pathArray = paths.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); if (pathArray.Length > 0) { installDir = Path.Combine(pathArray[pathArray.Length - 1], "VSSDK"); } } } } } if (string.IsNullOrEmpty(installDir)) { log.LogError("Unable to find Visual Studio SDK installation directory."); return(false); } DirectoryInfo installDirInfo = new DirectoryInfo(installDir); if (!installDirInfo.Exists) { log.LogError("Visual Studio SDK installation directory \"{0}\" does not exist.", installDir); return(false); } installDir = this._installationDirectory = installDirInfo.FullName; // Get the include files directory DirectoryInfo includesDirInfo = new DirectoryInfo(Path.Combine(installDir, VsSdkIncludeFilesSubdirectory)); if (includesDirInfo.Exists) { string includesDir = this._includesDirectory = includesDirInfo.FullName; log.LogMessage(MessageImportance.Low, "Visual Studio SDK include files directory found at \"{0}\".", includesDir); } else { log.LogWarning("Visual Studio SDK include files directory \"{0}\" does not exist.", includesDirInfo.FullName); } // Get the tools directory DirectoryInfo toolsDirInfo = new DirectoryInfo(Path.Combine(installDir, VsSdkToolsSubdirectory)); if (toolsDirInfo.Exists) { string toolsDir = this._toolsDirectory = toolsDirInfo.FullName; log.LogMessage(MessageImportance.Low, "Visual Studio SDK tools directory found at \"{0}\".", toolsDir); } else { log.LogWarning("Visual Studio SDK tools directory \"{0}\" does not exist.", toolsDirInfo.FullName); } // Get the redistributables directory DirectoryInfo redistributablesDirInfo = new DirectoryInfo(Path.Combine(installDir, VsSdkRedistributablesSubdirectory)); if (redistributablesDirInfo.Exists) { string redistributablesDir = this._redistributablesDirectory = redistributablesDirInfo.FullName; log.LogMessage(MessageImportance.Low, "Visual Studio SDK redistributables directory found at \"{0}\".", redistributablesDir); } else { log.LogWarning("Visual Studio SDK redistributables directory \"{0}\" does not exist.", redistributablesDirInfo.FullName); } return(true); }
public Configuration(string tempDir, string[] explicitSignList, Dictionary <string, SignInfo> mapPublicKeyTokenToSignInfo, Dictionary <ExplicitCertificateKey, string> overridingSigningInfo, string publishUri, TaskLoggingHelper log) { _pathToContainerUnpackingDirectory = Path.Combine(tempDir, "ZipArchiveUnpackingDirectory"); _log = log; _publishUri = publishUri; _defaultSignInfoForPublicKeyToken = mapPublicKeyTokenToSignInfo; _explicitCertificates = overridingSigningInfo; _zipDataMap = new Dictionary <FileName, ZipData>(); _explicitSignList = explicitSignList; }
public UploadClient(TaskLoggingHelper loggingHelper) { log = loggingHelper; }
public MsBuildContext(ITask parentTask) { _parentTask = parentTask; _logger = new TaskLoggingHelper(parentTask); }
public TraceLogger(TaskLoggingHelper log) { _log = log; }
public static void LogCodedError(this TaskLoggingHelper log, string code, string file, int lineNumber, string message, params object[] messageArgs) { log.LogError(string.Empty, code, string.Empty, file, lineNumber, 0, 0, 0, message, messageArgs); }
public AddKeepAlivesStep(DirectoryAssemblyResolver resolver, TypeDefinitionCache cache, TaskLoggingHelper logger, bool hasSystemPrivateCoreLib) : base(cache) { this.resolver = resolver; this.logger = logger; this.hasSystemPrivateCoreLib = hasSystemPrivateCoreLib; }
public static void LogDebugMessage(this TaskLoggingHelper log, string message, params object[] messageArgs) { log.LogMessage(MessageImportance.Low, message, messageArgs); }
/// <summary> /// Reads the .cache file from disk into a ResGenDependencies object. /// </summary> /// <param name="stateFile"></param> /// <param name="useSourcePath"></param> /// <returns></returns> internal static ResGenDependencies DeserializeCache(string stateFile, bool useSourcePath, TaskLoggingHelper log) { ResGenDependencies retVal = (ResGenDependencies)StateFileBase.DeserializeCache(stateFile, log, typeof(ResGenDependencies)); if (retVal == null) { retVal = new ResGenDependencies(); } // Ensure that the cache is properly initialized with respect to how resgen will // resolve linked files within .resx files. ResGen has two different // ways for resolving relative file-paths in linked files. The way // that ResGen resolved relative paths before Whidbey was always to // resolve from the current working directory. In Whidbey a new command-line // switch "/useSourcePath" instructs ResGen to use the folder that // contains the .resx file as the path from which it should resolve // relative paths. So we should base our timestamp/existence checking // on the same switch & resolve in the same manner as ResGen. retVal.UseSourcePath = useSourcePath; return(retVal); }
public static void LogTaskProperty(this TaskLoggingHelper log, string propertyName, bool value) { log.LogMessage(TaskPropertyImportance, " {0}: {1}", propertyName, value); }
/// <summary> /// /// </summary> /// <returns>True if the operation was successful</returns> internal static async Task<bool> ExecuteTargets ( ITaskItem[] projects, Hashtable propertiesTable, string[] undefineProperties, ArrayList targetLists, bool stopOnFirstFailure, bool rebaseOutputs, IBuildEngine3 buildEngine, TaskLoggingHelper log, ArrayList targetOutputs, bool useResultsCache, bool unloadProjectsOnCompletion, string toolsVersion ) { bool success = true; // We don't log a message about the project and targets we're going to // build, because it'll all be in the immediately subsequent ProjectStarted event. string[] projectDirectory = new string[projects.Length]; string[] projectNames = new string[projects.Length]; string[] toolsVersions = new string[projects.Length]; IList<IDictionary<string, ITaskItem[]>> targetOutputsPerProject = null; IDictionary[] projectProperties = new IDictionary[projects.Length]; List<string>[] undefinePropertiesPerProject = new List<string>[projects.Length]; for (int i = 0; i < projectNames.Length; i++) { projectNames[i] = null; projectProperties[i] = propertiesTable; if (projects[i] != null) { // Retrieve projectDirectory only the first time. It never changes anyway. string projectPath = FileUtilities.AttemptToShortenPath(projects[i].ItemSpec); projectDirectory[i] = Path.GetDirectoryName(projectPath); projectNames[i] = projects[i].ItemSpec; toolsVersions[i] = toolsVersion; // If the user specified a different set of global properties for this project, then // parse the string containing the properties if (!String.IsNullOrEmpty(projects[i].GetMetadata("Properties"))) { Hashtable preProjectPropertiesTable; if (!PropertyParser.GetTableWithEscaping (log, ResourceUtilities.FormatResourceString("General.OverridingProperties", projectNames[i]), "Properties", projects[i].GetMetadata("Properties").Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries), out preProjectPropertiesTable) ) { return false; } projectProperties[i] = preProjectPropertiesTable; } if (undefineProperties != null) { undefinePropertiesPerProject[i] = new List<string>(undefineProperties); } // If the user wanted to undefine specific global properties for this project, parse // that string and remove them now. string projectUndefineProperties = projects[i].GetMetadata("UndefineProperties"); if (!String.IsNullOrEmpty(projectUndefineProperties)) { string[] propertiesToUndefine = projectUndefineProperties.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (undefinePropertiesPerProject[i] == null) { undefinePropertiesPerProject[i] = new List<string>(propertiesToUndefine.Length); } if (log != null && propertiesToUndefine.Length > 0) { log.LogMessageFromResources(MessageImportance.Low, "General.ProjectUndefineProperties", projectNames[i]); foreach (string property in propertiesToUndefine) { undefinePropertiesPerProject[i].Add(property); log.LogMessageFromText(String.Format(CultureInfo.InvariantCulture, " {0}", property), MessageImportance.Low); } } } // If the user specified a different set of global properties for this project, then // parse the string containing the properties if (!String.IsNullOrEmpty(projects[i].GetMetadata("AdditionalProperties"))) { Hashtable additionalProjectPropertiesTable; if (!PropertyParser.GetTableWithEscaping (log, ResourceUtilities.FormatResourceString("General.AdditionalProperties", projectNames[i]), "AdditionalProperties", projects[i].GetMetadata("AdditionalProperties").Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries), out additionalProjectPropertiesTable) ) { return false; } Hashtable combinedTable = new Hashtable(StringComparer.OrdinalIgnoreCase); // First copy in the properties from the global table that not in the additional properties table if (projectProperties[i] != null) { foreach (DictionaryEntry entry in projectProperties[i]) { if (!additionalProjectPropertiesTable.Contains(entry.Key)) { combinedTable.Add(entry.Key, entry.Value); } } } // Add all the additional properties foreach (DictionaryEntry entry in additionalProjectPropertiesTable) { combinedTable.Add(entry.Key, entry.Value); } projectProperties[i] = combinedTable; } // If the user specified a different toolsVersion for this project - then override the setting if (!String.IsNullOrEmpty(projects[i].GetMetadata("ToolsVersion"))) { toolsVersions[i] = projects[i].GetMetadata("ToolsVersion"); } } } foreach (string[] targetList in targetLists) { if (stopOnFirstFailure && !success) { // Inform the user that we skipped the remaining targets StopOnFirstFailure=true. log.LogMessageFromResources(MessageImportance.Low, "MSBuild.SkippingRemainingTargets"); // We have encountered a failure. Caller has requested that we not // continue with remaining targets. break; } // Send the project off to the build engine. By passing in null to the // first param, we are indicating that the project to build is the same // as the *calling* project file. bool currentTargetResult = true; TaskHost taskHost = (TaskHost)buildEngine; BuildEngineResult result = await taskHost.InternalBuildProjects(projectNames, targetList, projectProperties, undefinePropertiesPerProject, toolsVersions, true /* ask that target outputs are returned in the buildengineresult */); currentTargetResult = result.Result; targetOutputsPerProject = result.TargetOutputsPerProject; success = success && currentTargetResult; // If the engine was able to satisfy the build request if (currentTargetResult) { for (int i = 0; i < projects.Length; i++) { IEnumerable nonNullTargetList = (targetList != null) ? targetList : targetOutputsPerProject[i].Keys; foreach (string targetName in nonNullTargetList) { if (targetOutputsPerProject[i].ContainsKey(targetName)) { ITaskItem[] outputItemsFromTarget = (ITaskItem[])targetOutputsPerProject[i][targetName]; foreach (ITaskItem outputItemFromTarget in outputItemsFromTarget) { // No need to rebase if the calling project is the same as the callee project // (project == null). Also no point in trying to copy item metadata either, // because no items were passed into the Projects parameter! if (projects[i] != null) { // Rebase the output item paths if necessary. No need to rebase if the calling // project is the same as the callee project (project == null). if (rebaseOutputs) { try { outputItemFromTarget.ItemSpec = Path.Combine(projectDirectory[i], outputItemFromTarget.ItemSpec); } catch (ArgumentException e) { log.LogWarningWithCodeFromResources(null, projects[i].ItemSpec, 0, 0, 0, 0, "MSBuild.CannotRebaseOutputItemPath", outputItemFromTarget.ItemSpec, e.Message); } } // Copy the custom item metadata from the "Projects" items to these // output items. projects[i].CopyMetadataTo(outputItemFromTarget); // Set a metadata on the output items called "MSBuildProjectFile" which tells you which project file produced this item. if (String.IsNullOrEmpty(outputItemFromTarget.GetMetadata(ItemMetadataNames.msbuildSourceProjectFile))) { outputItemFromTarget.SetMetadata(ItemMetadataNames.msbuildSourceProjectFile, projects[i].GetMetadata(FileUtilities.ItemSpecModifiers.FullPath)); } } // Set a metadata on the output items called "MSBuildTargetName" which tells you which target produced this item. if (String.IsNullOrEmpty(outputItemFromTarget.GetMetadata(ItemMetadataNames.msbuildSourceTargetName))) { outputItemFromTarget.SetMetadata(ItemMetadataNames.msbuildSourceTargetName, targetName); } } targetOutputs.AddRange(outputItemsFromTarget); } } } } } return success; }
public MSBuildLogger(TaskLoggingHelper logHelper) { _logHelper = logHelper; }