473,396 Members | 1,852 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

possible to execute code contained in a string ?

Is there any way in C# to mimic the T-SQL EXEC() command (which runs a
string as if it was in-line T-SQL code) ?

Nov 17 '05 #1
5 18644
Do you mean that you want a C# method that would take a string
containing some C# code and then execute it? Or do you mean you want a
C# method that would take an SQL command as a string and execute
against a database?

Nov 17 '05 #2
The former.
"Mohammad" <m@abdulfatah.net> wrote in message
news:11********************@o13g2000cwo.googlegrou ps.com...
Do you mean that you want a C# method that would take a string
containing some C# code and then execute it? Or do you mean you want a
C# method that would take an SQL command as a string and execute
against a database?

Nov 17 '05 #3
Short answer is no, there's isn't a built in function in C# that would
evaluate a C# expression stored in a string.

Long answer is still no, but it can be done. You basically have two
choices: use classes in the System.Reflection.Emit namespace to
implement this functionality yourself, or write your own mini
interpreter to parse and execute the subset of the C# expression
languange that you are interested in. You might want to use the ANTLR
parser generator(http://www,antlr.org/). I have used it once before,
and I found it to be quite impressive.

Be forewarned though, both options would constitute an act of
self-flagellation and loathing unlike any other. So, unless you
absolutely must have this functionality, or if you have some very
sinister sins that you want to repent, then don't do it!

Nov 17 '05 #4
There's plenty of scripting languages out there that you could
integrate into your C# application to do this - such as Perl (and
probably VBA?).

That might suit your goals?

Nov 17 '05 #5
That's possible : have a look to System.CodeDom and System.CodeDom.Compiler.

I have found an example I wrote few months ago :
assume 'usingList' is an arraylist with all using statement (without using
keyword, "System.Xml" for example)
assume 'importList' is an arraylist with all dll name that are necessary for
compilation ("system.dll" for example)
assume 'source' is the source code you want to compile
assume 'classname' is the name of the class you want to compile
assume 'methodname' is the name of the method

Have a look to the following code :
---------------------------------------
//Create method
CodeMemberMethod pMethod = new CodeMemberMethod();
pMethod.Name = methodname;
pMethod.Attributes = MemberAttributes.Public;
pMethod.Parameters.Add(new
CodeParameterDeclarationExpression(typeof(string[]),"boxes"));
pMethod.ReturnType=new CodeTypeReference(typeof(bool));
pMethod.Statements.Add(new CodeSnippetExpression(@"
bool result=true;
try {
"+source+@"
} catch {
result=false;
}
return result;
"));

//Crée la classe
CodeTypeDeclaration pClass = new
System.CodeDom.CodeTypeDeclaration(classname);
pClass.Attributes = MemberAttributes.Public;
pClass.Members.Add(pMethod);

//Crée le namespace
CodeNamespace pNamespace = new CodeNamespace("myNameSpace");
pNamespace.Types.Add(pClass);
foreach(string sUsing in usingList) pNamespace.Imports.Add(new
CodeNamespaceImport(sUsing));

//Create compile unit
CodeCompileUnit pUnit = new CodeCompileUnit();
pUnit.Namespaces.Add(pNamespace);

//Make compilation parameters
CompilerParameters pParams = new
CompilerParameters((string[])importList.ToArray(typeof(string)));
pParams.GenerateInMemory = true;

//Compile
CompilerResults pResults=(new
CSharpCodeProvider()).CreateCompiler().CompileAsse mblyFromDom(pParams,pUnit)
;
if (pResults.Errors != null && pResults.Errors.Count>0) {
foreach(CompilerError pError in pResults.Errors)
MessageBox.Show(pError.ToString());
result =
pResults.CompiledAssembly.CreateInstance("myNameSp ace."+classname);
}
---------------------------------------

for an example,
if 'usingList' equals {"System.Text.RegularExpressions"}
if 'importList' equals {"System.dll"}
if 'classname' equals "myClass"
if 'methodName' equals "myMethod"
if 'source' equals "
string pays=@"ES
FR
EN
"
Regex regex=new Regex(@"^[A-Za-z]{2}$");
result=regex.IsMatch(boxes[0]);
if (result) {
regex=new Regex(@"^"+boxes[0]+@".$",RegexOptions.Multiline);
result=regex.Matches(pays).Count!=0;
}

then, the code that will be compiled will be the following :

using System.Text.RegularExpressions;
namespace myNameSpace {
public class myClass {
public bool myMethod(string[] boxes) {
bool result=true;
try {
string pays=@"ES
FR
EN
"
Regex regex=new Regex(@"^[A-Za-z]{2}$");
result=regex.IsMatch(boxes[0]);
if (result) {
regex=new Regex(@"^"+boxes[0]+@".$",RegexOptions.Multiline);
result=regex.Matches(pays).Count!=0;
}
} catch {
result=false;
}
return result;
}
}
}

---------------------------------------------------

Hope it helps,

Ludovic Soeur.


"John Grandy" <johnagrandy-at-yahoo-dot-com> a écrit dans le message de
news:O1**************@TK2MSFTNGP14.phx.gbl...
The former.
"Mohammad" <m@abdulfatah.net> wrote in message
news:11********************@o13g2000cwo.googlegrou ps.com...
Do you mean that you want a C# method that would take a string
containing some C# code and then execute it? Or do you mean you want a
C# method that would take an SQL command as a string and execute
against a database?


Nov 17 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: wj | last post by:
Hi all, I wonder if it is possible to execute PHP-code automatically. Is it for example possible to sent an e-mail every day at lets say 9.00 pm automatically to adresses from a database? ...
2
by: Robin Tucker | last post by:
Is it possible to execute the code contained in a string? I would like to create a wizard for making a custom "filter" in my software, much the same as Outlook Express has mail "rules", ie: ...
1
by: neo1981 | last post by:
I want to execute code which is in a string variable like if i have a string like str='import xyz' then I want to execute import xyz in my program. Is there any way to do this ? :confused:
4
by: mynameistechno | last post by:
I need to execute code in an onload event. e.g. eval(element.getAttribute('onload')); This works in Firefox but not in IE (surprise!). IE's getAttribute for the onload event seems to return an...
1
by: mark4asp | last post by:
<form runat="server"automatically adds <divtag to code contained within. Is there a way to stop that? Mixing block-level elements with inline-level elements messes up the HTML becasuse that is...
4
by: gautam89 | last post by:
Hi everyone, I wanted to know if there is a way to execute code that is inside a string variable. If anyone know, please help as I am new to Java. Thanks..
8
by: shrik | last post by:
I have one main page which contains two iframes say 'leftpanel' and 'content'. leftpanel contain page which has tree in it. Now whenever i clikc on the partiucular node the pages in the 'content'...
2
by: =?Utf-8?B?RnJlZW1hbg==?= | last post by:
Hi, I'm new to vb.net. How to prevent vb.net to automatic execute code in design time? When I open a form design view in VS2005, vs pop up an error message: "Could not load file or assembly...
2
by: maya | last post by:
hi, I keep getting this error, "can't execute code from a freed script" when I go to another page (i.e., upon UNLOAD..) this error occurs only in IE, not FF (what a surprise.....;) what is...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.