Navigation

Feed your aggregator (RSS 2.0)   Send mail to the author(s)

Recent Entries
Archives
<February 2012>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910


Categories
Blogroll
Login

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.


Copyright 2012 Manish Kumar Singh
 Saturday, May 09, 2009
Compile .NET code on the fly

In this section I would like to demonstrate how to compile a .NET code on the fly. The code has been written in C#. It contains a class "InlineParser" which does the main job. It mainly, defines the class, does in-memory compilation and exposes a method for the execution of an inner method defined in the class. It also supports a choice of language whether C# or VB.NET for compilation.

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Text;

    5 using Microsoft.CSharp;

    6 using Microsoft.VisualBasic;

    7 using System.CodeDom.Compiler;

    8 using System.Reflection;

    9 using System.Xml.Linq;

   10 

   11 namespace com.eforceglobal.crux.bre

   12 {

   13     internalclassInlineParser

   14     {

   15         string expression = string.Empty;

   16         string functionArguments = string.Empty;

   17         string language = "CSharp";

   18         XDocument paramList = null;

   19         object objBase = null;

   20 

   21         public InlineParser(string expr, string functionArgs, XDocument parameters, string lang)

   22         {

   23             expression = expr;

   24             functionArguments = functionArgs;

   25             paramList = parameters;

   26             language = lang;

   27         }

   28 

   29         publicbool init()

   30         {

   31             if(language.ToLower().Equals("csharp"))

   32                 return InitCSharp();

   33             else

   34                 return InitVB();

   35         }

   36 

   37         internalbool InitCSharp()

   38         {

   39             // Compile the expression in a class on the fly

   40             CSharpCodeProvider cp = newCSharpCodeProvider(

   41                 newDictionary<string, string>() { { "CompilerVersion", "v3.5" } } );

   42 

   43             //ICodeCompiler ic = cp.CreateCompiler();

   44             CompilerParameters cparam = newCompilerParameters();

   45             cparam.GenerateInMemory = true;

   46             cparam.GenerateExecutable = false;

   47 

   48 

   49             // Reference Assembly

   50             cparam.ReferencedAssemblies.Add( "system.dll" );

   51             cparam.ReferencedAssemblies.Add( "mscorlib.dll" );

   52             cparam.ReferencedAssemblies.Add( "System.Core.dll" );

   53             cparam.ReferencedAssemblies.Add( "System.Xml.dll" );

   54             cparam.ReferencedAssemblies.Add( "System.Xml.Linq.dll" );

   55 

   56 

   57             // Write your code

   58             StringBuilder sb = newStringBuilder();

   59             sb.Append( "using System;\n" );

   60             sb.Append( "using System.Collections;\n" );

   61             sb.Append( "using System.Collections.Generic;\n" );

   62             sb.Append( "using System.Text;\n" );

   63             sb.Append( "using System.Text.RegularExpressions;\n" );

   64             sb.Append( "using System.Reflection;\n" );

   65             sb.Append( "using System.Linq;\n" );

   66             sb.Append( "using System.Xml.Linq;\n" );

   67 

   68             sb.Append( "namespace com.eforceglobal.crux.bre {\n" );

   69             sb.Append( "public class EvalClass {\n" );

   70             sb.Append( "public EvalClass(){}\n" );

   71             sb.Append( "public object Evaluate(\n" );

   72             sb.Append( functionArguments ).Append( " ) {\n" );

   73             sb.Append( expression ).Append("\n");

   74             sb.Append( "}\n}\n}" );

   75 

   76             //Console.WriteLine( sb.ToString() );

   77 

   78             string code = sb.ToString();

   79             CompilerResults cres = cp.CompileAssemblyFromSource( cparam, code );

   80 

   81             // Compilation Unsuccessfull

   82             StringBuilder errors = newStringBuilder();

   83             foreach ( CompilerError cerr in cres.Errors )

   84                 errors.Append( cerr.ErrorText );

   85 

   86             if ( cres.Errors.Count > 0 )

   87                 thrownewException( errors.ToString() );

   88 

   89             // Compilation Successfull

   90             if ( cres.Errors.Count == 0 && cres.CompiledAssembly != null )

   91             {

   92                 Type ClsObj = cres.CompiledAssembly.GetType( "com.eforceglobal.crux.bre.EvalClass" );

   93                 try

   94                 {

   95                     if ( ClsObj != null )

   96                     {

   97                         objBase = Activator.CreateInstance( ClsObj );

   98                     }

   99                 }

  100                 catch ( Exception ex )

  101                 {

  102                     throw;

  103                 }

  104                 returntrue;

  105             }

  106             else

  107                 returnfalse;

  108         }

  109 

  110         internalbool InitVB()

  111         {

  112             // Compile the expression in a class on the fly

  113             VBCodeProvider vb = newVBCodeProvider(

  114                 newDictionary<string, string>() { { "CompilerVersion", "v3.5" } } );

  115 

  116             //ICodeCompiler ic = cp.CreateCompiler();

  117             CompilerParameters cparam = newCompilerParameters();

  118             cparam.GenerateInMemory = true;

  119             cparam.GenerateExecutable = false;

  120 

  121 

  122             // Reference Assembly

  123             cparam.ReferencedAssemblies.Add( "system.dll" );

  124             cparam.ReferencedAssemblies.Add( "mscorlib.dll" );

  125             cparam.ReferencedAssemblies.Add( "System.Core.dll" );

  126             cparam.ReferencedAssemblies.Add( "System.Xml.dll" );

  127             cparam.ReferencedAssemblies.Add( "System.Xml.Linq.dll" );

  128 

  129 

  130             // Write your code

  131             StringBuilder sb = newStringBuilder();

  132             sb.Append( "Imports System\n" );

  133             sb.Append( "Imports System.Collections\n" );

  134             sb.Append( "Imports System.Collections.Generic\n" );

  135             sb.Append( "Imports System.Text\n" );

  136             sb.Append( "Imports System.Text.RegularExpressions\n" );

  137             sb.Append( "Imports System.Reflection\n" );

  138             sb.Append( "Imports System.Linq\n" );

  139             sb.Append( "Imports System.Xml.Linq\n" );

  140 

  141             sb.Append( "Namespace com.eforceglobal.crux.bre \n" );

  142             sb.Append( "Public Class EvalClass \n" );

  143             sb.Append( "Public Function Evaluate ( " );

  144             sb.Append( functionArguments ).Append(" ) As Object\n");

  145             sb.Append( expression ).Append( "\n" );

  146             sb.Append( "End Function\n" );

  147             sb.Append( "End Class\n" );

  148             sb.Append( "End Namespace" );

  149 

  150             //Console.WriteLine( sb.ToString() );

  151 

  152             string code = sb.ToString();

  153             CompilerResults cres = vb.CompileAssemblyFromSource( cparam, code );

  154 

  155             // Compilation Unsuccessfull

  156             StringBuilder errors = newStringBuilder();

  157             foreach ( CompilerError cerr in cres.Errors )

  158                 errors.Append( cerr.ErrorText );

  159 

  160             if ( cres.Errors.Count > 0 )

  161                 thrownewException( errors.ToString() );

  162 

  163             // Compilation Successfull

  164             if ( cres.Errors.Count == 0 && cres.CompiledAssembly != null )

  165             {

  166                 Type ClsObj = cres.CompiledAssembly.GetType( "com.eforceglobal.crux.bre.EvalClass" );

  167                 try

  168                 {

  169                     if ( ClsObj != null )

  170                     {

  171                         objBase = Activator.CreateInstance( ClsObj );

  172                     }

  173                 }

  174                 catch ( Exception ex )

  175                 {

  176                     throw;

  177                 }

  178                 returntrue;

  179             }

  180             else

  181                 returnfalse;

  182         }

  183 

  184         publicstring Evaluate()

  185         {

  186             string result = string.Empty;

  187             Type type = objBase.GetType();

  188             MethodInfo mInfo = type.GetMethod( "Evaluate" );

  189 

  190             if ( mInfo != null )

  191             {

  192                 ParameterInfo[] pInfo = mInfo.GetParameters();

  193                 object[] arguments = null;

  194                 if(pInfo!=null) arguments = newobject[pInfo.Length];

  195                 if ( pInfo != null )

  196                 {

  197                     foreach(ParameterInfo p in pInfo )

  198                         if ( paramList.Element( "arguments" ).Elements( p.Name ) != null )

  199                         {

  200                             arguments[p.Position] = (paramList.Element( "arguments" )

  201                                 .Elements( p.Name ).Single().Value);

  202                         }

  203                     if ( pInfo.Length != arguments.Length )

  204                         thrownewArgumentException( "Insufficient parameters." );

  205                 }

  206 

  207                 result = mInfo.Invoke( objBase, arguments ).ToString();

  208             }

  209 

  210             return result;

  211         }

  212     }

  213 }

