Ciao,
io usavo questo codice per eseguire del codice a runtime direttametne da stringa, è in C# ma lo puoi facilmente convertire in vb.net usando questo:
http://www.carlosag.net/Tools/CodeTranslator/
ti lascio anche il sorgente in C# perchè il traduttore non sempre è perfetto...ecco il codice:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
using System.IO;
using System.Drawing.Printing;
namespace WinTMP.Managers
{
public class CodeManager
{
public static object Execute(string csharpCode)
{
object result = null;
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("System.dll");
cp.ReferencedAssemblies.Add("System.Xml.dll");
cp.ReferencedAssemblies.Add("System.Data.dll");
cp.CompilerOptions = "/t:library";
cp.GenerateExecutable = false;
cp.GenerateInMemory = true;
//--- scrivo il codice sorgente
string codice = "using System;\r\n" +
"using System.Xml;\r\n" +
"using System.Data;\r\n" +
"using System.Data.SqlClient;\r\n" +
"namespace RuntimeEval { \r\n" +
"public class Evaluator {\r\n" +
"public object Run() {\r\n" +
csharpCode + "\r\n" +
"}\r\n" +
"}\r\n" +
"}";
try
{
//--- compilo ed eseguo
CompilerResults cr = provider.CompileAssemblyFromSource(cp, codice);
Assembly ass = cr.CompiledAssembly;
object obj = ass.CreateInstance("RuntimeEval.Evaluator");
Type t = obj.GetType();
MethodInfo method = t.GetMethod("Run");
result = method.Invoke(obj, null);
//--- cancello il file temporaneo
if (File.Exists(cr.PathToAssembly))
File.Delete(cr.PathToAssembly);
}
catch { }
return result;
}
}
}
che veniva chiamato ad esempio con:
string query =
"DataTable table = new DataTable();" +
"using (SqlConnection conn = new SqlConnection(@\"Data Source=.\...;\"))" +
"{" +
" SqlCommand cmd = conn.CreateCommand();" +
" cmd.CommandText = \"SELECT nominativo, codice FROM clienti\"; "+
" "+
" conn.Open(); "+
" table.Load(cmd.ExecuteReader()); " +
"}" +
"return table;";
dataGridView1.DataSource = CodeManager.Execute(query);
Ciao.
Matteo Raumer
[MCAD .net, MVP Visual C#]
http://blogs.dotnethell.it/freeteo