Type info for a type.
コード例 #1
0
		public static System.Type GetTypeFromInfo ( TP type ) {
#if NETFX_CORE
			return type.AsType();
#else
			return type;
#endif
		}
コード例 #2
0
        /// <summary>
        /// Finds an asynchronous method to execute.
        /// </summary>
        /// <param name="context">The widget context.</param>
        /// <param name="widgetType">The widget type.</param>
        /// <returns>The asynchronous method.</returns>
        public static MethodInfo FindAsyncMethod(WidgetContext context, TypeInfo widgetType)
        {
            string httpMethod = ResolveHttpMethod(context);
            string state = string.Empty; // Resolve a widget state?
            MethodInfo method = null;

            for (int i = 0; i < AsyncMethodNames.Length; i++)
            {
                string name = string.Format(AsyncMethodNames[i], state, httpMethod);
                method = GetMethod(name, widgetType);
                if (method != null)
                {
                    break;
                }
            }

            if (method == null)
            {
                return null;
            }

            if (!method.ReturnType.GetTypeInfo().IsGenericType
                || method.ReturnType.GetGenericTypeDefinition() != typeof(Task<>))
            {
                throw new InvalidOperationException($"Async method '{method.Name}' must return a task.");
            }

            return method;
        }
コード例 #3
0
        internal static void AssertMessageSerializable(object[] args)
        {
            foreach (object arg in args)
            {
                Debug.Assert(arg != null);

                if (arg is IMessageSerializable)
                {
                    continue;
                }

                Type type = arg.GetType();
                if (type == typeof(string) || type == typeof(AssemblyIdentity))
                {
                    continue;
                }

                System.Reflection.TypeInfo info = type.GetTypeInfo();
                if (info.IsPrimitive)
                {
                    continue;
                }

                throw ExceptionUtilities.UnexpectedValue(type);
            }
        }
コード例 #4
0
 public static bool IsAnonymous(this System.Reflection.TypeInfo type)
 {
     return(type.GetCustomAttribute <CompilerGeneratedAttribute>() != null &&
            type.IsGenericType && type.Name.Contains("AnonymousType") &&
            (type.Name.StartsWith("<>") || type.Name.StartsWith("VB$")) &&
            (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic);
 }
コード例 #5
0
        private static TestMethod CreateMethod(TypeInfo type, object instance, MethodInfo method)
        {
            TestMethod test = new TestMethod();
            test.Name = method.Name;

            if (method.GetCustomAttribute<AsyncTestMethodAttribute>(true) != null)
            {
                test.Test = new AsyncTestMethodAsyncAction(instance, method);                
            }
            else
            {
                test.Test = new TestMethodAsyncAction(instance, method);
            }

            ExcludeTestAttribute excluded = method.GetCustomAttribute<ExcludeTestAttribute>(true);
            if (excluded != null)
            {
                test.Exclude(excluded.Reason);
            }

            if (method.GetCustomAttribute<FunctionalTestAttribute>(true) != null)
            {
                test.Tags.Add("Functional");
            }

            test.Tags.Add(type.FullName + "." + method.Name);
            test.Tags.Add(type.Name + "." + method.Name);
            foreach (TagAttribute attr in method.GetCustomAttributes<TagAttribute>(true))
            {
                test.Tags.Add(attr.Tag);
            }

            return test;
        }
コード例 #6
0
ファイル: TypeResolver.cs プロジェクト: 6bee/aqua-core
        private static bool IsValid(Type type, TypeInfo typeInfo)
        {
            if (!ReferenceEquals(null, type))
            {
                if (typeInfo.IsArray)
                {
                    type = type.GetElementType();
                }

                if (typeInfo.IsAnonymousType || type.IsAnonymousType())
                {
                    var properties = type.GetProperties().Select(x => x.Name).ToList();
                    var propertyNames = typeInfo.Properties.Select(x => x.Name).ToList();

                    var match =
                        type.IsAnonymousType() &&
                        typeInfo.IsAnonymousType &&
                        properties.Count == propertyNames.Count &&
                        propertyNames.All(x => properties.Contains(x));

                    if (!match)
                    {
                        return false;
                    }
                }

                return true;
            }

            return false;
        }
コード例 #7
0
 protected static bool IsSupportedPrimitive(TypeInfo typeInfo)
 {
     return typeInfo.IsPrimitive
         || typeInfo.IsEnum
         || typeInfo == typeof(string).GetTypeInfo()
         || IsNullable(typeInfo.AsType());
 }
コード例 #8
0
ファイル: TypeInspector.cs プロジェクト: benpye/corefx
        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);
                }
            }
        }
コード例 #9
0
        private string FormatGenericTypeName(System.Reflection.TypeInfo typeInfo)
        {
            StringBuilder builder = new StringBuilder();

            Type[] genericArguments = typeInfo.IsGenericTypeDefinition ? typeInfo.GenericTypeParameters : typeInfo.GenericTypeArguments;
            if ((object)typeInfo.DeclaringType != null)
            {
                List <TypeInfo> instance2 = new List <TypeInfo>();
                do
                {
                    instance2.Add(typeInfo);
                    Type declaringType = typeInfo.DeclaringType;
                    typeInfo = (object)declaringType != null?IntrospectionExtensions.GetTypeInfo(declaringType) : null;
                }while (typeInfo != null);
                int genericArgIndex = 0;
                for (int index = instance2.Count - 1; index >= 0; --index)
                {
                    this.AppendTypeInstantiation(builder, instance2[index], genericArguments, ref genericArgIndex);
                    if (index > 0)
                    {
                        builder.Append('.');
                    }
                }
            }
            else
            {
                int genericArgIndex = 0;
                this.AppendTypeInstantiation(builder, typeInfo, genericArguments, ref genericArgIndex);
            }
            return(builder.ToString());
        }
コード例 #10
0
        public virtual string FormatTypeName(Type type)
        {
            if ((object)type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            string primitiveTypeName = this.GetPrimitiveTypeName(ObjectFormatterHelpers.GetPrimitiveSpecialType(type));

            if (primitiveTypeName != null)
            {
                return(primitiveTypeName);
            }
            if (type.IsGenericParameter)
            {
                return(type.Name);
            }
            if (type.IsArray)
            {
                return(this.FormatArrayTypeName(type, null));
            }
            System.Reflection.TypeInfo typeInfo = IntrospectionExtensions.GetTypeInfo(type);
            if (typeInfo.IsGenericType)
            {
                return(this.FormatGenericTypeName(typeInfo));
            }
            return(CommonTypeNameFormatter.FormatNonGenericTypeName(typeInfo));
        }
コード例 #11
0
ファイル: ControllerModel.cs プロジェクト: ymd1223/Mvc
        public ControllerModel(
            TypeInfo controllerType,
            IReadOnlyList<object> attributes)
        {
            if (controllerType == null)
            {
                throw new ArgumentNullException(nameof(controllerType));
            }

            if (attributes == null)
            {
                throw new ArgumentNullException(nameof(attributes));
            }

            ControllerType = controllerType;

            Actions = new List<ActionModel>();
            ApiExplorer = new ApiExplorerModel();
            Attributes = new List<object>(attributes);
            ControllerProperties = new List<PropertyModel>();
            Filters = new List<IFilterMetadata>();
            Properties = new Dictionary<object, object>();
            RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            Selectors = new List<SelectorModel>();
        }
コード例 #12
0
ファイル: TypeInfo.cs プロジェクト: l1183479157/coreclr
        public virtual bool IsAssignableFrom(TypeInfo typeInfo)
        {
            if (typeInfo == null)
                return false;

            if (this == typeInfo)
                return true;

            // If c is a subclass of this class, then c can be cast to this type.
            if (typeInfo.IsSubclassOf(this))
                return true;

            if (this.IsInterface)
            {
                return typeInfo.ImplementInterface(this);
            }
            else if (IsGenericParameter)
            {
                Type[] constraints = GetGenericParameterConstraints();
                for (int i = 0; i < constraints.Length; i++)
                    if (!constraints[i].IsAssignableFrom(typeInfo))
                        return false;

                return true;
            }

            return false;
        }
コード例 #13
0
ファイル: TypeExtensions.cs プロジェクト: rudimk/HAMMER
 public static ConstructorInfo[] GetConstructors(TypeInfo typeInfo, bool nonPublic = false)
 {
     if (nonPublic)
         return typeInfo.DeclaredConstructors.ToArray();
     return
         typeInfo.DeclaredConstructors.Where(x => x.IsPublic).ToArray();
 }
コード例 #14
0
        /// <summary>
        /// Finds a synchronous method to execute.
        /// </summary>
        /// <param name="context">The widget context.</param>
        /// <param name="widgetType">The widget type.</param>
        /// <returns>The synchronous method.</returns>
        public static MethodInfo FindSyncMethod(WidgetContext context, TypeInfo widgetType)
        {
            string httpMethod = ResolveHttpMethod(context);
            string state = string.Empty; // Resolve a widget state?
            MethodInfo method = null;

            for (int i = 0; i < SyncMethodNames.Length; i++)
            {
                string name = string.Format(SyncMethodNames[i], state, httpMethod);
                method = GetMethod(name, widgetType);
                if (method != null)
                {
                    break;
                }
            }

            if (method == null)
            {
                return null;
            }

            if (method.ReturnType == typeof(void))
            {
                throw new InvalidOperationException($"Sync method '{method.Name}' should return a value.");
            }

            if (method.ReturnType.IsAssignableFrom(typeof(Task)))
            {
                throw new InvalidOperationException($"Sync method '{method.Name}' cannot return a task.");
            }

            return method;
        }
コード例 #15
0
        public HandlerDescriptor(TypeInfo handlerType, DispatchingPriority priority)
        {
            Argument.IsNotNull(handlerType, nameof(handlerType));

            HandlerType = handlerType;
            Priority = priority;
        }
コード例 #16
0
        public static string GetComponentFullName(TypeInfo componentType)
        {
            if (componentType == null)
            {
                throw new ArgumentNullException(nameof(componentType));
            }

            var attribute = componentType.GetCustomAttribute<ViewComponentAttribute>();
            if (!string.IsNullOrEmpty(attribute?.Name))
            {
                return attribute.Name;
            }

            // If the view component didn't define a name explicitly then use the namespace + the
            // 'short name'.
            var shortName = GetShortNameByConvention(componentType);
            if (string.IsNullOrEmpty(componentType.Namespace))
            {
                return shortName;
            }
            else
            {
                return componentType.Namespace + "." + shortName;
            }
        }
コード例 #17
0
        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
        }
