How to execute c# statment in a string?(Compiling and Running code at runtime)
-
I'm trying to find the way how to execute a string contain c# code.
Example
string st = "if (textBox1.Text == "Jon" && chkText.Checked)
MessageBox.Show("Yes!");
else
MessageBox.Show(textBox1.Text);";I want to execute st then i want to see the result in a message box.
Please kindly help me. Thank in advance!
-
I'm trying to find the way how to execute a string contain c# code.
Example
string st = "if (textBox1.Text == "Jon" && chkText.Checked)
MessageBox.Show("Yes!");
else
MessageBox.Show(textBox1.Text);";I want to execute st then i want to see the result in a message box.
Please kindly help me. Thank in advance!
http://support.microsoft.com/kb/304655[^] I'd recommend against putting the MessageBox and references in your textbox there; a simple check whether the text passed as an argument would suffice. The advantage being that there's no reference from the compiled code to your UI.
Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]
-
I'm trying to find the way how to execute a string contain c# code.
Example
string st = "if (textBox1.Text == "Jon" && chkText.Checked)
MessageBox.Show("Yes!");
else
MessageBox.Show(textBox1.Text);";I want to execute st then i want to see the result in a message box.
Please kindly help me. Thank in advance!
When I'm debugging, I do the following
string st = something
if (textBox1.Text == "Jon" && chkText.Checked)
MessageBox.Show(st + " (if)");
else
MessageBox.Show(st + " (else)");" -
http://support.microsoft.com/kb/304655[^] I'd recommend against putting the MessageBox and references in your textbox there; a simple check whether the text passed as an argument would suffice. The advantage being that there's no reference from the compiled code to your UI.
Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]
thanks but i get error. Can u give me a small example!
-
thanks but i get error. Can u give me a small example!
jojoba2011 wrote:
thanks but i get error.
Can u give me a small example!If you'd get an error, it'd be more helpfull to solve that, than blindly trying examples. I'm guessing that it's due to the fact that you only have the body of a method in there; just like in Visual Studio, the code needs to be located in a class. Try the example below in a console-application.
using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using Microsoft.CSharp;class Program
{
static void Main(string[] args)
{
string sources = @"
using System;
public static class ExampleClass
{
public static void ExampleMethod()
{
Console.WriteLine(""Hello World!"");
}
}";CSharpCodeProvider codeProvider = new CSharpCodeProvider(); string Output = "Out.dll"; CompilerParameters parameters = new CompilerParameters() { GenerateExecutable = false, OutputAssembly = Output }; CompilerResults results = codeProvider.CompileAssemblyFromSource( parameters, sources); if (results.Errors.Count > 0) { foreach (CompilerError CompErr in results.Errors) { Console.WriteLine( "Line number " + CompErr.Line + ", Error Number: " + CompErr.ErrorNumber + ", '" + CompErr.ErrorText + ";"); } } else { // successfull compile, try to load what we just compiled Assembly myAssembly = Assembly.Load(File.ReadAllBytes("Out.dll")); // load the class; Type myType = myAssembly.GetType("ExampleClass"); // get the method; MethodInfo mi = myType.GetMethod("ExampleMethod"); // execute mi.Invoke(null, null); } Console.WriteLine("Hit any user to continue"); Console.ReadKey(); }
Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]
-
jojoba2011 wrote:
thanks but i get error.
Can u give me a small example!If you'd get an error, it'd be more helpfull to solve that, than blindly trying examples. I'm guessing that it's due to the fact that you only have the body of a method in there; just like in Visual Studio, the code needs to be located in a class. Try the example below in a console-application.
using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using Microsoft.CSharp;class Program
{
static void Main(string[] args)
{
string sources = @"
using System;
public static class ExampleClass
{
public static void ExampleMethod()
{
Console.WriteLine(""Hello World!"");
}
}";CSharpCodeProvider codeProvider = new CSharpCodeProvider(); string Output = "Out.dll"; CompilerParameters parameters = new CompilerParameters() { GenerateExecutable = false, OutputAssembly = Output }; CompilerResults results = codeProvider.CompileAssemblyFromSource( parameters, sources); if (results.Errors.Count > 0) { foreach (CompilerError CompErr in results.Errors) { Console.WriteLine( "Line number " + CompErr.Line + ", Error Number: " + CompErr.ErrorNumber + ", '" + CompErr.ErrorText + ";"); } } else { // successfull compile, try to load what we just compiled Assembly myAssembly = Assembly.Load(File.ReadAllBytes("Out.dll")); // load the class; Type myType = myAssembly.GetType("ExampleClass"); // get the method; MethodInfo mi = myType.GetMethod("ExampleMethod"); // execute mi.Invoke(null, null); } Console.WriteLine("Hit any user to continue"); Console.ReadKey(); }
Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]
vote => up. That's a very useful, and complete, example, thanks !
"What Turing gave us for the first time (and without Turing you just couldn't do any of this) is he gave us a way of thinking about and taking seriously and thinking in a disciplined way about phenomena that have, as I like to say, trillions of moving parts. Until the late 20th century, nobody knew how to take seriously a machine with a trillion moving parts. It's just mind-boggling." Daniel C. Dennett
-
jojoba2011 wrote:
thanks but i get error.
Can u give me a small example!If you'd get an error, it'd be more helpfull to solve that, than blindly trying examples. I'm guessing that it's due to the fact that you only have the body of a method in there; just like in Visual Studio, the code needs to be located in a class. Try the example below in a console-application.
using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using Microsoft.CSharp;class Program
{
static void Main(string[] args)
{
string sources = @"
using System;
public static class ExampleClass
{
public static void ExampleMethod()
{
Console.WriteLine(""Hello World!"");
}
}";CSharpCodeProvider codeProvider = new CSharpCodeProvider(); string Output = "Out.dll"; CompilerParameters parameters = new CompilerParameters() { GenerateExecutable = false, OutputAssembly = Output }; CompilerResults results = codeProvider.CompileAssemblyFromSource( parameters, sources); if (results.Errors.Count > 0) { foreach (CompilerError CompErr in results.Errors) { Console.WriteLine( "Line number " + CompErr.Line + ", Error Number: " + CompErr.ErrorNumber + ", '" + CompErr.ErrorText + ";"); } } else { // successfull compile, try to load what we just compiled Assembly myAssembly = Assembly.Load(File.ReadAllBytes("Out.dll")); // load the class; Type myType = myAssembly.GetType("ExampleClass"); // get the method; MethodInfo mi = myType.GetMethod("ExampleMethod"); // execute mi.Invoke(null, null); } Console.WriteLine("Hit any user to continue"); Console.ReadKey(); }
Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]
thanks in advanced! My question is this : Is it possible to excute code without creating any class ....?
string sources = @"
using System;
public static class ExampleClass
{
public static void ExampleMethod()
{
Console.WriteLine(""Hello World!"");
}
}";and one more : How to use the textBox1.Text and other controls values?
-
When I'm debugging, I do the following
string st = something
if (textBox1.Text == "Jon" && chkText.Checked)
MessageBox.Show(st + " (if)");
else
MessageBox.Show(st + " (else)");"Although MessageBox may have it's place in limited circumstances you may be better off using more robust debugging techniques that can be left in the finished product. Have a look at http://support.microsoft.com/kb/815788[^] and http://msdn.microsoft.com/en-us/library/system.diagnostics.debug(v=vs.110).aspx[^]
-
thanks in advanced! My question is this : Is it possible to excute code without creating any class ....?
string sources = @"
using System;
public static class ExampleClass
{
public static void ExampleMethod()
{
Console.WriteLine(""Hello World!"");
}
}";and one more : How to use the textBox1.Text and other controls values?
jojoba2011 wrote:
Is it possible to excute code without creating any class ....?
No. Then again, it wouldn't be much work to wrap it automatically in a class; it's just text after all. Also keep in mind that this class will not be "unloaded".
jojoba2011 wrote:
How to use the textBox1.Text and other controls values?
You see that using? The code one compiles needs to have a reference to your project. That means including a "using" directive in the source code, as well as adding a reference[^] to the compilerparameters. You could save a lot of pain by rewriting that part of the code to use variables/parameters, and not directly the UI-elements of your project. --edit; Alternatively, if you'd install Mono, there'd be the Eval[^] method.
Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]
-
I'm trying to find the way how to execute a string contain c# code.
Example
string st = "if (textBox1.Text == "Jon" && chkText.Checked)
MessageBox.Show("Yes!");
else
MessageBox.Show(textBox1.Text);";I want to execute st then i want to see the result in a message box.
Please kindly help me. Thank in advance!
i got the solution : http://stackoverflow.com/questions/14485226/convert-string-to-executable-c-sharp-code-in-code-behind Solved ! using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Microsoft.CSharp; using System.CodeDom.Compiler; using System.Reflection; namespace WindowsFormsApplication2 { public partial class Form1 : Form { private System.Windows.Forms.TextBox txtf; private System.Windows.Forms.TextBox txts; private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox txt; //public Form1() //{ // InitializeComponent(); //} public Form1() { this.txtf = new System.Windows.Forms.TextBox(); this.txts = new System.Windows.Forms.TextBox(); this.button1 = new System.Windows.Forms.Button(); this.txt = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // txtf // this.txtf.Location = new System.Drawing.Point(81, 125); this.txtf.Name = "txtf"; this.txtf.Size = new System.Drawing.Size(100, 20); this.txtf.TabIndex = 0; // // txts // this.txts.Location = new System.Drawing.Point(81, 161); this.txts.Name = "txts"; this.txts.Size = new System.Drawing.Size(100, 20); this.txts.TabIndex = 0; // // button1 // this.button1.Location = new System.Drawing.Point(81, 196); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 1; this.button1.Text = "button1"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // txt // this.txt.Location = new System.Drawing.Point(12, 12); this.txt.Multiline = true; this.txt.Name = "txt"; this.txt.Size = new System.Drawing.Size(260, 107); this.txt.TabIndex = 0; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScal