Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic run an Enum project inside another project

I did a project in C# that generates a .dll file that contains dynamic Enums generated from look-ups tables on a SQL Database. This is working ok, running the project, the dll is generated.

Now I need to include this dll in another project to be able to use these enums but I have to be sure that every time I run my project, the enum dll is up to date.

How can I run my enum dll project before
running the main project that contains the enum dll? is there any solution for that?

using System;
using System.Data.SqlClient;
using System.Reflection;
using System.Reflection.Emit;

namespace DynamicEnums
{
    class EnumCreator
    {
        static void Main(string[] args)
        {
            const string connectionString = 
                "Integrated Security=SSPI;Persist " +
                "Security Info=False;Initial Catalog=MyDB;Data Source=MyServer;" +
                "MultipleActiveResultSets=True";

            // Define Namespace name
            const string nameSpace = "EnumTypes";

            // Define Assembly name
            const string strAssemblyName = "MyEnums";

            // Table Suffix 
            const string tableSuffix = "TypeEnum";

            var mainQuery = string.Format("Select SCHEMA_NAME(schema_id) as [Schema], Name" +
                " from sys.tables where name like '%{0}'", tableSuffix); 

            // Get the current application domain for the current thread
            var currentDomain = AppDomain.CurrentDomain;

            // Create a dynamic assembly in the current application domain,
            // and allow it to be executed and saved to disk.
            var name = new AssemblyName(strAssemblyName);

            var assemblyBuilder =
                    currentDomain.DefineDynamicAssembly(name,
                            AssemblyBuilderAccess.RunAndSave);

            var moduleBuilder = 
                assemblyBuilder.DefineDynamicModule(name.Name, name.Name + ".dll");

            #region GetTheDataFromTheDatabase

            //Search for all Enum Lookup Tables
            using (var dbConn = new SqlConnection(connectionString))
            {
                using (var cmd = new SqlCommand())
                {
                    dbConn.Open();

                    cmd.Connection = dbConn;
                    cmd.CommandText = mainQuery;

                    SqlDataReader readerTables = cmd.ExecuteReader();

                    while (readerTables.Read())
                    {
                        using (var cmdEnum = new SqlCommand())
                        {
                            cmdEnum.Connection = dbConn;
                            cmdEnum.CommandText = string.Format("Select [{0}Id], [Name] from {1}.{0}",
                                readerTables["Name"],
                                readerTables["Schema"]);

                            SqlDataReader readerEnums = cmdEnum.ExecuteReader();

                            // Define a public enumeration and an underlying type of Integer
                            var myEnum = moduleBuilder.DefineEnum(
                                    string.Format("{0}.{1}", nameSpace, readerTables["Name"]),
                                    TypeAttributes.Public,
                                    typeof(int)
                            );

                            while (readerEnums.Read())
                            {
                                myEnum.DefineLiteral(readerEnums[1].ToString(),
                                       Convert.ToInt32(readerEnums[0].ToString()));       
                            }

                            // Create the enum
                            myEnum.CreateType();

                            readerEnums.Close();
                        }                        
                    }              
                    readerTables.Close();
                }

            } //eof using

            #endregion GetTheDataFromTheDatabase

            // save assembly
            assemblyBuilder.Save(name.Name + ".dll");
        }

    }
}
like image 428
rgx71 Avatar asked Apr 24 '26 11:04

rgx71


1 Answers

You could turn your dll-generating project into an executable, and set up a pre-build script that runs it. That should work, although you might have some issues with VS having a lock on the .dll you are trying to replace.

It might work better to have it generate and replace the source files that you compile into the Enum .dll rather than the .dll itself. Your solution compile would then build the Enum .dll while it was compiling the whole solution.

Here's a link to someone doing it (generating the code) with T4 templates: Creating Enums from Database Lookup Tables. I hope this helps.

like image 56
Ann L. Avatar answered Apr 27 '26 01:04

Ann L.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!