/// <summary> /// Sets a custom attribute using a custom attribute type. /// </summary> /// <param name="attributeType">Attribute type.</param> public void SetCustomAttribute(Type attributeType) { if (attributeType == null) { throw new ArgumentNullException("attributeType"); } ConstructorInfo ci = attributeType.GetConstructor(Type.EmptyTypes); CustomAttributeBuilder caBuilder = new CustomAttributeBuilder(ci, new object[0]); _typeBuilder.SetCustomAttribute(caBuilder); }
public TypeBuilder AddCustomAttribute(Type attributeType, Type[] attributeConstructorParameters, object[] attributeConstuctorArgs) { if (null == attributeType) { throw new ArgumentNullException(nameof(attributeType)); } if (null == attributeConstructorParameters) { throw new ArgumentNullException(nameof(attributeConstructorParameters)); } if (null == attributeConstuctorArgs) { throw new ArgumentNullException(nameof(attributeConstuctorArgs)); } ConstructorInfo ctorInfo = attributeType.GetConstructor(attributeConstructorParameters); CustomAttributeBuilder customAttributeBuilder = new CustomAttributeBuilder(ctorInfo, attributeConstuctorArgs); _typeBuilder.SetCustomAttribute(customAttributeBuilder); return(this); }
private static void AddEntityElementIdAnnotation(TypeBuilder typeBuilder, EntityElement entity) { var id = entity.Identity.Id.ToString(); var constructor = typeof(EntityElementIdAttribute).GetConstructors().First(); var customAttributeBuilder = new CustomAttributeBuilder(constructor, new object[] { id }); typeBuilder.SetCustomAttribute(customAttributeBuilder); }
private static void ProcessEntityComponent(Type baseType, TypeBuilder typeBuilder) { if (typeof(EntityComponent).IsAssignableFrom(baseType)) { // Add AllowMultipleComponentsAttribute on EntityComponent yaml proxy (since there might be more than one) var allowMultipleComponentsAttributeCtor = typeof(AllowMultipleComponentsAttribute).GetConstructor(Type.EmptyTypes); var allowMultipleComponentsAttribute = new CustomAttributeBuilder(allowMultipleComponentsAttributeCtor, new object[0]); typeBuilder.SetCustomAttribute(allowMultipleComponentsAttribute); } }
private void AddAttribute(TypeBuilder typeBuilder, Type attrType, Type[] attrCtorParamTypes, object[] attrCtorParams) { var ctorInfo = attrType.GetConstructor(attrCtorParamTypes); if (ctorInfo != null) { var attrBuilder = new CustomAttributeBuilder(ctorInfo, attrCtorParams); typeBuilder.SetCustomAttribute(attrBuilder); } }
internal static void SetHiddenAttribute(TypeBuilder tb) { if (s_HiddenCABuilder == null) { // Hide the type from Object Browsers Type []aConsParams = new Type[1]; aConsParams[0] = typeof(TypeLibTypeFlags); ConstructorInfo Cons = typeof(TypeLibTypeAttribute).GetConstructor(aConsParams); Object []aArgs = new Object[1]; aArgs[0] = TypeLibTypeFlags.FHidden; s_HiddenCABuilder = new CustomAttributeBuilder(Cons, aArgs); } tb.SetCustomAttribute(s_HiddenCABuilder); }
internal void Implement(TypeBuilder typeBuilder) { if (_dataContract != null) { // Use base data contract properties to help determine values of properties the proxy type's data contract. var propertyValues = new object[] { // IsReference _dataContract.IsReference }; var attributeBuilder = new CustomAttributeBuilder( _dataContractAttributeConstructor, new object[0], _dataContractProperties, propertyValues); typeBuilder.SetCustomAttribute(attributeBuilder); } }
/// <summary> /// Initializes a new instance of the <see cref="TypeBuilderHelper"/> class /// with the specified parameters. /// </summary> /// <param name="assemblyBuilder">Associated <see cref="AssemblyBuilderHelper"/>.</param> /// <param name="typeBuilder">A <see cref="TypeBuilder"/></param> public TypeBuilderHelper(AssemblyBuilderHelper assemblyBuilder, System.Reflection.Emit.TypeBuilder typeBuilder) { if (assemblyBuilder == null) { throw new ArgumentNullException("assemblyBuilder"); } if (typeBuilder == null) { throw new ArgumentNullException("typeBuilder"); } _assembly = assemblyBuilder; _typeBuilder = typeBuilder; _typeBuilder.SetCustomAttribute(_assembly.BLToolkitAttribute); }
internal static void SetClassInterfaceTypeToNone(TypeBuilder tb) { // Create the ClassInterface(ClassInterfaceType.None) CA builder if we haven't created it yet. if (s_NoClassItfCABuilder == null) { Type []aConsParams = new Type[1]; aConsParams[0] = typeof(ClassInterfaceType); ConstructorInfo Cons = typeof(ClassInterfaceAttribute).GetConstructor(aConsParams); Object[] aArgs = new Object[1]; aArgs[0] = ClassInterfaceType.None; s_NoClassItfCABuilder = new CustomAttributeBuilder(Cons, aArgs); } // Set the class interface type to none. tb.SetCustomAttribute(s_NoClassItfCABuilder); }
public static void Invoke(TypeBuilder t, string ExternalTarget) { t.SetCustomAttribute( new CustomAttributeBuilder( typeof(ScriptAttribute).GetConstructor(new Type[0]), new object[0], namedProperties: new[] { typeof(ScriptAttribute).GetProperty("HasNoPrototype") }, propertyValues: new object[] { true }, namedFields: new[] { typeof(ScriptAttribute).GetField("ExternalTarget") }, fieldValues: new object[] { ExternalTarget } ) ); }
internal override void Seal(TypeDescription existing = null) { if (PocoType != null || TypeBuilder != null) return; var name = "POCO" + Guid.NewGuid().ToString().Replace("-", ""); var protoMemberAttr = typeof(ProtoMemberAttribute).GetConstructor(new[] { typeof(int) }); var protoContractAttr = typeof(ProtoContractAttribute).GetConstructor(new Type[0]); var fields = new Dictionary<string, FieldInfo>(); TypeBuilder = ModuleBuilder.DefineType(name, TypeAttributes.Public, typeof(DynamicObject), new [] { typeof(IEnumerable) }); var ix = 1; foreach (var kv in Members.OrderBy(o => o.Key, StringComparer.Ordinal)) { var memberAttrBuilder = new CustomAttributeBuilder(protoMemberAttr, new object[] { ix }); kv.Value.Seal(existing); var propType = kv.Value.GetPocoType(existing); var field = TypeBuilder.DefineField(kv.Key, propType, FieldAttributes.Public); field.SetCustomAttribute(memberAttrBuilder); fields[kv.Key] = field; ix++; } var contractAttrBuilder = new CustomAttributeBuilder(protoContractAttr, new object[0]); TypeBuilder.SetCustomAttribute(contractAttrBuilder); // Define indexer var strEq = typeof(object).GetMethod("Equals", new[] { typeof(object) }); var tryGetIndexEmit = Sigil.Emit<TryGetIndexerDelegate>.BuildMethod(TypeBuilder, "TryGetIndex", MethodAttributes.Public | MethodAttributes.Virtual, CallingConventions.Standard | CallingConventions.HasThis); tryGetIndexEmit.LoadArgument(2); // object[] var invalid = tryGetIndexEmit.DefineLabel("invalid"); tryGetIndexEmit .Duplicate() // object[] object[] .LoadLength<object>() // int object[] .LoadConstant(1); // int int object[] tryGetIndexEmit.UnsignedBranchIfNotEqual(invalid); // object[] tryGetIndexEmit .LoadConstant(0) // int object[] .LoadElement<object>() // object .IsInstance<string>(); // int var valid = tryGetIndexEmit.DefineLabel("valid"); tryGetIndexEmit .BranchIfTrue(valid) // --empty-- .LoadArgument(2); // object[] tryGetIndexEmit.MarkLabel(invalid); tryGetIndexEmit.Pop(); // --empty-- tryGetIndexEmit .LoadArgument(3) // object& .LoadNull() // null object& .StoreIndirect(typeof(object)); // --empty-- tryGetIndexEmit .LoadConstant(0) // int .Return(); // --empty-- tryGetIndexEmit.MarkLabel(valid); tryGetIndexEmit.LoadArgument(3); // object& tryGetIndexEmit .LoadArgument(2) // object[] object& .LoadConstant(0) // int object[] object& .LoadElement<object>(); // object object& Sigil.Label next; var done = tryGetIndexEmit.DefineLabel("done"); foreach (var mem in Members) { next = tryGetIndexEmit.DefineLabel("next_" + mem.Key); var memKey = mem.Key; var field = fields[memKey]; tryGetIndexEmit .Duplicate() // object object object& .LoadConstant(memKey); // string object object object& tryGetIndexEmit.CallVirtual(strEq); // int object object7& tryGetIndexEmit.BranchIfFalse(next); // object object& tryGetIndexEmit .Pop() // object& .LoadArgument(0) // this object& .LoadField(field); // fieldType object& if (field.FieldType.IsValueType) { tryGetIndexEmit.Box(field.FieldType); // fieldType object& } tryGetIndexEmit.Branch(done); // fieldType object& tryGetIndexEmit.MarkLabel(next); // object object& } tryGetIndexEmit .Pop() // object& .LoadNull(); // null object& tryGetIndexEmit.MarkLabel(done); // *something* object& tryGetIndexEmit .StoreIndirect(typeof(object)) // --empty-- .LoadConstant(1) // int .Return(); // --empty-- var tryGetIndex = tryGetIndexEmit.CreateMethod(); TypeBuilder.DefineMethodOverride(tryGetIndex, typeof(DynamicObject).GetMethod("TryGetIndex")); // Implement IEnumerable var getEnumeratorEmit = Sigil.Emit<Func<IEnumerator>>.BuildMethod(TypeBuilder, "GetEnumerator", MethodAttributes.Public | MethodAttributes.Virtual, CallingConventions.Standard | CallingConventions.HasThis); var newStrList = typeof(List<string>).GetConstructor(new[] { typeof(int) }); var newEnumerator = Enumerator.GetConstructor(new[] { typeof(List<string>), typeof(object) }); var add = typeof(List<string>).GetMethod("Add"); getEnumeratorEmit.LoadConstant(Members.Count); getEnumeratorEmit.NewObject(newStrList); foreach (var mem in Members) { getEnumeratorEmit.Duplicate(); getEnumeratorEmit.LoadConstant(mem.Key); getEnumeratorEmit.Call(add); } getEnumeratorEmit.LoadArgument(0); getEnumeratorEmit.NewObject(newEnumerator); getEnumeratorEmit.Return(); var getEnumerator = getEnumeratorEmit.CreateMethod(); TypeBuilder.DefineMethodOverride(getEnumerator, typeof(IEnumerable).GetMethod("GetEnumerator")); // Define ToString() var toStringEmit = Sigil.Emit<Func<string>>.BuildMethod(TypeBuilder, "ToString", MethodAttributes.Public | MethodAttributes.Virtual, CallingConventions.Standard | CallingConventions.HasThis); var objToString = typeof(object).GetMethod("ToString"); var thunkField = TypeBuilder.DefineField("__ToStringThunk", typeof(Func<object, string>), FieldAttributes.Static | FieldAttributes.Private); var invoke = typeof(Func<object, string>).GetMethod("Invoke"); toStringEmit .LoadField(thunkField) .LoadArgument(0) .CallVirtual(invoke) .Return(); var toString = toStringEmit.CreateMethod(); TypeBuilder.DefineMethodOverride(toString, objToString); PocoType = TypeBuilder.CreateType(); // Set the ToStringCallback var firstInst = PocoType.GetConstructor(Type.EmptyTypes).Invoke(new object[0]); var setThunk = firstInst.GetType().GetField("__ToStringThunk", BindingFlags.NonPublic | BindingFlags.Static); setThunk.SetValue(firstInst, ToStringFunc); }
private static void GenerateTypeAttributes(TypeBuilder tb, Type type) { var attributes = type.GetCustomAttributes(false).OfType<Attribute>(); foreach (var attribute in attributes) { var cab = CreateAttributeBuilder(attribute); if (cab != null) tb.SetCustomAttribute(cab); } }
/// <summary> /// Applies attributes to the proxy class. /// </summary> /// <param name="typeBuilder">The type builder to use.</param> /// <param name="targetType">The proxied class.</param> /// <see cref="IProxyTypeBuilder.ProxyTargetAttributes"/> /// <see cref="IProxyTypeBuilder.TypeAttributes"/> protected virtual void ApplyTypeAttributes(TypeBuilder typeBuilder, Type targetType) { foreach (object attr in GetTypeAttributes(targetType)) { if (attr is CustomAttributeBuilder) { typeBuilder.SetCustomAttribute((CustomAttributeBuilder)attr); } else if (attr is CustomAttributeData) { typeBuilder.SetCustomAttribute( ReflectionUtils.CreateCustomAttribute((CustomAttributeData)attr)); } else if (attr is Attribute) { typeBuilder.SetCustomAttribute(ReflectionUtils.CreateCustomAttribute((Attribute)attr)); } } }
public void EmitAttribute (TypeBuilder builder, TypeSpec type) { if (ResolveTransformationCtor ()) { var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) }); builder.SetCustomAttribute (cab); } }
public static CompilerErrorCollection CompileToType(XmlReader stylesheet, XsltSettings settings, XmlResolver stylesheetResolver, bool debug, TypeBuilder typeBuilder, string scriptAssemblyPath) { if (stylesheet == null) throw new ArgumentNullException("stylesheet"); if (typeBuilder == null) throw new ArgumentNullException("typeBuilder"); if (settings == null) settings = XsltSettings.Default; if (settings.EnableScript && scriptAssemblyPath == null) throw new ArgumentNullException("scriptAssemblyPath"); if (scriptAssemblyPath != null) scriptAssemblyPath = Path.GetFullPath(scriptAssemblyPath); QilExpression qil; CompilerErrorCollection errors = new Compiler(settings, debug, scriptAssemblyPath).Compile(stylesheet, stylesheetResolver, out qil).Errors; if (!errors.HasErrors) { // Mark the type with GeneratedCodeAttribute to identify its origin if (GeneratedCodeCtor == null) GeneratedCodeCtor = typeof(GeneratedCodeAttribute).GetConstructor(new Type[] { typeof(string), typeof(string) }); typeBuilder.SetCustomAttribute(new CustomAttributeBuilder(GeneratedCodeCtor, new object[] { typeof(XslCompiledTransform).FullName, Version })); new XmlILGenerator().Generate(qil, typeBuilder); } return errors; }
//Метод, переводящий семантическое дерево в сборку .NET public void ConvertFromTree(SemanticTree.IProgramNode p, string TargetFileName, string SourceFileName, CompilerOptions options, string[] ResourceFiles) { //SystemLibrary.SystemLibInitializer.RestoreStandardFunctions(); bool RunOnly = false; string fname = TargetFileName; comp_opt = options; ad = Thread.GetDomain(); //получаем домен приложения //ad = ad.DomainManager.CreateDomain("D1", null, null); an = new AssemblyName(); //создаем имя сборки an.Version = new Version("1.0.0.0"); string dir = Directory.GetCurrentDirectory(); string source_name = fname;//p.Location.document.file_name; int pos = source_name.LastIndexOf(Path.DirectorySeparatorChar); if (pos != -1) //если имя файла указано с путем, то выделяем { dir = source_name.Substring(0, pos + 1); an.CodeBase = String.Concat("file:///", source_name.Substring(0, pos)); source_name = source_name.Substring(pos + 1); } string name = source_name.Substring(0, source_name.LastIndexOf('.')); if (comp_opt.target == TargetType.Exe || comp_opt.target == TargetType.WinExe) an.Name = name;// + ".exe"; else an.Name = name; //+ ".dll"; if (name == "PABCRtl" || name == "PABCRtl32") { an.Flags = AssemblyNameFlags.PublicKey; an.VersionCompatibility = System.Configuration.Assemblies.AssemblyVersionCompatibility.SameProcess; an.HashAlgorithm = System.Configuration.Assemblies.AssemblyHashAlgorithm.None; FileStream publicKeyStream = File.Open(Path.Combine(Path.GetDirectoryName(TargetFileName), name == "PABCRtl" ? "PublicKey.snk" : "PublicKey32.snk"), FileMode.Open); byte[] publicKey = new byte[publicKeyStream.Length]; publicKeyStream.Read(publicKey, 0, (int)publicKeyStream.Length); // Provide the assembly with a public key. an.SetPublicKey(publicKey); publicKeyStream.Close(); } if (RunOnly) ab = ad.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run, dir);//определяем сборку else ab = ad.DefineDynamicAssembly(an, AssemblyBuilderAccess.Save, dir);//определяем сборку //int nn = ad.GetAssemblies().Length; if (options.NeedDefineVersionInfo) { ab.DefineVersionInfoResource(options.Product, options.ProductVersion, options.Company, options.Copyright, options.TradeMark); } if (options.MainResourceFileName != null) { try { ab.DefineUnmanagedResource(options.MainResourceFileName); } catch { throw new TreeConverter.SourceFileError(options.MainResourceFileName); } } else if (options.MainResourceData != null) { try { ab.DefineUnmanagedResource(options.MainResourceData); } catch { throw new TreeConverter.SourceFileError(""); } } save_debug_info = comp_opt.dbg_attrs == DebugAttributes.Debug || comp_opt.dbg_attrs == DebugAttributes.ForDebbuging; add_special_debug_variables = comp_opt.dbg_attrs == DebugAttributes.ForDebbuging; //bool emit_sym = true; if (save_debug_info) //если модуль отладочный, то устанавливаем атрибут, запрещающий inline методов ab.SetCustomAttribute(typeof(System.Diagnostics.DebuggableAttribute).GetConstructor(new Type[] { typeof(bool), typeof(bool) }), new byte[] { 0x01, 0x00, 0x01, 0x01, 0x00, 0x00 }); //ab.SetCustomAttribute(typeof(System.Diagnostics.DebuggableAttribute).GetConstructor(new Type[] { typeof(bool), typeof(bool) }), new byte[] { 0x01, 0x00, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00 }); //else // ab.SetCustomAttribute(typeof(System.Diagnostics.DebuggableAttribute).GetConstructor(new Type[] { typeof(bool), typeof(bool) }), new byte[] { 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00 }); if (RunOnly) mb = ab.DefineDynamicModule(name, save_debug_info); else { if (comp_opt.target == TargetType.Exe || comp_opt.target == TargetType.WinExe) mb = ab.DefineDynamicModule(name + ".exe", an.Name + ".exe", save_debug_info); //определяем модуль (save_debug_info - флаг включать отладочную информацию) else mb = ab.DefineDynamicModule(name + ".dll", an.Name + ".dll", save_debug_info); } cur_unit = Path.GetFileNameWithoutExtension(SourceFileName); string entry_cur_unit = cur_unit; entry_type = mb.DefineType(cur_unit + ".Program", TypeAttributes.Public);//определяем синтетический статический класс основной программы cur_type = entry_type; //точка входа в приложение if (p.main_function != null) { ConvertFunctionHeader(p.main_function); entry_meth = helper.GetMethod(p.main_function).mi as MethodBuilder; /*entry_meth = entry_type.DefineMethod(p.main_function.name, MethodAttributes.Public | MethodAttributes.Static, typeof(void), GetParamTypes(p.main_function)); for (int i = 0; i < p.main_function.parameters.Length; i++) { if (p.main_function.parameters[i].parameter_type == parameter_type.var) entry_meth.DefineParameter(i + 1, ParameterAttributes.Retval, p.main_function.parameters[i].name); else entry_meth.DefineParameter(i + 1, ParameterAttributes.None, p.main_function.parameters[i].name); }*/ cur_meth = entry_meth; il = cur_meth.GetILGenerator(); if (options.target != TargetType.Dll && options.dbg_attrs == DebugAttributes.ForDebbuging) AddSpecialInitDebugCode(); } ILGenerator tmp_il = il; MethodBuilder tmp_meth = cur_meth; //при отладке компилятора здесь иногда ничего нет! ICommonNamespaceNode[] cnns = p.namespaces; //создаем отладочные документы if (save_debug_info) { first_doc = mb.DefineDocument(SourceFileName, SymDocumentType.Text, SymLanguageType.Pascal, SymLanguageVendor.Microsoft); for (int iii = 0; iii < cnns.Length; iii++) { if (cnns[iii].Location != null) doc = mb.DefineDocument(cnns[iii].Location.document.file_name, SymDocumentType.Text, SymLanguageType.Pascal, SymLanguageVendor.Microsoft); else doc = first_doc; sym_docs.Add(cnns[iii], doc);//сохраняем его в таблице документов } first_doc = sym_docs[cnns[0]]; if (p.main_function != null) { if (p.main_function.function_code is IStatementsListNode) EntryPointLocation = ((IStatementsListNode)p.main_function.function_code).LeftLogicalBracketLocation; else EntryPointLocation = p.main_function.function_code.Location; } else EntryPointLocation = null; } ICommonNamespaceNode entry_ns = null; //Переводим заголовки типов for (int iii = 0; iii < cnns.Length; iii++) { if (save_debug_info) doc = sym_docs[cnns[iii]]; bool is_main_namespace = cnns[iii].namespace_name == "" && comp_opt.target != TargetType.Dll || comp_opt.target == TargetType.Dll && cnns[iii].namespace_name == ""; ICommonNamespaceNode cnn = cnns[iii]; cur_type = entry_type; if (!is_main_namespace) cur_unit = cnn.namespace_name; else cur_unit = entry_cur_unit; if (iii == cnns.Length - 1 && comp_opt.target != TargetType.Dll || comp_opt.target == TargetType.Dll && iii == cnns.Length - 1) entry_ns = cnn; ConvertTypeHeaders(cnn.types); } //Переводим псевдоинстанции generic-типов foreach (ICommonTypeNode ictn in p.generic_type_instances) { ConvertTypeHeaderInSpecialOrder(ictn); } Dictionary<ICommonNamespaceNode, TypeBuilder> NamespacesTypes = new Dictionary<ICommonNamespaceNode, TypeBuilder>(); for (int iii = 0; iii < cnns.Length; iii++) { bool is_main_namespace = cnns[iii].namespace_name == "" && comp_opt.target != TargetType.Dll || comp_opt.target == TargetType.Dll && cnns[iii].namespace_name == ""; if (!is_main_namespace) { //определяем синтетический класс для модуля cur_type = mb.DefineType(cnns[iii].namespace_name + "." + cnns[iii].namespace_name, TypeAttributes.Public); types.Add(cur_type); NamespaceTypesList.Add(cur_type); NamespacesTypes.Add(cnns[iii], cur_type); if (cnns[iii].IsMain) { TypeBuilder attr_class = mb.DefineType(cnns[iii].namespace_name + "." + "$GlobAttr", TypeAttributes.Public | TypeAttributes.BeforeFieldInit, typeof(Attribute)); ConstructorInfo attr_ci = attr_class.DefineDefaultConstructor(MethodAttributes.Public); cur_type.SetCustomAttribute(attr_ci, new byte[4] { 0x01, 0x00, 0x00, 0x00 }); attr_class.CreateType(); } else { TypeBuilder attr_class = mb.DefineType(cnns[iii].namespace_name + "." + "$ClassUnitAttr", TypeAttributes.Public | TypeAttributes.BeforeFieldInit, typeof(Attribute)); ConstructorInfo attr_ci = attr_class.DefineDefaultConstructor(MethodAttributes.Public); cur_type.SetCustomAttribute(attr_ci, new byte[4] { 0x01, 0x00, 0x00, 0x00 }); attr_class.CreateType(); } } else { NamespacesTypes.Add(cnns[iii], entry_type); } } if (comp_opt.target == TargetType.Dll) { for (int iii = 0; iii < cnns.Length; iii++) { string tmp = cur_unit; if (cnns[iii].namespace_name != "") cur_unit = cnns[iii].namespace_name; else cur_unit = entry_cur_unit; foreach (ITemplateClass tc in cnns[iii].templates) { CreateTemplateClass(tc); } cur_unit = tmp; } for (int iii = 0; iii < cnns.Length; iii++) { string tmp = cur_unit; if (cnns[iii].namespace_name != "") cur_unit = cnns[iii].namespace_name; else cur_unit = entry_cur_unit; foreach (ITypeSynonym ts in cnns[iii].type_synonims) { CreateTypeSynonim(ts); } cur_unit = tmp; } } for (int iii = 0; iii < cnns.Length; iii++) { if (save_debug_info) doc = sym_docs[cnns[iii]]; cur_type = NamespacesTypes[cnns[iii]]; cur_unit_type = NamespacesTypes[cnns[iii]]; ConvertTypeMemberHeaders(cnns[iii].types); // cur_type = NamespacesTypes[cnns[iii]]; // cur_unit_type = NamespacesTypes[cnns[iii]]; // ConvertFunctionHeaders(cnns[iii].functions); } for (int iii = 0; iii < cnns.Length; iii++) { if (save_debug_info) doc = sym_docs[cnns[iii]]; cur_type = NamespacesTypes[cnns[iii]]; cur_unit_type = NamespacesTypes[cnns[iii]]; ConvertFunctionHeaders(cnns[iii].functions); } if (p.InitializationCode != null) { tmp_il = il; if (entry_meth != null) { il = entry_meth.GetILGenerator(); ConvertStatement(p.InitializationCode); } else { //il = unit_cci.GetILGenerator(); //ConvertStatement(p.InitializationCode); } il = tmp_il; } //Переводим псевдоинстанции generic-типов foreach (IGenericTypeInstance ictn in p.generic_type_instances) { ConvertGenericInstanceTypeMembers(ictn); } //Переводим псевдоинстанции функций foreach (IGenericFunctionInstance igfi in p.generic_function_instances) { ConvertGenericFunctionInstance(igfi); } for (int iii = 0; iii < cnns.Length; iii++) { if (save_debug_info) doc = sym_docs[cnns[iii]]; cur_type = NamespacesTypes[cnns[iii]]; cur_unit_type = NamespacesTypes[cnns[iii]]; //генерим инциализацию для полей foreach (SemanticTree.ICommonTypeNode ctn in cnns[iii].types) GenerateInitCodeForFields(ctn); } ConstructorBuilder unit_cci = null; //Переводим заголовки всего остального (процедур, переменных) for (int iii = 0; iii < cnns.Length; iii++) { if (save_debug_info) doc = sym_docs[cnns[iii]]; bool is_main_namespace = iii == cnns.Length - 1 && comp_opt.target != TargetType.Dll; ICommonNamespaceNode cnn = cnns[iii]; string tmp_unit_name = cur_unit; if (!is_main_namespace) cur_unit = cnn.namespace_name; else cur_unit = entry_cur_unit; cur_type = NamespacesTypes[cnn]; //ConvertFunctionHeaders(cnn.functions); if (!is_main_namespace) { //определяем статический конструктор класса для модуля ConstructorBuilder cb = cur_type.DefineConstructor(MethodAttributes.Static, CallingConventions.Standard, Type.EmptyTypes); il = cb.GetILGenerator(); if (cnn.IsMain) unit_cci = cb; ModulesInitILGenerators.Add(cur_type, il); //переводим глобальные переменные модуля ConvertGlobalVariables(cnn.variables); //перводим константы ConvertNamespaceConstants(cnn.constants); ConvertNamespaceEvents(cnn.events); //il.Emit(OpCodes.Ret); } else { //Не нарвится мне порядок вызова. надо с этим разобраться init_variables_mb = helper.GetMethodBuilder(cnn.functions[cnn.functions.Length-1]);// cur_type.DefineMethod("$InitVariables", MethodAttributes.Public | MethodAttributes.Static); il = entry_meth.GetILGenerator(); ModulesInitILGenerators.Add(cur_type, il); il = init_variables_mb.GetILGenerator(); ConvertGlobalVariables(cnn.variables); il = entry_meth.GetILGenerator(); //перводим константы ConvertNamespaceConstants(cnn.constants); ConvertNamespaceEvents(cnn.events); //il.Emit(OpCodes.Ret); } cur_unit = tmp_unit_name; } if (p.InitializationCode != null) { tmp_il = il; if (entry_meth == null) { il = unit_cci.GetILGenerator(); ConvertStatement(p.InitializationCode); } il = tmp_il; } cur_type = entry_type; //is_in_unit = false; //переводим реализации for (int iii = 0; iii < cnns.Length; iii++) { if (save_debug_info) doc = sym_docs[cnns[iii]]; bool is_main_namespace = iii == 0 && comp_opt.target != TargetType.Dll; ICommonNamespaceNode cnn = cnns[iii]; string tmp_unit_name = cur_unit; if (!is_main_namespace) cur_unit = cnn.namespace_name; //if (iii > 0) is_in_unit = true; cur_unit_type = NamespacesTypes[cnns[iii]]; cur_type = cur_unit_type; ConvertTypeImplementations(cnn.types); ConvertFunctionsBodies(cnn.functions); cur_unit = tmp_unit_name; } if (comp_opt.target != TargetType.Dll && p.main_function != null) { cur_unit_type = NamespacesTypes[cnns[0]]; cur_type = cur_unit_type; ConvertBody(p.main_function.function_code); } for (int iii = 0; iii < cnns.Length; iii++) { if (save_debug_info) doc = sym_docs[cnns[iii]]; cur_type = NamespacesTypes[cnns[iii]]; cur_unit_type = NamespacesTypes[cnns[iii]]; //вставляем ret в int_meth foreach (SemanticTree.ICommonTypeNode ctn in cnns[iii].types) GenerateRetForInitMeth(ctn); ModulesInitILGenerators[cur_type].Emit(OpCodes.Ret); } for (int iii = 0; iii < cnns.Length; iii++) { MakeAttribute(cnns[iii]); } doc = first_doc; cur_type = entry_type; // il = entry_type.DefineConstructor(MethodAttributes.Static, CallingConventions.Standard, Type.EmptyTypes).GetILGenerator(); // if (p.InitializationCode != null) // ConvertStatement(p.InitializationCode); /*cur_meth = entry_meth; il = entry_meth.GetILGenerator(); //переводим тело основной программы //Тут только вызовы init, final if (p.main_function != null) { ConvertBody(p.main_function.function_code); il.Emit(OpCodes.Ret); }*/ CloseTypes();//закрываем типы entry_type.CreateType(); switch (comp_opt.target) { case TargetType.Exe: ab.SetEntryPoint(entry_meth, PEFileKinds.ConsoleApplication); break; case TargetType.WinExe: if (!comp_opt.ForRunningWithEnvironment) ab.SetEntryPoint(entry_meth, PEFileKinds.WindowApplication); else ab.SetEntryPoint(entry_meth, PEFileKinds.ConsoleApplication); break; } /**/ try { //ne osobo vazhnaja vesh, sohranjaet v exe-shnik spisok ispolzuemyh prostranstv imen, dlja strahovki obernuli try catch if (comp_opt.dbg_attrs == DebugAttributes.ForDebbuging) { string[] namespaces = p.UsedNamespaces; TypeBuilder attr_class = mb.DefineType("$UsedNsAttr", TypeAttributes.Public | TypeAttributes.BeforeFieldInit, typeof(Attribute)); FieldBuilder fld_ns = attr_class.DefineField("ns", TypeFactory.StringType, FieldAttributes.Public); FieldBuilder fld_count = attr_class.DefineField("count", TypeFactory.Int32Type, FieldAttributes.Public); ConstructorBuilder attr_ci = attr_class.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, new Type[2] { TypeFactory.Int32Type, TypeFactory.StringType }); ILGenerator attr_il = attr_ci.GetILGenerator(); attr_il.Emit(OpCodes.Ldarg_0); attr_il.Emit(OpCodes.Ldarg_1); attr_il.Emit(OpCodes.Stfld, fld_count); attr_il.Emit(OpCodes.Ldarg_0); attr_il.Emit(OpCodes.Ldarg_2); attr_il.Emit(OpCodes.Stfld, fld_ns); attr_il.Emit(OpCodes.Ret); int len = 2 + 2 + 4 + 1; foreach (string ns in namespaces) { len += ns.Length + 1; } byte[] bytes = new byte[len]; bytes[0] = 1; bytes[1] = 0; using (BinaryWriter bw = new BinaryWriter(new MemoryStream())) { bw.Write(namespaces.Length); System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (string ns in namespaces) { sb.Append(Convert.ToChar(ns.Length)); sb.Append(ns); //bw.Write(ns); } if (sb.Length > 127) { len += 1; bytes = new byte[len]; bytes[0] = 1; bytes[1] = 0; } bw.Write(sb.ToString()); bw.Seek(0, SeekOrigin.Begin); bw.BaseStream.Read(bytes, 2, len - 4); if (sb.Length > 127) { bytes[7] = (byte)(sb.Length & 0xFF); bytes[6] = (byte)(0x80 | ((sb.Length & 0xFF00) >> 8)); } } entry_type.SetCustomAttribute(attr_ci, bytes); attr_class.CreateType(); } } catch (Exception e) { } if (an.Name == "PABCRtl" || an.Name == "PABCRtl32") { CustomAttributeBuilder cab = new CustomAttributeBuilder(typeof(AssemblyKeyFileAttribute).GetConstructor(new Type[] { typeof(string) }), new object[] { an.Name == "PABCRtl" ? "PublicKey.snk" : "PublicKey32.snk" }); ab.SetCustomAttribute(cab); cab = new CustomAttributeBuilder(typeof(AssemblyDelaySignAttribute).GetConstructor(new Type[] { typeof(bool) }), new object[] { true }); ab.SetCustomAttribute(cab); cab = new CustomAttributeBuilder(typeof(TargetFrameworkAttribute).GetConstructor(new Type[] { typeof(string) }), new object[] { ".NETFramework,Version=v4.0" }); ab.SetCustomAttribute(cab); } ab.SetCustomAttribute(new CustomAttributeBuilder(typeof(SecurityRulesAttribute).GetConstructor(new Type[] { typeof(SecurityRuleSet) }), new object[] { SecurityRuleSet.Level2 }, new PropertyInfo[] { typeof(SecurityRulesAttribute).GetProperty("SkipVerificationInFullTrust") }, new object[] { true })); /*ab.SetCustomAttribute(new CustomAttributeBuilder(typeof(System.Security.Permissions.SecurityPermissionAttribute).GetConstructor(new Type[] { typeof(System.Security.Permissions.SecurityAction) }), new object[] { System.Security.Permissions.SecurityAction.RequestMinimum }, new PropertyInfo[] { typeof(System.Security.Permissions.SecurityPermissionAttribute).GetProperty("UnmanagedCode") }, new object[] { true }));*/ if (entry_meth != null && comp_opt.target == TargetType.WinExe) { entry_meth.SetCustomAttribute(typeof(STAThreadAttribute).GetConstructor(Type.EmptyTypes), new byte[] { 0x01, 0x00, 0x00, 0x00 }); } List<FileStream> ResStreams = new List<FileStream>(); if (ResourceFiles != null) foreach (string resname in ResourceFiles) { FileStream stream = File.OpenRead(resname); ResStreams.Add(stream); mb.DefineManifestResource(Path.GetFileName(resname), stream, ResourceAttributes.Public); //System.Resources.ResourceManager rm; //System.Resources.ResourceSet rs;rs. } ab.SetCustomAttribute(typeof(System.Runtime.CompilerServices.CompilationRelaxationsAttribute).GetConstructor(new Type[1] { TypeFactory.Int32Type }), new byte[] { 0x01, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00 }); //ab.SetCustomAttribute(typeof(System.Runtime.CompilerServices.RuntimeCompatibilityAttribute, if (RunOnly) { object main_class = ab.CreateInstance(cur_unit + ".Program"); MethodInfo methodInfo = main_class.GetType().GetMethod("Main"); //AppDomain.CreateDomain( methodInfo.Invoke(main_class, null); //ad.ExecuteAssemblyByName(assembly_to_run.GetName(), new System.Security.Policy.Evidence(), null); } else { int tries = 0; bool not_done = true; do { try { if (comp_opt.target == TargetType.Exe || comp_opt.target == TargetType.WinExe) { if (comp_opt.platformtarget == NETGenerator.CompilerOptions.PlatformTarget.x86) ab.Save(an.Name + ".exe", PortableExecutableKinds.Required32Bit, ImageFileMachine.I386); //else if (comp_opt.platformtarget == NETGenerator.CompilerOptions.PlatformTarget.x64) // ab.Save(an.Name + ".exe", PortableExecutableKinds.PE32Plus, ImageFileMachine.IA64); else ab.Save(an.Name + ".exe"); //сохраняем сборку } else { if (comp_opt.platformtarget == NETGenerator.CompilerOptions.PlatformTarget.x86) ab.Save(an.Name + ".dll", PortableExecutableKinds.Required32Bit, ImageFileMachine.I386); //else if (comp_opt.platformtarget == NETGenerator.CompilerOptions.PlatformTarget.x64) // ab.Save(an.Name + ".dll", PortableExecutableKinds.PE32Plus, ImageFileMachine.IA64); else ab.Save(an.Name + ".dll"); } not_done = false; } catch (System.Runtime.InteropServices.COMException e) { throw new TreeConverter.SaveAssemblyError(e.Message); } catch (System.IO.IOException e) { if (tries < num_try_save) tries++; else throw new TreeConverter.SaveAssemblyError(e.Message); } } while (not_done); } foreach (FileStream fs in ResStreams) fs.Close(); //ad.ExecuteAssemblyByName(an, new System.Security.Policy.Evidence()); //это уже не нужно //Console.WriteLine(Environment.TickCount-ticks); }
public void EmitAttribute (TypeBuilder builder) { if (ResolveBuilder ()) builder.SetCustomAttribute (cab); }
internal static void MarkAsSerializable(TypeBuilder tb) { tb.SetCustomAttribute(new CustomAttributeBuilder(Compiler.Ctor_Serializable, new object[0])); }
private static void SetAttributes(TypeBuilder typeBuilder, Type type) { var attributeBuilders = TypeAttributeBuilders .GetOrAdd( type, t => { var customAttributes = t.GetCustomAttributesData(); return CreateCustomAttributeBuilders(customAttributes).ToArray(); }); Contract.Assume(attributeBuilders != null); foreach (var attributeBuilder in attributeBuilders) { typeBuilder.SetCustomAttribute(attributeBuilder); } }
private void add_possible_type_attribute(TypeBuilder tb, ITypeNode type) { if (comp_opt.target != TargetType.Dll) return; if (type.type_special_kind == type_special_kind.typed_file) { Type elem_type = helper.GetTypeReference(type.element_type).tp; CustomAttributeBuilder cust_bldr = null; if (type.element_type is ICompiledTypeNode || type.element_type is IRefTypeNode && (type.element_type as IRefTypeNode).pointed_type is ICompiledTypeNode) cust_bldr = new CustomAttributeBuilder(this.FileOfAttributeConstructor, new object[1] { elem_type }); else cust_bldr = new CustomAttributeBuilder(this.FileOfAttributeConstructor, new object[1] { elem_type.FullName }); tb.SetCustomAttribute(cust_bldr); } else if (type.type_special_kind == type_special_kind.set_type) { Type elem_type = helper.GetTypeReference(type.element_type).tp; CustomAttributeBuilder cust_bldr = null; if (type.element_type is ICompiledTypeNode || type.element_type is IRefTypeNode && (type.element_type as IRefTypeNode).pointed_type is ICompiledTypeNode) cust_bldr = new CustomAttributeBuilder(this.SetOfAttributeConstructor, new object[1] { elem_type }); else cust_bldr = new CustomAttributeBuilder(this.SetOfAttributeConstructor, new object[1] { elem_type.FullName }); tb.SetCustomAttribute(cust_bldr); } else if (type.type_special_kind == type_special_kind.short_string) { int len = (type as IShortStringTypeNode).Length; CustomAttributeBuilder cust_bldr = new CustomAttributeBuilder(this.ShortStringAttributeConstructor, new object[1] { len }); tb.SetCustomAttribute(cust_bldr); } }
private void CloneCustomAttributes(TypeBuilder typeBuilder, EntityInfo entity) { foreach (var attr in entity.Attributes) { CustomAttributeHandler handler; if (!_model.App.AttributeHandlers.TryGetValue(attr.GetType(), out handler)) continue; var attrBuilder = handler.Clone(attr); if (attrBuilder != null) typeBuilder.SetCustomAttribute(attrBuilder); } }
public static void SetCustomAttributes(TypeBuilder tb, IPersistentMap attributes) { foreach ( CustomAttributeBuilder cab in CreateCustomAttributeBuilders(attributes) ) tb.SetCustomAttribute(cab); }
private static void GenerateClassAttributes(TypeBuilder dynamicType, string[] properties) { var type = typeof(CompilerGeneratedAttribute); var customBuilder = new CustomAttributeBuilder(type.GetConstructor(new Type[0]), new object[0]); dynamicType.SetCustomAttribute(customBuilder); var type2 = typeof(DebuggerDisplayAttribute); var builder2 = new StringBuilder(@"\{ "); var flag = true; foreach (var propertyName in properties) { builder2.AppendFormat("{0}{1} = ", flag ? "" : ", ", propertyName); builder2.Append("{"); builder2.Append(propertyName); builder2.Append("}"); flag = false; } builder2.Append(" }"); var property = type2.GetProperty("Type"); var builder3 = new CustomAttributeBuilder(type2.GetConstructor(new[] { typeof(string) }), new object[] { builder2.ToString() }, new[] { property }, new object[] { "<Anonymous Type>" }); dynamicType.SetCustomAttribute(builder3); }
/// <summary> /// Generates attributes for a type. /// </summary> /// <param name="dynamicType">A <see cref="TypeBuilder"/> to generate the attributes for.</param> /// <param name="propertyNames">Names of the properties.</param> private static void GenerateClassAttributes(TypeBuilder dynamicType, IEnumerable<string> propertyNames) { Type attributeType1 = typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute); CustomAttributeBuilder compilerGenAttribute = new CustomAttributeBuilder(attributeType1.GetConstructor(new Type[0]), new object[0]); dynamicType.SetCustomAttribute(compilerGenAttribute); Type attributeType2 = typeof(DebuggerDisplayAttribute); StringBuilder sbValue = new StringBuilder("\\{ "); bool first = true; foreach (string propertyName in propertyNames) { sbValue.AppendFormat("{0}{1} = ", first ? "" : ", ", propertyName); sbValue.Append("{"); sbValue.Append(propertyName); sbValue.Append("}"); first = false; } sbValue.Append(" }"); PropertyInfo typeProperty = attributeType2.GetProperty("Type"); CustomAttributeBuilder debugDisplayAttribute = new CustomAttributeBuilder(attributeType2.GetConstructor(new[] { typeof(string) }), new object[] { sbValue.ToString() }, new[] { typeProperty }, new object[] { "<Anonymous Type>" }); dynamicType.SetCustomAttribute(debugDisplayAttribute); }
private void add_possible_type_attribute(TypeBuilder tb, ITypeSynonym type) { Type orig_type = get_type_reference_for_pascal_attributes(type.original_type); CustomAttributeBuilder cust_bldr = null; if (type.original_type is ICompiledTypeNode || type.original_type is IRefTypeNode && (type.original_type as IRefTypeNode).pointed_type is ICompiledTypeNode) cust_bldr = new CustomAttributeBuilder(this.TypeSynonimAttributeConstructor, new object[1] { orig_type }); else cust_bldr = new CustomAttributeBuilder(this.TypeSynonimAttributeConstructor, new object[1] { orig_type.FullName }); tb.SetCustomAttribute(cust_bldr); }
private static void AddSerializationSupport(System.Type baseType, System.Type[] baseInterfaces, TypeBuilder typeBuilder, FieldInfo interceptorField, ConstructorBuilder defaultConstructor) { ConstructorInfo serializableConstructor = typeof(SerializableAttribute).GetConstructor(new System.Type[0]); var customAttributeBuilder = new CustomAttributeBuilder(serializableConstructor, new object[0]); typeBuilder.SetCustomAttribute(customAttributeBuilder); DefineSerializationConstructor(typeBuilder, interceptorField, defaultConstructor); ImplementGetObjectData(baseType, baseInterfaces, typeBuilder, interceptorField); }
private void EmitCustomAttributes(TypeBuilder typeBuilder, IEnumerable<Cci.ICustomAttribute> attributes) { foreach (var attribute in attributes) { typeBuilder.SetCustomAttribute(CreateCustomAttributeBuilder(attribute)); } }
public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { _tb.SetCustomAttribute(customBuilder); }
internal void Implement(TypeBuilder typeBuilder, Action<FieldBuilder, bool> registerField) { if (_dataContract != null) { // Use base data contract properties to help determine values of properties the proxy type's data contract. object[] propertyValues = new object[] { // IsReference _dataContract.IsReference }; CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(s_DataContractAttributeConstructor, new object[0], s_DataContractProperties, propertyValues); typeBuilder.SetCustomAttribute(attributeBuilder); } }
public static void SetCustomAttributes(TypeBuilder tb, IPersistentMap attributes) { for (ISeq s = RT.seq(attributes); s != null; s = s.next()) tb.SetCustomAttribute(CreateCustomAttributeBuilder((IMapEntry)(s.first()))); }
private static void AddSerializationSupport(Type baseType, Type[] baseInterfaces, TypeBuilder typeBuilder, FieldInfo interceptorField, ConstructorBuilder defaultConstructor) { CustomAttributeBuilder customBuilder = new CustomAttributeBuilder(typeof (SerializableAttribute).GetConstructor(new Type[0]), new object[0]); typeBuilder.SetCustomAttribute(customBuilder); ProxyFactory.DefineSerializationConstructor(typeBuilder, interceptorField, defaultConstructor); ProxyFactory.ImplementGetObjectData(baseType, baseInterfaces, typeBuilder, interceptorField); }
/// <summary> /// Applies attributes to the proxy class. /// </summary> /// <param name="typeBuilder">The type builder to use.</param> /// <param name="targetType">The proxied class.</param> /// <see cref="IProxyTypeBuilder.ProxyTargetAttributes"/> /// <see cref="IProxyTypeBuilder.TypeAttributes"/> protected override void ApplyTypeAttributes(TypeBuilder typeBuilder, Type targetType) { foreach (object attr in GetTypeAttributes(targetType)) { if (attr is CustomAttributeBuilder) { typeBuilder.SetCustomAttribute((CustomAttributeBuilder)attr); } #if NET_2_0 else if (attr is CustomAttributeData) { typeBuilder.SetCustomAttribute( ReflectionUtils.CreateCustomAttribute((CustomAttributeData)attr)); } #endif else if (attr is Attribute) { typeBuilder.SetCustomAttribute( ReflectionUtils.CreateCustomAttribute((Attribute)attr)); } else if (attr is IObjectDefinition) { RootObjectDefinition objectDefinition = (RootObjectDefinition) attr; //TODO check that object definition is for an Attribute type. //Change object definition so it can be instantiated and make prototype scope. objectDefinition.IsAbstract = false; objectDefinition.IsSingleton = false; string objectName = ObjectDefinitionReaderUtils.GenerateObjectName(objectDefinition, objectFactory); objectFactory.RegisterObjectDefinition(objectName, objectDefinition); //find constructor and constructor arg values to create this attribute. ConstructorResolver constructorResolver = new ConstructorResolver(objectFactory, objectFactory, new SimpleInstantiationStrategy(), new ObjectDefinitionValueResolver(objectFactory)); ConstructorInstantiationInfo ci = constructorResolver.GetConstructorInstantiationInfo(objectName, objectDefinition, null, null); if (objectDefinition.PropertyValues.PropertyValues.Length == 0) { CustomAttributeBuilder cab = new CustomAttributeBuilder(ci.ConstructorInfo, ci.ArgInstances); typeBuilder.SetCustomAttribute(cab); } else { object attributeInstance = objectFactory.GetObject(objectName); IObjectWrapper wrappedAttributeInstance = new ObjectWrapper(attributeInstance); PropertyInfo[] namedProperties = wrappedAttributeInstance.GetPropertyInfos(); object[] propertyValues = new object[namedProperties.Length]; for (int i = 0; i < namedProperties.Length; i++) { propertyValues[i] = wrappedAttributeInstance.GetPropertyValue(namedProperties[i].Name); } CustomAttributeBuilder cab = new CustomAttributeBuilder(ci.ConstructorInfo, ci.ArgInstances, namedProperties, propertyValues); typeBuilder.SetCustomAttribute(cab); } } } }
public static void Define(TypeBuilder typeB, Interface iface) { foreach (Method declMethod in iface.Methods) DefineMethod (typeB, declMethod.Name, ifaceMethAttr, declMethod.Arguments, false); if (iface.Properties != null) foreach (NDesk.DBus.Introspection.Property prop in iface.Properties) { Type propType = new Signature (prop.Type).ToType (); PropertyBuilder prop_builder = typeB.DefineProperty (prop.Name, PropertyAttributes.None, propType, Type.EmptyTypes); if (prop.Access == propertyAccess.read || prop.Access == propertyAccess.readwrite) prop_builder.SetGetMethod (typeB.DefineMethod ("get_" + prop.Name, ifaceMethAttr | MethodAttributes.SpecialName, propType, Type.EmptyTypes)); if (prop.Access == propertyAccess.write || prop.Access == propertyAccess.readwrite) prop_builder.SetSetMethod (typeB.DefineMethod ("set_" + prop.Name, ifaceMethAttr | MethodAttributes.SpecialName, null, new Type[] {propType})); } if (iface.Signals != null) foreach (NDesk.DBus.Introspection.Signal signal in iface.Signals) { Type eventType = DefineHandler (modBdef, signal); EventBuilder event_builder = typeB.DefineEvent (signal.Name, EventAttributes.None, eventType); event_builder.SetAddOnMethod (typeB.DefineMethod ("add_" + signal.Name, ifaceMethAttr | MethodAttributes.SpecialName, null, new Type[] {eventType})); event_builder.SetRemoveOnMethod (typeB.DefineMethod ("remove_" + signal.Name, ifaceMethAttr | MethodAttributes.SpecialName, null, new Type[] {eventType})); } //apply InterfaceAttribute ConstructorInfo interfaceAttributeCtor = typeof (InterfaceAttribute).GetConstructor(new Type[] {typeof (string)}); CustomAttributeBuilder cab = new CustomAttributeBuilder (interfaceAttributeCtor, new object[] {iface.Name}); typeB.SetCustomAttribute (cab); }
/// <summary> /// Generate the declaration for the IgnoresAccessChecksToAttribute type. /// This attribute will be both defined and used in the dynamic assembly. /// Each usage identifies the name of the assembly containing non-public /// types the dynamic assembly needs to access. Normally those types /// would be inaccessible, but this attribute allows them to be visible. /// It works like a reverse InternalsVisibleToAttribute. /// This method returns the ConstructorInfo of the generated attribute. /// </summary> public static ConstructorInfo AddToModule(ModuleBuilder mb) { TypeBuilder attributeTypeBuilder = mb.DefineType("System.Runtime.CompilerServices.IgnoresAccessChecksToAttribute", TypeAttributes.Public | TypeAttributes.Class, typeof(Attribute)); // Create backing field as: // private string assemblyName; FieldBuilder assemblyNameField = attributeTypeBuilder.DefineField("assemblyName", typeof(string), FieldAttributes.Private); // Create ctor as: // public IgnoresAccessChecksToAttribute(string) ConstructorBuilder constructorBuilder = attributeTypeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, new Type[] { assemblyNameField.FieldType }); ILGenerator il = constructorBuilder.GetILGenerator(); // Create ctor body as: // this.assemblyName = {ctor parameter 0} il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg, 1); il.Emit(OpCodes.Stfld, assemblyNameField); // return il.Emit(OpCodes.Ret); // Define property as: // public string AssemblyName {get { return this.assemblyName; } } _ = attributeTypeBuilder.DefineProperty( "AssemblyName", PropertyAttributes.None, CallingConventions.HasThis, returnType: typeof(string), parameterTypes: null); MethodBuilder getterMethodBuilder = attributeTypeBuilder.DefineMethod( "get_AssemblyName", MethodAttributes.Public, CallingConventions.HasThis, returnType: typeof(string), parameterTypes: null); // Generate body: // return this.assemblyName; il = getterMethodBuilder.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, assemblyNameField); il.Emit(OpCodes.Ret); // Generate the AttributeUsage attribute for this attribute type: // [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] TypeInfo attributeUsageTypeInfo = typeof(AttributeUsageAttribute).GetTypeInfo(); // Find the ctor that takes only AttributeTargets ConstructorInfo attributeUsageConstructorInfo = attributeUsageTypeInfo.DeclaredConstructors .Single(c => c.GetParameters().Length == 1 && c.GetParameters()[0].ParameterType == typeof(AttributeTargets)); // Find the property to set AllowMultiple PropertyInfo allowMultipleProperty = attributeUsageTypeInfo.DeclaredProperties .Single(f => string.Equals(f.Name, "AllowMultiple")); // Create a builder to construct the instance via the ctor and property CustomAttributeBuilder customAttributeBuilder = new CustomAttributeBuilder(attributeUsageConstructorInfo, new object[] { AttributeTargets.Assembly }, new PropertyInfo[] { allowMultipleProperty }, new object[] { true }); // Attach this attribute instance to the newly defined attribute type attributeTypeBuilder.SetCustomAttribute(customAttributeBuilder); // Make the TypeInfo real so the constructor can be used. return(attributeTypeBuilder.CreateTypeInfo() !.DeclaredConstructors.Single()); }
private static void AddCustomClassAttribute (TypeBuilder typeBuilder, Type customAttrType) { var attribCtorParams = new Type[] {}; var attribCtorInfo = customAttrType.GetConstructor(attribCtorParams); var attribBuilder = new CustomAttributeBuilder(attribCtorInfo, new object[] { }); typeBuilder.SetCustomAttribute(attribBuilder); }