Example #1
0
	/// <summary>
	/// Guesses the IType by the type
	/// </summary>
	/// <param name="type">The type.</param>
	/// <returns></returns>
	public static IType GuessType(System.Type type)
	{
		if(type.FullName.StartsWith(typeof(Nullable<>).FullName))
		{
			type = type.GetGenericArguments()[0];
		}
		if (clrTypeToNHibernateType.ContainsKey(type))
		{
			return clrTypeToNHibernateType[type];
		}
		else if (type.IsEnum)
		{
			return Enum(type);
		}
		else if (
			typeof(IUserType).IsAssignableFrom(type) ||
			typeof(ICompositeUserType).IsAssignableFrom(type))
		{
			return Custom(type);
		}
		else
		{
			return Entity(type);
		}
	}
Example #2
0
        private static string GetDisplayName(System.Reflection.MethodBase method, string name, object[] arglist)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder(name);

            if (method.IsGenericMethod)
            {
                sb.Append("<");
                int cnt = 0;
                foreach (var t in method.GetGenericArguments())
                {
                    if (cnt++ > 0)
                        sb.Append(",");
                    sb.Append(t.Name);
                }
                sb.Append(">");
            }

            if (arglist != null)
            {
                sb.Append("(");

                for (int i = 0; i < arglist.Length; ++i)
                {
                    if (i > 0)
                        sb.Append(",");
                    sb.Append(GetDisplayString(arglist[i]));
                }

                sb.Append(")");
            }

            return sb.ToString();
        }
Example #3
0
 private static System.Type FindIEnumerable(System.Type seqType)
 {
     if (seqType == null || seqType == typeof(string))
         return null;
     if (seqType.IsArray)
         return typeof(IEnumerable<>).MakeGenericType(seqType.GetElementType());
     if (seqType.IsGenericType) {
         foreach (System.Type arg in seqType.GetGenericArguments())
         {
             System.Type ienum = typeof(IEnumerable<>).MakeGenericType(arg);
             if (ienum.IsAssignableFrom(seqType)) {
                 return ienum;
             }
         }
     }
     System.Type[] ifaces = seqType.GetInterfaces();
     if (ifaces != null && ifaces.Length > 0) {
         foreach (System.Type iface in ifaces)
         {
             System.Type ienum = FindIEnumerable(iface);
             if (ienum != null) return ienum;
         }
     }
     if (seqType.BaseType != null && seqType.BaseType != typeof(object)) {
         return FindIEnumerable(seqType.BaseType);
     }
     return null;
 }
Example #4
0
 internal static System.Type GetNonNullableType(System.Type type)
 {
     if (IsNullableType(type)) {
         return type.GetGenericArguments()[0];
     }
     return type;
 }
 internal static void AppendTypeName(System.Type t, bool topLevelFullName, StringBuilder sb)
 {
     string s = topLevelFullName ? t.FullName : t.Name;
     if (t.IsGenericType)
     {
         int index = s.IndexOf("`", StringComparison.Ordinal);
         if (index == -1)
         {
             index = s.Length;
         }
         sb.Append(s.Substring(0, index));
         AppendGenericArguments(t.GetGenericArguments(), sb);
         if (index < s.Length)
         {
             index++;
             while ((index < s.Length) && char.IsNumber(s, index))
             {
                 index++;
             }
             sb.Append(s.Substring(index));
         }
     }
     else
     {
         sb.Append(s);
     }
 }