Notice that the class name of the class to be compiled is "EvalClass" and the inner method of the class is "Evaluate". Calling the "Evaluate()" method requires you to execute the following lines of code.

  1 var parser = newInlineParser(subExpression, funcArgs, Arguments.Document, lang);

  2 parser.init();

  3 retString = parser.Evaluate();

Manish


.Net
Saturday, May 09, 2009 6:21:03 AM (GMT Standard Time, UTC+00:00)  #  Comments [17] Trackback
Tracked by:
"http://www.google.com/search?q=wljhiihk" (http://www.google.com/search?q=wljhii... [Pingback]
"http://www.eatout.co.za/specials/specials_detail.asp?iID=401" (http://www.eatou... [Pingback]
"http://www.eatout.co.za/specials/specials_detail.asp?iID=431" (http://www.eatou... [Pingback]
"http://www.unioeste.br/servicos/centraleventos/lista_evento.asp?codvalue=715" (... [Pingback]
"http://www.unioeste.br/servicos/centraleventos/lista_evento.asp?codvalue=743" (... [Pingback]
"http://www.huntingtonbeachca.gov/residents/green_city/index_post.cfm?ID=293" (h... [Pingback]
"http://www.huntingtonbeachca.gov/residents/green_city/index_post.cfm?ID=295" (h... [Pingback]
"http://www.tj.to.gov.br/exibir_noticia_novo.asp?id=1876" (http://www.tj.to.gov.... [Pingback]
"http://www.tj.to.gov.br/exibir_noticia_novo.asp?id=1885" (http://www.tj.to.gov.... [Pingback]
"http://www.tj.to.gov.br/exibir_noticia_novo.asp?id=1907" (http://www.tj.to.gov.... [Pingback]
"http://www.tj.to.gov.br/exibir_noticia_novo.asp?id=1905" (http://www.tj.to.gov.... [Pingback]
"http://www.eppo.go.th/Thaienergynews/Energy_News/Articles/ArticleShowDetail.asp... [Pingback]
"http://www.eppo.go.th/Thaienergynews/Energy_News/Articles/ArticleShowDetail.asp... [Pingback]
"http://www.eppo.go.th/Thaienergynews/Energy_News/Articles/ArticleShowDetail.asp... [Pingback]
"http://www.compuware.com/d/press-release.asp?newsitemid=763496684" (http://www.... [Pingback]
"http://www.compuware.com/d/press-release.asp?newsitemid=992601082" (http://www.... [Pingback]
"http://www.ktzmico.com/en/newscompanynewsxr/xr-detail.aspx?xr_id=825939636" (ht... [Pingback]
"http://www.ktzmico.com/en/newscompanynewsxr/xr-detail.aspx?xr_id=537157525" (ht... [Pingback]
"http://www.google.com/search?q=zbfflfyo" (http://www.google.com/search?q=zbfflf... [Pingback]
"http://www.pharmabiz.com/brief/Comment.asp?articleid=495933218" (http://www.pha... [Pingback]
"http://www.lsmsa.edu/content.cfm?id=767" (http://www.lsmsa.edu/content.cfm?id=7... [Pingback]
"http://www.lsmsa.edu/content.cfm?id=823" (http://www.lsmsa.edu/content.cfm?id=8... [Pingback]
"http://www.lsmsa.edu/content.cfm?id=841" (http://www.lsmsa.edu/content.cfm?id=8... [Pingback]
"http://www.hurriyetusa.com/haber_detay.asp?id=25784" (http://www.hurriyetusa.co... [Pingback]
"http://www.irishabroad.com/yourroots/familynames/SurnameView.asp?id=1988" (http... [Pingback]
"http://www.torontozoo.com/ExploretheZoo/AnimalDetails.asp?AnimalId=771" (http:/... [Pingback]
"http://www.google.com/search?q=ongwobag" (http://www.google.com/search?q=ongwob... [Pingback]
"http://www.google.com/search?q=rgzslsld" (http://www.google.com/search?q=rgzsls... [Pingback]
"http://www.google.com/search?q=voswfqnc" (http://www.google.com/search?q=voswfq... [Pingback]
"http://www.campeggi.com/scheda_campeggio.asp?id=258874185" (http://www.campeggi... [Pingback]
"http://www.ciaobambino.com/profile.asp?id=2263" (http://www.ciaobambino.com/pro... [Pingback]
"http://www.buenasalud.com/lib/def_lookup.cfm?no=11319" (http://www.buenasalud.c... [Pingback]
"http://www.blackwebportal.com/yellow/myShop.cfm?ID=7113" (http://www.blackwebpo... [Pingback]
"http://www.blackwebportal.com/yellow/myShop.cfm?ID=7112" (http://www.blackwebpo... [Pingback]
"http://www.blackwebportal.com/yellow/myShop.cfm?ID=7102" (http://www.blackwebpo... [Pingback]
"http://www.google.com/search?q=rpgfzzlm" (http://www.google.com/search?q=rpgfzz... [Pingback]
"http://www.mutualfundsindia.com/prudent/mf/fund_facts_rpt.asp?scheme=cxcilauy" ... [Pingback]
"http://www.mutualfundsindia.com/prudent/mf/fund_facts_rpt.asp?scheme=ubbpxabo" ... [Pingback]
"http://www.cdispatch.com/yournews/article.asp?aid=294" (http://www.cdispatch.co... [Pingback]
"http://www.mutualfundsindia.com/prudent/mf/fund_facts_rpt.asp?scheme=rlgtmmjq" ... [Pingback]
"http://www.phrae.mju.ac.th/media/mjutv/?media_id=113" (http://www.phrae.mju.ac.... [Pingback]
"http://www.wpt.org/garden/recipes/recipe2.cfm?recipe_id=392416981" (http://www.... [Pingback]
"http://www.wpt.org/garden/recipes/recipe2.cfm?recipe_id=809411326" (http://www.... [Pingback]
"http://www.wpt.org/garden/recipes/recipe2.cfm?recipe_id=436046956" (http://www.... [Pingback]
"http://www.cdispatch.com/yournews/article.asp?aid=394" (http://www.cdispatch.co... [Pingback]
"http://www.google.com/search?q=fjfzdfkw" (http://www.google.com/search?q=fjfzdf... [Pingback]
"http://www.google.com/search?q=cvngeewn" (http://www.google.com/search?q=cvngee... [Pingback]
"http://www.gods-kingdom-ministries.org/weblog/WebPosting.cfm?LogID=177775870" (... [Pingback]
"http://www.observatoriodoalgarve.com/cna/opinioes_ver.asp?opiniao=848" (http://... [Pingback]
"http://wine.appellationamerica.com/classifieds.aspx?cat=436021201" (http://wine... [Pingback]
"http://www.observatoriodoalgarve.com/cna/opinioes_ver.asp?opiniao=866" (http://... [Pingback]
"http://wine.appellationamerica.com/classifieds.aspx?cat=481840308" (http://wine... [Pingback]
"http://www.observatoriodoalgarve.com/cna/opinioes_ver.asp?opiniao=842" (http://... [Pingback]
"http://www.cashluna.org/templates20/print.cfm?id=2395" (http://www.cashluna.org... [Pingback]
"http://www.cashluna.org/templates20/print.cfm?id=2428" (http://www.cashluna.org... [Pingback]
"http://www.google.com/search?q=odhdoitc" (http://www.google.com/search?q=odhdoi... [Pingback]
Wednesday, June 01, 2011 8:57:21 AM (GMT Standard Time, UTC+00:00)
Versace Neckties
http://www.faters.com/neckties-versace-neckties-c-953_960.html

Nike ACG Boots
http://www.faters.com/nike-boots-c-1003.html

Nike Air Force Ones
http://www.faters.com/nike-force-ones-c-463.html

Air Force One High
http://www.faters.com/nike-force-ones-force-high-c-463_466.html

Air Force Ones Low
http://www.faters.com/nike-force-ones-force-ones-c-463_470.html

New Air Force Ones
http://www.faters.com/nike-force-ones-force-ones-c-463_874.html

Nike Court Force
http://www.faters.com/nike-force-ones-nike-court-force-c-463_1462.html

Woman Air Force Ones
http://www.faters.com/nike-force-ones-woman-force-ones-c-463_469.html

Nike Air Max
http://www.faters.com/nike-air-max-c-129.html

Nike Air Max TN8
http://www.faters.com/nike-nike-c-129_700.html

Air Max 180
http://www.faters.com/nike-air-max-air-max-180-c-129_141.html

Air Max 2011 Shoes
http://www.faters.com/nike-2011-shoes-c-129_1315.html

Air Max 87
http://www.faters.com/nike-air-max-air-max-87-c-129_133.html

Air Max 91
http://www.faters.com/nike-air-max-air-max-91-c-129_137.html

Air Max 95
http://www.faters.com/nike-air-max-air-max-95-c-129_138.html

Air Max Ltd
http://www.faters.com/nike-air-max-air-max-ltd-c-129_143.html

Air Max Tn
http://www.faters.com/nike-air-max-air-max-tn-c-129_142.html

Air Stab 89
http://www.faters.com/nike-stab-c-129_134.html

Nike Air Max 2009
http://www.faters.com/nike-nike-2009-c-129_1061.html

Nike Air Max 2010
http://www.faters.com/nike-nike-2010-c-129_1177.html

Nike Air Max 24/7
http://www.faters.com/nike-nike-c-129_1207.html

Nike Air Max 90
http://www.faters.com/nike-nike-c-129_1062.html

Nike Air Max 90 Boots
http://www.faters.com/nike-nike-boots-c-129_1068.html

Nike Air Max 92 Shoes
http://www.faters.com/nike-nike-shoes-c-129_762.html

Nike Air Max Classic BW
http://www.faters.com/nike-nike-classic-c-129_1063.html

Nike Air Max LeBron VIII
http://www.faters.com/nike-nike-lebron-viii-c-129_1336.html

Nike Air Max NoMo
http://www.faters.com/nike-nike-nomo-c-129_1261.html

Nike Air Max Trainer
http://www.faters.com/nike-nike-trainer-c-129_1365.html

Nike Air Max Uptempo
http://www.faters.com/nike-nike-uptempo-c-129_1455.html

Nike Air Max Uptempo 97
http://www.faters.com/nike-nike-uptempo-c-129_1339.html

Nike Air Max Women Shoes
http://www.faters.com/nike-nike-women-shoes-c-129_943.html

Nike Air Skyline
http://www.faters.com/nike-nike-skyline-c-129_1150.html

Nike Air Structure Triax 91
http://www.faters.com/nike-nike-structure-triax-c-129_1064.html

Nike Air Zenyth
http://www.faters.com/nike-nike-zenyth-c-129_1065.html

Nike Lunar Max Shoes
http://www.faters.com/nike-nike-lunar-shoes-c-129_1436.html

Nike Air Presto Running Shoes
http://www.faters.com/nike-presto-running-shoes-c-1205.html

Nike Baseball Shoes
http://www.faters.com/nike-baseball-shoes-c-1343.html

Nike Blazer Shoes
http://www.faters.com/nike-blazer-shoes-c-892.html

Nike Cortez Shoes
http://www.faters.com/nike-cortez-shoes-c-1147.html

Nike Dunk & SB
http://www.faters.com/nike-dunk-c-36.html
Thursday, June 02, 2011 8:26:52 AM (GMT Standard Time, UTC+00:00)
http://www.uscheapnfljerseys.com/
http://www.uscheapnfljerseys.com/cheap-nfl-jerseys
http://www.uscheapnfljerseys.com/cheap-nhl-jerseys
http://www.uscheapnfljerseys.com/cheap-nba-jerseys
Friday, July 15, 2011 9:50:01 PM (GMT Standard Time, UTC+00:00)
I strictly recommend not to hold off until you get big sum of cash to order goods! You should just take the business loans or consolidation loans and feel yourself free
Tuesday, August 23, 2011 10:08:05 PM (GMT Standard Time, UTC+00:00)
I opine that no thing can be as safe as custom papers writing corporation. Futhermore, you should not bother about your confidential information when buy custom made essays. Your future career depends on you only.
Friday, August 26, 2011 3:11:28 PM (GMT Standard Time, UTC+00:00)
In students' community cannot exist without custom writing services. Students are not indolent they are lack of time.
Saturday, August 27, 2011 11:49:16 PM (GMT Standard Time, UTC+00:00)
Are you willing to be the best among your group mates? Professionally written academic papers should surely get it. Hence, don't wait longer and utilize the help writing essay company to order high quality stuff at.
Thursday, September 01, 2011 6:44:39 AM (GMT Standard Time, UTC+00:00)
I do not know if you believe me, thus, I would appreciate your good enough releases referring to this topic. Before this I used the assistance of Freelance writing job service.
Sunday, September 04, 2011 3:36:53 PM (GMT Standard Time, UTC+00:00)
Thank you a lot for the best article referring to this good topic! If students are willing to buy custom essay papers and custom essay search for trustworthy essay writing services. That’s the very good way to academic success!
Sunday, September 04, 2011 3:54:22 PM (GMT Standard Time, UTC+00:00)
Good enough chapter just about this good post! I guess, that’s really worth to buy essays to get a result!
Tuesday, September 06, 2011 5:12:40 AM (GMT Standard Time, UTC+00:00)
I apprize your fact about this post. I was willing let you know that I haven’t detect a kind of professional dissertation writer before this moment. Have you a chance accomplish the very correctly finished thesis and doctoral thesis?
Tuesday, September 06, 2011 5:38:44 AM (GMT Standard Time, UTC+00:00)
To know more about this good post, people should buy custom essay papers at the research paper writing service.
Monday, September 12, 2011 4:54:22 PM (GMT Standard Time, UTC+00:00)
Even if you didn't attempt to use the RSS submissions options, you should visit rss directory submission service. That can be the wisest way of search engine optimization!
Monday, September 26, 2011 1:14:12 PM (GMT Standard Time, UTC+00:00)
cheap ugg boots uk,ugg boots sale uk,cheap uggs shop,<strong>cheap ugg boots uk</strong>,<strong>UGG Bailey Button</strong>,<strong>ugg boots sale uk</strong>,<strong>UGG Classic Cardy</strong>,<strong>UGG Classic Mini</strong>,<strong>ugg boots sale</strong>,<strong>UGG Classic Short</strong>,<strong>UGG Classic Tall</strong>,<strong>UGG Metallic Short</strong>,<strong>cheap ugg boots</strong>,<strong>UGG Metallic Tall</strong>,<strong>UGG Ultra Short</strong>,<strong>UGG Ultra Tall</strong>,<strong>cheap uggs</strong>,<strong>UGG Bailey Button Triplet</strong>,<strong>UGG Classic Short Fancy</strong>,<strong>UGG Classic Tall Fancy</strong>,<strong>UGG Nightfall</strong>,<strong>ghd hair straightener</strong>,<strong>ghd australia</strong>,<strong>ghd straighteners</strong>,<strong>ghd hair straightener australia</strong>,<strong>ghd outlet</strong>,
Monday, November 07, 2011 3:34:05 PM (GMT Standard Time, UTC+00:00)
i will follow your advice, it looks helpful essay
alex
Monday, November 07, 2011 3:37:14 PM (GMT Standard Time, UTC+00:00)
i was looking for this info just other day, this is great that i found this website custom essay
alex
Monday, November 14, 2011 10:36:55 PM (GMT Standard Time, UTC+00:00)
bgt hgnhj gji
Saturday, January 28, 2012 1:28:06 AM (GMT Standard Time, UTC+00:00)
Buildings are not very cheap and not every person is able to buy it. But, mortgage loans are invented to help people in such situations.
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview