/// <summary> /// Deserialize the file into an SdkResolverManifest. /// </summary> /// <param name="filePath">Path to the manifest xml file.</param> /// <returns>New deserialized collection instance.</returns> internal static SdkResolverManifest Load(string filePath) { XmlReaderSettings readerSettings = new XmlReaderSettings() { IgnoreComments = true, IgnoreWhitespace = true, DtdProcessing = DtdProcessing.Ignore, XmlResolver = null }; using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) using (XmlReader reader = XmlReader.Create(stream, readerSettings)) { while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: switch (reader.Name) { case "SdkResolver": return(ParseSdkResolverElement(reader)); default: throw new XmlException(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("UnrecognizedElement", reader.Name)); } default: throw new XmlException(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("UnrecognizedElement", reader.Name)); } } } return(null); }
/// <summary> /// Constructs a BuildAbortedException with an additional message attached and an inner exception. /// </summary> public BuildAbortedException(string message, Exception innerException) : base(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("BuildAbortedWithMessage", message), innerException) { ResourceUtilities.FormatResourceStringStripCodeAndKeyword(out string errorCode, out _, "BuildAbortedWithMessage", message); ErrorCode = errorCode; }
/// <summary> /// Throws an ArgumentException if the string has zero length, unless it is /// null, in which case no exception is thrown. /// </summary> internal static void VerifyThrowArgumentLengthIfNotNull(string parameter, string parameterName) { if (parameter?.Length == 0 && s_throwExceptions) { throw new ArgumentException(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("Shared.ParameterCannotHaveZeroLength", parameterName)); } }
/// <summary> /// Read the provided binary log file and raise corresponding events for each BuildEventArgs /// </summary> /// <param name="sourceFilePath">The full file path of the binary log file</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> indicating the replay should stop as soon as possible.</param> public void Replay(string sourceFilePath, CancellationToken cancellationToken) { using (var stream = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { var gzipStream = new GZipStream(stream, CompressionMode.Decompress, leaveOpen: true); var binaryReader = new BinaryReader(gzipStream); int fileFormatVersion = binaryReader.ReadInt32(); // the log file is written using a newer version of file format // that we don't know how to read if (fileFormatVersion > BinaryLogger.FileFormatVersion) { var text = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("UnsupportedLogFileFormat", fileFormatVersion, BinaryLogger.FileFormatVersion); throw new NotSupportedException(text); } var reader = new BuildEventArgsReader(binaryReader, fileFormatVersion); while (true) { if (cancellationToken.IsCancellationRequested) { return; } BuildEventArgs instance = reader.Read(); if (instance == null) { break; } Dispatch(instance); } } }
/// <summary> /// Pretty prints the aggregated results and saves it to disk /// </summary> /// <remarks> /// If the extension of the file to log is 'md', markdown content is generated. Otherwise, it falls /// back to a tab separated format /// </remarks> private void GenerateProfilerReport() { try { Console.WriteLine(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("WritingProfilerReport", FileToLog)); // If the extension of the file is 'md', markdown content is produced. For any other case, // a tab separated format is generated var content = System.IO.Path.GetExtension(FileToLog) == ".md" ? ProfilerResultPrettyPrinter.GetMarkdownContent(GetAggregatedResult()) : ProfilerResultPrettyPrinter.GetTsvContent(GetAggregatedResult()); File.WriteAllText(FileToLog, content); Console.WriteLine(ResourceUtilities.GetResourceString("WritingProfilerReportDone")); } catch (DirectoryNotFoundException ex) { Console.WriteLine(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ErrorWritingProfilerReport", ex.Message)); } catch (IOException ex) { Console.WriteLine(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ErrorWritingProfilerReport", ex.Message)); } catch (UnauthorizedAccessException ex) { Console.WriteLine(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ErrorWritingProfilerReport", ex.Message)); } catch (SecurityException ex) { Console.WriteLine(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ErrorWritingProfilerReport", ex.Message)); } }
public void LogVerbosityMessage(LoggerVerbosity loggerVerbosity, bool shouldContain) { using (var testEnvironment = TestEnvironment.Create()) { var fileLogger = new FileLogger { Verbosity = loggerVerbosity }; var logFile = testEnvironment.CreateFile(".log"); fileLogger.Parameters = "logfile=" + logFile.Path; Project project = ObjectModelHelpers.CreateInMemoryProject(@" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <Target Name=`Build` /> </Project> "); project.Build(fileLogger); project.ProjectCollection.UnregisterAllLoggers(); string log = File.ReadAllText(logFile.Path); var message = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("LogLoggerVerbosity", loggerVerbosity); if (shouldContain) { Assert.Contains(message, log); } else { Assert.DoesNotContain(message, log); } } }
private static string BuildStringFromResource ( string projectFile, int fileLine, int fileEndLine, int fileColumn, int fileEndColumn, string resourceName, params object[] args ) { string errorCode; string helpKeyword; string message = ResourceUtilities.FormatResourceStringStripCodeAndKeyword(out errorCode, out helpKeyword, resourceName, args); return(EventArgsFormatting.FormatEventMessage ( "error", AssemblyResources.GetString("SubCategoryForSchemaValidationErrors"), message, errorCode, projectFile, fileLine, fileEndLine, fileColumn, fileEndColumn, 0 /* thread id */ )); }
private string GatherArguments(string parentSwitch, ICollection <Tuple <string, bool> > arguments, string separator) { string retVal = String.Empty; if (arguments != null) { foreach (Tuple <string, bool> arg in arguments) { if (_activeCommandLineToolSwitches.TryGetValue(arg.Item1, out CommandLineToolSwitch argSwitch)) { if (!String.IsNullOrEmpty(retVal)) { retVal += separator; } retVal += argSwitch.Value; } else { if (arg.Item2) { throw new ArgumentException(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("Xaml.MissingRequiredArgument", parentSwitch, arg.Item1)); } } } } return(retVal); }
/// <summary> /// Retrieve the project call stack based on the starting point of buildEventContext e /// </summary> internal string[] ProjectCallStackFromProject(BuildEventContext e) { BuildEventContext currentKey = e; ProjectStartedEventMinimumFields startedEvent = GetProjectStartedEvent(currentKey); List <string> stackTrace = new List <string>(); // If there is no started event then there should be no stack trace // this is a valid situation if the event occures in the engine or outside the context of a project // or the event is raised before the project started event if (startedEvent == null) { return(Array.Empty <string>()); } List <ProjectStartedEventMinimumFields> projectStackTrace = GetProjectCallStack(e); foreach (ProjectStartedEventMinimumFields projectStartedEvent in projectStackTrace) { if (!string.IsNullOrEmpty(projectStartedEvent.TargetNames)) { stackTrace.Add(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ProjectStackWithTargetNames", projectStartedEvent.ProjectFile, projectStartedEvent.TargetNames, projectStartedEvent.FullProjectKey)); } else { stackTrace.Add(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ProjectStackWithDefaultTargets", projectStartedEvent.ProjectFile, projectStartedEvent.FullProjectKey)); } } stackTrace.Reverse(); return(stackTrace.ToArray()); }
internal static void VerifyProjectSchema ( string projectFile, string schemaFile, string binPath ) { ErrorUtilities.VerifyThrowArgumentNull(projectFile, nameof(projectFile)); ErrorUtilities.VerifyThrowArgumentNull(binPath, nameof(binPath)); if (string.IsNullOrEmpty(schemaFile)) { schemaFile = Path.Combine(binPath, "Microsoft.Build.xsd"); } if (FileSystems.Default.FileExists(schemaFile)) { // Print the schema file we're using, particularly since it can vary // according to the toolset being used Console.WriteLine(AssemblyResources.GetString("SchemaFileLocation"), schemaFile); } else { // If we've gotten to this point, there is no schema to validate against -- just exit. InitializationException.Throw ( ResourceUtilities.FormatResourceStringStripCodeAndKeyword("SchemaNotFoundErrorWithFile", schemaFile), null /* No associated command line switch */ ); } ProjectSchemaValidationHandler validationHandler = new ProjectSchemaValidationHandler(); validationHandler.VerifyProjectSchema(projectFile, schemaFile); }
/// <summary> /// Parse a Xaml document from a TextReader /// </summary> internal bool ParseXamlDocument(TextReader reader, string desiredRule) { ErrorUtilities.VerifyThrowArgumentNull(reader, nameof(reader)); ErrorUtilities.VerifyThrowArgumentLength(desiredRule, nameof(desiredRule)); object rootObject = XamlServices.Load(reader); if (null != rootObject) { XamlTypes.ProjectSchemaDefinitions schemas = rootObject as XamlTypes.ProjectSchemaDefinitions; if (schemas != null) { foreach (XamlTypes.IProjectSchemaNode node in schemas.Nodes) { XamlTypes.Rule rule = node as XamlTypes.Rule; if (rule != null) { if (String.Equals(rule.Name, desiredRule, StringComparison.OrdinalIgnoreCase)) { return(ParseXamlDocument(rule)); } } } throw new XamlParseException(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("Xaml.RuleNotFound", desiredRule)); } else { throw new XamlParseException(ResourceUtilities.GetResourceString("Xaml.InvalidRootObject")); } } return(false); }
/// <summary> /// Initializes the logger by subscribing to events of IEventSource /// </summary> public void Initialize(IEventSource eventSource) { _initialTargetOutputLogging = Environment.GetEnvironmentVariable("MSBUILDTARGETOUTPUTLOGGING"); _initialLogImports = Traits.Instance.EscapeHatches.LogProjectImports; Environment.SetEnvironmentVariable("MSBUILDTARGETOUTPUTLOGGING", "true"); Environment.SetEnvironmentVariable("MSBUILDLOGIMPORTS", "1"); Traits.Instance.EscapeHatches.LogProjectImports = true; ProcessParameters(); try { string logDirectory = null; try { logDirectory = Path.GetDirectoryName(FilePath); } catch (Exception) { // Directory creation is best-effort; if finding its path fails don't create the directory // and possibly let the FileStream constructor below report the failure } if (logDirectory != null) { Directory.CreateDirectory(logDirectory); } stream = new FileStream(FilePath, FileMode.Create); if (CollectProjectImports != ProjectImportsCollectionMode.None) { projectImportsCollector = new ProjectImportsCollector(FilePath, CollectProjectImports == ProjectImportsCollectionMode.ZipFile); } if (eventSource is IEventSource3 eventSource3) { eventSource3.IncludeEvaluationMetaprojects(); } } catch (Exception e) { string errorCode; string helpKeyword; string message = ResourceUtilities.FormatResourceStringStripCodeAndKeyword(out errorCode, out helpKeyword, "InvalidFileLoggerFile", FilePath, e.Message); throw new LoggerException(message, e, errorCode, helpKeyword); } stream = new GZipStream(stream, CompressionLevel.Optimal); binaryWriter = new BinaryWriter(stream); eventArgsWriter = new BuildEventArgsWriter(binaryWriter); binaryWriter.Write(FileFormatVersion); LogInitialInfo(); eventSource.AnyEventRaised += EventSource_AnyEventRaised; }
/// <summary> /// Creates new file for logging /// </summary> private void InitializeFileLogger(IEventSource eventSource, int nodeCount) { // Prepend the default setting of "forcenoalign": no alignment is needed as we're // writing to a file string parameters = Parameters; if (parameters != null) { Parameters = "FORCENOALIGN;" + parameters; } else { Parameters = "FORCENOALIGN;"; } ParseFileLoggerParameters(); // Finally, ask the base console logger class to initialize. It may // want to make decisions based on our verbosity, so we do this last. base.Initialize(eventSource, nodeCount); if (!SkipProjectStartedText && Verbosity >= LoggerVerbosity.Normal) { eventSource.BuildStarted += (obj, args) => WriteHandler(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("LogLoggerVerbosity", Verbosity)); } try { string logDirectory = null; try { logDirectory = Path.GetDirectoryName(Path.GetFullPath(_logFileName)); } catch { // Directory creation is best-effort; if finding its path fails don't create the directory // and possibly let OpenWrite() below report the failure } if (logDirectory != null) { Directory.CreateDirectory(logDirectory); } _fileWriter = FileUtilities.OpenWrite(_logFileName, _append, _encoding); _fileWriter.AutoFlush = _autoFlush; } catch (Exception e) when(ExceptionHandling.IsIoRelatedException(e)) { string errorCode; string helpKeyword; string message = ResourceUtilities.FormatResourceStringStripCodeAndKeyword(out errorCode, out helpKeyword, "InvalidFileLoggerFile", _logFileName, e.Message); _fileWriter?.Dispose(); throw new LoggerException(message, e.InnerException, errorCode, helpKeyword); } }
/// <summary> /// Loads a logger from its assembly, instantiates it, and handles errors. /// </summary> /// <returns>Instantiated logger.</returns> private ILogger CreateLogger(bool forwardingLogger) { ILogger logger = null; try { if (forwardingLogger) { // load the logger from its assembly LoadedType loggerClass = (new TypeLoader(s_forwardingLoggerClassFilter)).Load(_loggerClassName, _loggerAssembly); if (loggerClass != null) { // instantiate the logger logger = (IForwardingLogger)Activator.CreateInstance(loggerClass.Type); } } else { // load the logger from its assembly LoadedType loggerClass = (new TypeLoader(s_loggerClassFilter)).Load(_loggerClassName, _loggerAssembly); if (loggerClass != null) { // instantiate the logger logger = (ILogger)Activator.CreateInstance(loggerClass.Type); } } } catch (InvalidCastException e) { // The logger when trying to load has hit an invalid case, this is usually due to the framework assembly being a different version string message = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("LoggerInstantiationFailureErrorInvalidCast", _loggerClassName, _loggerAssembly.AssemblyLocation, e.Message); throw new LoggerException(message, e.InnerException); } catch (TargetInvocationException e) { // At this point, the interesting stack is the internal exception; // the outer exception is System.Reflection stuff that says nothing // about the nature of the logger failure. Exception innerException = e.InnerException; if (innerException is LoggerException) { // Logger failed politely during construction. In order to preserve // the stack trace at which the error occured we wrap the original // exception instead of throwing. LoggerException l = ((LoggerException)innerException); throw new LoggerException(l.Message, innerException, l.ErrorCode, l.HelpKeyword); } else { throw; } } return logger; }
/// <summary> /// Throws an ArgumentNullException if the given string parameter is null /// and ArgumentException if it has zero length. /// </summary> /// <param name="parameter"></param> /// <param name="parameterName"></param> internal static void VerifyThrowArgumentInvalidPath(string parameter, string parameterName) { VerifyThrowArgumentNull(parameter, parameterName); if (FileUtilities.PathIsInvalid(parameter) && s_throwExceptions) { throw new ArgumentException(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("Shared.ParameterCannotHaveInvalidPathChars", parameterName, parameter)); } }
/// <summary> /// Throws an ArgumentNullException if the given collection is null /// and ArgumentException if it has zero length. /// </summary> /// <param name="parameter"></param> /// <param name="parameterName"></param> internal static void VerifyThrowArgumentLength <T>(IReadOnlyCollection <T> parameter, string parameterName) { VerifyThrowArgumentNull(parameter, parameterName); if (parameter.Count == 0 && s_throwExceptions) { throw new ArgumentException(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("Shared.ParameterCannotHaveZeroLength", parameterName)); } }
public void OverridePropertiesInInferredCreateProperty() { string[] files = null; try { files = ObjectModelHelpers.GetTempFiles(2, new DateTime(2005, 1, 1)); MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <ItemGroup> <i Include='" + files[0] + "'><output>" + files[1] + @"</output></i> </ItemGroup> <ItemGroup> <EmbeddedResource Include='a.resx'> <LogicalName>foo</LogicalName> </EmbeddedResource> <EmbeddedResource Include='b.resx'> <LogicalName>bar</LogicalName> </EmbeddedResource> <EmbeddedResource Include='c.resx'> <LogicalName>barz</LogicalName> </EmbeddedResource> </ItemGroup> <Target Name='t2' DependsOnTargets='t'> <Message Text='final:[$(LinkSwitches)]'/> </Target> <Target Name='t' Inputs='%(i.Identity)' Outputs='%(i.Output)'> <Message Text='start:[Hello]'/> <CreateProperty Value=""@(EmbeddedResource->'/assemblyresource:%(Identity),%(LogicalName)', ' ')"" Condition=""'%(LogicalName)' != '' ""> <Output TaskParameter=""Value"" PropertyName=""LinkSwitches""/> </CreateProperty> <Message Text='end:[hello]'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List <ILogger> loggers = new List <ILogger>(); loggers.Add(logger); project.Build("t2", loggers); // We should only see messages from the second target, as the first is only inferred logger.AssertLogDoesntContain("start:"); logger.AssertLogDoesntContain("end:"); logger.AssertLogContains(new string[] { "final:[/assemblyresource:c.resx,barz]" }); logger.AssertLogDoesntContain(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("TaskStarted", "CreateProperty")); logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("PropertyOutputOverridden", "LinkSwitches", "/assemblyresource:a.resx,foo", "/assemblyresource:b.resx,bar") }); logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("PropertyOutputOverridden", "LinkSwitches", "/assemblyresource:b.resx,bar", "/assemblyresource:c.resx,barz") }); } finally { ObjectModelHelpers.DeleteTempFiles(files); } }
/// <summary> /// Processes a particular ToolsetPropertyDefinition into the correct value and location in the initial and/or final property set. /// </summary> /// <param name="property">The ToolsetPropertyDefinition being analyzed.</param> /// <param name="properties">The final set of properties that we wish this toolset property to be added to. </param> /// <param name="globalProperties">The global properties, used for expansion and to make sure none are overridden.</param> /// <param name="initialProperties">The initial properties, used for expansion and added to if "accumulateProperties" is true.</param> /// <param name="accumulateProperties">If "true", we add this property to the initialProperties dictionary, as well, so that properties later in the toolset can use this value.</param> /// <param name="toolsPath">If this toolset property is the "MSBuildToolsPath" property, we will return the value in this parameter.</param> /// <param name="binPath">If this toolset property is the "MSBuildBinPath" property, we will return the value in this parameter.</param> /// <param name="expander">The expander used to expand the value of the properties. Ref because if we are accumulating the properties, we need to re-create the expander to account for the new property value.</param> private void EvaluateAndSetProperty(ToolsetPropertyDefinition property, PropertyDictionary <ProjectPropertyInstance> properties, PropertyDictionary <ProjectPropertyInstance> globalProperties, PropertyDictionary <ProjectPropertyInstance> initialProperties, bool accumulateProperties, ref string toolsPath, ref string binPath, ref Expander <ProjectPropertyInstance, ProjectItemInstance> expander) { if (0 == String.Compare(property.Name, ReservedPropertyNames.toolsPath, StringComparison.OrdinalIgnoreCase)) { toolsPath = ExpandPropertyUnescaped(property, expander); toolsPath = ExpandRelativePathsRelativeToExeLocation(toolsPath); if (accumulateProperties) { SetProperty ( new ToolsetPropertyDefinition(ReservedPropertyNames.toolsPath, toolsPath, property.Source), initialProperties, globalProperties ); } } else if (0 == String.Compare(property.Name, ReservedPropertyNames.binPath, StringComparison.OrdinalIgnoreCase)) { binPath = ExpandPropertyUnescaped(property, expander); binPath = ExpandRelativePathsRelativeToExeLocation(binPath); if (accumulateProperties) { SetProperty ( new ToolsetPropertyDefinition(ReservedPropertyNames.binPath, binPath, property.Source), initialProperties, globalProperties ); } } else if (ReservedPropertyNames.IsReservedProperty(property.Name)) { // We don't allow toolsets to define reserved properties string baseMessage = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("CannotModifyReservedProperty", property.Name); InvalidToolsetDefinitionException.Throw("InvalidPropertyNameInToolset", property.Name, property.Source.LocationString, baseMessage); } else { // It's an arbitrary property property.Value = ExpandPropertyUnescaped(property, expander); SetProperty(property, properties, globalProperties); if (accumulateProperties) { SetProperty(property, initialProperties, globalProperties); } } if (accumulateProperties) { expander = new Expander <ProjectPropertyInstance, ProjectItemInstance>(initialProperties, FileSystems.Default); } }
/// <summary> /// Throws an InvalidOperationException with the specified resource string /// </summary> /// <param name="resourceName">Resource to use in the exception</param> /// <param name="args">Formatting args.</param> internal static void ThrowInvalidOperation(string resourceName, params object[] args) { #if DEBUG ResourceUtilities.VerifyResourceStringExists(resourceName); #endif if (s_throwExceptions) { throw new InvalidOperationException(ResourceUtilities.FormatResourceStringStripCodeAndKeyword(resourceName, args)); } }
/// <summary> /// Verifies the given arrays are not null and have the same length /// </summary> /// <param name="parameter1"></param> /// <param name="parameter2"></param> /// <param name="parameter1Name"></param> /// <param name="parameter2Name"></param> internal static void VerifyThrowArgumentArraysSameLength(Array parameter1, Array parameter2, string parameter1Name, string parameter2Name) { VerifyThrowArgumentNull(parameter1, parameter1Name); VerifyThrowArgumentNull(parameter2, parameter2Name); if (parameter1.Length != parameter2.Length && s_throwExceptions) { throw new ArgumentException(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("Shared.ParametersMustHaveTheSameLength", parameter1Name, parameter2Name)); } }
public void TestGeneralFrameworkMonikerGoodWithInvalidCharInIncludePath() { string tempDirectory = Path.Combine(Path.GetTempPath(), "TestGeneralFrameworkMonikerGoodWithInvalidCharInIncludePath"); string framework41Directory = Path.Combine(tempDirectory, Path.Combine("MyFramework", "v4.1") + Path.DirectorySeparatorChar); string redistListDirectory = Path.Combine(framework41Directory, "RedistList"); string redistListFile = Path.Combine(redistListDirectory, "FrameworkList.xml"); try { Directory.CreateDirectory(framework41Directory); Directory.CreateDirectory(redistListDirectory); string redistListContents = "<FileList Redist='Microsoft-Windows-CLRCoreComp' IncludeFramework='v4.*' Name='Chained oh noes'>" + "<File AssemblyName='System.Xml' Version='2.0.0.0' PublicKeyToken='b03f5f7f11d50a3a' Culture='Neutral' FileVersion='2.0.50727.208' InGAC='true' />" + "<File AssemblyName='Microsoft.Build.Engine' Version='2.0.0.0' PublicKeyToken='b03f5f7f11d50a3a' Culture='Neutral' FileVersion='2.0.50727.208' InGAC='true' />" + "</FileList >"; File.WriteAllText(redistListFile, redistListContents); string targetFrameworkMoniker = "MyFramework, Version=v4.1"; MockEngine engine = new MockEngine(); GetReferenceAssemblyPaths getReferencePaths = new GetReferenceAssemblyPaths(); getReferencePaths.BuildEngine = engine; getReferencePaths.TargetFrameworkMoniker = targetFrameworkMoniker; getReferencePaths.RootPath = tempDirectory; getReferencePaths.Execute(); string[] returnedPaths = getReferencePaths.ReferenceAssemblyPaths; Assert.Empty(returnedPaths); string displayName = getReferencePaths.TargetFrameworkMonikerDisplayName; Assert.Null(displayName); FrameworkNameVersioning frameworkMoniker = new FrameworkNameVersioning(getReferencePaths.TargetFrameworkMoniker); if (NativeMethodsShared.IsWindows) { engine.AssertLogContains("MSB3643"); } else { // Since under Unix there are no invalid characters, we don't fail in the incorrect path // and go through to actually looking for the directory string message = ResourceUtilities.FormatResourceStringStripCodeAndKeyword( "GetReferenceAssemblyPaths.NoReferenceAssemblyDirectoryFound", frameworkMoniker.ToString()); engine.AssertLogContains(message); } } finally { if (Directory.Exists(framework41Directory)) { FileUtilities.DeleteWithoutTrailingBackslash(framework41Directory, true); } } }
/// <summary> /// Throws an ArgumentNullException if the given parameter is null. /// </summary> /// <remarks>This method is thread-safe.</remarks> internal static void VerifyThrowArgumentNull(object parameter, string parameterName, string resourceName) { if (parameter == null && s_throwExceptions) { // Most ArgumentNullException overloads append its own rather clunky multi-line message. // So use the one overload that doesn't. throw new ArgumentNullException( ResourceUtilities.FormatResourceStringStripCodeAndKeyword(resourceName, parameterName), (Exception)null); } }
public void VerifyFindInvalidProjectReferences() { // Create the engine. MockEngine engine = new MockEngine(); FindInvalidProjectReferences t = new FindInvalidProjectReferences(); t.TargetPlatformVersion = "8.0"; t.TargetPlatformIdentifier = "Windows"; Dictionary <string, string> proj1 = new Dictionary <string, string>(); proj1["TargetPlatformMoniker"] = "Windows, Version=7.0"; Dictionary <string, string> proj2 = new Dictionary <string, string>(); proj2["TargetPlatformMoniker"] = "Windows, Version=8.0"; Dictionary <string, string> proj3 = new Dictionary <string, string>(); proj3["TargetPlatformMoniker"] = "Windows, Version=8.1"; Dictionary <string, string> proj4 = new Dictionary <string, string>(); proj4["TargetPlatformMoniker"] = "Windows, Version=8.2"; t.ProjectReferences = new TaskItem[] { new TaskItem("proj1.proj", proj1), new TaskItem("proj2.proj", proj2), new TaskItem("proj3.proj", proj3), new TaskItem("proj4.proj", proj4) }; t.BuildEngine = engine; bool succeeded = t.Execute(); Assert.True(succeeded); string warning1 = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("FindInvalidProjectReferences.WarnWhenVersionIsIncompatible", "Windows", "8.0", "proj1.proj", "Windows, Version=7.0"); engine.AssertLogDoesntContain(warning1); string warning2 = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("FindInvalidProjectReferences.WarnWhenVersionIsIncompatible", "Windows", "8.0", "proj2.proj", "Windows, Version=8.0"); engine.AssertLogDoesntContain(warning2); string warning3 = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("FindInvalidProjectReferences.WarnWhenVersionIsIncompatible", "Windows", "8.0", "proj3.proj", "Windows, Version=8.1"); engine.AssertLogContains(warning3); string warning4 = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("FindInvalidProjectReferences.WarnWhenVersionIsIncompatible", "Windows", "8.0", "proj4.proj", "Windows, Version=8.2"); engine.AssertLogContains(warning4); Assert.Equal(t.InvalidReferences.Length, 2); Assert.Equal(t.InvalidReferences[0].ItemSpec, "proj3.proj"); Assert.Equal(t.InvalidReferences[1].ItemSpec, "proj4.proj"); }