1

My question is how it compiles C# code inside the HTML

string path = string.Format("{0}\\Templates\\RazorExample.cshtml", Directory.GetCurrentDirectory());
string template = System.Text.Encoding.UTF8.GetString(System.IO.File.ReadAllBytes(path));
string returnedView = Engine.Razor.RunCompile(template, "report", typeof(ViewModels.ReportViewModel), reportViewModel, null);
File.WriteAllText(fileName, returnedView);
ArunPratap
  • 4,816
  • 7
  • 25
  • 43
  • HTML doesn't get compiled. It's not a programming language, it's just mark-up. In the case of Razor, the HTML is usually the output of executing the c#. So the RunCompile command in Razorengine I imagine executes the c# in the template. But someone with more in depth knowledge of the framework might have a better answer. Or you could study the source code of the project – ADyson Jul 23 '19 at 08:11
  • Yes,I think so but I checked the source code inside vs but I couldn't figure out. – Mehrad Sharifi Jul 23 '19 at 09:13
  • I think basically it does the same as when you actually visit a view page in an MVC app - it executes the C# in the template file, and that (along with any static HTML in the template) outputs the finished HTML which, in your code above, you are saving into a file. Do you need more detail than that? Is there a specific issue which puzzles you? – ADyson Jul 23 '19 at 10:46
  • Thanks mate,but I was just curious about how it executes the c# in the template file – Mehrad Sharifi Jul 23 '19 at 11:03
  • Without looking at the source, you could imagine it might do some dynamic compilation, similar to this idea: https://stackoverflow.com/questions/42992476/dynamically-execute-string-as-code-in-c-sharp. Obviously it's a bit more complex because it has to parse which bits are code and which are static HTML, but the general principle is probably quite similar – ADyson Jul 23 '19 at 12:19

1 Answers1

0

This is very brief but it should help. when everything is configured for debugging you can see the final code by adding compilation errors (the errors should point you to the generated c# files). With this trick you should see how the engine works, you can also try to use several features and see how the code will look like:

  • Basically, all markup is transformed into Stream.WriteLine call.
  • C# code is unchanged (this is basically your question)
  • code is compiled
  • assembly is loaded
  • method is executed

This is the reason why compilation is expensive and execution is cheap. Because in the end "execution" is just a single method call.

So the answer is: Your c# is compiled with the regular c# compiler, no magic there.

matthid
  • 1,644
  • 16
  • 26