Created
August 25, 2011 11:05
-
-
Save vietnt/1170443 to your computer and use it in GitHub Desktop.
c#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ITemplate Compile(string assemblyPath, string templateId, string input, List<string> usings) | |
{ | |
var providerOptions = new Dictionary<string, string>(); | |
providerOptions.Add("CompilerVersion", "v4.0"); | |
ITemplate _template = null; | |
var usingBuilder = new StringBuilder(); | |
foreach (var @using in _usings) | |
{ | |
usingBuilder.AppendFormat("using {0};", @using); | |
usingBuilder.AppendLine(); | |
} | |
var provider = new CSharpCodeProvider(providerOptions); | |
var typeName = string.Format("Templates_Template_{0}_{1}", templateId, DateTime.Now.Ticks); | |
var options = new CompilerParameters(); | |
options.ReferencedAssemblies.Add("System.dll"); | |
options.ReferencedAssemblies.Add("System.Core.dll"); | |
options.ReferencedAssemblies.Add("Microsoft.CSharp.dll"); | |
options.ReferencedAssemblies.Add(Path.Combine(assemblyPath, "Zero.Web.dll")); | |
options.ReferencedAssemblies.Add(Path.Combine(assemblyPath, "Zero.Core.dll")); | |
options.GenerateInMemory = true; | |
var inputs = new[] | |
{ | |
usings, | |
"constant #1", | |
"constant #2", | |
input, | |
}; | |
var code = string.Join("", inputs); | |
CompilerResults results = provider.CompileAssemblyFromSource( | |
options, | |
new string[] { code }); | |
if (!results.Errors.HasErrors) | |
{ | |
_template = (ITemplate)results.CompiledAssembly.CreateInstance(typeName); | |
return _template; | |
} | |
var builder = new StringBuilder(); | |
foreach (object e in results.Errors) | |
{ | |
var tmp = e.ToString(); | |
builder.Append(tmp); | |
} | |
throw new Exception(code + "\n Compile error: " + builder); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment