How to compile the C# custom code script

The Following function compiles the c-sharp code script and return and logs any compiler result to the calller.The code utilizes the using System.CodeDom.Compiler and using Microsoft.CSharp namespaces. We can call this function like this -

 CompilerResults results = CompileAssembly(script, type);

String errorDesc = null;

if (results.Errors.Count>0)

 foreach (CompilerError error in results.Errors)

{

errorDesc = errorDesc + error.ErrorNumber.ToString();

 

errorDesc = errorDesc + error.ErrorText;

errorDesc = errorDesc + error.IsWarning.ToString();

 errorDesc = errorDesc + error.Line.ToString();

errorDesc = errorDesc + error.Column.ToString();

 MessageBox.Show(errorDesc);

}

private CompilerResults CompileAssembly(string script, string name, string assemblyLocation)

{

CompilerResults results = null;

try

 {

CSharpCodeProvider codeProvider = new CSharpCodeProvider();

 ICodeCompiler compiler = codeProvider.CreateCompiler();

 // Setup compiler parameters and add the references needed

CompilerParameters compilerParams = new CompilerParameters();

 compilerParams.CompilerOptions = Constants.COMPILE_PARAMS;

 //This controls the out assembly as executable or a DLL

compilerParams.GenerateExecutable = false;

compilerParams.GenerateInMemory = false;

compilerParams.IncludeDebugInformation = false;

compilerParams.ReferencedAssemblies.Add("System.dll");

 compilerParams.ReferencedAssemblies.Add("System.Data.dll");

compilerParams.ReferencedAssemblies.Add("System.XML.dll");

compilerParams.ReferencedAssemblies.Add("System.Web.dll");

//This sets the output location of the assembly

compilerParams.OutputAssembly = assemblyLocation + ".dll";

// Compile the code

results = compiler.CompileAssemblyFromSource(compilerParams, script);

// Log any compiler errors

if (results.Errors.Count > 0)

{

StringBuilder msg;

foreach (CompilerError error in results.Errors)

{

msg = new StringBuilder();

msg.AppendFormat("CompileAssembly() encountered the following compile error: ({0}) {1}", error.ErrorNumber, error.ErrorText);

//use ypour custom logger here logger.WriteLine(TraceLevel.Warning, Constants.LOG_CATEGORY, msg.ToString());

}

 }

 }

 catch (Exception ex)

 {

string msg = "CompileAssembly() reported this exception: " + ex.Message;

 logger.WriteLine(TraceLevel.Error, Constants.LOG_CATEGORY, msg);

}

return results; // Return the CompilerResults object

}

Ebook Download
View all
Learn
View all