Example #1
0
        public static bool IsGenericTypeOf(this Type t, Type genericDefinition, out Type[] genericParameters)
        {
            genericParameters = new Type[] { };
            if (!genericDefinition.IsGenericType) {
                return false;
            }

            var isMatch = t.IsGenericType && t.GetGenericTypeDefinition() == genericDefinition.GetGenericTypeDefinition();
            if (!isMatch && t.BaseType != null) {
                isMatch = IsGenericTypeOf(t.BaseType, genericDefinition, out genericParameters);
            }
            if (!isMatch && genericDefinition.IsInterface && t.GetInterfaces().Any()) {
                foreach (var i in t.GetInterfaces()) {
                    if (i.IsGenericTypeOf(genericDefinition, out genericParameters)) {
                        isMatch = true;
                        break;
                    }
                }
            }

            if (isMatch && !genericParameters.Any()) {
                genericParameters = t.GetGenericArguments();
            }
            return isMatch;
        }
 // this has been through red and green phase, it has yet to see it's refactor phase
 public Type Close(Type conversionPatternType, Type sourceType, Type targetType)
 {
     var @interface = conversionPatternType.GetInterface(typeof (IConversionPattern<,>));
     if (@interface == null)
     {
         throw new ArgumentException(string.Format("Type {0} doesn't implement {1} and therefore is invalid for this operation.", conversionPatternType, typeof (IConversionPattern<,>)));
     }
     var arguments = @interface.GetGenericArguments();
     var interfaceSourceType = arguments[0];
     var interfaceTargetType = arguments[1];
     if (conversionPatternType.IsGenericType == false)
     {
         if (sourceType.Is(interfaceSourceType) && targetType.Is(interfaceTargetType))
         {
             return conversionPatternType;
         }
         return null;
     }
     var openClassArguments = conversionPatternType.GetGenericArguments();
     var parameters = new Type[openClassArguments.Length];
     if (TryAddParameters(sourceType, interfaceSourceType, parameters, openClassArguments) == false)
     {
         return null;
     }
     if (TryAddParameters(targetType, interfaceTargetType, parameters, openClassArguments) == false)
     {
         return null;
     }
     if (parameters.Any(p => p == null))
     {
         return null;
     }
     return conversionPatternType.MakeGenericType(parameters);
 }
        public static Assembly[] MapConventionsForAssemblies(Type[] viewAssemblyRootAnchors, Type[] viewModelAssemblyRootAnchors)
        {
            if (viewAssemblyRootAnchors == null) throw new ArgumentNullException("viewAssemblyRootAnchors");
            if (viewAssemblyRootAnchors.Any(type => type == null))
                throw new ArgumentException("viewAssemblyRootAnchors contains null elements");
            if (viewModelAssemblyRootAnchors == null) throw new ArgumentNullException("viewModelAssemblyRootAnchors");
            if (viewModelAssemblyRootAnchors.Any(type => type == null))
                throw new ArgumentException("viewModelAssemblyRootAnchors contains null elements");

            foreach (var viewAssemblyRootAnchor in viewAssemblyRootAnchors)
            {
                foreach (var viewModelAssemblyRootAnchor in viewModelAssemblyRootAnchors)
                {
                    //{
                    //    var vmNs = viewModelAssemblyRootAnchor.Namespace + ".ViewModels";
                    //    var vNs = viewAssemblyRootAnchor.Namespace + ".Views";
                    //    ViewLocator.AddNamespaceMapping(vmNs, vNs);
                    //    ViewModelLocator.AddNamespaceMapping(vNs, vmNs);
                    //}

                    {
                        var vmNs = viewModelAssemblyRootAnchor.Namespace + ".ViewModels";
                        var vNs = viewAssemblyRootAnchor.Namespace + ".Views";
                        ViewLocator.AddSubNamespaceMapping(vmNs, vNs);
                        ViewModelLocator.AddSubNamespaceMapping(vNs, vmNs);
                    }
                }
            }

            return
                viewAssemblyRootAnchors.Concat(viewModelAssemblyRootAnchors)
                                       .Select(type => type.Assembly)
                                       .Distinct()
                                       .ToArray();
        }
 public static ConstructorInfo GetConstructor(this Type sourceType, Type[] types) {
     if(sourceType == null)
         throw new ArgumentException("sourceType");
     if (types == null || types.Any(t => t == null))
         throw new ArgumentNullException("types");
     return sourceType.GetTypeInfo().DeclaredConstructors.Where(ci => CheckParametersTypes(ci.GetParameters(), types)).FirstOrDefault();
 }
 private void VerifyClassHasNotBeenPassedAsAnAdditionalInterface(Type[] additionalInterfaces)
 {
     if (additionalInterfaces != null && additionalInterfaces.Any(x => x.IsClass))
     {
         throw new SubstituteException("Can not substitute for multiple classes. To substitute for multiple types only one type can be a concrete class; other types can only be interfaces.");
     }
 }
 /*********
 ** Protected methods
 *********/
 /// <summary>Get whether the value implements an expected type.</summary>
 /// <param name="value">The value to check.</param>
 /// <param name="types">The expected types that the value must implement.</param>
 protected bool HasType(object value, Type[] types)
 {
     if (value == null)
         return true; // type is irrelevant in this case
     Type actualType = value.GetType();
     return types.Any(type => type.IsAssignableFrom(actualType));
 }
Example #7
0
        public static bool IsGenericTypeOf(this Type t, Type genericDefinition, out Type[] genericParameters)
        {
            genericParameters = new Type[] { };
            if (!genericDefinition.GetTypeInfo().IsGenericType)
            {
                return(false);
            }

            var isMatch = t.GetTypeInfo().IsGenericType&& t.GetGenericTypeDefinition() == genericDefinition.GetGenericTypeDefinition();

            if (!isMatch && t.GetTypeInfo().BaseType != null)
            {
                isMatch = IsGenericTypeOf(t.GetTypeInfo().BaseType, genericDefinition, out genericParameters);
            }
            if (!isMatch && genericDefinition.GetTypeInfo().IsInterface&& t.GetInterfaces().Any())
            {
                foreach (var i in t.GetInterfaces())
                {
                    if (i.IsGenericTypeOf(genericDefinition, out genericParameters))
                    {
                        isMatch = true;
                        break;
                    }
                }
            }

            if (isMatch && !genericParameters.Any())
            {
                genericParameters = t.GetGenericArguments();
            }
            return(isMatch);
        }
 private static List<MethodCommandTypeTuple> GetHandlersForCommandTypes(Type type, Type[] commandTypes, MethodParameterInjector injector)
 {
     return type.GetMethods()
         .Select(m => new {Method = m, Params = m.GetParameters()})
         .Where(p => commandTypes.Any(ct => IsValidCommandHandler(ct, p.Method, p.Params, injector)))
         .Select(p => new MethodCommandTypeTuple { Method = p.Method, HandlerType = p.Method.DeclaringType, CommandType = FindCommandTypeInMethodParameters(commandTypes, p.Method)})
         .ToList();
 }
Example #9
0
        // based on https://exceldna.codeplex.com/wikipage?title=Reference
        public static bool IsValidExcelDnaType(Type type)
        {
            var validTypes =
                new Type[] {typeof(String), typeof(DateTime), typeof(Double), typeof(Double[]), typeof(Double[,]),
                            typeof(Object), typeof(Object[]), typeof(Object[,]), typeof(Boolean), typeof(Int32),
                            typeof(Int16), typeof(UInt16), typeof(Decimal), typeof(Int64)};

            return validTypes.Any(t => type.Equals(t));
        }
        /// <summary>
        /// Checks if this exception's type is the same, or a sub-class, of any of the specified types.
        /// </summary>
        /// <param name="ex">This instance.</param>
        /// <param name="types">Types to be matched against.</param>
        /// <returns>Whether or not this exception matched any of the specified types.</returns>
        public static bool IsAnyOf(this Exception ex, Type[] types)
        {
            if (ex == null)
            {
                throw new ArgumentNullException("ex");
            }
            if (types == null)
            {
                throw new ArgumentNullException("types");
            }

            Type exceptionType = ex.GetType();
            return types.Any(type => type.IsAssignableFrom(exceptionType));
        }
Example #11
0
        public static string GeneratePublicApi(Assembly assemby, Type[] includeTypes = null, bool shouldIncludeAssemblyAttributes = true)
        {
            var assemblyResolver = new DefaultAssemblyResolver();
            var assemblyPath = assemby.Location;
            assemblyResolver.AddSearchDirectory(Path.GetDirectoryName(assemblyPath));

            var readSymbols = File.Exists(Path.ChangeExtension(assemblyPath, ".pdb"));
            var asm = AssemblyDefinition.ReadAssembly(assemblyPath, new ReaderParameters(ReadingMode.Deferred)
            {
                ReadSymbols = readSymbols,
                AssemblyResolver = assemblyResolver,
            });

            return CreatePublicApiForAssembly(asm, tr => includeTypes == null || includeTypes.Any(t => t.FullName == tr.FullName && t.Assembly.FullName == tr.Module.Assembly.FullName), shouldIncludeAssemblyAttributes);
        }
Example #12
0
        /// <summary>
        /// Prepare the specified types.
        /// </summary>
        public static void Prepare(Type[] types)
        {
            if (!types.Any())
                return;
            if (types.Any(NothingToDo.With))
                throw new InvalidOperationException(
                    "Unable to make proxies for types: " +
                    string.Join(", ", types.Where(NothingToDo.With)));

            var unpreparedTypes = types
                .Where(t => !proxies.ContainsKey(t))
                .ToArray();
            var compiledAssembly = MakeAssembly(cu => {
                cu.ReferencedAssemblies.Add(ShieldedDll);
                foreach (var loc in unpreparedTypes.SelectMany(GetReferences).Distinct())
                    cu.ReferencedAssemblies.Add(loc);

                foreach (var t in unpreparedTypes)
                    PrepareType(t, cu);
            });
            foreach (var t in unpreparedTypes)
                proxies.TryAdd(t, compiledAssembly.GetType(
                    t.Namespace + "." + GetNameForDerivedClass(t)));
        }
		//public object Create(IDynamicProxy handler, Type objType, bool isObjInterface) {
		public object Create(IDynamicProxy handler, Type objType, Type[] aditionalInterfaces = null) {

			string typeName = objType.FullName + PROXY_SUFFIX;
			Type type = typeMap[typeName] as Type;

			// Verifica se o tipo já existe no cache de tipos criados dinamicamente. Caso não exista, cria a nova instancia e adiciona ao cache.
			if (type == null) {

				List<Type> interfacesToImplement = new List<Type>();

				// Verifica se foram especificadas interfaces adicionais.
				if (aditionalInterfaces != null && aditionalInterfaces.Any() == true) { interfacesToImplement.AddRange(aditionalInterfaces); }

				if (objType.IsInterface == true) {

					// Pega todas as interfaces que são herdadas.
					Type[] baseInterfaces = objType.GetInterfaces();

					if (baseInterfaces != null) {

						// Adiciona cada interface herdada na lista de interfaces a serem implementadas.
						for (int i = 0; i < baseInterfaces.Length; i++) {
							interfacesToImplement.Add(baseInterfaces[i]);
						}
					}

					interfacesToImplement.Add(objType);
				}
				else {
					interfacesToImplement.AddRange(objType.GetInterfaces());
				}

				// Verifica se foram encontradas interfaces a serem implementadas.
				if (interfacesToImplement == null || interfacesToImplement.Any() == false) {

					throw new ArgumentException(objType.FullName + " has no interfaces to implement", "objType");
				}

				type = CreateType(handler, interfacesToImplement.ToArray(), typeName);

				Type existingType = typeMap[typeName] as Type;
				if (existingType == null) { typeMap.Add(typeName, type); }
			}

			// Retorna uma nova instancia do tipo.
			return Activator.CreateInstance(type, new object[] { handler });
		}
Example #14
0
        private static void ValidateThatOnlyOneServiceIsPresent(Type[] serviceTypes)
        {
            if (!serviceTypes.Any())
            {
                throw new TypeLoadException("Unable to locate any concrete implementations of IService");
            }

            if (serviceTypes.Count() != 1)
            {
                var services = new StringBuilder("Only one service is allowed per service host. The following services were detected:\n");

                foreach (var serviceType in serviceTypes)
                {
                    services.AppendLine(serviceType.FullName);
                }

                throw new InvalidOperationException(services.ToString());
            }
        }
        static void AddAdvancedClassTypeConverters()
        {
            // Add the types we want to have use the AdvancedClassTypeConverter. This is purely just for
            // a better PropertyGrid-based editing experience. Since it doesn't really matter if we add too many
            // types (since it is only really for the PropertyGrid), we just add EVERY table from the DbObjs.
            var filterCreator = new TypeFilterCreator
            {
                IsClass = true,
                IsAbstract = false,
                CustomFilter = (x => x.Name.EndsWith("Table") && (x.Namespace ?? string.Empty).Contains("DbObjs"))
            };
            var filter = filterCreator.GetFilter();

            var typesToAdd = TypeHelper.FindTypes(filter, null);
            AdvancedClassTypeConverter.AddTypes(typesToAdd.ToArray());

            // Also automatically add all the instantiable types that derive from some of our base classes
            var baseTypes = new Type[] { typeof(Entity), typeof(MapBase) };
            filterCreator = new TypeFilterCreator { IsClass = true, IsAbstract = false, CustomFilter = (x => baseTypes.Any(x.IsSubclassOf)) };
            filter = filterCreator.GetFilter();

            typesToAdd = TypeHelper.FindTypes(filter, null);
            AdvancedClassTypeConverter.AddTypes(typesToAdd.ToArray());

            // Manually add some other types we want to have use the AdvancedClassTypeConverter. Again, doesn't
            // really matter what you add here. In general, you should just add to this when you notice that
            // a PropertyGrid isn't using the AdvancedClassTypeConverter.
            AdvancedClassTypeConverter.AddTypes(typeof(MutablePair<ItemTemplateID, byte>),
                typeof(MutablePair<CharacterTemplateID, ushort>), typeof(EditorQuest), typeof(EditorAlliance), typeof(EditorShop),
                typeof(EditorCharacterTemplate));

            // Set the properties we want to force being readonly in the PropertyGrid
            AdvancedClassTypeConverter.SetForceReadOnlyProperties(typeof(CharacterTemplateTable), "ID");
            AdvancedClassTypeConverter.SetForceReadOnlyProperties(typeof(EditorCharacterTemplate), "ID");
            AdvancedClassTypeConverter.SetForceReadOnlyProperties(typeof(ItemTemplateTable), "ID");

#if !TOPDOWN
            // Set the UITypeEditor for specific properties on classes instead of every property with a certain type
            AdvancedClassTypeConverter.SetForceEditor(typeof(ItemTemplateTable),
                new KeyValuePair<string, UITypeEditor>("EquippedBody", new BodyPaperDollTypeEditor()));
#endif
        }
Example #16
0
        public IEnumerable<MethodInfo> FindAvailableMethods(Type[] types)
        {
            if (!string.IsNullOrEmpty(TypeName))
            {
                types = types.Where(type => type.Name == TypeName).ToArray();

                if (!types.Any())
                {
                    var message = string.Format("No type named '{0}' could be found.", TypeName);
                    throw new InvalidOperationException(message);
                }
            }

            const BindingFlags bindingFlags =
                BindingFlags.Public |
                BindingFlags.Static |
                BindingFlags.Instance |
                BindingFlags.DeclaredOnly;

            return types.SelectMany(type => type.GetMethods(bindingFlags)
                .OrderByDescending(method => method.GetParameters().Length));
        }
Example #17
0
        /// <summary>
        /// Gets a System.Linq.Expressions.Expression.Type object that represents a generic
        /// System.Func or System.Action delegate type that has specific type arguments.
        /// 
        /// For <paramref name="types"/> longer than 17 items, current module's <see cref="TypeBuilder"/> is used instead of Transient one.
        /// This avoids of "Unable to make a reference to a transient module from a non-transient module." exception.
        /// 
        /// For less or equal than 17 items, <see cref="System.Linq.Expressions.Expression.GetDelegateType"/> is used.
        /// </summary>
        /// <param name="types">The type arguments of the delegate.</param>
        /// <param name="uniqueId">A number used to name new delegate.</param>
        /// <returns>The delegate type.</returns>
        public Type/*!*/GetDelegateType(Type[]/*!*/types, long uniqueId)
        {
            Debug.Assert(types != null);

            if (moduleBuilder.IsTransient() ||  // we are in transient module (so dynamically created types can be referenced)
                (types.Length <= 17 && !types.Any((Type t) => t.IsByRef)))    // OR less or equal 17 items and none of them is by reference
                return System.Linq.Expressions.Expression.GetDelegateType(types);

            // else, Action or Func cannot be used, make the delegate:
            return
                GetDelegateTypeFromCache(types) ??      // try to find in cache first
                AddDelegateTypeToCache(                 // create the delegate type
                    types,
                    CreateDelegateType(moduleBuilder, types, string.Format("Delegate{0}'{1}", types.Length, uniqueId)));
        }
 private static string NoteThatSkippedDecoratorsWereFound(Type serviceType, Type[] decorators) =>
     decorators.Any()
         ? string.Format(CultureInfo.InvariantCulture,
             " Note that {0} {1} found as implementation of {2}, but {1} skipped during batch-" +
             "registration by the container because {3} considered to be a decorator (because {4} " +
             "a cyclic reference to {5}).",
             Helpers.ToCommaSeparatedText(decorators.Select(Helpers.ToFriendlyName)),
             decorators.Length == 1 ? "was" : "were",
             serviceType.GetGenericTypeDefinition().ToFriendlyName(),
             decorators.Length == 1 ? "it is" : "there are",
             decorators.Length == 1 ? "it contains" : "they contain",
             decorators.Length == 1 ? "itself" : "themselves")
         : string.Empty;
