Exemple #1
0
        private string GetTypeAttributes(TypeAttributes attr)
        {
            string result = "";

            if (attr.HasFlag(TypeAttributes.Public))
            {
                result += "public ";
            }
            if (attr.HasFlag(TypeAttributes.Sealed))
            {
                result += "sealed ";
            }
            if (attr.HasFlag(TypeAttributes.Abstract))
            {
                if (attr.HasFlag(TypeAttributes.Interface))
                {
                    result += "interface";
                }
                else
                {
                    result += "abstract class";
                }
            }
            else
            {
                result += "class";
            }
            return(result);
        }
Exemple #2
0
        /// <summary>
        /// 初始化环境,3.5 使用
        /// </summary>
        /// <param name="types">需要初始化调用的静态类</param>
        public void Init(IEnumerable <Type> types)
        {
            if (_haveInit)
            {
                return;
            }

            container = new FrameworkContainer();
            _modules  = new FrameworkModules(this);
            cyclePool = new RecyclableObjectPool();
            if (types != null)
            {
                types.ForEach((type) =>
                {
                    TypeAttributes ta = type.Attributes;
                    if (ta.HasFlag(TypeAttributes.Abstract) && ta.HasFlag(TypeAttributes.Sealed))
                    {
                        RuntimeHelpers.RunClassConstructor(type.TypeHandle);
                    }
                });
            }

            if (onInit != null)
            {
                onInit();
            }
            deltaTime = TimeSpan.Zero;
            _disposed = false;
            _haveInit = true;
            sw_delta  = new Stopwatch();
            sw_init   = new Stopwatch();
            sw_init.Start();
        }
        public void DefineNestedType(string name, TypeAttributes attributes, Type parent, PackingSize packingSize, int typesize, Type[] implementedInterfaces)
        {
            bool isDefaultImplementedInterfaces = implementedInterfaces?.Length == 0;
            bool isDefaultPackingSize = packingSize == PackingSize.Unspecified;
            bool isDefaultSize = typesize == 0;
            bool isDefaultParent = parent == null;
            bool isDefaultAttributes = attributes == TypeAttributes.NestedPrivate;

            Action<TypeBuilder, TypeBuilder> verify = (type, declaringType) =>
            {
                bool allowsNullParent = attributes.HasFlag(TypeAttributes.Abstract) && attributes.HasFlag(TypeAttributes.ClassSemanticsMask);
                Type baseType = allowsNullParent ? parent : (parent ?? typeof(object));
                Helpers.VerifyType(type, declaringType.Module, declaringType, name, attributes, baseType, typesize, packingSize, implementedInterfaces);
            };

            if (isDefaultImplementedInterfaces)
            {
                if (isDefaultSize && isDefaultPackingSize)
                {
                    if (isDefaultParent)
                    {
                        if (isDefaultAttributes)
                        {
                            // Use DefineNestedType(string)
                            TypeBuilder type1 = Helpers.DynamicType(TypeAttributes.Public);
                            verify(type1.DefineNestedType(name), type1);
                        }
                        // Use DefineNestedType(string, TypeAttributes)
                        TypeBuilder type2 = Helpers.DynamicType(TypeAttributes.Public);
                        verify(type2.DefineNestedType(name, attributes), type2);
                    }
                    // Use DefineNestedType(string, TypeAttributes, Type)
                    TypeBuilder type3 = Helpers.DynamicType(TypeAttributes.Public);
                    verify(type3.DefineNestedType(name, attributes, parent), type3);
                }
                else if (isDefaultSize)
                {
                    // Use DefineNestedType(string, TypeAttributes, Type, PackingSize)
                    TypeBuilder type4 = Helpers.DynamicType(TypeAttributes.Public);
                    verify(type4.DefineNestedType(name, attributes, parent, packingSize), type4);
                }
                else if (isDefaultPackingSize)
                {
                    // Use DefineNestedType(string, TypeAttributes, Type, int)
                    TypeBuilder type5 = Helpers.DynamicType(TypeAttributes.Public);
                    verify(type5.DefineNestedType(name, attributes, parent, typesize), type5);
                }
                // Use DefineNestedType(string, TypeAttributes, Type, PackingSize, int);
                TypeBuilder type6 = Helpers.DynamicType(TypeAttributes.Public);
                verify(type6.DefineNestedType(name, attributes, parent, packingSize, typesize), type6);
            }
            else
            {
                // Use DefineNestedType(string, TypeAttributes, Type, Type[])
                Assert.True(isDefaultSize && isDefaultPackingSize); // Sanity check
                TypeBuilder type7 = Helpers.DynamicType(TypeAttributes.Public);
                verify(type7.DefineNestedType(name, attributes, parent, implementedInterfaces), type7);
            }
        }
        private void OutputTypeAttributes(CodeTypeDeclaration e)
        {
            if ((e.Attributes & MemberAttributes.New) != 0)
            {
                output.Write("new ");
            }

            TypeAttributes attributes = e.TypeAttributes;

            switch (attributes & TypeAttributes.VisibilityMask)
            {
            case TypeAttributes.Public:
            case TypeAttributes.NestedPublic:
                output.Write("public ");
                break;

            case TypeAttributes.NestedPrivate:
                output.Write("private ");
                break;

            case TypeAttributes.NestedFamily:
                output.Write("protected ");
                break;
            }

            if (e.IsEnum)
            {
                output.Write("enum ");
            }
            else
            {
                switch (attributes & TypeAttributes.ClassSemanticsMask)
                {
                case TypeAttributes.Class:
                    if (attributes.HasFlag(TypeAttributes.Sealed))
                    {
                        if (attributes.HasFlag(TypeAttributes.Abstract))
                        {
                            output.Write("static ");
                        }
                        else
                        {
                            output.Write("final ");
                        }
                    }
                    else if (attributes.HasFlag(TypeAttributes.Abstract))
                    {
                        output.Write("abstract ");
                    }
                    output.Write("class ");
                    break;

                case TypeAttributes.Interface:
                    output.Write("interface ");
                    break;
                }
            }
        }
Exemple #5
0
        /// <summary>
        /// Convert type attributes to string
        /// </summary>
        private static String Convert(NetTypeDefinition type, TypeAttributes source)
        {
            string result;

            switch (source & TypeAttributes.VisibilityMask)
            {
            case TypeAttributes.NotPublic:
            case TypeAttributes.NestedAssembly:
                result = "internal ";
                break;

            case TypeAttributes.Public:
            case TypeAttributes.NestedPublic:
                result = "public ";
                break;

            case TypeAttributes.NestedPrivate:
                result = "private ";
                break;

            case TypeAttributes.NestedFamily:
            case TypeAttributes.NestedFamANDAssem:
                result = "protected ";
                break;

            case TypeAttributes.NestedFamORAssem:
                result = "protected internal ";
                break;

            default:
                throw new ArgumentException(string.Format("Unknown visibility 0x{0:X4}", (int)(source & TypeAttributes.VisibilityMask)));
            }
            if (!(type.IsInterface || type.IsStruct || type.IsEnum || type.IsStatic))
            {
                if (source.HasFlag(TypeAttributes.Abstract))
                {
                    result += "abstract ";
                }
                if (source.HasFlag(TypeAttributes.Sealed))
                {
                    result += "sealed ";
                }
            }
            if (type.IsStatic)
            {
                result += "static ";
            }
            if (type.IsEnum)
            {
                result += "sealed ";
            }
            if (!type.IsEnum)
            {
                result += "partial ";
            }
            return(result);
        }
        internal static string ProtectionModifierCSharp(this TypeAttributes typeAttributes)
        {
            //Must come before NestedFamANDAssem
            if (typeAttributes.HasFlag(TypeAttributes.NestedFamORAssem))
            {
                return("protected internal");
            }
            if (typeAttributes.HasFlag(TypeAttributes.NestedFamANDAssem))
            {
                return("private protected");
            }
            if (typeAttributes.HasFlag(TypeAttributes.NestedFamily) && !typeAttributes.HasFlag(TypeAttributes.Public))
            {
                return("protected");
            }

            if (typeAttributes.HasFlag(TypeAttributes.NestedAssembly))
            {
                return("internal");
            }
            if (typeAttributes.HasFlag(TypeAttributes.Public) ^
                typeAttributes.HasFlag(TypeAttributes.NestedPublic))
            {
                return("public");
            }
            if (typeAttributes.HasFlag(TypeAttributes.NestedPrivate)) //Must come after public
            {
                return("private");
            }
            return("internal");
        }
        public static bool IsVisible(MetadataReader metaReader, TypeDefinition currentType)
        {
            TypeDefinitionHandle typeDefHandle = currentType.GetDeclaringType();

            // the visibility is not really a mask until you mask it with the VisibilityMask.
            TypeAttributes visibility = currentType.Attributes & TypeAttributes.VisibilityMask;

            if (typeDefHandle.IsNil)
            {
                return(visibility.HasFlag(TypeAttributes.Public));
            }

            return(visibility.HasFlag(TypeAttributes.Public) &
                   IsVisible(metaReader, metaReader.GetTypeDefinition(typeDefHandle)));
        }
