possible to execute code contained in a string ?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • John Grandy

    #1

    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) ?



  • Mohammad

    #2
    Re: possible to execute code contained in a string ?

    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?

    Comment

    • John Grandy

      #3
      Re: possible to execute code contained in a string ?

      The former.


      "Mohammad" <m@abdulfatah.n et> wrote in message
      news:1112057880 .276639.5950@o1 3g2000cwo.googl egroups.com...[color=blue]
      > 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?
      >[/color]


      Comment

      • Mohammad

        #4
        Re: possible to execute code contained in a string ?

        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.Reflecti on.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!

        Comment

        • geoffblanduk_nospam@yahoo.co.uk

          #5
          Re: possible to execute code contained in a string ?

          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?

          Comment

          • Ludovic SOEUR

            #6
            Re: possible to execute code contained in a string ?

            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
            CodeMemberMetho d pMethod = new CodeMemberMetho d();
            pMethod.Name = methodname;
            pMethod.Attribu tes = MemberAttribute s.Public;
            pMethod.Paramet ers.Add(new
            CodeParameterDe clarationExpres sion(typeof(str ing[]),"boxes"));
            pMethod.ReturnT ype=new CodeTypeReferen ce(typeof(bool) );
            pMethod.Stateme nts.Add(new CodeSnippetExpr ession(@"
            bool result=true;
            try {
            "+source+@"
            } catch {
            result=false;
            }
            return result;
            "));

            //Crée la classe
            CodeTypeDeclara tion pClass = new
            System.CodeDom. CodeTypeDeclara tion(classname) ;
            pClass.Attribut es = MemberAttribute s.Public;
            pClass.Members. Add(pMethod);

            //Crée le namespace
            CodeNamespace pNamespace = new CodeNamespace(" myNameSpace");
            pNamespace.Type s.Add(pClass);
            foreach(string sUsing in usingList) pNamespace.Impo rts.Add(new
            CodeNamespaceIm port(sUsing));

            //Create compile unit
            CodeCompileUnit pUnit = new CodeCompileUnit ();
            pUnit.Namespace s.Add(pNamespac e);

            //Make compilation parameters
            CompilerParamet ers pParams = new
            CompilerParamet ers((string[])importList.ToA rray(typeof(str ing)));
            pParams.Generat eInMemory = true;

            //Compile
            CompilerResults pResults=(new
            CSharpCodeProvi der()).CreateCo mpiler().Compil eAssemblyFromDo m(pParams,pUnit )
            ;
            if (pResults.Error s != null && pResults.Errors .Count>0) {
            foreach(Compile rError pError in pResults.Errors )
            MessageBox.Show (pError.ToStrin g());
            result =
            pResults.Compil edAssembly.Crea teInstance("myN ameSpace."+clas sname);
            }
            ---------------------------------------

            for an example,
            if 'usingList' equals {"System.Text.R egularExpressio ns"}
            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.Is Match(boxes[0]);
            if (result) {
            regex=new Regex(@"^"+boxe s[0]+@".$",RegexOpt ions.Multiline) ;
            result=regex.Ma tches(pays).Cou nt!=0;
            }

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

            using System.Text.Reg ularExpressions ;
            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.Is Match(boxes[0]);
            if (result) {
            regex=new Regex(@"^"+boxe s[0]+@".$",RegexOpt ions.Multiline) ;
            result=regex.Ma tches(pays).Cou nt!=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:O1xRF6$MFH A.2136@TK2MSFTN GP14.phx.gbl...[color=blue]
            > The former.
            >
            >
            > "Mohammad" <m@abdulfatah.n et> wrote in message
            > news:1112057880 .276639.5950@o1 3g2000cwo.googl egroups.com...[color=green]
            > > 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?
            > >[/color]
            >
            >[/color]


            Comment

            Working...