public static Plugin[] InstantiatePlugins(Type[] types) { if (_logger.IsDebugEnabled) { _logger.Debug("Instantiating plugins: {0}", String.Join(",", types.Select(a => a.FullName))); } return types.Select(Activator.CreateInstance).Cast<Plugin>().ToArray(); }
public static LongLookup<MessageMetadata> BuildMetadata(IStructSizeCounter counter, Func<Type, int> messageIdGetter, Type[] structTypes) { var keys = structTypes.Select(GetKey).ToArray(); var values = structTypes.Select(type => new MessageMetadata(messageIdGetter(type), (short) counter.GetSize(type), (short) (int) Marshal.OffsetOf(type, Envelope.FieldName))).ToArray(); var metadata = new LongLookup<MessageMetadata>(keys, values); return metadata; }
/// <summary> /// Constructs the exception with a reference to the message that could be handled by multiple saga handlers /// </summary> public MultipleSagaHandlersFoundException(object messageThatCouldBeHandledByMultipleSagaHandlers, Type[] sagaHandlerTypes) : base(string.Format("The message type {0} could be handled by multiple saga handlers: {1}. This is an error because it would require that multiple saga instances could be updated atomically, which is not possible with all saga persisters", messageThatCouldBeHandledByMultipleSagaHandlers.GetType(), string.Join(", ", sagaHandlerTypes.Select(t => t.ToString())))) { this.messageThatCouldBeHandledByMultipleSagaHandlers = messageThatCouldBeHandledByMultipleSagaHandlers; this.sagaHandlerTypes = sagaHandlerTypes; }
internal static AssemblyLoaderReflectionCriterion LoadTypesAssignableFrom(Type[] requiredTypes) { // any types provided must be converted to reflection-only // types, or they aren't comparable with other reflection-only // types. requiredTypes = requiredTypes.Select(TypeUtils.ToReflectionOnlyType).ToArray(); string[] complaints = new string[requiredTypes.Length]; for (var i = 0; i < requiredTypes.Length; ++i) { complaints[i] = String.Format("Assembly contains no types assignable from {0}.", requiredTypes[i].FullName); } return AssemblyLoaderReflectionCriterion.NewCriterion( (Type type, out IEnumerable<string> ignored) => { ignored = null; foreach (var requiredType in requiredTypes) { if (requiredType.IsAssignableFrom(type)) { // we found a match! load the assembly. return true; } } return false; }, complaints); }
/// <summary> /// Gets the filter for the classifiers based on the runtime types. /// </summary> /// <param name="runtimeTypes">The runtime types.</param> /// <returns>A predicate to filter the classifiers based on the provided runtime types.</returns> private static Func<IClassifier, bool> GetRuntimeTypesFilter(Type[] runtimeTypes) { var runtimeTypeInfos = runtimeTypes.Select(t => t.AsRuntimeTypeInfo()).ToList(); return c => c.Parts.OfType<IRuntimeTypeInfo>() .Any(info => runtimeTypeInfos.Contains(info)); }
/// <summary> /// Gets the filter for the classifiers based on the runtime types. /// </summary> /// <param name="runtimeTypes">The runtime types.</param> /// <returns>A predicate to filter the classifiers based on the provided runtime types.</returns> private static Func<IClassifier, bool> GetRuntimeTypesFilter(Type[] runtimeTypes) { var runtimeTypeInfos = runtimeTypes.Select(t => t.GetTypeInfo()).ToList(); return c => c.UnderlyingElementInfos.OfType<IRuntimeNamedElementInfo>() .Any(info => runtimeTypeInfos.Contains(info.RuntimeElement)); }
public MultipleResourceTypesException(string requestedTypeName, Type[] types) : base(string.Format("There are mutiple types that can be created for requested type '{0}': '{1}'", requestedTypeName, string.Join(",", types.Select(x => x.FullName).ToArray()))) { RequestedTypeName = requestedTypeName; Types = types; }
// TODO: replace binding flags by bool flags protected MethodBaseInfo(string name, Type declaringType, BindingFlags bindingFlags, Type[] genericArguments, Type[] parameterTypes, Dictionary<Type, TypeInfo> referenceTracker) : this(name, TypeInfo.Create(referenceTracker, declaringType, includePropertyInfos: false, setMemberDeclaringTypes: false), bindingFlags, ReferenceEquals(null, genericArguments) ? null : genericArguments.Select(x => TypeInfo.Create(referenceTracker, x, false, false)), ReferenceEquals(null, parameterTypes) ? null : parameterTypes.Select(x => TypeInfo.Create(referenceTracker, x, false, false))) { }
public FilterRegisterItem(Type controllerType, ReflectedActionDescriptor actionDescriptor, Type[] filterTypes) { ControllerType = controllerType; ActionDescriptor = actionDescriptor; _actionParameterDescriptors = ActionDescriptor.GetParameters(); FilterTypes = filterTypes; Filters = () => FilterTypes.Select(f => Activator.CreateInstance(f) as FilterAttribute); }
private void LoadTypes(Type[] types) { _types = types; chklstMatchingTypes.Items.Clear(); foreach (var type in types.Select(i => new DbeType(i))) { chklstMatchingTypes.Items.Add(type, true); } }
private string GetWrappingNameWithType(Type[] types) { if (!_baseType.IsGenericType) return ClassNamePlaceHolder + _baseType.Name; var genericParamString = GetGenericParamString(types.Select(GetParameterName)); var typeNameWithoutGenericParams = _baseType.Name.Split('`')[0]; return string.Format("{0}{1}<{2}>", ClassNamePlaceHolder, typeNameWithoutGenericParams, genericParamString); }
public static CSharpCompilation Generate(Options options, Type[] types, ITestOutputHelper output = null) { // generate code from types var generator = new EntryCodeGenerator(options); generator.GenerateCode(types); var code = generator.CodeWriter.ToString(); if (output != null) { var typeInfo = string.Join(", ", types.Select(t => t.Name)); output.WriteLine($"***** Generated Code({typeInfo}) *****"); output.WriteLine(code); output.WriteLine(""); } // compile generated code output?.WriteLine($"***** Compile Code *****"); var parseOption = new CSharpParseOptions(LanguageVersion.CSharp6, DocumentationMode.Parse, SourceCodeKind.Regular); var syntaxTrees = new[] { CSharpSyntaxTree.ParseText(code, parseOption, "Generated.cs") }; var references = new[] { typeof(object), typeof(IInterfacedActor), typeof(InterfacedActor), typeof(IActorRef), typeof(IGreeter) } .Select(t => MetadataReference.CreateFromFile(t.Assembly.Location)); var compilation = CSharpCompilation.Create( "Generated.dll", syntaxTrees: syntaxTrees, references: references, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); using (var ms = new MemoryStream()) { var result = compilation.Emit(ms); if (!result.Success) { var failures = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error); foreach (var diagnostic in failures) { var line = diagnostic.Location.GetLineSpan(); output?.WriteLine("{0}({1}): {2} {3}", line.Path, line.StartLinePosition.Line + 1, diagnostic.Id, diagnostic.GetMessage()); } } Assert.True(result.Success, "Build error!"); } return compilation; }
internal static bool TryReflectMethod(out MethodInfo methodInfo, out UnityReflectionException exception, UnityObject reflectionTarget, string name, Type[] parameterTypes) { #if !NETFX_CORE methodInfo = null; Type type = reflectionTarget.GetType(); BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy; if (parameterTypes != null) // Explicit matching { methodInfo = type.GetMethod(name, flags, null, parameterTypes, null); if (methodInfo == null) { methodInfo = type.GetExtensionMethods() .Where(extension => extension.Name == name) .Where(extension => Enumerable.SequenceEqual(extension.GetParameters().Select(paramInfo => paramInfo.ParameterType), parameterTypes)) .FirstOrDefault(); } if (methodInfo == null) { exception = new UnityReflectionException(string.Format("No matching method found: '{0}.{1} ({2})'", type.Name, name, string.Join(", ", parameterTypes.Select(t => t.Name).ToArray()))); return false; } } else // Implicit matching { var normalMethods = type.GetMember(name, MemberTypes.Method, flags).OfType<MethodInfo>().ToList(); var extensionMethods = type.GetExtensionMethods().Where(extension => extension.Name == name).ToList(); var methods = new List<MethodInfo>(); methods.AddRange(normalMethods); methods.AddRange(extensionMethods); if (methods.Count == 0) { exception = new UnityReflectionException(string.Format("No matching method found: '{0}.{1}'", type.Name, name)); return false; } if (methods.Count > 1) { exception = new UnityReflectionException(string.Format("Multiple method signatures found for '{0}.{1}'\nSpecify the parameter types explicitly.", type.FullName, name)); return false; } methodInfo = methods[0]; } exception = null; return true; #else throw new Exception("Reflection is not supported in .NET Core."); #endif }
public object InvokeGeneric(object instance, string name, Type[] types, params object[] arguments) { Type instanceType = instance.GetType(); string key = instanceType.FullName + ":" + name + ":" + string.Join(":", types.Select(t=>t.FullName)); Func<object, object[], object> result = CachedMethods.GetOrAdd(key, a => { return CreateMethod(instanceType, name, types); }); return result(instance, arguments); }
public void CreatesCorrectFixtures(Type testClass, Type[] fixtureTypes, InterfaceFixtureSetFactory sut) { var result = sut.CreateFixturesFor(Reflector.Wrap(testClass)); Assert.IsType<FixtureSet>(result); var fixtureSet = (FixtureSet) result; Assert.That(fixtureSet.Fixtures, Matches.AllOf(fixtureTypes .Select(type => { var ifc = testClass.GetInterfaces().First(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IUseFixture<>) && x.GetGenericArguments()[0] == type); return Has.Entry(Is.EqualTo(ifc.GetMethod("SetFixture", new[] {type})), Is.InstanceOf(type)); }))); }
private static string GetMetricName(Type declaringType, string methodName, bool isGenericMethod, Type[] genericArguments) { if (isGenericMethod) { return string.Format( "{0}.{1}<{2}>", declaringType.Name, methodName, string.Join(", ", genericArguments.Select(t => t.Name).ToArray())); } return string.Format("{0}.{1}", declaringType.Name, methodName); }
public ILDynamicTypeDebugImpl(string name, Type baseType, Type[] interfaces) { _name = name; var uniqueName = UniqueName(name); _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(uniqueName), AssemblyBuilderAccess.RunAndSave, "dynamicIL"); _moduleBuilder = _assemblyBuilder.DefineDynamicModule(uniqueName + ".dll", true); var sourceCodeFileName = Path.GetFullPath("dynamicIL/" + uniqueName + ".il"); _symbolDocumentWriter = _moduleBuilder.DefineDocument(sourceCodeFileName, SymDocumentType.Text, SymLanguageType.ILAssembly, SymLanguageVendor.Microsoft); _sourceCodeWriter = new SourceCodeWriter(sourceCodeFileName, _symbolDocumentWriter); _sourceCodeWriter.WriteLine(string.Format("class {0} : {1}{2}", name, baseType.ToSimpleName(), string.Concat(interfaces.Select(i => ", " + i.ToSimpleName())))); _sourceCodeWriter.OpenScope(); _typeBuilder = _moduleBuilder.DefineType(name, TypeAttributes.Public, baseType, interfaces); _forbidenInstructions = new ILGenForbidenInstructionsCheating(_typeBuilder); }
public ILDynamicTypeDebugImpl(string name, Type baseType, Type[] interfaces) { _name = name; var uniqueName = UniqueName(name, 259 - (DynamicILDirectoryPath.DynamicIL.Length + 1 + 4)); _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(uniqueName), AssemblyBuilderAccess.RunAndSave, DynamicILDirectoryPath.DynamicIL); _moduleBuilder = _assemblyBuilder.DefineDynamicModule(uniqueName + ".dll", true); var sourceCodeFileName = Path.Combine(DynamicILDirectoryPath.DynamicIL, uniqueName + ".il"); _symbolDocumentWriter = _moduleBuilder.DefineDocument(sourceCodeFileName, SymDocumentType.Text, SymLanguageType.ILAssembly, SymLanguageVendor.Microsoft); _sourceCodeWriter = new SourceCodeWriter(sourceCodeFileName, _symbolDocumentWriter); _sourceCodeWriter.WriteLine( $"class {name} : {baseType.ToSimpleName()}{string.Concat(interfaces.Select(i => ", " + i.ToSimpleName()))}"); _sourceCodeWriter.OpenScope(); _typeBuilder = _moduleBuilder.DefineType(name, TypeAttributes.Public, baseType, interfaces); _forbidenInstructions = new ILGenForbidenInstructionsCheating(_typeBuilder); }
public static IDictionary<string, TypeReferencePair> Resolve(MethodDefinition methodDefinition, Type[] types) { var methodParameters = methodDefinition.GenericParameters; var assemblyResolver = methodDefinition.Module.AssemblyResolver; return types.Select((type, i) => { var parameter = methodParameters[i]; var moudle = type.Assembly.GetName().FullName; var assembly = assemblyResolver.Resolve(moudle); return new { Key = parameter.FullName, Type = type, TypeRefence = assembly.MainModule.Import(type) }; }) .ToDictionary(kv => kv.Key, kv => new TypeReferencePair(kv.Type, kv.TypeRefence)); }
private static string GetString(IMethodInfo method, Argument[] arguments, Type[] typeArguments) { var csharp = string.Concat(method.TypeName, ".", method.Name); if (typeArguments.Length > 0) { csharp = string.Format( CultureInfo.InvariantCulture, "{0}<{1}>", csharp, string.Join(", ", typeArguments.Select(typeArgument => GetString(typeArgument)).ToArray())); } var format = "{0}"; var parameterTokens = new List<string>(); if (Command.ShowExampleValues) { format += "({1})"; var parameters = method.MethodInfo.GetParameters(); int parameterIndex; for (parameterIndex = 0; parameterIndex < arguments.Length; parameterIndex++) { if (arguments[parameterIndex].IsGeneratedDefault) { continue; } parameterTokens.Add(string.Concat( parameterIndex >= parameters.Length ? "???" : parameters[parameterIndex].Name, ": ", GetString(arguments[parameterIndex]))); } for (; parameterIndex < parameters.Length; parameterIndex++) { parameterTokens.Add(parameters[parameterIndex].Name + ": ???"); } } return string.Format(CultureInfo.InvariantCulture, format, csharp, string.Join(", ", parameterTokens.ToArray())); }
/// <summary> /// Creates an instance of the specified through either public or non-public constructor. /// </summary> /// <param name="type">The type to create an instance for.</param> /// <param name="argTypes">Argument types of the constructor to use.</param> /// <param name="args">Arguments to pass to the method.</param> /// <returns>The newly created instance.</returns> public static object CreateInstance(Type type, Type[] argTypes, params object[] args) { ExceptionUtilities.CheckArgumentNotNull(type, "type"); try { ConstructorInfo ctor = type.GetConstructor( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder, argTypes, null); ExceptionUtilities.CheckObjectNotNull( ctor, "Failed to create instance of type {0}. Constructor with types {1} not found.", type.ToString(), string.Join(", ", argTypes.Select(a => a.ToString()))); return ctor.Invoke(args); } catch (TargetInvocationException tie) { throw tie.InnerException; } }
private TestEdFiControllerTypeCache GetControllerTypeCache(Type[] markerInterfaces) { var assemblies = markerInterfaces.Select(t => t.Assembly).ToArray(); var controllerTypeCache = new TestEdFiControllerTypeCache(assemblies); return controllerTypeCache; }
public static MethodDefinition ResolveMethod(TypeDefinition typeDefinition, string methodName, Type[] parameterTypes) { if (parameterTypes == null) { _log.Warn("\"ResolveMethod\" overload with parameter types called unnecessarily."); return ResolveMethod(typeDefinition, methodName); } try { MethodDefinition methodDefinition = typeDefinition.Methods.Single( m => m.Name == methodName && m.Parameters.Select(p => p.ParameterType.Name.Replace("TypeDefinition", "Type")) .SequenceEqual(parameterTypes.Select(p => p.Name.Replace("TypeDefinition", "Type")))); _log.Debug("Method \"{0}\" successfully resolved in \"{1}\".", methodName, typeDefinition.FullName); return methodDefinition; } catch (InvalidOperationException) { _log.Error("Method \"{0}\" with specified parameter types is unrecognised.", methodName); throw new ArgumentException(string.Format("Method \"{0}\" with specified parameter types is unrecognised.", methodName), "methodName"); } }
private static string FormatMessage(Type type, string message, Type[] argumentTypes) { return string.Format("An object of type {0} could not be created. {1}{2}", type.Name, message, string.Join(", ", argumentTypes.Select(x => x.Name).ToArray())); }
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { return targetTypes.Select(t => DependencyProperty.UnsetValue).ToArray(); }
/// <summary> /// Construct an "invoke" message. /// </summary> /// <param name="objectID"> /// The object id. /// </param> /// <param name="method"> /// The method. /// </param> /// <param name="typeArguments"> /// The type arguments. /// </param> /// <param name="arguments"> /// The arguments. /// </param> /// <returns> /// The <see cref="Message"/>. /// </returns> public Message ConstructInvokeMessage(ID objectID, string method, Type[] typeArguments, object[] arguments) { return new Message { ID = ID.NewRandom(), Type = MessageType.Invoke, InvokeObjectID = objectID, InvokeMethod = method, InvokeTypeArguments = typeArguments.Select(x => x.AssemblyQualifiedName).ToArray(), InvokeArguments = arguments.Select(x => this.m_ObjectWithTypeSerializer.Serialize(x)).ToArray() }; }
protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { var i = 0; var parameters = types.Select(c => (ParameterInfo)new FickleParameterInfo(c, "param" + (i++).ToString())).ToArray(); return new FickleConstructorInfo(this, "ctor", parameters); }
internal static string MultipleTypesThatRepresentClosedGenericType(Type closedServiceType, Type[] implementations) => string.Format(CultureInfo.InvariantCulture, "There are {0} types in the supplied list of types or assemblies that represent the " + "same closed generic type {1}. Conflicting types: {2}.", implementations.Length, closedServiceType.ToFriendlyName(), implementations.Select(type => type.ToFriendlyName()).ToCommaSeparatedText());
private static string NoteThatSkippedDecoratorsWereFound(Type serviceType, Type[] decorators) => decorators.Any() ? string.Format(CultureInfo.InvariantCulture, " Note that {0} {1} found as implementation of {2}, but {1} skipped during batch-" + "registration by the container because {3} considered to be a decorator (because {4} " + "a cyclic reference to {5}).", Helpers.ToCommaSeparatedText(decorators.Select(Helpers.ToFriendlyName)), decorators.Length == 1 ? "was" : "were", serviceType.GetGenericTypeDefinition().ToFriendlyName(), decorators.Length == 1 ? "it is" : "there are", decorators.Length == 1 ? "it contains" : "they contain", decorators.Length == 1 ? "itself" : "themselves") : string.Empty;
private static string GetMessage(Type[] badTypes) { return "The following context types do not implement a suitable context interface: " + string.Join(", ", badTypes.Select(t => t.Name).ToArray()); }