Dynamic Code Integration with .NET System.CodeDom

If we are building some sort of script executor/runner or SQL code executor we may need to have some dynamic code along with static codes. Such as if we have an SQL script executor which executes SQL from reading SQL script from a file (which may be serialized or can be read as a normal file), we may need dynamic code or data along with static code or data. For example consider the following SQL.

[code lang=”sql” title=”Script”]
"SELECT userid from dbo.user WHERE registration_date = ‘2014-08-4′;"
[/code]

If we are running this script with our script executor on daily basis and we need to have “userid” of the users of current date what can we do? Consider the script goes directly to SQL query executor and there are some scenario we may need to change the script code as support task frequently.
.NET Code Document Object Model (CodeDOM) API or CodeDom compiler gives us ability to dynamically create / compile our code on run-time. and we can use .NET reflection to invoke methods on our compiled codes.
The following program is an example of upper scenario. We can have dynamic code on our script file and compiled it before sending to actual query executor. For example we can have following code

[code lang=”sql” title=”Script”]
"SELECT userid from dbo.user WHERE registration_date = \’"+DateTime.Now.ToString() +"\’;"
[/code]

The code is pretty much self explaining what it does.

[code lang=”csharp” title=”Program”]
using System.IO;
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;

class Program
{
public static string EvaluateSourceCode(string source)
{
string result = "";

//prepare script
string src = "using System;\r\n\r\n" +
"namespace DataDynaCode\r\n" +
"{\r\n" +
" public sealed class Dyna\r\n" +
" {\r\n" +
" public string GetCompiledResult()\r\n" +
" {\r\n" +
" return " + source + ";" +
" }\r\n" +
" }\r\n" +
"}\r\n";

//compiler params
CompilerParameters compilerParams = new CompilerParameters();
compilerParams.GenerateInMemory = true;
compilerParams.TreatWarningsAsErrors = true;
compilerParams.GenerateExecutable = false;
compilerParams.CompilerOptions = "/optimize";
compilerParams.ReferencedAssemblies.Add("System.dll");
compilerParams.ReferencedAssemblies.Add("mscorlib.dll");

//compile and store results
CSharpCodeProvider cSharpCodeProvider = new CSharpCodeProvider();
CompilerResults compilerResults = cSharpCodeProvider.CompileAssemblyFromSource(compilerParams, src);

//invoke method using reflection and get output
if (!compilerResults.Errors.HasErrors)
{
Assembly assembly = compilerResults.CompiledAssembly;
Type classType = assembly.GetType("DataDynaCode.Dyna");
object objectInstance = Activator.CreateInstance(classType);
result = (string)classType.InvokeMember("GetCompiledResult", BindingFlags.InvokeMethod, null, objectInstance, null);
}

if (string.IsNullOrEmpty(result))
{
result = source;
}

return result;
}

public static void Main()
{
string code = "\"Now time: \" + DateTime.Now.ToString()";
string result = Program.EvaluateSourceCode(code);
Console.WriteLine(result);
}
}
[/code]

Incoming search terms:

  • tushoroy com
  • www tuhroy com

Tushar Roy

Software Engineer (Backend engineer), Android Developer,

Leave a Reply

Your email address will not be published. Required fields are marked *


*