Exemple #8
0
        public void DefineNestedType(string name, TypeAttributes attributes, Type parent, PackingSize packingSize, int typesize, Type[] implementedInterfaces)
        {
            bool isDefaultImplementedInterfaces = implementedInterfaces?.Length == 0;
            bool isDefaultPackingSize           = packingSize == PackingSize.Unspecified;
            bool isDefaultSize       = typesize == 0;
            bool isDefaultParent     = parent == null;
            bool isDefaultAttributes = attributes == TypeAttributes.NestedPrivate;

            void Verify(TypeBuilder type, TypeBuilder declaringType)
            {
                bool allowsNullParent = attributes.HasFlag(TypeAttributes.Abstract) && attributes.HasFlag(TypeAttributes.ClassSemanticsMask);
                Type baseType         = allowsNullParent ? parent : (parent ?? typeof(object));

                Helpers.VerifyType(type, declaringType.Module, declaringType, name, attributes, baseType, typesize, packingSize, implementedInterfaces);
            }

            if (isDefaultImplementedInterfaces)
            {
                if (isDefaultSize && isDefaultPackingSize)
                {
                    if (isDefaultParent)
                    {
                        if (isDefaultAttributes)
                        {
                            // Use DefineNestedType(string)
                            TypeBuilder type1 = Helpers.DynamicType(TypeAttributes.Public);
                            Verify(type1.DefineNestedType(name), type1);
                        }
                        // Use DefineNestedType(string, TypeAttributes)
                        TypeBuilder type2 = Helpers.DynamicType(TypeAttributes.Public);
                        Verify(type2.DefineNestedType(name, attributes), type2);
                    }
                    // Use DefineNestedType(string, TypeAttributes, Type)
                    TypeBuilder type3 = Helpers.DynamicType(TypeAttributes.Public);
                    Verify(type3.DefineNestedType(name, attributes, parent), type3);
                }
                else if (isDefaultSize)
                {
                    // Use DefineNestedType(string, TypeAttributes, Type, PackingSize)
                    TypeBuilder type4 = Helpers.DynamicType(TypeAttributes.Public);
                    Verify(type4.DefineNestedType(name, attributes, parent, packingSize), type4);
                }
                else if (isDefaultPackingSize)
                {
                    // Use DefineNestedType(string, TypeAttributes, Type, int)
                    TypeBuilder type5 = Helpers.DynamicType(TypeAttributes.Public);
                    Verify(type5.DefineNestedType(name, attributes, parent, typesize), type5);
                }
                // Use DefineNestedType(string, TypeAttributes, Type, PackingSize, int);
                TypeBuilder type6 = Helpers.DynamicType(TypeAttributes.Public);
                Verify(type6.DefineNestedType(name, attributes, parent, packingSize, typesize), type6);
            }
            else
            {
                // Use DefineNestedType(string, TypeAttributes, Type, Type[])
                Assert.True(isDefaultSize && isDefaultPackingSize); // Sanity check
                TypeBuilder type7 = Helpers.DynamicType(TypeAttributes.Public);
                Verify(type7.DefineNestedType(name, attributes, parent, implementedInterfaces), type7);
            }
        }
        public void DefineType(string name, TypeAttributes attributes, Type parent, PackingSize packingSize, int typesize, Type[] implementedInterfaces)
        {
            bool isDefaultImplementedInterfaces = implementedInterfaces?.Length == 0;
            bool isDefaultPackingSize           = packingSize == PackingSize.Unspecified;
            bool isDefaultSize       = typesize == 0;
            bool isDefaultParent     = parent == null;
            bool isDefaultAttributes = attributes == TypeAttributes.NotPublic;

            void Verify(TypeBuilder type, Module module)
            {
                Type baseType = attributes.HasFlag(TypeAttributes.Abstract) && parent == null ? null : (parent ?? typeof(object));

                Helpers.VerifyType(type, module, null, name, attributes, baseType, typesize, packingSize, implementedInterfaces);
            }

            if (isDefaultImplementedInterfaces)
            {
                if (isDefaultSize && isDefaultPackingSize)
                {
                    if (isDefaultParent)
                    {
                        if (isDefaultAttributes)
                        {
                            // Use DefineType(string)
                            ModuleBuilder module1 = Helpers.DynamicModule();
                            Verify(module1.DefineType(name), module1);
                        }
                        // Use DefineType(string, TypeAttributes)
                        ModuleBuilder module2 = Helpers.DynamicModule();
                        Verify(module2.DefineType(name, attributes), module2);
                    }
                    // Use DefineType(string, TypeAttributes, Type)
                    ModuleBuilder module3 = Helpers.DynamicModule();
                    Verify(module3.DefineType(name, attributes, parent), module3);
                }
                else if (isDefaultSize)
                {
                    // Use DefineType(string, TypeAttributes, Type, PackingSize)
                    ModuleBuilder module4 = Helpers.DynamicModule();
                    Verify(module4.DefineType(name, attributes, parent, packingSize), module4);
                }
                else if (isDefaultPackingSize)
                {
                    // Use DefineType(string, TypeAttributes, Type, int)
                    ModuleBuilder module5 = Helpers.DynamicModule();
                    Verify(module5.DefineType(name, attributes, parent, typesize), module5);
                }
                // Use DefineType(string, TypeAttributes, Type, PackingSize, int)
                ModuleBuilder module6 = Helpers.DynamicModule();
                Verify(module6.DefineType(name, attributes, parent, packingSize, typesize), module6);
            }
            else
            {
                // Use DefineType(string, TypeAttributes, Type, Type[])
                Assert.True(isDefaultSize && isDefaultPackingSize); // Sanity check
                ModuleBuilder module7 = Helpers.DynamicModule();
                Verify(module7.DefineType(name, attributes, parent, implementedInterfaces), module7);
            }
        }
        public void DefineType(string name, TypeAttributes attributes, Type parent, PackingSize packingSize, int typesize, Type[] implementedInterfaces)
        {
            bool isDefaultImplementedInterfaces = implementedInterfaces?.Length == 0;
            bool isDefaultPackingSize = packingSize == PackingSize.Unspecified;
            bool isDefaultSize = typesize == 0;
            bool isDefaultParent = parent == null;
            bool isDefaultAttributes = attributes == TypeAttributes.NotPublic;

            Action<TypeBuilder, Module> verify = (type, module) =>
            {
                Type baseType = attributes.HasFlag(TypeAttributes.Abstract) && parent == null ? null : (parent ?? typeof(object));
                Helpers.VerifyType(type, module, null, name, attributes, baseType, typesize, packingSize, implementedInterfaces);
            };

            if (isDefaultImplementedInterfaces)
            {
                if (isDefaultSize && isDefaultPackingSize)
                {
                    if (isDefaultParent)
                    {
                        if (isDefaultAttributes)
                        {
                            // Use DefineType(string)
                            ModuleBuilder module1 = Helpers.DynamicModule();
                            verify(module1.DefineType(name), module1);
                        }
                        // Use DefineType(string, TypeAttributes)
                        ModuleBuilder module2 = Helpers.DynamicModule();
                        verify(module2.DefineType(name, attributes), module2);
                    }
                    // Use DefineType(string, TypeAttributes, Type)
                    ModuleBuilder module3 = Helpers.DynamicModule();
                    verify(module3.DefineType(name, attributes, parent), module3);
                }
                else if (isDefaultSize)
                {
                    // Use DefineType(string, TypeAttributes, Type, PackingSize)
                    ModuleBuilder module4 = Helpers.DynamicModule();
                    verify(module4.DefineType(name, attributes, parent, packingSize), module4);
                }
                else if (isDefaultPackingSize)
                {
                    // Use DefineType(string, TypeAttributes, Type, int)
                    ModuleBuilder module5 = Helpers.DynamicModule();
                    verify(module5.DefineType(name, attributes, parent, typesize), module5);
                }
                // Use DefineType(string, TypeAttributes, Type, PackingSize, int)
                ModuleBuilder module6 = Helpers.DynamicModule();
                verify(module6.DefineType(name, attributes, parent, packingSize, typesize), module6);
            }
            else
            {
                // Use DefineType(string, TypeAttributes, Type, Type[])
                Assert.True(isDefaultSize && isDefaultPackingSize); // Sanity check
                ModuleBuilder module7 = Helpers.DynamicModule();
                verify(module7.DefineType(name, attributes, parent, implementedInterfaces), module7);
            }
        }
Exemple #11
0
        private void AddModifiers(TypeAttributes attributes, MutableSymbol symbolToAdd)
        {
            SymbolModifier modifiers = symbolToAdd.Modifiers;

            // Same as Roslyn PENamedTypeSymbol.DeclaredAccessibility
            switch (attributes & TypeAttributes.VisibilityMask)
            {
            case TypeAttributes.NestedAssembly:
                modifiers = SymbolModifier.Internal;
                break;

            case TypeAttributes.NestedFamORAssem:
            case TypeAttributes.NestedFamANDAssem:
                modifiers = SymbolModifier.Protected | SymbolModifier.Internal;
                break;

            case TypeAttributes.NestedPrivate:
                modifiers = SymbolModifier.Private;
                break;

            case TypeAttributes.Public:
            case TypeAttributes.NestedPublic:
                modifiers = SymbolModifier.Public;
                break;

            case TypeAttributes.NestedFamily:
                modifiers = SymbolModifier.Protected;
                break;

            case TypeAttributes.NotPublic:
                modifiers = SymbolModifier.Internal;
                break;
            }


            // Same as Roslyn PENamedTypeSymbol.IsStatic
            if (attributes.HasFlag(TypeAttributes.Sealed) && attributes.HasFlag(TypeAttributes.Abstract))
            {
                modifiers |= SymbolModifier.Static;
            }

            symbolToAdd.Modifiers = modifiers;
        }
        public EnumCreator CreateEnum(string name, TypeAttributes typeAttributes = TypeAttributes.Public)
        {
            VerificationName(name);
            if (typeAttributes.HasFlag(TypeAttributes.Interface))
            {
                throw new Exception("An enum cant have interface attribute");
            }
            EnumCreator @enum = new EnumCreator(name, moduleBuilder, typeAttributes);

            enumCreators.Append(@enum);
            return(@enum);
        }
Exemple #13
0
 internal TypeCreator(string name, ModuleBuilder moduleBuilder, TypeAttributes typeAttributes)
 {
     if (typeAttributes.HasFlag(TypeAttributes.Interface))
     {
         throw new Exception("This class is made to created Class use interfacesCreator for interface");
     }
     this.Name               = name;
     this.moduleBuilder      = moduleBuilder;
     this.State              = Metadata.State.NotDefined;
     this.IsGenericParameter = false;
     this.TypeAttributes     = typeAttributes;
     this.IsClass            = true;
     this.Assembly           = moduleBuilder.Assembly;
 }
Exemple #14
0
        public void Generate(string className, string namespacestr, List <string> namespaceList, string pathStr, TypeAttributes typeAttributes, string constructorStr, string interfaceName, string returnType)
        {
            try
            {
                CodeCompileUnit unit            = new CodeCompileUnit();
                CodeNamespace   sampleNamespace = new CodeNamespace(namespacestr);
                //导入命名空间
                for (int i = 0; i < namespaceList.Count; i++)
                {
                    sampleNamespace.Imports.Add(new CodeNamespaceImport(namespaceList[i]));
                }
                CodeTypeDeclaration Customerclass = new CodeTypeDeclaration(className);
                Customerclass.TypeAttributes = typeAttributes;
                if (typeAttributes.HasFlag(TypeAttributes.Class))
                {
                    //添加构造
                    CodeMemberMethod method = new CodeMemberMethod();
                    method.Name       = "Create";
                    method.Attributes = MemberAttributes.Public;
                    method.ReturnType = new CodeTypeReference(returnType);
                    method.Statements.Add(new CodeSnippetExpression(constructorStr));
                    Customerclass.Members.Add(method);

                    //继承接口
                    if (!string.IsNullOrEmpty(interfaceName))
                    {
                        Customerclass.BaseTypes.Add(new CodeTypeReference(interfaceName));
                    }
                }
                sampleNamespace.Types.Add(Customerclass);
                unit.Namespaces.Add(sampleNamespace);
                string               outputFile = pathStr + className + ".cs";
                CodeDomProvider      provider   = CodeDomProvider.CreateProvider("CSharp");
                CodeGeneratorOptions options
                    = new CodeGeneratorOptions();
                options.BracingStyle             = "C";
                options.BlankLinesBetweenMembers = true;
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputFile))
                {
                    provider.GenerateCodeFromCompileUnit(unit, sw, options);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #15
0
        public Class(Type type)
        {
            TypeAttributes attributes = type.Attributes;

            if (attributes.HasFlag(TypeAttributes.Public))
            {
                Name = "public ";
            }
            else if (attributes.HasFlag(TypeAttributes.NotPublic))
            {
                Name = "private ";
            }
            else if (attributes.HasFlag(TypeAttributes.NestedFamily))
            {
                Name = "protected ";
            }
            else if (attributes.HasFlag(TypeAttributes.NestedAssembly))
            {
                Name = "internal ";
            }

            if (attributes.HasFlag(TypeAttributes.Interface))
            {
                Name = Name + "interface ";
            }
            else if (attributes.HasFlag(TypeAttributes.Class))
            {
                Name = Name + "class ";
            }

            Name    = Name + type.Name;
            Methods = new List <Method>();

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

            Methods      = GetMethods(type, bindingFlags);
            Fields       = GetFields(type, bindingFlags);
            Properties   = GetProperties(type, bindingFlags);
            Constructors = GetConstructors(type, bindingFlags);
        }
Exemple #16
0
    private static TypeDefinition _Inject(ModuleDefinition mod, TypeDefinition type, Dictionary <MetadataToken, IMemberDefinition> mems)
    {
        TypeAttributes att = type.Attributes;

        if (att.HasFlag(TypeAttributes.NotPublic))
        {
            att &= ~TypeAttributes.NotPublic;
        }

        att |= TypeAttributes.Public;
        TypeDefinition definition = new TypeDefinition(type.Namespace, type.Name, att)
        {
            ClassSize   = type.ClassSize,
            PackingSize = type.PackingSize
        };

        if (type.BaseType != null)
        {
            definition.BaseType = mod.Import(type.BaseType);
        }
        mems.Add(type.MetadataToken, definition);
        foreach (TypeDefinition definition2 in type.NestedTypes)
        {
            TypeDefinition item = _Inject(mod, definition2, mems);
            definition.NestedTypes.Add(item);
        }
        foreach (FieldDefinition definition4 in type.Fields)
        {
            if (!definition4.IsLiteral)
            {
                FieldDefinition definition5 = new FieldDefinition(definition4.Name, definition4.Attributes, mod.TypeSystem.Void);
                mems.Add(definition4.MetadataToken, definition5);
                definition.Fields.Add(definition5);
            }
        }
        foreach (MethodDefinition definition6 in type.Methods)
        {
            TransportAction visible = TransportAction.Public;
            if (!TypeCheck.KeepMethod(type, definition6, out visible))
            {
                continue;
            }

            MethodAttributes methodAtt = definition6.Attributes;

            if (visible == TransportAction.Public)
            {
                if (methodAtt.HasFlag(MethodAttributes.Private))
                {
                    methodAtt &= ~MethodAttributes.Private;
                }

                if (visible == TransportAction.Public)
                {
                    methodAtt |= MethodAttributes.Public;
                }
            }

            MethodDefinition definition7 = new MethodDefinition(definition6.Name, methodAtt, definition6.ReturnType);
            mems.Add(definition6.MetadataToken, definition7);
            definition.Methods.Add(definition7);
        }
        return(definition);
    }
Exemple #17
0
        void DealWithType(TypeDefinition type)
        {
            TypeAttributes att = type.Attributes;

            if (att.HasFlag(TypeAttributes.NotPublic))
            {
                att &= ~TypeAttributes.NotPublic;
            }

            att |= TypeAttributes.Public;

            TypeDefinition nTypeDef = CecilHelper.Inject(newModule.MainModule, type);

            if (type.CustomAttributes.Where(x => x.AttributeType.FullName == "System.CodeDom.Compiler.GeneratedCodeAttribute").Count() != 0)//type.Namespace.EndsWith(".My")
            {
                // newModule.MainModule.Types.Add(.DeclaringType);
                newModule.MainModule.Import(type);
                return;
            }

            bool add = false;
            List <MethodDefinition> RemoveMethods = new List <MethodDefinition>();


            foreach (MethodDefinition method in type.Methods)
            {
                if (!method.HasBody)
                {
                    continue;
                }
                if (!method.IsStatic)
                {
                    continue;
                }

                TransportAction visibility = TransportAction.Public;

                if (!TypeCheck.KeepMethod(type, method, out visibility))
                {
                    continue;
                }

                if (!method.IsStatic)
                {
                    MessageBox.Show("RemoteCall must be only used on static methods.\n: " + method.FullName);
                    throw new Exception("Not static");
                }

                add = true;

                if (visibility == TransportAction.Move)
                {
                    RemoveMethods.Add(method);
                    continue;
                }

                if (visibility == TransportAction.Copy)
                {
                    continue;
                }

                method.Body.Instructions.Clear();

                ILProcessor ilp = method.Body.GetILProcessor();

                if (visibility == TransportAction.MoveClear)
                {
                    ilp.Append(Instruction.Create(OpCodes.Ret));
                    continue;
                }



                ilp.Append(Instruction.Create(OpCodes.Ldstr, Hashing.SHA(string.Format("{0}.{1}", type.FullName, method.Name))));

                if (method.Parameters.Count == 0)
                {
                    ilp.Append(Instruction.Create(OpCodes.Ldc_I4_0));
                    ilp.Append(Instruction.Create(OpCodes.Newarr, objectReference));
                }
                else
                {
                    ilp.Append(Instruction.Create(OpCodes.Ldc_I4, method.Parameters.Count));
                    ilp.Append(Instruction.Create(OpCodes.Newarr, objectReference));

                    for (int i = 0; i < method.Parameters.Count; i++)
                    {
                        ilp.Append(Instruction.Create(OpCodes.Dup));
                        ilp.Append(Instruction.Create(OpCodes.Ldc_I4, i));
                        ilp.Append(Instruction.Create(OpCodes.Ldarg, method.Parameters[i]));
                        ilp.Append(Instruction.Create(OpCodes.Box, method.Parameters[i].ParameterType));
                        ilp.Append(Instruction.Create(OpCodes.Stelem_Ref));
                    }
                }
                ilp.Append(Instruction.Create(OpCodes.Call, CreateRemoteCallRef));
                ilp.Append(Instruction.Create(OpCodes.Unbox_Any, method.ReturnType));
                ilp.Append(Instruction.Create(OpCodes.Ret));
            }

            foreach (MethodDefinition md in RemoveMethods)
            {
                type.Methods.Remove(md);
            }

            if (add)
            {
                newModule.MainModule.Types.Add(nTypeDef);
            }
        }
Exemple #18
0
        public void Generate(string className, string namespacestr, List <string> namespaceList, string pathStr, TypeAttributes typeAttributes, bool needConstructor = true, bool needcrmService = false, string interfaceName = null, string constructorParametTypeName = null, string constructorParametName = null, string PropertyParametName = null)
        {
            string outputFile = "";

            try
            {
                CodeCompileUnit unit            = new CodeCompileUnit();
                CodeNamespace   sampleNamespace = new CodeNamespace(namespacestr);
                //导入命名空间
                for (int i = 0; i < namespaceList.Count; i++)
                {
                    sampleNamespace.Imports.Add(new CodeNamespaceImport(namespaceList[i]));
                }
                CodeTypeDeclaration Customerclass = new CodeTypeDeclaration(className);
                Customerclass.TypeAttributes = typeAttributes;
                if (typeAttributes.HasFlag(TypeAttributes.Class))
                {
                    if (needConstructor)
                    {
                        if (needcrmService)
                        {
                            CodeMemberField crmfield = new CodeMemberField("ICrmService", "_crmService");
                            crmfield.Attributes = MemberAttributes.Private;
                            Customerclass.Members.Add(crmfield);
                        }
                        //添加字段
                        CodeMemberField field = new CodeMemberField(constructorParametTypeName, PropertyParametName);
                        field.Attributes = MemberAttributes.Public;
                        Customerclass.Members.Add(field);
                        //添加构造
                        CodeConstructor constructor = new CodeConstructor();
                        if (needcrmService)
                        {
                            constructor.Parameters.Add(new CodeParameterDeclarationExpression("ICrmService", "crmService"));
                            constructor.Statements.Add(new CodeSnippetExpression($@" _crmService = crmService;
                     {PropertyParametName}={constructorParametName}"));
                        }
                        else
                        {
                            constructor.Statements.Add(new CodeSnippetExpression($@"{PropertyParametName}={constructorParametName}"));
                        }

                        constructor.Attributes = MemberAttributes.Public;
                        constructor.Parameters.Add(new CodeParameterDeclarationExpression(constructorParametTypeName, constructorParametName));

                        Customerclass.Members.Add(constructor);
                    }
                    //继承接口
                    if (!string.IsNullOrEmpty(interfaceName))
                    {
                        Customerclass.BaseTypes.Add(new CodeTypeReference(interfaceName));
                    }
                }
                sampleNamespace.Types.Add(Customerclass);
                unit.Namespaces.Add(sampleNamespace);
                outputFile = pathStr + className + ".cs";
                CodeDomProvider      provider = CodeDomProvider.CreateProvider("CSharp");
                CodeGeneratorOptions options  = new CodeGeneratorOptions();
                options.BracingStyle             = "C";
                options.BlankLinesBetweenMembers = true;
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputFile))
                {
                    provider.GenerateCodeFromCompileUnit(unit, sw, options);
                }
            }
            catch (Exception ex)
            {
                var pathstr = outputFile;
                throw ex;
            }
        }