Hi Manu Prasad,
I have prepared one method which can take the expression statement to execute as parameter and give the boolean result as you are expecting.
You need the namespaces as listed below :-
using System;
using System.Text;
using System.CodeDom;
using Microsoft.CSharp;
using System.Reflection;
using System.Windows.Forms;
using System.CodeDom.Compiler;
using System.Collections.Generic;
I hope the below method will be helpful for you which created exclusively for your post.
public bool TestDymanicCode(string strCodeSnippetToExecute)
{
bool bResult = false;
string strSourceTemplate =
@"using System;
using System.Windows.Forms;
namespace TestNamespace {
public static class TestClass {
public static bool Execute() {
@Placeholder
}
}
}";
string strReplacedCode = strSourceTemplate.Replace("@Placeholder", strCodeSnippetToExecute);
CodeSnippetCompileUnit objCodeSnippetCompileUnit = new CodeSnippetCompileUnit(strReplacedCode);
using (CSharpCodeProvider provider =
new CSharpCodeProvider(new Dictionary<string,> { { "CompilerVersion", "v3.5" } }))
{
CompilerParameters objCompilerParameters = new CompilerParameters();
objCompilerParameters.ReferencedAssemblies.Add("System.dll");
objCompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
objCompilerParameters.GenerateExecutable = false;
objCompilerParameters.GenerateInMemory = true;
objCompilerParameters.IncludeDebugInformation = false;
CompilerResults objCompilerResults = provider.CompileAssemblyFromDom(objCompilerParameters, objCodeSnippetCompileUnit);
if (!objCompilerResults.Errors.HasErrors)
{
Type type = objCompilerResults.CompiledAssembly.GetType("TestNamespace.TestClass");
MethodInfo method = type.GetMethod("Execute");
object val = method.Invoke(null, new object[] { });
bResult = Convert.ToBoolean(val);
}
else
{
StringBuilder objSB = new StringBuilder();
foreach (CompilerError objCompilerError in objCompilerResults.Errors)
objSB.AppendFormat("Error found in line {0}:\n\n{1}", objCompilerError.Line, objCompilerError.ErrorText);
MessageBox.Show(objSB.ToString(), "Compiler Error");
}
}
return bResult;
}
The upper method can be called like this :-
string strReturnCodeSnippet = "return (\"" + txtTestDynamic.Text + "\" == \"Test\");";
MessageBox.Show(TestDymanicCode(strReturnCodeSnippet).ToString());
Hope you will be helpful by this.