コード例 #18
0
ファイル: Util.cs プロジェクト: Banane9/SilverConfig
        public static bool InheritsOrImplements(this TypeInfo child, TypeInfo parent)
        {
            if (child == null || parent == null)
                return false;

            parent = resolveGenericTypeDefinition(parent);

            var currentChild = child.IsGenericType
                                   ? child.GetGenericTypeDefinition().GetTypeInfo()
                                   : child;

            while (currentChild != typeof(object).GetTypeInfo())
            {
                if (parent == currentChild || hasAnyInterfaces(parent, currentChild))
                    return true;

                currentChild = currentChild.BaseType != null
                               && currentChild.BaseType.GetTypeInfo().IsGenericType
                                   ? currentChild.BaseType.GetTypeInfo().GetGenericTypeDefinition().GetTypeInfo()
                                   : currentChild.BaseType.GetTypeInfo();

                if (currentChild == null)
                    return false;
            }
            return false;
        }
コード例 #19
0
        /// <summary>
        /// Registers a new type to be compiled.
        /// </summary>
        /// <param name="type">the type to register</param>
        public void RegisterInterface(TypeInfo type)
        {
            logger.LogDebug($"Registering the interface: {type.FullName}");

            var fullyQualifiedClassName = fauxDiscovery.GetImplementationNameFor(type);

            if (fullyQualifiedClassName != null)
            {
                // already registered
                return;
            }

            var binding        = type.GetCustomAttribute <HystrixFauxClientAttribute>() == null ? BindingType.Core : BindingType.Hystrix;
            var sourceCodeList = serviceClassGenerators[binding].GenerateSource(type, out fullyQualifiedClassName);

            fauxDiscovery.RegisterType(type, fullyQualifiedClassName);

            foreach (var sourceCode in sourceCodeList)
            {
#if NETSTANDARD
                syntaxTrees.Add(SyntaxFactory.ParseSyntaxTree(sourceCode));
#else
                codeSources.Add(sourceCode);
#endif
            }

            logger.LogDebug($"Finished compiling the syntax tree for {fullyQualifiedClassName} generated from {type.FullName}");
        }
コード例 #20
0
ファイル: LifetimeFeature.cs プロジェクト: ESgarbi/corefx
        public override CompositeActivator RewriteActivator(
            TypeInfo partType,
            CompositeActivator activatorBody,
            IDictionary<string, object> partMetadata,
            IEnumerable<CompositionDependency> dependencies)
        {
            if (!ContractHelpers.IsShared(partMetadata))
                return activatorBody;

            object sharingBoundaryMetadata;
            if (!partMetadata.TryGetValue(SharingBoundaryPartMetadataName, out sharingBoundaryMetadata))
                sharingBoundaryMetadata = null;

            var sharingBoundary = (string)sharingBoundaryMetadata;
            var sharingKey = LifetimeContext.AllocateSharingId();

            return (c, o) =>
            {
                var scope = c.FindContextWithin(sharingBoundary);
                if (object.ReferenceEquals(scope, c))
                    return scope.GetOrCreate(sharingKey, o, activatorBody);
                else
                    return CompositionOperation.Run(scope, (c1, o1) => c1.GetOrCreate(sharingKey, o1, activatorBody));
            };
        }
コード例 #21
0
        /// <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));
            }
        }
コード例 #22
0
        private static IEnumerable<TagHelperDescriptor> BuildTagHelperDescriptors(
            TypeInfo typeInfo,
            string assemblyName,
            IEnumerable<TagHelperAttributeDescriptor> attributeDescriptors,
            IEnumerable<TargetElementAttribute> targetElementAttributes)
        {
            var typeName = typeInfo.FullName;

            // If there isn't an attribute specifying the tag name derive it from the name
            if (!targetElementAttributes.Any())
            {
                var name = typeInfo.Name;

                if (name.EndsWith(TagHelperNameEnding, StringComparison.OrdinalIgnoreCase))
                {
                    name = name.Substring(0, name.Length - TagHelperNameEnding.Length);
                }

                return new[]
                {
                    BuildTagHelperDescriptor(
                        ToHtmlCase(name),
                        typeName,
                        assemblyName,
                        attributeDescriptors,
                        requiredAttributes: Enumerable.Empty<string>())
                };
            }

            return targetElementAttributes.Select(
                attribute => BuildTagHelperDescriptor(typeName, assemblyName, attributeDescriptors, attribute));
        }
コード例 #23
0
 public void AddController(TypeInfo controllerTypeInfo)
 {
     if (IsValidController(controllerTypeInfo))
     {
         ControllersType.Add(controllerTypeInfo);
     }
 }
コード例 #24
0
 public PluginInfo this[TypeInfo type]
 {
     get
     {
         return pluginInfoList.SingleOrDefault(t => t.Assembly == type.Assembly);
     }
 }
コード例 #25
0
        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;
        }
コード例 #26
0
        private static void CreateObjectPropertyGraphs(TypeInfo cls, ObjectGraph obj)
        {
            foreach (var p in cls.GetProperties().Where(w => w.MemberType == MemberTypes.Property))
            {
                var pg = new PropertyGraph
                {
                    Name          = _nullableRegex.IsMatch(p.Name) ? _nullableRegex.Match(p.Name).Value : p.Name,
                    SourceType    = p.PropertyType.GetFormattedName(true),
                    IsKeyProperty = p.Name.EndsWith("Id", StringComparison.CurrentCultureIgnoreCase), //NOTE: cheesy
                };

                foreach (var m in p.GetAccessors())
                {
                    if (m.Name.StartsWith("get_"))
                    {
                        pg.GetterVisibility = (m.IsPublic) ? MethodVisibilities.Public :
                                              m.IsPrivate ? MethodVisibilities.Private : MethodVisibilities.Protected;
                    }

                    if (m.Name.StartsWith("set_"))
                    {
                        pg.SetterVisibility = (m.IsPublic) ? MethodVisibilities.Public :
                                              m.IsPrivate ? MethodVisibilities.Private : MethodVisibilities.Protected;
                    }
                }

                obj.Properties.Add(pg);
                Text.GrayLine(
                    $"\tProperty: {p.Name}, Type: {p.PropertyType.GetFormattedName()}, Get: {Enum.GetName(typeof(MethodVisibilities), pg.GetterVisibility)}, Set: {Enum.GetName(typeof(MethodVisibilities), pg.SetterVisibility)}");
            }
        }
コード例 #27
0
        private static string FormatNonGenericTypeName(TypeInfo typeInfo, CommonTypeNameFormatterOptions options)
        {
            if (options.ShowNamespaces)
            {
                return typeInfo.FullName.Replace('+', '.');
            }

            if (typeInfo.DeclaringType == null)
            {
                return typeInfo.Name;
            }

            var stack = ArrayBuilder<string>.GetInstance();

            do
            {
                stack.Push(typeInfo.Name);
                typeInfo = typeInfo.DeclaringType?.GetTypeInfo();
            } while (typeInfo != null);

            stack.ReverseContents();
            var typeName = string.Join(".", stack);
            stack.Free();

            return typeName;
        }
コード例 #28
0
        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;
            }
        }
コード例 #29
0
ファイル: EntityProcessor.cs プロジェクト: psowinski/xenko
        /// <summary>
        /// Initializes a new instance of the <see cref="EntityProcessor"/> class.
        /// </summary>
        /// <param name="mainComponentType">Type of the main component.</param>
        /// <param name="additionalTypes">The additional types required by this processor.</param>
        /// <exception cref="System.ArgumentNullException">If parameteters are null</exception>
        /// <exception cref="System.ArgumentException">If a type does not inherit from EntityComponent</exception>
        protected EntityProcessor(Type mainComponentType, Type[] additionalTypes)
        {
            if (mainComponentType == null) throw new ArgumentNullException(nameof(mainComponentType));
            if (additionalTypes == null) throw new ArgumentNullException(nameof(additionalTypes));

            MainComponentType = mainComponentType;
            mainTypeInfo = MainComponentType.GetTypeInfo();
            Enabled = true;

            RequiredTypes = new TypeInfo[additionalTypes.Length];

            // Check that types are valid
            for (int i = 0; i < additionalTypes.Length; i++)
            {
                var requiredType = additionalTypes[i];
                if (!typeof(EntityComponent).GetTypeInfo().IsAssignableFrom(requiredType.GetTypeInfo()))
                {
                    throw new ArgumentException($"Invalid required type [{requiredType}]. Expecting only an EntityComponent type");
                }

                RequiredTypes[i] = requiredType.GetTypeInfo();
            }

            if (RequiredTypes.Length > 0)
            {
                componentTypesSupportedAsRequired = new Dictionary<TypeInfo, bool>();
            }

            UpdateProfilingKey = new ProfilingKey(GameProfilingKeys.GameUpdate, this.GetType().Name);
            DrawProfilingKey = new ProfilingKey(GameProfilingKeys.GameDraw, this.GetType().Name);
        }
コード例 #30
0
        private async Task <MethodInfo> CreateFunctionTarget(CancellationToken cancellationToken)
        {
            try
            {
                await VerifyPackageReferencesAsync();

                ICompilation      compilation       = _compilationService.GetFunctionCompilation(Metadata);
                FunctionSignature functionSignature = compilation.GetEntryPointSignature(_functionEntryPointResolver);

                ImmutableArray <Diagnostic> bindingDiagnostics = ValidateFunctionBindingArguments(functionSignature, _triggerInputName, _inputBindings, _outputBindings, throwIfFailed: true);
                TraceCompilationDiagnostics(bindingDiagnostics);

                Assembly assembly = compilation.EmitAndLoad(cancellationToken);
                _assemblyLoader.CreateOrUpdateContext(Metadata, assembly, _metadataResolver, TraceWriter);

                // Get our function entry point
                _functionSignature = functionSignature;
                System.Reflection.TypeInfo scriptType = assembly.DefinedTypes
                                                        .FirstOrDefault(t => string.Compare(t.Name, functionSignature.ParentTypeName, StringComparison.Ordinal) == 0);

                return(_functionEntryPointResolver.GetFunctionEntryPoint(scriptType.DeclaredMethods.ToList()));
            }
            catch (CompilationErrorException ex)
            {
                TraceOnPrimaryHost("Function compilation error", TraceLevel.Error);
                TraceCompilationDiagnostics(ex.Diagnostics);
                throw;
            }
        }
コード例 #31
0
        private bool DerivesFromController(TypeInfo typeInfo, ISet<Assembly> candidateAssemblies)
        {
            while (typeInfo != ObjectTypeInfo)
            {
                var baseTypeInfo = typeInfo.BaseType.GetTypeInfo();

                // A base type will be treated as a controller if
                // a) it ends in the term "Controller" and
                // b) it's assembly is one of the candidate assemblies we're considering. This ensures that the assembly
                // the base type is declared in references Mvc.
                if (baseTypeInfo.Name.EndsWith(ControllerTypeName, StringComparison.Ordinal) &&
                    candidateAssemblies.Contains(baseTypeInfo.Assembly))
                {
                    return true;
                }

                // c). The base type is called 'Controller.
                if (string.Equals(baseTypeInfo.Name, ControllerTypeName, StringComparison.Ordinal))
                {
                    return true;
                }

                typeInfo = baseTypeInfo;
            }

            return false;
        }
コード例 #32
0
        public static MethodInfo FindSyncMethod(TypeInfo componentType, object[] args)
        {
            if (componentType == null)
            {
                throw new ArgumentNullException(nameof(componentType));
            }

            var method = GetMethod(componentType, args, SyncMethodName);
            if (method == null)
            {
                return null;
            }

            if (method.ReturnType == typeof(void))
            {
                throw new InvalidOperationException(
                    Resources.FormatViewComponent_SyncMethod_ShouldReturnValue(SyncMethodName));
            }
            else if (method.ReturnType.IsAssignableFrom(typeof(Task)))
            {
                throw new InvalidOperationException(
                    Resources.FormatViewComponent_SyncMethod_CannotReturnTask(SyncMethodName, nameof(Task)));
            }

            return method;
        }
コード例 #33
0
        static void EnsureSatisfiesClassConstraints(TypeInfo[] typeParameters, TypeInfo[] typeArguments, object definition, SigTypeContext typeContext)
        {
            if (typeParameters.Length != typeArguments.Length)
            {
                throw new ArgumentException(SR.Argument_GenericArgsCount);
            }

            // Do sanity validation of all arguments first. The actual constraint validation can fail in unexpected ways 
            // if it hits SigTypeContext with these never valid types.
            for (int i = 0; i < typeParameters.Length; i++)
            {
                TypeInfo actualArg = typeArguments[i];

                if (actualArg.IsSystemVoid() || (actualArg.HasElementType && !actualArg.IsArray))
                {
                    throw new ArgumentException(SR.Format(SR.Argument_NeverValidGenericArgument, actualArg));
                }
            }

            for (int i = 0; i < typeParameters.Length; i++)
            {
                TypeInfo formalArg = typeParameters[i];
                TypeInfo actualArg = typeArguments[i];

                if (!formalArg.SatisfiesConstraints(typeContext, actualArg))
                {
                    throw new ArgumentException(SR.Format(SR.Argument_ConstraintFailed, actualArg, definition.ToString(), formalArg),
                        String.Format("GenericArguments[{0}]", i));
                }
            }
        }
コード例 #34
0
 static TypeInfo[] TypesToTypeInfos(Type[] types)
 {
     TypeInfo[] result = new TypeInfo[types.Length];
     for (int i = 0; i < types.Length; i++)
         result[i] = types[i].GetTypeInfo();
     return result;
 }
コード例 #35
0
ファイル: SerializeType.cs プロジェクト: SirePi/duality
        /// <summary>
        /// Creates a new SerializeType based on a <see cref="System.Type"/>, gathering all the information that is necessary for serialization.
        /// </summary>
        /// <param name="t"></param>
        public SerializeType(Type t)
        {
            this.type = t.GetTypeInfo();
            this.typeString = t.GetTypeId();
            this.dataType = GetDataType(this.type);
            this.dontSerialize = this.type.HasAttributeCached<DontSerializeAttribute>();
            this.defaultValue = this.type.GetDefaultOf();

            if (this.dataType == DataType.Struct)
            {
                // Retrieve all fields that are not flagged not to be serialized
                IEnumerable<FieldInfo> filteredFields = this.type
                    .DeclaredFieldsDeep()
                    .Where(f => !f.IsStatic && !f.HasAttributeCached<DontSerializeAttribute>());

                // Ugly hack to skip .Net collection _syncRoot fields.
                // Can't use field.IsNonSerialized, because that doesn't exist in the PCL profile,
                // and implementing a whole filtering system just for this would be overkill.
                filteredFields = filteredFields
                    .Where(f => !(
                        f.FieldType == typeof(object) &&
                        f.Name == "_syncRoot" &&
                        typeof(System.Collections.ICollection).GetTypeInfo().IsAssignableFrom(f.DeclaringType.GetTypeInfo())));

                // Store the filtered fields in a fixed form
                this.fields = filteredFields.ToArray();
                this.fields.StableSort((a, b) => string.Compare(a.Name, b.Name));
            }
            else
            {
                this.fields = new FieldInfo[0];
            }
        }
コード例 #36
0
ファイル: ControllerModel.cs プロジェクト: huoxudong125/Mvc
        public ControllerModel(
            TypeInfo controllerType,
            IReadOnlyList<object> attributes)
        {
            if (controllerType == null)
            {
                throw new ArgumentNullException(nameof(controllerType));
            }

            if (attributes == null)
            {
                throw new ArgumentNullException(nameof(attributes));
            }

            ControllerType = controllerType;

            Actions = new List<ActionModel>();
            ApiExplorer = new ApiExplorerModel();
            Attributes = new List<object>(attributes);
            AttributeRoutes = new List<AttributeRouteModel>();
            ActionConstraints = new List<IActionConstraintMetadata>();
            Filters = new List<IFilterMetadata>();
            RouteConstraints = new List<IRouteConstraintProvider>();
            Properties = new Dictionary<object, object>();
            ControllerProperties = new List<PropertyModel>();
        }
コード例 #37
0
 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);
 }
コード例 #38
0
        public static CreateObject CreateConstructorMethod(Type objType, TypeInfo objTypeInfo = null)
        {
            CreateObject c;
            if (objTypeInfo == null)
                objTypeInfo = objType.GetTypeInfo();

            var n = objTypeInfo.Name + ".ctor";
            if(objTypeInfo.IsClass)
            {
                var dynMethod = new DynamicMethod(n, objType, Type.EmptyTypes);
                var ilGen = dynMethod.GetILGenerator();
                var ct = objTypeInfo.GetConstructor(Type.EmptyTypes)
                    ?? objTypeInfo.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null);
                if (ct == null)
                    return null;
                ilGen.Emit(OpCodes.Newobj, ct);
                ilGen.Emit(OpCodes.Ret);
                c = (CreateObject)dynMethod.CreateDelegate(typeof(CreateObject));
            }
            else
            {
                var dynMethod = new DynamicMethod(n, typeof(object), null, objType);
                var ilGen = dynMethod.GetILGenerator();
                var lv = ilGen.DeclareLocal(objType);
                ilGen.Emit(OpCodes.Ldloca_S, lv);
                ilGen.Emit(OpCodes.Initobj, objType);
                ilGen.Emit(OpCodes.Ldloc_0);
                ilGen.Emit(OpCodes.Box, objType);
                ilGen.Emit(OpCodes.Ret);
                c = (CreateObject)dynMethod.CreateDelegate(typeof(CreateObject));
            }

            return c;
        }
コード例 #39
0
        private static void CreateObjectMethodGraphs(GenesisContext genesis, TypeInfo cls, ObjectGraph obj)
        {
            var events = new List <string>();

            foreach (var m in cls.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
            {
                if (m.Name.StartsWith("get_") || m.Name.StartsWith("set_"))
                {
                    continue; //already did property accessors
                }
                if (m.Name.StartsWith("add_") || m.Name.StartsWith("remove_"))
                {
                    var name = m.Name.Split('_')[1]; //just get the event Name
                    if (!events.Contains(name))
                    {
                        events.Add(name);
                    }
                }

                Debug.WriteLine($@"Method:{(_nullableRegex.IsMatch(m.Name) ? _nullableRegex.Match(m.Name).Value : m.Name)}");
                var methodGraph = new MethodGraph
                {
                    Name                      = _nullableRegex.IsMatch(m.Name) ? _nullableRegex.Match(m.Name).Value : m.Name,
                    MethodVisibility          = MethodVisibilities.Public,
                    ReturnDataType            = m.ReturnType,
                    ReturnTypeFormattedName   = m.ReturnType.GetFormattedName(),
                    HasGenericParams          = m.ContainsGenericParameters,
                    IsGeneric                 = m.IsGenericMethod,
                    FormattedGenericArguments = m.GetGenericArguments().ToFormattedNames(),
                };

                foreach (var par in m.GetParameters().OrderBy(o => o.Position))
                {
                    var mp = new ParameterGraph
                    {
                        DataType = par.ParameterType,
                        DataTypeFormattedName = par.ParameterType.GetFormattedName(),
                        DisplayName           = par.ParameterType.GetDisplayName(),
                        Name       = par.Name,
                        IsOut      = par.IsOut,
                        IsIn       = par.IsIn,
                        IsOptional = par.IsOptional,
                        Position   = par.Position,
                        IsGeneric  = par.ParameterType.IsGenericType,
                        IsGenericMethodParameter          = par.ParameterType.IsGenericMethodParameter,
                        GenericArgumentFormattedTypeNames = par.ParameterType.GetGenericArguments().ToFormattedNames(),
                    };

                    methodGraph.Parameters.Add(mp);
                }

                obj.Methods.Add(methodGraph);

                Text.GrayLine(
                    $"\tMethod: {m.Name}, Return: {methodGraph.ReturnTypeFormattedName}, Visibility: {(m.IsPublic ? "public" : m.IsPrivate ? "private" : "protected")}");
            }

            genesis.Objects.Add(obj);
        }
コード例 #40
0
        public static TP GetTypeInfo(TP type)
        {
#if NETFX_CORE
            return(type.GetTypeInfo());
#else
            return(type);
#endif
        }
コード例 #41
0
ファイル: SymbolType.cs プロジェクト: treesportrait/coreclr
 public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo)
 {
     if (typeInfo == null)
     {
         return(false);
     }
     return(IsAssignableFrom(typeInfo.AsType()));
 }
コード例 #42
0
 protected WebServiceComplier(TypeInfo type)
 {
     typeInfo     = type;
     newClassName = $"{RootNamespace}.{typeInfo.FullName.Replace(".", string.Empty)}";
     UpdateReferences(GetType().GetTypeInfo().Assembly);
     UpdateReferences(typeInfo.Assembly);
     Define();
 }
コード例 #43
0
        public static System.Type GetTypeFromInfo(TP type)
        {
#if NETFX_CORE
            return(type.AsType());
#else
            return(type);
#endif
        }
コード例 #44
0
        public static bool HasJsonUseTypeHintAttribute(TP tp)
        {
#if WINDOWS_STORE
            return(tp.GetCustomAttribute <JsonUseTypeHintAttribute> (true) != null);
#else
            return(tp.GetCustomAttributes(typeof(JsonUseTypeHintAttribute), true).Length != 0);
#endif
        }
コード例 #45
0
 public static bool IsAnonymous(this System.Reflection.TypeInfo type)
 {
     return(type.Namespace == null &&
            type.IsSealed &&
            (type.Name.StartsWith("<>f__AnonymousType", StringComparison.Ordinal) ||
             type.Name.StartsWith("<>__AnonType", StringComparison.Ordinal) ||
             type.Name.StartsWith("VB$AnonymousType_", StringComparison.Ordinal)) &&
            type.IsDefined(typeof(CompilerGeneratedAttribute), false));
 }
コード例 #46
0
 /// <summary>
 /// Gets a value that indicates if <paramref name="targetTypeInfo"/> is represented using
 /// <paramref name="sourceTypeSymbol"/> in the symbol graph.
 /// </summary>
 /// <param name="sourceTypeSymbol">The <see cref="ITypeSymbol"/>.</param>
 /// <param name="targetTypeInfo">The <see cref="System.Reflection.TypeInfo"/>.</param>
 /// <returns><c>true</c> if <paramref name="targetTypeInfo"/> is a symbol for
 /// <paramref name="sourceTypeSymbol"/>.</returns>
 public static bool IsType(
     ITypeSymbol sourceTypeSymbol,
     System.Reflection.TypeInfo targetTypeInfo)
 {
     return(string.Equals(
                RuntimeTypeInfo.SanitizeFullName(targetTypeInfo.FullName),
                RuntimeTypeInfo.SanitizeFullName(GetFullName(sourceTypeSymbol)),
                StringComparison.Ordinal));
 }
コード例 #47
0
 private static bool UseCollectionFormat(
     IEnumerable <CommonObjectFormatter.Visitor.FormattedMember> members,
     System.Reflection.TypeInfo originalType)
 {
     if (IntrospectionExtensions.GetTypeInfo(typeof(IEnumerable)).IsAssignableFrom(originalType))
     {
         return(Enumerable.All <CommonObjectFormatter.Visitor.FormattedMember>(members, member => member.Index >= 0));
     }
     return(false);
 }
コード例 #48
0
        public static TMemberInfo EnsureFound <TMemberInfo>(TypeInfo type, string name, Func <TypeInfo, string, TMemberInfo> getMember)
        {
            var member = getMember(type, name);

            if (member == null)
            {
                throw new MissingMemberException($"Member '{name}' was not found on {type}.");
            }
            return(member);
        }
コード例 #49
0
        public void ResolveMemberInfo_should_return_original_field_info()
        {
            var typeResolver = new TypeResolver();

            System.Reflection.TypeInfo   type           = typeof(TypeHiding).GetTypeInfo();
            System.Reflection.FieldInfo  fieldInfo      = type.GetDeclaredField(nameof(TypeHiding.Field));
            Aqua.TypeSystem.FieldInfo    mappedField    = new Aqua.TypeSystem.FieldInfo(fieldInfo);
            System.Reflection.MemberInfo resolvedMember = mappedField.ResolveMemberInfo(typeResolver);

            resolvedMember.ShouldBe(fieldInfo);
        }
コード例 #50
0
        public void ResolveMemberInfo_should_return_original_property_info()
        {
            var typeResolver = new TypeResolver();

            System.Reflection.TypeInfo     type           = typeof(TypeHiding).GetTypeInfo();
            System.Reflection.PropertyInfo propertyInfo   = type.GetDeclaredProperty(nameof(TypeHiding.Property));
            Aqua.TypeSystem.PropertyInfo   mappedProperty = new Aqua.TypeSystem.PropertyInfo(propertyInfo);
            System.Reflection.MemberInfo   resolvedMember = mappedProperty.ResolveMemberInfo(typeResolver);

            resolvedMember.ShouldBe(propertyInfo);
        }
コード例 #51
0
        public void ResolveMethod_should_return_original_method_info()
        {
            var typeResolver = new TypeResolver();

            System.Reflection.TypeInfo   type           = typeof(TypeHiding).GetTypeInfo();
            System.Reflection.MethodInfo methodInfo     = type.GetDeclaredMethod(nameof(TypeHiding.Method));
            Aqua.TypeSystem.MethodInfo   mappedMethod   = new Aqua.TypeSystem.MethodInfo(methodInfo);
            System.Reflection.MethodInfo resolvedMethod = mappedMethod.ResolveMethod(typeResolver);

            resolvedMethod.ShouldBe(methodInfo);
        }
コード例 #52
0
        } // End Function GetGetter

        // ------------------------------------



        public static System.Reflection.MemberInfo[] GetFieldsAndProperties(System.Type t)
        {
            System.Reflection.TypeInfo ti = System.Reflection.IntrospectionExtensions.GetTypeInfo(t);

            System.Reflection.FieldInfo[]    fis = ti.GetFields();
            System.Reflection.PropertyInfo[] pis = ti.GetProperties();
            System.Reflection.MemberInfo[]   mis = new System.Reflection.MemberInfo[fis.Length + pis.Length];
            System.Array.Copy(fis, mis, fis.Length);
            System.Array.Copy(pis, 0, mis, fis.Length, pis.Length);

            return(mis);
        } // End Function GetFieldsAndProperties
コード例 #53
0
ファイル: CSharpTests.cs プロジェクト: SISW-MOM/IoTGateway
        private static string GetLocation(Type T)
        {
            System.Reflection.TypeInfo TI = T.GetTypeInfo();
            string s = TI.Assembly.Location;

            if (!string.IsNullOrEmpty(s))
            {
                return(s);
            }

            return(Path.Combine(Path.GetDirectoryName(GetLocation(typeof(CSharpTests))), TI.Module.ScopeName));
        }
コード例 #54
0
        private static ImmutableDictionary <SyntaxKind, IDeclarationHandler> InitializeHandlerLookup()
        {
            System.Reflection.TypeInfo handlerTypeInfo   = typeof(IDeclarationHandler).GetTypeInfo();
            System.Reflection.TypeInfo containerTypeInfo = typeof(DeclarationHandlers).GetTypeInfo();

            System.Reflection.TypeInfo[] handlerTypes = containerTypeInfo.DeclaredNestedTypes
                                                        .Where(t => handlerTypeInfo.IsAssignableFrom(t))
                                                        .ToArray();

            return(handlerTypes
                   .Select(t => Activator.CreateInstance(t.AsType()) as IDeclarationHandler)
                   .ToImmutableDictionary(handler => handler.Kind));
        }
コード例 #55
0
        private static ImmutableArray <dynamic> Create(System.Reflection.TypeInfo rowType, params Action <dynamic>[] callbacks)
        {
            var builder = ImmutableArray.CreateBuilder <dynamic>();

            foreach (var callback in callbacks)
            {
                var row = Activator.CreateInstance(rowType);
                callback(row);
                builder.Add(row);
            }

            return(builder.ToImmutable());
        }
コード例 #56
0
        //-----------------------------------------------------------------------------------------------------------------------------------------------------

        private static bool IsNullableValueType(System.Reflection.TypeInfo typeInfo, out Type underlyingValueType)
        {
            if (typeInfo.IsGenericType &&
                !typeInfo.IsGenericTypeDefinition &&
                typeInfo.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                underlyingValueType = typeInfo.GetGenericArguments()[0];
                return(true);
            }

            underlyingValueType = null;
            return(false);
        }
コード例 #57
0
        //public string CreateInterface(string srvName,string route,string requestMethod,string returnType, List<ParameterModel> paramsList)
        // {
        //     logger.LogDebug($"Create a interface by servcer name : {srvName}");
        //     var sourceCode = WebServiceClassGenerator.GenerateInterfaceSource(srvName, route,requestMethod, returnType,paramsList, out var fullyQualifiedClassName);
        //     syntaxTrees.Add(SyntaxFactory.ParseSyntaxTree(sourceCode));

        //     logger.LogDebug($"Finished compiling the syntax tree for {fullyQualifiedClassName}");

        //     return fullyQualifiedClassName;
        // }

        public string RegisterInterface(TypeInfo type)
        {
            logger.LogDebug($"Registering the interface: {type.FullName}");

            UpdateReferences(type.Assembly);
            var sourceCode = WebServiceClassGenerator.GenerateSource(type, out var fullyQualifiedClassName);

            syntaxTrees.Add(SyntaxFactory.ParseSyntaxTree(sourceCode));

            logger.LogDebug($"Finished compiling the syntax tree for {fullyQualifiedClassName} generated from {type.FullName}");

            return(fullyQualifiedClassName);
        }
コード例 #58
0
 internal static string GetContentPropertyName(System.Reflection.TypeInfo typeInfo)
 {
     while (typeInfo != null)
     {
         var propName = GetContentPropertyName(typeInfo.CustomAttributes);
         if (propName != null)
         {
             return(propName);
         }
         typeInfo = typeInfo?.BaseType?.GetTypeInfo();
     }
     return(null);
 }
コード例 #59
0
            private void FormatKeyValuePair(CommonObjectFormatter.Builder result, object obj)
            {
                System.Reflection.TypeInfo typeInfo = IntrospectionExtensions.GetTypeInfo(obj.GetType());
                object obj1 = typeInfo.GetDeclaredProperty("Key").GetValue(obj, Array.Empty <object>());
                object obj2 = typeInfo.GetDeclaredProperty("Value").GetValue(obj, Array.Empty <object>());

                result.AppendGroupOpening();
                result.AppendCollectionItemSeparator(true);
                this.FormatObjectRecursive(result, obj1, false);
                result.AppendCollectionItemSeparator(false);
                this.FormatObjectRecursive(result, obj2, false);
                result.AppendGroupClosing();
            }
コード例 #60
0
        static IEnumerable <T> GetParts <T>(Type type, Func <System.Reflection.TypeInfo, IEnumerable <T> > selector)
        {
            Type t = type;

            while (t != null)
            {
                System.Reflection.TypeInfo ti = t.GetTypeInfo();
                foreach (T f in selector(ti))
                {
                    yield return(f);
                }
                t = ti.BaseType;
            }
        }