I had a requirement where user can create and store conditions in database
for eg. if(FB > 5000) then 100 else 200
it is working fine user can create the formula but my main main problem is executing that formula
so at runtime FB
gets replaced with specific value and proper string is generated
i.e. int a; if(6000 > 5000) {a= 100 }else {a= 200}
To execute the above method at runtime i have used CSharpCodeProvider
CSharpCodeProvider c = new CSharpCodeProvider();
ICodeCompiler icc = c.CreateCompiler();
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("system.dll");
cp.CompilerOptions = "/t:library";
//cp.CompilerOptions = "optimize";
cp.GenerateInMemory = true;
StringBuilder sb = new StringBuilder("");
sb.Append("using System;\n");
sb.Append("namespace CSCodeEvaler{ \n");
sb.Append("public class CSCodeEvaler{ \n");
sb.Append("public double EvalCode(){\n");
sb.Append(condition);
sb.Append("return cond1; \n");
sb.Append("} \n");
sb.Append("} \n");
sb.Append("}\n");
CompilerResults cr = icc.CompileAssemblyFromSource(cp, sb.ToString());
if (cr.Errors.Count > 0)
{
//Log Errors
return 0;
}
System.Reflection.Assembly assembly = cr.CompiledAssembly;
object o = assembly.CreateInstance("CSCodeEvaler.CSCodeEvaler");
Type t = o.GetType();
MethodInfo mi = t.GetMethod("EvalCode");
object s = mi.Invoke(o, null);
It is also working fine but my problem is it is taking too much time i.e performance is very slow, so is there any alternative to achieve the same ???