/// <summary> /// Copies the value of all fields from one <see cref="object"/> to another. /// </summary> internal static void CopyTo <T>(this T from, T to) where T : class { // Find base type of both compilations TypeInfo fromType = from.GetType().GetTypeInfo(); TypeInfo toType = to.GetType().GetTypeInfo(); Type baseType; if (fromType.IsAssignableFrom(toType)) { // ToCompilation inherits FromCompilation baseType = fromType.AsType(); } else if (toType.IsAssignableFrom(fromType)) { // FromCompilation inherits ToCompilation baseType = toType.AsType(); } else { // No common type: find first common type baseType = FindCommonType(fromType.AsType(), toType.AsType()); } // Copy fields from one compilation to the other foreach (FieldInfo field in baseType.GetAllFields()) { if (field.IsStatic) { continue; } field.SetValue(to, field.GetValue(from)); } }
public override CompositeActivator RewriteActivator( TypeInfo partType, CompositeActivator activator, IDictionary<string, object> partMetadata, IEnumerable<CompositionDependency> dependencies) { var propertyDependencies = dependencies .Where(dep => dep.Site is PropertyImportSite) .ToDictionary(d => ((PropertyImportSite)d.Site).Property); if (propertyDependencies.Count == 0) return activator; var lc = Expression.Parameter(typeof(LifetimeContext)); var op = Expression.Parameter(typeof(CompositionOperation)); var inst = Expression.Parameter(typeof(object)); var typed = Expression.Variable(partType.AsType()); var statements = new List<Expression>(); var assignTyped = Expression.Assign(typed, Expression.Convert(inst, partType.AsType())); statements.Add(assignTyped); foreach (var d in propertyDependencies) { var property = d.Key; var assignment = Expression.Assign( Expression.MakeMemberAccess(typed, property), Expression.Convert( Expression.Call( Expression.Constant(d.Value.Target.GetDescriptor().Activator), s_activatorInvokeMethod, lc, op), property.PropertyType)); statements.Add(assignment); } statements.Add(inst); var setAll = Expression.Block(new[] { typed }, statements); var setAction = Expression.Lambda<Func<object, LifetimeContext, CompositionOperation, object>>( setAll, inst, lc, op).Compile(); return (c, o) => { var i = activator(c, o); o.AddNonPrerequisiteAction(() => setAction(i, c, o)); return i; }; }
public override DiscoveredExport CloseGenericExport(TypeInfo closedPartType, Type[] genericArguments) { var closedContractType = Contract.ContractType.MakeGenericType(genericArguments); var newContract = Contract.ChangeType(closedContractType); var property = closedPartType.AsType().GetRuntimeProperty(_property.Name); return new DiscoveredPropertyExport(newContract, Metadata, property); }
protected static bool IsSupportedPrimitive(TypeInfo typeInfo) { return typeInfo.IsPrimitive || typeInfo.IsEnum || typeInfo == typeof(string).GetTypeInfo() || IsNullable(typeInfo.AsType()); }
public override IEnumerable<CompositionDependency> GetDependencies(TypeInfo partType, DependencyAccessor definitionAccessor) { var partTypeAsType = partType.AsType(); var imports = (from pi in partTypeAsType.GetRuntimeProperties() .Where(pi => pi.CanWrite && pi.SetMethod.IsPublic && !(pi.SetMethod.IsStatic)) let attrs = _attributeContext.GetDeclaredAttributes(pi.DeclaringType, pi).ToArray() let site = new PropertyImportSite(pi) where attrs.Any(a => a is ImportAttribute || a is ImportManyAttribute) select new { Site = site, ImportInfo = ContractHelpers.GetImportInfo(pi.PropertyType, attrs, site) }).ToArray(); if (imports.Length == 0) return NoDependencies; var result = new List<CompositionDependency>(); foreach (var i in imports) { if (!i.ImportInfo.AllowDefault) { result.Add(definitionAccessor.ResolveRequiredDependency(i.Site, i.ImportInfo.Contract, false)); } else { CompositionDependency optional; if (definitionAccessor.TryResolveOptionalDependency(i.Site, i.ImportInfo.Contract, false, out optional)) result.Add(optional); // Variation from CompositionContainer behaviour: we don't have to support recomposition // so we don't require that defaultable imports be set to null. } } return result; }
private static MethodInfo GetMethod(TypeInfo componentType, object[] args, string methodName) { Type[] types; if (args == null || args.Length == 0) { types = Type.EmptyTypes; } else { types = new Type[args.Length]; for (var i = 0; i < args.Length; i++) { types[i] = args[i]?.GetType() ?? typeof(object); } } #if NET451 return componentType.AsType().GetMethod( methodName, BindingFlags.Public | BindingFlags.Instance, binder: null, types: types, modifiers: null); #else var method = componentType.AsType().GetMethod(methodName, types: types); // At most one method (including static and instance methods) with the same parameter types can exist // per type. return method != null && method.IsStatic ? null : method; #endif }
public static System.Type GetTypeFromInfo ( TP type ) { #if NETFX_CORE return type.AsType(); #else return type; #endif }
private static MethodInfo GetMethod(TypeInfo componentType, object[] args, string methodName) { args = args ?? new object[0]; var argumentExpressions = new Expression[args.Length]; for (var i = 0; i < args.Length; i++) { argumentExpressions[i] = Expression.Constant(args[i], args[i].GetType()); } try { // We're currently using this technique to make a call into a component method that looks like a // regular method call. // // Ex: @Component.Invoke<Cart>("hello", 5) => cart.Invoke("hello", 5) // // This approach has some drawbacks, namely it doesn't account for default parameters, and more // noticably, it throws if the method is not found. // // Unfortunely the overload of Type.GetMethod that we would like to use is not present in CoreCLR. // Item #160 in Jira tracks these issues. var expression = Expression.Call( Expression.Constant(null, componentType.AsType()), methodName, null, argumentExpressions); return expression.Method; } catch (InvalidOperationException) { return null; } }
private IEnumerable<DiscoveredExport> DiscoverPropertyExports(TypeInfo partType) { var partTypeAsType = partType.AsType(); foreach (var property in partTypeAsType.GetRuntimeProperties() .Where(pi => pi.CanRead && pi.GetMethod.IsPublic && !pi.GetMethod.IsStatic)) { foreach (var export in _attributeContext.GetDeclaredAttributes<ExportAttribute>(partTypeAsType, property)) { IDictionary<string, object> metadata = new Dictionary<string, object>(); ReadMetadataAttribute(export, metadata); var applied = _attributeContext.GetDeclaredAttributes(partTypeAsType, property); ReadLooseMetadata(applied, metadata); var contractType = export.ContractType ?? property.PropertyType; CheckPropertyExportCompatibility(partType, property, contractType.GetTypeInfo()); var exportKey = new CompositionContract(export.ContractType ?? property.PropertyType, export.ContractName); if (metadata.Count == 0) metadata = s_noMetadata; yield return new DiscoveredPropertyExport(exportKey, metadata, property); } } }
public static System.Type GetTypeFromInfo(TP type) { #if NETFX_CORE return(type.AsType()); #else return(type); #endif }
public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo) { if (typeInfo == null) { return(false); } return(IsAssignableFrom(typeInfo.AsType())); }
private void ProcessType(TypeInfo typeInfo) { var type = typeInfo.AsType(); if (alreadyProcessed.Contains(type) || typeInfo.IsInterface || typeInfo.IsAbstract || !condition(type)) return; alreadyProcessed.Add(type); callback(type); }
public virtual Migration CreateMigration(TypeInfo migrationClass, string activeProvider) { Check.NotNull(activeProvider, nameof(activeProvider)); var migration = (Migration)Activator.CreateInstance(migrationClass.AsType()); migration.ActiveProvider = activeProvider; return migration; }
private HarshContentTypeId Build(TypeInfo t) { if (t.AsType() == typeof(HarshEntity)) { // don't recurse up to Object. we should never get // here anyway, since entities are supposed to inherit from // something with an absolute ID specified, // not directly from the HarshEntity class. return null; } var cta = t.GetCustomAttribute<ContentTypeAttribute>(inherit: false); if (cta == null) { if (t == _entityTypeInfo) { throw Logger.Fatal.InvalidOperationFormat( SR.ContentTypeIdBuilder_NoContentTypeAttribute, t.FullName ); } else { throw Logger.Fatal.InvalidOperationFormat( SR.ContentTypeIdBuilder_NoContentTypeAttributeBaseClass, t.FullName, _entityTypeInfo.FullName ); } } var ctid = HarshContentTypeId.Parse(cta.ContentTypeId); if (ctid.IsAbsolute) { // an absolute ID. do not recurse further up the // class hierarchy, take it as it is return ctid; } else { // not an absolute ID, append the parent type ID first var result = Build(t.BaseType.GetTypeInfo()); if (result == null) { throw Logger.Fatal.InvalidOperationFormat( SR.ContentTypeIdBuilder_NoAbsoluteIDInHierarchy, _entityTypeInfo.FullName ); } return result.Append(ctid); } }
private static ViewComponentDescriptor CreateCandidate(TypeInfo typeInfo) { var candidate = new ViewComponentDescriptor() { FullName = ViewComponentConventions.GetComponentFullName(typeInfo), ShortName = ViewComponentConventions.GetComponentName(typeInfo), Type = typeInfo.AsType(), }; return candidate; }
/// <summary> /// Creates a descriptor for the given widget type. /// </summary> /// <param name="typeInfo">The widget type.</param> /// <returns>The widget descriptor.</returns> private static WidgetDescriptor CreateDescriptor(TypeInfo typeInfo) { var descriptor = new WidgetDescriptor { FullName = WidgetConventions.GetWidgetFullName(typeInfo), ShortName = WidgetConventions.GetWidgetName(typeInfo), Type = typeInfo.AsType() }; return descriptor; }
/// <summary> /// Gets the underlying element type. /// </summary> /// <param name="type">The type to extract the underlying type (if any).</param> /// <returns>The underlying element type.</returns> /// <returns>The underlying type.</returns> public static Type GetUnderlyingType(TypeInfo type) { if (type.IsArray) { return type.GetElementType(); } if (type.IsGenericType == false) { return type.AsType(); } Type enumerableType; if (TryGetEnumerableType(type, out enumerableType)) { return enumerableType.GetTypeInfo().GenericTypeArguments[0]; ; } return type.AsType(); }
private static ViewComponentDescriptor CreateDescriptor(TypeInfo typeInfo) { var candidate = new ViewComponentDescriptor { FullName = ViewComponentConventions.GetComponentFullName(typeInfo), ShortName = ViewComponentConventions.GetComponentName(typeInfo), TypeInfo = typeInfo, MethodInfo = FindMethod(typeInfo.AsType()) }; return candidate; }
public override CompositeActivator RewriteActivator( TypeInfo partType, CompositeActivator activator, IDictionary<string, object> partMetadata, IEnumerable<CompositionDependency> dependencies) { var result = activator; var partTypeAsType = partType.AsType(); var importsSatisfiedMethods = partTypeAsType.GetRuntimeMethods() .Where(mi => _attributeContext.GetDeclaredAttribute<OnImportsSatisfiedAttribute>(mi.DeclaringType, mi) != null); foreach (var m in importsSatisfiedMethods) { if (!(m.IsPublic || m.IsAssembly) | m.IsStatic || m.ReturnType != typeof(void) || m.IsGenericMethodDefinition || m.GetParameters().Length != 0) { var message = string.Format( Properties.Resources.OnImportsSatisfiedFeature_AttributeError, partType, m.Name); throw new CompositionFailedException(message); } var ois = Expression.Parameter(typeof(object), "ois"); var call = Expression.Lambda<Action<object>>( Expression.Call(Expression.Convert(ois, partType.AsType()), m), ois).Compile(); var prev = result; result = (c, o) => { var psn = prev(c, o); o.AddPostCompositionAction(() => call(psn)); return psn; }; } return result; }
public bool InspectTypeForPart(TypeInfo type, out DiscoveredPart part) { part = null; if (type.IsAbstract || !type.IsClass || _attributeContext.GetDeclaredAttribute<PartNotDiscoverableAttribute>(type.AsType(), type) != null) return false; foreach (var export in DiscoverExports(type)) { part = part ?? new DiscoveredPart(type, _attributeContext, _activationFeatures); part.AddDiscoveredExport(export); } return part != null; }
private static IBuildScript CreateBuildScriptInstance(Assembly assembly, string fileName) { TypeInfo type = assembly.DefinedTypes.FirstOrDefault(i => i.ImplementedInterfaces.Any(x => x == typeof(IBuildScript))); if (type == null) { throw new ScriptLoaderExcetpion($"Class in file: {fileName} must inherit from DefaultBuildScript or implement IBuildScipt interface. See getting started on https://github.com/flubu-core/flubu.core/wiki"); } var obj = Activator.CreateInstance(type.AsType()); var buildScript = obj as IBuildScript ?? throw new ScriptLoaderExcetpion($"Class in file: {fileName} must inherit from DefaultBuildScript or implement IBuildScipt interface. See getting started on https://github.com/flubu-core/flubu.core/wiki"); return(buildScript); }
internal static bool HasOverriddenToString(System.Reflection.TypeInfo type) { if (type.IsInterface) { return(false); } for (; type.AsType() != (object)typeof(object); type = IntrospectionExtensions.GetTypeInfo(type.BaseType)) { if ((object)type.GetDeclaredMethod("ToString") != null) { return(true); } } return(false); }
private static void ProcessType(IContainerConfiguration container, TypeInfo concreteType, Type serviceType) { var typeDefinition = serviceType.GetGenericTypeDefinition(); if (HandlerTypeDefinitions.Any(h => h == typeDefinition)) { var serviceScope = concreteType.GetServiceScope() ?? ServiceScope.Default; container. Register(serviceType). InScope(serviceScope). UsingConcreteType(concreteType.AsType()); } }
public TestFixture(TypeInfo testType, CustomAttributeData testFixtureAttribute) { Type = testType; Tests = new List<Test>(); // Tesztesetek meghatározása foreach (var method in TestHelper.GetMethods(Type, attribute => attribute.AttributeType.FullName == TestAttributes.Test)) { Tests.Add(new Test(this, method)); } TestFixtureAttribute = testFixtureAttribute; Instance = TestHelper.CreateTestFixture(Type.AsType(), testFixtureAttribute); FindSetUpFixture(out _setUpFixture, out _setUpMethod); FindTearDownFixture(out _tearDownFixture, out _tearDownMethod); }
public void ProcessType(IContainerConfiguration container, TypeInfo type) { var settingsAttribute = type.GetCustomAttribute<SettingsAttribute>(); if (settingsAttribute != null) { var settingsType = type.AsType(); var settingsScope = settingsAttribute.Scope; var activatorConfiguration = new SettingsActivatorConfiguration(settingsScope, settingsType); container.Register(activatorConfiguration); } foreach (var serviceType in type.ImplementedInterfaces) { ProcessServiceType(container, type, serviceType); } }
public static bool IsSupportedFieldType(TypeInfo t) { if (t.IsPointer || t.IsByRef) return false; var handle = t.AsType().TypeHandle; for (var i = 0; i < UnsupportedTypeHandles.Length; i++) { if (handle.Equals(UnsupportedTypeHandles[i])) return false; } for (var i = 0; i < UnsupportedBaseTypes.Length; i++) { if (UnsupportedBaseTypes[i].IsAssignableFrom(t)) return false; } return true; }
private static void ProcessServiceType(IContainerConfiguration container, TypeInfo concreteType, Type serviceType) { if (serviceType.IsConstructedGenericType) { var typeDefinition = serviceType.GetGenericTypeDefinition(); if (typeDefinition == SettingsHandlerTypeDefinition) { var serviceScope = concreteType.GetServiceScope() ?? ServiceScope.Default; container. Register(serviceType). InScope(serviceScope). UsingConcreteType(concreteType.AsType()); } } }
IEnumerable<string> FormatType(TypeInfo type) { if (type.IsEnum) { return $"{type.Name}".InArray() .Concat("{") .Concat(Enum.GetValues(type.AsType()).Cast<Enum>().Select(v => $" {v} = {(int)(object)v}")) .Concat("}"); } var kind = type.IsInterface ? "interface" : type.IsAbstract ? "abstract class" : "class"; var interfaces = type.GetInterfaces(); var members = type.GetMembers(BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public) .OrderBy(t => t.Name) .ToArray(); var fields = members.OfType<FieldInfo>().ToArray(); var ctors = members.OfType<ConstructorInfo>().ToArray(); var properties = members.OfType<PropertyInfo>().ToArray(); var events = members.OfType<EventInfo>().ToArray(); var methods = members.OfType<MethodInfo>().ToArray(); var types = members.OfType<TypeInfo>().ToArray(); var other = members.Except(methods).Except(properties).Except(fields).Except(ctors).Except(events).Except(types).ToArray(); var body = fields.Select(f => $"{Static(f.IsStatic)}{f.FieldType} {f.Name}") .Concat(events.Select(e => $"event {FormatTypeName(e.EventHandlerType)} {e.Name}")) .Concat(ctors.SelectMany(FormatCtor)) .Concat(properties.Select(p => $"{FormatProperty(p)}")) .Concat(methods.SelectMany(FormatMethods)) .Concat(other.Select(o => $"UNKNOWN {o.GetType().Name} {o.Name}")) .Concat(types.SelectMany(FormatType)); return $"{kind} {type.Name}".InArray() .Concat(interfaces.Select(i => $" {FormatTypeName(i)}")) .Concat("{") .Concat(body.Select(l => " " + l)) .Concat("}"); }
public static bool IsAssignableFrom(TypeInfo toTypeInfo, TypeInfo fromTypeInfo, FoundationTypes foundationTypes) { if (toTypeInfo == null) throw new NullReferenceException(); if (fromTypeInfo == null) return false; // It would be more appropriate to throw ArgumentNullException here, but returning "false" is the desktop-compat behavior. if (fromTypeInfo.Equals(toTypeInfo)) return true; if (toTypeInfo.IsGenericTypeDefinition) { // Asking whether something can cast to a generic type definition is arguably meaningless. The desktop CLR Reflection layer converts all // generic type definitions to generic type instantiations closed over the formal generic type parameters. The .NET Native framework // keeps the two separate. Fortunately, under either interpretation, returning "false" unless the two types are identical is still a // defensible behavior. To avoid having the rest of the code deal with the differing interpretations, we'll short-circuit this now. return false; } if (fromTypeInfo.IsGenericTypeDefinition) { // The desktop CLR Reflection layer converts all generic type definitions to generic type instantiations closed over the formal // generic type parameters. The .NET Native framework keeps the two separate. For the purpose of IsAssignableFrom(), // it makes sense to unify the two for the sake of backward compat. We'll just make the transform here so that the rest of code // doesn't need to know about this quirk. fromTypeInfo = fromTypeInfo.GetGenericTypeDefinition().MakeGenericType(fromTypeInfo.GenericTypeParameters).GetTypeInfo(); } if (fromTypeInfo.CanCastTo(toTypeInfo, foundationTypes)) return true; Type toType = toTypeInfo.AsType(); Type fromType = fromTypeInfo.AsType(); // Desktop compat: IsAssignableFrom() considers T as assignable to Nullable<T> (but does not check if T is a generic parameter.) if (!fromType.IsGenericParameter) { Type nullableUnderlyingType = Nullable.GetUnderlyingType(toType); if (nullableUnderlyingType != null && nullableUnderlyingType.Equals(fromType)) return true; } return false; }
private static bool HasOverriddenToString(TypeInfo type) { if (type.IsInterface) { return false; } while (type.AsType() != typeof(object)) { if (type.GetDeclaredMethod("ToString", Type.EmptyTypes) != null) { return true; } type = type.BaseType.GetTypeInfo(); } return false; }
internal ClassMetadata(TypeInfo typeInfo) { #if !DataAnnotations_Missing var table = (TableAttribute)typeInfo.GetCustomAttributes(typeof(TableAttribute), true).SingleOrDefault(); if (table != null) { MappedTableName = table.Name; MappedSchemaName = table.Schema; } #endif #if Weird_Reflection var shadowingProperties = (from p in typeInfo.DeclaredProperties where IsHidingMember(p) select p).ToList(); var propertyList = typeInfo.DeclaredProperties.ToList(); #elif TypeInfo_Is_Not_Type var type = typeInfo.AsType(); var shadowingProperties = (from p in type.GetProperties() where IsHidingMember(p) select p).ToList(); var propertyList = type.GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); #else var shadowingProperties = (from p in typeInfo.GetProperties() where IsHidingMember(p) select p).ToList(); var propertyList = typeInfo.GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); #endif Func<PropertyInfo, bool> IsHidden = propertyInfo => !shadowingProperties.Contains(propertyInfo) && shadowingProperties.Any(p => p.Name == propertyInfo.Name); Properties = new PropertyMetadataCollection(propertyList.Where(p => !IsHidden(p)).Select(p => new PropertyMetadata(p))); //List the properties that are affected when the indicated property is modified. foreach (var property in Properties) foreach (CalculatedFieldAttribute fieldList in property.PropertyInfo.GetCustomAttributes(typeof(CalculatedFieldAttribute), true)) foreach (var field in fieldList.SourceProperties) { if (!Properties.Contains(field)) throw new InvalidOperationException(string.Format("Cannot find property {0} on type {1}. This is needed for the calculated property {2}", field, typeInfo.FullName, property.Name)); Properties[field].AddCalculatedField(property); } foreach (var property in Properties) property.EndInit(); Constructors = new ConstructorMetadataCollection(typeInfo.DeclaredConstructors); }
protected override bool IsController(TypeInfo typeInfo) { var type = typeInfo.AsType(); if (!typeof(IApplicationService).IsAssignableFrom(type) || !type.IsPublic || type.IsAbstract || type.IsGenericType) { return false; } var remoteServiceAttr = ReflectionHelper.GetSingleAttributeOrDefault<RemoteServiceAttribute>(type); if (remoteServiceAttr != null && !remoteServiceAttr.IsEnabledFor(type)) { return false; } var configuration = _iocResolver.Resolve<AbpAspNetCoreConfiguration>().ControllerAssemblySettings.GetSettingOrNull(type); return configuration != null && configuration.TypePredicate(type); }
// // T[] casts to IList<T>. This could be handled by the normal ancestor-walking code // but for one complication: T[] also casts to IList<U> if T[] casts to U[]. // private static bool CanCastArrayToInterface(this TypeInfo fromTypeInfo, TypeInfo toTypeInfo, FoundationTypes foundationTypes) { Debug.Assert(fromTypeInfo.IsArray); Debug.Assert(toTypeInfo.IsInterface); Type toType = toTypeInfo.AsType(); if (toType.IsConstructedGenericType) { Type[] toTypeGenericTypeArguments = toTypeInfo.GenericTypeArguments; if (toTypeGenericTypeArguments.Length != 1) return false; TypeInfo toElementTypeInfo = toTypeGenericTypeArguments[0].GetTypeInfo(); Type toTypeGenericTypeDefinition = toTypeInfo.GetGenericTypeDefinition(); TypeInfo fromElementTypeInfo = fromTypeInfo.GetElementType().GetTypeInfo(); foreach (Type ifc in fromTypeInfo.ImplementedInterfaces) { if (ifc.IsConstructedGenericType) { Type ifcGenericTypeDefinition = ifc.GetGenericTypeDefinition(); if (ifcGenericTypeDefinition.Equals(toTypeGenericTypeDefinition)) { if (fromElementTypeInfo.IsElementTypeCompatibleWith(toElementTypeInfo, foundationTypes)) return true; } } } return false; } else { foreach (Type ifc in fromTypeInfo.ImplementedInterfaces) { if (ifc.Equals(toType)) return true; } return false; } }
private IEnumerable<DiscoveredExport> DiscoverInstanceExports(TypeInfo partType) { var partTypeAsType = partType.AsType(); foreach (var export in _attributeContext.GetDeclaredAttributes<ExportAttribute>(partTypeAsType, partType)) { IDictionary<string, object> metadata = new Dictionary<string, object>(); ReadMetadataAttribute(export, metadata); var applied = _attributeContext.GetDeclaredAttributes(partTypeAsType, partType); ReadLooseMetadata(applied, metadata); var contractType = export.ContractType ?? partTypeAsType; CheckInstanceExportCompatibility(partType, contractType.GetTypeInfo()); var exportKey = new CompositionContract(contractType, export.ContractName); if (metadata.Count == 0) metadata = s_noMetadata; yield return new DiscoveredInstanceExport(exportKey, metadata); } }
private static IEnumerable <Lazy <TExtensionWrapper, OrderableLanguageMetadataData> > GetExportsWithOrderableLanguageMetadataSlow <TExtensionWrapper>( MefHostServices hostServices, TypeInfo extensionType, Func <object, TExtensionWrapper> createWrapper ) { var mefHostServicesType = typeof(MefHostServices).GetTypeInfo(); var getExports = EnsureFound( mefHostServicesType, "Microsoft.CodeAnalysis.Host.Mef.IMefHostExportProvider.GetExports", (t, n) => t.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic) .FirstOrDefault(m => m.Name == n && m.GetGenericArguments().Length == 2) ); var metadataType = mefHostServicesType.Assembly.GetType("Microsoft.CodeAnalysis.Host.Mef.OrderableLanguageMetadata", true).GetTypeInfo(); var getExportsOfProvider = getExports.MakeGenericMethod(extensionType.AsType(), metadataType.AsType()); var exports = (IEnumerable)getExportsOfProvider.Invoke(hostServices, null); var metadataLanguagePropery = EnsureFound(metadataType, "Language", (t, n) => t.GetProperty(n)); TypeInfo? lazyType = null; PropertyInfo?metadataProperty = null; PropertyInfo?valueProperty = null; foreach (var export in exports) { if (lazyType == null) { lazyType = export.GetType().GetTypeInfo(); metadataProperty = EnsureFound(lazyType, "Metadata", (t, n) => t.GetProperty(n)); valueProperty = EnsureFound(lazyType, "Value", (t, n) => t.GetProperty(n)); } var metadata = metadataProperty !.GetValue(export); var language = (string)metadataLanguagePropery.GetValue(metadata); yield return(new Lazy <TExtensionWrapper, OrderableLanguageMetadataData>( // ReSharper disable once AccessToModifiedClosure () => createWrapper(valueProperty !.GetValue(export)), new OrderableLanguageMetadataData(language) )); } }
internal HarshEntityMetadata(HarshEntityMetadataRepository repository, TypeInfo entityTypeInfo) : base(entityTypeInfo) { if (repository == null) { throw Logger.Fatal.ArgumentNull(nameof(repository)); } if (!HarshEntityTypeInfo.IsAssignableFrom(ObjectTypeInfo)) { throw Logger.Fatal.ArgumentTypeNotAssignableTo( nameof(entityTypeInfo), entityTypeInfo.AsType(), HarshEntityTypeInfo.AsType() ); } Repository = repository; GetBaseEntity(); CreateDeclaredFields(); }
public Type Build() { TypeInfo typeInfo = CompileResultTypeInfo(); return(typeInfo.AsType()); TypeInfo CompileResultTypeInfo() { TypeBuilder typeBuilder = GetTypeBuilder(); typeBuilder.DefineDefaultConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); if (useChildVerbsAsCategory) { AddUseChildVerbsAsCategory(); } AddVerbAttribute(); AddOptions(); AddExamples(); TypeInfo objectTypeInfo = typeBuilder.CreateTypeInfo(); return(objectTypeInfo); TypeBuilder GetTypeBuilder() { string typeSignature = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture); TypeBuilder result = ModuleBuilder.DefineType(typeSignature, TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit | TypeAttributes.AutoLayout, baseType); return(result); } void AddUseChildVerbsAsCategory() { Type childVerbsAsCategory = typeof(UseChildVerbsAsCategoryAttribute); ConstructorInfo constructor = childVerbsAsCategory.GetConstructor(Array.Empty <Type>()); typeBuilder.SetCustomAttribute(new CustomAttributeBuilder(constructor, Array.Empty <object>())); } void AddVerbAttribute() { Type verbAttribute = typeof(VerbAttribute); ConstructorInfo constructor = verbAttribute.GetConstructor(new[] { typeof(string), typeof(bool) }); PropertyInfo helpTextProperty = verbAttribute.GetProperty("HelpText"); typeBuilder.SetCustomAttribute(new CustomAttributeBuilder(constructor, new object[] { name, false }, new[] { helpTextProperty }, new object[] { helpText })); } void AddExamples() { if (!examples.Any()) { return; } Type propertyType = typeof(IEnumerable <UsageExample>); PropertyBuilder builder = CreateExampleProperty(); AddUsageAttribute(); void AddUsageAttribute() { Type usageAttributeType = typeof(UsageAttribute); ConstructorInfo constructor = usageAttributeType.GetConstructor(Array.Empty <Type>()); CustomAttributeBuilder usageAttributeBuilder = new CustomAttributeBuilder(constructor, Array.Empty <object>()); builder.SetCustomAttribute(usageAttributeBuilder); } PropertyBuilder CreateExampleProperty() { string propertyName = Guid.NewGuid().ToByteString(); PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null); MethodBuilder getPropMthdBldr = typeBuilder.DefineMethod("get_" + propertyName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Static, propertyType, Type.EmptyTypes); ILGenerator getIl = getPropMthdBldr.GetILGenerator(); ConstructorInfo constructor = typeof(UsageExample).GetConstructor(new [] { typeof(string), typeof(string) }); //create new array getIl.Emit(OpCodes.Ldc_I4, examples.Count); getIl.Emit(OpCodes.Newarr, typeof(UsageExample)); //set array items for (int i = 0; i < examples.Count; i++) { getIl.Emit(OpCodes.Dup); getIl.Emit(OpCodes.Ldc_I4, i); //create usage example object getIl.Emit(OpCodes.Ldstr, examples[i].Description); getIl.Emit(OpCodes.Ldstr, examples[i].Command); getIl.Emit(OpCodes.Newobj, constructor); getIl.Emit(OpCodes.Stelem_Ref); } //Return getIl.Emit(OpCodes.Ret); propertyBuilder.SetGetMethod(getPropMthdBldr); return(propertyBuilder); } } void AddOptions() { foreach (Option option in options) { Type propertyType = GetPropertyType(option.ValueType); PropertyBuilder propertyBuilder = CreateProperty(option.Name, propertyType); AddOptionAttribute(propertyBuilder, option); } void AddOptionAttribute(PropertyBuilder propertyBuilder, Option option) { Type optionAttribute = typeof(OptionAttribute); PropertyInfo helpTextProperty = optionAttribute.GetProperty("HelpText"); PropertyInfo separatorProperty = optionAttribute.GetProperty("Separator"); PropertyInfo requiredProperty = optionAttribute.GetProperty("Required"); PropertyInfo setNameProperty = optionAttribute.GetProperty("SetName"); ConstructorInfo constructor = optionAttribute.GetConstructor( option.ShortName != default(char) ? new[] { typeof(char), typeof(string) } : new[] { typeof(string) }); object[] constructorArgs = option.ShortName != default(char) ? new object[] { option.ShortName, option.Name } : new object[] { option.Name }; List <PropertyInfo> namedProperties = new List <PropertyInfo>(new[] { helpTextProperty, requiredProperty }); List <object> propertiesValues = new List <object>(new object[] { option.Help, option.Mandatory }); if (option.ValueType == OptionValueType.MultipleValue && !option.Separator.Equals(' ')) { namedProperties.Add(separatorProperty); propertiesValues.Add(option.Separator); } if (!string.IsNullOrEmpty(option.SetName)) { namedProperties.Add(setNameProperty); propertiesValues.Add(option.SetName); } CustomAttributeBuilder builder = new CustomAttributeBuilder(constructor, constructorArgs, namedProperties.ToArray(), propertiesValues.ToArray()); propertyBuilder.SetCustomAttribute(builder); } Type GetPropertyType(OptionValueType optionValueType) { switch (optionValueType) { case OptionValueType.WithoutValue: return(typeof(bool)); case OptionValueType.SingleValue: return(typeof(string)); case OptionValueType.MultipleValue: return(typeof(IEnumerable <string>)); default: throw new ArgumentException("Unkown option value type", nameof(optionValueType)); } } PropertyBuilder CreateProperty(string propertyName, Type propertyType) { FieldBuilder fieldBuilder = typeBuilder.DefineField("_" + propertyName, propertyType, FieldAttributes.Private); PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null); MethodBuilder getPropMthdBldr = typeBuilder.DefineMethod("get_" + propertyName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, propertyType, Type.EmptyTypes); ILGenerator getIl = getPropMthdBldr.GetILGenerator(); getIl.Emit(OpCodes.Ldarg_0); getIl.Emit(OpCodes.Ldfld, fieldBuilder); getIl.Emit(OpCodes.Ret); MethodBuilder setPropMthdBldr = typeBuilder.DefineMethod("set_" + propertyName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, null, new[] { propertyType }); ILGenerator setIl = setPropMthdBldr.GetILGenerator(); Label modifyProperty = setIl.DefineLabel(); Label exitSet = setIl.DefineLabel(); setIl.MarkLabel(modifyProperty); setIl.Emit(OpCodes.Ldarg_0); setIl.Emit(OpCodes.Ldarg_1); setIl.Emit(OpCodes.Stfld, fieldBuilder); setIl.Emit(OpCodes.Nop); setIl.MarkLabel(exitSet); setIl.Emit(OpCodes.Ret); propertyBuilder.SetGetMethod(getPropMthdBldr); propertyBuilder.SetSetMethod(setPropMthdBldr); return(propertyBuilder); } } } }
public static bool IsConstructedGenericType(this System.Reflection.TypeInfo type) { return(type.AsType().IsConstructedGenericType); }
public virtual bool IsAssignableFrom(TypeInfo typeInfo) { return(IsAssignableFrom(typeInfo.AsType())); }
void SetupPart(System.Reflection.TypeInfo sourceType, BindingExpressionPart part) { part.Arguments = null; part.LastGetter = null; part.LastSetter = null; PropertyInfo property = null; if (part.IsIndexer) { if (sourceType.IsArray) { int index; if (!int.TryParse(part.Content, NumberStyles.Number, CultureInfo.InvariantCulture, out index)) { Console.WriteLine($"Binding : {part.Content} could not be parsed as an index for a {sourceType}"); } else { part.Arguments = new object[] { index } }; part.LastGetter = sourceType.GetDeclaredMethod("Get"); part.LastSetter = sourceType.GetDeclaredMethod("Set"); part.SetterType = sourceType.GetElementType(); } DefaultMemberAttribute defaultMember = sourceType.GetCustomAttributes(typeof(DefaultMemberAttribute), true).OfType <DefaultMemberAttribute>().FirstOrDefault(); string indexerName = defaultMember != null ? defaultMember.MemberName : "Item"; part.IndexerName = indexerName; #if NETSTANDARD2_0 try { property = sourceType.GetDeclaredProperty(indexerName); } catch (AmbiguousMatchException) { // Get most derived instance of property foreach (var p in sourceType.GetProperties().Where(prop => prop.Name == indexerName)) { if (property == null || property.DeclaringType.IsAssignableFrom(property.DeclaringType)) { property = p; } } } #else property = sourceType.GetDeclaredProperty(indexerName); #endif if (property == null) //is the indexer defined on the base class? { property = sourceType.BaseType?.GetProperty(indexerName); } if (property == null) //is the indexer defined on implemented interface ? { foreach (var implementedInterface in sourceType.ImplementedInterfaces) { property = implementedInterface.GetProperty(indexerName); if (property != null) { break; } } } if (property != null) { ParameterInfo parameter = property.GetIndexParameters().FirstOrDefault(); if (parameter != null) { try { object arg = Convert.ChangeType(part.Content, parameter.ParameterType, CultureInfo.InvariantCulture); part.Arguments = new[] { arg }; } catch (FormatException) { } catch (InvalidCastException) { } catch (OverflowException) { } } } } else { property = sourceType.GetDeclaredProperty(part.Content) ?? sourceType.BaseType?.GetProperty(part.Content); } if (property != null) { if (property.CanRead && property.GetMethod != null) { if (property.GetMethod.IsPublic && !property.GetMethod.IsStatic) { part.LastGetter = property.GetMethod; } } if (property.CanWrite && property.SetMethod != null) { if (property.SetMethod.IsPublic && !property.SetMethod.IsStatic) { part.LastSetter = property.SetMethod; part.SetterType = part.LastSetter.GetParameters().Last().ParameterType; if (Binding.AllowChaining) { FieldInfo bindablePropertyField = sourceType.GetDeclaredField(part.Content + "Property"); if (bindablePropertyField != null && bindablePropertyField.FieldType == typeof(BindableProperty) && sourceType.ImplementedInterfaces.Contains(typeof(IElementController))) { MethodInfo setValueMethod = null; #if NETSTANDARD1_0 foreach (MethodInfo m in sourceType.AsType().GetRuntimeMethods()) { if (m.Name.EndsWith("IElementController.SetValueFromRenderer")) { ParameterInfo[] parameters = m.GetParameters(); if (parameters.Length == 2 && parameters[0].ParameterType == typeof(BindableProperty)) { setValueMethod = m; break; } } } #else setValueMethod = typeof(IElementController).GetMethod("SetValueFromRenderer", new[] { typeof(BindableProperty), typeof(object) }); #endif if (setValueMethod != null) { part.LastSetter = setValueMethod; part.IsBindablePropertySetter = true; part.BindablePropertyField = bindablePropertyField.GetValue(null); } } } } } #if !NETSTANDARD1_0 //TupleElementNamesAttribute tupleEltNames; //if (property != null // && part.NextPart != null // && property.PropertyType.IsGenericType // && (property.PropertyType.GetGenericTypeDefinition() == typeof(ValueTuple<>) // || property.PropertyType.GetGenericTypeDefinition() == typeof(ValueTuple<,>) // || property.PropertyType.GetGenericTypeDefinition() == typeof(ValueTuple<,,>) // || property.PropertyType.GetGenericTypeDefinition() == typeof(ValueTuple<,,,>) // || property.PropertyType.GetGenericTypeDefinition() == typeof(ValueTuple<,,,,>) // || property.PropertyType.GetGenericTypeDefinition() == typeof(ValueTuple<,,,,,>) // || property.PropertyType.GetGenericTypeDefinition() == typeof(ValueTuple<,,,,,,>) // || property.PropertyType.GetGenericTypeDefinition() == typeof(ValueTuple<,,,,,,,>)) // && (tupleEltNames = property.GetCustomAttribute(typeof(TupleElementNamesAttribute)) as TupleElementNamesAttribute) != null) //{ // // modify the nextPart to access the tuple item via the ITuple indexer // var nextPart = part.NextPart; // var name = nextPart.Content; // var index = tupleEltNames.TransformNames.IndexOf(name); // if (index >= 0) // { // nextPart.IsIndexer = true; // nextPart.Content = index.ToString(); // } //} #endif } }
private string GetTypeDeclaration(System.Reflection.TypeInfo typeInfo) { var result = new StringBuilder(); if (typeInfo.IsNestedPublic || typeInfo.IsPublic) { result.Append("public "); } else if (typeInfo.IsNestedPrivate) { result.Append("private "); } else if (typeInfo.IsNestedFamily) { result.Append("protected "); } else if (typeInfo.IsNestedAssembly) { result.Append("internal "); } else if (typeInfo.IsNestedFamORAssem) { result.Append("protected internal "); } else if (typeInfo.IsNestedFamANDAssem) { result.Append("private protected "); } else if (typeInfo.IsNotPublic) { result.Append("private "); } if (typeInfo.IsAbstract && typeInfo.IsSealed) { result.Append("static "); } else if (typeInfo.IsAbstract) { result.Append("abstract "); } else if (typeInfo.IsSealed) { result.Append("sealed "); } if (typeInfo.IsClass) { result.Append("class "); } else if (typeInfo.IsEnum) { result.Append("enum "); } else if (typeInfo.IsInterface) { result.Append("interface "); } else if (typeInfo.IsGenericType) { result.Append("generic "); } else if (typeInfo.IsValueType && !typeInfo.IsPrimitive) { result.Append("struct "); } result.Append($"{GetTypeName(typeInfo.AsType())} "); return(result.ToString()); }
public bool IsAssignableFrom(TypeInfo c) { return(type.IsAssignableFrom(c.AsType())); }
public static bool IsSameOrSubClass(this TypeInfo subclass, TypeInfo baseclass) => subclass.IsSubclassOf(baseclass.AsType()) || subclass == baseclass;
public bool IsAssignableFrom(TypeInfo typeInfo) => _type.IsAssignableFrom(typeInfo.AsType());
public object Resolve(System.Reflection.TypeInfo typeInfo) { return(_typeResolutionDelegate(typeInfo.AsType())); }
public void Error(TypeInfo typeInfo, string message) { Error(typeInfo.AsType(), message); }
public void Warning(TypeInfo typeInfo, string message) { Warning(typeInfo.AsType(), message); }
public bool IsAssignableFrom(TypeInfo typeInfo) { return(_type.IsAssignableFrom(typeInfo.AsType())); }
public object Resolve(System.Reflection.TypeInfo typeInfo) { return(_typeResolutionDelegate(typeInfo.AsType()) ?? _engine.CreateInstance(typeInfo.AsType())); }
public static ConstructorInfo GetConstructor(this TypeInfo ti, Type[] types) { return(ti.AsType().GetConstructor(types)); }
/// <summary>Returns a value that indicates whether the specified type can be assigned to this type.</summary> /// <param name="typeInfo">The type to check.</param> /// <returns> /// <see langword="true" /> if the specified type can be assigned to this type; otherwise, <see langword="false" />.</returns> // Token: 0x060047A0 RID: 18336 RVA: 0x00102FDB File Offset: 0x001011DB public override bool IsAssignableFrom(TypeInfo typeInfo) { return(!(typeInfo == null) && this.IsAssignableFrom(typeInfo.AsType())); }