예제 #1
0
        internal IEnumerable <Path> FindMethods(string basePath, Type markedType, IList <Type> definitionsTypesList)
        {
            bool        addedSlash = false;
            List <Path> paths      = new List <Path>();
            List <Tuple <string, PathAction> > pathActions = new List <Tuple <string, PathAction> >();

            if (!basePath.EndsWith("/"))
            {
                addedSlash = true;
                basePath   = basePath + "/";
            }

            List <Type> types;
            Type        serviceType;

            if (markedType.IsInterface)
            {
                //search for service impl type
                var allTypes = AppDomain.CurrentDomain
                               .GetAssemblies()
                               .SelectMany(s => s.GetTypes())
                               .Where(type => markedType.IsAssignableFrom(type) && !type.IsInterface)
                               .ToList();

                serviceType = allTypes.Except(allTypes.Select(type => type.BaseType)).Single();

                types = new List <Type> {
                    markedType
                };
            }
            else
            {
                serviceType = markedType;

                //search all interfaces for this type for potential DataContracts, and build a set of items
                types = serviceType.GetInterfaces().ToList();
                types.Add(serviceType);
            }

            foreach (Type i in types)
            {
                Attribute dc = i.GetCustomAttribute(typeof(ServiceContractAttribute));
                if (dc == null)
                {
                    continue;
                }

                //found a DataContract, now get a service map and inspect the methods for WebGet/WebInvoke
                if (i.IsInterface)
                {
                    InterfaceMapping map = serviceType.GetInterfaceMap(i);
                    pathActions.AddRange(GetActions(map.TargetMethods, map.InterfaceMethods, definitionsTypesList));
                }
                else
                {
                    pathActions.AddRange(GetActions(i.GetMethods(), i.GetMethods(), definitionsTypesList));
                }
            }

            foreach (Tuple <string, PathAction> pathAction in pathActions)
            {
                string path = basePath;
                if (string.IsNullOrWhiteSpace(pathAction.Item1) && addedSlash)
                {
                    path = path.Substring(0, path.Length - 1);
                }

                GetPath(path, pathAction.Item1, paths).Actions.Add(pathAction.Item2);
            }

            return(paths);
        }
