chris carter's web log

Home |  Contact |  Admin
 

15 Minutes

Posted on June 9, 2008

Pop Quiz Hot Shot: How long does it take you to write CodeDom code, compile it, and call it? Do you even know where to start?  This is what  I came up with in 15 minutes, started at 10:17pm ended at 10:32pm:

using System;
using NUnit.Framework;
using System.Reflection;
using System.CodeDom;
using Microsoft.CSharp;
using System.CodeDom.Compiler;

namespace DataBoundControls
{
	[TestFixture]
	public class CodeGenTests
	{
		[Test]
		public void PopQuiz()
		{
			CodeTypeDeclaration clazz = new CodeTypeDeclaration("TableGenerator");
			CodeMemberMethod method = new CodeMemberMethod();
			method.ReturnType = new CodeTypeReference(typeof(string));
			method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "name"));
			method.Name = "SayHello";
			method.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			method.Statements.Add(
				new CodeMethodReturnStatement(
					new CodeArgumentReferenceExpression("name")));
			clazz.Members.Add(method);
			CodeNamespace nspace = new CodeNamespace("Dummy");
			nspace.Types.Add(clazz);
			nspace.Imports.Add(new CodeNamespaceImport("System"));

			CodeDomProvider generator = new CSharpCodeProvider();
			//Next line shows what was generated
			//generator.GenerateCodeFromNamespace(nspace, Console.Out, new CodeGeneratorOptions());
			CodeCompileUnit unit = new CodeCompileUnit();
			unit.Namespaces.Add(nspace);
			CompilerParameters parameters = new CompilerParameters { GenerateInMemory = true };
			CompilerResults results = generator.CompileAssemblyFromDom(parameters, unit);
			Assembly ass = results.CompiledAssembly;
			Type type = ass.GetType("Dummy.TableGenerator");
			object inst = Activator.CreateInstance(type);
			MethodInfo sayhello = type.GetMethod("SayHello");
			string result = sayhello.Invoke(inst, new object[] { "Chris" }).ToString();
			Console.WriteLine(result);

		}
	}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46