Last active
February 24, 2016 12:56
-
-
Save NorbiPeti/5e4f2d7620b0f67f692a to your computer and use it in GitHub Desktop.
A full-featured calculator using built-in methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.CSharp; | |
using System; | |
using System.CodeDom.Compiler; | |
using System.Collections.Generic; | |
using System.ComponentModel; | |
using System.Data; | |
using System.Drawing; | |
using System.Linq; | |
using System.Reflection; | |
using System.Text; | |
using System.Text.RegularExpressions; | |
using System.Threading.Tasks; | |
using System.Windows.Forms; | |
namespace Calc | |
{ | |
public partial class Form1 : Form //5 | |
{ | |
public Form1() | |
{ | |
InitializeComponent(); | |
} | |
private void button1_Click(object sender, EventArgs e) | |
{ | |
CSharpCodeProvider provider = new CSharpCodeProvider(); | |
CompilerParameters parameters = new CompilerParameters(); | |
// True - memory generation, false - external file generation | |
parameters.GenerateInMemory = true; | |
// True - exe file generation, false - dll file generation | |
parameters.GenerateExecutable = false; | |
parameters.ReferencedAssemblies.Add("Calc.exe"); | |
string input = inputTextBox.Text; | |
string pattern = "(\\d+)"; | |
string replacement = "Convert.ToDouble(${1})"; | |
Regex rgx = new Regex(pattern); | |
input = rgx.Replace(input, replacement); | |
string code = @"using System; | |
public class Program : Calc.IOperation | |
{ | |
public double Do() | |
{ | |
return " + input + @"; | |
} | |
}"; | |
CompilerResults results = provider.CompileAssemblyFromSource(parameters, code); | |
if (results.Errors.HasErrors) | |
{ | |
StringBuilder sb = new StringBuilder(); | |
foreach (CompilerError error in results.Errors) | |
{ | |
sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText)); | |
} | |
label1.Text = sb.ToString(); | |
return; | |
} | |
Type type = results.CompiledAssembly.GetTypes().First(t => typeof(IOperation).IsAssignableFrom(t)); | |
IOperation op = (IOperation)Activator.CreateInstance(type, false); | |
label1.Text = op.Do().ToString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment