Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » Windows Forms C# » CodeDom Calculator - Evaluating C# Math Expressions dynamically

CodeDom Calculator - Evaluating C# Math Expressions dynamically

This article describes how to use CodeDom and Reflection to Create a Calculator that can evaluate simple and complex math expressions on the fly.

Author Rank :
Page Views : 109569
Downloads : 3796
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
CodeDomCalculator.zip
 
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
Mindcracker MVP Summit 2012
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Introduction

CodeDom and Reflection give you the ability to dynamically build C# Code into a string, compile it, and run it all inside your program. This very powerful feature in .NET allows us to create the CodeDom calculator, a calculator that evaluates expressions (and even lines of C# code) inside a Windows Form. We primarily use the System.Math class to do the calculations, but we've coded the CodeDom calculator in such a way, so that we don't need to apply the Math. prefix before our functions. We'll show you in a minute how this is done.  

 

Figure 1 - CodeDom Calculator in Action 

Usage

The CodeDom Calculator can be used in one of two ways:  a)  just enter some math expression you want to evaluate using C# Syntax.  b) write a block of code in C# to evaluate something more complex. The first method (method a)  only requires you to type in the math expression as shown in figure 2.

Figure 2 - Evaluating a long function in the CodeDom Calculator

In method b, we do something a bit different. At the top line you place the word answer terminated with a semicolon. After that you write any C# code you wish.  At the end of your code fragment, remember to assign the final answer to the variable answer. You may still leave off the Math class prefix when writing this code.  Figure 3 is an example of summing numbers from 1 to 10 using C# in CodDom.

Figure 3 - Summing numbers from 1 to 10 using code Dom

Creating and Running the Calculator Class

The three steps to evaluating the expression are:  1) Create  C# code  around the function using CodeDom 2) compile the code into an assembly using the CodeDom Compiler 3) Create an instance of the Calculator class 4) Call the Calculate method on the Calculator Class to obtain the answer. Figure 2 shows the CodeDom class we wish to generate. The Calculate method will contain the expression we typed into our CodeDom calculator

Figure 4 - Calculator class in UML Reverse Engineered using WithClass

The assembly that is actually generated by CodeDom for figure 3 is shown in the listing below. We will talk more about how we generated this class with all the cool methods in CodeDom in the next section, but as you can see, our evaluation code was just slapped right into the Calculate method. The reason we place answer; at the top line is so we can just force a dummy line at the top of the Calculate method for large blocks of code (the dummy line being Answer = answer;)  If we had just put in a simple evaluation expression, such as 1 + 1, this same line becomes a Answer = 1 + 1; inside our code.

Listing 1 - CodeDom generated code for the Calculator

 namespace ExpressionEvaluator
 {
    using System;
    using System.Windows.Forms;
    public class Calculator
    {       
        private double answer;     
        /// Default Constructor for class
        public Calculator()
        {
           
//TODO: implement default constructor
        }
        
        // The Answer property is the returned result
        public virtual double Answer
        {
            get

              
{
                return this.answer;
               }

            set
              {
                this.answer = value;
              }
        }
        /// Calculate an expression
        public virtual double Calculate()
        {
          Answer = answer;
          for (int i = 1; i <= 10; i++)
              answer = answer + i;
            return this.Answer;
        }
    }
}

The Code

Upon clicking the Calculate button, the code is generated, compiled and run. Listing 2 shows the calculate event handler that executes all of these steps in sequence. Although the details aren't shown here, all of the steps are contained in the methods: BuildClass, CompileAssembly, and RunCode.

Listing 2 - Event Handler for calculating the Math Expression

            private void btnCalculate_Click(object sender, System.EventArgs e)
            {
           
// Blank out result fields and compile result fields
            InitializeFields(); 
            // change evaluation string to pick up Math class members
           string expression = RefineEvaluationString(txtCalculate.Text);
            // build the class using codedom
            BuildClass(expression);
             // compile the class into an in-memory assembly.
           
// if it doesn't compile, show errors in the window
            CompilerResults results = CompileAssembly();
            // write out the source code for debugging purposes
            Console.WriteLine("...........................\r\n");
            Console.WriteLine(_source.ToString());
 
            // if the code compiled okay,
           
// run the code using the new assembly (which is inside the results)
            if (results != null && results.CompiledAssembly != null)
            {
               
// run the evaluation function
                RunCode(results);
            }
        }

So what does a CodeDom generation look like?  If you look at the classes  in CodeDom carefully, they almost look like a language grammar break down.  Each constructor uses another CodeDom object to construct it and builds a composite of grammar snippets. Table 1 shows the classes we use in this project to construct our assembly and their individual purpose.

CodeDom Object Purpose
CSharpCodeProvider Provider for generating C# Code
CodeNamespace Class for constructing namespace generation
CodeNamespaceImport Generates using statements
CodeTypeDeclaration Generates class structure
CodeConstructor Generates constructor
CodeTypeReference Generates reference for a type
CodeCommentStatement Generates a C# Comment
CodeAssignStatement Generates assignment statement
CodeFieldReferenceExpression Generates a field reference
CodeThisReferenceExpression Generates a this pointer
CodeSnippetExpression Generates any literal string you specify into the code (used to place our evaluation string)
CodeMemberMethod Generates a new method

Table 1 - CodeDom classes used to build the Calculator

Let's look at our CodeDom method for generating code shown in listing 3. As you can see its easier to get your head around code generation with CodeDom, because it breaks down the generation into simple pieces. First we create the generator and in this case we are generating C#, so we create a C# Generator. Then we begin to create and assemble the pieces. First we create the namespace, then we add to it the different import libraries we want to include. Next we create the class. We add to the class a constructor, a property and a method.  In the method we add statements for the method. Inside these statements, we stick the expression that we typed into the text box to evaluate. The expression we typed in is used in the CodeSnippetExpression constructor so we can generate the code directly from our evaluation string. The expression also uses the constructor of the CodeAssignStatement so we can assign it to the Answer property. When we are finished assembling the composite pieces of the CodeDom hierarchy, we just call GenerateCodeFromNamespace with  the CodeDom generator on our assembled namespace. This gets streamed out to our StringWriter and assigned internally to a StringBuilder class where we can extract the whole assembly code from a string.

Listing 3 - Building the Calculator class using CodeDom classes

              /// <summary>
             ///
Main driving routine for building a class
            /// </summary>
        void BuildClass(string expression)
         {
           
// need a string to put the code into
              _source = new StringBuilder();
              StringWriter sw = new StringWriter(_source);
           
//Declare your provider and generator
              CSharpCodeProvider codeProvider = new CSharpCodeProvider();
              ICodeGenerator generator = codeProvider.CreateGenerator(sw);                 
              CodeGeneratorOptions codeOpts = new CodeGeneratorOptions();
              CodeNamespace myNamespace = new CodeNamespace("ExpressionEvaluator");
              myNamespace.Imports.Add(new CodeNamespaceImport("System"));
              myNamespace.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
 
             //Build the class declaration and member variables               
             CodeTypeDeclaration classDeclaration = new CodeTypeDeclaration();
                  classDeclaration.IsClass = true;
                  classDeclaration.Name = "Calculator";
                  classDeclaration.Attributes = MemberAttributes.Public;
                  classDeclaration.Members.Add(FieldVariable("answer", typeof(double), MemberAttributes.Private));
                  //default constructor
                  CodeConstructor defaultConstructor = new CodeConstructor();
                  defaultConstructor.Attributes = MemberAttributes.Public;
                  defaultConstructor.Comments.Add(new CodeCommentStatement("Default Constructor for class", true));
                  defaultConstructor.Statements.Add(new CodeSnippetStatement("//TODO: implement default constructor"));
                  classDeclaration.Members.Add(defaultConstructor);
 
                  //home brewed method that uses CodeDom to make a property
                  classDeclaration.Members.Add(this.MakeProperty("Answer", "answer", typeof(double)));
                   //Our Calculate Method
                  CodeMemberMethod myMethod = new CodeMemberMethod();
                  myMethod.Name = "Calculate";
                  myMethod.ReturnType = new CodeTypeReference(typeof(double));
                  myMethod.Comments.Add(new CodeCommentStatement("Calculate an expression", true));
                  myMethod.Attributes = MemberAttributes.Public;
                  myMethod.Statements.Add(new CodeAssignStatement(new CodeSnippetExpression("Answer"),

                        new
CodeSnippetExpression(expression)));
//            Include the generation below if you want your answer to pop up in a message box
//            myMethod.Statements.Add(new CodeSnippetExpression("MessageBox.Show(String.Format(\"Answer = {0}\", Answer))"));
            //  return answer
            myMethod.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(
                  new
CodeThisReferenceExpression(), "Answer")));
                  classDeclaration.Members.Add(myMethod);
                  //write code
                  myNamespace.Types.Add(classDeclaration);
                  generator.GenerateCodeFromNamespace(myNamespace, sw, codeOpts);                  
                 
// cleanup
                  sw.Flush();
                  sw.Close();
            }

Compiling

Compiling is broken down into 3 pieces: Creating the CodeDom compiler, creating the compile parameters, and compiling the code into the assembly as shown in listing 4.

Listing 4  - Compiling the Assembly with CodeDom

      /// <summary>
        ///
Compiles the c# into an assembly if there are no syntax errors
        ///
</summary>
        /// <returns></returns>
        private CompilerResults CompileAssembly()
        {
           
// create a compiler
            ICodeCompiler compiler = CreateCompiler();
           
// get all the compiler parameters
            CompilerParameters parms = CreateCompilerParameters();
           
// compile the code into an assembly
            CompilerResults results = CompileCode(compiler, parms, _source.ToString());
            return results;
        }

The CreateCompiler code simply constructs a C# CodeDom provider object and creates a compiler object from it.

Listing 5 - Creating the C# Compiler Object

ICodeCompiler CreateCompiler()
        {
           
//Create an instance of the C# compiler  
            CodeDomProvider codeProvider = null;
            codeProvider = new CSharpCodeProvider();
           ICodeCompiler compiler = codeProvider.CreateCompiler();
            return compiler;
        }

We also need to put together compiler parameters as shown in listing 6. Since we are generating an in-memory dll class library, we need to set the appropriate compiler options to make this happen. Also we can use the parameters to add any reference libraries we want to bring into the picture (namely the System library which contains the System.Math class).

Listing 6 - Creating parameters for the compiler

         /// <summary>
        /// Creawte parameters for compiling
        /// </summary>
        /// <returns></returns>
        CompilerParameters  CreateCompilerParameters()
        {
           
//add compiler parameters and assembly references
            CompilerParameters compilerParams = new CompilerParameters();
            compilerParams.CompilerOptions = "/target:library /optimize";
            compilerParams.GenerateExecutable = false;
            compilerParams.GenerateInMemory = true;
            compilerParams.IncludeDebugInformation = false;
            compilerParams.ReferencedAssemblies.Add("mscorlib.dll");
            compilerParams.ReferencedAssemblies.Add("System.dll");
            compilerParams.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            return compilerParams;
        }

Finally we need to compile are code. This is accomplished with the method  CompileAssemblyFromSource as shown in listing 7. This method takes the parameters set in listing 5 and the source code of the assembly as a string and compiles the code into an assembly. A reference to the assembly will be assigned in the Compiler results. If there are any errors in the compilation, we write them out to the bottom text box, and set the compiler results to null so we know not to try and run the assembly.

Listing 7 - Compiling the Generated Code into an Assembly using the Compiler Parameters

        private CompilerResults CompileCode(ICodeCompiler compiler, CompilerParameters parms, string source)
        {
                        //actually compile the code
            CompilerResults results = compiler.CompileAssemblyFromSource(parms, source); 
            //Do we have any compiler errors?
 
          if (results.Errors.Count > 0)
            {
              foreach (CompilerError error in results.Errors)
                 WriteLine("Compile Error:"+error.ErrorText);
                return null;
            }   
            return results;
        }

Running the Code

Assuming there are no errors after compiling, we can run the assembly. Running the assembly is not accomplished through CodeDom, but rather through Reflection. Reflection allows us to create a Calculator object from our newly created in-memory assembly and run the Calculate method contained within. Listing 8 shows how we run the Calculate method. First we get a reference to the executingAssembly from our results. Then we call CreateInstance on the newly created Calculator class to construct an instance of the class. From our assembly we loop through each class contained within the assembly (in this case only one class, Calculator) and get the class definition. Then we loop through each member in the class and look for the Calculate method.  Once we've obtained the Calculate method, we simply call Invoke on the Calculate method through the object created in CreateInstance. This will execute Calculate on our CodeDom generated assembly and return a resulting double value. The answer is then placed in the result text box.

Listing 8 - Running the Calculate method of the generated Assembly through Reflection

        private void RunCode(CompilerResults results)
        {
              Assembly executingAssembly = results.CompiledAssembly;
               try
                  {
                    //can't call the entry method if the assembly is null
   
                if (executingAssembly != null)
                     {
                       object assemblyInstance = executingAssembly.CreateInstance("ExpressionEvaluator.Calculator");
                      //Use reflection to call the static Main function       
                    
Module[] modules = executingAssembly.GetModules(false);
                      Type[] types = modules[0].GetTypes(); 
                              //loop through each class and each method that was defined
                             //  and look for the first occurrence of the Calculate method
                       foreach (Type type in types)
                         {
                              MethodInfo[] mis = type.GetMethods();
                              foreach (MethodInfo mi in mis)
                               {
                                  if (mi.Name == "Calculate")
                                  {
                                     // execute the Calculate method, and retrieve the answer
                                     object result = mi.Invoke(assemblyInstance, null);
                                     // place the answer on the win form in the result text box
                                     txtResult.Text =  result.ToString();
                                  }
                               }
                          }
                     }
                  }
                  catch (Exception ex)
                  {
                        Console.WriteLine("Error:  An exception occurred while executing the script", ex);                
                  }
        }

Making the Input Compileable

Once of the nice things about accepting code dynamically while the program is running, is that you can decide what is acceptable input before compiling, and then tweak the code input so that it will compile. Another words, the input doesn't initially have to be C#, it just needs to be C# at the point we need to compile it. We decided that the CodeDom calculator would be easier to use if the person typing in the expression didn't have to type the prefix Math before every math function in the System.Math library. By pre-parsing the entered evaluation string, and inserting the Math prefix anywhere it is needed (before compiling), We can make the slightly easier evaluation expression compileable. Also, we felt that the user shouldn't have to worry about case when using the math library, so we handle this situation as well. First we use reflection to create a map of all members of the Math library. Then we use regular expressions to match all words contained in our evaluation strings and see if any of these map to members of the math library. If they do, we append the Math prefix to them before we compile. Listing 9 shows how we can create a map of all members of the Math class through reflection.

Listing 9 - Gathering Members of the Math class through reflection

        ArrayList _mathMembers = new ArrayList();
        Hashtable _mathMembersMap = new Hashtable(); 
        void GetMathMemberNames()
        {
           
// get a reflected assembly of the System assembly
            Assembly systemAssembly = Assembly.GetAssembly(typeof(System.Math));
            try
            {
               
//cant call the entry method if the assembly is null
                if (systemAssembly != null)
                {
                    //Use reflection to get a reference to the Math class 
                    Module[] modules = systemAssembly.GetModules(false);
                    Type[] types = modules[0].GetTypes();
                     //loop through each class that was defined and look for the first occurrance of the Math class
                    foreach (Type type in types)
                    {
                        if (type.Name == "Math")
                        {
                            // get all of the members of the math class and map them to the same member
                            // name in uppercase
                            MemberInfo[] mis = type.GetMembers();
                            foreach (MemberInfo mi in mis)
                            {
                                _mathMembers.Add(mi.Name);
                                _mathMembersMap[mi.Name.ToUpper()] = mi.Name;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error:  An exception occurred while executing the script", ex);
            }
        }

Listing 10 shows how we use the map of the Math members to determine where we should place the Math prefix in our code to make it compileable. By using the regular expression class, we can find all the alphabetic words in our evaluation expression. We can then check all those words against the math member map. Any word that is the same name as  a System.Math member will be replaced with the Math prefix and the member name contained in the map. Because the math member map key is upper case and the value in the math member is the proper case, the person typing the evaluation string need not worry about case when typing. Another words, no matter what case the user types in, the evaluation words will be replaced with the proper case previously read in through Reflection of the System.Math library.

Listing 10 - Tweaking the evaluation expression by adding the static Math class prefix

        /// <summary>
        ///
Need to change eval string to use .NET Math library
        ///
</summary>
        /// <param name="eval">evaluation expression
</param>
        ///
<returns></returns>
        string RefineEvaluationString(string eval)
        {
            // look for regular expressions with only letters
            Regex regularExpression = new Regex("[a-zA-Z_]+");
            // track all functions and constants in the evaluation expression we already replaced
            ArrayList replacelist = new ArrayList();
            // find all alpha words inside the evaluation function that are possible functions
            MatchCollection matches = regularExpression.Matches(eval);
            foreach (Match m in matches)
            {
               
// if the word is found in the math member map, add a Math prefix to it
                bool isContainedInMathLibrary = _mathMembersMap[m.Value.ToUpper()] != null;
                if (replacelist.Contains(m.Value) == false && isContainedInMathLibrary)
                {
                    eval = eval.Replace(m.Value, "Math." + _mathMembersMap[m.Value.ToUpper()]);
                }
                // we matched it already, so don't allow us to replace it again
                replacelist.Add(m.Value);
            }
            // return the modified evaluation string
            return eval;
        }

Conclusion

CodeDom opens up a world of possible dynamic coding that we can conjure on the fly. Code that writes itself may not always bring to mind stories only found in science fiction. Also there are other practical uses of dynamic code generation such as Aspect Oriented Programming, dynamic state machines, and powerful script engines. I think we will see many more uses for this potent technique. In the meantime, keep yours eyes open for the next generation of the .NET framework while coding in C#.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 Article Extensions
Contents added by Edward Zilberman on Jun 08, 2009
Download File: codeCalculator_EZ.zip
Please find the downlodable code in attachment.
Contents added by Edward Zilberman on Jun 08, 2009

Functionality presented in this article ( "...a calculator that evaluates expressions (and even lines of C# code) inside a Windows Form. ) may be extended to evaluate not only the numerical expressions, but also logical ( boolean ) and string expressions.

Code belove represents the modified fragment of original code

 

void BuildClass(string expression)

{

// need a string to put the code into

_source = new StringBuilder();

StringWriter sw = new StringWriter(_source);

//Declare your provider and generator

CSharpCodeProvider codeProvider = new CSharpCodeProvider();

ICodeGenerator generator = codeProvider.CreateGenerator(sw);

CodeGeneratorOptions codeOpts = new CodeGeneratorOptions();

CodeNamespace myNamespace = new CodeNamespace("ExpressionEvaluator");

myNamespace.Imports.Add(new CodeNamespaceImport("System"));

myNamespace.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));

//Build the class declaration and member variables

CodeTypeDeclaration classDeclaration = new CodeTypeDeclaration();

classDeclaration.IsClass = true;

classDeclaration.Name = "Calculator";

classDeclaration.Attributes = MemberAttributes.Public;

classDeclaration.Members.Add(FieldVariable("answer", type of(string), MemberAttributes.Private));

//default constructor

CodeConstructor defaultConstructor = new CodeConstructor();

defaultConstructor.Attributes = MemberAttributes.Public;

defaultConstructor.Comments.Add(new CodeCommentStatement("Default Constructor for class", true));

defaultConstructor.Statements.Add(new CodeSnippetStatement("//TODO: implement default constructor"));

classDeclaration.Members.Add(defaultConstructor);

//property

classDeclaration.Members.Add(this.MakeProperty("Answer", "answer", typeof(string)));

//Our Calculate Method

CodeMemberMethod myMethod = new CodeMemberMethod();

myMethod.Name = "Calculate";

myMethod.ReturnType = new CodeTypeReference(typeof(string));

myMethod.Comments.Add(new CodeCommentStatement("Calculate an expression", true));

myMethod.Attributes = MemberAttributes.Public;

myMethod.Statements.Add(new CodeAssignStatement(new CodeSnippetExpression("Object obj"), new CodeSnippetExpression(expression)));

myMethod.Statements.Add(new CodeAssignStatement(new CodeSnippetExpression("Answer"), new CodeSnippetExpression("obj.ToString()")));

myMethod.Statements.Add(

new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "Answer")));

classDeclaration.Members.Add(myMethod);

//write code

myNamespace.Types.Add(classDeclaration);

generator.GenerateCodeFromNamespace(myNamespace, sw, codeOpts);

sw.Flush();

sw.Close();

}


You can notice that generated code manipulates  "Object" instead of "double" and converts the "object" to "string".
See the example of generated code belove.

 

namespace ExpressionEvaluator {

using System;

using System.Windows.Forms;

public class Calculator {

private string answer;

/// Default Constructor for class

public Calculator() {

//TODO: implement default constructor

}

// The Answer property is the returned result

public virtual string Answer {

get {

return this.answer;

}

set {

this.answer = value;

}

}

/// Calculate an expression

public virtual string Calculate() {

Object obj = "a" + "b";

Answer = obj.ToString();

return this.Answer;

}

}

}


This litle change generalizes the type of evaluated expression and allows to evaluate numerical, boolean and string expresions ( and combinations ).

Please see the xamples below:
example_boolean.bmp
example_string.bmp

Edward Ziberman
ezilberm@yahoo.com
Tel:(262)650-8413



 [Top] Rate this article
 
 About the author
 
Mike Gold

Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. Mike is a Microsoft MVP and founding member of C# Corner. He has a BSEE and MEng EE from Cornell University and has consulted for Chase Manhattan Bank, JP Morgan, Merrill Lynch, and Charles Schwab. Currently he is a senior developer at Finisar Corp. He has been involved in several .NET book projects, and is currently working on a book for using .NET with embedded systems.

He can be reached at mike@c-sharpcorner.com

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Mindcracker MVP Summit 2012
Become a Sponsor
 Comments
InitializeFields(); FieldVariable, MakeProperty by Heike On July 23, 2007
What is done in the Method InitializeFields()? Where are defined FieldVariable and MakeProperty are used in Method BuildClass(string expression). I would be very delighted about an answer.
Reply | Email | Modify 
Very cool idea.... by Travis On January 2, 2009
That was a cool idea. I am looking to do some dynamic calculations. During my testing of your app, some calculations return incorrect values. For example, if you put in 1 / 2, you will get 0, instead of .5 . Another example is 30 / 5 you get 6, but if you do 5 / 30 you get 0. I am not sure why its not returning the double, it seems to just strip off the remainders if the value is less than a whole number? I'll note this project as a possible solution, but I will keep looking. Thanks for the good ideas though. Well written and explained.
Reply | Email | Modify 
Re: Very cool idea.... by lukasz On February 24, 2009
this is because 1/2 is calculated as C# expression so here we have integer division :) if you want get correct result you should write: 1.0 / 2.
Reply | Email | Modify 
Thanks by Baatarkhuu On July 14, 2009
Good job. Very appreciated.
Reply | Email | Modify 
thank you by li On September 4, 2009
thank you very much.
Reply | Email | Modify 
Really Nice Article by Sameep On January 2, 2010
Hi Mike,
This is Really Nice article and helps me a lot..

Thanks.
Reply | Email | Modify 
Thank you very much by AZA On May 20, 2010
Nice article. Exactly what i was looking for dynamical code generation :) thankyou very much
Reply | Email | Modify 
Does this support function? by Jacopo On June 2, 2010
Hi,really thanks for the evaluator,i really thank you to post it.
I've one question,does it support function or method?
Thanks.
Reply | Email | Modify 
Great Article by Lloyd On September 4, 2010
Thanks - this article was a huge help - also the additional logical expression content.
Reply | Email | Modify 
Re: Great Article by Mike On September 4, 2010

Thanks Lloyd,

Glad I could be of service.

Reply | Email | Modify 
Re: Re: Great Article by lafa On September 8, 2010
hi i used ur concept and built a dll /library to use in an asp.net website
My environment is windows 7 64bit and it works fine but the moment i deploy the application to a client machine running win xp/vista 32 bit i get the following error

Exception: Metadata file 'c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_wp.exe' could not be opened -- 'An attempt was made to load a program with an incorrect format

i have tried to compile the application using x86 but that does not help either.. 
Please help
wat could be the problem 
Reply | Email | Modify 
Re: Re: Re: Great Article by Mike On September 8, 2010
could be you have incompatible libraries? (.NET 40 vs. .NET 2.0 for example?)
Reply | Email | Modify 
Re: Re: Re: Re: Great Article by lafa On September 9, 2010
hi,
How do i check for that..but i think i have already tried installing .net 4.0 client profile on the client although am not using .net 4.0
My application is using 3.5 abut 4.0 is installed in the development machine 

thanks
Reply | Email | Modify 
Excelent Article by Horacio On October 8, 2010
Thank you Mike, it 's an excelent article, very helpfull. Thank you once again
Reply | Email | Modify 
Wrong result, please help by minhhai_cd On November 24, 2010
Hello Edward Ziberman

My axample: 100/(1+2*3)*5 your result=70 but in exactly is 71.43 Please help about this bug, almost be round(<1)

Thank you

Reply | Email | Modify 
Re: Wrong result, please help by Mike On November 24, 2010
try putting a d after each number.  Or put a decimal point after each number  (e.g. 100.0)

C# is going to interpret your example as integers so it will give an integer result.  That is why you get the answer you do.
Reply | Email | Modify 
nice, but by Eugene On November 26, 2010
dont usable, very slow
Reply | Email | Modify 
Please help me round a group of long method by minhhai_cd On December 8, 2010
Hello Mike Gold Now i want to round a group of long method like example: 2*100 + Round(200/6)=217 How to do that on your calculator by "Round", what method to replace for "Round"? Thank you so much
Reply | Email | Modify 
Re: Please help me round a group of long method by Mike On December 9, 2010
You should be able to use the round method in Math.Round. The calculator should replace it. If not you may need to change it in the source code. round(200/17)
Reply | Email | Modify 
Re: Re: Please help me round a group of long method by minhhai_cd On December 9, 2010
I type into your application: 10 + Math.Round(200/6,1) and result : Compile Error:'System.Math' does not contain a definition for 'Math' , please guide futher, thank you
Reply | Email | Modify 
Re: Re: Re: Please help me round a group of long method by Mike On December 9, 2010
just type round(100/17) not Math.Round(100/17), the application appends the Math and primary cap for you <g>
Reply | Email | Modify 
Please help me "Compile Error:The operation overflows at compile time in checked mode" bug by minhhai_cd On December 9, 2010
I have a calculation: 2000*2000000 but it is raise Compile Error:The operation overflows at compile time in checked mode, please help me how to upgrade higher with billion calculation? Thank you
Reply | Email | Modify 
Re: Please help me "Compile Error:The operation overflows at compile time in checked mode" bug by minhhai_cd On December 15, 2010
Hello Sir, please help me above bug?
Reply | Email | Modify 
Evaluating an expression with existing variable by Luke On April 4, 2011
Why is it if I declare two variables as public at the top.. , int x = 10; int y = 10; and then I type x*y in the calculator this doesnt work? how would I get this to work? I can see if you can dynamically create variables with this but what about if you have a string that has "x*y" in it and you want to evaluate this? Thanks. Luke
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.