Example #19
0
		static bool IsNodeTypeInteresting(INode node, Type[] interestingNodeTypes)
		{
			Type nodeType = node.GetType();
			return interestingNodeTypes.Any(interestingType => interestingType.IsAssignableFrom(nodeType) || (nodeType == interestingType));
		}
 private Type GetPrimaryProxyType(Type[] typesToProxy)
 {
     if (typesToProxy.Any(x => x.IsSubclassOf(typeof(Delegate)))) return typesToProxy.First(x => x.IsSubclassOf(typeof(Delegate)));
     if (typesToProxy.Any(x => x.IsClass)) return typesToProxy.First(x => x.IsClass);
     return typesToProxy.First();
 }
        /// <summary>
        /// Method that implements parameter binding hookup to the global configuration object's
        /// ParameterBindingRules collection delegate.
        /// 
        /// This routine filters based on POST/PUT method status and simple parameter
        /// types.
        /// </summary>
        /// <example>
        /// GlobalConfiguration.Configuration.
        ///       .ParameterBindingRules
        ///       .Insert(0,NAMECLASS.HookupParameterBinding);
        /// </example>    
        /// <param name="descriptor"></param>
        /// <returns></returns>
        public static System.Web.Http.Controllers.HttpParameterBinding HookupParameterBinding(HttpParameterDescriptor descriptor)
        {
            var supportedMethods = descriptor.ActionDescriptor.SupportedHttpMethods;

            // Only apply this binder on POST and PUT operations
            if (supportedMethods.Contains(HttpMethod.Post) ||
                supportedMethods.Contains(HttpMethod.Put))
            {
                var supportedTypes = new Type[] { typeof(string), 
                                                typeof(int), 
                                                typeof(decimal), 
                                                typeof(double), 
                                                typeof(bool),
                                                typeof(DateTime),
                                                typeof(byte[]),
                                                typeof(string[])
                                            };

                if (supportedTypes.Any(typ => typ == descriptor.ParameterType))
                    return new PostPutVariableParameterBinding(descriptor);
            }

            return null;
        }
        private static Type MakeNewDelegate(Type[] types) {
            Debug.Assert(types != null && types.Length > 0);

            // Can only used predefined delegates if we have no byref types and
            // the arity is small enough to fit in Func<...> or Action<...>
            if (types.Length > MaximumArity || types.Any(t => t.IsByRef)) {
                return MakeNewCustomDelegate(types);
            }

            Type result;
            if (types[types.Length - 1] == typeof(void)) {
                result = GetActionType(types.RemoveLast());
            } else {
                result = GetFuncType(types);
            }
            Debug.Assert(result != null);
            return result;
        }
Example #23
0
 static void GenType(Type tp, Type[] extendedTypes, string module, StringBuilder sb) {
   sb.Append("export interface "); sb.Append(tp.Name);
   if (ancestors(tp).Any()) {
     sb.Append(" extends "); sb.Append(module == tp.BaseType.Namespace ? tp.BaseType.Name : tp.BaseType.FullName);
   }
   sb.AppendLine(" {");
   foreach (var fld in tp.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)) {
     if (fld.Name == "typeOfs" || (fld.GetCustomAttributes(typeof(JsonIgnoreAttribute), false).Any() && !fld.GetCustomAttributes(typeof(JsonGenOnlyAttribute), false).Any())) continue;
     sb.Append("  ");
     sb.Append(fld.Name);
     if (nulableFieldType(fld.FieldType)) sb.Append('?');
     sb.Append(": ");
     fieldType(fld.FieldType, module, sb);
     sb.AppendLine(";");
   }
   foreach (var prop in tp.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)) {
     if (prop.GetCustomAttributes(typeof(JsonIgnoreAttribute), false).Any() && !prop.GetCustomAttributes(typeof(JsonGenOnlyAttribute), false).Any()) continue;
     sb.Append("  ");
     sb.Append(prop.Name);
     if (nulableFieldType(prop.PropertyType)) sb.Append('?');
     sb.Append(": ");
     fieldType(prop.PropertyType, module, sb);
     sb.AppendLine(";");
   }
   sb.AppendLine("}");
   bool isExtended = extendedTypes.Any(t => t == tp);
   if (isExtended) { sb.Append("export var "); sb.Append(tp.Name); sb.Append("_Type = '"); sb.Append(tp.FullName); sb.AppendLine("';"); }
   if (isExtended) {
     var scormCmd = cmdAss.GetType("scorm.ScormCmd");
     var isCmd = tp == scormCmd || tp.IsSubclassOf(scormCmd);
     sb.Append("export function "); sb.Append(tp.Name); sb.Append("_Create (");
     bool first = true;
     foreach (var fld in tp.GetFields(BindingFlags.Instance | BindingFlags.Public).Where(fld => !fld.GetCustomAttributes(typeof(JsonIgnoreAttribute), false).Any())) {
       //if (fld.Name == "VerifyStatus") {
       //  var ok = !fld.GetCustomAttributes(typeof(JsonGenOnlyAttribute), true).Any();
       //  System.Diagnostics.Debugger.Break();
       //}
       if (fld.Name == "typeOfs" || (isCmd && fld.Name == "date")) continue;
       if (first) first = false; else sb.Append(", ");
       sb.Append(fld.Name); sb.Append(": "); fieldType(fld.FieldType, module, sb);
     }
     sb.Append("): "); sb.Append(tp.Name); sb.AppendLine("{");
     sb.Append("  return {");
     first = true;
     foreach (var fld in tp.GetFields(BindingFlags.Instance | BindingFlags.Public).Where(fld => !fld.GetCustomAttributes(typeof(JsonIgnoreAttribute), false).Any())) {
       if (fld.Name == "typeOfs") continue;
       if (first) first = false; else sb.Append(", ");
       sb.Append(fld.Name); sb.Append(": ");
       sb.Append(isCmd && fld.Name == "date" ? "Utils.nowToInt()" : fld.Name);
     }
     sb.AppendLine("};");
     sb.AppendLine("}");
   }
 }
