Dynamically generate ENUMs through assembly
In C# ENUMs are storage efficient data structure acting at run-time just like primitive types. The following presents one way to generate an enumeration class within a dynamic assembly using database data.
Let’s assume we have the following table and we want to map this to an enum type:
—————-
id | description
—————-
0 | pink
1 | magenta
—————-
First will retrieve the data constructing the enum source code into a string variable. For data access we use a SQL helper class that loads a DataReader object.
One thing we have to check here is to remove not allowed characters from the enumeration names list. Also values must be integer numbers.
string strEnumSource = "enum colors {"; OracleDataReader rdr = Sql.ExecuteReader("SELECT id, description FROM colors"); if (rdr.HasRows) { while (rdr.Read()) { int nValue; string strKey; strKey = Convert.ToString(rdr[1]); strKey = Regex.Replace(strKey, @"[^\w\.@-]", ""); if (!Int32.TryParse(Convert.ToString(rdr[0]), out nValue)) throw new Exception("ERROR: value must be an integer!"); strEnumSource += strKey + "=" + nValue + ","; } } if (strEnumSource.EndsWith(",")) strEnumSource = strEnumSource.Remove(strEnumSource.LastIndexOf(",")); strEnumSource += "}";
Next will compile the enum using the CodeDomProvider abstract class. A CodeDomProvider implementation provides an interface for generating code and managing compilation for a single programming language.
CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
We don’t want to save anything to disk so will use a CompilerParameters object to specify the compiler settings.
CompilerParameters cparam = new CompilerParameters(); cparam.GenerateExecutable = false; cparam.GenerateInMemory = true; cparam.TreatWarningsAsErrors = false; CompilerResults cresult = codeProvider.CompileAssemblyFromSource(cparam, strEnumSource);
The Errors property of the CompilerResults class exposes the messages resulting from compilation, if any.
if (cresult.Errors.Count > 0) { foreach (CompilerError ce in cresult.Errors) strErrors += ce.ToString() + System.Environment.NewLine; throw new Exception("ERROR: " + strErrors); }
If there are no compilation errors we can simply get the type compiled and ready for use.
Type enumType = cresult.CompiledAssembly.GetType("colors"); int[] nValues = (int[])Enum.GetValues(enumType); string str = ""; foreach (int nValue in nValues) str += String.Format(" {0}: {1} ", Enum.GetName(enumType, nValue), nValue);
Namespace: System.CodeDom.Compiler


Tags: 



2 Responses
Hardware Review: Motorola Droid on Verizon | Cambridge Apartments for Rent
September 16, 2010 1
[...] Generate enum type at run-time within dynamic assembly | Ropardo Blog [...]
October 20, 2010 2
Thanks for the info
Leave a Reply