Example #6
0
		/// <summary>
		/// Guesses the IType by the type
		/// </summary>
		/// <param name="type">The type.</param>
		/// <returns></returns>
		public static IType GuessType(System.Type type)
		{
			if(type.IsGenericType && typeof(Nullable<>).Equals(type.GetGenericTypeDefinition()))
			{
				type = type.GetGenericArguments()[0];
			}

			if (clrTypeToNHibernateType.ContainsKey(type))
			{
				return clrTypeToNHibernateType[type];
			}
			else if (type.IsEnum)
			{
				return (IType) Activator.CreateInstance(typeof (EnumType<>).MakeGenericType(type));
			}
			else if (
				typeof(IUserType).IsAssignableFrom(type) ||
				typeof(ICompositeUserType).IsAssignableFrom(type))
			{
				return Custom(type);
			}
			else
			{
				return Entity(type);
			}
		}
 protected override Type GetComponentType(System.Reflection.MethodInfo method, object[] arguments)
 {
     var newtype = typeof(IQueryHandler<,>)
          .MakeGenericType(
              arguments[0].GetType(),
              method.GetGenericArguments()[0]
          );
     return newtype;
 }
	private static System.Type GetCollectionValueType(System.Type type)
	{
		if (type == null)
			return null;
		var genericArguments = type.GetGenericArguments();
		if (genericArguments.Length == 0)
			return null;
		return genericArguments[0];
	}
Example #9
0
        /// <summary>
        /// Generates a class name for the Template base
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        /// <remarks>This is probably not the right location to put this but it seemed the most logical choice</remarks>
        public string GenerateClassName(System.Type type)
        {
            if (!type.IsGenericType)
                return type.Namespace + "." + type.Name;

            return type.Namespace
                   + "."
                   + type.Name.Substring(0, type.Name.IndexOf('`'))
                   + "(Of "
                   + string.Join(", ", type.GetGenericArguments()
                                           .Select(GenerateClassName))
                   + ")";
        }
Example #10
0
        public static System.Type TryGetCollectionItemType(System.Type collectionType)
        {
            if (collectionType == null)
                return null;

            if (collectionType.IsInterface && IsCollectionType(collectionType))
                return collectionType.GetGenericArguments().Single();

            System.Type enumerableType = collectionType.GetInterfaces().FirstOrDefault(IsCollectionType);
            if (enumerableType == null)
                return null;

            return enumerableType.GetGenericArguments().Single();
        }
Example #11
0
 internal static string Type(System.Type type, bool dropNamespaces = false)
 {
     string assemblyQualifiedName;
     Exception exception;
     if (type == null)
     {
         return string.Empty;
     }
     if (type.IsGenericType && !type.IsGenericTypeDefinition)
     {
         string str2 = Type(type.GetGenericTypeDefinition(), dropNamespaces);
         int num = str2.LastIndexOf('`');
         int length = str2.Length - (str2.Length - num);
         StringBuilder builder = new StringBuilder(str2, 0, length, 0x200);
         builder.Append('[');
         bool flag = true;
         foreach (System.Type type2 in type.GetGenericArguments())
         {
             if (!flag)
             {
                 builder.Append(',');
             }
             flag = false;
             builder.Append(Type(type2, dropNamespaces));
         }
         builder.Append(']');
         assemblyQualifiedName = builder.ToString();
     }
     else if (type.IsArray)
     {
         string str3 = Type(type.GetElementType(), dropNamespaces);
         StringBuilder builder2 = new StringBuilder(str3, str3.Length + 10);
         builder2.Append("[");
         for (int i = 0; i < (type.GetArrayRank() - 1); i++)
         {
             builder2.Append(",");
         }
         builder2.Append("]");
         assemblyQualifiedName = builder2.ToString();
     }
     else
     {
         assemblyQualifiedName = TypeAccelerators.FindBuiltinAccelerator(type) ?? (dropNamespaces ? type.Name : type.ToString());
     }
     if ((!type.IsGenericParameter && !type.ContainsGenericParameters) && (!dropNamespaces && (LanguagePrimitives.ConvertStringToType(assemblyQualifiedName, out exception) != type)))
     {
         assemblyQualifiedName = type.AssemblyQualifiedName;
     }
     return assemblyQualifiedName;
 }
Example #12
0
        private static Maybe<object> ChangeType(IEnumerable<string> values, System.Type conversionType, CultureInfo conversionCulture)
        {
            var type =
                conversionType.GetGenericArguments()
                              .SingleOrDefault()
                              .ToMaybe()
                              .FromJust(
                                  new ApplicationException("Non scalar properties should be sequence of type IEnumerable<T>."));

            var converted = values.Select(value => ChangeType(value, type, conversionCulture));

            return converted.Any(a => a.MatchNothing())
                ? Maybe.Nothing<object>()
                : Maybe.Just(converted.Select(c => ((Just<object>)c).Value).ToArray(type));
        }
        public override System.Threading.Tasks.Task WriteToStreamAsync(System.Type type, object value, System.IO.Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext)
        {
            var obj = new ExpandoObject() as IDictionary<string, Object>;
            if (type.IsSubclassOf(typeof(BaseMetaResponseModel)) && type.IsGenericType)
            {
                Type innerType = type.GetGenericArguments()[0];
                var genericValue = (value as BaseMetaResponseModel);
                value = genericValue.Content;
                type = innerType;
                obj["meta"] = genericValue.Meta;

            }
            var root = GetRootFieldName(type, value);
            obj[root] = value;
            return base.WriteToStreamAsync(type, obj as object, writeStream, content, transportContext);
        }
Example #14
0
        protected MethodBaseInfo(System.Reflection.MethodBase methodInfo, Dictionary<Type, TypeInfo> referenceTracker)
            : base(methodInfo, referenceTracker)
        {
            var bindingFlags = methodInfo.IsStatic ? BindingFlags.Static : BindingFlags.Instance;
            bindingFlags |= methodInfo.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic;
            BindingFlags = bindingFlags;

            var genericArguments = methodInfo.IsGenericMethod ? methodInfo.GetGenericArguments() : null;
            GenericArgumentTypes = ReferenceEquals(null, genericArguments) || genericArguments.Length == 0
                ? null
                : genericArguments.Select(x => TypeInfo.Create(referenceTracker, x, false, false)).ToList();

            var parameters = methodInfo.GetParameters();
            ParameterTypes = parameters.Length == 0
                ? null
                : parameters.Select(x => TypeInfo.Create(referenceTracker, x.ParameterType, false, false)).ToList();
        }
 public ISerializationSurrogate GetSurrogate(System.Type type, StreamingContext context, out ISurrogateSelector selector)
 {
   if (type.IsGenericType)
   {
     System.Type genericTypeDefinition = type.GetGenericTypeDefinition();
     if (genericTypeDefinition == typeof (List<>))
     {
       selector = (ISurrogateSelector) this;
       return ListSerializationSurrogate.Default;
     }
     if (genericTypeDefinition == typeof (Dictionary<,>))
     {
       selector = (ISurrogateSelector) this;
       return (ISerializationSurrogate) Activator.CreateInstance(typeof (DictionarySerializationSurrogate<,>).MakeGenericType(type.GetGenericArguments()));
     }
   }
   selector = (ISurrogateSelector) null;
   return (ISerializationSurrogate) null;
 }
	/// <summary>
	/// Guesses the IType by the type
	/// </summary>
	/// <param name="type">The type.</param>
	/// <returns></returns>
	public static IType GuessType(System.Type type)
	{
		if(type.IsGenericType && typeof(Nullable<>) == type.GetGenericTypeDefinition())
		{
			type = type.GetGenericArguments()[0];
		}
		IType value;
		if (clrTypeToNHibernateType.TryGetValue(type, out value))
			return value;
		if (type.IsEnum)
		{
			return (IType) Activator.CreateInstance(typeof (EnumType<>).MakeGenericType(type));
		}
		if (typeof(IUserType).IsAssignableFrom(type) ||
			typeof(ICompositeUserType).IsAssignableFrom(type))
		{
			return Custom(type);
		}
		
		return Entity(type);
	}
Example #17
0
        public static IEnumerable<System.Type> GetTypeInterfaceGenericArguments(System.Type type, System.Type interfaceType)
        {
            System.Type[] arguments = interfaceType.GetGenericArguments();

            if (arguments != null)
            {
                return arguments;
            }

            if (interfaceType == typeof(ICollection<>))
            {
                return type.GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).
                    Where(methodInfo => methodInfo.Name == "Add" && methodInfo.ParameterTypes.Length == 1).First().ParameterTypes;
            }

            if (interfaceType == typeof(IDictionary<,>))
            {
                return type.GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).
                    Where(methodInfo => methodInfo.Name == "Add" && methodInfo.ParameterTypes.Length == 2).First().ParameterTypes;
            }

            throw new Granular.Exception("Can't get generic arguments for type \"{0}\" interface \"{1}\"", type.Name, interfaceType.Name);
        }
Example #18
0
	private static System.Type ExtractUnderlyingTypeFromNullable(System.Type type)
	{
		return type.GetGenericArguments()[0];
	}
Example #19
0
        /// <summary>
        /// Adds a single type to the type set.
        /// IEnumerable and IEnumerator types are handled specially.
        /// </summary>
        protected static void AddSubType(HashSet<System.Type> typeSet, System.Type t)
        {
            // MoonSharp handles IEnumerator and IEnumerable types automatically, so just
            // register the generic type used.
            if (typeof(IEnumerable).IsAssignableFrom(t) ||
                typeof(IEnumerator).IsAssignableFrom(t))
            {
                System.Type[] genericArguments = t.GetGenericArguments();
                if (genericArguments.Count() == 1)
                {
                    System.Type containedType = genericArguments[0];

                    // The generic type could itself be an IEnumerator or IEnumerable, so
                    // recursively check for this case.
                    AddSubType(typeSet, containedType);
                }
            }
            else if (t != typeof(System.Object))
            {
                // Non-IEnumerable/IEnumerator types will be registered.
                typeSet.Add(t);
            }
        }
		private static Boolean IsNullableEnum(System.Type typeClass)
		{
			if (!typeClass.IsGenericType) return false;
			System.Type nullable = typeof(Nullable<>);
			if (!nullable.Equals(typeClass.GetGenericTypeDefinition())) return false;

			System.Type genericClass = typeClass.GetGenericArguments()[0];
			return genericClass.IsSubclassOf(typeof(Enum));
		}
Example #21
0
        /// <summary>
        /// Determines if the two types are either identical, or are both generic parameters or generic types
        /// with generic parameters in the same locations (generic parameters match any other generic parameter,
        /// but NOT concrete types).
        /// </summary>
        private static bool IsSimilarType(this System.Type thisType, System.Type type)
        {
            // Ignore any 'ref' types
            if (thisType.IsByRef)
                thisType = thisType.GetElementType();
            if (type.IsByRef)
                type = type.GetElementType();

            // Handle array types
            if (thisType.IsArray && type.IsArray)
                return thisType.GetElementType().IsSimilarType(type.GetElementType());

            // If the types are identical, or they're both generic parameters or the special 'T' type, treat as a match
            if (thisType == type || ((thisType.IsGenericParameter || thisType == typeof(T)) && (type.IsGenericParameter || type == typeof(T))))
                return true;

            // Handle any generic arguments
            if (thisType.IsGenericType && type.IsGenericType)
            {
                System.Type[] thisArguments = thisType.GetGenericArguments();
                System.Type[] arguments = type.GetGenericArguments();
                if (thisArguments.Length == arguments.Length)
                    return !thisArguments.Where((t, i) => !t.IsSimilarType(arguments[i])).Any();
            }

            return false;
        }
Example #22
0
        public override DecodedObject<object> decodeSequenceOf(DecodedObject<object> decodedTag, System.Type objectClass, ElementInfo elementInfo, System.IO.Stream stream)
        {
            if (!CoderUtils.isSequenceSetOf(elementInfo))
            {
                if (!checkTagForObject(decodedTag, TagClasses.Universal, ElementType.Constructed, UniversalTags.Sequence, elementInfo))
                    return null;
            }
            else
            {
                if (!checkTagForObject(decodedTag, TagClasses.Universal, ElementType.Constructed, UniversalTags.Set, elementInfo))
                    return null;
            }

            Type paramType = (System.Type)objectClass.GetGenericArguments()[0];
            Type collectionType = typeof(List<>);
            Type genCollectionType = collectionType.MakeGenericType(paramType);
            Object param = Activator.CreateInstance(genCollectionType);

            DecodedObject<int> len = decodeLength(stream);
            if (len.Value != 0)
            {
                int lenOfItems = 0;
                int itemsCnt = 0;
                do
                {
                    ElementInfo info = new ElementInfo();
                    info.ParentAnnotatedClass = elementInfo.AnnotatedClass;
                    info.AnnotatedClass = paramType;

                    if (elementInfo.hasPreparedInfo())
                    {
                        ASN1SequenceOfMetadata seqOfMeta = (ASN1SequenceOfMetadata)elementInfo.PreparedInfo.TypeMetadata;
                        info.PreparedInfo = (seqOfMeta.getItemClassMetadata());
                    }

                    DecodedObject<object> itemTag = decodeTag(stream);
                    DecodedObject<object> item = decodeClassType(itemTag, paramType, info, stream);
                    MethodInfo method = param.GetType().GetMethod("Add");
                    if (item != null)
                    {
                        lenOfItems += item.Size + itemTag.Size;
                        method.Invoke(param, new object[] { item.Value });
                        itemsCnt++;
                    }
                }
                while (lenOfItems < len.Value);
                CoderUtils.checkConstraints(itemsCnt, elementInfo);
            }
            return new DecodedObject<object>(param, len.Value + len.Size);
        }
Example #23
0
		AstType GenerateReflectedType(System.Type type)
		{
			if (type == typeof(void))
				return new PrimitiveType("void");

			var name = type.FullName;
			if (type.IsGenericType)
				name = name.Substring(0, name.IndexOf('`'));

			return CreateAstType(name, type.GetGenericArguments().Select(GenerateReflectedType));
		}
        public static string GetNiceTypeName(System.Type type, NamingOptions options)
        {
            if (options != null && options.NameOverrideFunc !=null)
            {
                string s = options.NameOverrideFunc(type);
                if (s != null)
                {
                    return s;
                }
            }

            if (IsNullableType(type))
            {
                var actualtype = type.GetGenericArguments()[0];
                return GetNiceTypeName(actualtype, options) + "?";
            }

            if (type.IsArray)
            {
                var at = type.GetElementType();
                return string.Format("{0}[]", GetNiceTypeName(at, options));
            }

            if (type.IsGenericType)
            {
                var sb = new System.Text.StringBuilder();
                var tokens = type.Name.Split('`');

                sb.Append(tokens[0]);
                var gas = type.GetGenericArguments();
                var ga_names = gas.Select(i => GetNiceTypeName(i, options));

                sb.Append("<");
                Join(sb, ", ", ga_names);
                sb.Append(">");
                return sb.ToString();
            }

            return type.Name;
        }
Example #25
0
 static void AppendGeneric(StringBuilder signature, System.Type type)
 {
     var separator =  type.Name.Substring(0, type.Name.IndexOf('`'));
     AppendGenericTypes(signature, separator, type.GetGenericArguments());
 }
Example #26
0
	public static IType GetMetaType(System.Type typeClass, IDictionary parameters)
	{
		IType type;
		if (typeof(IType).IsAssignableFrom(typeClass))
		{
			try
			{
				type = (IType)Activator.CreateInstance(typeClass);
			}
			catch (Exception e)
			{
				throw new MappingException("Could not instantiate IType " + typeClass.Name + ": " + e, e);
			}
			InjectParameters(type, parameters);
		}
		else if (typeof(ICompositeUserType).IsAssignableFrom(typeClass))
		{
			type = new CompositeCustomType(typeClass, parameters);
		}
		else if (typeof(IUserType).IsAssignableFrom(typeClass))
		{
			type = new CustomType(typeClass, parameters);
		}
		else if (typeof(ILifecycle).IsAssignableFrom(typeClass))
		{
			type = NHibernateUtil.Entity(typeClass);
		}
		else if (typeClass.IsEnum)
		{
			type = NHibernateUtil.Enum(typeClass);
		}
		else if (IsNullableEnum(typeClass))
		{
			type = NHibernateUtil.Enum(typeClass.GetGenericArguments()[0]);
		}
		else if (typeClass.IsSerializable)
		{
			var typeName = typeClass.FullName;
			var typeClassification = GetTypeClassification(typeName);
			if (typeClassification == TypeClassification.Length)
			{
				var parsedTypeName = typeName.Split(lengthSplit);
				type = GetSerializableType(typeClass, Int32.Parse(parsedTypeName[1]));
			}
			else
			{
				type = GetSerializableType(typeClass);
			}
		}
		else
		{
			type = null;
		}
		return type;
	}
Example #27
0
        /// <summary>
        /// Конструктор узла.
        /// </summary>
        /// <param name="mi">Оборачиваемый метод.</param>
		private compiled_function_node(System.Reflection.MethodInfo mi)
		{
			_mi=mi;
			type_node ret_val=null;
			if (_mi.ReturnType!=null)
			{
				ret_val=compiled_type_node.get_type_node(mi.ReturnType);
                if (ret_val == SystemLibrary.SystemLibrary.void_type)
                {
                    ret_val = null;
                }
			}
			System.Reflection.ParameterInfo[] pinf=mi.GetParameters();
            parameter_list pal = new parameter_list();
            //if (!(_mi.IsGenericMethod))
            {
                int i = 1;
                foreach (System.Reflection.ParameterInfo pi in pinf)
                {
                    Type t = null;
                    
                    type_node par_type = null;
                    SemanticTree.parameter_type pt = SemanticTree.parameter_type.value;
//                    if (pi.ParameterType.Name.EndsWith("&") == true)
                    //(ssyy) Лучше так:
                    if (pi.ParameterType.IsByRef)
                    {
                        //t = pi.ParameterType.Assembly.GetType(pi.ParameterType.FullName.Substring(0, pi.ParameterType.FullName.Length - 1));
                        //(ssyy) Лучше так:
                        t = pi.ParameterType.GetElementType();
                        par_type = compiled_type_node.get_type_node(t);
                        pt = SemanticTree.parameter_type.var;
                    }
                    else
                    {
                        if (pi.Position == 0)
                        {
                            par_type = compiled_type_node.get_type_node(pi.ParameterType);
                            if (NetHelper.NetHelper.IsExtensionMethod(mi))
                            {
                                connected_to_type = par_type as compiled_type_node;
                            }
                        }
                    }
                    string name = pi.Name;
                    compiled_parameter crpar = new compiled_parameter(pi);
                    crpar.SetParameterType(pt);
                    pal.AddElement(crpar);
                    if (pi.IsOptional && pi.DefaultValue != null)
                        _num_of_default_parameters++;
                    i++;
                }
            }
            //else
            if (_mi.IsGenericMethod)
            {
                _generic_params_count = mi.GetGenericArguments().Length;
            }
            _is_extension_method = NetHelper.NetHelper.IsExtensionMethod(mi);
			this.return_value_type=ret_val;
			this.parameters.AddRange(pal);
		}
Example #28
0
 public static IEnumerable<System.Type> GetTypeInterfaceGenericArguments(System.Type type, System.Type interfaceType)
 {
     return interfaceType.GetGenericArguments();
 }
 private string GetSimpleTypeFullName(System.Type type)
 {
     if (type == null)
     {
         return string.Empty;
     }
     StringBuilder builder = new StringBuilder(type.FullName);
     Stack<System.Type> stack = new Stack<System.Type>();
     stack.Push(type);
     while (stack.Count > 0)
     {
         type = stack.Pop();
         while (type.IsArray)
         {
             type = type.GetElementType();
         }
         if (type.IsGenericType && !type.IsGenericTypeDefinition)
         {
             foreach (System.Type type2 in type.GetGenericArguments())
             {
                 builder.Replace("[" + type2.AssemblyQualifiedName + "]", this.GetSimpleTypeFullName(type2));
                 stack.Push(type2);
             }
         }
     }
     return builder.ToString();
 }
Example #30
0
            /// <summary>
            /// Check that the select sequence has the right type. For example,
            /// we can't return a class in a function.
            /// </summary>
            /// <param name="type"></param>
            /// <returns></returns>
            private bool isGoodSelectSequenceType(System.Type type)
            {
                var arg = type.GetGenericArguments();
                if (arg.Length != 1)
                    return false;

                var cls = arg[0];
                return !cls.IsClass && !cls.IsInterface;
            }