Example #24
0
        /// <summary>
        /// A method to invoke a delegate locally.
        /// </summary>
        /// <param name="dt">
        /// The type of the target that the invocation will occur on.
        /// </param>
        /// <param name="mi">
        /// The method reference for the method that will be invoked.
        /// </param>
        /// <param name="target">
        /// The target that the invocation will occur on.
        /// </param>
        /// <param name="targs">
        /// The type arguments for the call.
        /// </param>
        /// <param name="args">
        /// The arguments for the call.
        /// </param>
        /// <returns>
        /// The resulting <see cref="object"/>.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// Thrown if <see cref="targs"/> is null.
        /// </exception>
        public static object InvokeDynamic(Type dt, MethodInfo mi, object target, Type[] targs, object[] args)
        {
            if (targs == null || targs.Any(x => x == null))
            {
                throw new ArgumentNullException("targs");
            }

            foreach (var nt in dt.GetNestedTypes(BindingFlags.NonPublic))
            {
                if (mi.Name.IndexOf("__") == -1)
                {
                    continue;
                }

                if (nt.FullName.Contains("+" + mi.Name.Substring(0, mi.Name.IndexOf("__")) + "__InvokeDirect"))
                {
                    return InvokeDynamicBase(nt, mi, target, targs, args);
                }
            }

            // Fall back to slow invocation.
            if (mi.IsGenericMethod)
            {
                mi = mi.MakeGenericMethod(targs);
            }

            return mi.Invoke(target, args);
        }
