Beispiel #1
0
        internal IContentSerializer GetSerializer(Type storageType, Type objectType)
        {
            lock (contentSerializers)
            {
                // Process serializer attributes of objectType
                foreach (var contentSerializer in GetSerializers(objectType))
                {
                    if (objectType.GetTypeInfo().IsAssignableFrom(contentSerializer.ActualType.GetTypeInfo()) && (storageType == null || contentSerializer.SerializationType == storageType))
                        return contentSerializer;
                }

                // Process serializer attributes of storageType
                if (storageType != null)
                {
                    foreach (var contentSerializer in GetSerializers(storageType))
                    {
                        if (objectType.GetTypeInfo().IsAssignableFrom(contentSerializer.ActualType.GetTypeInfo()) && contentSerializer.SerializationType == storageType)
                            return contentSerializer;
                    }
                }

                //foreach (var contentSerializerGroup in contentSerializers)
                //{
                //    if (contentSerializerGroup.Key.GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo()))
                //    {
                //        return GetSerializer(contentSerializerGroup.Value, storageType);
                //    }
                //}
            }

            return null;
        }
        public ActionsGroupNode ReadController(Type type, AssemblyNode assemblyNode)
        {
            var controller = new ActionsGroupNode
            {
                Assembly = assemblyNode
            };

            string routePrefix = null;
            var routePrefixAttribute = type.GetTypeInfo().GetCustomAttribute<RouteAttribute>(false) ?? type.GetTypeInfo().GetCustomAttribute<RouteAttribute>();
            if (routePrefixAttribute != null)
            {
                routePrefix = routePrefixAttribute.Template;
            }

            controller.Name = type.Name.Replace("Controller", string.Empty);
            controller.Name = NameCleaner.Replace(controller.Name, string.Empty);
            controller.Documentation = documentation.GetDocumentation(type);

            foreach (var methodInfo in type.GetMethods().Where(x => x.IsPublic))
            {
                if (methodInfo.GetCustomAttribute<NonActionAttribute>() != null) continue;
                if (methodInfo.IsSpecialName) continue;

                var action = ReadAction(routePrefix, methodInfo, controller);
                if (action != null)
                {
                    controller.Actions.Add(action);
                }
            }
            return controller;
        }
Beispiel #3
0
        private static object InvokeMemberOnType(Type type, object target, string name, object[] args)
        {
            BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

            try
            {
                // Try to invokethe method
                return type.InvokeMember(
                    name,
                    BindingFlags.InvokeMethod | bindingFlags,
                    null,
                    target,
                    args);
            }
            catch (MissingMethodException)
            {
                // If we couldn't find the method, try on the base class
                if (type.GetTypeInfo().BaseType != null)
                {
                    return InvokeMemberOnType(type.GetTypeInfo().BaseType, target, name, args);
                }
                //Don't care if the method don't exist.
                return null;
            }
        }
Beispiel #4
0
            public EnumDescriptor(Type type)
            {
                _type = type;
                _enum2name = new Dictionary<object, string>();
                _name2enum = new Dictionary<string, object>();

                var names = Enum.GetNames(type);

                foreach (string name in names)
                {
                    #if NET40
                    var member = type.GetFields().Single(x => x.Name == name);
                    #elif !PCL
                    var member = type.GetTypeInfo().GetRuntimeFields().Single((x) => x.Name == name);
                    #else
                    var member = type.GetTypeInfo().GetDeclaredField(name);
                    #endif
                    var value = Enum.Parse(type, name);
                    var realName = name;

                    #if NET40
                    var attr = (EnumValueAttribute)member.GetCustomAttributes(typeof(EnumValueAttribute), false).FirstOrDefault();
                    #else
                    var attr = member.GetCustomAttribute<EnumValueAttribute>();
                    #endif

                    if (attr != null)
                        realName = attr.Value;

                    _enum2name[value] = realName;
                    _name2enum[realName] = value;
                }
            }
		/// <summary>
		/// Gets the type converter for the specified type.
		/// </summary>
		/// <returns>The type converter, or null if the type has no defined converter.</returns>
		/// <param name="type">Type to get the converter for.</param>
		public static TypeConverter GetConverter(Type type)
		{
			var attr = type.GetTypeInfo().GetCustomAttribute<TypeConverterAttribute>();
			Type converterType = null;
			if (attr != null)
				converterType = Type.GetType(attr.ConverterTypeName);
			if (converterType == null)
			{
				if (!converters.TryGetValue(type, out converterType))
				{
					if (type.GetTypeInfo().IsGenericType && type.GetTypeInfo().GetGenericTypeDefinition() == typeof(Nullable<>))
						return new NullableConverter(type);
					if (type.GetTypeInfo().IsEnum)
						return new EnumConverter(type);
					if (typeof(Delegate).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()))
						return new EventConverter();
				}
			}
			
			if (converterType != null)
			{
				if (converterType.GetTypeInfo().GetConstructors().Any(r => r.GetParameters().Select(p => p.ParameterType).SequenceEqual(new [] { typeof(Type) })))
					return Activator.CreateInstance(converterType, type) as TypeConverter;
				return Activator.CreateInstance(converterType) as TypeConverter;
			}
			
			return null;
		}
        private static bool checkGenericType(Type pluggedType, Type pluginType)
        {
            if (pluginType.GetTypeInfo().IsAssignableFrom(pluggedType.GetTypeInfo())) return true;

            // check interfaces
            foreach (var type in pluggedType.GetInterfaces())
            {
                if (!type.GetTypeInfo().IsGenericType)
                {
                    continue;
                }

                if (type.GetGenericTypeDefinition() == pluginType)
                {
                    return true;
                }
            }

            if (pluggedType.GetTypeInfo().BaseType.GetTypeInfo().IsGenericType)
            {
                var baseType = pluggedType.GetTypeInfo().BaseType.GetGenericTypeDefinition();

                if (baseType == pluginType)
                {
                    return true;
                }
                else
                {
                    return CanBeCast(pluginType, baseType);
                }
            }

            return false;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="EnumTypeConfiguration"/> class.
        /// </summary>
        public EnumTypeConfiguration(ODataModelBuilder builder, Type clrType)
        {
            if (builder == null)
            {
                throw Error.ArgumentNull("builder");
            }
            if (clrType == null)
            {
                throw Error.ArgumentNull("clrType");
            }

            if (!clrType.GetTypeInfo().IsEnum)
            {
                throw Error.Argument("clrType", SRResources.TypeCannotBeEnum, clrType.FullName);
            }

            ClrType = clrType;
            IsFlags = clrType.GetTypeInfo().GetCustomAttributes(typeof(FlagsAttribute), false).Any();
            UnderlyingType = Enum.GetUnderlyingType(clrType);
            ModelBuilder = builder;
            _name = clrType.EdmName();
            _namespace = clrType.Namespace ?? DefaultNamespace;
            ExplicitMembers = new Dictionary<Enum, EnumMemberConfiguration>();
            RemovedMembers = new List<Enum>();
        }
        private static ProxyGeneratorResult GenerateProxy(
            Type typeOfProxy,
            ProxyGenerationOptions options,
            IEnumerable<Type> additionalInterfacesToImplement,
            IEnumerable<object> argumentsForConstructor,
            IFakeCallProcessorProvider fakeCallProcessorProvider)
        {
            Guard.AgainstNull(typeOfProxy, nameof(typeOfProxy));
            Guard.AgainstNull(additionalInterfacesToImplement, nameof(additionalInterfacesToImplement));
            Guard.AgainstNull(fakeCallProcessorProvider, nameof(fakeCallProcessorProvider));

            if (typeOfProxy.GetTypeInfo().IsValueType)
            {
                return GetProxyResultForValueType(typeOfProxy);
            }

            if (typeOfProxy.GetTypeInfo().IsSealed)
            {
                return new ProxyGeneratorResult(DynamicProxyResources.ProxyIsSealedTypeMessage.FormatInvariant(typeOfProxy));
            }

            GuardAgainstConstructorArgumentsForInterfaceType(typeOfProxy, argumentsForConstructor);

            return CreateProxyGeneratorResult(typeOfProxy, options, additionalInterfacesToImplement, argumentsForConstructor, fakeCallProcessorProvider);
        }
		private Tuple<IList<MethodInfo>, IList<MethodInfo>> FindGetters(Type viewModelType)
		{
			Tuple<IList<MethodInfo>, IList<MethodInfo>> methodInfos;
			if (!_knownTypes.TryGetValue(viewModelType, out methodInfos))
			{
				var commandTypeInfo = typeof(ICommand).GetTypeInfo();
				var observablePropertyType = typeof(IObservableProperty<>);
				var ovvmTypeTypeInfo = typeof(IObservableViewModel).GetTypeInfo();
				var propertieGetters = viewModelType.GetTypeInfo()
												.DeclaredProperties
												.Where(p => commandTypeInfo.IsAssignableFrom(p.PropertyType.GetTypeInfo()) ||
															ovvmTypeTypeInfo.IsAssignableFrom(p.PropertyType.GetTypeInfo()) ||
															IsGenericTypeDefinitionProperty(p.PropertyType, observablePropertyType))
												.Select(p => p.GetMethod)
												.ToList();

				//find inner view models  recursively
				var viewModelTypeInfo = typeof(IViewModel).GetTypeInfo();
				var childrenGetters = viewModelType.GetTypeInfo()
												   .DeclaredProperties
												   .Where(p => viewModelTypeInfo.IsAssignableFrom(p.PropertyType.GetTypeInfo()))
												   .Select(p => p.GetMethod)
												   .ToList();

				methodInfos = new Tuple<IList<MethodInfo>, IList<MethodInfo>>(propertieGetters, childrenGetters);
				_knownTypes.Add(viewModelType, methodInfos);
			}
			return methodInfos;
		}
        private static ITypeDetails CreateNew(Type type)
        {
            var readibles = new List<IPropertyReader>();
            var writables = new List<IPropertyWriter>();

            foreach (var pi in type.GetTypeInfo().GetProperties())
            {
                var propertyInfo = CreatePropertyAccessor(type, pi);

                if (propertyInfo == null)
                {
                    continue;
                }

                var propertyReader = propertyInfo as IPropertyReader;
                if (propertyReader != null)
                {
                    readibles.Add(propertyReader);
                }

                var propertyWriter = propertyInfo as IPropertyWriter;
                if (propertyWriter != null)
                {
                    writables.Add(propertyWriter);
                }
            }

            var defaultValue = type.GetTypeInfo().IsValueType ? Activator.CreateInstance(type) : null;
            return new TypeDetails(type, defaultValue, readibles.ToArray(), writables.ToArray());
        }
Beispiel #11
0
        private static Type FindIEnumerable(Type seqType)
        {
            if (seqType == null || seqType == typeof(string))
                return null;
            if (seqType.IsArray)
                return typeof(IEnumerable<>).MakeGenericType(seqType.GetElementType());
            if (seqType.GetTypeInfo().IsGenericType)
            {
                foreach (Type arg in seqType.GetGenericArguments())
                {
                    Type ienum = typeof(IEnumerable<>).MakeGenericType(arg);
                    if (ienum.IsAssignableFrom(seqType))
                    {
                        return ienum;
                    }
                }
            }
            Type[] ifaces = seqType.GetInterfaces();
            if (ifaces != null && ifaces.Length > 0)
            {
                foreach (Type iface in ifaces)
                {
                    Type ienum = FindIEnumerable(iface);
                    if (ienum != null) return ienum;
                }
            }

            var basetype = seqType.GetTypeInfo().BaseType;
            if (basetype != null && basetype != typeof(object))
            {
                return FindIEnumerable(basetype);
            }
            return null;
        }
Beispiel #12
0
 private static object CreateDictionary(Type dictionaryType)
 {
     Type keyType = dictionaryType.GetTypeInfo().GenericTypeArguments[0];
     Type valueType = dictionaryType.GetTypeInfo().GenericTypeArguments[1];
     var type = typeof(Dictionary<,>).MakeGenericType(keyType, valueType);
     return DelegateFactory.CreateCtor(type)();
 }
Beispiel #13
0
        /// <summary>
        /// A helper to check to see if a generic parameter type meets the specified constraints
        /// </summary>
        /// <param name="genericParameterType">The generic parameter type</param>
        /// <param name="exported">The type parameter on the exported class</param>
        /// <returns>True if the type meets the constraints, otherwise false</returns>
        public static bool DoesTypeMeetGenericConstraints(Type genericParameterType, Type exported)
        {
            bool meets = true;
            var constraints = genericParameterType.GetTypeInfo().GetGenericParameterConstraints();

            foreach (Type constraint in constraints)
            {
                if (constraint.GetTypeInfo().IsInterface)
                {
                    if (exported.GetTypeInfo().GUID == constraint.GetTypeInfo().GUID)
                    {
                        continue;
                    }

                    if (exported.GetTypeInfo().ImplementedInterfaces.Any(x => x.GetTypeInfo().GUID == constraint.GetTypeInfo().GUID))
                    {
                        continue;
                    }

                    meets = false;
                    break;
                }

                if (!constraint.GetTypeInfo().IsAssignableFrom(exported.GetTypeInfo()))
                {
                    meets = false;
                    break;
                }
            }

            return meets;
        }
        /// <summary>
        /// Returns any bindings from the specified collection that match the specified service.
        /// </summary>
        /// <param name="bindings">The multimap of all registered bindings.</param>
        /// <param name="service">The service in question.</param>
        /// <returns>The series of matching bindings.</returns>
        public IEnumerable<IBinding> Resolve(IDictionary<Type, IEnumerable<IBinding>> bindings, Type service)
        {
            if (!service.GetTypeInfo().IsGenericType || service.GetTypeInfo().IsGenericTypeDefinition || !bindings.ContainsKey(service.GetGenericTypeDefinition()))
                return Enumerable.Empty<IBinding>();

            return bindings[service.GetGenericTypeDefinition()];
        }
Beispiel #15
0
        internal IContentSerializer GetSerializer(Type storageType, Type objectType)
        {
            lock (contentSerializers)
            {
                // Process serializer attributes of objectType
                foreach (var contentSerializer in GetSerializers(objectType))
                {
                    if (objectType.GetTypeInfo().IsAssignableFrom(contentSerializer.ActualType.GetTypeInfo()) && (storageType == null || contentSerializer.SerializationType == storageType))
                        return contentSerializer;
                }

                // Process serializer attributes of storageType
                if (storageType != null)
                {
                    foreach (var contentSerializer in GetSerializers(storageType))
                    {
                        if (objectType.GetTypeInfo().IsAssignableFrom(contentSerializer.ActualType.GetTypeInfo()) && contentSerializer.SerializationType == storageType)
                            return contentSerializer;
                    }
                }

                //foreach (var contentSerializerGroup in contentSerializers)
                //{
                //    if (contentSerializerGroup.Key.GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo()))
                //    {
                //        return GetSerializer(contentSerializerGroup.Value, storageType);
                //    }
                //}
            }

            throw new Exception(string.Format("Could not find a serializer for the type [{0}, {1}]", storageType == null ? null : storageType.Name, objectType == null ? null : objectType.Name));
        }
        public Type GetGenericInterface(Type type, Type interfaceType)
        {
            if (!interfaceType.GetTypeInfo().IsGenericTypeDefinition)
            {
                throw new ArgumentException(
                    "The interface must be a generic interface definition: " + interfaceType.Name,
                    "interfaceType");
            }

            // our contract states that we will not return generic interface definitions without generic type arguments
            if (type == interfaceType)
                return null;
            if (type.GetTypeInfo().IsGenericType)
            {
                if (type.GetGenericTypeDefinition() == interfaceType)
                    return type;
            }
            Type[] interfaces = type.GetTypeInfo().ImplementedInterfaces.ToArray();
            for (int i = 0; i < interfaces.Length; i++)
            {
                if (interfaces[i].GetTypeInfo().IsGenericType)
                {
                    if (interfaces[i].GetGenericTypeDefinition() == interfaceType)
                        return interfaces[i];
                }
            }

            return null;
        }
 /// <summary>
 /// Calls GenerateManifest() on the event source passed in, saves the output to a file under 'folder'
 /// and returns the filename under which the manifest was saved.
 /// </summary>
 /// <param name="eventSourceType">The EventSource derived class whose manifest we want saved</param>
 /// <param name="folder">The folder where the manifest will be saved</param>
 /// <returns>The filename under 'folder' that contains the ETW manifest</returns>
 private string SaveEventSourceManifest(Type eventSourceType, string folder)
 {
     var manfilename = Path.Combine(folder, GetPrefixFromType(eventSourceType) + eventSourceType.Name + ".man");
     using (var manfile = new System.IO.StreamWriter(new System.IO.MemoryStream(Encoding.Unicode.GetBytes(manfilename))))
     {
         string man = null;
         string dllName = Path.GetFileName(eventSourceType.GetTypeInfo().Assembly.Location);
         //if (!eventSourceType.GetTypeInfo().Assembly.ReflectionOnly)
         //{
         var baseAssm = eventSourceType.GetTypeInfo().BaseType.GetTypeInfo().Assembly;
         var tyGmf = (baseAssm != null) ? baseAssm.GetType(eventSourceType.GetTypeInfo().BaseType.Namespace + ".EventManifestOptions") : null;
         MethodInfo mi = null;
         if (tyGmf != null)
         {
             //mi = eventSourceType.GetTypeInfo().GetMethod("GenerateManifest", BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public,
             //                               null, new Type[] { typeof(Type), typeof(string), tyGmf }, null);
             mi = eventSourceType.GetTypeInfo().GetDeclaredMethod("GenerateManifest");
         }
         if (mi != null)
         {
             man = (string)mi.Invoke(null, new object[] { eventSourceType, dllName, 2 });
         }
         manfile.Write(man);
     }
     return manfilename;
 }
Beispiel #18
0
        // public methods
        /// <inheritdoc/>
        public override IBsonSerializer GetSerializer(Type type, IBsonSerializerRegistry serializerRegistry)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            var typeInfo = type.GetTypeInfo();
            if (typeInfo.IsGenericType && typeInfo.ContainsGenericParameters)
            {
                var message = string.Format("Generic type {0} has unassigned type parameters.", BsonUtils.GetFriendlyTypeName(type));
                throw new ArgumentException(message, "type");
            }

            Type serializerType;
            if (_serializerTypes.TryGetValue(type, out serializerType))
            {
                return CreateSerializer(serializerType, serializerRegistry);
            }

            if (typeInfo.IsGenericType && !typeInfo.ContainsGenericParameters)
            {
                Type serializerTypeDefinition;
                if (_serializerTypes.TryGetValue(type.GetGenericTypeDefinition(), out serializerTypeDefinition))
                {
                    return CreateGenericSerializer(serializerTypeDefinition, type.GetTypeInfo().GetGenericArguments(), serializerRegistry);
                }
            }

            return null;
        }
        /// <summary>
        /// Coerces the provided value to the destination type.
        /// </summary>
        /// <param name="destinationType">The destination type.</param>
        /// <param name="providedValue">The provided value.</param>
        /// <returns>The coerced value.</returns>
        public static object CoerceValue(Type destinationType, object providedValue)
        {
            if (providedValue == null)
                return GetDefaultValue(destinationType);

            if (destinationType.GetTypeInfo().IsAssignableFrom(providedValue.GetType().GetTypeInfo()))
                return providedValue;

            Func<object, object> customConverter;
            if (CustomConverters.TryGetValue(destinationType, out customConverter))
                return customConverter(providedValue);

            if (destinationType.GetTypeInfo().IsEnum)
            {
                var stringValue = providedValue as string;
                if (stringValue != null)
                    return Enum.Parse(destinationType, stringValue, true);

                return Enum.ToObject(destinationType, providedValue);
            }

            if (typeof(Guid).GetTypeInfo().IsAssignableFrom(destinationType.GetTypeInfo()))
            {
                var stringValue = providedValue as string;
                if (stringValue != null)
                    return new Guid(stringValue);
            }

            return Convert.ChangeType(providedValue, destinationType, CultureInfo.CurrentCulture);
        }
        /// <summary>
        ///     Determines whether this instance can convert the specified object type.
        /// </summary>
        /// <param name="objectType">Type of the object.</param>
        /// <returns></returns>
        public override bool CanConvert(Type objectType)
        {
            if (typeof(IMessageNotification).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo()))
                return true;

            return typeof(ICommentNotification).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
        }
        public PluginFamily Build(Type type)
        {
            if (!type.GetTypeInfo().IsGenericType) return null;

            var basicType = type.GetGenericTypeDefinition();

            if (!_graph.Families.Has(basicType))
            {
                // RIGHT HERE: do the connections thing HERE!
                var connectingTypes = _graph.ConnectedConcretions.Where(x => x.CanBeCastTo(type)).ToArray();
                if (connectingTypes.Any())
                {
                    var family = new PluginFamily(type);
                    connectingTypes.Each(family.AddType);

                    return family;
                }

                return _graph.Families.ToArray().FirstOrDefault(x => type.GetTypeInfo().IsAssignableFrom(x.PluginType.GetTypeInfo()));
            }

            var basicFamily = _graph.Families[basicType];
            var templatedParameterTypes = type.GetGenericArguments();

            return basicFamily.CreateTemplatedClone(templatedParameterTypes.ToArray());
        }
        /// <summary>
        /// Creates an instace of type <paramref name="nodeType"/>.
        /// </summary>
        /// <exception cref="ExpressionNodeInstantiationException">
        /// Thrown if the <paramref name="parseInfo"/> or the <paramref name="additionalConstructorParameters"/> 
        /// do not match expected constructor parameters of the <paramref name="nodeType"/>.
        /// </exception>
        public static IExpressionNode CreateExpressionNode(
        Type nodeType, MethodCallExpressionParseInfo parseInfo, object[] additionalConstructorParameters)
        {
            ArgumentUtility.CheckNotNull ("nodeType", nodeType);
              ArgumentUtility.CheckTypeIsAssignableFrom ("nodeType", nodeType, typeof (IExpressionNode));
              ArgumentUtility.CheckNotNull ("additionalConstructorParameters", additionalConstructorParameters);

            #if NETFX_CORE
              var constructors = nodeType.GetTypeInfo().DeclaredConstructors.Where (c => c.IsPublic).ToArray();
            #else
              var constructors = nodeType.GetTypeInfo().GetConstructors().Where (c => c.IsPublic).ToArray();
            #endif
              if (constructors.Length > 1)
              {
            var message = string.Format (
            "Expression node type '{0}' contains too many constructors. It must only contain a single constructor, allowing null to be passed for any optional arguments.",
            nodeType.FullName);
            throw new ArgumentException (message, "nodeType");
              }

              object[] constructorParameterArray = GetParameterArray (constructors[0], parseInfo, additionalConstructorParameters);
              try
              {
            return (IExpressionNode) constructors[0].Invoke (constructorParameterArray);
              }
              catch (ArgumentException ex)
              {
            var message = GetArgumentMismatchMessage (ex);
            throw new ExpressionNodeInstantiationException (message);
              }
        }
 public static bool IsValidRazorFileInfoCollection(Type type)
 {
     return 
         RazorFileInfoCollectionType.IsAssignableFrom(type) &&
         !type.GetTypeInfo().IsAbstract &&
         !type.GetTypeInfo().ContainsGenericParameters;
 }
Beispiel #24
0
        public static Type GetInterface(this Type type, Type lookInterfaceType)
        {
            if (type == null)
                throw new ArgumentNullException("type");
            if (lookInterfaceType == null)
                throw new ArgumentNullException("lookInterfaceType");

            var typeinfo = lookInterfaceType.GetTypeInfo();
            if (typeinfo .IsGenericTypeDefinition)
            {
                if (typeinfo.IsInterface)
                    foreach (var interfaceType in type.GetTypeInfo().ImplementedInterfaces)
                        if (interfaceType.GetTypeInfo().IsGenericType
                            && interfaceType.GetGenericTypeDefinition() == lookInterfaceType)
                            return interfaceType;

                for (Type t = type; t != null; t = t.GetTypeInfo().BaseType)
                    if (t.GetTypeInfo().IsGenericType && t.GetGenericTypeDefinition() == lookInterfaceType)
                        return t;
            }
            else
            {
                if (lookInterfaceType.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()))
                    return lookInterfaceType;
            }

            return null;
        }
Beispiel #25
0
		public static bool IsAnonymousType(Type t)
		{
			return (t.GetTypeInfo().GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).FirstOrDefault() as CompilerGeneratedAttribute) != null
				&& t.GetTypeInfo().IsGenericType
					&& (t.Name.Contains("AnonymousType") || t.Name.Contains("AnonType"))
						&& (t.Name.StartsWith("<>") || t.Name.StartsWith("VB$"))
							&& t.GetTypeInfo().IsNotPublic;
		}
        public override bool CanConvert(Type objectType)
        {
#if NETFX_CORE
            return objectType.GetTypeInfo().IsEnum;
#else
            return objectType.GetTypeInfo().IsEnum;
#endif
        }
 private static IEnumerable<Type> GetAllBaseTypes(Type type)
 {
     while (type.GetTypeInfo().BaseType != null)
     {
         yield return type;
         type = type.GetTypeInfo().BaseType;
     }
 }
Beispiel #28
0
 private void InitTestData()
 {
     string filePath = Path.Combine(@"TestFiles\", FilePathUtil.GetTestDataPath(), @"xsltc\precompiled\Scripting28.dll");
     _asm = AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.GetFullPath(filePath));
     _type = _asm.GetType("Scripting28");
     _meth = ReflectionTestCaseBase.GetStaticMethod(_type, "Execute");
     _staticData = (Byte[])_type.GetTypeInfo().GetField("staticData", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static).GetValue(_type);
     _ebTypes = (Type[])_type.GetTypeInfo().GetField("ebTypes", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static).GetValue(_type);
 }
Beispiel #29
0
 public static bool IsAnonymousType(Type t)
 {
     
     return t.GetTypeInfo().GetCustomAttribute<CompilerGeneratedAttribute>() != null
         && t.GetTypeInfo().IsGenericType
             && (t.Name.Contains("AnonymousType") || t.Name.Contains("AnonType"))
                 && (t.Name.StartsWith("<>") || t.Name.StartsWith("VB$"))
                     && (t.GetTypeInfo().Attributes & AnonymousTypeAttributes) == AnonymousTypeAttributes;
 }
		/// <inheritdoc />
		public bool CanConvertFromHttpContent(Type typeToConvertTo, HttpContent httpContent)
		{
			if (!typeToConvertTo.GetTypeInfo().IsClass && !typeToConvertTo.GetTypeInfo().IsInterface)
			{
				return false;
			}
			var httpBehaviour = HttpBehaviour.Current;
			return !httpBehaviour.ValidateResponseContentType || SupportedContentTypes.Contains(httpContent.GetContentType());
		}
Beispiel #31
0
        ///<summary>
        /// We calculate the start property indices, based on the type and it's class hierarchy, for example, DateView (70,000)- > Spin (60,000) -> View (50,000).
        /// </summary>
        private void GetPropertyStartRange(System.Type viewType, ref PropertyRange range)
        {
            const int maxCountPerDerivation = 1000; // For child and animatable properties we use a gap of 1000 between each
                                                    // views property range in the hierarchy

            // custom views start there property index, at view_PROPERTY_END_INDEX
            // we add 1000, just incase View class (our C# custom view base) starts using scriptable properties
            int startEventPropertyIndex = (int)View.PropertyRange.CONTROL_PROPERTY_END_INDEX + maxCountPerDerivation;

            // for animatable properties current range starts at ANIMATABLE_PROPERTY_REGISTRATION_START_INDEX,
            // we add 1000, just incase View class starts using animatable properties
            int startAnimatablePropertyIndex = (int)Tizen.NUI.PropertyRanges.ANIMATABLE_PROPERTY_REGISTRATION_START_INDEX + maxCountPerDerivation;

            while (viewType?.GetTypeInfo()?.BaseType?.Name != "CustomView")   // custom view is our C# view base class. we don't go any deeper.
            {
                // for every base class increase property start index
                startEventPropertyIndex      += (int)Tizen.NUI.PropertyRanges.DEFAULT_PROPERTY_MAX_COUNT_PER_DERIVATION; // DALi uses 10,000
                startAnimatablePropertyIndex += maxCountPerDerivation;
                if (viewType != null)
                {
                    NUILog.Debug("getStartPropertyIndex =  " + viewType.Name + "current index " + startEventPropertyIndex);
                    viewType = viewType.GetTypeInfo()?.BaseType;
                }
            }

            range.startEventIndex    = startEventPropertyIndex;
            range.lastUsedEventIndex = startEventPropertyIndex;

            range.startAnimationIndex    = startAnimatablePropertyIndex;
            range.lastUsedAnimationIndex = startAnimatablePropertyIndex;
        }
        public static Type?TryGetElementType(this Type type, Type interfaceOrBaseType)
        {
            if (type.GetTypeInfo().IsGenericTypeDefinition)
            {
                return(null);
            }

            var types = GetGenericTypeImplementations(type, interfaceOrBaseType);

            Type?singleImplementation = null;

            foreach (var implementation in types)
            {
                if (singleImplementation == null)
                {
                    singleImplementation = implementation;
                }
                else
                {
                    singleImplementation = null;
                    break;
                }
            }

            return(singleImplementation?.GetTypeInfo().GenericTypeArguments.FirstOrDefault());
        }
Beispiel #33
0
 static public PacketAttribute GetAttr(System.Type packetType)
 {
     foreach (object attribute in packetType.GetTypeInfo().GetCustomAttributes(typeof(PacketAttribute), false))
     {
         return((PacketAttribute)attribute);
     }
     throw new System.Exception("packet type is wrong");
 }
Beispiel #34
0
 public static System.Type[] GetInterfaces(System.Type pType)
 {
                 #if UNITY_EDITOR || !UNITY_METRO
     return(pType.GetInterfaces());
                 #else
     return(pType.GetTypeInfo().ImplementedInterfaces.ToArray());
                 #endif
 }
Beispiel #35
0
    public static bool IsEnum(System.Type type)
    {
#if NETFX_CORE
        return(type.GetTypeInfo().IsEnum);
#else
        return(type.IsEnum);
#endif
    }
        public static TP GetTypeInfo(System.Type type)
        {
#if NETFX_CORE
            return(type.GetTypeInfo());
#else
            return(type);
#endif
        }
Beispiel #37
0
 private static Dictionary <object, string> GetNameMapping(System.Type enumType) =>
 enumType.GetTypeInfo().DeclaredFields
 .Where(f => f.IsStatic)
 .ToDictionary(f => f.GetValue(null),
               f => f.GetCustomAttributes <OriginalNameAttribute>()
               .FirstOrDefault()
               // If the attribute hasn't been applied, fall back to the name of the field.
               ?.Name ?? f.Name);
Beispiel #38
0
        internal static bool IsEnumType(System.Type t)
        {
#if NEW_REFLECTION
            return(t.GetTypeInfo().IsEnum);
#else
            return(t.IsEnum);
#endif
        }
Beispiel #39
0
 static public bool IsCaching(System.Type packetType)
 {
     foreach (object attribute in packetType.GetTypeInfo().GetCustomAttributes(typeof(PacketAttribute), false))
     {
         return(((PacketAttribute)attribute).Caching);
     }
     return(true);
 }
Beispiel #40
0
        public static Type BaseType(this System.Type type)
        {
#if NETFX_CORE
            return(type.GetTypeInfo().BaseType);
#else
            return(type.BaseType);
#endif
        }
        /**
         * Just forward this call to the proper spot
         */
        public static bool IsAssignableFrom(this System.Type type, System.Type other)
        {
#if NETFX_CORE
            return(type.GetTypeInfo().IsAssignableFrom(other.GetTypeInfo()));
#else
            return(type.IsAssignableFrom(other));
#endif
        }
Beispiel #42
0
 public static PropertyInfo[] GetProperties(System.Type pType)
 {
                 #if UNITY_EDITOR || !UNITY_METRO
     return(pType.GetProperties());
                 #else
     return(pType.GetTypeInfo().DeclaredProperties.ToArray());
                 #endif
 }
Beispiel #43
0
 public static bool IsClass(System.Type pType)
 {
                 #if UNITY_EDITOR || !UNITY_METRO
     return(pType.IsClass);
                 #else
     return(pType.GetTypeInfo().IsClass);
                 #endif
 }
Beispiel #44
0
 public static FieldInfo[] GetFields(System.Type pType)
 {
                 #if UNITY_EDITOR || !UNITY_METRO
     return(pType.GetFields());
                 #else
     return(pType.GetTypeInfo().DeclaredFields.ToArray());
                 #endif
 }
Beispiel #45
0
        /**
         * Missing IsSubclassOf, this works well
         */
        public static bool IsSubclassOf(this Type type, System.Type parent)
        {
#if NETFX_CORE
            return(parent.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()));
#else
            throw new NotImplementedException();
#endif
        }
        /**
         * Missing IsSubclassOf, this works well
         */
        public static bool IsSubclassOf(this System.Type type, System.Type parent)
        {
#if NETFX_CORE
            return(parent.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()));
#else
            return(type.IsSubclassOf(parent));
#endif
        }
Beispiel #47
0
        public static TypeR Convert(this System.Type type)
        {
#if UNITY_WSA
            return(type.GetTypeInfo());
#else
            return(type);
#endif
        }
Beispiel #48
0
        public override bool CanConvert(System.Type objectType)
        {
#if  NETSTANDARD1_3
            return(typeof(T).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo()));
#else
            return(typeof(T).IsAssignableFrom(objectType));
#endif
        }
Beispiel #49
0
        //private HashSet<Type> typeHasTypeHintCache;

        #endregion Fields

        #region Properties

        public static TP GetTypeInfo(System.Type tp)
        {
#if WINDOWS_STORE
            return(tp.GetTypeInfo());
#else
            return(tp);
#endif
        }
Beispiel #50
0
        internal static Array GetEnumValues(System.Type enumType)
        {
            if (!enumType.GetTypeInfo().IsEnum)
            {
                throw new ArgumentException("Not an enumeration type", "enumType");
            }

            return(Enum.GetValues(enumType));
        }
        public static bool IsPrimitive(System.Type type, bool includeEnums)
        {
            if (type.GetTypeInfo().IsPrimitive)
            {
                return(true);
            }

            if (includeEnums && type.GetTypeInfo().IsEnum)
            {
                return(true);
            }

            return(type == typeof(string) ||
                   type == typeof(decimal) ||
                   type == typeof(DateTime) ||
                   type == typeof(DateTimeOffset) ||
                   type == typeof(TimeSpan) ||
                   type == typeof(Guid));
        }
Beispiel #52
0
            internal static PrimitiveConverter ForType(BclType type)
            {
                TypeCode underlyingTypeCode = BclType.GetTypeCode(type.GetTypeInfo().GetEnumUnderlyingType());

                if (!s_genericTypes.TryGetValue(underlyingTypeCode, out var genericConverterType))
                {
                    throw new InvalidOperationException($"Unexpected underlying type code for enum: {underlyingTypeCode}");
                }
                return((PrimitiveConverter)Activator.CreateInstance(genericConverterType.MakeGenericType(type)));
            }
Beispiel #53
0
        private static bool HandleEnum(Type type, Value value, object propValue, IEntityFactory entityFactory)
        {
            if (type.GetTypeInfo().IsEnum)
            {
                value.StringValue = propValue.ToString();
                return(true);
            }

            return(false);
        }
