Ropardo Sowftware development company

Experience software development with ROPARDO S.R.L.

RSS Feed
RSS Feed
  • Home
  • About ROPARDO S.R.L
  • Our websites

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

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
Get Shareaholic
Tags: C# CodeDomProvider compiler dll enum run-time assembly

 Posted in: Microsoft.NET
August 12, 2010 | Daniel Bozdoc | 2 Comments

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 [...]

  • zerodtkjoe
    October 20, 2010
    2

    Thanks for the info

Leave a Reply

 


  • « Previous post
  • Next post »
  • Recent Posts

    • Installing PyGraphviz on Windows
    • Convert python object to XML representation
    • Liferay Portlet Development
    • Norway Road Show 2011 private meeting invitation
    • Oracle OpenWorld 2011
  • Ropardo is Hiring

  • Subscribe

    • Add to Google Reader or Homepage Add to netvibes TopOfBlogs
  • Recent Comments

    • Rajkumar Pomaji on Bluetooth PC Remote Control
    • Stelian Morariu on GWT 2.1 – Uploading a file using the RPC mechanism
    • Sergio on GWT 2.1 – Uploading a file using the RPC mechanism
    • Artem on Liferay: Deployment will start in a few seconds… and how to realy start
    • rkd80 on GWT 2.1 – Uploading a file using the RPC mechanism
  • Archives

    • November 2011 (1)
    • September 2011 (4)
    • July 2011 (3)
    • June 2011 (2)
    • May 2011 (4)
    • April 2011 (4)
    • March 2011 (3)
    • February 2011 (2)
    • January 2011 (2)
    • December 2010 (1)
    • November 2010 (4)
    • October 2010 (4)
    • August 2010 (3)
    • July 2010 (3)
    • June 2010 (6)
    • May 2010 (8)
    • April 2010 (7)
    • March 2010 (9)
    • February 2010 (6)
    • January 2010 (5)
    • December 2009 (7)
    • November 2009 (9)
    • October 2009 (10)
    • September 2009 (14)
    • August 2009 (10)
    • July 2009 (1)
    • June 2009 (1)
    • May 2009 (1)
    • April 2009 (1)
    • March 2009 (1)
    • October 2008 (3)
    • October 2007 (3)
    • July 2007 (4)
    • June 2007 (1)
    • May 2007 (3)
  • Meta

    • Log in
    • Entries RSS
    • Comments RSS
    • WordPress.org
  • Categories

    • News (15)
    • Ropardo Team (8)
    • Ropardo Products (6)
      • File Tracking Client (4)
      • iManagement (2)
    • Software Development (83)
      • Microsoft.NET (22)
      • Java (40)
      • Oracle (8)
      • Power Builder (3)
      • Liferay (5)
      • Lotus Notes (9)
      • xWiki (4)
    • System Adminstration (13)
      • Linux (10)
      • Windows (3)
    • Programming (1)
    • Uncategorized (3)
    • Databases (10)
      • MSSQL (5)
      • PostgreeSQL (3)
    • Microsoft.NET (1)
    • Web Development (28)
      • ASP/ASPX (3)
      • Content Management Systems (1)
      • HTML/CSS (5)
      • Javascrip/AJAX (8)
      • PHP (7)
    • Oracle E Business Suite (6)
  • Tags

    .NET ajax blog C# certification client CMS control css database Debugging django Domino Eclipse extension file tracking filter fun gentoo google Hibernate how to html image iManagement import Java javascript jQuery liferay Linux Lotus Notes lotus script Oracle Oracle BI Publisher 11g PHP portal PostgreSQL powerbuilder Python SQL Telerik velocity xml Xwiki

© 2010 ROPARDO s.r.l..

Powered by WordPress. Styled by Ropardo