예제 #2
0
        // #lizard forgives
        unsafe static public VirtualMachine Load(Stream stream)
        {
            List <IntPtr> nativePointers = new List <IntPtr>();

            IntPtr        nativePointer;
            Instruction **unmanagedCodes = null;

            Type[]       externTypes;
            MethodBase[] externMethods;
            List <ExceptionHandler[]> exceptionHandlers = new List <ExceptionHandler[]>();

            string[]              internStrings;
            FieldInfo[]           fieldInfos;
            Type[]                staticFieldTypes;
            int[]                 cctors;
            AnonymousStoreyInfo[] anonymousStoreyInfos;

            using (BinaryReader reader = new BinaryReader(stream))
            {
                var instructionMagic = reader.ReadUInt64();
                if (instructionMagic != Instruction.INSTRUCTION_FORMAT_MAGIC)
                {
                    throw new Exception("instruction magic not match, expect "
                                        + Instruction.INSTRUCTION_FORMAT_MAGIC
                                        + ", but got " + instructionMagic);
                }

                var interfaceBridgeTypeName = reader.ReadString();
                var interfaceBridgeType     = Type.GetType(interfaceBridgeTypeName);
                if (interfaceBridgeType == null)
                {
                    throw new Exception("assembly may be not injected yet, cat find "
                                        + interfaceBridgeTypeName);
                }

                //BindingFlags flag = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static
                //    | BindingFlags.NonPublic |BindingFlags.Public;
                int externTypeCount = reader.ReadInt32();
                externTypes = new Type[externTypeCount];
                for (int i = 0; i < externTypeCount; i++)
                {
                    var assemblyQualifiedName = reader.ReadString();
                    externTypes[i] = Type.GetType(assemblyQualifiedName);
                    if (externTypes[i] == null)
                    {
                        throw new Exception("can not load type [" + assemblyQualifiedName + "]");
                    }
                }

                int methodCount = reader.ReadInt32();

                nativePointer  = System.Runtime.InteropServices.Marshal.AllocHGlobal(sizeof(Instruction *) * methodCount);
                unmanagedCodes = (Instruction **)nativePointer.ToPointer();
                nativePointers.Add(nativePointer);

                for (int j = 0; j < methodCount; j++)
                {
                    //Console.WriteLine("==================method" + j + "==================");
                    int codeSize = reader.ReadInt32();
                    nativePointer = System.Runtime.InteropServices.Marshal.AllocHGlobal(sizeof(Instruction) * codeSize);
                    var unmanagedCode = (Instruction *)nativePointer.ToPointer();
                    for (int i = 0; i < codeSize; i++)
                    {
                        unmanagedCode[i].Code    = (Code)reader.ReadInt32();
                        unmanagedCode[i].Operand = reader.ReadInt32();
                        //Console.WriteLine(i + " Code=" + unmanagedCode[i].Code + " Operand="
                        //    + unmanagedCode[i].Operand);
                    }
                    unmanagedCodes[j] = unmanagedCode;
                    nativePointers.Add(nativePointer);
                    ExceptionHandler[] ehsOfMethod = new ExceptionHandler[reader.ReadInt32()];
                    for (int i = 0; i < ehsOfMethod.Length; i++)
                    {
                        ExceptionHandler ehOfMethod = new ExceptionHandler();
                        ehOfMethod.HandlerType  = (ExceptionHandlerType)reader.ReadInt32();
                        ehOfMethod.CatchTypeId  = reader.ReadInt32();
                        ehOfMethod.TryStart     = reader.ReadInt32();
                        ehOfMethod.TryEnd       = reader.ReadInt32();
                        ehOfMethod.HandlerStart = reader.ReadInt32();
                        ehOfMethod.HandlerEnd   = reader.ReadInt32();
                        ehsOfMethod[i]          = ehOfMethod;
                        if (ehOfMethod.HandlerType == ExceptionHandlerType.Catch)
                        {
                            ehOfMethod.CatchType = ehOfMethod.CatchTypeId == -1 ?
                                                   typeof(object) : externTypes[ehOfMethod.CatchTypeId];
                        }
                    }
                    exceptionHandlers.Add(ehsOfMethod);
                }

                int externMethodCount = reader.ReadInt32();
                externMethods = new MethodBase[externMethodCount];
                for (int i = 0; i < externMethodCount; i++)
                {
                    externMethods[i] = readMethod(reader, externTypes);
                }

                int internStringsCount = reader.ReadInt32();
                internStrings = new string[internStringsCount];
                for (int i = 0; i < internStringsCount; i++)
                {
                    internStrings[i] = reader.ReadString();
                }

                fieldInfos = new FieldInfo[reader.ReadInt32()];
                for (int i = 0; i < fieldInfos.Length; i++)
                {
                    var type      = externTypes[reader.ReadInt32()];
                    var fieldName = reader.ReadString();
                    fieldInfos[i] = type.GetField(fieldName,
                                                  BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
                    if (fieldInfos[i] == null)
                    {
                        throw new Exception("can not load field [" + fieldName + "] of " + type);
                    }
                }

                staticFieldTypes = new Type[reader.ReadInt32()];
                cctors           = new int[staticFieldTypes.Length];
                for (int i = 0; i < staticFieldTypes.Length; i++)
                {
                    staticFieldTypes[i] = externTypes[reader.ReadInt32()];
                    cctors[i]           = reader.ReadInt32();
                }

                Dictionary <MethodInfo, int> itfMethodToId = new Dictionary <MethodInfo, int>();
                int maxId = 0;

                foreach (var itf in interfaceBridgeType.GetInterfaces())
                {
                    InterfaceMapping map = interfaceBridgeType.GetInterfaceMap(itf);
                    for (int i = 0; i < map.InterfaceMethods.Length; i++)
                    {
                        IDTagAttribute idTag = Attribute.GetCustomAttribute(map.TargetMethods[i],
                                                                            typeof(IDTagAttribute), false) as IDTagAttribute;
                        MethodInfo im = map.InterfaceMethods[i];
                        if (idTag == null)
                        {
                            throw new Exception(string.Format("can not find id for {0}", im));
                        }
                        int id = idTag.ID;
                        //VirtualMachine._Info(string.Format("{0} [{1}]", im, id));
                        maxId = id > maxId ? id : maxId;
                        itfMethodToId.Add(im, id);
                    }
                }

                anonymousStoreyInfos = new AnonymousStoreyInfo[reader.ReadInt32()];
                for (int i = 0; i < anonymousStoreyInfos.Length; i++)
                {
                    int   fieldNum   = reader.ReadInt32();
                    int[] fieldTypes = new int[fieldNum];
                    for (int fieldIdx = 0; fieldIdx < fieldNum; ++fieldIdx)
                    {
                        fieldTypes[fieldIdx] = reader.ReadInt32();
                    }
                    int ctorId       = reader.ReadInt32();
                    int ctorParamNum = reader.ReadInt32();
                    var slots        = readSlotInfo(reader, itfMethodToId, externTypes, maxId);

                    int   virtualMethodNum = reader.ReadInt32();
                    int[] vTable           = new int[virtualMethodNum];
                    for (int vm = 0; vm < virtualMethodNum; vm++)
                    {
                        vTable[vm] = reader.ReadInt32();
                    }
                    anonymousStoreyInfos[i] = new AnonymousStoreyInfo()
                    {
                        CtorId       = ctorId,
                        FieldNum     = fieldNum,
                        FieldTypes   = fieldTypes,
                        CtorParamNum = ctorParamNum,
                        Slots        = slots,
                        VTable       = vTable
                    };
                }


                var virtualMachine = new VirtualMachine(unmanagedCodes, () =>
                {
                    for (int i = 0; i < nativePointers.Count; i++)
                    {
                        System.Runtime.InteropServices.Marshal.FreeHGlobal(nativePointers[i]);
                    }
                })
                {
                    ExternTypes          = externTypes,
                    ExternMethods        = externMethods,
                    ExceptionHandlers    = exceptionHandlers.ToArray(),
                    InternStrings        = internStrings,
                    FieldInfos           = fieldInfos,
                    AnonymousStoreyInfos = anonymousStoreyInfos,
                    StaticFieldTypes     = staticFieldTypes,
                    Cctors = cctors
                };

                var             wrappersManagerImplName = reader.ReadString();
                WrappersManager wrapperManager          = Activator.CreateInstance(Type.GetType(wrappersManagerImplName, true),
                                                                                   virtualMachine) as WrappersManager;
                if (wrapperManager == null)
                {
                    throw new Exception("can not create WrappersManager!");
                }
                virtualMachine.WrappersManager = wrapperManager;

                var assemblyStr = reader.ReadString();
                var idMapList   = new List <Type>();
                for (int i = 0; i < 100; i++)
                {
                    var idMapType = Type.GetType("IFix.IDMAP" + i + assemblyStr, false);
                    if (idMapType == null)
                    {
                        break;
                    }
                    idMapList.Add(idMapType);
                }

                lock (removers)
                {
                    var    assembly = wrapperManager.GetType().Assembly;
                    Action remover;
                    if (removers.TryGetValue(assembly, out remover))
                    {
                        removers.Remove(assembly);
                        remover();
                    }

                    //int fixCount = reader.ReadInt32();
                    //FieldInfo[] toSet = new FieldInfo[fixCount];

                    //for (int i = 0; i < fixCount; i++)
                    //{
                    //    var fixMethod = readMethod(reader, externTypes);
                    //    var fixMethodIdx = reader.ReadInt32();
                    //    var redirectField = getRedirectField(fixMethod);
                    //    toSet[i] = redirectField;
                    //    var wrapper = wrapperManager.CreateWrapper(fixMethodIdx);
                    //    if (wrapper == null)
                    //    {
                    //        throw new Exception("create wrapper fail");
                    //    }
                    //    redirectField.SetValue(null, wrapper);
                    //}

                    //removers[assembly] = () =>
                    //{
                    //    for (int i = 0; i < fixCount; i++)
                    //    {
                    //        toSet[i].SetValue(null, null);
                    //    }
                    //};

                    int   fixCount      = reader.ReadInt32();
                    int[] methodIdArray = new int[fixCount];
                    int[] posArray      = new int[fixCount];
                    int   maxPos        = -1;
                    for (int i = 0; i < fixCount; i++)
                    {
                        var fixMethod   = readMethod(reader, externTypes);
                        var fixMethodId = reader.ReadInt32();
                        var pos         = getMapId(idMapList, fixMethod);
                        methodIdArray[i] = fixMethodId;
                        posArray[i]      = pos;
                        if (pos > maxPos)
                        {
                            maxPos = pos;
                        }
                    }
                    Array arr = wrapperManager.InitWrapperArray(maxPos + 1) as Array;
                    for (int i = 0; i < fixCount; i++)
                    {
                        var wrapper = wrapperManager.CreateWrapper(methodIdArray[i]);
                        if (wrapper == null)
                        {
                            throw new Exception("create wrapper fail");
                        }
                        arr.SetValue(wrapper, posArray[i]);
                    }
                    removers[assembly] = () =>
                    {
                        wrapperManager.InitWrapperArray(0);
                    };
                }

                int newClassCount = reader.ReadInt32();
                for (int i = 0; i < newClassCount; i++)
                {
                    var newClassFullName = reader.ReadString();
                    var newClassName     = Type.GetType(newClassFullName);
                    if (newClassName != null)
                    {
                        throw new Exception(newClassName + " class is expected to be a new class , but it already exists ");
                    }
                }

                return(virtualMachine);
            }
        }
예제 #3
0
        // We cache this by mapping MemberInfo to MemberInfo in our
        // cache.  Note that because assemblies can never be unloaded,
        // there's no reason to flush this cache (we won't be holding
        // anything alive longer than it would have been alive anyway.
        public static MemberInfo ConvertToInterfaceMI(MemberInfo mi)
        {
            // First, try to hit the cache:
            MemberInfo cmi = (MemberInfo)Cache.Get(mi);

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

            // Failed to hit the cache, do the lookup.
            // TODO: clean this up a bit.
            // TODO: Deal with non-methodInfo objects (work off MethodBase)
            MethodInfo minfo = mi as MethodInfo;

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

            MethodInfo intfMethodInfo = null;

            // check for AutoDone
            Type reflectType = minfo.ReflectedType;

            if (reflectType.IsInterface)
            {
                intfMethodInfo = minfo;
            }
            else
            {
                // get all the interfaces implemented by the class
                Type[] rgInterfaces = reflectType.GetInterfaces();
                if (rgInterfaces == null)
                {
                    return(null);
                }

                // iterate through all the interfaces
                for (int ii = 0; ii < rgInterfaces.Length; ii++)
                {
                    // get interface mapping for each interface
                    InterfaceMapping imap = reflectType.GetInterfaceMap(rgInterfaces[ii]);

                    if (imap.TargetMethods == null)
                    {
                        continue;
                    }

                    // check if a class method in this inteface map matches
                    for (int j = 0; j < imap.TargetMethods.Length; j++)
                    {
                        // see if the class method matches
                        if (imap.TargetMethods[j] == minfo)
                        {
                            // grab the interface method
                            intfMethodInfo = imap.InterfaceMethods[j];
                            break;
                        }
                    }

                    if (intfMethodInfo != null)
                    {
                        break;
                    }
                }
            }

            DBG.Assert(intfMethodInfo == null ||
                       intfMethodInfo.ReflectedType.IsInterface,
                       "Failed to map class method to interface method");

            Cache.Reset(mi, intfMethodInfo);

            return((MemberInfo)intfMethodInfo);
        }
예제 #4
0
        public static MemberInfo ConvertToClassMI(Type t, MemberInfo mi)
        {
            // get reflected type
            Type reflectType = mi.ReflectedType;

            if (!reflectType.IsInterface)
            {
                return(mi);
            }

            // First, try to hit the cache.  We look for the cache entry
            // for this type, and it should be a little cache-table
            // of it's own.  In that cache-table, we
            Cachetable subcache = (Cachetable)Cache.Get(t);

            if (subcache != null)
            {
                MemberInfo cmi = (MemberInfo)subcache.Get(mi);
                if (cmi != null)
                {
                    return(cmi);
                }
            }

            DBG.Assert(t != null, "class type is null");
            DBG.Assert(!t.IsInterface, " class type is actually an interface");

            MethodInfo minfo         = (MethodInfo)mi;
            MethodInfo clsMethodInfo = null;

            // minfo is an interface member info, map it to class memeber info

            // get the interface map
            DBG.Info(DBG.SC, "ReflectionCache: Looking up " + reflectType + " on " + t);
            InterfaceMapping imap = t.GetInterfaceMap(reflectType);

            if (imap.TargetMethods == null)
            {
                throw new InvalidCastException();
            }
            for (int i = 0; i < imap.TargetMethods.Length; i++)
            {
                if (imap.InterfaceMethods[i] == minfo)
                {
                    clsMethodInfo = imap.TargetMethods[i];
                    break;
                }
            }

            DBG.Assert(clsMethodInfo != null, "Failed to map interface method to class method");
            DBG.Assert(!clsMethodInfo.ReflectedType.IsInterface,
                       "Failed to map interface method to class method");

            // Store the result in the cache:
            if (subcache == null)
            {
                subcache = (Cachetable)Cache.Set(t, new Cachetable());
            }

            subcache.Reset(mi, clsMethodInfo);

            return((MemberInfo)clsMethodInfo);
        }
예제 #5
0
        //public void AddType<T>(string serviceAddress)
        //{
        //    AddType(typeof(T), serviceAddress);
        //}

        private void Init()
        {
            string        errMsg       = null;
            Type          type         = m_instance.GetType();
            bool          hasOperation = false;
            List <string> methodNames  = new List <string>();

            foreach (Type iType in type.GetInterfaces())
            {
                ServiceContractAttribute serviceContractAttr = iType.GetCustomAttribute <ServiceContractAttribute>(true);
                if (serviceContractAttr != null)
                {
                    InterfaceMapping map = type.GetInterfaceMap(iType);
                    for (int i = 0; i < map.InterfaceMethods.Length; i++)
                    {
                        OperationContractAttribute operationContractAttr = map.InterfaceMethods[i].GetCustomAttribute <OperationContractAttribute>(true);
                        if (operationContractAttr != null)
                        {
                            hasOperation = true;
                            string     action       = GetAction(serviceContractAttr, iType.Name, operationContractAttr, map.InterfaceMethods[i].Name);
                            MethodInfo targetMethod = map.TargetMethods[i];
                            AddOperation(action, targetMethod);
                        }
                    }
                }
            }
            {
                ServiceContractAttribute serviceContractAttr = type.GetCustomAttribute <ServiceContractAttribute>();
                if (hasOperation)
                {
                    if (serviceContractAttr != null)
                    {
                        errMsg = String.Format("{0} cannot in both interface and class!", typeof(ServiceContractAttribute).Name);
                        throw new InvalidOperationException(errMsg);
                    }
                }
                else if (serviceContractAttr == null)
                {
                    errMsg = String.Format("No {0} define in type {1}!", typeof(ServiceContractAttribute).Name, type.Name);
                    throw new InvalidOperationException(errMsg);
                }
                else
                {
                    MethodInfo[] methods = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
                    foreach (MethodInfo method in methods)
                    {
                        OperationContractAttribute operationContractAttr = method.GetCustomAttribute <OperationContractAttribute>(true);
                        if (operationContractAttr != null)
                        {
                            hasOperation = true;
                            string action = GetAction(serviceContractAttr, type.Name, operationContractAttr, method.Name);
                            AddOperation(action, method);
                        }
                    }
                }
                if (!hasOperation)
                {
                    errMsg = String.Format("No method mark as {0}!", typeof(OperationContractAttribute).Name);
                    throw new InvalidOperationException(errMsg);
                }
            }
        }
예제 #6
0
        protected override void BuildInterfaceMethod()
        {
            bool returnIfNonZero = false;
            bool returnIfZero    = false;

            if (Context.ReturnValue != null)
            {
                object[] attrs =
                    Context.MethodBuilder.OverriddenMethod.ReturnTypeCustomAttributes.GetCustomAttributes(true);

                foreach (object o in attrs)
                {
                    if (o is ReturnIfNonZeroAttribute)
                    {
                        returnIfNonZero = true;
                    }
                    else if (o is ReturnIfZeroAttribute)
                    {
                        returnIfZero = true;
                    }
                }
            }

            Type       interfaceType = Context.CurrentInterface;
            EmitHelper emit          = Context.MethodBuilder.Emitter;

            foreach (DictionaryEntry de in Context.Fields)
            {
                PropertyInfo property = (PropertyInfo)de.Key;
                FieldBuilder field    = (FieldBuilder)de.Value;

                if (field.FieldType.IsPrimitive || field.FieldType == typeof(string))
                {
                    continue;
                }

                Type[] types = field.FieldType.GetInterfaces();

                foreach (Type type in types)
                {
                    if (type != interfaceType)
                    {
                        continue;
                    }

                    InterfaceMapping im = field.FieldType.GetInterfaceMap(type);

                    for (int j = 0; j < im.InterfaceMethods.Length; j++)
                    {
                        if (im.InterfaceMethods[j] == Context.MethodBuilder.OverriddenMethod)
                        {
                            MethodInfo targetMethod = im.TargetMethods[j];

                            Label label     = new Label();
                            bool  checkNull = false;

                            if (CallLazyInstanceInsurer(field) == false && field.FieldType.IsClass)
                            {
                                // Check if field is null.
                                //
                                checkNull = true;

                                label = emit.DefineLabel();

                                emit
                                .ldarg_0
                                .ldfld(field)
                                .brfalse_s(label)
                                ;
                            }

                            // this.
                            //
                            emit
                            .ldarg_0
                            .end();

                            // Load the field and prepare it for interface method call if the method is private.
                            //
                            if (field.FieldType.IsValueType)
                            {
                                if (targetMethod.IsPublic)
                                {
                                    emit.ldflda(field);
                                }
                                else
                                {
                                    emit
                                    .ldfld(field)
                                    .box(field.FieldType);
                                }
                            }
                            else
                            {
                                if (targetMethod.IsPublic)
                                {
                                    emit.ldfld(field);
                                }
                                else
                                {
                                    emit
                                    .ldfld(field)
                                    .castclass(interfaceType);
                                }
                            }

                            // Check parameter attributes.
                            //
                            ParameterInfo[] pi = Context.MethodBuilder.OverriddenMethod.GetParameters();

                            for (int k = 0; k < pi.Length; k++)
                            {
                                object[] attrs = pi[k].GetCustomAttributes(true);
                                bool     stop  = false;

                                foreach (object a in attrs)
                                {
                                    // Parent - set this.
                                    //
                                    if (a is ParentAttribute)
                                    {
                                        emit
                                        .ldarg_0
                                        .end()
                                        ;

                                        if (!TypeHelper.IsSameOrParent(pi[k].ParameterType, Context.Type))
                                        {
                                            emit
                                            .castclass(pi[k].ParameterType)
                                            ;
                                        }

                                        stop = true;

                                        break;
                                    }

                                    // PropertyInfo.
                                    //
                                    if (a is PropertyInfoAttribute)
                                    {
                                        FieldBuilder ifb = GetPropertyInfoField(property);

                                        emit.ldsfld(ifb);
                                        stop = true;

                                        break;
                                    }
                                }

                                if (stop)
                                {
                                    continue;
                                }

                                // Pass argument.
                                //
                                emit.ldarg((byte)(k + 1));
                            }

                            // Call the method.
                            //
                            if (field.FieldType.IsValueType)
                            {
                                if (targetMethod.IsPublic)
                                {
                                    emit.call(targetMethod);
                                }
                                else
                                {
                                    emit.callvirt(im.InterfaceMethods[j]);
                                }
                            }
                            else
                            {
                                if (targetMethod.IsPublic)
                                {
                                    emit.callvirt(targetMethod);
                                }
                                else
                                {
                                    emit.callvirt(im.InterfaceMethods[j]);
                                }
                            }

                            // Return if appropriated result.
                            //
                            if (Context.ReturnValue != null)
                            {
                                emit.stloc(Context.ReturnValue);

                                if (returnIfNonZero)
                                {
                                    emit
                                    .ldloc(Context.ReturnValue)
                                    .brtrue(Context.ReturnLabel);
                                }
                                else if (returnIfZero)
                                {
                                    emit
                                    .ldloc(Context.ReturnValue)
                                    .brfalse(Context.ReturnLabel);
                                }
                            }

                            if (checkNull)
                            {
                                emit.MarkLabel(label);
                            }

                            break;
                        }
                    }

                    break;
                }
            }
        }
        /// <summary>
        /// Internal method that's used to parse the currently selected object
        /// parsing methods and properties and the various object properties including
        /// object inheritance etc.
        /// </summary>
        /// <param name="dotnetObject"></param>
        /// <param name="type"></param>
        /// <param name="dontParseMethods"></param>
        protected void ParseObject(DotnetObject dotnetObject, Type type, bool dontParseMethods)
        {
            // *** Pass down high level options
            dotnetObject.Name        = type.Name;
            dotnetObject.RawTypeName = type.Name;

            dotnetObject.Syntax = cSyntax;
            dotnetObject.RetrieveDeclaredMembersOnly = RetrieveDeclaredMembersOnly;

            bool IsVb = cSyntax.StartsWith("VB");

            // *** If we have a generic type strip off
            if (type.IsGenericType)
            {
                dotnetObject.Name = DotnetObject.GetGenericTypeName(type, GenericTypeNameFormats.TypeName);
            }

            dotnetObject.FormattedName = dotnetObject.TypeNameForLanguage(dotnetObject.Name);


            // *** Parse basic type features
            if (type.IsPublic || type.IsNestedPublic)
            {
                dotnetObject.Scope = "public";
            }
            if (!type.IsVisible)
            {
                dotnetObject.Scope    = "internal";
                dotnetObject.Internal = true;
            }
            else if (type.IsNotPublic || type.IsNestedPrivate)
            {
                dotnetObject.Scope = "private";
            }

            if (IsVb)
            {
                dotnetObject.Scope = StringUtils.ProperCase(dotnetObject.Scope);
            }

            if (type.IsSealed && type.IsAbstract)
            {
                dotnetObject.Other = "static";
            }
            else
            {
                if (type.IsSealed)
                {
                    if (IsVb)
                    {
                        dotnetObject.Other = "NotInheritable";
                    }
                    else
                    {
                        dotnetObject.Other = "sealed";
                    }
                }

                if (type.IsAbstract)
                {
                    if (IsVb)
                    {
                        dotnetObject.Other = "MustInherit";
                    }
                    else
                    {
                        dotnetObject.Other += "abstract";
                    }
                }
            }

            // *** Get the type 'signature'
            dotnetObject.Signature    = type.FullName;
            dotnetObject.RawSignature = dotnetObject.Signature;

            //// *** Generic Type: Replace signature wwBusiness`1 with wwBusiness<EntityType> (cName)
            //if (loType.IsGenericType)
            //    loObject.cSignature = loObject.cSignature.Substring(0, loObject.cSignature.LastIndexOf(".")+1) + loObject.cName;

            dotnetObject.Namespace = type.Namespace;
            dotnetObject.Assembly  = type.Assembly.CodeBase;
            dotnetObject.Assembly  = dotnetObject.Assembly.Substring(dotnetObject.Assembly.LastIndexOf("/") + 1);

            dotnetObject.Type = "class";
            if (type.IsInterface)
            {
                dotnetObject.Type = "interface";
            }
            else if (type.IsEnum)
            {
                dotnetObject.Type = "enum";
            }
            else if (type.IsValueType)
            {
                dotnetObject.Type = "struct";
            }

            // *** Figure out the base type and build inheritance tree
            // *** for this class
            if (type.BaseType != null)
            {
                string BaseTypeName = null;
                if (type.BaseType.IsGenericType)
                {
                    //BaseTypeName = DotnetObject.GetGenericTypeName(type.BaseType, GenericTypeNameFormats.TypeName);
                    //else
                    BaseTypeName = type.BaseType.Name;
                }

                dotnetObject.InheritsFrom = dotnetObject.TypeNameForLanguage(BaseTypeName);

                if (dotnetObject.InheritsFrom == "MulticastDelegate" || dotnetObject.InheritsFrom == "Delegate")
                {
                    dotnetObject.Type = "delegate";
                }

                Type[] Implementations = type.GetInterfaces();

                if (Implementations != null)
                {
                    foreach (Type Implementation in Implementations)
                    {
                        // *** This will work AS LONG AS THE INTERFACE HAS AT LEAST ONE MEMBER!
                        // *** This will give not show an 'empty' placeholder interface
                        // *** Can't figure out a better way to do this...
                        InterfaceMapping im = type.GetInterfaceMap(Implementation);
                        if (im.TargetMethods.Length > 0 && im.TargetMethods[0].DeclaringType == type)
                        {
                            if (Implementation.IsGenericType)
                            {
                                dotnetObject.Implements += DotnetObject.GetGenericTypeName(Implementation, GenericTypeNameFormats.TypeName) + ",";
                            }
                            else
                            {
                                dotnetObject.Implements += Implementation.Name + ",";
                            }
                        }
                    }
                    if (dotnetObject.Implements != "")
                    {
                        dotnetObject.Implements = dotnetObject.Implements.TrimEnd(',');
                    }
                }


                // *** Create the Inheritance Tree
                List <string> Tree    = new List <string>();
                Type          Current = type;
                while (Current != null)
                {
                    if (Current.IsGenericType)
                    {
                        Tree.Add(dotnetObject.TypeNameForLanguage(DotnetObject.GetGenericTypeName(Current, GenericTypeNameFormats.FullTypeName)));
                    }
                    else
                    {
                        Tree.Add(Current.FullName);
                    }

                    Current = Current.BaseType;
                }

                // *** Walk our list backwards to build the string
                for (int z = Tree.Count - 1; z >= 0; z--)
                {
                    dotnetObject.InheritanceTree += Tree[z] + "\r\n";
                }
            }

            if (!dontParseMethods)
            {
                //dotnetObject.LoadMethods(type);
                //dotnetObject.LoadProperties(type);
                //dotnetObject.LoadEvents(type);
            }
        }
예제 #8
0
        public static XmlRpcServiceInfo CreateServiceInfo(Type type)
        {
            XmlRpcServiceInfo svcInfo = new XmlRpcServiceInfo();
            // extract service info
            XmlRpcServiceAttribute svcAttr = (XmlRpcServiceAttribute)
                                             Attribute.GetCustomAttribute(type, typeof(XmlRpcServiceAttribute));

            if (svcAttr != null && svcAttr.Description != "")
            {
                svcInfo.doc = svcAttr.Description;
            }
            if (svcAttr != null && svcAttr.Name != "")
            {
                svcInfo.Name = svcAttr.Name;
            }
            else
            {
                svcInfo.Name = type.Name;
            }
            // extract method info
            Hashtable methods = new Hashtable();

            foreach (Type itf in type.GetInterfaces())
            {
                XmlRpcServiceAttribute itfAttr = (XmlRpcServiceAttribute)
                                                 Attribute.GetCustomAttribute(itf, typeof(XmlRpcServiceAttribute));
                if (itfAttr != null)
                {
                    svcInfo.doc = itfAttr.Description;
                }
#if (!COMPACT_FRAMEWORK)
                InterfaceMapping imap = type.GetInterfaceMap(itf);
                foreach (MethodInfo mi in imap.InterfaceMethods)
                {
                    ExtractMethodInfo(methods, mi, itf);
                }
#else
                foreach (MethodInfo mi in itf.GetMethods())
                {
                    ExtractMethodInfo(methods, mi, itf);
                }
#endif
            }

            foreach (MethodInfo mi in type.GetMethods())
            {
                ArrayList mthds = new ArrayList();
                mthds.Add(mi);
                MethodInfo curMi = mi;
                while (true)
                {
                    MethodInfo baseMi = curMi.GetBaseDefinition();
                    if (baseMi.DeclaringType == curMi.DeclaringType)
                    {
                        break;
                    }
                    mthds.Insert(0, baseMi);
                    curMi = baseMi;
                }
                foreach (MethodInfo mthd in mthds)
                {
                    ExtractMethodInfo(methods, mthd, type);
                }
            }
            svcInfo.methodInfos = new XmlRpcMethodInfo[methods.Count];
            methods.Values.CopyTo(svcInfo.methodInfos, 0);
            Array.Sort(svcInfo.methodInfos);
            return(svcInfo);
        }
예제 #9
0
 public InterfaceMembersOnClassCollector(Type type, bool onlyProxyVirtual, InterfaceMapping map) : base(type)
 {
     this.onlyProxyVirtual = onlyProxyVirtual;
     this.map = map;
 }
예제 #10
0
 public abstract InterfaceMapping ProjectInterfaceMapping(InterfaceMapping value);
예제 #11
0
        public void Export <T>(U objectFrom, IEnumerable <FieldInfo> fieldGetters, List <T> toList)
        {
            deep++;
            if (Type.GetTypeCode(typeof(T)) == TypeCode.Object)
            {
                List <List <FieldInfo> > groupedGetters = new List <List <FieldInfo> >();
                int  index   = 0;
                int  ddCount = 0;
                bool create  = toList.Count == 0;
                foreach (FieldInfo fi in fieldGetters)
                {
                    int  level       = deep;
                    int  position    = 0;
                    bool doubleDigit = false;
                    foreach (char c in fi.Name)
                    {
                        position++;
                        if (Char.IsDigit(c) && doubleDigit == false)
                        {
                            if (level > 1)
                            {
                                level--;
                                continue;
                            }
                            int newIndex;
                            if (position + 1 == fi.Name.Length)
                            {
                                doubleDigit = true;
                                newIndex    = Int32.Parse(fi.Name.Substring(position - 1, 2));                             // Double Digit Index
                            }
                            else
                            {
                                Char[] testChar = fi.Name.Substring(position - 2, 1).ToCharArray();
                                if (Char.IsDigit(testChar[0]))
                                {
                                    newIndex = Int32.Parse(fi.Name.Substring(position - 2, 2));
                                }
                                else
                                {
                                    newIndex = Int32.Parse(c.ToString());
                                }

                                /*
                                 * try {
                                 *      newIndex = Int32.Parse(fi.Name.Substring(position - 2, 2));
                                 * }
                                 * catch {
                                 *      newIndex = Int32.Parse(c.ToString());
                                 * }*/
                            }
                            if (newIndex != index)
                            {
                                if (create)
                                {
                                    T instance = default(T);
                                    if (typeof(T).IsAbstract)
                                    {
                                        InterfaceMapping iMap = default(InterfaceMapping);
                                        try {
                                            iMap = typeof(U).GetInterfaceMap(typeof(IAdvice));
                                        } catch (ArgumentException) { }
                                        if (iMap.InterfaceMethods != null)
                                        {
                                            Type type = ((IAdvice)objectFrom).GetClassType(fi);
                                            if (type != null && type.IsSubclassOf(typeof(T)))
                                            {
                                                instance = (T)Activator.CreateInstance(type);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        instance = Activator.CreateInstance <T>();
                                    }
                                    if (instance == null)
                                    {
                                        index++;
                                        break;
                                    }
                                    toList.Add(instance);
                                }
                                groupedGetters.Add(new List <FieldInfo> {
                                    fi
                                });
                                if (doubleDigit == false)
                                {
                                    index++;
                                }
                                else
                                {
                                    ddCount++;
                                }
                            }
                            else
                            {
                                groupedGetters.Last().Add(fi);
                            }
                            break;
                        }
                    }
                }
                index = index + ddCount;
                if (index == 0 && fieldGetters.Count() == 1)
                {
                    T instance = Activator.CreateInstance <T>();
                    groupedGetters.Add(new List <FieldInfo> {
                        fieldGetters.First()
                    });
                    toList.Add(instance);
                }
                for (int i = 0; i < groupedGetters.Count; i++)
                {
                    if (toList.Count - 1 < i)
                    {
                        break;
                    }
                    IDynamicImport <U> dynAdd = (IDynamicImport <U>)toList[i];
                    dynAdd.Import(objectFrom, groupedGetters[i]);
                }
            }
            else
            {
                foreach (var getter in fieldGetters)
                {
                    if (typeof(T).Equals(getter.FieldType))
                    {
                        T item = (T)getter.GetValue(objectFrom);
                        if (item != null)
                        {
                            toList.Add(item);
                        }
                    }
                }
            }
            deep--;
        }
예제 #12
0
        /// <summary>
        /// Validates all controller classes in the provided enumberble
        ///  (ie. from an assembly.GetTypes() call) for
        ///  their service interfaces checking for any discrepancies.
        /// Discrepancies are reported as exceptions allowing one to hook
        ///  this into the server startup or unit testing to catch problems.
        /// </summary>
        public static void ValidateControllers(IEnumerable <Type> types)
        {
            foreach (Type t in types)
            {
                if (t.IsClass && t.BaseType.Equals(typeof(Controller)))
                {
                    foreach (Type i in t.GetInterfaces())
                    {
                        IEnumerable <Microsoft.AspNetCore.Mvc.RouteAttribute> iRouteAttributes = i.GetCustomAttributes <Microsoft.AspNetCore.Mvc.RouteAttribute>();
                        IEnumerable <Microsoft.AspNetCore.Mvc.RouteAttribute> tRouteAttributes = t.GetCustomAttributes <Microsoft.AspNetCore.Mvc.RouteAttribute>();

                        if (iRouteAttributes.Count() > tRouteAttributes.Count())
                        {
                            throw new Exception("In controller " + t.FullName + " the number of [Route] custom attributes doesn't match the interface " + i.FullName);
                        }

                        foreach (Microsoft.AspNetCore.Mvc.RouteAttribute route1 in iRouteAttributes)
                        {
                            bool matched = false;
                            foreach (Microsoft.AspNetCore.Mvc.RouteAttribute route2 in tRouteAttributes)
                            {
                                if (Object.Equals(route1.Template, route2.Template) &&
                                    route1.Order == route2.Order &&
                                    Object.Equals(route1.Name, route2.Name))
                                {
                                    matched = true;
                                    break;
                                }
                            }

                            if (!matched)
                            {
                                throw new Exception("In controller " + t.FullName + " the annotation [Route(" + route1.Template + ", Name=\"" + route1.Name + "\", Order=" + route1.Order + ")] on interface " + i.FullName + " is not found");
                            }
                        }

                        InterfaceMapping mapping = t.GetInterfaceMap(i);

                        for (int idx = 0; idx < mapping.InterfaceMethods.Length; idx++)
                        {
                            MethodInfo m1 = mapping.InterfaceMethods[idx];
                            MethodInfo m2 = mapping.TargetMethods[idx];

                            var m1RouteAttributes = m1.GetCustomAttributes <Microsoft.AspNetCore.Mvc.RouteAttribute>();
                            var m2RouteAttributes = m2.GetCustomAttributes <Microsoft.AspNetCore.Mvc.RouteAttribute>();

                            if (m1RouteAttributes.Count() > m2RouteAttributes.Count())
                            {
                                throw new Exception("In controller " + t.FullName + " on method " + m2 + " there is a mismatch on the number of [Route] attributes on interface " + i.FullName);
                            }

                            foreach (Microsoft.AspNetCore.Mvc.RouteAttribute route1 in m1RouteAttributes)
                            {
                                bool matched = false;
                                foreach (Microsoft.AspNetCore.Mvc.RouteAttribute route2 in m2RouteAttributes)
                                {
                                    if (Object.Equals(route1.Template, route2.Template) &&
                                        route1.Order == route2.Order &&
                                        Object.Equals(route1.Name, route2.Name))
                                    {
                                        matched = true;
                                        break;
                                    }
                                }

                                if (!matched)
                                {
                                    throw new Exception("In controller " + t.FullName + " the annotation [Route(\"" + route1.Template + "\", Name=\"" + route1.Name + "\", Order=" + route1.Order + ")] on interface " + i.FullName + " was not applied to method " + m1);
                                }
                            }

                            var m1MethodAttr = m1.GetCustomAttributes <HttpMethodAttribute>();
                            var m2MethodAttr = m2.GetCustomAttributes <HttpMethodAttribute>();

                            if (m1MethodAttr.Count() > m2MethodAttr.Count())
                            {
                                throw new Exception("In controller " + t.FullName + " on method " + m2 + " there is a mismatch on the number of [Http*] attributes on interface " + i.FullName);
                            }

                            foreach (HttpMethodAttribute methodAttr1 in m1MethodAttr)
                            {
                                bool matched = false;
                                foreach (HttpMethodAttribute methodAttr2 in m2MethodAttr)
                                {
                                    if (Object.Equals(methodAttr1.Template, methodAttr2.Template) &&
                                        methodAttr1.Order == methodAttr2.Order &&
                                        Object.Equals(methodAttr1.Name, methodAttr2.Name) &&
                                        Object.Equals(methodAttr1.GetType(), methodAttr2.GetType()))
                                    {
                                        matched = true;
                                        break;
                                    }
                                }

                                if (!matched)
                                {
                                    throw new Exception("In controller " + t.FullName + " the annotation [" + methodAttr1.GetType().Name + "(" + methodAttr1.Template + ", Name=\"" + methodAttr1.Name + "\", Order=" + methodAttr1.Order + ")] on interface " + i.FullName + " was not applied to method " + m1);
                                }
                            }

                            var m1RespTypeAttributes = m1.GetCustomAttributes <ProducesResponseTypeAttribute>();
                            var m2RespTypeAttributes = m2.GetCustomAttributes <ProducesResponseTypeAttribute>();

                            if (m1RespTypeAttributes.Count() > m2RespTypeAttributes.Count())
                            {
                                throw new Exception("In controller " + t.FullName + " on method " + m2 + " there is a mismatch on the number of [ProducesResponseType] attributes on interface " + i.FullName);
                            }

                            foreach (ProducesResponseTypeAttribute respTypeAttr1 in m1RespTypeAttributes)
                            {
                                bool matched = false;
                                foreach (ProducesResponseTypeAttribute respTypeAttr2 in m2RespTypeAttributes)
                                {
                                    if (Object.Equals(respTypeAttr1.Type, respTypeAttr2.Type) &&
                                        Object.Equals(respTypeAttr1.StatusCode, respTypeAttr2.StatusCode))
                                    {
                                        matched = true;
                                        break;
                                    }
                                }

                                if (!matched)
                                {
                                    throw new Exception("In controller " + t.FullName + " the annotation [ProducesResponseType(" + respTypeAttr1.Type.Name + ", " + respTypeAttr1.StatusCode + ")] on interface " + i.FullName + " was not applied to method " + m1);
                                }
                            }
                        }
                    }
                }
            }
        }
예제 #13
0
        /// <summary>
        /// add detail member to js type definition
        /// </summary>
        /// <param name="source"></param>
        /// <param name="targetTypeDef"></param>
        /// <returns></returns>
        void AddTypeDefinitionDetail(Type source, JsTypeDefinition targetTypeDef)
        {
            //------------------------------
            //this is sample only ***
            //------------------------------

            JsTypeAttribute foundJsTypeAttr = FindSingleCustomAttr <JsTypeAttribute>(source);

            Type[] interfaces = source.GetInterfaces();
            Dictionary <string, JsPropertyDefinition> declarProps = new Dictionary <string, JsPropertyDefinition>();

            for (int i = interfaces.Length - 1; i >= 0; --i)
            {
                Type i_interface = interfaces[i];
                //check if an interface has Js...attribute or not
                JsTypeAttribute foundJsTypeAttr2 = FindSingleCustomAttr <JsTypeAttribute>(i_interface);
                if (foundJsTypeAttr2 != null)
                {
                    InterfaceMapping interfaceMapping = source.GetInterfaceMap(i_interface);
                    //all members is
                    int m = interfaceMapping.InterfaceMethods.Length;
                    for (int n = 0; n < m; ++n)
                    {
                        MethodInfo interface_met = interfaceMapping.InterfaceMethods[n];
                        MethodInfo target_met    = interfaceMapping.TargetMethods[n];
                        if (!target_met.IsPublic)
                        {
                            //if this is public we will add it later***
                            if (target_met.IsSpecialName)
                            {
                                //eg. property ?
                                string metName = GetProperMemberName(target_met);
                                if (metName.StartsWith("get_"))
                                {
                                    string onlyPropName = metName.Substring(4);
                                    //property get
                                    JsPropertyDefinition existingProp;
                                    if (!declarProps.TryGetValue(onlyPropName, out existingProp))
                                    {
                                        existingProp = new JsPropertyDefinition(onlyPropName);
                                        declarProps.Add(onlyPropName, existingProp);
                                    }
                                    existingProp.GetterMethod = new JsPropertyGetDefinition(metName, target_met);
                                }
                                else if (metName.StartsWith("set_"))
                                {
                                    //property set
                                    string onlyPropName = metName.Substring(4);
                                    //property get
                                    JsPropertyDefinition existingProp;
                                    if (!declarProps.TryGetValue(onlyPropName, out existingProp))
                                    {
                                        existingProp = new JsPropertyDefinition(onlyPropName);
                                        declarProps.Add(onlyPropName, existingProp);
                                    }
                                    existingProp.SetterMethod = new JsPropertySetDefinition(metName, target_met);
                                }
                            }
                            else
                            {
                                JsMethodAttribute foundJsMetAttr = FindSingleCustomAttr <JsMethodAttribute>(target_met);
                                string            metName;
                                if (foundJsMetAttr != null)
                                {
                                    metName = foundJsMetAttr.Name ?? GetProperMemberName(target_met);
                                }
                                else
                                {
                                    metName = GetProperMemberName(target_met);
                                }
                                targetTypeDef.AddMember(new JsMethodDefinition(metName, target_met));
                            }
                        }
                    }
                }
            }
            //------------------------------
            int propCount = declarProps.Count;

            if (declarProps.Count > 0)
            {
                foreach (JsPropertyDefinition prop in declarProps.Values)
                {
                    targetTypeDef.AddMember(prop);
                }
            }
            //------------------------------
            MethodInfo[] methods = source.GetMethods(
                System.Reflection.BindingFlags.Instance |
                System.Reflection.BindingFlags.Public);

            foreach (var met in methods)
            {
                if (met.IsSpecialName)
                {
                    continue;
                }
                JsMethodAttribute foundJsMetAttr = FindSingleCustomAttr <JsMethodAttribute>(met);
                if (foundJsMetAttr != null)
                {
                    targetTypeDef.AddMember(new JsMethodDefinition(foundJsMetAttr.Name ?? GetProperMemberName(met), met));
                }
                //in this version,
                //if not found js attr, -> not expose it
            }
            var properties = source.GetProperties(System.Reflection.BindingFlags.Instance
                                                  | System.Reflection.BindingFlags.Public);

            foreach (var property in properties)
            {
                JsPropertyAttribute foundJsPropAttr = FindSingleCustomAttr <JsPropertyAttribute>(property);
                if (foundJsPropAttr != null)
                {
                    targetTypeDef.AddMember(new JsPropertyDefinition(foundJsPropAttr.Name ?? GetProperMemberName(property), property));
                }
                //in this version,
                //if not found js attr, -> not expose it
            }
        }