Beispiel #54
0
        /// <summary>
        /// Load the enum helper class against a given enum type
        /// </summary>
        /// <param name="enumType">The enum type to locate the helper</param>
        /// <returns>System.Type of the helper class for the given enum type</returns>
        private static System.Type loadEnumHelperType(System.Type enumType)
        {
#if WINDOWS_UWP || DNXCORE50 || NETSTANDARD1_3
            bool     isNullableGeneric = enumType.GetTypeInfo().IsGenericType&& enumType.GetGenericTypeDefinition() == typeof(Nullable <>);
            Assembly assembly          = enumType.GetTypeInfo().Assembly;
#else
            bool     isNullableGeneric = enumType.IsGenericType && enumType.GetGenericTypeDefinition() == typeof(Nullable <>);
            Assembly assembly          = enumType.Assembly;
#endif
            string      enumHelperClassName = string.Format("{0}Helper", isNullableGeneric ? Nullable.GetUnderlyingType(enumType).FullName : enumType.FullName);
            System.Type enumHelperType      = assembly.GetType(enumHelperClassName);

            if (enumHelperType == null)
            {
                throw new InvalidCastException("Unable to load enum helper for casting value");
            }

            return(enumHelperType);
        }
Beispiel #55
0
        private static bool HandleComplexType(Type type, Value value, object propValue, IEntityFactory entityFactory, IList <string> recursionPath)
        {
            if (type.GetTypeInfo().IsClass)
            {
                value.EntityValue = entityFactory.EmbeddedEntityFromPoco(propValue, recursionPath);
                return(true);
            }

            return(false);
        }
Beispiel #56
0
        private static IFirestoreInternalConverter CreateConverter(BclType targetType)
        {
            var targetTypeInfo = targetType.GetTypeInfo();

            if (targetType.IsArray)
            {
                return(new ArrayConverter(targetType.GetElementType()));
            }
            if (targetTypeInfo.IsDefined(typeof(FirestoreDataAttribute)))
            {
                return(AttributedTypeConverter.ForType(targetType));
            }
            // Simple way of checking for an anonymous type. Far from foolproof, but a reasonable start.
            if (targetTypeInfo.IsDefined(typeof(CompilerGeneratedAttribute)))
            {
                return(new AnonymousTypeConverter(targetType));
            }

            if (targetTypeInfo.IsEnum)
            {
                return(new EnumConverter(targetType));
            }
            if (TryGetStringDictionaryValueType(targetType, out var dictionaryElementType))
            {
                var method = s_createDictionaryConverter.MakeGenericMethod(dictionaryElementType);
                try
                {
                    return((IFirestoreInternalConverter)method.Invoke(null, new object[] { targetType }));
                }
                catch (TargetInvocationException e) when(e.InnerException != null)
                {
                    throw e.InnerException;
                }
            }

            if (typeof(IList).IsAssignableFrom(targetType))
            {
                return(new ListConverter(targetType));
            }

            throw new ArgumentException($"Unable to create converter for type {targetType.GetTypeInfo().FullName}");
        }
Beispiel #57
0
        public static Guid?TypeGuid(System.Type type)
        {
            var attrs = type.GetTypeInfo().GetCustomAttributes(typeof(GuidAttribute), false);
            var attr  = attrs.FirstOrDefault() as GuidAttribute;

            if (attr == null)
            {
                return(null);
            }
            return(Guid.Parse(attr.Value));
        }
Beispiel #58
0
 public static Assembly[] GetAssembly()
 {
                 #if UNITY_EDITOR || !UNITY_METRO
     return(AppDomain.CurrentDomain.GetAssemblies());
                 #else
     Assembly[]  a = new Assembly[1];
     System.Type t = typeof(int);
     a[0] = t.GetTypeInfo().Assembly;
     return(a);
                 #endif
 }
        internal ListConverter(BclType targetType) : base(targetType)
        {
            // We could make this type generic, like DictionaryConverter. There's a difference
            // in that we don't need a generic interface in the conversion code here.
            var interfaces = targetType.GetTypeInfo().GetInterfaces();

            var genericListInterface = interfaces.Select(t => t.GetTypeInfo()).FirstOrDefault(iface => iface.IsGenericType && iface.GetGenericTypeDefinition() == typeof(IList <>));

            // Just use object if the type isn't actually generic.
            _elementType = genericListInterface?.GenericTypeArguments[0] ?? typeof(object);
        }
        /// <summary>
        /// Factory method to construct a converter for an attributed type.
        /// </summary>
        internal static IFirestoreInternalConverter ForType(BclType targetType)
        {
            var typeInfo  = targetType.GetTypeInfo();
            var attribute = typeInfo.GetCustomAttribute <FirestoreDataAttribute>(inherit: false);

            // This would be an internal library bug. We shouldn't be calling it in this case.
            GaxPreconditions.CheckState(attribute != null, "Type {0} is not decorated with {1}.", targetType.FullName, nameof(FirestoreDataAttribute));

            return(attribute.ConverterType == null
                ? new AttributedTypeConverter(targetType, attribute)
                : CustomConverter.ForConverterType(attribute.ConverterType, targetType));
        }