Example #25
0
		private static MemberInfo ResolveDocStyleMember(string docId)
		{
			// Conversion operator syntax not supported yet
			if (docId.Contains('~')) return null;

			// Determine entry type
			EntryType memberEntryType;
			switch (docId[0])
			{
				case 'M':	memberEntryType = EntryType.Method;		break;
				case 'T':	memberEntryType = EntryType.Type;		break;
				case 'F':	memberEntryType = EntryType.Field;		break;
				case 'P':	memberEntryType = EntryType.Property;	break;
				case 'E':	memberEntryType = EntryType.Event;		break;
				default:	memberEntryType = EntryType.Unknown;	return null;
			}

			// Determine member name and its (Declaring) type name
			string memberName;
			string memberTypeName;
			if (memberEntryType == EntryType.Type)
			{
				memberName = memberTypeName = docId.Remove(0, 2);
			}
			else
			{
				int memberNameSepIndex = docId.IndexOfAny(MemberNameSep);
				int lastDotIndex = memberNameSepIndex != -1 ? 
					docId.LastIndexOf('.', memberNameSepIndex) :
					docId.LastIndexOf('.');
				memberTypeName = docId.Substring(2, lastDotIndex - 2);
				memberName = docId.Substring(lastDotIndex + 1, docId.Length - lastDotIndex - 1);
			}

			// Determine the members (declaring) type
			TypeInfo memberType = ResolveDocStyleType(memberTypeName);
			if (memberType == null) return null;

			// Determine the member info
			if (memberEntryType == EntryType.Type)
				return memberType;
			else if (memberEntryType == EntryType.Field)
				return memberType.GetRuntimeFields().FirstOrDefault(m => m.Name == memberName);
			else if (memberEntryType == EntryType.Event)
				return memberType.GetRuntimeEvents().FirstOrDefault(m => m.Name == memberName);
			else if (memberEntryType == EntryType.Property)
			{
				string methodName;
				Type[] paramTypes;
				int paramIndex = memberName.IndexOf('(');
				if (paramIndex != -1)
				{
					methodName = memberName.Substring(0, paramIndex);
					string paramList = memberName.Substring(paramIndex + 1, memberName.Length - paramIndex - 2);
					string[] paramTypeNames = paramList.Split(',');
					paramTypes = new Type[paramTypeNames.Length];
					for (int i = 0; i < paramTypeNames.Length; i++)
					{
						bool isByRef = false;
						if (paramTypeNames[i].EndsWith("@"))
						{
							// ref / out parameter
							paramTypeNames[i] = paramTypeNames[i].Remove(paramTypeNames[i].Length - 1);
							isByRef = true;
						}

						paramTypes[i] = ResolveDocStyleType(paramTypeNames[i]);

						if (isByRef && paramTypes[i] != null) paramTypes[i] = paramTypes[i].MakeByRefType();
					}
				}
				else
				{
					methodName = memberName;
					paramTypes = Type.EmptyTypes;
				}

				// If we can't resolve one of our parameter names, don't try to retrieve the member
				if (paramTypes.Any(p => p == null))
					return null;

				return memberType.GetRuntimeProperties().FirstOrDefault(m => 
				{
					if (m.Name != methodName) return false;

					ParameterInfo[] indexerParams = m.GetIndexParameters();
					if (indexerParams.Length != paramTypes.Length) return false;

					for (int i = 0; i < paramTypes.Length; i++)
					{
						if (paramTypes[i] != indexerParams[i].ParameterType)
							return false;
					}
					return true;
				});
			}
			else if (memberEntryType == EntryType.Method)
			{
				string methodName;
				string[] paramTypeNames;
				int paramIndex = memberName.IndexOf('(');
				if (paramIndex != -1)
				{
					methodName = memberName.Substring(0, paramIndex);
					string paramList = memberName.Substring(paramIndex + 1, memberName.Length - paramIndex - 2);
					paramTypeNames = SplitGenArgs(paramList);
				}
				else
				{
					methodName = memberName;
					paramTypeNames = new string[0];
				}
				
				// Determine parameter types
				Type[] paramTypes = new Type[paramTypeNames.Length];
				bool[] paramTypeByRef = new bool[paramTypeNames.Length];
				for (int i = 0; i < paramTypeNames.Length; i++)
				{
					paramTypeByRef[i] = false;
					if (paramTypeNames[i].EndsWith("@"))
					{
						// ref / out parameter
						paramTypeNames[i] = paramTypeNames[i].Remove(paramTypeNames[i].Length - 1);
						paramTypeByRef[i] = true;
					}

					if (paramTypeNames[i][0] == '`' && paramTypeNames[i][1] != '`')
					{
						int typeGenArgIndex = 0;
						int.TryParse(paramTypeNames[i].Substring(1, paramTypeNames[i].Length - 1), out typeGenArgIndex);
						paramTypes[i] = memberType.GetGenericArguments()[typeGenArgIndex];
					}
					else if (paramTypeNames[i].StartsWith("``"))
						paramTypes[i] = null;
					else
						paramTypes[i] = ResolveDocStyleType(paramTypeNames[i]);

					if (paramTypeByRef[i] && paramTypes[i] != null) paramTypes[i] = paramTypes[i].MakeByRefType();
				}
				
				if (methodName == "#ctor") memberEntryType = EntryType.Constructor;
				if (memberEntryType == EntryType.Constructor)
				{
					// If we can't resolve one of our parameter names, don't try to retrieve the member
					if (paramTypes.Any(p => p == null))
						return null;

					return memberType.GetConstructor(paramTypes);
				}
				else
				{
					int genMethodArgDeclIndex = methodName.IndexOf("``", System.StringComparison.Ordinal);
					int genMethodArgs = 0;
					if (genMethodArgDeclIndex != -1)
					{
						genMethodArgs = int.Parse(methodName.Substring(genMethodArgDeclIndex + 2, methodName.Length - genMethodArgDeclIndex - 2));
						methodName = methodName.Remove(genMethodArgDeclIndex);
					}

					MethodInfo[] availMethods = memberType.GetRuntimeMethods().Where(
						m => m.Name == methodName && 
						m.GetGenericArguments().Length == genMethodArgs &&
						m.GetParameters().Length == paramTypes.Length).ToArray();

					// Select the method that fits
					foreach (MethodInfo method in availMethods)
					{
						bool possibleMatch = true;
						ParameterInfo[] methodParams = method.GetParameters();
						for (int i = 0; i < methodParams.Length; i++)
						{
							// Generic method param
							if (paramTypes[i] == null)
							{
								Type genMethodParam = ResolveDocStyleType(paramTypeNames[i], method);
								if (paramTypeByRef[i] && genMethodParam != null) genMethodParam = genMethodParam.MakeByRefType();

								if (genMethodParam != methodParams[i].ParameterType)
								{
									possibleMatch = false;
									break;
								}
							}
							// Some other param
							else if (methodParams[i].ParameterType != paramTypes[i])
							{
								possibleMatch = false;
								break;
							}
						}
						if (possibleMatch)
							return method;
					}
				}
			}

			return null;
		}
