/// <summary> /// Adds additionaly type information. /// </summary> /// <param name="typeMapping">The new type mapping.</param> public void AddTypeInfo(TypeMapping typeMapping) { if (typeIds.ContainsKey(typeMapping.Id)) { return; } try { Type type = TypeLoader.Load(typeMapping.TypeName); typeIds.Add(typeMapping.Id, type); Type serializerType = TypeLoader.Load(typeMapping.Serializer); object serializer; if (serializerInstances.ContainsKey(serializerType)) { serializer = serializerInstances[serializerType]; } else { serializer = Activator.CreateInstance(serializerType, true); serializerInstances.Add(serializerType, serializer); } serializerMapping.Add(type, serializer); } catch (PersistenceException) { throw; } catch (Exception e) { throw new PersistenceException(string.Format( "Could not add type info for {0} ({1})", typeMapping.TypeName, typeMapping.Serializer), e); } }
internal static Type?NewResourceHandlerTypeFor(string?resourceHandlerTypeName) { try { Type?resourceHandlerClass = TypeLoader.Load(resourceHandlerTypeName); if (resourceHandlerClass == null) { if (TryLoadAlreadyGeneratedAssembly(resourceHandlerTypeName, out var assembly)) { try { resourceHandlerClass = assembly?.GetType(resourceHandlerTypeName !, true); } catch (Exception) { resourceHandlerClass = Assembly.GetCallingAssembly().GetType(resourceHandlerTypeName !, true); } } else { resourceHandlerClass = Assembly.GetCallingAssembly().GetType(resourceHandlerTypeName !, true); } } ConfirmResourceHandler(resourceHandlerClass); return(resourceHandlerClass); } catch (Exception e) { throw new ArgumentException($"The resource handler class {resourceHandlerTypeName} cannot be loaded because: {e.Message}"); } }
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.True(loadedType.Assembly.AssemblyLocation.Equals(forwardingLoggerAssemblyLocation, StringComparison.OrdinalIgnoreCase)); Assert.True(loadedType.Type.Equals(firstPublicType)); 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.True(loadedType.Assembly.AssemblyLocation.Equals(fileLoggerAssemblyLocation, StringComparison.OrdinalIgnoreCase)); Assert.True(loadedType.Type.Equals(firstPublicType)); }
public void NoTypeNamePicksFirstType() { Type forwardingLoggerType = typeof(net.r_eg.IeXod.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(net.r_eg.IeXod.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); }
private static Type ActorClassWithProtocol(string?actorClassname, Type protocolClass) { try { var actorClass = TypeLoader.Load(actorClassname); AssertActorWithProtocol(actorClass, protocolClass); return(actorClass); } catch (Exception e) { throw new ArgumentException($"The class {actorClassname} cannot be loaded because: {e.Message}", e); } }
public void TypeLoader_ShouldLoadModule_WhenValidTypeNameIsProvided() { // Given var types = new string[] { "Test.Extensible.Module.TestModule, Test.Extensible.Module" }; var loader = new TypeLoader <TestAppEvents>(types); // When var modules = loader.Load(new TestAppEvents()); // Then Assert.Single(modules); }
public void TypeLoader_ShouldNotBindEvents_WhenNoValidTypeNamesAreProvided() { // Given var types = new string[] { }; var loader = new TypeLoader <TestAppEvents>(types); var events = new TestAppEvents(); // When var modules = loader.Load(events); //Then Assert.Null(events.MyEvent); }
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 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 TypeLoader_ShouldBindEvents_WhenValidTypeNameIsProvided() { // Given var types = new string[] { "Test.Extensible.Module.TestModule, Test.Extensible.Module" }; var loader = new TypeLoader <TestAppEvents>(types); var events = new TestAppEvents(); // When var modules = loader.Load(events); //Then Assert.NotNull(events.MyEvent); }
public void TypeLoader_ShouldLoadModules_WhenMultipleTypeNamesProvided() { // Given var types = new string[] { "Test.Extensible.Module.TestModule, Test.Extensible.Module", "Test.Extensible.ModuleLoaders.TestTypeModule, Test.Extensible" }; var loader = new TypeLoader <TestAppEvents>(types); // When var modules = loader.Load(new TestAppEvents()); // Then Assert.Equal(2, modules.Count()); }
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); }
private void WriteDataContext(CodeWriter writer, Database schema, GenerationContext context) { if (schema.Tables.Count == 0) { writer.WriteCommentLine("L69 no tables found"); return; } string contextBase = schema.BaseType; var contextBaseType = TypeLoader.Load(contextBase); // if we don't specify a base type, use the default if (string.IsNullOrEmpty(contextBase)) { contextBaseType = typeof(DataContext); } // in all cases, get the literal type name from loaded type contextBase = writer.GetLiteralType(contextBaseType); var specifications = SpecificationDefinition.Partial; if (schema.AccessModifierSpecified) { specifications |= GetSpecificationDefinition(schema.AccessModifier); } else { specifications |= SpecificationDefinition.Public; } if (schema.ModifierSpecified) { specifications |= GetSpecificationDefinition(schema.Modifier); } using (writer.WriteClass(specifications, schema.Class, contextBase)) { WriteDataContextExtensibilityDeclarations(writer, schema, context); WriteDataContextCtors(writer, schema, contextBaseType, context); WriteDataContextTables(writer, schema, context); WriteDataContextProcedures(writer, schema, context); } }
public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) { IEnumerator<Tag> it = metaInfo.GetEnumerator(); try { it.MoveNext(); } catch (InvalidOperationException e) { throw new PersistenceException("Insufficient meta information to instantiate Type object", e); } try { return TypeLoader.Load((string)it.Current.Value); } catch (InvalidCastException e) { throw new PersistenceException("Invalid meta information during reconstruction of Type object", e); } catch (TypeLoadException e) { throw new PersistenceException(String.Format( "Cannot load Type {0}, make sure all required assemblies are available.", (string)it.Current.Value), e); } }
private Tuple <string, IList <MethodParameter> > Parse(string?to) { var bad = $"Invalid to declaration: {to}"; var openParen = to?.IndexOf("("); var closeParen = to?.LastIndexOf(")"); if (!openParen.HasValue || openParen < 0 || !closeParen.HasValue || closeParen < 0) { throw new InvalidOperationException(bad); } var methodName = to?.Substring(0, openParen.Value); var rawParameters = to?.Substring(openParen.Value + 1, closeParen.Value - (openParen.Value + 1)).Split(','); var parameters = new List <MethodParameter>(rawParameters !.Length); foreach (var p in rawParameters) { var rawParameter = p.Trim(); if (!string.IsNullOrEmpty(rawParameter)) { if (rawParameter.StartsWith("body:")) { var body = TypeAndName(rawParameter.Substring(5)); parameters.Add(new MethodParameter(body[0], body[1], TypeLoader.Load(QualifiedType(body[0])))); } else { var other = TypeAndName(rawParameter); parameters.Add(new MethodParameter(other[0], other[1])); } } } return(new Tuple <string, IList <MethodParameter> >(methodName !, parameters)); }
/// <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> /// 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); }