Created
May 27, 2011 00:17
-
-
Save jongalloway/994396 to your computer and use it in GitHub Desktop.
ASP.NET MVC - Dynamic Model w/ Mono compiler as a service
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
using System.IO; | |
using System.Reflection; | |
using System.Web.Mvc; | |
using Mono.CSharp; | |
using System; | |
namespace DynamicModelCompilation.Controllers | |
{ | |
public class HomeController : Controller | |
{ | |
public ActionResult Index() | |
{ | |
string modelDefinition = | |
@" | |
public class Monkey | |
{ | |
[Required] | |
[StringLength(3, ErrorMessage = ""The {0} must be at least {2} characters long."", MinimumLength = 1)] | |
public string Name { get; set; } | |
[Required] | |
[DataType(DataType.Password)] | |
public string Password { get; set; } | |
[Display(Name = ""Is this monkey happy?"")] | |
public bool IsHappy { get; set; } | |
public bool GetsDownOn" | |
+ DateTime.Now.DayOfWeek + | |
@"{ get; set; } | |
} | |
"; | |
var report = new Report(new ConsoleReportPrinter()); | |
var evaluator = new Evaluator(new CompilerSettings(), report); | |
System.Uri uri = new System.Uri(Assembly.GetExecutingAssembly().CodeBase); | |
string path = Path.GetDirectoryName(uri.LocalPath).Replace("\\DynamicModelCompilation\\bin", "\\lib"); | |
evaluator.LoadAssembly(Path.Combine(path, "System.ComponentModel.DataAnnotations.dll")); | |
evaluator.Run("using System.ComponentModel.DataAnnotations;"); | |
evaluator.Run(modelDefinition); | |
object model = evaluator.Evaluate("new Monkey();"); | |
var props = model.GetType().GetProperties(); | |
return View(model); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment