Generando un ensamblado dinamicamente y verificandolo

En estas semanas estuve trabajando en una caracteristica dentro de nuestro framework, que involucra crear un ensamblado dinamicamente y verificarlo. Esto pronto será reemplazado por Roslyn, pero mientras continuo trabajando en ello, aquí me permito compartir con ustedes el código mas importante:

 

El código que genera la DLL

private
static
CompilerErrorCollection _errs = null;

private
static
List<string> errors = new
List<string>();

 

public
static
bool GenerateDLL(string path)

{


var yourCodeAsString = @»using System; using System.Collections.Generic; namespace MainProcess

{

class Program

{

private static Random rdx = new Random();

static void Main(string[] args)

{

for (int i = 0; i < rdx.Next(1,21); i++)

{

Console.WriteLine(rdx.Next(100, 1001));

}

}

}

;


CSharpCodeProvider codeProvider = new
CSharpCodeProvider();


ICodeCompiler icc = codeProvider.CreateCompiler();

System.CodeDom.Compiler.CompilerParameters parameters = new
CompilerParameters();

parameters.GenerateExecutable = false;

parameters.OutputAssembly = path + @»AutoGen.dll»;


CompilerResults results = icc.CompileAssemblyFromSource(parameters, yourCodeAsString);

 


if (results.Errors.Count > 0)

{

_errs = results.Errors;

 


foreach (CompilerError error in results.Errors)

{


if (error.IsWarning) continue;

errors.Add(string.Format(«{0} at line {1} column {2}«,

error.ErrorText, error.Line, error.Column));

}

 


return
false;

}


return
true;

}

 

Finalmente el código que verifica la DLL:

GenerateDLL(path);

 


var pi = new
ProcessStartInfo(«PeVerify.exe», path + @»AutoGen.dll /md /il /nologo»)

{

UseShellExecute = false,

RedirectStandardOutput = true,

WorkingDirectory = Environment.CurrentDirectory,

CreateNoWindow = true,

};

 


using (var p = Process.Start(pi))

{


string stdOut = p.StandardOutput.ReadToEnd();

p.WaitForExit();


if (p.ExitCode != 0)

{


Console.WriteLine(stdOut);

 

}

}

 


Console.WriteLine(«Finished!»);

 

Saludos