/// <summary> /// Returns all of the extension methods with the given name. /// </summary> public IEnumerable <MethodInfo> GetExtensionMethods(string /*!*/ name) { Assert.NotNull(name); lock (this) { EnsureLoaded(); foreach (var keyValue in _loadedAssemblies) { AssemblyLoadInfo info = keyValue.Value; Debug.Assert(info.Types != null); foreach (var type in info.Types) { List <MethodInfo> methods; if (type.ExtensionMethods.TryGetValue(name, out methods)) { foreach (var method in methods) { yield return(method); } } } } } }
public void NoTypeNamePicksFirstType() { Type forwardingLoggerType = typeof(Microsoft.Build.Logging.ConfigurableForwardingLogger); string forwardingLoggerAssemblyLocation = forwardingLoggerType.Assembly.Location; TypeFilter forwardingLoggerfilter = new TypeFilter(IsForwardingLoggerClass); Type firstPublicType = FirstPublicDesiredType(forwardingLoggerfilter, forwardingLoggerAssemblyLocation); TypeLoader loader = new TypeLoader(forwardingLoggerfilter); LoadedType loadedType = loader.Load(String.Empty, AssemblyLoadInfo.Create(null, forwardingLoggerAssemblyLocation)); Assert.IsNotNull(loadedType); Assert.IsTrue(loadedType.Assembly.AssemblyLocation.Equals(forwardingLoggerAssemblyLocation, StringComparison.OrdinalIgnoreCase)); Assert.IsTrue(loadedType.Type.Equals(firstPublicType)); Type fileLoggerType = typeof(Microsoft.Build.Logging.FileLogger); string fileLoggerAssemblyLocation = forwardingLoggerType.Assembly.Location; TypeFilter fileLoggerfilter = new TypeFilter(IsLoggerClass); firstPublicType = FirstPublicDesiredType(fileLoggerfilter, fileLoggerAssemblyLocation); loader = new TypeLoader(fileLoggerfilter); loadedType = loader.Load(String.Empty, AssemblyLoadInfo.Create(null, fileLoggerAssemblyLocation)); Assert.IsNotNull(loadedType); Assert.IsTrue(loadedType.Assembly.AssemblyLocation.Equals(fileLoggerAssemblyLocation, StringComparison.OrdinalIgnoreCase)); Assert.IsTrue(loadedType.Type.Equals(firstPublicType)); }
public void NoTypeNamePicksFirstType() { Type forwardingLoggerType = typeof(Microsoft.Build.Logging.ConfigurableForwardingLogger); string forwardingLoggerAssemblyLocation = forwardingLoggerType.Assembly.Location; Func <Type, object, bool> forwardingLoggerfilter = IsForwardingLoggerClass; Type firstPublicType = FirstPublicDesiredType(forwardingLoggerfilter, forwardingLoggerAssemblyLocation); TypeLoader loader = new TypeLoader(forwardingLoggerfilter); LoadedType loadedType = loader.Load(String.Empty, AssemblyLoadInfo.Create(null, forwardingLoggerAssemblyLocation)); Assert.NotNull(loadedType); Assert.Equal(forwardingLoggerAssemblyLocation, loadedType.Assembly.AssemblyLocation); Assert.Equal(firstPublicType, loadedType.Type); Type fileLoggerType = typeof(Microsoft.Build.Logging.FileLogger); string fileLoggerAssemblyLocation = forwardingLoggerType.Assembly.Location; Func <Type, object, bool> fileLoggerfilter = IsLoggerClass; firstPublicType = FirstPublicDesiredType(fileLoggerfilter, fileLoggerAssemblyLocation); loader = new TypeLoader(fileLoggerfilter); loadedType = loader.Load(String.Empty, AssemblyLoadInfo.Create(null, fileLoggerAssemblyLocation)); Assert.NotNull(loadedType); Assert.Equal(fileLoggerAssemblyLocation, loadedType.Assembly.AssemblyLocation); Assert.Equal(firstPublicType, loadedType.Type); }
public void RegisterTask(string classname, AssemblyLoadInfo assemblyLoadInfo) { assemblyInformation.Add(classname, assemblyLoadInfo); Assembly assembly; if (assemblyLoadInfo.InfoType == LoadInfoType.AssemblyFilename) { assembly = Assembly.LoadFrom(assemblyLoadInfo.Filename); } else if (assemblyLoadInfo.InfoType == LoadInfoType.AssemblyName) { assembly = Assembly.Load(assemblyLoadInfo.AssemblyName); } else { assembly = Assembly.Load(assemblyLoadInfo.AssemblyNameString); } Type type = assembly.GetType(classname); if (type == null) { // search for matching class in case namespace was not used foreach (Type exportedType in assembly.GetExportedTypes()) { if (exportedType.Name == classname) { type = exportedType; break; } } } typesByFullName.Add(classname, type); typesByShortName [GetShortName(classname)] = type; }
public static ExtensionMethodSet AddType(PythonContext context, ExtensionMethodSet /*!*/ existingSet, PythonType /*!*/ type) { Assert.NotNull(existingSet, type); lock (existingSet) { AssemblyLoadInfo assemblyLoadInfo; Assembly assembly = type.UnderlyingSystemType.GetTypeInfo().Assembly; if (existingSet._loadedAssemblies.TryGetValue(assembly, out assemblyLoadInfo)) { if (assemblyLoadInfo.IsFullAssemblyLoaded || (assemblyLoadInfo.Types != null && assemblyLoadInfo.Types.Contains(type)) || (assemblyLoadInfo.Namespaces != null && assemblyLoadInfo.Namespaces.Contains(type.UnderlyingSystemType.Namespace))) { // type is already in this set. return(existingSet); } } var dict = NewInfoOrCopy(existingSet); if (!dict.TryGetValue(assembly, out assemblyLoadInfo)) { dict[assembly] = assemblyLoadInfo = new AssemblyLoadInfo(assembly); } if (assemblyLoadInfo.Types == null) { assemblyLoadInfo.Types = new HashSet <PythonType>(); } assemblyLoadInfo.Types.Add(type); return(context.UniqifyExtensions(new ExtensionMethodSet(dict))); } }
/// <summary> /// Returns all of the extension methods which are applicable for the given type. /// </summary> public IEnumerable <MethodInfo> GetExtensionMethods(PythonType type) { lock (this) { EnsureLoaded(); foreach (var keyValue in _loadedAssemblies) { AssemblyLoadInfo info = keyValue.Value; Debug.Assert(info.Types != null); foreach (var containingType in info.Types) { foreach (var methodList in containingType.ExtensionMethods.Values) { foreach (var method in methodList) { var methodParams = method.GetParameters(); if (methodParams.Length == 0) { continue; } if (PythonExtensionBinder.IsApplicableExtensionMethod(type.UnderlyingSystemType, methodParams[0].ParameterType)) { yield return(method); } } } } } } }
public void RegisterMultipleTasksSomeWithSameName() { UsingTaskInfo[] taskInfos = { new UsingTaskInfo("CustomTask", "CustomTask, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", null), new UsingTaskInfo("YetAnotherCustomTask", "YetAnotherCustomTask, Version=9.0.0.0, Culture=neutral, PublicKeyToken=null", null), new UsingTaskInfo("CustomTask", "CustomTask, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null", null) }; TaskRegistry registryStub = TaskRegistryHelperMethods.CreateTaskRegistryAndRegisterTasks(taskInfos); //First assert that there are two unique buckets Assert.AreEqual(2, registryStub.AllTaskDeclarations.Count, "Expected only two buckets since two of three tasks have the same name!"); //Now let's look at the bucket with only one task ArrayList singletonBucket = (ArrayList)registryStub.AllTaskDeclarations[taskInfos[1].TaskName]; Assert.IsNotNull(singletonBucket, "Task AssemblyLoadInfo not found in TaskRegistry.AllTaskDeclarations!"); Assert.AreEqual(1, singletonBucket.Count, "Expected only one AssemblyLoadInfo registered under this TaskName!"); AssemblyLoadInfo singletonAssemblyLoadInfo = (AssemblyLoadInfo)singletonBucket[0]; Assert.AreEqual(singletonAssemblyLoadInfo, taskInfos[1].AssemblyInfo, "Task AssemblyLoadInfo was not properly registered by TaskRegistry.RegisterTask!"); //Finally let's look at the bucket with two tasks ArrayList duplicateBucket = (ArrayList)registryStub.AllTaskDeclarations[taskInfos[0].TaskName]; Assert.IsNotNull(duplicateBucket, "Task AssemblyLoadInfo not found in TaskRegistry.AllTaskDeclarations!"); Assert.AreEqual(2, duplicateBucket.Count, "Expected two AssemblyLoadInfos registered under this TaskName!"); bool bothTaskVersionsFound = duplicateBucket.Contains(taskInfos[0].AssemblyInfo) && duplicateBucket.Contains(taskInfos[2].AssemblyInfo); Assert.IsTrue(bothTaskVersionsFound, "Expected both versions of the task to be registered in this bucket!"); }
/// <summary> /// Converts the path to the logger assembly to a full path /// </summary> internal void ConvertPathsToFullPaths() { if (loggerAssembly.AssemblyFile != null) { loggerAssembly = new AssemblyLoadInfo(loggerAssembly.AssemblyName, Path.GetFullPath(loggerAssembly.AssemblyFile)); } }
/// <summary> /// Converts the path to the logger assembly to a full path /// </summary> internal void ConvertPathsToFullPaths() { if (_loggerAssembly.AssemblyFile != null) { _loggerAssembly = AssemblyLoadInfo.Create(_loggerAssembly.AssemblyName, Path.GetFullPath(_loggerAssembly.AssemblyFile)); } }
/// <summary> /// Abstract out the creation of the new AssemblyTaskFactory with default task, and /// with some basic validation. /// </summary> private void SetupTaskFactory(IDictionary <string, string> factoryParameters, bool explicitlyLaunchTaskHost) { _taskFactory = new AssemblyTaskFactory(); #if FEATURE_ASSEMBLY_LOCATION _loadInfo = AssemblyLoadInfo.Create(null, Assembly.GetAssembly(typeof(TaskToTestFactories)).Location); #else _loadInfo = AssemblyLoadInfo.Create(typeof(TaskToTestFactories).GetTypeInfo().Assembly.FullName, null); #endif _loadedType = _taskFactory.InitializeFactory(_loadInfo, "TaskToTestFactories", new Dictionary <string, TaskPropertyInfo>(), string.Empty, factoryParameters, explicitlyLaunchTaskHost, null, ElementLocation.Create("NONE"), String.Empty); Assert.True(_loadedType.Assembly.Equals(_loadInfo)); // "Expected the AssemblyLoadInfo to be equal" }
private void LoadAllTypes() { var newAssemblies = new Dictionary <Assembly, AssemblyLoadInfo>(_loadedAssemblies.Count); foreach (var keyValue in _loadedAssemblies) { AssemblyLoadInfo info = keyValue.Value; var asm = keyValue.Key; newAssemblies[asm] = info.EnsureTypesLoaded(); } _loadedAssemblies = newAssemblies; }
public static ExtensionMethodSet AddNamespace(PythonContext context, ExtensionMethodSet /*!*/ existingSet, NamespaceTracker /*!*/ ns) { Assert.NotNull(existingSet, ns); lock (existingSet) { AssemblyLoadInfo asmInfo; Dictionary <Assembly, AssemblyLoadInfo> newDict = null; foreach (var assembly in ns.PackageAssemblies) { if (existingSet != null && existingSet._loadedAssemblies.TryGetValue(assembly, out asmInfo)) { if (asmInfo.IsFullAssemblyLoaded) { // full assembly is already in this set. continue; } if (asmInfo.Namespaces == null || !asmInfo.Namespaces.Contains(ns.Name)) { if (newDict == null) { newDict = NewInfoOrCopy(existingSet); } if (newDict[assembly].Namespaces == null) { newDict[assembly].Namespaces = new HashSet <string>(); } newDict[assembly].Namespaces.Add(ns.Name); } } else { if (newDict == null) { newDict = NewInfoOrCopy(existingSet); } var newAsmInfo = newDict[assembly] = new AssemblyLoadInfo(assembly); newAsmInfo.Namespaces = new HashSet <string>(); newAsmInfo.Namespaces.Add(ns.Name); } } if (newDict != null) { return(context.UniqifyExtensions(new ExtensionMethodSet(newDict))); } return(existingSet); } }
internal void CreateFromStream(BinaryReader reader) { #region LoggerClassName if (reader.ReadByte() == 0) { _loggerClassName = null; } else { _loggerClassName = reader.ReadString(); } #endregion #region LoggerSwitchParameters if (reader.ReadByte() == 0) { _loggerSwitchParameters = null; } else { _loggerSwitchParameters = reader.ReadString(); } #endregion #region LoggerAssembly if (reader.ReadByte() == 0) { _loggerAssembly = null; } else { string assemblyName = null; string assemblyFile = null; if (reader.ReadByte() != 0) { assemblyFile = reader.ReadString(); } if (reader.ReadByte() != 0) { assemblyName = reader.ReadString(); } _loggerAssembly = AssemblyLoadInfo.Create(assemblyName, assemblyFile); } #endregion _verbosity = (LoggerVerbosity)reader.ReadInt32(); _loggerId = reader.ReadInt32(); }
public void Regress640476PartialName() { string forwardingLoggerLocation = typeof(net.r_eg.IeXod.Logging.ConfigurableForwardingLogger).Assembly.Location; TypeLoader loader = new TypeLoader(IsForwardingLoggerClass); LoadedType loadedType = loader.Load("ConfigurableForwardingLogger", AssemblyLoadInfo.Create(null, forwardingLoggerLocation)); Assert.NotNull(loadedType); Assert.Equal(forwardingLoggerLocation, loadedType.Assembly.AssemblyLocation); string fileLoggerLocation = typeof(net.r_eg.IeXod.Logging.FileLogger).Assembly.Location; loader = new TypeLoader(IsLoggerClass); loadedType = loader.Load("FileLogger", AssemblyLoadInfo.Create(null, fileLoggerLocation)); Assert.NotNull(loadedType); Assert.Equal(fileLoggerLocation, loadedType.Assembly.AssemblyLocation); }
public void Regress640476PartialName() { string forwardingLoggerLocation = typeof(Microsoft.Build.Logging.ConfigurableForwardingLogger).Assembly.Location; TypeLoader loader = new TypeLoader(IsForwardingLoggerClass); LoadedType loadedType = loader.Load("ConfigurableForwardingLogger", AssemblyLoadInfo.Create(null, forwardingLoggerLocation)); Assert.NotNull(loadedType); Assert.True(loadedType.Assembly.AssemblyLocation.Equals(forwardingLoggerLocation, StringComparison.OrdinalIgnoreCase)); string fileLoggerLocation = typeof(Microsoft.Build.Logging.FileLogger).Assembly.Location; loader = new TypeLoader(IsLoggerClass); loadedType = loader.Load("FileLogger", AssemblyLoadInfo.Create(null, fileLoggerLocation)); Assert.NotNull(loadedType); Assert.True(loadedType.Assembly.AssemblyLocation.Equals(fileLoggerLocation, StringComparison.OrdinalIgnoreCase)); }
public void Regress640476FullyQualifiedName() { Type forwardingLoggerType = typeof(Microsoft.Build.Logging.ConfigurableForwardingLogger); string forwardingLoggerLocation = forwardingLoggerType.Assembly.Location; TypeLoader loader = new TypeLoader(IsForwardingLoggerClass); LoadedType loadedType = loader.Load(forwardingLoggerType.FullName, AssemblyLoadInfo.Create(null, forwardingLoggerLocation)); Assert.NotNull(loadedType); Assert.Equal(forwardingLoggerLocation, loadedType.Assembly.AssemblyLocation); Type fileLoggerType = typeof(Microsoft.Build.Logging.FileLogger); string fileLoggerLocation = fileLoggerType.Assembly.Location; loader = new TypeLoader(IsLoggerClass); loadedType = loader.Load(fileLoggerType.FullName, AssemblyLoadInfo.Create(null, fileLoggerLocation)); Assert.NotNull(loadedType); Assert.Equal(fileLoggerLocation, loadedType.Assembly.AssemblyLocation); }
public void RegisterTaskSimple() { UsingTaskInfo[] taskInfos = { new UsingTaskInfo("CustomTask", "CustomTask, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", null) }; TaskRegistry registryStub = TaskRegistryHelperMethods.CreateTaskRegistryAndRegisterTasks(taskInfos); int registeredTaskCount = TaskRegistryHelperMethods.GetDeepCountOfRegisteredTasks(registryStub.AllTaskDeclarations); Assert.AreEqual(1, registeredTaskCount, "Expected only one registered task in TaskRegistry.AllTaskDeclarations!"); ArrayList taskAssemblyLoadInfoList = (ArrayList)registryStub.AllTaskDeclarations[taskInfos[0].TaskName]; Assert.IsNotNull(taskAssemblyLoadInfoList, "Task AssemblyLoadInfo not found in TaskRegistry.AllTaskDeclarations!"); Assert.AreEqual(1, taskAssemblyLoadInfoList.Count, "Expected only one AssemblyLoadInfo registered!"); AssemblyLoadInfo taskAssemblyLoadInfo = (AssemblyLoadInfo)taskAssemblyLoadInfoList[0]; Assert.AreEqual(taskAssemblyLoadInfo, taskInfos[0].AssemblyInfo, "Task AssemblyLoadInfo was not properly registered by TaskRegistry.RegisterTask!"); }
/// <summary> /// Creates a logger description from given data /// </summary> public LoggerDescription ( string loggerClassName, string loggerAssemblyName, string loggerAssemblyFile, string loggerSwitchParameters, LoggerVerbosity verbosity ) { _loggerClassName = loggerClassName; if (loggerAssemblyFile != null && !Path.IsPathRooted(loggerAssemblyFile)) { loggerAssemblyFile = FileUtilities.NormalizePath(loggerAssemblyFile); } _loggerAssembly = AssemblyLoadInfo.Create(loggerAssemblyName, loggerAssemblyFile); _loggerSwitchParameters = loggerSwitchParameters; _verbosity = verbosity; }
public void RegisterMultipleTasksWithDifferentNamesFromSameAssembly() { UsingTaskInfo[] taskInfos = { new UsingTaskInfo("CustomTask", "CustomTasks, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", null), new UsingTaskInfo("YetAnotherCustomTask", null, "bin\\Assemblies\\YetAnotherCustomTask.dll"), new UsingTaskInfo("AnotherCustomTask", "CustomTasks, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", null) }; TaskRegistry registryStub = TaskRegistryHelperMethods.CreateTaskRegistryAndRegisterTasks(taskInfos); int registeredTaskCount = TaskRegistryHelperMethods.GetDeepCountOfRegisteredTasks(registryStub.AllTaskDeclarations); Assert.AreEqual(3, registeredTaskCount, "Expected three registered tasks in TaskRegistry.AllTaskDeclarations!"); foreach (UsingTaskInfo taskInfo in taskInfos) { ArrayList taskAssemblyLoadInfoList = (ArrayList)registryStub.AllTaskDeclarations[taskInfo.TaskName]; Assert.IsNotNull(taskAssemblyLoadInfoList, "Task AssemblyLoadInfo not found in TaskRegistry.AllTaskDeclarations!"); Assert.AreEqual(1, taskAssemblyLoadInfoList.Count, "Expected only one AssemblyLoadInfo registered under this TaskName!"); AssemblyLoadInfo taskAssemblyLoadInfo = (AssemblyLoadInfo)taskAssemblyLoadInfoList[0]; Assert.AreEqual(taskAssemblyLoadInfo, taskInfo.AssemblyInfo, "Task AssemblyLoadInfo was not properly registered by TaskRegistry.RegisterTask!"); } }
private static Dictionary <Assembly, AssemblyLoadInfo> NewInfoOrCopy(ExtensionMethodSet /*!*/ existingSet) { var dict = new Dictionary <Assembly, AssemblyLoadInfo>(); if (existingSet != null) { foreach (var keyValue in existingSet._loadedAssemblies) { var assemblyLoadInfo = new AssemblyLoadInfo(keyValue.Key); if (keyValue.Value.Namespaces != null) { assemblyLoadInfo.Namespaces = new HashSet <string>(keyValue.Value.Namespaces); } if (keyValue.Value.Types != null) { assemblyLoadInfo.Types = new HashSet <PythonType>(keyValue.Value.Types); } dict[keyValue.Key] = assemblyLoadInfo; } } return(dict); }
public void AllUsingTaskAttributesAreExpanded() { UsingTaskInfo[] taskInfos = { new UsingTaskInfo("$(Property1)@(ThirdItem)$(Property2)", null, "Some\\$(Property3)\\Path\\CustomTasks.dll"), new UsingTaskInfo("YetAnotherCustomTask", "$(Property4)@(ThirdItem), Version=9.0.0.0, Culture=neutral, PublicKeyToken=null", null), new UsingTaskInfo("Custom$(Property5)Task", null, "Some\\Relative\\Path\\CustomTasks.dll", "'@(ThirdItem)$(Property1)' == 'ThirdValue1Value1'") }; TaskRegistry registryStub = TaskRegistryHelperMethods.CreateTaskRegistryAndRegisterTasks(taskInfos); int registeredTaskCount = TaskRegistryHelperMethods.GetDeepCountOfRegisteredTasks(registryStub.AllTaskDeclarations); Assert.AreEqual(3, registeredTaskCount, "Expected three registered tasks in TaskRegistry.AllTaskDeclarations!"); foreach (UsingTaskInfo taskInfo in taskInfos) { UsingTaskInfo expandedTaskInfo = taskInfo.CopyAndExpand(TaskRegistryHelperMethods.RegistryExpander); ArrayList taskAssemblyLoadInfoList = (ArrayList)registryStub.AllTaskDeclarations[expandedTaskInfo.TaskName]; Assert.IsNotNull(taskAssemblyLoadInfoList, "Task AssemblyLoadInfo not found in TaskRegistry.AllTaskDeclarations!"); Assert.AreEqual(1, taskAssemblyLoadInfoList.Count, "Expected only one AssemblyLoadInfo registered under this TaskName!"); AssemblyLoadInfo taskAssemblyLoadInfo = (AssemblyLoadInfo)taskAssemblyLoadInfoList[0]; Assert.AreEqual(taskAssemblyLoadInfo, expandedTaskInfo.AssemblyInfo, "Task AssemblyLoadInfo was not properly registered by TaskRegistry.RegisterTask!"); } }
internal void Load(TaskDatabase db) { AssemblyLoadInfo loadInfo = null; if (AssemblyName != null) { loadInfo = new AssemblyLoadInfo(AssemblyName, TaskName); } else if (AssemblyFile != null) { Expression exp = new Expression(); // FIXME: test it exp.Parse(AssemblyFile, ParseOptions.Split); string filename = (string)exp.ConvertTo(project, typeof(string)); if (Path.IsPathRooted(filename) == false) { string ffn; if (importedProject != null) { ffn = Path.GetDirectoryName(importedProject.FullFileName); } else if (project.FullFileName != String.Empty) { ffn = Path.GetDirectoryName(project.FullFileName); } else { ffn = Environment.CurrentDirectory; } filename = Path.Combine(ffn, filename); } loadInfo = new AssemblyLoadInfo(LoadInfoType.AssemblyFilename, filename, null, null, null, null, TaskName); } db.RegisterTask(TaskName, loadInfo); }
public void TearDownAttribute() { _taskFactory = null; _loadInfo = null; _loadedType = null; }
public UsingTaskInfo(string taskName, string assemblyName, string assemblyFile) { TaskName = taskName; AssemblyInfo = new AssemblyLoadInfo(assemblyName, assemblyFile); }
/// <summary> /// Initialize the factory from the task registry /// </summary> internal LoadedType InitializeFactory ( AssemblyLoadInfo loadInfo, string taskName, IDictionary <string, TaskPropertyInfo> taskParameters, string taskElementContents, IDictionary <string, string> taskFactoryIdentityParameters, bool taskHostFactoryExplicitlyRequested, TargetLoggingContext targetLoggingContext, ElementLocation elementLocation, string taskProjectFile ) { ErrorUtilities.VerifyThrowArgumentNull(loadInfo, "loadInfo"); VerifyThrowIdentityParametersValid(taskFactoryIdentityParameters, elementLocation, taskName, "Runtime", "Architecture"); if (taskFactoryIdentityParameters != null) { _factoryIdentityParameters = new Dictionary <string, string>(taskFactoryIdentityParameters, StringComparer.OrdinalIgnoreCase); } _taskHostFactoryExplicitlyRequested = taskHostFactoryExplicitlyRequested; try { ErrorUtilities.VerifyThrowArgumentLength(taskName, "taskName"); _taskName = taskName; _loadedType = _typeLoader.Load(taskName, loadInfo); ProjectErrorUtilities.VerifyThrowInvalidProject(_loadedType != null, elementLocation, "TaskLoadFailure", taskName, loadInfo.AssemblyLocation, String.Empty); } catch (TargetInvocationException e) { // Exception thrown by the called code itself // Log the stack, so the task vendor can fix their code ProjectErrorUtilities.VerifyThrowInvalidProject(false, elementLocation, "TaskLoadFailure", taskName, loadInfo.AssemblyLocation, Environment.NewLine + e.InnerException.ToString()); } catch (ReflectionTypeLoadException e) { // ReflectionTypeLoadException.LoaderExceptions may contain nulls foreach (Exception exception in e.LoaderExceptions) { if (exception != null) { targetLoggingContext.LogError(new BuildEventFileInfo(taskProjectFile), "TaskLoadFailure", taskName, loadInfo.AssemblyLocation, exception.Message); } } ProjectErrorUtilities.VerifyThrowInvalidProject(false, elementLocation, "TaskLoadFailure", taskName, loadInfo.AssemblyLocation, e.Message); } catch (ArgumentNullException e) { // taskName may be null ProjectErrorUtilities.VerifyThrowInvalidProject(false, elementLocation, "TaskLoadFailure", taskName, loadInfo.AssemblyLocation, e.Message); } catch (Exception e) // Catching Exception, but rethrowing unless it's a well-known exception. { if (ExceptionHandling.NotExpectedReflectionException(e)) { throw; } ProjectErrorUtilities.VerifyThrowInvalidProject(false, elementLocation, "TaskLoadFailure", taskName, loadInfo.AssemblyLocation, e.Message); } return(_loadedType); }
private static int RunTarget() { StaticTarget target; var ser = new DataContractJsonSerializer(typeof(StaticTarget)); using (var memoryStream = new MemoryStream()) { using (var writer = new StreamWriter(memoryStream, Encoding.Default, 1024 * 4, true)) { string s; while ((s = Console.ReadLine()) != null) { writer.WriteLine(s); } } memoryStream.Position = 0; target = (StaticTarget)ser.ReadObject(memoryStream); } foreach (StaticTarget.Task staticTask in target.Tasks) { Type type; if (staticTask.AssemblyFile != null) { AssemblyName an = AssemblyName.GetAssemblyName(staticTask.AssemblyFile); if (an == null) { Console.WriteLine("Caouldn't get assembly name for assembly file: " + staticTask.AssemblyFile); return(1); } Assembly a = Assembly.Load(an); if (a == null) { Console.WriteLine("Couldn't loaded assembly for assembly: " + an.FullName + " from file: " + staticTask.AssemblyFile); return(1); } type = a.GetType(staticTask.Name.Split(',')[0]); if (type == null) { Console.WriteLine("Couldn't create type for string: " + staticTask.Name.Split(',')[0] + " assembly file: " + (staticTask.AssemblyFile ?? "null") + " and assembly name: " + (staticTask.AssemblyName ?? "null")); Console.WriteLine("Types in the assembly:\n" + string.Join(",\n", a.GetTypes().Select(availableType => availableType.FullName))); return(1); } } else { type = Type.GetType(staticTask.Name); if (type == null) { Console.WriteLine("Couldn't create type for string: " + staticTask.Name + " assembly file: " + (staticTask.AssemblyFile ?? "null") + " and assembly name: " + (staticTask.AssemblyName ?? "null")); return(1); } } var assemblyLoadInfo = AssemblyLoadInfo.Create(assemblyFile: staticTask.AssemblyFile, assemblyName: staticTask.AssemblyName); if (assemblyLoadInfo == null) { Console.WriteLine("Couldn't create type for assembly file: " + (staticTask.AssemblyFile ?? "null") + " and name: " + (staticTask.AssemblyName ?? "null")); return(1); } LoadedType loadedType = new LoadedType(type, assemblyLoadInfo, null); TaskPropertyInfo[] taskProperties = AssemblyTaskFactory.GetTaskParameters(loadedType); ITask task = TaskLoader.CreateTask(loadedType, staticTask.Name, staticTask.AssemblyName, 0, 0, null #if FEATURE_APPDOMAIN , null #endif , false #if FEATURE_APPDOMAIN , out var appDomain #endif ); foreach (var parameter in staticTask.Parameters) { var taskPropertyInfo = taskProperties.FirstOrDefault(property => property.Name == parameter.Key); if (taskPropertyInfo == null) { Console.Error.WriteLine("Could not find property: \"" + parameter.Key + "\" for task + \"" + staticTask.Name + "\""); return(1); } StaticTarget.Task.ParameterType parameterType = parameter.Value.ParameterType; switch (parameterType) { case StaticTarget.Task.ParameterType.Primitive: object value = GetTypedValue(parameter.Value.Primitive.Type, parameter.Value.Primitive.Value); TaskFactoryWrapper.SetPropertyValue(task, taskPropertyInfo, value); break; case StaticTarget.Task.ParameterType.Primitives: var values = GetTypedArrayValue(parameter.Value.Primitives.Type, parameter.Value.Primitives.Values); TaskFactoryWrapper.SetPropertyValue(task, taskPropertyInfo, values); break; case StaticTarget.Task.ParameterType.TaskItem: TaskFactoryWrapper.SetPropertyValue(task, taskPropertyInfo, new TaskItem(parameter.Value.TaskItem.ItemSpec, parameter.Value.TaskItem.Metadata)); break; case StaticTarget.Task.ParameterType.TaskItems: ITaskItem[] taskItems = parameter.Value.TaskItems.Select(taskItem => new TaskItem(taskItem.ItemSpec, taskItem.Metadata)).ToArray(); TaskFactoryWrapper.SetPropertyValue(task, taskPropertyInfo, taskItems); break; } } task.BuildEngine = new SimpleBuildEngine(); try { // MSBuild ignores this return value :( task.Execute(); } catch (Exception e) { Console.Error.WriteLine("TASK ERROR: " + e); return(1); } } return(0); }
/// <summary> /// This is responsible for invoking Execute on the Task /// Any method calling ExecuteTask must remember to call CleanupTask /// </summary> /// <remarks> /// We also allow the Task to have a reference to the BuildEngine by design /// at ITask.BuildEngine /// </remarks> /// <param name="oopTaskHostNode">The OutOfProcTaskHostNode as the BuildEngine</param> /// <param name="taskName">The name of the task to be executed</param> /// <param name="taskLocation">The path of the task binary</param> /// <param name="taskFile">The path to the project file in which the task invocation is located.</param> /// <param name="taskLine">The line in the project file where the task invocation is located.</param> /// <param name="taskColumn">The column in the project file where the task invocation is located.</param> /// <param name="appDomainSetup">The AppDomainSetup that we want to use to launch our AppDomainIsolated tasks</param> /// <param name="taskParams">Parameters that will be passed to the task when created</param> /// <returns>Task completion result showing success, failure or if there was a crash</returns> internal OutOfProcTaskHostTaskResult ExecuteTask ( IBuildEngine oopTaskHostNode, string taskName, string taskLocation, string taskFile, int taskLine, int taskColumn, #if FEATURE_APPDOMAIN AppDomainSetup appDomainSetup, #endif IDictionary <string, TaskParameter> taskParams ) { buildEngine = oopTaskHostNode; this.taskName = taskName; #if FEATURE_APPDOMAIN _taskAppDomain = null; #endif wrappedTask = null; LoadedType taskType = null; try { TypeLoader typeLoader = new TypeLoader(TaskLoader.IsTaskClass); taskType = typeLoader.Load(taskName, AssemblyLoadInfo.Create(null, taskLocation)); } catch (Exception e) { if (ExceptionHandling.IsCriticalException(e)) { throw; } Exception exceptionToReturn = e; // If it's a TargetInvocationException, we only care about the contents of the inner exception, // so just save that instead. if (e is TargetInvocationException) { exceptionToReturn = e.InnerException; } return(new OutOfProcTaskHostTaskResult ( TaskCompleteType.CrashedDuringInitialization, exceptionToReturn, "TaskInstantiationFailureError", new string[] { taskName, taskLocation, String.Empty } )); } OutOfProcTaskHostTaskResult taskResult; if (taskType.HasSTAThreadAttribute()) { #if FEATURE_APARTMENT_STATE taskResult = InstantiateAndExecuteTaskInSTAThread(oopTaskHostNode, taskType, taskName, taskLocation, taskFile, taskLine, taskColumn, #if FEATURE_APPDOMAIN appDomainSetup, #endif taskParams); #else return(new OutOfProcTaskHostTaskResult ( TaskCompleteType.CrashedDuringInitialization, null, "TaskInstantiationFailureNotSupported", new string[] { taskName, taskLocation, typeof(RunInSTAAttribute).FullName } )); #endif } else { taskResult = InstantiateAndExecuteTask(oopTaskHostNode, taskType, taskName, taskLocation, taskFile, taskLine, taskColumn, #if FEATURE_APPDOMAIN appDomainSetup, #endif taskParams); } return(taskResult); }
/// <summary> /// Reads the given <UsingTask> tag and saves the task information specified in it. /// </summary> /// <param name="usingTask"></param> /// <param name="expander"></param> /// <param name="loggingServices"></param> /// <param name="buildEventContext"></param> public void RegisterTask(UsingTask usingTask, Expander expander, EngineLoggingServices loggingServices, BuildEventContext buildEventContext) { if ( // if the <UsingTask> tag doesn't have a condition on it (usingTask.Condition == null) || // or if the condition holds Utilities.EvaluateCondition(usingTask.Condition, usingTask.ConditionAttribute, expander, null, ParserOptions.AllowProperties | ParserOptions.AllowItemLists, loggingServices, buildEventContext) ) { // Lazily allocate the hashtables if they are needed if (registeredTasks == null) { cachedTaskClassesWithExactMatch = new Hashtable(StringComparer.OrdinalIgnoreCase); cachedTaskClassesWithFuzzyMatch = new Hashtable(StringComparer.OrdinalIgnoreCase); registeredTasks = new Hashtable(StringComparer.OrdinalIgnoreCase); } string assemblyName = null; string assemblyFile = null; if (usingTask.AssemblyName != null) { // expand out all embedded properties and items in the assembly name assemblyName = expander.ExpandAllIntoString(usingTask.AssemblyName, usingTask.AssemblyNameAttribute); ProjectErrorUtilities.VerifyThrowInvalidProject(assemblyName.Length > 0, usingTask.AssemblyNameAttribute, "InvalidEvaluatedAttributeValue", assemblyName, usingTask.AssemblyName, XMakeAttributes.assemblyName, XMakeElements.usingTask); } else { // expand out all embedded properties and items in the assembly file/path assemblyFile = expander.ExpandAllIntoString(usingTask.AssemblyFile, usingTask.AssemblyFileAttribute); ProjectErrorUtilities.VerifyThrowInvalidProject(assemblyFile.Length > 0, usingTask.AssemblyFileAttribute, "InvalidEvaluatedAttributeValue", assemblyFile, usingTask.AssemblyFile, XMakeAttributes.assemblyFile, XMakeElements.usingTask); // figure out the directory of the project in which this <UsingTask> node was defined string projectFile = XmlUtilities.GetXmlNodeFile(usingTask.TaskNameAttribute.OwnerElement, String.Empty); string projectDir = (projectFile.Length > 0) ? Path.GetDirectoryName(projectFile) : String.Empty; // ensure the assembly file/path is relative to the project in which this <UsingTask> node was defined -- we // don't want paths from imported projects being interpreted relative to the main project file try { assemblyFile = Path.Combine(projectDir, assemblyFile); } catch (ArgumentException ex) { // Invalid chars in AssemblyFile path ProjectErrorUtilities.VerifyThrowInvalidProject(false, usingTask.AssemblyFileAttribute, "InvalidAttributeValueWithException", assemblyFile, XMakeAttributes.assemblyFile, XMakeElements.usingTask, ex.Message); } } AssemblyLoadInfo taskAssembly = new AssemblyLoadInfo(assemblyName, assemblyFile); // expand out all embedded properties and items string taskName = expander.ExpandAllIntoString(usingTask.TaskName, usingTask.TaskNameAttribute); ProjectErrorUtilities.VerifyThrowInvalidProject(taskName.Length > 0, usingTask.TaskNameAttribute, "InvalidEvaluatedAttributeValue", taskName, usingTask.TaskName, XMakeAttributes.taskName, XMakeElements.usingTask); // since more than one task can have the same name, we want to keep track of all assemblies that are declared to // contain tasks with a given name... ArrayList taskAssemblies = (ArrayList)registeredTasks[taskName]; if (taskAssemblies == null) { taskAssemblies = new ArrayList(); registeredTasks[taskName] = taskAssemblies; } taskAssemblies.Add(taskAssembly); } }