Skip to content

Instantly share code, notes, and snippets.

@jongalloway
Created May 27, 2011 00:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jongalloway/994396 to your computer and use it in GitHub Desktop.
Save jongalloway/994396 to your computer and use it in GitHub Desktop.
ASP.NET MVC - Dynamic Model w/ Mono compiler as a service
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