Example #26
0
        // end clone 


        private static Type GetCommonBaseType(Type[] types, Type baseType) {
            return types.Any(type => !type.IsAssignableFrom(baseType)) ? GetCommonBaseType(types, baseType.BaseType) : baseType;
        }
        private void SetAllowedChildren(ContentType documentType, Type[] allowedChildDocumentTypes)
        {
            if (documentType == null || allowedChildDocumentTypes == null || !allowedChildDocumentTypes.Any())
                return;

            documentType.AllowedChildContentTypeIDs = allowedChildDocumentTypes
                .Where(allowedChildDocumentType => _typeDocumentTypeIdMappings.ContainsKey(allowedChildDocumentType))
                .Select(allowedChildDocumentType => _typeDocumentTypeIdMappings[allowedChildDocumentType]).ToArray();
        }
        internal static Type MakeDelegate(Type[] types) {
            Debug.Assert(types != null && types.Length > 0);

            // Can only used predefined delegates if we have no byref types and
            // the arity is small enough to fit in Func<...> or Action<...>
            if (types.Length > MaximumArity || types.Any(t => t.IsByRef)) {
                return MakeCustomDelegate(types);
            }

            Type returnType = types[types.Length - 1];
            if (returnType == typeof(void)) {
                types = types.RemoveLast();
                switch (types.Length) {
                    case 0: return typeof(Action);
                    #region Generated Delegate Action Types

                    // *** BEGIN GENERATED CODE ***
                    // generated by function: gen_delegate_action from: generate_dynsites.py

                    case 1: return typeof(Action<>).MakeGenericType(types);
                    case 2: return typeof(Action<,>).MakeGenericType(types);
                    case 3: return typeof(Action<,,>).MakeGenericType(types);
                    case 4: return typeof(Action<,,,>).MakeGenericType(types);
                    case 5: return typeof(Action<,,,,>).MakeGenericType(types);
                    case 6: return typeof(Action<,,,,,>).MakeGenericType(types);
                    case 7: return typeof(Action<,,,,,,>).MakeGenericType(types);
                    case 8: return typeof(Action<,,,,,,,>).MakeGenericType(types);
                    case 9: return typeof(Action<,,,,,,,,>).MakeGenericType(types);
                    case 10: return typeof(Action<,,,,,,,,,>).MakeGenericType(types);
                    case 11: return typeof(Action<,,,,,,,,,,>).MakeGenericType(types);
                    case 12: return typeof(Action<,,,,,,,,,,,>).MakeGenericType(types);
                    case 13: return typeof(Action<,,,,,,,,,,,,>).MakeGenericType(types);
                    case 14: return typeof(Action<,,,,,,,,,,,,,>).MakeGenericType(types);
                    case 15: return typeof(Action<,,,,,,,,,,,,,,>).MakeGenericType(types);
                    case 16: return typeof(Action<,,,,,,,,,,,,,,,>).MakeGenericType(types);

                    // *** END GENERATED CODE ***

                    #endregion
                }
            } else {
                switch (types.Length) {
                    #region Generated Delegate Func Types

                    // *** BEGIN GENERATED CODE ***
                    // generated by function: gen_delegate_func from: generate_dynsites.py

                    case 1: return typeof(Func<>).MakeGenericType(types);
                    case 2: return typeof(Func<,>).MakeGenericType(types);
                    case 3: return typeof(Func<,,>).MakeGenericType(types);
                    case 4: return typeof(Func<,,,>).MakeGenericType(types);
                    case 5: return typeof(Func<,,,,>).MakeGenericType(types);
                    case 6: return typeof(Func<,,,,,>).MakeGenericType(types);
                    case 7: return typeof(Func<,,,,,,>).MakeGenericType(types);
                    case 8: return typeof(Func<,,,,,,,>).MakeGenericType(types);
                    case 9: return typeof(Func<,,,,,,,,>).MakeGenericType(types);
                    case 10: return typeof(Func<,,,,,,,,,>).MakeGenericType(types);
                    case 11: return typeof(Func<,,,,,,,,,,>).MakeGenericType(types);
                    case 12: return typeof(Func<,,,,,,,,,,,>).MakeGenericType(types);
                    case 13: return typeof(Func<,,,,,,,,,,,,>).MakeGenericType(types);
                    case 14: return typeof(Func<,,,,,,,,,,,,,>).MakeGenericType(types);
                    case 15: return typeof(Func<,,,,,,,,,,,,,,>).MakeGenericType(types);
                    case 16: return typeof(Func<,,,,,,,,,,,,,,,>).MakeGenericType(types);
                    case 17: return typeof(Func<,,,,,,,,,,,,,,,,>).MakeGenericType(types);

                    // *** END GENERATED CODE ***

                    #endregion
                }
            }
            throw Assert.Unreachable;
        }
        private static Type GetGenericParameterType(Type[] types, int memberNo, ParameterInfo parameter)
        {
            if (!types.Any())
            {
                throw new IndexOutOfRangeException("There is no types defined for interfaces");
            }

            if (types.Length < memberNo + 1)
            {
                throw new IndexOutOfRangeException(string.Format("Theris is no type defined for {0}", parameter.Name));
            }

            return types[memberNo];
        }
Example #30
0
		public static bool IsNearType(Mobile mob, Type[] types, int range)
		{
			IPooledEnumerable eable = mob.GetObjectsInRange(range);

			if (eable.OfType<IEntity>().Any(e => types.Any(t => e.TypeEquals(t))))
			{
				eable.Free();
				return true;
			}

			eable.Free();
			return false;
		}
 private static bool CheckIfAllowedTemplatesContainsDefaultTemplate(Type[] allowedTemplates, Type defaultTemplate)
 {
     return (allowedTemplates.Any() && !allowedTemplates.Contains(defaultTemplate));
 }