Click here to Skip to main content
15,886,199 members
Articles / Programming Languages / C#

A Command Line Calculator

Rate me:
Please Sign up or sign in to vote.
2.84/5 (23 votes)
24 Nov 2005CPOL4 min read 109.7K   2.8K   28  
A command line calculator using CodeDOM.
using System;
using System.Diagnostics;
namespace Calculate
{
	/// <summary>
	/// Summary description for ExpressionEvaluator.
	/// </summary>
	public class ExpressionCalculator
	{
		public ExpressionCalculator()
		{
			//
			// TODO: Add constructor logic here
			//
		}
		public static double Calculate(string expression)
		{
			Microsoft.CSharp.CSharpCodeProvider cp = new Microsoft.CSharp.CSharpCodeProvider();   
			System.CodeDom.Compiler.ICodeCompiler ic = cp.CreateCompiler();   
			System.CodeDom.Compiler.CompilerParameters cpar = new System.CodeDom.Compiler.CompilerParameters();   
			cpar.GenerateInMemory = true;   
			cpar.GenerateExecutable = false;   
			cpar.ReferencedAssemblies.Add("system.dll");   
			cpar.ReferencedAssemblies.Add(Process.GetCurrentProcess().MainModule.FileName);   
			MyClassBase myobj = null;
			string src = @"using System; 
                           class myclass:Calculate.MyClassBase {
								 private double %MT_VARIABLES%;
                                 public myclass()
                                 {
                                 }
                                 public override double eval()
                                 {
									return " + expression + @";
                                 }
                           }"; 
			string variables="ans=0";
			string []keys;
			keys=Variables.GetVariables().GetKeys();
			if(keys.Length>0)
				variables="";
			for(int i=0;i<keys.Length;i++)
			{
				variables=variables+keys[i]+"="+Convert.ToString(Variables.GetVariables()[keys[i]]);
				if(i<keys.Length-1)
					variables=variables+",";
			}
			src=src.Replace(@"%MT_VARIABLES%",variables);
			System.CodeDom.Compiler.CompilerResults cr = ic.CompileAssemblyFromSource(cpar,src);   
			foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
			{
				throw new Exception(ce.ErrorText);
			}
			if (cr.Errors.Count == 0 && cr.CompiledAssembly != null)   
			{    
				Type ObjType = cr.CompiledAssembly.GetType("myclass");    
				try    
				{     
					if (ObjType != null)     
					{      
						myobj = (MyClassBase)Activator.CreateInstance(ObjType);     
					}    
				}    
				catch (Exception ex)    
				{     
					throw ex;
				}    
				return myobj.eval();   
			}   
			else
			{
				throw new Exception("Failed to compile");
			}
		}
		public static bool IsCompiled(string source)
		{
			Microsoft.CSharp.CSharpCodeProvider cp = new Microsoft.CSharp.CSharpCodeProvider();   
			System.CodeDom.Compiler.ICodeCompiler ic = cp.CreateCompiler();   
			System.CodeDom.Compiler.CompilerParameters cpar = new System.CodeDom.Compiler.CompilerParameters();   
			cpar.GenerateInMemory = true;   
			cpar.GenerateExecutable = false;   
			cpar.ReferencedAssemblies.Add("system.dll");   
			System.CodeDom.Compiler.CompilerResults cr = ic.CompileAssemblyFromSource(cpar,source);   
			foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
			{
				return false;
			}
			if (cr.Errors.Count == 0 && cr.CompiledAssembly != null)   
			{    
				return true;
			}   
			else
			{
				return false;
			}
		}
	}

	
	public class MyClassBase 
	{  
		public MyClassBase()  
		{  
		}  
		public virtual double eval()  
		{   
			return 0.0;  
		} 
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) KAZ Software Limited
Bangladesh Bangladesh
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions