Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute code that is in a string? [duplicate]

Tags:

c#

Say I have something like this:

string singleStatement = "System.DateTime.Now";

Is there some way to take singleStatement and parse and run it at run time?

So that:

DateTime currentTime = singleStatement.SomeCoolMethodToRunTheText();

would assign the value of DateTime.Now to currentTime.

like image 528
Vaccano Avatar asked Jan 26 '11 00:01

Vaccano


People also ask

Can you write code for finding all duplicate characters in string?

toCharArray(); System. out. println("The string is:" + str); The duplicate characters are found in the string using a nested for loop.


1 Answers

Read this (quote follows).

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 at 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().CompileAssemblyFromDom(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 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;
        }
    }
}
like image 149
Shimmy Weitzhandler Avatar answered Sep 17 '22 22:09

Shimmy Weitzhandler