Search code examples
c#.netdynamiccompilationcodedom

C# dynamic compilation of string and .cs file


I'm working on a website where a user can implement a C# code solution to a problem in a browser text area and submit it. The server will then compile that code together with a predefined interface I provide on the server. Think of it as a strategy design pattern; I provide a strategy interface and users implement it. So I need to compile a string and a predefined *.cs file together at run-time. Here's the code I have now that compiles only the string portion:

CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");

CompilerParameters parameters = new CompilerParameters();
parameters.OutputAssembly = "CodeOutputTest.dll";   // need to name this dynamically.  where to store it?
parameters.GenerateExecutable = false;
parameters.IncludeDebugInformation = false;

CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, request.Code);

Users would submit something like this:

public class UserClass : IStrategy
{
     public string ExecuteSolution(string input)
     {
         // user code
     }
}

Security concerns aside (that's a heavy question for another day)...how can I compile this together with my predefined interface *.cs file? Or is there a better way of handling this?


Solution

  • CodeDomProvider.CompileAssemblyFromSource() is defined as

    public virtual CompilerResults CompileAssemblyFromSource(
        CompilerParameters options, params string[] sources)
    

    That means you can compile one assembly from multiple source files. Something like:

    codeProvider.CompileAssemblyFromSource(parameters, request.Code, otherCode);
    

    Another (possibly better) option is to reference already compiled assembly that contains the code you need. You can do this using CompilerParameters.ReferencedAssemblies:

    parameters.ReferencedAssemblies.Add("SomeLibrary.dll");