SHARE
TWEET

C# runtime compilation

Manu404 Jan 28th, 2012 92 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /// <summary>
  2. /// Produces new assembly at runtime.
  3. /// </summary>
  4. /// <param name="references">The assembly references.</param>
  5. /// <param name="sourceCode">The source code to compile.</param>
  6. /// <param name="outputAssemblyName">Output dll name.</param>
  7. /// <returns>Compilation result</returns>
  8. private CompilerResults ProduceAssembly(string[] references,
  9.                                         string sourceCode,
  10.                                         string outputAssemblyName)
  11. {
  12.     CSharpCodeProvider codeProvider = new CSharpCodeProvider();
  13.     ICodeCompiler codeCompiler = codeProvider.CreateCompiler();
  14.  
  15.     CompilerParameters compilerParameters =
  16.                     new CompilerParameters(references,
  17.                                             outputAssemblyName);
  18.     compilerParameters.GenerateExecutable = false;
  19.     compilerParameters.GenerateInMemory = false;
  20.  
  21.     return codeCompiler.CompileAssemblyFromSource(compilerParameters,
  22.                                                   sourceCode);
  23.  
  24. }
  25.  
  26. /// <summary>
  27. /// Creates new object from dynamicaly loaded assembly
  28. /// </summary>
  29. /// <param name="AssemblyName">Name of the assembly to load.</param>
  30. /// <param name="className">Name of the class to instanciate.</param>
  31. /// <param name="constructorParameters">The constructor parameters.</param>
  32. private bool CreateObjectFromAssembly(string AssemblyName,
  33.                                         string className,
  34.                                         object[] constructorParameters,
  35.                                         out object createdObject)
  36. {
  37.     object tmp = createdObject = null;
  38.     Assembly myAssembly = Assembly.LoadFrom(AssemblyName);
  39.     Module[] myModules = myAssembly.GetModules();
  40.  
  41.     myModules.Where(module => module.Name == AssemblyName)
  42.                 .Select(module => module.GetTypes())
  43.                 .ToList()
  44.                 .ForEach
  45.                 (
  46.                 t => t.Where(types => types.Name == className)
  47.                     .ToList()
  48.                     .ForEach(
  49.                         type => tmp = Activator.CreateInstance(type,
  50.                                                     constructorParameters))
  51.                 );
  52.     createdObject = tmp;
  53.     return createdObject != null;
  54. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top