code generation RRS feed

  • Question

  • in short I am looking for dynamicaly code creation help. Consider example below. How to be able keeping isolated different publishers from each other I would like to auto generate the code below for each new publisher type that appears. The only thing that changes is that a number 1 increases for each new publisher type.

    interface IProcess_1_DataEvents : IProcessDataEvents
    public class ProcessData_1_Subscriber : SubscriberManager<IProcess_1_DataEvents>, IProcess_1_DataEvents


    The code generating above code is shown below. Now everything is going well until in line number 7 while calling DefineType for second time while passing inn the type created in line 5 a compile error occurs.


    Error: The type or namespace name 'processDataEventsType' could not be found (are you missing a using directive or an assembly reference?


    Any help appreciates

    1. AssemblyName assemblyName = new AssemblyName("myAssembly");
    2. AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName,AssemblyBuilderAccess.RunAndSave);
    3. ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("myModule", "myAssembly.dll");
    4. TypeBuilder processDataEventsBuilder =
    moduleBuilder.DefineType(string.Format("IProcess_{0}_DataEvents", FmcAudit.GuidHyphensToUnderscores(DATA_SIMULATOR_ID)), 
    5. TypeAttributes.Public | TypeAttributes.Interface | TypeAttributes.Abstract,
    new Type[]{typeof(IProcessDataEvents)});
    6. Type processDataEventsType = processDataEventsBuilder.CreateType();
    7. TypeBuilder subscriptionManagerTypeBuilder =
    moduleBuilder.DefineType(string.Format("ProcessData_{0}_SubscriptionManager", FmcAudit.GuidHyphensToUnderscores(DATA_SIMULATOR_ID)),
    TypeAttributes.Public | TypeAttributes.Class,
    new Type[] 
    8. Type subscriptionManagerType = subscriptionManagerTypeBuilder.CreateType();
    9. assemblyBuilder.Save("myassembly.dll");
    Sunday, May 25, 2008 9:57 PM

All replies

  • It works when I try it, albeit after considerable editing.  Exactly what exception do you get?  If it is TypeLoadException, access denied, your IProcessDataEvent interface isn't public.
    Monday, May 26, 2008 2:36 AM
  • Okay, it is not line 6 but line 7 that complains about compile error:

    The type or namespace name 'processDataEventsType' could not be found (are you missing a using directive or an assembly reference.


    it is worth noting here that IProcessDataEvent interface is not auto generated, but rather loaded from a references assembly. It is the derived version (IProcess_1_DataEvents), that gets code generated.


    now use of this recent created Type in ModuleBuilder.DefineType (line 7) that fails like mentioned above.


    You could'nt share your "working" code?

    Monday, May 26, 2008 9:11 AM