Skip to content

Instantly share code, notes, and snippets.

@Nisden
Created November 26, 2011 15:41
Show Gist options
  • Save Nisden/1395877 to your computer and use it in GitHub Desktop.
Save Nisden/1395877 to your computer and use it in GitHub Desktop.
public double calculate(string expr)
{
// Try to replace things with Math
string[] mathfunktions = this.mathfunktions().Select(x => x.Name).ToArray();
foreach (var item in mathfunktions)
{
if (expr.ToLower().Contains(item.ToLower()))
{
string exprlocal = expr;
int expstart = exprlocal.IndexOf(item.ToLower());
exprlocal = exprlocal.Substring(expstart, exprlocal.Length - expstart);
string exprexpression = item;
int expend = exprlocal.IndexOf(')');
if (expend != exprlocal.Length - 1)
{
exprlocal = exprlocal.Remove(expend + 1);
}
string replace = exprlocal;
exprlocal = exprlocal.Replace(exprexpression.ToLower(), string.Empty);
exprlocal = exprlocal.Substring(1, exprlocal.Length - 1);
exprlocal = exprlocal.Remove(exprlocal.Length - 1);
string insert = " + Math." + exprexpression + "(" + exprlocal + ") + ";
expr = expr.Replace(replace, insert);
if (expr.Length == insert.Length)
{
expr = expr.Replace(" + ", string.Empty);
}
}
}
// Compile and so on....
Microsoft.CSharp.CSharpCodeProvider cp = new Microsoft.CSharp.CSharpCodeProvider();
System.CodeDom.Compiler.CompilerParameters cpar = new System.CodeDom.Compiler.CompilerParameters();
cpar.GenerateInMemory = true;
cpar.GenerateExecutable = false;
cpar.ReferencedAssemblies.Add("system.dll");
cpar.ReferencedAssemblies.Add(Application.ExecutablePath);
string src = "using System;" +
"class myclass:AdvCalc.calc" +
"{" +
"public myclass(){}" +
"public override double calculate()" +
"{" +
"return " + expr + ";" +
"}" +
"}";
System.CodeDom.Compiler.CompilerResults cr = cp.CompileAssemblyFromSource(cpar, src);
calc myobj = null;
if (cr.Errors.Count == 0 && cr.CompiledAssembly != null)
{
Type ObjType = cr.CompiledAssembly.GetType("myclass");
try
{
if (ObjType != null)
{
myobj = (calc)Activator.CreateInstance(ObjType);
}
}
catch
{
// Error 0
MessageBox.Show("Could not calculate");
return 0;
}
// Get result
return myobj.calculate();
}
else
{
// Error 0
MessageBox.Show("Could not calculate");
return 0;
}
}
public System.Reflection.MethodInfo[] mathfunktions()
{
return typeof(Math).GetMethods().Where(x => x.GetParameters().Length == 1 && (x.GetParameters()[0].ParameterType == typeof(double) || x.GetParameters()[0].ParameterType == typeof(int))).ToArray();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment