dotnetdevcsharp
dotnetdevcsharp

Reputation: 3980

How does one run code within the browser at Run-time

I have been using the documentation here https://support.microsoft.com/en-gb/help/304655/how-to-programmatically-compile-code-using-c-compiler I am trying to learn about compilers a bit more I want to host on my own site a simple text editor that I can use to run the code of a script say something simple like

The program is required to Print out Console.WriteLine("Hello World");

If anything other than Hello World is printed out the program would be in error.

I have been looking at Microsoft code on running .net code at runtime but both these force it to create an exe I want the result to be like .net fiddle in a text box.

I presume what I have to do some how is run the exe and use the process to return the result bare in mind this is inside a mvc applicaiton.

Or is their any cool nugets that can save me the time here.

private void Compiler(string code)
{

  CSharpCodeProvider codeProvider = new CSharpCodeProvider();
  ICodeCompiler icc = codeProvider.CreateCompiler();
  string Output = "Out.exe";
  System.CodeDom.Compiler.CompilerParameters parameters = new 
  CompilerParameters();
  //Make sure we generate an EXE, not a DLL
        parameters.GenerateExecutable = true;
        parameters.OutputAssembly = Output;
        CompilerResults results = icc.CompileAssemblyFromSource(parameters, code);

        if (results.Errors.Count > 0)
        {

            foreach (CompilerError CompErr in results.Errors)
            {
                CompilerError error = new CompilerError();
                error.Line = CompErr.Line;
                error.ErrorNumber = CompErr.ErrorNumber;
                error.ErrorText = CompErr.ErrorText;                   
            }
        }
        else
        {
            //Successful Compile

            CodeResult result = new CodeResult();
            result.Message = "Success";


        }
}

So how would one capture the above and return and also how does one add support for other languages like python or vb.net

Is this something that blazor could perhaps be good at doing for me ?

I am wanting to provide an experience like .net fiddle https://dotnetfiddle.net

Upvotes: 1

Views: 651

Answers (1)

Tewr
Tewr

Reputation: 3853

Suchiman / Robin Sue is has integrated the Monaco editor as well as an in-browser C# compiler in this nifty blazor project (live demo)

Upvotes: 2

Related Questions