protected void WeaveTypeProperties(TypeDefinition type) { var properties = type.Properties.Where( p => p.CustomAttributes.Any( a => a.AttributeType.FullName == typeof (PropertyAttribute).FullName)); if(!properties.Any()) return; if(!type.HasInterface(typeof(IPropertyNotifier).FullName)) throw new Exception(string.Format("Type {0} has properties but does not implement {1}", type.FullName, typeof(IPropertyNotifier).FullName)); Console.WriteLine(type.FullName); var weaver = new TypeWeaver(originType, type); foreach(var property in properties) { weaver.NamePrefix = "<$" + property.Name + "$>"; var desNotifierMethod = type.GetMethod(tNotifierMethod.Name); weaver.Map(tNotifierMethod, desNotifierMethod); var propField = weaver.AddDefinition(tPropertyField); propField.FieldType = property.PropertyType; weaver.AddConstant(tPropertyNameC,property.Name); //TODO delete property generated field weaver.Merge(tPropertyProperty, property); weaver.ProcessInstructions(); } }
/// <summary> /// Method verifies that the type implements IDisposable and emits /// IL to implement it if necessary. /// </summary> /// <param name="type">The type that needs to be checked and potentially modified.</param> private void EnsureTypeImplementsIDisposable(TypeDefinition type) { // Verify whether the class already implements IDisposable. If not then // implement it. if (!type.HasInterface("System.IDisposable")) { type.Interfaces.Add(type.Module.ImportReference(typeof(IDisposable))); // Verify whether the type already has a public Dipose method. If not then add a shell. if (!type.HasDisposeMethod()) { var disposeMethodAttribs = Mono.Cecil.MethodAttributes.Public | Mono.Cecil.MethodAttributes.Final | Mono.Cecil.MethodAttributes.HideBySig | Mono.Cecil.MethodAttributes.NewSlot | Mono.Cecil.MethodAttributes.Virtual; var disposeDefinition = new MethodDefinition("Dispose", disposeMethodAttribs, ModuleDefinition.TypeSystem.Void); // Empty method shell that only returns void. disposeDefinition.Body.Instructions.Add(Instruction.Create(OpCodes.Nop)); disposeDefinition.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); type.Methods.Add(disposeDefinition); } } }