Create Classes then Objects at Runtime

May 18, 2010 at 1:58 PM

Hi

I have a need to create classes at runtime. Is this already supported? If not is this project a good place to start?

Thanks

May 18, 2010 at 5:19 PM
Edited May 18, 2010 at 6:04 PM

I found that I can do this easily with the following:

        public static Assembly CreateType(String XmlSchema)
        {
            var generatorParams = new GeneratorParams();

            generatorParams.InputData = XmlSchema;

            generatorParams.AutomaticProperties = false;
            generatorParams.BaseClassName = "Whatever";
            generatorParams.CollectionBase = null;
            generatorParams.CollectionObjectType = CollectionType.List;
            generatorParams.Language = GenerationLanguage.CSharp;
            generatorParams.IncludeSerializeMethod = false;
            generatorParams.TargetFramework = TargetFramework.Net35;
            generatorParams.UseGenericBaseClass = false;

            // Create an instance of Generator
            var generator = new GeneratorFacade(generatorParams);

            var result2 = generator.GenerateBytes();

            String code = System.Text.ASCIIEncoding.ASCII.GetString(result2.Entity);


            CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerParameters parameters = new CompilerParameters();
            CompilerResults results = null;

            parameters.OutputAssembly = "Whatever";
            parameters.ReferencedAssemblies.Add("system.dll");
            parameters.ReferencedAssemblies.Add("system.xml.dll");
            parameters.ReferencedAssemblies.Add("system.data.dll");
            parameters.ReferencedAssemblies.Add("system.web.dll");
            parameters.CompilerOptions = "/t:library";
            parameters.GenerateInMemory = true;
            parameters.GenerateExecutable = false;
            parameters.IncludeDebugInformation = false;

            results = provider.CompileAssemblyFromSource(parameters, code);

            if (results.Errors.Count != 0)
            {
                throw new Exception("Code compilation errors occurred.");
            }
            else
            {
                return results.CompiledAssembly;
            }

            
        }

 

I added a InputData property to the generatorParams class to suite my situation. I also modified a couple of lines of code that expect to be using an InputFile.

Half of the code came from here  http://www.eggheadcafe.com/articles/aspnet_dynamic_code_runtime.asp

If this kind of thing is already supported and I'm making work for myself please let me know :)