Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating ASP.NET MVC style views in a console application?

I have a console application that requires me to send out e-mails. Right now I use a string builder to create the e-mails, but I'd like to get more fancy. Then it dawned on me: it would be nice to send my object to an ASP.NET MVC style view, where I'd have the HTML markup, and then return it to mail out. Right now, I have it going as;

    private void MailJobList(List<Job> newJobs) {
                var body = new System.Text.StringBuilder();
                var from = new MailAddress("[email protected]");
                var to = new MailAddress(addresslist.Get());

                var message = new MailMessage(from, to);

                message.Subject = "New job list";

    //mail settings ommitted here for brevity

                body.Append("New jobs: ");
                if (newJobs.Any()) {
                    foreach (var newJob in newJobs) {
                        body.Append(newJob.Job + ", ");
                    }
                }

                message.Body = body.ToString();

                client.Send(message);
}

Obviously that's just plain text, but I'd really like to be able to do something like:

var body = RenderHTMLMessage(newJobs);

It seems like I should be able to leverage ASP.NET MVC's view engine (or Spark or any other view engine) and not roll my own. If I'm off mark here or there's any easier way to do this, I'm open to suggestions.

like image 809
chum of chance Avatar asked Oct 19 '10 16:10

chum of chance


3 Answers

You can use the new Razor view engine in a console app, see the following blog post:

http://thegsharp.wordpress.com/2010/07/07/using-razor-from-a-console-application/

like image 152
Simon Steele Avatar answered Nov 10 '22 07:11

Simon Steele


You can use the Spark View Engine as a general purpose templating engine. The creator of Spark wrote a blogpost on how to go about doing it (would be a good start).

like image 20
Roman Avatar answered Nov 10 '22 07:11

Roman


You can use T4 templates, which have a syntax similar to asp.net, to do this. It requires the T4 version that ships with VS2010, though. Here is an example, and here is msdn on the subject

like image 2
Gabe Moothart Avatar answered Nov 10 '22 09:11

Gabe Moothart