<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://weblogs.asp.net/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Fredrik Normén</title><link>http://weblogs.asp.net/fredriknormen/default.aspx</link><description>ASP.NET, AJAX, Silverlight, RIA, Architecture, Clean Code</description><dc:language>en</dc:language><generator>CommunityServer 2007 SP1 (Build: 20510.895)</generator><item><title>OWIN and Razor</title><link>http://weblogs.asp.net/fredriknormen/archive/2013/02/06/owin-and-razor.aspx</link><pubDate>Wed, 06 Feb 2013 22:00:39 GMT</pubDate><guid isPermaLink="false">c06e2b9d-981a-45b4-a55f-ab0d8bbfdc1c:9846679</guid><dc:creator>Fredrik N</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://weblogs.asp.net/fredriknormen/rsscomments.aspx?PostID=9846679</wfw:commentRss><comments>http://weblogs.asp.net/fredriknormen/archive/2013/02/06/owin-and-razor.aspx#comments</comments><description>&lt;p&gt;Just for fun added a simple support for using Razor together with OWIN. You can read a little bit about OWIN on my &lt;a href="http://weblogs.asp.net/fredriknormen/archive/2013/02/02/creating-a-simple-rest-like-service-with-owin-open-web-server-interface.aspx"&gt;previous blog post&lt;/a&gt;.
&lt;/p&gt;&lt;p&gt;I wanted my example to be similar to the MVC pattern, so I can use a Model, Controller (in this case I use a simple method) and a View. My Model is simple:&lt;br/&gt;
	&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    public class Customer&lt;br/&gt;    {
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        public int Id { get; set; }&lt;br/&gt;
				&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        public string Name { get; set; }&lt;br/&gt;    }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;The "Controller" I use will only return the Model, but I can also return a IView and specify which view to be used to render my model. By default convention is used, so the name of the returned Model will be the name of the View to use. Here is my "Controller":
&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    public Customer ListCustomer()&lt;br/&gt;    {
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;       return new Customer() { Id = 1, Name = "John Doe" };&lt;br/&gt;    }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;It just return a new Customer with the name "John Doe".
&lt;/p&gt;&lt;p&gt;To configure the use of Razor with OWIN and to setup "routes", I created a RazorConfig class. By using its Get property, I can map a "route" to a "Controller". Here is the RezorConfig class:
&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;     public class RazorConfig&lt;br/&gt;     {&lt;br/&gt;        private readonly Dictionary&amp;lt;string, Func&amp;lt;object&amp;gt;&amp;gt; _get = new Dictionary&amp;lt;string, Func&amp;lt;object&amp;gt;&amp;gt;();&lt;br/&gt;
				&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        private IViewLocator _viewLocator;&lt;br/&gt;        private IViewParser _viewParser;&lt;br/&gt;
				&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        public IDictionary&amp;lt;string, Func&amp;lt;object&amp;gt;&amp;gt; Get&lt;br/&gt;        {&lt;br/&gt;            get { return _get; }&lt;br/&gt;        }&lt;br/&gt;
				&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        public IViewLocator ViewLocator&lt;br/&gt;        {&lt;br/&gt;            get&lt;br/&gt;            {&lt;br/&gt;                if (_viewLocator != null)&lt;br/&gt;                    return _viewLocator;&lt;br/&gt;
				&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;                return new RazorViewLocator();&lt;br/&gt;            }&lt;br/&gt;            set&lt;br/&gt;            {&lt;br/&gt;                _viewLocator = value;&lt;br/&gt;            }&lt;br/&gt;        }&lt;br/&gt;&lt;br/&gt;        public IViewParser ViewParser&lt;br/&gt;        {&lt;br/&gt;            get&lt;br/&gt;            {&lt;br/&gt;                if (_viewParser != null)&lt;br/&gt;                    return _viewParser;&lt;br/&gt;
				&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;                return new RazorViewParser();&lt;br/&gt;            }&lt;br/&gt;            set&lt;br/&gt;            {&lt;br/&gt;                _viewParser = value;&lt;br/&gt;            }&lt;br/&gt;        }&lt;br/&gt;    }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;The RazorConfig can also be used to specify a custom view locator and a custom view  parser. The RazorViewLoctor I have created will look for views in a Views folder. The RazorViewParser will use &lt;a href="http://razorengine.codeplex.com/"&gt;RazorEngine&lt;/a&gt;.
&lt;/p&gt;&lt;p&gt;Here is the Startup.cs where I configure the "routes" with the RazorConfiguration:
&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;   public class Startup&lt;br/&gt;   {&lt;br/&gt;        public void Configuration(IAppBuilder app)&lt;br/&gt;        {&lt;br/&gt;            var razorConfig = new RazorConfig();&lt;br/&gt;
				&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            razorConfig.Get["/customer"] = ListCustomer;&lt;br/&gt;            razorConfig.Get["/user"] = ListUser;&lt;br/&gt;
				&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            app.UseRazor(razorConfig);&lt;br/&gt;        }&lt;br/&gt;    }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;The Get property of the RazorConfig will be sued to configure the "controllers" to be used for HTTP Get of a specific "route".
&lt;/p&gt;&lt;p&gt;If I do a HTTP GET, e.g. GET &lt;a href="http://localhost/customer"&gt;http://localhost/customer&lt;/a&gt;", the ListCustomer will be invoked. The ListCusomer returns a Customer, so a view with the name Customer.cshtml will be used to render the returned Customer model.
&lt;/p&gt;&lt;p&gt;I have created an extension method for the IAppBuilder, UseRazor. UseRazor takes the RazorConfig as a parameter:
&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    public static class RazorExtensions&lt;br/&gt;    {&lt;br/&gt;        public static void UseRazor(this IAppBuilder builder, RazorConfig razorConfig)&lt;br/&gt;        {&lt;br/&gt;            if (builder == null)&lt;br/&gt;                throw new ArgumentNullException("builder");&lt;br/&gt;
				&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            builder.Use(new Func&amp;lt;object, object&amp;gt;(ignored =&amp;gt; new Razor(razorConfig)));&lt;br/&gt;        }&lt;br/&gt;    }&lt;/span&gt;&lt;br/&gt;
			&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;br/&gt;The extension will use the class Razor. The class Razor will handle the HTTP request and make sure the correct view for the request will be written to the HTTP stream:
&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    public class Razor&lt;br/&gt;    {&lt;br/&gt;        private RazorConfig _config;&lt;br/&gt;
				&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        public Razor(RazorConfig config)&lt;br/&gt;        {&lt;br/&gt;            _config = config;&lt;br/&gt;        }&lt;br/&gt;&lt;br/&gt;        public Task Invoke(IDictionary&amp;lt;string, object&amp;gt; env)&lt;br/&gt;        {&lt;br/&gt;            switch (((string)env["owin.RequestMethod"]).ToUpper())&lt;br/&gt;            {&lt;br/&gt;                case "GET":&lt;br/&gt;                    HttpGetHandler(env);&lt;br/&gt;                    break;&lt;br/&gt;            }&lt;br/&gt;
				&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            return Task.FromResult&amp;lt;object&amp;gt;(null);&lt;br/&gt;        }&lt;br/&gt;
				&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        private void HttpGetHandler(IDictionary&amp;lt;string, object&amp;gt; env)&lt;br/&gt;        {&lt;br/&gt;            var responseContent = _config.Get[(string)env["owin.RequestPath"]].Invoke();&lt;br/&gt;
				&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            var responseHeader = (IDictionary&amp;lt;string, string[]&amp;gt;)env["owin.ResponseHeaders"];&lt;br/&gt;            responseHeader.Add("Content-Type", new[] { "text/html" });&lt;br/&gt;
				&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            using (var writer = new StreamWriter((Stream)env["owin.ResponseBody"]))&lt;br/&gt;            {&lt;br/&gt;                var parsedView = ParseView(responseContent.GetType(), responseContent);&lt;br/&gt;                writer.Write(parsedView);&lt;br/&gt;            }&lt;br/&gt;        }&lt;br/&gt;
				&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        private string ParseView(Type type, object model)&lt;br/&gt;        {&lt;br/&gt;            var viewName = GetViewName(model != null ? model.GetType() : type);&lt;br/&gt;            var view = model as IView ?? new View(viewName, model, type);&lt;br/&gt;
				&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            var viewTemplate = _config.ViewLocator.GetView(null, view);&lt;br/&gt;
				&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            return _config.ViewParser.ParseView(view, viewTemplate);&lt;br/&gt;        }&lt;br/&gt;
				&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        private string GetViewName(Type modelType)&lt;br/&gt;        {&lt;br/&gt;            var viewAttributes = (ViewAttribute[])modelType.GetCustomAttributes(typeof(ViewAttribute), true);&lt;br/&gt;            if (viewAttributes.Length &amp;gt; 0)&lt;br/&gt;                return viewAttributes[0].ViewName;&lt;br/&gt;&lt;br/&gt;            return modelType.Name;&lt;br/&gt;        }&lt;br/&gt;    }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;The Razor class can get the name of the view to be used to render a model by convention, or attribute (ViewAttribute on the model).
&lt;/p&gt;&lt;p&gt;Here is the Customer.cshtml view I used to see that I managed to get Razor to work:
&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    &amp;lt;!DOCTYPE html&amp;gt;&lt;br/&gt;    &amp;lt;html&amp;gt;&lt;br/&gt;      &amp;lt;head&amp;gt;&amp;lt;/head&amp;gt;&lt;br/&gt;      &amp;lt;body&amp;gt;&lt;br/&gt;         &amp;lt;div id="body"&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            &amp;lt;section&amp;gt;                &lt;br/&gt;               &amp;lt;div&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;                  &amp;lt;hgroup&amp;gt;&lt;br/&gt;                      &amp;lt;h1&amp;gt;Welcome '@Model.Name' to OWIN Razor Test!&amp;lt;/h1&amp;gt;&lt;br/&gt;                  &amp;lt;/hgroup&amp;gt;&lt;br/&gt;               &amp;lt;/div&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;           &amp;lt;/section&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;         &amp;lt;/div&amp;gt;&lt;br/&gt;      &amp;lt;/body&amp;gt;&lt;br/&gt;   &amp;lt;/html&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;The code in this blog post is far from perfect, it just a simple code to render a Razor view for a model. You may notice that I fail to follow the law of delimiters when I Get- and Parse a View ;)
&lt;/p&gt;&lt;p&gt;If you are interested in the RazorViewLocator and RazorViewParser code, you can take a look at the code added to the &lt;a href="https://github.com/fredrikn/WebApiContrib.Formatting.RazorViewEngine"&gt;ASP.Net Web API Contrib&lt;/a&gt;.
&lt;/p&gt;&lt;p&gt;If you want to know when I publish a new blog post, feel free to follow me on twitter: &lt;a href="https://twitter.com/fredrikn"&gt;@fredrikn&lt;/a&gt;&lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=9846679" width="1" height="1"&gt;</description><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/.Net/default.aspx">.Net</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/Razor/default.aspx">Razor</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/OWIN/default.aspx">OWIN</category></item><item><title>Feature enabling when using Branch by Abstraction</title><link>http://weblogs.asp.net/fredriknormen/archive/2013/02/03/feature-enabling-when-using-branch-by-abstraction.aspx</link><pubDate>Sun, 03 Feb 2013 12:36:26 GMT</pubDate><guid isPermaLink="false">c06e2b9d-981a-45b4-a55f-ab0d8bbfdc1c:9833021</guid><dc:creator>Fredrik N</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://weblogs.asp.net/fredriknormen/rsscomments.aspx?PostID=9833021</wfw:commentRss><comments>http://weblogs.asp.net/fredriknormen/archive/2013/02/03/feature-enabling-when-using-branch-by-abstraction.aspx#comments</comments><description>&lt;p&gt;Something that I haven't liked for a long time is the use of branches in a projects. I don't like the waste when it comes to merge between branches, "Merge hell". In the beginning of the project I'm in now, it took hours to do merges before a release, both handling conflicts, but also selects different changeset that should include and not include in the merge before a release. The hard part was when a branch per feature was present. Later on this was changed into one single dev branch, but still sometimes two branches may exists. The team was used to work like this from previous projects. To handle this merge hell one dedicated person handle all the merge so the team can work undisturbed (not true, they were involved when conflicts occurs). Even with a dedicated person, the problem still exists, it was just moved. The time it takes to do the merge, was there, the problem with non-disciplines people that did not following the guidelines when it comes to fixing bugs in different branches, or forgot to merge into the main branch, created problems. Wouldn't it be nice to get rid of all the merge problems, let everyone just work in the same branch? There is a way, it may not work for every projects though (sometimes a bigger change may be useful to have in a single branch, but I think it should first be avoided). The solution to the problem is what Paul Hammant calls "&lt;a href="http://paulhammant.com/blog/branch_by_abstraction.html/"&gt;Branch by Abstraction&lt;/a&gt;".
&lt;/p&gt;&lt;p&gt;In short, it's about creating an abstraction over the part of the system that need to be changed, or use an existing abstraction. Implement the new feature side by side with the current production code, and when the new feature is tested and ready for production, switch the old code with the new one, then the old code can be removed. New abstractions added, may also be removed if it's not needed for future use. All code is checked-in into one mainline by everyone in the team. Before a release, a release branch from the mainline is created (used to fix production bugs). 
&lt;/p&gt;&lt;p&gt;BUT! And it's a BIG but, it requires a lot of discipline among the team members and also a good architecture.
&lt;/p&gt;&lt;p&gt;One key "solution" when it comes to work with Branch by Abstraction is to use "feature enabling", to be able to enable features first when it's ready for production. 
&lt;/p&gt;&lt;h2&gt;&lt;br/&gt;Feature enabling on an environment level
&lt;/h2&gt;&lt;p&gt;&lt;br/&gt;Visual Studio has support of using compiler directives or build options like Debug and Release etc. I decided to not use those options, instead a flag in a configuration file, the reason is that I want my Continuous Integration still always use a release build, and the deployment of artifacts to the test environment (for the test team) should be in release mode. The same with compiler directives.
&lt;/p&gt;&lt;p&gt;Because the build script we use uses XML transforming of configuration files based on the environment it will build and deploy too, I think the configuration file is a good place to add a "featuring enable" switch.
&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;&amp;lt;appSettings&amp;gt;&lt;br/&gt;    &amp;lt;add key="FeatureEnableEnvironment" value="development" /&amp;gt;&lt;br/&gt;&amp;lt;appSettings&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;The value of the FeatureEnableEnvironment key in the configuration for the test and development environment is "development". For production it's "production", but this value is ignored. Example of a transforming settings in the configuration file for the production environment:&lt;br/&gt;
	&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;&amp;lt;appSettings&amp;gt;&lt;br/&gt;    &amp;lt;add&lt;br/&gt;      key="FeatureEnableEnvironment"&lt;br/&gt;      value="production"&lt;br/&gt;      xdt:Transform="SetAttributes"&lt;br/&gt;      xdt:Locator="Match(key)"/&amp;gt;&lt;br/&gt;&amp;lt;/appSettings&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;The bootstrapper used for configure the object to an IoC Container will read from the setting, and will override the production registration (default registration is for production) with the new object that developers is working on. Here is the bootstrapper for the IoC container, Microsoft Unity 2.0 is used as a IoC contrainer.
&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;&lt;br/&gt;&lt;/span&gt;&lt;span style="font-size:12pt"&gt;public void Configure(IUnityContainer container)&lt;br/&gt;{&lt;br/&gt;    RegisterForProduction(container);&lt;br/&gt;&lt;br/&gt;    if (IsDevelopmentEnvironment())&lt;br/&gt;        RegisterForDevelopment(container);&lt;br/&gt;}&lt;br/&gt;&lt;br/&gt;private void RegisterForProduction(IUnityContainer container)&lt;br/&gt;{&lt;br/&gt;     container.RegisterType&amp;lt;IRejectInvoiceProcess, RejectInvoiceProcess&amp;gt;();&lt;br/&gt;}&lt;br/&gt;&lt;br/&gt;private void RegisterForDevelopment(IUnityContainer container)&lt;br/&gt;{&lt;br/&gt;     container.RegisterType&amp;lt;IRejectInvoiceProcess, RejectInvoiceProcess_2&amp;gt;();&lt;br/&gt;}&lt;br/&gt;
				&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;When a new feature is under development, an override of the production registration is done within the method RegisterForDevelopment. When the feature is approved for production, the old object will be removed, and the new one will be used instead (probably also be renamed). The override registration in the RegisterForDevelopment will of course also be removed by the team.
&lt;/p&gt;&lt;p&gt;Any suggestion and comment of making this even better are welcome, the problem with the blog I use is that there are a lot of spam, so adding a comment to the post will probably disappear among all the spams. So please send med a message on twitter when a comment is added, so I know when to look among all the comments.
&lt;/p&gt;&lt;p&gt;If you want to know when I publish a new blog post, feel free to follow me on twitter: &lt;a href="https://twitter.com/fredrikn"&gt;@fredrikn&lt;/a&gt;&lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=9833021" width="1" height="1"&gt;</description><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/.Net/default.aspx">.Net</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/Architect/default.aspx">Architect</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/Unity/default.aspx">Unity</category></item><item><title>Creating a simple REST like service with OWIN – Open Web Server Interface</title><link>http://weblogs.asp.net/fredriknormen/archive/2013/02/02/creating-a-simple-rest-like-service-with-owin-open-web-server-interface.aspx</link><pubDate>Sat, 02 Feb 2013 12:06:20 GMT</pubDate><guid isPermaLink="false">c06e2b9d-981a-45b4-a55f-ab0d8bbfdc1c:9828295</guid><dc:creator>Fredrik N</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://weblogs.asp.net/fredriknormen/rsscomments.aspx?PostID=9828295</wfw:commentRss><comments>http://weblogs.asp.net/fredriknormen/archive/2013/02/02/creating-a-simple-rest-like-service-with-owin-open-web-server-interface.aspx#comments</comments><description>&lt;p&gt;"&lt;span style="color:black"&gt;OWIN, a standard interface between .NET web servers and web applications. The goal of OWIN is to decouple server and application and, by being an open standard, stimulate the open source ecosystem of .NET web development tools." – owin.org
&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:black"&gt;OWIN can be used for extremely lightweight hosts that can run from command line, Windows service, client, low power devices etc. Many applications today doesn't use all the features that IIS (Internet Information Service) provide use with, because we just doesn't need them.
&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:black"&gt;In this blog post I will show you a very simple REST like service using OWIN (the code will just support easy GETs nothing more, so it's not a complete REST service).
&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:black"&gt;OWIN is based on a very simple interface, it uses something called application delegate or AppFunc. An application delegate takes the IDictionary&amp;lt;string,object&amp;gt; environment and returns a Task when it has finished processing.&lt;span style="font-family:Helvetica"&gt;&lt;br/&gt;
			&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;  using AppFunc = Func&amp;lt;&lt;br/&gt;        IDictionary&amp;lt;string, object&amp;gt;, // Environment&lt;br/&gt;        Task&amp;gt;; // Done
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;span style="color:black"&gt;The dictionary has some keys that can be used to get access to request and response, headers, body, Query string, request method etc. You can find the key's in the &lt;a href="http://owin.org/spec/owin-1.0.0.html"&gt;OWIN specification&lt;/a&gt; (This blog post will mention some of them later).
&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:black"&gt;In this blog post I will use &lt;a href="http://katanaproject.codeplex.com"&gt;Katana&lt;/a&gt; to host my OWIN and REST like service. To setup a simple OWIN application using Katana, take a look at this &lt;a href="http://katanaproject.codeplex.com/documentation"&gt;documentation&lt;/a&gt; (I will not give instruction how to set it up in this blog post).
&lt;/span&gt;&lt;/p&gt;&lt;p&gt;An OWIN hosts can do the following when its starts:
&lt;/p&gt;&lt;p&gt;It first creates properties with startup data or capabilities provided by the host. The properties is an IDirectory&amp;lt;string, object&amp;gt;. The host selects the server to be used and will provides it with the Properties collection, then it locates the application setup code and invokes it with the Properties collection. The application can then use the properties and decide its own requesting pipeline. Then the host invokes the server startup code with the properties and finish configure itself to accepting requests.&lt;br/&gt;&lt;br/&gt;The OWIN namespace has the IAppBuilder interface, this will contain the Properties mentioned above. When using Katana a Startup class is needed with two methods:
&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;br/&gt;&lt;span style="font-size:11pt"&gt;public void Configuration(IAppBuilder app)&lt;br/&gt;&lt;br/&gt;public Task Invoke(IDictionary&amp;lt;string, object&amp;gt; env)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;The Configuration method will be called when the hosts is starting, and the IAppBuilder will be passed to the Configuration method. The Invoke will be called every time an incoming request should be handled. The env argument will contain a dictionary with environment information, such as request and response.
&lt;/p&gt;&lt;p&gt;I created a simple solution to register "routes" and execute methods based on the requested path. Here is my Startup class:
&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;public class Startup : BaseNavigation&lt;br/&gt;{&lt;br/&gt;    public void Configuration(IAppBuilder app)&lt;br/&gt;    {&lt;br/&gt;       Get["/list/customers"] = ListCustomers;&lt;br/&gt;       Get["/list/users"] = ListUsers;&lt;br/&gt;&lt;br/&gt;       app.Run(this);&lt;br/&gt;    }&lt;br/&gt;&lt;br/&gt;    public Task Invoke(IDictionary&amp;lt;string, object&amp;gt; env)&lt;br/&gt;    {&lt;br/&gt;       switch (((string)env["owin.RequestMethod"]).ToUpper())&lt;br/&gt;       {&lt;br/&gt;          case "GET":&lt;br/&gt;                HttpGetHandler(env);&lt;br/&gt;               break;&lt;br/&gt;           //...
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;       }&lt;br/&gt;&lt;br/&gt;       return Task.FromResult&amp;lt;object&amp;gt;(null);&lt;br/&gt;    }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;The BaseNavigation class inherited by the Startup class just contains a Get property:
&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;br/&gt;&lt;span style="font-size:11pt"&gt;public class BaseNavigation&lt;br/&gt;{&lt;br/&gt;    Dictionary&amp;lt;string, Func&amp;lt;object&amp;gt;&amp;gt; _get = new Dictionary&amp;lt;string, Func&amp;lt;object&amp;gt;&amp;gt;();&lt;br/&gt;&lt;br/&gt;    public IDictionary&amp;lt;string, Func&amp;lt;object&amp;gt;&amp;gt; Get&lt;br/&gt;    {&lt;br/&gt;        get { return _get; }&lt;br/&gt;    }&lt;br/&gt;}&lt;/span&gt;&lt;br/&gt;
			&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;br/&gt;In the Startup's Configuration method I use the Get property to set up which methods that should handle the request for a specific "route". The Get property will only be used to get the "routes" when the incoming request is a HTTP GET. Within the Startup class's Invoke method (as mentioned earlier, the Invoke method will be called on each request) I use the "env" argument to get access to the requested method, this is done by using one of the key specified ("owin.RequestMethod") in the OWIN specification.
&lt;/p&gt;&lt;p&gt;If the request method is GET, I make a call to my HttpGetHandler that will handle the GET:&lt;br/&gt;
	&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;private void HttpGetHandler(IDictionary&amp;lt;string, object&amp;gt; env)&lt;br/&gt;{&lt;br/&gt;    var responseContent = Get[(string)env["owin.RequestPath"]].Invoke();&lt;br/&gt;&lt;br/&gt;    var requestHeader = (IDictionary&amp;lt;string, string[]&amp;gt;)env["owin.RequestHeaders"];&lt;br/&gt;    var responseHeader = (IDictionary&amp;lt;string, string[]&amp;gt;)env["owin.ResponseHeaders"];&lt;br/&gt;&lt;br/&gt;    responseHeader.Add("Content-Type", requestHeader["Accept"]);&lt;br/&gt;    env["owin.ResponseStatusCode"] = 200;&lt;br/&gt;&lt;br/&gt;    using (var writer = new StreamWriter((Stream)env["owin.ResponseBody"]))&lt;br/&gt;    {&lt;br/&gt;        new JsonSerializer().Serialize(writer, responseContent);&lt;br/&gt;    }    &lt;br/&gt;}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;strong&gt;&lt;em&gt;NOTE: I don't care about the HTTP Headers "Content-type" or "Accept" header to decide the format for the returned response, I simply use JSON, the goal is not to write a perfect REST infrastructure, just a simple demonstration of OWIN, there are no error handlers is added to the code.
&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;By using the "owin.RequestPath", I can get access to the request path, for example if I do GET &lt;a href="http://localhost/list/customer"&gt;http://localhost/list/customer&lt;/a&gt;, the "list/customer" will be the request path. Because the key value of the BaseNivgation's Get property is the request path, I just use the path as a key and invoke the Func&amp;lt;T&amp;gt; registered, in this case when "list/customer" is the request path, the ListCustomers method will be executed. To demonstrate how we can get access to the request and response header, I simply gets the "owin.RequestHeaders" and "owin.ResponseHeaders", and adds the "Content-Type" to the response header with the value of the request headers "Accept" header.
&lt;/p&gt;&lt;p&gt;To write to the response stream of a request, the "owin.ResponseBody" key of the "env" argument can be used. The "owin.RequestBody" can be used to get the stream of the request body.
&lt;/p&gt;&lt;p&gt;By setting the "env"'s "owin.ResponseStatusCode", I can specify the HTTP status of the request, in this case 200 (which is also default).
&lt;/p&gt;&lt;p&gt;Here are the ListCustomers and ListUsers methods and the Customer and User classes:&lt;br/&gt;
	&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;public IEnumerable&amp;lt;Customer&amp;gt; ListCustomers()&lt;br/&gt;{&lt;br/&gt;   return new[] { new Customer() { Id = 1, Name = "John Doe" } };&lt;br/&gt;}&lt;br/&gt;&lt;br/&gt;public IEnumerable&amp;lt;User&amp;gt; ListUsers()&lt;br/&gt;{&lt;br/&gt;   return new[] { new User() { Id = 1, Name = "Super User" } };&lt;br/&gt;}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;&lt;br/&gt;public class Customer&lt;br/&gt;{&lt;br/&gt;   public int Id { get; set; }&lt;br/&gt;&lt;br/&gt;   public string Name { get; set; }&lt;br/&gt;}&lt;br/&gt;&lt;br/&gt;public class User&lt;br/&gt;{&lt;br/&gt;    public int Id { get; set; }&lt;br/&gt;&lt;br/&gt;    public string Name { get; set; }&lt;br/&gt;}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;h2&gt;Summary
&lt;/h2&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;In this blog post you have seen how OWIN and Katana was used to create a simple REST like service (well, far from a complete one). The idea was to show some basic stuffs that can be done by using OWIN.
&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;If you want to know when I publish a new blog post, feel free to follow me on twitter: &lt;a href="https://twitter.com/fredrikn"&gt;@fredrikn&lt;/a&gt;&lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=9828295" width="1" height="1"&gt;</description><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/ASP.Net/default.aspx">ASP.Net</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/.Net/default.aspx">.Net</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/OWIN/default.aspx">OWIN</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/REST/default.aspx">REST</category></item><item><title>Team Foundation Server 2012 build notification using ASP.Net Web API Part 2</title><link>http://weblogs.asp.net/fredriknormen/archive/2013/01/28/team-foundation-server-2012-build-notification-using-asp-net-web-api-part-2.aspx</link><pubDate>Mon, 28 Jan 2013 19:22:21 GMT</pubDate><guid isPermaLink="false">c06e2b9d-981a-45b4-a55f-ab0d8bbfdc1c:9810477</guid><dc:creator>Fredrik N</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://weblogs.asp.net/fredriknormen/rsscomments.aspx?PostID=9810477</wfw:commentRss><comments>http://weblogs.asp.net/fredriknormen/archive/2013/01/28/team-foundation-server-2012-build-notification-using-asp-net-web-api-part-2.aspx#comments</comments><description>&lt;p&gt;In my &lt;a href="http://weblogs.asp.net/fredriknormen/archive/2013/01/27/team-foundation-server-2012-build-notification-using-asp-net-web-api.aspx"&gt;previous blog post&lt;/a&gt; I wrote about how to get information about a build, the problem with that code was that the code only returned the user who requested the build, not the user who had checked-in a changeset that failed the build. So this blog post will cover that part.
&lt;/p&gt;&lt;p&gt;The &lt;a href="http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&amp;amp;l=EN-US&amp;amp;k=k(Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&amp;amp;rd=true"&gt;VersionControlServer&lt;/a&gt; class in the assembly Microsoft.TeamFoundation.VersionControl.Client can be used to get Changesets from a specific branch. To get access to the VersionControlServer I use the &lt;a href="http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&amp;amp;l=EN-US&amp;amp;k=k(Microsoft.TeamFoundation.Client.TfsTeamProjectCollection);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&amp;amp;rd=true"&gt;TfsTeamPorjectCollection&lt;/a&gt;'s &lt;a href="http://msdn.microsoft.com/en-us/library/ff737476.aspx"&gt;GetService&amp;lt;T&amp;gt;&lt;/a&gt; method, where T is set to VersionControlServer. To query a branch changeset history, the &lt;a href="http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&amp;amp;l=EN-US&amp;amp;k=k(Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer.QueryHistory);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&amp;amp;rd=true"&gt;QueryHistory&lt;/a&gt; method of the VersionControlServer can be used. The QueryHistory method needs the path to the branch and other query parameters to get changessets. To get the path, I created a helper method (GetFirstServerItemFromBuild, it will get the path from the &lt;a href="http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&amp;amp;l=EN-US&amp;amp;k=k(Microsoft.TeamFoundation.Build.Client.IBuildDefinition);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&amp;amp;rd=true"&gt;BuildDefinition&lt;/a&gt;:&lt;br/&gt;&lt;br/&gt;
	&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:12pt"&gt;        private string GetFirstServerItemFromBuild(string buildName)&lt;br/&gt;        {&lt;br/&gt;            var buildService = _teamProjectCollection.GetService&amp;lt;IBuildServer&amp;gt;();&lt;br/&gt;            var build = GetBuildDefinition(buildName, buildService);&lt;br/&gt;&lt;br/&gt;            return build.Workspace.Mappings.First().ServerItem;&lt;br/&gt;        }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;br/&gt;&lt;br/&gt;When setting up a build in TFS, we need to specify Working folders under the Workspace settings, in my case the first working folder has the path to the branch.&lt;br/&gt;&lt;br/&gt;
	&lt;/p&gt;&lt;p&gt;&lt;img src="http://weblogs.asp.net/blogs/fredriknormen/012813_1954_TeamFoundat1.png" alt=""/&gt;
	&lt;/p&gt;&lt;p&gt;By using the &lt;a href="http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&amp;amp;l=EN-US&amp;amp;k=k(Microsoft.TeamFoundation.Build.Client.IBuildDefinition);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&amp;amp;rd=true"&gt;BuildDefintion&lt;/a&gt;'s &lt;a href="http://msdn.microsoft.com/en-us/library/microsoft.teamfoundation.build.client.ibuilddefinition.workspace.aspx"&gt;Workspace&lt;/a&gt; and its &lt;a href="http://msdn.microsoft.com/en-us/library/microsoft.teamfoundation.build.client.iworkspacetemplate.mappings.aspx"&gt;Mappings&lt;/a&gt; property, I can get the first item from the Working folders. The ServerItem property will return the Source Control Folder.
&lt;/p&gt;&lt;p&gt;To get the most possible ChangeSet that may cause the build to fail I specify a "from date" (passed as an argument to a helper method, more about that later) and a "to date" to the QueryHistory method. The "from date" will be three weeks back in time from when the latest build was started, and the "to date" will be when the latest build was started. I will then take the First &lt;a href="http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&amp;amp;l=EN-US&amp;amp;k=k(Microsoft.TeamFoundation.VersionControl.Client.Changeset);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&amp;amp;rd=true"&gt;ChangeSet&lt;/a&gt; from the QueryHistory's result. QueryHistory don't take a DateTime as argument for the dates, instead a &lt;a href="http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&amp;amp;l=EN-US&amp;amp;k=k(Microsoft.TeamFoundation.VersionControl.Client.VersionSpec);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&amp;amp;rd=true"&gt;VersionSpec&lt;/a&gt; class, so I created a helper method that will parse a DateTime to a VersionSpec.&lt;br/&gt;&lt;br/&gt;
	&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:12pt"&gt;        private static VersionSpec CreateDateVSpec(DateTime date)&lt;br/&gt;        {&lt;br/&gt;            //Format is:  D2009-11-16T14:32&lt;br/&gt;            return VersionSpec.ParseSingleSpec(&lt;br/&gt;                                               string.Format("D{0:yyy}-{0:MM}-{0:dd}T{0:HH}:{0:mm}", date),&lt;br/&gt;                                               string.Empty);&lt;br/&gt;        }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;br/&gt;&lt;br/&gt;I created a helper method added to my TfsBuidService class for helping me to get the latest change set, here is the code for the helper method.&lt;br/&gt;&lt;br/&gt;&lt;span style="font-size:12pt"&gt;
		&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:12pt"&gt;    public Changeset GetLatestChangeset(DateTime versionTodate, string buildName)&lt;br/&gt;      {&lt;br/&gt;            var path = this.GetFirstServerItemFromBuild(buildName);
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:12pt"&gt;            var vcs = _teamProjectCollection.GetService&amp;lt;VersionControlServer&amp;gt;();&lt;br/&gt;&lt;br/&gt;            var versionFrom = CreateDateVSpec(versionTodate.AddDays(-21));&lt;br/&gt;            var versionTo = CreateDateVSpec(versionTodate);&lt;br/&gt;&lt;br/&gt;            var results = vcs.QueryHistory(path, VersionSpec.Latest, 0, RecursionType.Full, null, versionFrom, versionTo, int.MaxValue, false, true);&lt;br/&gt;&lt;br/&gt;            return results.Cast&amp;lt;Changeset&amp;gt;().FirstOrDefault();&lt;br/&gt;        }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;I made some changes to my Web API, so it takes information from the latest change set:
&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:12pt"&gt;    private static BuildDetail GetBuildDetail(string buildName)&lt;br/&gt;      {&lt;br/&gt;          var tfsBuildService = new TfsBuildService(&lt;br/&gt;                                                    TFS_SERVER_COLLECTION_URI,&lt;br/&gt;                                                    USER_DOMAIN,&lt;br/&gt;                                                    USER_NAME,&lt;br/&gt;                                                    USER_PASSWORD,&lt;br/&gt;                                                    PROJECT_NAME);&lt;br/&gt;&lt;br/&gt;           var lastBuild = tfsBuildService.GetLastBuildDetail(buildName);&lt;br/&gt;           var changeSet = tfsBuildService.GetLatestChangeset(lastBuild.StartTime, buildName);&lt;br/&gt;&lt;br/&gt;           return new BuildDetail&lt;br/&gt;           {&lt;br/&gt;               RequestedBy = lastBuild.RequestedBy,&lt;br/&gt;               Status = lastBuild.Status.ToString(),&lt;br/&gt;               FinishTime = lastBuild.FinishTime,&lt;br/&gt;               StartTime = lastBuild.StartTime,&lt;br/&gt;               LastCheckedInUser = changeSet != null ? changeSet.OwnerDisplayName : lastBuild.RequestedBy,&lt;br/&gt;               ChangeSetComment = changeSet != null ? changeSet.Comment : string.Empty,&lt;br/&gt;               ChangeSetId = changeSet != null ? changeSet.ChangesetId : -1,&lt;br/&gt;               WorkItemTitle = tfsBuildService.GetLatestWorkItemTitle(changeSet)&lt;br/&gt;           };&lt;br/&gt;       }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;br/&gt;&lt;br/&gt;The resource returned from the Web API will now also include extra information, such as the last work item associated to the last changeset, changeset's id, changeset's comment by the user who check-in the code and the last user who checked-in the code. To get the latest changeset, the last build's StartTime is used to query the build's branch for the latest changeset.
&lt;/p&gt;&lt;p&gt;To get the latest work item associated to the changeset, I created a helper method that takes the ChangeSet as an argument, just to extract the Work item title:
&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:12pt"&gt;      public string GetLatestWorkItemTitle(Changeset changeSet)&lt;br/&gt;      {&lt;br/&gt;          if (changeSet == null)&lt;br/&gt;              return string.Empty;&lt;br/&gt;&lt;br/&gt;          if (changeSet.AssociatedWorkItems == null || !changeSet.AssociatedWorkItems.Any())&lt;br/&gt;              return string.Empty;&lt;br/&gt;&lt;br/&gt;          return changeSet.AssociatedWorkItems[0].Title;&lt;br/&gt;      }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;Even if the TFS API for 2012 had lack of example on MSDN, it was quite easy to understand how to use them.
&lt;/p&gt;&lt;p&gt;I hope some of you may found this blog post useful.
&lt;/p&gt;&lt;p&gt;If you want to know when I have published a blog post, then feel free to follow me on twitter: &lt;a href="https://twitter.com/fredrikn"&gt;@fredrikn&lt;/a&gt;&lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=9810477" width="1" height="1"&gt;</description><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/.Net/default.aspx">.Net</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/.Net+4.5/default.aspx">.Net 4.5</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/VIsual+Studio+2012/default.aspx">VIsual Studio 2012</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/Team+Foundation+Server/default.aspx">Team Foundation Server</category></item><item><title>Team Foundation Server 2012 build notification using ASP.Net Web API</title><link>http://weblogs.asp.net/fredriknormen/archive/2013/01/27/team-foundation-server-2012-build-notification-using-asp-net-web-api.aspx</link><pubDate>Sun, 27 Jan 2013 11:12:00 GMT</pubDate><guid isPermaLink="false">c06e2b9d-981a-45b4-a55f-ab0d8bbfdc1c:9805632</guid><dc:creator>Fredrik N</dc:creator><slash:comments>4</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://weblogs.asp.net/fredriknormen/rsscomments.aspx?PostID=9805632</wfw:commentRss><comments>http://weblogs.asp.net/fredriknormen/archive/2013/01/27/team-foundation-server-2012-build-notification-using-asp-net-web-api.aspx#comments</comments><description>&lt;p&gt;For the last three years I have helped a financial company with a business critical financial system. I have the role as an architect and coach when it comes to system design. I also spend times to make the team work more efficiently, to release new features with high quality, and maintainable code faster. So the last months I have spent a lot of time with a Deployment Process, to see how we can use Continuous Delivery. We use Visual Studio 2012 and Team Foundation Server 2012 (TFS) as our configuration system. We use gated check-ins (The goal is to use branch by abstractions, so the team work against one mainline only, to remove the "merge hell"). Even if we use gated check-ins we had to disable some acceptance tests because the time it takes for them to run. Instead we use a build that runs at lunch time and one at the night to include the acceptance tests (Those needs to be observed by the team). So far TFS have worked perfect, both for Gated check-in and Continuous Integration for the mainline.  We also use TFS for a "push deployment" to our internal test and UAT environment. Everything is automated. We haven't yet "enable" the "push-deploy" against our production environment yet.
&lt;/p&gt;&lt;p&gt;For showing progress and what the team is working on we have a LCD screen on the wall displaying the TFS's Kanban board. During this weekend I have put together a simple program that will show if a build has failed (the one we run during lunch and at the night, that includes the long running acceptance tests) and the person that brook it, just for fun. Today every team member uses the Build Notification program shipped with Visual Studio, and also an e-mail alert for build notifications. The little program I put together during this weekend will show alerts on the LCD screen.
&lt;/p&gt;&lt;p&gt;Team Foundation Server has Web Services that can query the build server for information, but it returns a lot of data and I had some authentication problem accessing it. Instead I decided to create a REST service with ASP.Net Web API to query the build server, and just fetch the information I need for my purpose, and also to try out the TFS 2012 APIs.
&lt;/p&gt;&lt;h1&gt;Accessing the TFS Build server
&lt;/h1&gt;&lt;p&gt;&lt;span style="color:#323e4f; font-size:15pt"&gt;&lt;strong&gt;&lt;br/&gt;&lt;/strong&gt;&lt;/span&gt;To access the TFS build server from code I added references to the Microsoft.TeamFoundation.Build.Client, Microsoft.TeamFoundation.Client and Microsoft.TeamFoundation.Common assemblies (In the Reference Manager you can find those assemblies by selecting Assemblies/Extensions).
&lt;/p&gt;&lt;p&gt;To connect to the TFS and get the Team project collection I'm working against, I use the &lt;a href="http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&amp;amp;l=EN-US&amp;amp;k=k(Microsoft.TeamFoundation.Client.TfsTeamProjectCollection.%23ctor);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&amp;amp;rd=true"&gt;TfsTeamProjetCollection&lt;/a&gt; class. The &lt;a href="http://msdn.microsoft.com/en-us/library/ff737302.aspx"&gt;TfsTeamProjectCollection constructor&lt;/a&gt; can take an URI and ICredentials as argument. I will use the &lt;a href="http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&amp;amp;l=EN-US&amp;amp;k=k(System.Net.NetworkCredential.%23ctor);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&amp;amp;rd=true"&gt;NetworkCredential&lt;/a&gt; to provide login information to the TFS.
&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;br/&gt;&lt;span style="font-size:11pt"&gt;_teamProjectCollection = new TfsTeamProjectCollection(
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;                                                      new Uri(uri),
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;                                                      new NetworkCredential(username, password, domain));
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;To get access to the Build Server to get the latest build definition, the &lt;a href="http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&amp;amp;l=EN-US&amp;amp;k=k(Microsoft.TeamFoundation.Client.TfsConnection.GetService%60%601);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&amp;amp;rd=true"&gt;TfsTeamProjectCollection's GetService&amp;lt;T&amp;gt;&lt;/a&gt; method can be used, and the &amp;lt;T&amp;gt; represents the type of the service to get. In this case I want the &lt;a href="http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&amp;amp;l=EN-US&amp;amp;k=k(Microsoft.TeamFoundation.Build.Client.IBuildServer);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&amp;amp;rd=true"&gt;IBuildServer&lt;/a&gt;. To get a build definition from the build server, the &lt;a href="http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&amp;amp;l=EN-US&amp;amp;k=k(Microsoft.TeamFoundation.Build.Client.IBuildServer.GetBuildDefinition);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&amp;amp;rd=true"&gt;IBuildServer's GetBuildDefinition&lt;/a&gt; method can be used, it can take the name of the project the build belongs to and also the build to get. The GetBuildDefinition method returns &lt;a href="http://msdn.microsoft.com/en-us/library/microsoft.teamfoundation.build.client.ibuilddefinition.aspx"&gt;IBuildDefintion&lt;/a&gt;.&lt;br/&gt;
	&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;var buildService = _teamProjectCollection.GetService&amp;lt;IBuildServer&amp;gt;();
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;var build = buildService.GetBuildDefinition(_projectName, buildName);
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;if (build == null)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;   throw new BuildDefinitionDoesNotExistException(string.Format("The Build '{0}' can't be found", buildName));
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;To get the details from a specific build, the &lt;a href="http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&amp;amp;l=EN-US&amp;amp;k=k(Microsoft.TeamFoundation.Build.Client.IBuildServer.GetBuild);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&amp;amp;rd=true"&gt;IBuildServer's GetBuild&lt;/a&gt; method can be used. The GetBuild method can take an URI for a specific build and returns &lt;a href="http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&amp;amp;l=EN-US&amp;amp;k=k(Microsoft.TeamFoundation.Build.Client.IBuildDetail);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&amp;amp;rd=true"&gt;IBuildDetail&lt;/a&gt;. In my case I want to get the latest build, so I use the IBuildDefinition's &lt;a href="http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&amp;amp;l=EN-US&amp;amp;k=k(Microsoft.TeamFoundation.Build.Client.IBuildDefinition.LastBuildUri);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&amp;amp;rd=true"&gt;LastBuildUri&lt;/a&gt; property so get the URI for the latest build.
&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;return buildService.GetBuild(build.LastBuildUri);
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;Here is the whole code of a class (TfsBuildService) that uses the code above (I uses this as a simple helper method for my Web API):
&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;namespace TfsNotifierWebApi.Models
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;{
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    using System;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    using System.Net;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    using Microsoft.TeamFoundation.Build.Client;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    using Microsoft.TeamFoundation.Client;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    public class TfsBuildService : ITfsBuildService
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    {
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        private readonly string _projectName;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        private TfsTeamProjectCollection _teamProjectCollection;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        public TfsBuildService(string uri, string domain, string username, string password, string projectName)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        {
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            _projectName = projectName;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            _teamProjectCollection = new TfsTeamProjectCollection(
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;                                                                new Uri(uri),
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;                                                                new NetworkCredential(username, password, domain));
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        public IBuildDetail GetLastBuildDetail(string buildName)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        {
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            var buildService = _teamProjectCollection.GetService&amp;lt;IBuildServer&amp;gt;();
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            var build = buildService.GetBuildDefinition(_projectName, buildName);
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            if (build == null)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;                throw new BuildDefinitionDoesNotExistException(string.Format("The Build '{0}' can't be found", buildName));
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            return buildService.GetBuild(build.LastBuildUri);
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;br/&gt;The IBuildDetail will provide me with information such as who requested the build (RequestedBy) and the status of the build (Status).
&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;h1&gt;The Web API&lt;br/&gt;
	&lt;/h1&gt;&lt;p&gt;I created a simple ASP.Net Web API ApiController that will use the TfsBuildService class (mentioned above) to access a build, and returns information about the build. Here is the code of my Web API:&lt;br/&gt;
	&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;namespace TfsNotifierWebApi.Controllers
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;{
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    using System;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    using System.Net;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    using System.Net.Http;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    using System.Web.Http;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    using TfsNotifierWebApi.Models;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    public class BuildController : ApiController
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    {
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        public const string PROJECT_NAME = "myProject";
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        public const string TFS_SERVER_COLLECTION_URI = "http://&amp;lt;my server&amp;gt;:8080/tfs/&amp;lt;my collection&amp;gt;";
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        public const string USER_NAME = "&amp;lt;username&amp;gt;";
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        public const string USER_PASSWORD = "&amp;lt;password&amp;gt;";
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        public const string USER_DOMAIN = "&amp;lt;domain&lt;/span&gt;&amp;gt;&lt;span style="font-size:11pt"&gt;";
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        public HttpResponseMessage Get(string buildName)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        {
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            try
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            {
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;                return Request.CreateResponse(HttpStatusCode.OK, GetBuildDetail(buildName));
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            catch (Exception e)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            {
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;                return Request.CreateResponse(HttpStatusCode.NotFound, new HttpError(e.Message));
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        private static BuildDetail GetBuildDetail(string buildName)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        {
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            var tfsBuildService = new TfsBuildService(
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;                                                    TFS_SERVER_COLLECTION_URI,
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;                                                    USER_DOMAIN,
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;                                                    USER_NAME,
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;                                                    USER_PASSWORD,
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;                                                    PROJECT_NAME);
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            var lastBuild = tfsBuildService.GetLastBuildDetail(buildName);
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            return new BuildDetail
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            {
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;                RequestedBy = lastBuild.RequestedBy,
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;                Status = lastBuild.Status.ToString(),
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;                FinishTime = lastBuild.FinishTime,
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;                StartTime = lastBuild.StartTime
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            };
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;span style="font-size:12pt"&gt;&lt;strong&gt;&lt;em&gt;IMPORTANT NOTE: The constants storing the information about accessing the TFS is only used in this code for demonstration purpose, NEVER store sensitive information in constants, it's a BAD idea when it comes to security.
&lt;/em&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;&lt;p&gt;The Web API will returns a HttpRespnseMessage with the content set to my custom class, BuildDefintion:&lt;br/&gt;
	&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;namespace TfsNotifierWebApi.Models
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;{
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    using System;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    public class BuildDetail
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    {
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        public string RequestedBy { get; set; }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        public string Status { get; set; }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        public DateTime FinishTime { get; set; }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        public DateTime StartTime { get; set; }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;I think the Web API code will describe itself, so I will skip the details.
&lt;/p&gt;&lt;h1&gt;The Client Side
&lt;/h1&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;On the client side to call the Web API, I decided to use a simple WPF application. I use the HttpClient to access the Web API.&lt;br/&gt;&lt;span style="font-size:12pt"&gt;
		&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;private dynamic GetBuildInfo(string buildName)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;{
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    var httpClient = new HttpClient();
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    var result = httpClient.GetAsync("http://localhost:10927/api/build/" + buildName).Result;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    var buildDetail = result.Content.ReadAsStringAsync().Result;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    return JObject.Parse(buildDetail);
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;I use the Newsoft.Json lib to parse the JSON result returned from the Web API into a dynamic object, JObject.Parse.
&lt;/p&gt;&lt;p&gt;The WPF application was made by KISS (Keep it Simple Stupid). I use a simple DispatcherTimer to poll against the Web API to see if the latest build status has changed.
&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;br/&gt;&lt;span style="font-size:11pt"&gt;using System;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;using System.Net.Http;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;using System.Windows;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;using System.Windows.Media;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;using System.Windows.Media.Imaging;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;using Newtonsoft.Json.Linq;&lt;br/&gt;&lt;br/&gt;public MainWindow()
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;{
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;   WindowState = WindowState.Minimized;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;   InitializeComponent();
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;   UpdateBuildStatus();
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;   var dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;   dispatcherTimer.Tick += dispatcherTimer_Tick;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;   dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 5);
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;   dispatcherTimer.Start();
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;void dispatcherTimer_Tick(object sender, EventArgs e)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;{
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;   UpdateBuildStatus();
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;The UpdateBuildStatus method will update the client with red color if the build has failed, and yellow if partially succeeded. It will also try to get an image from an Images folder of the user started the build.
&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;private void UpdateBuildStatus()
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;{
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;   var result = GetBuildInfo("Test - Nightly Build");
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    requestByTextBlock.Text = result.RequestedBy;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    requestByImage.Source = new BitmapImage(new Uri("Images/" + result.RequestedBy + ".jpg", UriKind.Relative));
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    var status = result.Status;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    switch ((string)status)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    {
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        case "Failed":
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;             SetBackgroundColor(237, 28, 36);
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;             Activate();
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;             WindowState = WindowState.Maximized;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;             break;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        case "PartiallySucceeded":
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;             SetBackgroundColor(255, 201, 14);
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;             Activate();
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;             WindowState = WindowState.Maximized;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;             break;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        default:
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;             WindowState = WindowState == WindowState.Maximized ? WindowState.Minimized : WindowState;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;             SetBackgroundColor(195, 195, 195);
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;             break;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    }&lt;br/&gt;}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;br/&gt;The SetBackgroundColor method is a helper method to set a Grid's background color.
&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;private void SetBackgroundColor(byte r, byte g, byte b)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;{
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;   mainGrid.Background = new SolidColorBrush(Color.FromRgb(r, g, b));
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;Here is the XAML is you are interested:
&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;&amp;lt;Window x:Class="TfsNotifier.MainWindow"
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        Title="MainWindow" Height="1000" Width="800"&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    &amp;lt;Grid Name="mainGrid"&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        &amp;lt;StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            &amp;lt;TextBlock FontSize="90px" FontWeight="ExtraBold" Name="requestByTextBlock"&amp;gt;&amp;lt;/TextBlock&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            &amp;lt;Image Stretch="None" Name="requestByImage" MaxHeight="500" MaxWidth="700"&amp;gt;&amp;lt;/Image&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        &amp;lt;/StackPanel&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    &amp;lt;/Grid&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;&amp;lt;/Window&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;h1&gt;The last words
&lt;/h1&gt;&lt;p&gt;&lt;br/&gt;You may wonder why I have created a Web API instead of using the TFS Api directly from the WPF. By using the Web API I can also create a Windows 8 app or a ASP.Net Single Page Application (SPA) as clients etc.
&lt;/p&gt;&lt;p&gt;If you want to know when I have published a blog post, then feel free to follow me on twitter: &lt;a href="https://twitter.com/fredrikn"&gt;@fredrikn&lt;/a&gt;
	&lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=9805632" width="1" height="1"&gt;</description><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/ASP.Net/default.aspx">ASP.Net</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/.Net/default.aspx">.Net</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/.Net+4.5/default.aspx">.Net 4.5</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/VIsual+Studio+2012/default.aspx">VIsual Studio 2012</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/ASP.Net+WebApi/default.aspx">ASP.Net WebApi</category></item><item><title>Using Razor engine together with Asp.Net Web API to create a Hypermedia API</title><link>http://weblogs.asp.net/fredriknormen/archive/2013/01/20/using-razor-engine-together-with-asp-net-web-api-to-create-a-hypermedia-api.aspx</link><pubDate>Sun, 20 Jan 2013 20:38:00 GMT</pubDate><guid isPermaLink="false">c06e2b9d-981a-45b4-a55f-ab0d8bbfdc1c:9779098</guid><dc:creator>Fredrik N</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://weblogs.asp.net/fredriknormen/rsscomments.aspx?PostID=9779098</wfw:commentRss><comments>http://weblogs.asp.net/fredriknormen/archive/2013/01/20/using-razor-engine-together-with-asp-net-web-api-to-create-a-hypermedia-api.aspx#comments</comments><description>&lt;p&gt;This blog post is created just for fun, and it's will be about how we can use Razor to create a Hypermedia API using XML as a hypermedia for a "Maze game" inspired from the book "Building Hypermedia APIs with HTML5 and Node", Mike Amundsen. Only the server-side API is covered in this blog post, so no Client.
&lt;/p&gt;&lt;p&gt;&lt;em&gt;&lt;strong&gt;Note: &lt;/strong&gt;The code in this blog post will use the &lt;a href="https://github.com/WebApiContrib/WebApiContrib.Formatting.RazorViewEngine"&gt;WebAPI Contrib's Formatting.RazorViewEngine&lt;/a&gt;
		&lt;/em&gt;&lt;/p&gt;&lt;p&gt;Here is a short description of the game:
&lt;/p&gt;&lt;p&gt;In this "Maze Game", a client should be able to request a maze to play. The client should be able to navigate from a starting point through the maze to the exit. The cells in the maze can have different exit (doorways) into other cells (north, south, east and west).
&lt;/p&gt;&lt;p&gt;To design the media type for the game, we first need to know what clients can do, so here is a list of requirements of the game:
&lt;/p&gt;&lt;ul&gt;&lt;li&gt;A list of available mazes to select among.
&lt;/li&gt;&lt;li&gt;Be able to select one maze to play.
&lt;/li&gt;&lt;li&gt;See all the doorways in each cell.
&lt;/li&gt;&lt;li&gt;Navigate through a selected doorway into the next cell.
&lt;/li&gt;&lt;li&gt;See the exit of the maze and navigate through the exit.
&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;To design the hypermedia we can take the requirements and turn it into some states.
&lt;/p&gt;&lt;p&gt;The following is a list of application states and transitions for each identified state of the maze:
&lt;/p&gt;&lt;p&gt;Collection State
&lt;/p&gt;&lt;p&gt;    The response represents a list of mazes.
&lt;/p&gt;&lt;p style="margin-left: 36pt"&gt;Possible transitions are:&lt;br/&gt;&lt;br/&gt;1) Select a maze (Item State), or&lt;br/&gt;2) reload the list (Collection state).
&lt;/p&gt;&lt;p&gt;Item State
&lt;/p&gt;&lt;p&gt;    The response represents a single maze.
&lt;/p&gt;&lt;p&gt;    Possible transition are:
&lt;/p&gt;&lt;ol style="margin-left: 54pt"&gt;&lt;li&gt;Start into the maze, or
&lt;/li&gt;&lt;li&gt;reload the list (Collection Sate), or
&lt;/li&gt;&lt;li&gt;reload the maze (Item State).
&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;Cell State
&lt;/p&gt;&lt;p&gt;    The response represents a single cell in the maze.
&lt;/p&gt;&lt;p&gt;    Possible transitions are:
&lt;/p&gt;&lt;ol style="margin-left: 54pt"&gt;&lt;li&gt;Continue through one of the doorways to the next cell (Cell State)
&lt;/li&gt;&lt;li&gt;Return to the maze (Item State)
&lt;/li&gt;&lt;li&gt;Return to the maze list (Collection State), or
&lt;/li&gt;&lt;li&gt;reload the cell (Cell State).
&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;Error State
&lt;/p&gt;&lt;p&gt;    The response represents the details of an error. No transitions from this state.
&lt;/p&gt;&lt;p&gt;Here is the hypermedia design of the above states:
&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;&amp;lt;maze&amp;gt;&lt;br/&gt;    &amp;lt;collection/&amp;gt;&lt;br/&gt;    &amp;lt;item/&amp;gt;&lt;br/&gt;    &amp;lt;cell/&amp;gt;&lt;br/&gt;    &amp;lt;error&amp;gt;&lt;br/&gt;&amp;lt;/maze&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;br/&gt;For the Item State's transition the &lt;span style="font-family:Consolas"&gt;&amp;lt;link href="…" rel="maze"/&amp;gt;&lt;/span&gt; will be used, the "href" and "rel" attribute is used to hold the URI and transition identifier.
&lt;/p&gt;&lt;p&gt;For the Collection State the "href" attribute will be used for reloading the list:
&lt;/p&gt;&lt;p&gt;&lt;span style="font-family:Consolas"&gt;&amp;lt;collection href="…"&amp;gt;
&lt;/span&gt;&lt;/p&gt;&lt;p&gt;A fully Collection State could look like this
&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;&amp;lt;maze&amp;gt;&lt;br/&gt;    &amp;lt;collection href="…"&amp;gt;&lt;br/&gt;        &amp;lt;link href="…" rel="maze" /&amp;gt;&lt;br/&gt;        &amp;lt;link href="…" rel="maze" /&amp;gt;&lt;br/&gt;        …&lt;br/&gt;    &amp;lt;/collection&amp;gt;&lt;br/&gt;&amp;lt;/maze&amp;gt;&lt;br/&gt;
				&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;The Item State is represented by using the &amp;lt;item/&amp;gt; element, it also uses the &amp;lt;link/&amp;gt; element for transitions and the" href" attribute for reloading the maze details. Here is an example:
&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;&amp;lt;maze&amp;gt;&lt;br/&gt;    &amp;lt;item href="…"&amp;gt;&lt;br/&gt;        &amp;lt;link href="…" rel="collection" /&amp;gt;&lt;br/&gt;        &amp;lt;link href="…" rel="start" /&amp;gt;&lt;br/&gt;        …&lt;br/&gt;    &amp;lt;/item&amp;gt;&lt;br/&gt;&amp;lt;/maze&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;br/&gt;The Cell State is represented in the following way:
&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;&amp;lt;maze&amp;gt;&lt;br/&gt;    &amp;lt;cell href="…"&amp;gt;&lt;br/&gt;        &amp;lt;link href="…" rel="north" /&amp;gt;&lt;br/&gt;        &amp;lt;link href="…" rel="south" /&amp;gt;&lt;br/&gt;        &amp;lt;link href="…" rel="east" /&amp;gt;&lt;br/&gt;        &amp;lt;link href="…" rel="west" /&amp;gt;&lt;br/&gt;        &amp;lt;link href="…" rel="exit" /&amp;gt;&lt;br/&gt;        &amp;lt;link href="…" rel="maze" /&amp;gt;&lt;br/&gt;        &amp;lt;link href="…" rel="collection" /&amp;gt;&lt;br/&gt;    &amp;lt;/cell&amp;gt;&lt;br/&gt;&amp;lt;/maze&amp;gt;&lt;br/&gt;
				&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;br/&gt;Now when the design of the hypermedia is done, we can start creating our API and the Razor views that should render the media.
&lt;/p&gt;&lt;p&gt;The following code are simple fakes that representation the Model of the Maze:&lt;br/&gt;
	&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;using System.Collections.Generic;&lt;br/&gt;using System.Linq;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;namespace MvcWebApiSiteTest.Models&lt;br/&gt;{&lt;br/&gt;    public class MazeDb&lt;br/&gt;    {&lt;br/&gt;        public MazeGame GetMaze()&lt;br/&gt;        {&lt;br/&gt;            var maze = new Maze { Id = "my-only-maze", Description = "My only maze" };
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            maze.AddCell(new Cell { Id = 1, Doorways = new[] { new DoorWay { Id = 1, Direction = "north", Cell = 2 } } });&lt;br/&gt;            maze.AddCell(new Cell { Id = 2, Doorways = new[] { new DoorWay { Id = 1, Direction = "exit" } } });
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            return new MazeGame { Mazes = new List&amp;lt;Maze&amp;gt; { maze } };
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        }&lt;br/&gt;   }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;   public class MazeGame&lt;br/&gt;   {&lt;br/&gt;        public IEnumerable&amp;lt;Maze&amp;gt; Mazes { get; set; }&lt;br/&gt;   }&lt;br/&gt;&lt;br/&gt;   public class Maze&lt;br/&gt;   {&lt;br/&gt;        private IList&amp;lt;Cell&amp;gt; _cells = new List&amp;lt;Cell&amp;gt;();&lt;br/&gt;&lt;br/&gt;        public string Id { get; set; }&lt;br/&gt;        public string Description { get; set; }&lt;br/&gt;        public Cell Start { get { return Cells.First(); }}&lt;br/&gt;        public IEnumerable&amp;lt;Cell&amp;gt; Cells { get { return _cells; }}&lt;br/&gt;&lt;br/&gt;        public void AddCell(Cell cell)&lt;br/&gt;        {&lt;br/&gt;            cell.Maze = this;&lt;br/&gt;            _cells.Add(cell);&lt;br/&gt;        }&lt;br/&gt;    }&lt;br/&gt;&lt;br/&gt;    public class Cell&lt;br/&gt;    {&lt;br/&gt;        public Maze Maze { get; set; }&lt;br/&gt;        public int Id { get; set; }&lt;br/&gt;        public IEnumerable&amp;lt;DoorWay&amp;gt; Doorways { get; set; }&lt;br/&gt;    }&lt;br/&gt;&lt;br/&gt;    public class DoorWay&lt;br/&gt;    {&lt;br/&gt;        public int Id { get; set; }&lt;br/&gt;        public string Direction { get; set; }&lt;br/&gt;        public int Cell { get; set; }&lt;br/&gt;    }&lt;br/&gt;}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;The following is the ApiController used. The code for accessing the Maze are just fakes (Because the blog post is not about how to write the server-side code, it's about how to use the RazorViewEngine to create a hypermedia, the code is simple and stupid and far from perfect!):
&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;using System.Web.Http;&lt;br/&gt;&lt;br/&gt;namespace MvcWebApiSiteTest.Controllers&lt;br/&gt;{&lt;br/&gt;    using System.Linq;&lt;br/&gt;    using MvcWebApiSiteTest.Models;&lt;br/&gt;&lt;br/&gt;    public class MazeController : ApiController&lt;br/&gt;    {&lt;br/&gt;        // GET /maze&lt;br/&gt;        public MazeGame Get()&lt;br/&gt;        {&lt;br/&gt;            var mazeDb = new MazeDb();&lt;br/&gt;            return mazeDb.GetMaze();&lt;br/&gt;        }&lt;br/&gt;&lt;br/&gt;        // GET /maze/{maze}&lt;br/&gt;        public Maze Get(string maze)&lt;br/&gt;        {&lt;br/&gt;            var mazeDb = new MazeDb();&lt;br/&gt;            return mazeDb.GetMaze()&lt;br/&gt;                         .Mazes.Single(m =&amp;gt; m.Id == maze);&lt;br/&gt;        }&lt;br/&gt;&lt;br/&gt;        // GET /maze/{maze}/{id}&lt;br/&gt;        public Cell Get(string maze, int id)&lt;br/&gt;        {&lt;br/&gt;            var mazeDb = new MazeDb();&lt;br/&gt;            return mazeDb.GetMaze()&lt;br/&gt;                         .Mazes.Single(m =&amp;gt; m.Id == maze)&lt;br/&gt;                         .Cells.Single(c =&amp;gt; c.Id == id);&lt;br/&gt;        }&lt;br/&gt;    }&lt;br/&gt;}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;br/&gt;&lt;br/&gt;The following code configures the route for the API so it can take "maze" and "id" from the URL as parameters (instead of using Querystrings) into the Get methods of the MazeController:
&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;&lt;br/&gt;config.Routes.MapHttpRoute(&lt;br/&gt;                name: "DefaultApi",&lt;br/&gt;                routeTemplate: "maze/{maze}/{id}",&lt;br/&gt;                defaults: new { controller = "maze", maze = RouteParameter.Optional, id = RouteParameter.Optional }&lt;br/&gt;            );&lt;br/&gt;
				&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;br/&gt;Now when the server-side API is created, we can go on to the Razor Views that will render the hypermedia designed earlier in this blog post.
&lt;/p&gt;&lt;p&gt;The WebApi Contrib's Formatting RazorViewEngine can use convention before configuration to locate the View for rendering the Model the MazeController returns. The name of the view should be the same name as the class the MazeController returns. The Views are created in the Views folder and the views are MazeGame.cshtml (Representation the Collection State of the Maze), Maze.cshtml (Represents the Item State) and the Cell.cshtml (Represents the Cell State). Here is the code of the Views:
&lt;/p&gt;&lt;p&gt;&lt;strong&gt;MazeGame.cshtml
&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;br/&gt;&lt;span style="font-size:11pt"&gt;&amp;lt;?xml version="1.0" encoding="utf-8" ?&amp;gt;&lt;br/&gt;&amp;lt;maze&amp;gt;&lt;br/&gt;    &amp;lt;collection href="http://weblogs.asp.net/mazeGame"&amp;gt;&lt;br/&gt;        @foreach (var maze in Model.Mazes)&lt;br/&gt;        {&lt;br/&gt;            &amp;lt;link href="http://weblogs.asp.net/maze/@maze.Id" rel="maze" /&amp;gt;&lt;br/&gt;        }&lt;br/&gt;    &amp;lt;/collection&amp;gt;&lt;br/&gt;&amp;lt;/maze&amp;gt;&lt;br/&gt;
				&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;br/&gt;Here is a representation of the MazeGame.cshtml ouput:&lt;br/&gt;
	&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;&amp;lt;?xml version="1.0" encoding="utf-8" ?&amp;gt; 
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;&amp;lt;maze&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    &amp;lt;collection href="http://weblogs.asp.net/mazeGame"&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            &amp;lt;link href="http://weblogs.asp.net/maze/my-only-maze" rel="maze" /&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    &amp;lt;/collection&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;&amp;lt;/maze&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;Maze.cshtml
&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;br/&gt;&lt;span style="font-size:11pt"&gt;&amp;lt;?xml version="1.0" encoding="utf-8" ?&amp;gt;&lt;br/&gt;&amp;lt;maze&amp;gt;&lt;br/&gt;    &amp;lt;item href="http://weblogs.asp.net/maze/@Model.Id" &amp;gt;&lt;br/&gt;        &amp;lt;link href="http://weblogs.asp.net/mazeGame" rel="collection"&amp;gt;&lt;br/&gt;        &amp;lt;link href="http://weblogs.asp.net/maze/@Model.Id/@Model.Start.Id" rel="start" /&amp;gt;&lt;br/&gt;    &amp;lt;/item&amp;gt;&lt;br/&gt;&amp;lt;/maze&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;Here is a representation of the Maze.cshtml output:
&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;br/&gt;&lt;span style="font-size:11pt"&gt;&amp;lt;?xml version="1.0" encoding="utf-8" ?&amp;gt; 
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;&amp;lt;maze&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    &amp;lt;item href="http://weblogs.asp.net/maze/my-only-maze" &amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        &amp;lt;link href="http://weblogs.asp.net/mazeGame" rel="collection"&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        &amp;lt;link href="http://weblogs.asp.net/maze/my-only-maze/1" rel="start" /&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    &amp;lt;/item&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;&amp;lt;/maze&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;Cell.cshtml
&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;&amp;lt;?xml version="1.0" encoding="utf-8" ?&amp;gt; 
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;&amp;lt;maze&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    &amp;lt;cell href="http://weblogs.asp.net/maze/@Model.Maze.Id/@Model.Id"&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        @foreach (var cell in Model.Doorways)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        {
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;            &amp;lt;link href="http://weblogs.asp.net/maze/@Model.Maze.Id/@cell.Cell" rel="@cell.Direction" /&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        &amp;lt;link href="http://weblogs.asp.net/maze/@Model.Maze.Id" rel="maze" /&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        &amp;lt;link href="http://weblogs.asp.net/maze" rel="collection" /&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    &amp;lt;/cell&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;&amp;lt;/maze&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;Here is a representation of the Cell.cshtml output:&lt;br/&gt;
	&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;&amp;lt;?xml version="1.0" encoding="utf-8" ?&amp;gt; 
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;&amp;lt;maze&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    &amp;lt;cell href="http://weblogs.asp.net/maze/my-only-maze/1"&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        &amp;lt;link href="http://weblogs.asp.net/maze/my-only-maze/2" rel="north" /&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        &amp;lt;link href="http://weblogs.asp.net/maze/my-only-maze" rel="maze" /&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;        &amp;lt;link href="http://weblogs.asp.net/maze" rel="collection" /&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;    &amp;lt;/cell&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;&amp;lt;/maze&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;Now when the Views for rending the hypermedia is done, we need to configure so we can use a specific media type to access our hypermedia. We will use "application/maze+xml" as the media type.
&lt;/p&gt;&lt;p&gt;To add the support of our own media type "application/maze+xml" we can take advantage of the WebApiContrib Razor Formatter's HtmlMediaTypeViewFormatter. We can simply add the "application/maze+xml" media type to the HtmlMediaTypeViewFormatter, here is the Application_Start method of the Global.asax to add our media type and use the HtmlMediaTypeViewFormatter:&lt;br/&gt;
	&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;protected void Application_Start()
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;{
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;      AreaRegistration.RegisterAllAreas();
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;      var formatter = new HtmlMediaTypeViewFormatter();
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;      formatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/maze+xml"));
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;      GlobalConfiguration.Configuration.Formatters.Add(formatter);
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;      GlobalViews.DefaultViewParser = new RazorViewParser();
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;      GlobalViews.DefaultViewLocator = new RazorViewLocator();
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;      WebApiConfig.Register(GlobalConfiguration.Configuration);
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;      FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;      RouteConfig.RegisterRoutes(RouteTable.Routes);
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;      BundleConfig.RegisterBundles(BundleTable.Bundles);
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;br/&gt;To access the Maze Hypermedia API by a HTTP GET, make sure the HTTP Header Accept is set to "application/maze+xml":
&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;&lt;span style="font-size:11pt"&gt;Accept: application/maze+xml
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;br/&gt;All done!&lt;strong&gt;
		&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;By using ASP.Net Web API and the WebApiContrib.Formatting.RazorViewEngine, we can use Razor to create a hypermedia, wasn't that cool? ;)
&lt;/p&gt;&lt;p&gt;By following me on twitter &lt;a href="https://twitter.com/fredrikn"&gt;@fredrikn&lt;/a&gt;, you will know when I publish new blog posts.&lt;span style="font-family:Consolas"&gt;
		&lt;/span&gt;&lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;
 &lt;/p&gt;&lt;p&gt;&lt;span style="font-family:Consolas"&gt;
		&lt;/span&gt; &lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=9779098" width="1" height="1"&gt;</description><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/ASP.Net/default.aspx">ASP.Net</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/.Net/default.aspx">.Net</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/WebApi/default.aspx">WebApi</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/ASP.Net+WebApi/default.aspx">ASP.Net WebApi</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/hypermedia+API/default.aspx">hypermedia API</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/hypermedia/default.aspx">hypermedia</category></item><item><title>ASP.Net Web API and using Razor the next step</title><link>http://weblogs.asp.net/fredriknormen/archive/2012/07/17/asp-net-web-api-and-using-razor-the-next-step.aspx</link><pubDate>Tue, 17 Jul 2012 20:16:08 GMT</pubDate><guid isPermaLink="false">c06e2b9d-981a-45b4-a55f-ab0d8bbfdc1c:8751814</guid><dc:creator>Fredrik N</dc:creator><slash:comments>6</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://weblogs.asp.net/fredriknormen/rsscomments.aspx?PostID=8751814</wfw:commentRss><comments>http://weblogs.asp.net/fredriknormen/archive/2012/07/17/asp-net-web-api-and-using-razor-the-next-step.aspx#comments</comments><description>&lt;p&gt;In my previous blog post “&lt;a href="http://weblogs.asp.net/fredriknormen/archive/2012/06/28/using-razor-together-with-asp-net-web-api.aspx" target="_blank"&gt;Using Razor together with ASP.NET Web API&lt;/a&gt;” I wrote about a solution to use a MediaTypeFormatter to render HTML by using Razor when the API is accessed from a browser. I’m now sort of done with the basics and will share the current solution in this blog post. The source code will later be available.    &lt;br /&gt;    &lt;br /&gt;I decided to make the solution more extendable so I created a HtmlMediaTypeViewFormatter that inherits from the MediaTypeFormatter:&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;&lt;br /&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; HtmlMediaTypeViewFormatter : MediaTypeFormatter
{
    &lt;span class="rem"&gt;//...&lt;/span&gt;
}&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;With the new generic solution any kind of “parser” can be used to render the HTML, not only by using Razor. I made this possible by using a IViewParser:&lt;/p&gt;

&lt;p&gt;
  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;&lt;br /&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; IViewParser
{
   &lt;span class="kwrd"&gt;byte&lt;/span&gt;[] ParseView(IView view, &lt;span class="kwrd"&gt;string&lt;/span&gt; viewTemplate, Encoding encoding);
}&lt;/pre&gt;
  &lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

  &lt;br /&gt;The IViewParser’s responsibility is to implement the logic to use a template (for example a razor template) and parse a view’s model into a encoded byte array.&lt;/p&gt;

&lt;p&gt;Another interface that is introduce is the IViewLocator, with the IViewLocator it will be easy to replace how to locate the templates passed into the IViewParser. At the moment the IViewLocator also has the responsibility to return the content of the located template, so the default RazorViewLocator in the project will locate and read a .cshtml or .vbhtml file and the content of the file is passed as an argument to the IViewParser. Here is part of the IViewLocator code:
  &lt;br /&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; IViewLocator
{
    &lt;span class="kwrd"&gt;string&lt;/span&gt; GetView(&lt;span class="kwrd"&gt;string&lt;/span&gt; siteRootPath, IView view);
}&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;
  &lt;br /&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;internal&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; RazorViewLocator : IViewLocator
{
     &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt;[] viewLocationFormats = &lt;span class="kwrd"&gt;new&lt;/span&gt;[]
        {
             &lt;span class="str"&gt;&amp;quot;~\\Views\\{0}.cshtml&amp;quot;&lt;/span&gt;,
             &lt;span class="str"&gt;&amp;quot;~\\Views\\{0}.vbhtml&amp;quot;&lt;/span&gt;,
             &lt;span class="str"&gt;&amp;quot;~\\Views\\Shared\\{0}.cshtml&amp;quot;&lt;/span&gt;,
             &lt;span class="str"&gt;&amp;quot;~\\Views\\Shared\\{0}.vbhtml&amp;quot;&lt;/span&gt;
         };


     &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; GetView(&lt;span class="kwrd"&gt;string&lt;/span&gt; siteRootPath, IView view)
     {
         &lt;span class="kwrd"&gt;if&lt;/span&gt; (view == &lt;span class="kwrd"&gt;null&lt;/span&gt;)
             &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; ArgumentNullException(&lt;span class="str"&gt;&amp;quot;view&amp;quot;&lt;/span&gt;);

         var path = GetPhysicalSiteRootPath(siteRootPath);

         &lt;span class="kwrd"&gt;foreach&lt;/span&gt;(&lt;span class="kwrd"&gt;string&lt;/span&gt; viewLocationFormat &lt;span class="kwrd"&gt;in&lt;/span&gt; viewLocationFormats)
         {
             var potentialViewPathFormat = viewLocationFormat.Replace(&lt;span class="str"&gt;&amp;quot;~&amp;quot;&lt;/span&gt;, GetPhysicalSiteRootPath(siteRootPath));

             var viewPath = &lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(potentialViewPathFormat, view.ViewName);

             &lt;span class="kwrd"&gt;if&lt;/span&gt; (File.Exists(viewPath))
                 &lt;span class="kwrd"&gt;return&lt;/span&gt; File.ReadAllText(viewPath);
         }

         &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; FileNotFoundException(&lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;&amp;quot;Can't find a view with the name '{0}.cshtml' or '{0}.vbhtml in the '\\Views' folder under  path '{1}'&amp;quot;&lt;/span&gt;, view.ViewName, path));
     }

      &lt;span class="rem"&gt;///...&lt;/span&gt;
}&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;
  &lt;br /&gt;Here is some code from the HtmlMediaTypeViewFormatter, so you can get a glimpse how the IViewLocator and IViewParser is used:

  &lt;br /&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; Task WriteToStreamAsync(
                                       Type type,
                                       &lt;span class="kwrd"&gt;object&lt;/span&gt; &lt;span class="kwrd"&gt;value&lt;/span&gt;,
                                       Stream stream,
                                       HttpContentHeaders contentHeaders,
                                       TransportContext transportContext)
{
     &lt;span class="kwrd"&gt;return&lt;/span&gt; TaskHelpers.RunSync(() =&amp;gt;
           {
              var encoding = SelectCharacterEncoding(contentHeaders);

              var parsedView = ParseView(type, &lt;span class="kwrd"&gt;value&lt;/span&gt;, encoding);

              stream.Write(parsedView, 0, parsedView.Length);
              stream.Flush();
           });
}


&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;byte&lt;/span&gt;[] ParseView(Type type, &lt;span class="kwrd"&gt;object&lt;/span&gt; model, System.Text.Encoding encoding)
{
      var view = model &lt;span class="kwrd"&gt;as&lt;/span&gt; IView;

       &lt;span class="kwrd"&gt;if&lt;/span&gt; (view == &lt;span class="kwrd"&gt;null&lt;/span&gt;)
            view = &lt;span class="kwrd"&gt;new&lt;/span&gt; View(GetViewName(model), model, type);

        var viewTemplate = _viewLocator.GetView(_siteRootPath, view);

        &lt;span class="kwrd"&gt;return&lt;/span&gt; _viewParser.ParseView(view, viewTemplate, encoding);
}&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;
  &lt;br /&gt;&lt;strong&gt;&lt;em&gt;Note: The WriteToStreamAsync in the RTM code of ASP.NET WebAPI is different from the above code. I decided to still use the bits shipped with Visual Studio 2012 RC. This will of course be changed later.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The IViewLocator and IViewParser can be changed by using a global configuration class, GlobalViews, so in App_Start of a Web API project or in Global.asax the locator and parser can be replaced with another implementation, for example:
  &lt;br /&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;GlobalViews.DefaultViewLocator = &lt;span class="kwrd"&gt;new&lt;/span&gt; MyViewParser();
GlobalViews.DefaultViewLocator = &lt;span class="kwrd"&gt;new&lt;/span&gt; DatabaseViewLocator();&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;The HtmlMediaTypeViewFormatter can also inject the dependencies to a locator and parser.
  &lt;br /&gt;&lt;/p&gt;

&lt;h2&gt;How to decide which view to be used&lt;/h2&gt;

&lt;p&gt;
  &lt;br /&gt;There are different ways to configure which View that should be used when accessing a API of a ApiController. Here are the examples:&lt;/p&gt;

&lt;h3&gt;&lt;font style="font-weight: bold"&gt;Convention
    &lt;br /&gt;&lt;/font&gt;&lt;font style="font-weight: bold"&gt;
    &lt;br /&gt;&lt;/font&gt;&lt;/h3&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; CustomerController : ApiController
{
     &lt;span class="rem"&gt;// GET api/customer&lt;/span&gt;
     &lt;span class="kwrd"&gt;public&lt;/span&gt; Customer Get()
     {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; Customer { Name = &lt;span class="str"&gt;&amp;quot;John Doe&amp;quot;&lt;/span&gt;, Country = &lt;span class="str"&gt;&amp;quot;Sweden&amp;quot;&lt;/span&gt; };
     }
}&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;By default with no configurations at all (just adding the HtmlMediaTypeViewFormatter to the Formatters collection in the Global.asax) a view will be located by using the name of the returned model, in the above code “Customer”&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h3&gt;&lt;font style="font-weight: bold"&gt;Configuration&lt;/font&gt;&lt;/h3&gt;

&lt;p&gt;By using annotation (with the ViewAttribute) you can specify which view a specific model should use:&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;[View(&lt;span class="str"&gt;&amp;quot;Customer&amp;quot;&lt;/span&gt;)]
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Customer
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Name { get; set; }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Country { get; set; }
}&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;By using the GlobalViews in the Global.asax, mapping between model an views can be configured, here is code from the App_Start folder:
  &lt;br /&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; ViewConfig
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; RegisterViews(IDictionary&amp;lt;Type, &lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; views)
    {
        views.Add(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(Customer), &lt;span class="str"&gt;&amp;quot;CustomerViaConfig&amp;quot;&lt;/span&gt;);
    }
}&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;
  &lt;br /&gt;So if the Customer type is returned from the Web API, the “CustomerViaConfig” view will be used.&lt;/p&gt;

&lt;p&gt;By returning an IView class, the view can be specified within the Web API’s return result:
  &lt;br /&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; CustomerController : ApiController
{
   &lt;span class="rem"&gt;// GET api/customer&lt;/span&gt;
   &lt;span class="kwrd"&gt;public&lt;/span&gt; View Get()
   {
      &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; View(&lt;span class="str"&gt;&amp;quot;CustomerViaView&amp;quot;&lt;/span&gt;, &lt;span class="kwrd"&gt;new&lt;/span&gt; Customer { Name = &lt;span class="str"&gt;&amp;quot;John Doe&amp;quot;&lt;/span&gt;, Country = &lt;span class="str"&gt;&amp;quot;Sweden&amp;quot;&lt;/span&gt; });
   }
}&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h2&gt;Summary&lt;/h2&gt;

&lt;p&gt;By using a HtmlMediaTypeViewFormatter, we can now render HTML when accessing our Web API from a browser, and we can specify which view to be used by using different kind of configuration or convention. It’s easy to replace the parser that is used to render the HTML and also how and where to locate a view to be used. The source code will sometime in a near future (I hope) be available for download.&lt;/p&gt;

&lt;p&gt;My next goal is to make a WHOLE web site explaining the use of my project, just by using ASP.Net Web API.. I promise to let all of you know when that happens.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;If you want to know when I post a new blog post, you can simply follow me on twitter &lt;a href="http://twitter.com/fredrikn" target="_blank"&gt;@fredrikn&lt;/a&gt;&lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=8751814" width="1" height="1"&gt;</description><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/Razor/default.aspx">Razor</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/WebApi/default.aspx">WebApi</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/ASP.Net+WebApi/default.aspx">ASP.Net WebApi</category></item><item><title>Using Razor together with ASP.NET Web API</title><link>http://weblogs.asp.net/fredriknormen/archive/2012/06/28/using-razor-together-with-asp-net-web-api.aspx</link><pubDate>Thu, 28 Jun 2012 19:53:11 GMT</pubDate><guid isPermaLink="false">c06e2b9d-981a-45b4-a55f-ab0d8bbfdc1c:8666864</guid><dc:creator>Fredrik N</dc:creator><slash:comments>11</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://weblogs.asp.net/fredriknormen/rsscomments.aspx?PostID=8666864</wfw:commentRss><comments>http://weblogs.asp.net/fredriknormen/archive/2012/06/28/using-razor-together-with-asp-net-web-api.aspx#comments</comments><description>&lt;p&gt;On the blog post “&lt;a href="http://ben.onfabrik.com/posts/if-then-if-then-if-then-mvc" target="_blank"&gt;If Then, If Then, If Then, MVC&lt;/a&gt;” I found the following code example:    &lt;br /&gt;&lt;/p&gt;  &lt;pre class="csharpcode"&gt;[HttpGet]&lt;br /&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; ActionResult List() 
{
    var list = &lt;span class="kwrd"&gt;new&lt;/span&gt;[] { &lt;span class="str"&gt;&amp;quot;John&amp;quot;&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;Pete&amp;quot;&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;Ben&amp;quot;&lt;/span&gt; };

    &lt;span class="kwrd"&gt;if&lt;/span&gt; (Request.AcceptTypes.Contains(&lt;span class="str"&gt;&amp;quot;application/json&amp;quot;&lt;/span&gt;)) {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; Json(list, JsonRequestBehavior.AllowGet);
    }

    &lt;span class="kwrd"&gt;if&lt;/span&gt; (Request.IsAjaxRequest()) [
        &lt;span class="kwrd"&gt;return&lt;/span&gt; PartialView(&lt;span class="str"&gt;&amp;quot;_List&amp;quot;&lt;/span&gt;, list);
    }

    &lt;span class="kwrd"&gt;return&lt;/span&gt; View(list);
}&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;
  &lt;br /&gt;The code is a ASP.NET MVC Controller where it reuse the same “business” code but returns JSON if the request require JSON, a partial view when the request is an AJAX request or a normal ASP.NET MVC View.&lt;/p&gt;

&lt;p&gt;The above code may have several reasons to be changed, and also do several things, the code is not closed for modifications. To extend the code with a new way of presenting the model, the code need to be modified. So I started to think about how the above code could be rewritten so it will follow the Single Responsibility and open-close principle. I came up with the following result and with the use of ASP.NET Web API:
  &lt;br /&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; String[] Get()
{
      &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt;[] { &lt;span class="str"&gt;&amp;quot;John&amp;quot;&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;Pete&amp;quot;&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;Ben&amp;quot;&lt;/span&gt; };
}&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;It just returns the model, nothing more. The code will do one thing and it will do it well. But it will not solve the problem when it comes to return Views. If we use the ASP.NET Web Api we can get the result as JSON or XML, but not as a partial view or as a ASP.NET MVC view. Wouldn’t it be nice if we could do the following against the Get() method?&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;Accept: application/json&lt;/p&gt;

&lt;p&gt;JSON will be returned – Already part of the Web API&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;Accept: text/html&lt;/p&gt;

&lt;p&gt;Returns the model as HTML by using a View&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;The best thing, it’s possible!&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;By using the &lt;a href="http://razorengine.codeplex.com/" target="_blank"&gt;RazorEngine&lt;/a&gt; I created a custom MediaTypeFormatter (RazorFormatter, code at the end of this blog post) and associate it with the media type “text/html”. I decided to use convention before configuration to decide which Razor view should be used to render the model. To register the formatter I added the following code to Global.asax:

  &lt;br /&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;GlobalConfiguration.Configuration.Formatters.Add(&lt;span class="kwrd"&gt;new&lt;/span&gt; RazorFormatter());&lt;/pre&gt;

&lt;p&gt;
  &lt;br /&gt;Here is an example of a ApiController that just simply returns a model:

  &lt;br /&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Web.Http;

&lt;span class="kwrd"&gt;namespace&lt;/span&gt; WebApiRazor.Controllers
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; CustomersController : ApiController
    {
        &lt;span class="rem"&gt;// GET api/values&lt;/span&gt;
        &lt;span class="kwrd"&gt;public&lt;/span&gt; Customer Get()
        {
            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; Customer { Name = &lt;span class="str"&gt;&amp;quot;John Doe&amp;quot;&lt;/span&gt;, Country = &lt;span class="str"&gt;&amp;quot;Sweden&amp;quot;&lt;/span&gt; };
        }
    }


    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Customer
    {
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Name { get; set; }

        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Country { get; set; }
    }
}&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;Because I decided to use convention before configuration I only need to add a view with the same name as the model, Customer.cshtml, here is the example of the View:&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
    
    &amp;lt;head&amp;gt;
        &amp;lt;script src=&lt;span class="str"&gt;&amp;quot;http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.1.min.js&amp;quot;&lt;/span&gt; type=&lt;span class="str"&gt;&amp;quot;text/javascript&amp;quot;&lt;/span&gt;&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;/head&amp;gt;

    &amp;lt;body&amp;gt;

        &amp;lt;div id=&lt;span class="str"&gt;&amp;quot;body&amp;quot;&lt;/span&gt;&amp;gt;
            &amp;lt;section&amp;gt;
                
                &amp;lt;div&amp;gt;
                    &amp;lt;hgroup&amp;gt;
                        &amp;lt;h1&amp;gt;Welcome &lt;span class="str"&gt;'@Model.Name'&lt;/span&gt; to ASP.NET Web API Razor Formatter!&amp;lt;/h1&amp;gt;
                    &amp;lt;/hgroup&amp;gt;
                &amp;lt;/div&amp;gt;
                &amp;lt;p&amp;gt;
                    Using the same URL &lt;span class="str"&gt;&amp;quot;api/values&amp;quot;&lt;/span&gt; but &lt;span class="kwrd"&gt;using&lt;/span&gt; AJAX: &amp;lt;button&amp;gt;Press to show content!&amp;lt;/button&amp;gt;
                &amp;lt;/p&amp;gt;
                &amp;lt;p&amp;gt;
                    
                &amp;lt;/p&amp;gt;

            &amp;lt;/section&amp;gt;
        &amp;lt;/div&amp;gt;

    &amp;lt;/body&amp;gt;
    
    &amp;lt;script type=&lt;span class="str"&gt;&amp;quot;text/javascript&amp;quot;&lt;/span&gt;&amp;gt;

        $(&lt;span class="str"&gt;&amp;quot;button&amp;quot;&lt;/span&gt;).click(function () {

            $.ajax({
                url: &lt;span class="str"&gt;'/api/values'&lt;/span&gt;,
                type: &lt;span class="str"&gt;&amp;quot;GET&amp;quot;&lt;/span&gt;,
                contentType: &lt;span class="str"&gt;&amp;quot;application/json; charset=utf-8&amp;quot;&lt;/span&gt;,
                success: function(data, status, xhr)
                {
                    alert(data.Name);
                },
                error: function(xhr, status, error)
                {
                    alert(error);
                }});
            });
&amp;lt;/script&amp;gt;
&amp;lt;/html&amp;gt;&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;Now when I open up a browser and enter the following URL: &lt;a href="http://localhost/api/customers"&gt;http://localhost/api/customers&lt;/a&gt; the above View will be displayed and it will render the model the ApiController returns. If I use Ajax against the same ApiController with the content type set to “json”, the ApiController will now return the model as JSON.&lt;/p&gt;

&lt;p&gt;Here is a part of a really early prototype of the Razor formatter (The code is far from perfect, just use it for testing). I will rewrite the code and also make it possible to specify an attribute to the returned model, so it can decide which view to be used when the media type is “text/html”, but by default the formatter will use convention:
  &lt;br /&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; System;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Net.Http.Formatting;

&lt;span class="kwrd"&gt;namespace&lt;/span&gt; WebApiRazor.Models
{
    &lt;span class="kwrd"&gt;using&lt;/span&gt; System.IO;
    &lt;span class="kwrd"&gt;using&lt;/span&gt; System.Net;
    &lt;span class="kwrd"&gt;using&lt;/span&gt; System.Net.Http.Headers;
    &lt;span class="kwrd"&gt;using&lt;/span&gt; System.Reflection;
    &lt;span class="kwrd"&gt;using&lt;/span&gt; System.Threading.Tasks;

    &lt;span class="kwrd"&gt;using&lt;/span&gt; RazorEngine;

    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; RazorFormatter : MediaTypeFormatter
    {
        &lt;span class="kwrd"&gt;public&lt;/span&gt; RazorFormatter()
        {
            SupportedMediaTypes.Add(&lt;span class="kwrd"&gt;new&lt;/span&gt; MediaTypeHeaderValue(&lt;span class="str"&gt;&amp;quot;text/html&amp;quot;&lt;/span&gt;)); 
            SupportedMediaTypes.Add(&lt;span class="kwrd"&gt;new&lt;/span&gt; MediaTypeHeaderValue(&lt;span class="str"&gt;&amp;quot;application/xhtml+xml&amp;quot;&lt;/span&gt;));
        }

        //...&lt;br /&gt;
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; Task WriteToStreamAsync(
                                                Type type,
                                                &lt;span class="kwrd"&gt;object&lt;/span&gt; &lt;span class="kwrd"&gt;value&lt;/span&gt;,
                                                Stream stream,
                                                HttpContentHeaders contentHeaders,
                                                TransportContext transportContext)
        {
            var task = Task.Factory.StartNew(() =&amp;gt;
                {
&lt;span class="str"&gt;                    var viewPath = // Get path to the view by the name of the type&lt;/span&gt;

                    var template = File.ReadAllText(viewPath);

                    Razor.Compile(template, type, type.Name);
                    var razor = Razor.Run(type.Name, &lt;span class="kwrd"&gt;value&lt;/span&gt;);

                    var buf = System.Text.Encoding.Default.GetBytes(razor);

                    stream.Write(buf, 0, buf.Length);

                    stream.Flush();
                });

            &lt;span class="kwrd"&gt;return&lt;/span&gt; task;
        }
    }
}&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;By using formatters and the ASP.NET Web API we can easily just extend our code without doing any changes to our ApiControllers when we want to return a new format. This blog post just showed how we can extend the Web API to use Razor to format a returned model into HTML.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;If you want to know when I will post more blog posts, please feel free to follow me on twitter:&amp;#160;&amp;#160; &lt;a href="http://twitter.com/#!/fredrikn" target="_blank"&gt;@fredrikn&lt;/a&gt;&lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=8666864" width="1" height="1"&gt;</description><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/ASP.Net/default.aspx">ASP.Net</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/WebApi/default.aspx">WebApi</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/ASP.Net+WebApi/default.aspx">ASP.Net WebApi</category></item><item><title>ASP.NET Web API Exception Handling</title><link>http://weblogs.asp.net/fredriknormen/archive/2012/06/11/asp-net-web-api-exception-handling.aspx</link><pubDate>Mon, 11 Jun 2012 21:14:18 GMT</pubDate><guid isPermaLink="false">c06e2b9d-981a-45b4-a55f-ab0d8bbfdc1c:8596653</guid><dc:creator>Fredrik N</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://weblogs.asp.net/fredriknormen/rsscomments.aspx?PostID=8596653</wfw:commentRss><comments>http://weblogs.asp.net/fredriknormen/archive/2012/06/11/asp-net-web-api-exception-handling.aspx#comments</comments><description>&lt;p&gt;When I talk about exceptions in my product team I often talk about two kind of exceptions, business and critical exceptions. Business exceptions are exceptions thrown based on “business rules”, for example if you aren’t allowed to do a purchase. Business exceptions in most case aren’t important to log into a log file, they can directly be shown to the user. An example of a business exception could be &amp;quot;DeniedToPurchaseException”, or some validation exceptions such as “FirstNameIsMissingException” etc.&lt;/p&gt;  &lt;p&gt;Critical Exceptions are all other kind of exceptions such as the SQL server is down etc. Those kind of exception message need to be logged and should not reach the user, because they can contain information that can be harmful if it reach out to wrong kind of users.&lt;/p&gt;  &lt;p&gt;I often distinguish business exceptions from critical exceptions by creating a base class called BusinessException, then in my error handling code I catch on the type BusinessException and all other exceptions will be handled as critical exceptions.&lt;/p&gt;  &lt;p&gt;This blog post will be about different ways to handle exceptions and how Business and Critical Exceptions could be handled.   &lt;br /&gt;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Web API and Exceptions the basics&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;When an exception is thrown in a ApiController a response message will be returned with a status code set to 500 and a response formatted by the formatters based on the “Accept” or “Content-Type” HTTP header, for example JSON or XML. Here is an example:&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;pre class="csharpcode"&gt;        &lt;span class="kwrd"&gt;public&lt;/span&gt; IEnumerable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; Get()
        {
            &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; ApplicationException(&lt;span class="str"&gt;&amp;quot;Error!!!!!&amp;quot;&lt;/span&gt;);

            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt;[] { &lt;span class="str"&gt;&amp;quot;value1&amp;quot;&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;value2&amp;quot;&lt;/span&gt; };
        }&lt;/pre&gt;

&lt;p&gt;&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

  &lt;br /&gt;The response message will be:

  &lt;br /&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;HTTP/1.1 500 Internal Server Error
Content-Length: 860
Content-Type: application/json; charset=utf-8

{ &lt;span class="str"&gt;&amp;quot;ExceptionType&amp;quot;&lt;/span&gt;:&lt;span class="str"&gt;&amp;quot;System.ApplicationException&amp;quot;&lt;/span&gt;,&lt;span class="str"&gt;&amp;quot;Message&amp;quot;&lt;/span&gt;:&lt;span class="str"&gt;&amp;quot;Error!!!!!&amp;quot;&lt;/span&gt;,&lt;span class="str"&gt;&amp;quot;StackTrace&amp;quot;&lt;/span&gt;:&lt;span class="str"&gt;&amp;quot;   at ...&amp;quot;&lt;/span&gt;}&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;The stack trace will be returned to the client, this is because of making it easier to debug. Be careful so you don’t leak out some sensitive information to the client. So as long as you are developing your API, this is not harmful. In a production environment it can be better to log exceptions and return a user friendly exception instead of the original exception.&lt;/p&gt;

&lt;p&gt;There is a specific exception shipped with ASP.NET Web API that will not use the formatters based on the “Accept” or “Content-Type” HTTP header, it is the exception is the &lt;a href="http://msdn.microsoft.com/en-us/library/system.web.http.httpresponseexception(v=vs.108).aspx" target="_blank"&gt;HttpResponseException&lt;/a&gt; class.

  &lt;br /&gt;

  &lt;br /&gt;Here is an example where the HttpReponseExcetpion is used:

  &lt;br /&gt;&lt;/p&gt;

&lt;p&gt;
  &lt;pre class="csharpcode"&gt;        &lt;span class="rem"&gt;// GET api/values&lt;/span&gt;
        [ExceptionHandling]
        &lt;span class="kwrd"&gt;public&lt;/span&gt; IEnumerable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; Get()
        {
            &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; HttpResponseException(&lt;span class="kwrd"&gt;new&lt;/span&gt; HttpResponseMessage(HttpStatusCode.InternalServerError));

            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt;[] { &lt;span class="str"&gt;&amp;quot;value1&amp;quot;&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;value2&amp;quot;&lt;/span&gt; };
        }&lt;/pre&gt;
  &lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

  &lt;br /&gt;The response will not contain any content, only header information and the status code based on the &lt;a href="http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&amp;amp;l=EN-US&amp;amp;k=k(System.Net.HttpStatusCode);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&amp;amp;rd=true" target="_blank"&gt;HttpStatusCode&lt;/a&gt; passed as an argument to the &lt;a href="http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&amp;amp;l=EN-US&amp;amp;k=k(&amp;quot;System.Net.Http.HttpResponseMessage.%23ctor&amp;quot;);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&amp;amp;rd=true" target="_blank"&gt;HttpResponseMessage&lt;/a&gt;. Because the HttpResponsException takes a HttpResponseMessage as an argument, we can give the response a content:&lt;/p&gt;

&lt;p&gt;
  &lt;br /&gt;

  &lt;pre class="csharpcode"&gt;        &lt;span class="kwrd"&gt;public&lt;/span&gt; IEnumerable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; Get()
        {
            &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; HttpResponseException(&lt;span class="kwrd"&gt;new&lt;/span&gt; HttpResponseMessage(HttpStatusCode.InternalServerError)
                                                {
                                                    Content = &lt;span class="kwrd"&gt;new&lt;/span&gt; StringContent(&lt;span class="str"&gt;&amp;quot;My Error Message&amp;quot;&lt;/span&gt;),
                                                    ReasonPhrase = &lt;span class="str"&gt;&amp;quot;Critical Exception&amp;quot;&lt;/span&gt;
                                                });

            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt;[] { &lt;span class="str"&gt;&amp;quot;value1&amp;quot;&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;value2&amp;quot;&lt;/span&gt; };
        }&lt;/pre&gt;
  &lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;The code above will have the following response:&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;HTTP/1.1 500 Critical Exception
Content-Length: 5
Content-Type: text/plain; charset=utf-8

My Error Message&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;The Content property of the HttpResponseMessage doesn’t need to be just plain text, it can also be other formats, for example JSON, XML etc.&lt;/p&gt;

&lt;p&gt;By using the HttpResponseException we can for example catch an exception and throw a user friendly exception instead:&lt;/p&gt;

&lt;p&gt;
  &lt;br /&gt;

  &lt;pre class="csharpcode"&gt;        &lt;span class="kwrd"&gt;public&lt;/span&gt; IEnumerable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; Get()
        {
            &lt;span class="kwrd"&gt;try&lt;/span&gt;
            {
                DoSomething();

                &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt;[] { &lt;span class="str"&gt;&amp;quot;value1&amp;quot;&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;value2&amp;quot;&lt;/span&gt; };

            }
            &lt;span class="kwrd"&gt;catch&lt;/span&gt; (Exception e)
            {
                &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; HttpResponseException(&lt;span class="kwrd"&gt;new&lt;/span&gt; HttpResponseMessage(HttpStatusCode.InternalServerError)
                                                {
                                                    Content = &lt;span class="kwrd"&gt;new&lt;/span&gt; StringContent(&lt;span class="str"&gt;&amp;quot;An error occurred, please try again or contact the administrator.&amp;quot;&lt;/span&gt;),
                                                    ReasonPhrase = &lt;span class="str"&gt;&amp;quot;Critical Exception&amp;quot;&lt;/span&gt;
                                                });
            }
        }&lt;/pre&gt;
  &lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;Adding a try catch to every ApiController methods will only end in duplication of code, by using a custom &lt;a href="http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&amp;amp;l=EN-US&amp;amp;k=k(System.Web.Http.Filters.ExceptionFilterAttribute);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&amp;amp;rd=true" target="_blank"&gt;ExceptionFilterAttribute&lt;/a&gt; or our own custom ApiController base class we can reduce code duplicationof code and also have a more general exception handler for our ApiControllers . By creating a custom ApiController’s and override the ExecuteAsync method, we can add a try catch around the base.ExecuteAsync method, but I prefer to skip the creation of a own custom ApiController, better to use a solution that require few files to be modified.&lt;/p&gt;

&lt;p&gt;The ExceptionFilterAttribute has a OnException method that we can override and add our exception handling. Here is an example:
  &lt;br /&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;    &lt;span class="kwrd"&gt;using&lt;/span&gt; System;
    &lt;span class="kwrd"&gt;using&lt;/span&gt; System.Diagnostics;
    &lt;span class="kwrd"&gt;using&lt;/span&gt; System.Net;
    &lt;span class="kwrd"&gt;using&lt;/span&gt; System.Net.Http;
    &lt;span class="kwrd"&gt;using&lt;/span&gt; System.Web.Http;
    &lt;span class="kwrd"&gt;using&lt;/span&gt; System.Web.Http.Filters;

    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; ExceptionHandlingAttribute : ExceptionFilterAttribute
    {
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; OnException(HttpActionExecutedContext context)
        {
            &lt;span class="kwrd"&gt;if&lt;/span&gt; (context.Exception &lt;span class="kwrd"&gt;is&lt;/span&gt; BusinessException)
            {
                &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; HttpResponseException(&lt;span class="kwrd"&gt;new&lt;/span&gt; HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = &lt;span class="kwrd"&gt;new&lt;/span&gt; StringContent(context.Exception.Message),
                    ReasonPhrase = &lt;span class="str"&gt;&amp;quot;Exception&amp;quot;&lt;/span&gt;
                });

            }&lt;br /&gt;
            //Log Critical errors&lt;br /&gt;            Debug.WriteLine(context.Exception);

            &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; HttpResponseException(&lt;span class="kwrd"&gt;new&lt;/span&gt; HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = &lt;span class="kwrd"&gt;new&lt;/span&gt; StringContent(&lt;span class="str"&gt;&amp;quot;An error occurred, please try again or contact the administrator.&amp;quot;&lt;/span&gt;),
                ReasonPhrase = &lt;span class="str"&gt;&amp;quot;Critical Exception&amp;quot;&lt;/span&gt;
            });
        }
    }&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Note: Something to have in mind is that the ExceptionFilterAttribute will be ignored if the ApiController action method throws a HttpResponseException.
      &lt;br /&gt;&lt;/em&gt;&lt;/strong&gt;

  &lt;br /&gt;The code above will always make sure a HttpResponseExceptions will be returned, it will also make sure the critical exceptions will show a more user friendly message. The OnException method can also be used to log exceptions.&lt;/p&gt;

&lt;p&gt;By using a ExceptionFilterAttribute the Get() method in the previous example can now look like this:&lt;/p&gt;

&lt;p&gt;
  &lt;br /&gt;

  &lt;pre class="csharpcode"&gt;        &lt;span class="kwrd"&gt;public&lt;/span&gt; IEnumerable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; Get()
        {
                DoSomething();

                &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt;[] { &lt;span class="str"&gt;&amp;quot;value1&amp;quot;&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;value2&amp;quot;&lt;/span&gt; };
        }&lt;/pre&gt;
  &lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

  &lt;br /&gt;To use the an ExceptionFilterAttribute, we can for example add the ExceptionFilterAttribute to our ApiControllers methods or to the ApiController class definition, or register it globally for all ApiControllers. You can read more about is &lt;a href="http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling" target="_blank"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Note: If something goes wrong in the ExceptionFilterAttribute and an exception is thrown that is not of type HttpResponseException, a formatted exception will be thrown with stack trace etc to the client.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;strong&gt;
  &lt;p&gt;
    &lt;br /&gt;&lt;/p&gt;
  &lt;strong&gt;How about using a custom IHttpActionInvoker?&lt;/strong&gt;&lt;/strong&gt;

&lt;p&gt;We can create our own IHTTPActionInvoker and add Exception handling to the invoker. The IHttpActionInvoker will be used to invoke the ApiController’s ExecuteAsync method. Here is an example where the default IHttpActionInvoker, ApiControllerActionInvoker, is used to add exception handling:
  &lt;br /&gt;&lt;/p&gt;

&lt;p&gt;
  &lt;br /&gt;

  &lt;pre class="csharpcode"&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; MyApiControllerActionInvoker : ApiControllerActionInvoker
    {
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; Task&amp;lt;HttpResponseMessage&amp;gt; InvokeActionAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken)
        {
            var result = &lt;span class="kwrd"&gt;base&lt;/span&gt;.InvokeActionAsync(actionContext, cancellationToken);

            &lt;span class="kwrd"&gt;if&lt;/span&gt; (result.Exception != &lt;span class="kwrd"&gt;null&lt;/span&gt; &amp;amp;&amp;amp; result.Exception.GetBaseException() != &lt;span class="kwrd"&gt;null&lt;/span&gt;)
            {
                var baseException = result.Exception.GetBaseException();

                &lt;span class="kwrd"&gt;if&lt;/span&gt; (baseException &lt;span class="kwrd"&gt;is&lt;/span&gt; BusinessException)
                {
                    &lt;span class="kwrd"&gt;return&lt;/span&gt; Task.Run&amp;lt;HttpResponseMessage&amp;gt;(() =&amp;gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; HttpResponseMessage(HttpStatusCode.InternalServerError)
                                                                {
                                                                    Content = &lt;span class="kwrd"&gt;new&lt;/span&gt; StringContent(baseException.Message),
                                                                    ReasonPhrase = &lt;span class="str"&gt;&amp;quot;Error&amp;quot;&lt;/span&gt;

                                                                });
                }
                &lt;span class="kwrd"&gt;else&lt;/span&gt;
                {
                    &lt;span class="rem"&gt;//Log critical error&lt;/span&gt;
                    Debug.WriteLine(baseException);

                    &lt;span class="kwrd"&gt;return&lt;/span&gt; Task.Run&amp;lt;HttpResponseMessage&amp;gt;(() =&amp;gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; HttpResponseMessage(HttpStatusCode.InternalServerError)
                    {
                        Content = &lt;span class="kwrd"&gt;new&lt;/span&gt; StringContent(baseException.Message),
                        ReasonPhrase = &lt;span class="str"&gt;&amp;quot;Critical Error&amp;quot;&lt;/span&gt;
                    });
                }
            }

            &lt;span class="kwrd"&gt;return&lt;/span&gt; result;
        }
    }&lt;/pre&gt;
  &lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

  &lt;br /&gt;

  &lt;br /&gt;You can register the IHttpActionInvoker with your own IoC to resolve the MyApiContollerActionInvoker, or add it in the Global.asax:

  &lt;br /&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;GlobalConfiguration.Configuration.Services.Remove(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(IHttpActionInvoker), GlobalConfiguration.Configuration.Services.GetActionInvoker());

GlobalConfiguration.Configuration.Services.Add(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(IHttpActionInvoker), &lt;span class="kwrd"&gt;new&lt;/span&gt; MyApiControllerActionInvoker());&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How about using a Message Handler for Exception Handling?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;By creating a custom Message Handler, we can handle error after the ApiController and the ExceptionFilterAttribute is invoked and in that way create a global exception handler, BUT, the only thing we can take a look at is the &lt;a href="http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&amp;amp;l=EN-US&amp;amp;k=k(System.Net.Http.HttpResponseMessage);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&amp;amp;rd=true" target="_blank"&gt;HttpResponseMessage&lt;/a&gt;, we can’t add a try catch around the Message Handler’s SendAsync method. The last Message Handler that will be used in the Wep API pipe-line is the &lt;a href="http://msdn.microsoft.com/en-us/library/system.web.http.dispatcher.httpcontrollerdispatcher(v=vs.108).aspx" target="_blank"&gt;HttpControllerDispatcher&lt;/a&gt; and this Message Handler is added to the &lt;a href="http://msdn.microsoft.com/en-us/library/system.web.http.httpserver(v=vs.108).aspx" target="_blank"&gt;HttpServer&lt;/a&gt; in an early stage. The HttpControllerDispatcher will use the IHttpActionInvoker to invoke the ApiController method. The HttpControllerDipatcher has a try catch that will turn ALL exceptions into a HttpResponseMessage, so that is the reason why a try catch around the SendAsync in a custom Message Handler want help us. If we create our own Host for the Wep API we could create our own custom HttpControllerDispatcher and add or exception handler to that class, but that would be little tricky but is possible.&lt;/p&gt;

&lt;p&gt;We can in a Message Handler take a look at the HttpResponseMessage’s IsSuccessStatusCode property to see if the request has failed and if we throw the HttpResponseException in our ApiControllers, we could use the HttpResponseException and give it a Reason Phrase and use that to identify business exceptions or critical exceptions.&lt;/p&gt;

&lt;p&gt;I wouldn’t add an exception handler into a Message Handler, instead I should use the ExceptionFilterAttribute and register it globally for all ApiControllers. BUT, now to another interesting issue. What will happen if we have a Message Handler that throws an exception?&amp;#160; Those exceptions will not be catch and handled by the ExceptionFilterAttribute.&lt;/p&gt;

&lt;p&gt;I found a&amp;#160; bug in my previews blog post about “&lt;a href="http://weblogs.asp.net/fredriknormen/archive/2012/06/09/log-message-request-and-response-in-asp-net-webapi.aspx" target="_blank"&gt;Log message Request and Response in ASP.NET WebAPI&lt;/a&gt;” in the MessageHandler I use to log incoming and outgoing messages. Here is the code from my blog before I fixed the bug:&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; MessageHandler : DelegatingHandler
    {
        &lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; async Task&amp;lt;HttpResponseMessage&amp;gt; SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var corrId = &lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;&amp;quot;{0}{1}&amp;quot;&lt;/span&gt;, DateTime.Now.Ticks, Thread.CurrentThread.ManagedThreadId);
            var requestInfo = &lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;&amp;quot;{0} {1}&amp;quot;&lt;/span&gt;, request.Method, request.RequestUri);

            var requestMessage = await request.Content.ReadAsByteArrayAsync();

            await IncommingMessageAsync(corrId, requestInfo, requestMessage);

            var response = await &lt;span class="kwrd"&gt;base&lt;/span&gt;.SendAsync(request, cancellationToken);

            var responseMessage = await response.Content.ReadAsByteArrayAsync();

            await OutgoingMessageAsync(corrId, requestInfo, responseMessage);

            &lt;span class="kwrd"&gt;return&lt;/span&gt; response;
        }


        &lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; Task IncommingMessageAsync(&lt;span class="kwrd"&gt;string&lt;/span&gt; correlationId, &lt;span class="kwrd"&gt;string&lt;/span&gt; requestInfo, &lt;span class="kwrd"&gt;byte&lt;/span&gt;[] message);
        &lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; Task OutgoingMessageAsync(&lt;span class="kwrd"&gt;string&lt;/span&gt; correlationId, &lt;span class="kwrd"&gt;string&lt;/span&gt; requestInfo, &lt;span class="kwrd"&gt;byte&lt;/span&gt;[] message);
    }&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;If a ApiController throws a HttpResponseException, the Content property of the HttpResponseMessage from the SendAsync will be NULL. So a null reference exception is thrown within the MessageHandler. The yellow screen of death will be returned to the client, and the content is HTML and the Http status code is 500. The bug in the MessageHandler was solved by adding a check against the HttpResponseMessage’s IsSuccessStatusCode property:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; MessageHandler : DelegatingHandler
    {
        &lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; async Task&amp;lt;HttpResponseMessage&amp;gt; SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var corrId = &lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;&amp;quot;{0}{1}&amp;quot;&lt;/span&gt;, DateTime.Now.Ticks, Thread.CurrentThread.ManagedThreadId);
            var requestInfo = &lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;&amp;quot;{0} {1}&amp;quot;&lt;/span&gt;, request.Method, request.RequestUri);

            var requestMessage = await request.Content.ReadAsByteArrayAsync();

            await IncommingMessageAsync(corrId, requestInfo, requestMessage);

            var response = await &lt;span class="kwrd"&gt;base&lt;/span&gt;.SendAsync(request, cancellationToken);

            &lt;span class="kwrd"&gt;byte&lt;/span&gt;[] responseMessage;

            &lt;span class="kwrd"&gt;if&lt;/span&gt; (response.IsSuccessStatusCode)
                responseMessage = await response.Content.ReadAsByteArrayAsync();
            &lt;span class="kwrd"&gt;else&lt;/span&gt;
                responseMessage = Encoding.UTF8.GetBytes(response.ReasonPhrase);

            await OutgoingMessageAsync(corrId, requestInfo, responseMessage);

            &lt;span class="kwrd"&gt;return&lt;/span&gt; response;
        }


        &lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; Task IncommingMessageAsync(&lt;span class="kwrd"&gt;string&lt;/span&gt; correlationId, &lt;span class="kwrd"&gt;string&lt;/span&gt; requestInfo, &lt;span class="kwrd"&gt;byte&lt;/span&gt;[] message);
        &lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; Task OutgoingMessageAsync(&lt;span class="kwrd"&gt;string&lt;/span&gt; correlationId, &lt;span class="kwrd"&gt;string&lt;/span&gt; requestInfo, &lt;span class="kwrd"&gt;byte&lt;/span&gt;[] message);
    }&lt;br /&gt;&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;
  &lt;br /&gt;If we don’t handle the exceptions that can occur in a custom Message Handler, we can have a hard time to find the problem causing the exception. The savior in this case is the Global.asax’s Application_Error:

  &lt;br /&gt;&lt;/p&gt;



&lt;pre class="csharpcode"&gt;        &lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Application_Error()
        {
            var exception = Server.GetLastError();

            Debug.WriteLine(exception);
        }&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;
  &lt;br /&gt;I would recommend you to add the Application_Error to the Global.asax and log all exceptions to make sure all kind of exception is handled.&lt;/p&gt;

&lt;p&gt;
  &lt;br /&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;There are different ways we could add Exception Handling to the Wep API, we can use a custom ApiController, ExceptionFilterAttribute, IHttpActionInvoker or Message Handler. The ExceptionFilterAttribute would be a good place to add a global exception handling, require very few modification, just register it globally for all ApiControllers, even the IHttpActionInvoker can be used to minimize the modifications of files. Adding the Application_Error to the global.asax is a good way to catch all unhandled exception that can occur, for example exception thrown in a Message Handler.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;If you want to know when I have posted a blog post, you can follow me on twitter &lt;a href="http://twitter.com/#!/fredrikn" target="_blank"&gt;@fredrikn&lt;/a&gt;&lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=8596653" width="1" height="1"&gt;</description><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/ASP.Net/default.aspx">ASP.Net</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/.Net/default.aspx">.Net</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/WebApi/default.aspx">WebApi</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/ASP.Net+WebApi/default.aspx">ASP.Net WebApi</category></item><item><title>Log message Request and Response in ASP.NET WebAPI</title><link>http://weblogs.asp.net/fredriknormen/archive/2012/06/09/log-message-request-and-response-in-asp-net-webapi.aspx</link><pubDate>Sat, 09 Jun 2012 10:54:00 GMT</pubDate><guid isPermaLink="false">c06e2b9d-981a-45b4-a55f-ab0d8bbfdc1c:8588689</guid><dc:creator>Fredrik N</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://weblogs.asp.net/fredriknormen/rsscomments.aspx?PostID=8588689</wfw:commentRss><comments>http://weblogs.asp.net/fredriknormen/archive/2012/06/09/log-message-request-and-response-in-asp-net-webapi.aspx#comments</comments><description>&lt;p&gt;By logging both incoming and outgoing messages for services can be useful in many scenarios, such as debugging, tracing, inspection and helping customers with request problems etc.&amp;nbsp; I have a customer that need to have both incoming and outgoing messages to be logged. They use the information to see strange behaviors and also to help customers when they call in&amp;nbsp; for help (They can by looking in the log see if the customers sends in data in a wrong or strange way).&lt;/p&gt;    &lt;p&gt;&lt;strong&gt;Concerns&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Most loggings in applications are cross-cutting concerns and should not be&amp;nbsp; a core concern for developers. Logging messages like this:&lt;/p&gt;    &lt;pre class="csharpcode"&gt;        &lt;span class="rem"&gt;// GET api/values/5&lt;/span&gt;
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Get(&lt;span class="kwrd"&gt;int&lt;/span&gt; id)
        {
            &lt;span class="rem"&gt;//Cross-cutting concerns&lt;/span&gt;
            Log(&lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;"Request: GET api/values/{0}"&lt;/span&gt;, id));

            &lt;span class="rem"&gt;//Core-concern&lt;/span&gt;
            var response = DoSomething();

            &lt;span class="rem"&gt;//Cross-cutting concerns&lt;/span&gt;
            Log(&lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;"Reponse: GET api/values/{0}\r\n{1}"&lt;/span&gt;, id, response));

            &lt;span class="kwrd"&gt;return&lt;/span&gt; response;
        }&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;
  &lt;br&gt;will only result in duplication of code, and unnecessarily concerns for the developers to be aware of, if they miss adding the logging code, no logging will take place. Developers should focus on the core-concern, not the cross-cutting concerns. By just focus on the core-concern the above code will look like this:

  &lt;br&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;        &lt;span class="rem"&gt;// GET api/values/5&lt;/span&gt;
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Get(&lt;span class="kwrd"&gt;int&lt;/span&gt; id)
        {
            &lt;span class="kwrd"&gt;return&lt;/span&gt; DoSomething();
        }&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;
  &lt;br&gt;The logging should then be placed somewhere else so the developers doesn’t need to focus care about the cross-concern.

  &lt;br&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Using Message Handler for logging
    &lt;br&gt;

    &lt;br&gt;&lt;/strong&gt;There are different ways we could place the cross-cutting concern of logging message when using WebAPI. We can for example create a custom ApiController and override the ApiController’s ExecutingAsync method, or add a ActionFilter, or use a Message Handler. The disadvantage with custom ApiController is that we need to make sure we inherit from it, the disadvantage of ActionFilter, is that we need to add the filter to the controllers, both will modify our ApiControllers. By using a Message Handler we don’t need to do any changes to our ApiControllers. So the best suitable place to add our logging would be in a custom Message Handler. A Message Handler will be used before the HttpControllerDispatcher (The part in the WepAPI pipe-line that make sure the right controller is used and called etc).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Note: You can read more about message handlers &lt;/em&gt;&lt;/strong&gt;&lt;a href="http://www.asp.net/web-api/overview/working-with-http/http-message-handlers" target="_blank" mce_href="http://www.asp.net/web-api/overview/working-with-http/http-message-handlers"&gt;&lt;strong&gt;&lt;em&gt;here&lt;/em&gt;&lt;/strong&gt;&lt;/a&gt;&lt;strong&gt;&lt;em&gt;, it will give you a good understanding of the WebApi pipe-line.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To create a Message Handle we can inherit from the &lt;a href="http://msdn.microsoft.com/en-us/library/system.net.http.delegatinghandler(v=vs.110).aspx" target="_blank" mce_href="http://msdn.microsoft.com/en-us/library/system.net.http.delegatinghandler(v=vs.110).aspx"&gt;DelegatingHandler&lt;/a&gt; class and override the SendAsync method:

  &lt;br&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; MessageHandler : DelegatingHandler
    {
        &lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; async Task&amp;lt;HttpResponseMessage&amp;gt; SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
           &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;base&lt;/span&gt;.SendAsync(request, cancellationToken);
        }
    }&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;



&lt;p&gt;If we skip the call to the base.SendAsync our ApiController’s methods will never be invoked, nor other Message Handlers. Everything placed before base.SendAsync will be called before the HttpControllerDispatcher (before WebAPI will take a look at the request which controller and method it should be invoke), everything after the base.SendAsync, will be executed after our ApiController method has returned a response. So a message handle will be a perfect place to add cross-cutting concerns such as logging.&lt;/p&gt;

&lt;p&gt;To get the content of our response within a Message Handler we can use the request argument of the SendAsync method. The request argument is of type &lt;a href="http://msdn.microsoft.com/en-us/library/system.net.http.httprequestmessage(v=vs.110).aspx" target="_blank" mce_href="http://msdn.microsoft.com/en-us/library/system.net.http.httprequestmessage(v=vs.110).aspx"&gt;HttpRequestMessage&lt;/a&gt; and has a &lt;a href="http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&amp;amp;l=EN-US&amp;amp;k=k(System.Net.Http.HttpRequestMessage.Content);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&amp;amp;rd=true" target="_blank" mce_href="http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&amp;amp;l=EN-US&amp;amp;k=k(System.Net.Http.HttpRequestMessage.Content);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&amp;amp;rd=true"&gt;Content property&lt;/a&gt; (Content is of type &lt;a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpcontent(v=vs.110)" target="_blank" mce_href="http://msdn.microsoft.com/en-us/library/system.net.http.httpcontent(v=vs.110)"&gt;HttpContent&lt;/a&gt;. The HttpContent has several method that can be used to read the incoming message, such as ReadAsStreamAsync, ReadAsByteArrayAsync and ReadAsStringAsync etc.&lt;/p&gt;

&lt;p&gt;Something to be aware of is what will happen when we read from the HttpContent. When we read from the HttpContent, we read from a stream, once we read from it, we can’t be read from it again. So if we read from the Stream before the base.SendAsync, the next coming Message Handlers and the HttpControllerDispatcher can’t read from the Stream because it’s already read, so our ApiControllers methods will never be invoked etc. The only way to make sure we can do repeatable reads from the HttpContent is to copy the content into a buffer, and then read from that buffer. This can be done by using the HttpContent’s &lt;a href="http://msdn.microsoft.com/en-us/library/hh138085(v=vs.110)" target="_blank" mce_href="http://msdn.microsoft.com/en-us/library/hh138085(v=vs.110)"&gt;LoadIntoBufferAsync&lt;/a&gt; method. If we make a call to the LoadIntoBufferAsync method before the base.SendAsync, the incoming stream will be read in to a byte array, and then other HttpContent read operations will read from that buffer if it’s exists instead directly form the stream. There is one method on the HttpContent that will internally make a call to the&amp;nbsp; LoadIntoBufferAsync for us, and that is the &lt;a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpcontent.readasbytearrayasync(v=vs.110)" target="_blank" mce_href="http://msdn.microsoft.com/en-us/library/system.net.http.httpcontent.readasbytearrayasync(v=vs.110)"&gt;ReadAsByteArrayAsync&lt;/a&gt;. This is the method we will use to read from the incoming and outgoing message.&lt;/p&gt;

&lt;p&gt;
  &lt;br&gt;

  &lt;br&gt;

  &lt;pre class="csharpcode"&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; MessageHandler : DelegatingHandler
    {
        &lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; async Task&amp;lt;HttpResponseMessage&amp;gt; SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var requestMessage = await request.Content.ReadAsByteArrayAsync();

            var response = await &lt;span class="kwrd"&gt;base&lt;/span&gt;.SendAsync(request, cancellationToken);

            var responseMessage = await response.Content.ReadAsByteArrayAsync();

            &lt;span class="kwrd"&gt;return&lt;/span&gt; response;
        }
    }&lt;/pre&gt;
  &lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

  &lt;br&gt;The above code will read the content of the incoming message and then call the SendAsync and after that read from the content of the response message.

&lt;p&gt;The following code will add more logic such as creating a correlation id to combine the request with the response, and create a log entry etc:&lt;/p&gt;

&lt;p&gt;
  &lt;br&gt;

  &lt;pre class="csharpcode"&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; MessageHandler : DelegatingHandler
    {
        &lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; async Task&amp;lt;HttpResponseMessage&amp;gt; SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var corrId = &lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;"{0}{1}"&lt;/span&gt;, DateTime.Now.Ticks, Thread.CurrentThread.ManagedThreadId);
            var requestInfo = &lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;"{0} {1}"&lt;/span&gt;, request.Method, request.RequestUri);

            var requestMessage = await request.Content.ReadAsByteArrayAsync();

            await IncommingMessageAsync(corrId, requestInfo, requestMessage);

            var response = await &lt;span class="kwrd"&gt;base&lt;/span&gt;.SendAsync(request, cancellationToken);

            &lt;font color="#000000"&gt;&lt;span class="kwrd"&gt;byte&lt;/span&gt;[] responseMessage;

            &lt;span class="kwrd"&gt;if&lt;/span&gt; (response.IsSuccessStatusCode)
                responseMessage = await response.Content.ReadAsByteArrayAsync();
            &lt;span class="kwrd"&gt;else&lt;/span&gt;
                responseMessage = Encoding.UTF8.GetBytes(response.ReasonPhrase);

            await OutgoingMessageAsync(corrId, requestInfo, responseMessage);

            &lt;/font&gt;&lt;span class="kwrd"&gt;return&lt;/span&gt; response;
        }


        &lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; Task IncommingMessageAsync(&lt;span class="kwrd"&gt;string&lt;/span&gt; correlationId, &lt;span class="kwrd"&gt;string&lt;/span&gt; requestInfo, &lt;span class="kwrd"&gt;byte&lt;/span&gt;[] message);
        &lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; Task OutgoingMessageAsync(&lt;span class="kwrd"&gt;string&lt;/span&gt; correlationId, &lt;span class="kwrd"&gt;string&lt;/span&gt; requestInfo, &lt;span class="kwrd"&gt;byte&lt;/span&gt;[] message);
    }



    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; MessageLoggingHandler : MessageHandler
    {
        &lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; async Task IncommingMessageAsync(&lt;span class="kwrd"&gt;string&lt;/span&gt; correlationId, &lt;span class="kwrd"&gt;string&lt;/span&gt; requestInfo, &lt;span class="kwrd"&gt;byte&lt;/span&gt;[] message)
        {
            await Task.Run(() =&amp;gt;
                Debug.WriteLine(&lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;"{0} - Request: {1}\r\n{2}"&lt;/span&gt;, correlationId, requestInfo, Encoding.UTF8.GetString(message))));
        }


        &lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; async Task OutgoingMessageAsync(&lt;span class="kwrd"&gt;string&lt;/span&gt; correlationId, &lt;span class="kwrd"&gt;string&lt;/span&gt; requestInfo, &lt;span class="kwrd"&gt;byte&lt;/span&gt;[] message)
        {
            await Task.Run(() =&amp;gt;
                Debug.WriteLine(&lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;"{0} - Response: {1}\r\n{2}"&lt;/span&gt;, correlationId, requestInfo, Encoding.UTF8.GetString(message))));
        }
    }&lt;/pre&gt;
  &lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;



&lt;p&gt;The code above will show the following in the Visual Studio output window when the “api/values” service (One standard controller added by the default WepAPI template) is requested with a Get http method :
  &lt;br&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;6347483479959544375 - Request: GET http:&lt;span class="rem"&gt;//localhost:3208/api/values&lt;/span&gt;

6347483479959544375 - Response: GET http:&lt;span class="rem"&gt;//localhost:3208/api/values&lt;/span&gt;
[&lt;span class="str"&gt;"value1"&lt;/span&gt;,&lt;span class="str"&gt;"value2"&lt;/span&gt;]&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;



&lt;p&gt;&lt;strong&gt;Register a Message Handler&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To register a Message handler we can use the Add method of the GlobalConfiguration.Configration.MessageHandlers in for example Global.asax:&lt;/p&gt;

&lt;p&gt;
  &lt;br&gt;

  &lt;pre class="csharpcode"&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; WebApiApplication : System.Web.HttpApplication
    {
        &lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Application_Start()
        {
           &lt;strong&gt; GlobalConfiguration.Configuration.MessageHandlers.Add(&lt;span class="kwrd"&gt;new&lt;/span&gt; MessageLoggingHandler());&lt;/strong&gt;
            &lt;/pre&gt;

  &lt;pre class="csharpcode"&gt;            ...&lt;/pre&gt;

  &lt;pre class="csharpcode"&gt;        }
    }&lt;/pre&gt;
  &lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;



&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;By using a Message Handler we can easily remove cross-cutting concerns like logging from our controllers.&lt;/p&gt;

&lt;p&gt;You can also find the source code used in this blog post on &lt;a href="http://www.forkcan.com/viewcode/1209/ASPNET-MVC-40-Web-API-Message-logger-for-Net-45" target="_blank" mce_href="http://www.forkcan.com/viewcode/1209/ASPNET-MVC-40-Web-API-Message-logger-for-Net-45"&gt;ForkCan.com&lt;/a&gt;, feel free to make a fork or add comments, such as making the code better etc.&lt;/p&gt;

&lt;p&gt;
  &lt;br&gt;Feel free to follow me on twitter &lt;a href="http://twitter.com/#!/fredrikn" target="_blank" mce_href="http://twitter.com/#!/fredrikn"&gt;@fredrikn&lt;/a&gt; if you want to know when I will write other blog posts etc.&lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=8588689" width="1" height="1"&gt;</description><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/ASP.Net/default.aspx">ASP.Net</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/WebApi/default.aspx">WebApi</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/ASP.Net+WebApi/default.aspx">ASP.Net WebApi</category></item><item><title>Visual Studio 2012 RC and Windows 8 Release Review is available for download</title><link>http://weblogs.asp.net/fredriknormen/archive/2012/05/31/visual-studio-2012-rc-and-windows-8-release-review-is-available-for-download.aspx</link><pubDate>Thu, 31 May 2012 20:11:00 GMT</pubDate><guid isPermaLink="false">c06e2b9d-981a-45b4-a55f-ab0d8bbfdc1c:8552537</guid><dc:creator>Fredrik N</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://weblogs.asp.net/fredriknormen/rsscomments.aspx?PostID=8552537</wfw:commentRss><comments>http://weblogs.asp.net/fredriknormen/archive/2012/05/31/visual-studio-2012-rc-and-windows-8-release-review-is-available-for-download.aspx#comments</comments><description>&lt;p&gt;Today Visual Studio 2012 RC is available for download at:&lt;/p&gt;&lt;p&gt;&lt;a href="http://www.microsoft.com/visualstudio/11/en-us/downloads#express-win8" mce_href="http://www.microsoft.com/visualstudio/11/en-us/downloads#express-win8"&gt;http://www.microsoft.com/visualstudio/11/en-us/downloads#express-win8&lt;/a&gt;&lt;/p&gt;&lt;p&gt;EF 5, MVC 4, WebApi and much more in the RC release.&amp;nbsp;&lt;/p&gt;&lt;p&gt;Widows 8 Release Review!&lt;/p&gt;&lt;p&gt;&lt;a href="http://blogs.msdn.com/b/b8/archive/2012/05/31/delivering-the-windows-8-release-preview.aspx" mce_href="http://blogs.msdn.com/b/b8/archive/2012/05/31/delivering-the-windows-8-release-preview.aspx"&gt;http://blogs.msdn.com/b/b8/archive/2012/05/31/delivering-the-windows-8-release-preview.aspx&lt;/a&gt;&lt;/p&gt;&lt;p&gt;ASP.NET MVC 4 RC for Visual Studio 2010 SP1&lt;/p&gt;&lt;p&gt;&lt;a href="http://www.microsoft.com/en-us/download/details.aspx?id=29935"&gt;http://www.microsoft.com/en-us/download/details.aspx?id=29935&lt;/a&gt;&amp;nbsp;&lt;/p&gt;&lt;p&gt;Happy coding!!&lt;br&gt;&lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=8552537" width="1" height="1"&gt;</description><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/ASP.Net/default.aspx">ASP.Net</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/Visual+Studio+2010/default.aspx">Visual Studio 2010</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/Windows+8/default.aspx">Windows 8</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/.Net+4.5/default.aspx">.Net 4.5</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/VIsual+Studio+2012/default.aspx">VIsual Studio 2012</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/MVC+4/default.aspx">MVC 4</category></item><item><title>Using Entity Framework 4.3 Database migration for any project</title><link>http://weblogs.asp.net/fredriknormen/archive/2012/02/15/using-entity-framework-4-3-database-migration-for-any-project.aspx</link><pubDate>Wed, 15 Feb 2012 13:22:22 GMT</pubDate><guid isPermaLink="false">c06e2b9d-981a-45b4-a55f-ab0d8bbfdc1c:8296862</guid><dc:creator>Fredrik N</dc:creator><slash:comments>10</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://weblogs.asp.net/fredriknormen/rsscomments.aspx?PostID=8296862</wfw:commentRss><comments>http://weblogs.asp.net/fredriknormen/archive/2012/02/15/using-entity-framework-4-3-database-migration-for-any-project.aspx#comments</comments><description>&lt;p&gt;In this blog post I’m going to write about the Entity Framework 4.3 Database migration and how to use it without using Code-First or Entity Framework as an OR-M at all.&lt;/p&gt;  &lt;p&gt;To get started just create a simple project, for example a Console Application. After that write the following in the Package Manager Console (In the Visual Studio menu, select View/Other Windows/Package Manager Console). Write the following and hit enter:&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;div id="codeSnippetWrapper"&gt;   &lt;div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"&gt;     &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;PM&amp;gt; Install-Package EntityFramework&lt;/pre&gt;
&lt;!--CRLF--&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;After the EntityFramework 4.3 is installed we need to enable the database migration. Only one project in our solution can be enabled. To enable migration just enter the following in the Package Manager Console:&lt;/p&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"&gt;
    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;PM&amp;gt; Enable-Migrations&lt;/pre&gt;
&lt;!--CRLF--&gt;&lt;/div&gt;
&lt;/div&gt;



&lt;p&gt;When this is done we will now have a folder in our project called Migrations. In this folder we will see Configuration.cs file (this file may showed up after you have enabled the migrations).&lt;/p&gt;

&lt;p&gt;In the Migrations folder we will add our database changes for the current version of our code. More about this later.&lt;/p&gt;

&lt;p&gt;Open the application configuration file and add a connection string:&lt;/p&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"&gt;
    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;&amp;lt;?&lt;/span&gt;&lt;span style="color: #800000"&gt;xml&lt;/span&gt; &lt;span style="color: #ff0000"&gt;version&lt;/span&gt;&lt;span style="color: #0000ff"&gt;=&amp;quot;1.0&amp;quot;&lt;/span&gt; &lt;span style="color: #ff0000"&gt;encoding&lt;/span&gt;&lt;span style="color: #0000ff"&gt;=&amp;quot;utf-8&amp;quot;&lt;/span&gt;?&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;configuration&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;  &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;configSections&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;    &lt;span style="color: #008000"&gt;&amp;lt;!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;    &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;section&lt;/span&gt; &lt;span style="color: #ff0000"&gt;name&lt;/span&gt;&lt;span style="color: #0000ff"&gt;=&amp;quot;entityFramework&amp;quot;&lt;/span&gt; &lt;span style="color: #ff0000"&gt;type&lt;/span&gt;&lt;span style="color: #0000ff"&gt;=&amp;quot;System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.3.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089&amp;quot;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;/&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;  &lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;configSections&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;&amp;#160;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;  &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;connectionStrings&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;    &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;add&lt;/span&gt; &lt;span style="color: #ff0000"&gt;name&lt;/span&gt;&lt;span style="color: #0000ff"&gt;=&amp;quot;BlogContext&amp;quot;&lt;/span&gt;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;         &lt;span style="color: #ff0000"&gt;providerName&lt;/span&gt;&lt;span style="color: #0000ff"&gt;=&amp;quot;System.Data.SqlClient&amp;quot;&lt;/span&gt;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;         &lt;span style="color: #ff0000"&gt;connectionString&lt;/span&gt;&lt;span style="color: #0000ff"&gt;=&amp;quot;Data Source=.;Initial Catalog=MyBlog;Persist Security Info=True;Integrated Security=true&amp;quot;&lt;/span&gt;&lt;span style="color: #0000ff"&gt;/&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;  &lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;connectionStrings&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;configuration&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;!--CRLF--&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;I gave the connection string the name “BlogContext”, I also use a database with the name MyBlog.
  &lt;br /&gt;

  &lt;br /&gt;If you use Entity Framework and code-first, Code-First can create a database for us based on our model. But this blog post will be about not using Entity Framework as the OR-M at all, instead I already have an existing database called “MyBlog”. This database has one table called “Blog” with two column, BlogId and Name:&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&lt;a href="http://weblogs.asp.net/blogs/fredriknormen/image_31812AB1.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://weblogs.asp.net/blogs/fredriknormen/image_thumb_1A72A975.png" width="271" height="159" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Note: The _MigrationHistory table as you can see in the image above is a table that will be created by EF 4.3 Database Migration to keep track of the migrations. It will use that table know the current state of the migration, only to make sure it knows which migrations that is in pending state (has not bean applied) etc.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This blog post pretends that we already have an earlier version of our program that works against the database schema above. Now in our new version we are going to add one new column for specifying when a Blog record is created.&lt;/p&gt;

&lt;p&gt;After our connection string is in place, we need to create a DbContext class. The EF 4.3 Database Migration needs a DbContext, we will just create an empty DbContext. By doing so we can use the EF 4.3 Database migration without using EF as our OR-M.&lt;/p&gt;

&lt;p&gt;Add a new class with the same name as the connection string, for example “BlogContext”, we must make sure it will inherit from the DbContext class:&lt;/p&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"&gt;
    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;namespace&lt;/span&gt; ConsoleApplication6.Model&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;{&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;    &lt;span style="color: #0000ff"&gt;using&lt;/span&gt; System.Data.Entity;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;&amp;#160;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; BlogContext : DbContext&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;    {&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;    }&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;}&lt;/pre&gt;
&lt;!--CRLF--&gt;&lt;/div&gt;
&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;&lt;em&gt;Note: EF will by default try to locate a connection string with the same name as our DbContext class.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When this is done we need to open the Configuration.cs file located in the earlier created Migrations folder. We need to specify that the configuration of the migration should use our BlogContext, we do that by using the DbMigrationsConfiguration&amp;lt;T&amp;gt; and specify that the T is our BlogContext. The configuration class is used to configure the database migration, it also need to know which database it should work against etc. This is done by specifying a DbContext and in our case our BlogContext:
  &lt;br /&gt;&lt;/p&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"&gt;
    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;namespace&lt;/span&gt; ConsoleApplication6.Migrations&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;{&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;    &lt;span style="color: #0000ff"&gt;using&lt;/span&gt; System.Data.Entity.Migrations;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;&amp;#160;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;    &lt;span style="color: #0000ff"&gt;using&lt;/span&gt; ConsoleApplication6.Model;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;&amp;#160;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;    &lt;span style="color: #0000ff"&gt;internal&lt;/span&gt; &lt;span style="color: #0000ff"&gt;sealed&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; Configuration : DbMigrationsConfiguration&amp;lt;BlogContext&amp;gt;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;    {&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;        &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; Configuration()&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;        {&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;            AutomaticMigrationsEnabled = &lt;span style="color: #0000ff"&gt;false&lt;/span&gt;;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;        }&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;    }&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;}&lt;/pre&gt;
&lt;!--CRLF--&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Note: The AutomaticMigrationsEnabled is set to false by default, if we use Code-First and want to let the migration tool automatically handle migrations, we can enable it and just add the changes to our Model, and the migration will check for the changes and do migration based on it, here is more information about it: &lt;/em&gt;&lt;/strong&gt;&lt;a href="http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-automatic-migrations-walkthrough.aspx"&gt;&lt;strong&gt;&lt;em&gt;EF 4.3 Automatic Migration&lt;/em&gt;&lt;/strong&gt;&lt;/a&gt;&lt;strong&gt;&lt;em&gt;. But in this example we will handle the migration manually.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;There is Seed( xxx ) method added to the Configuration file, by using that method we can for example use it to fill/seed our database with data after a migration. I have removed that method because in this example we will not use it.&lt;/p&gt;

&lt;p&gt;Now when all the basic configuration of our Migration is setup, we can start adding a migration. We do that by using the command “Add-Migration”. In this example we will add a new column to our Blog table called “Created”. So in the Package Console Manager we write:&lt;/p&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"&gt;
    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;PM&amp;gt; Add-Migration AddBlogCreated&lt;/pre&gt;
&lt;!--CRLF--&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;We will now have a file added to the Migrations folder with the name “AddBlogCreated.cs” and the file will also have a timestamp as a prefix, this is used to know the order the migration should taka place. A Migration file will have two methods, Up and Down. The Up method will be used to specify what changes the current version of our application need to apply to the database, the Down is used to reverse the changes we have added to the Up method. When EF 4.3 Database Migration will update the database, it will run all migration in the timestamp order, and only those that haven’t been used since the last update (The _MigrationHistory table know about which migration that was last used). The Up method of all migrations will be called and do the changes we have specified to the database. If we decide to go back to a previous migration, the Down method will be called to redo the changes in a revers order.&lt;/p&gt;

&lt;p&gt;By using the AddColumn method in the migration file, we can easy add columns to our database, by using the RemoveColumn, we can remove a column that is added. The following example adds a column to the “Blog” table with the name “Created” and specify that it’s a DateTime, it will also remove the column if the migration is reversed.
  &lt;br /&gt;&lt;/p&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"&gt;
    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;namespace&lt;/span&gt; ConsoleApplication6.Migrations&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;{&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;    &lt;span style="color: #0000ff"&gt;using&lt;/span&gt; System.Data.Entity.Migrations;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;    &lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;partial&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; AddBlogCreated : DbMigration&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;    {&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;        &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;override&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Up()&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;        {&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;            AddColumn(&lt;span style="color: #006080"&gt;&amp;quot;Blog&amp;quot;&lt;/span&gt;, &lt;span style="color: #006080"&gt;&amp;quot;Created&amp;quot;&lt;/span&gt;, c =&amp;gt; c.DateTime());&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;        }&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;&amp;#160;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;        &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;override&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Down()&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;        {&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;            DropColumn(&lt;span style="color: #006080"&gt;&amp;quot;Blog&amp;quot;&lt;/span&gt;, &lt;span style="color: #006080"&gt;&amp;quot;Created&amp;quot;&lt;/span&gt;);&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;        }&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;    }&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;}&lt;/pre&gt;
&lt;!--CRLF--&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;When specifying the column type we can also specify if the column is nullable or has a default value etc.&lt;/p&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"&gt;
    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;AddColumn(&lt;span style="color: #006080"&gt;&amp;quot;Blog&amp;quot;&lt;/span&gt;, &lt;span style="color: #006080"&gt;&amp;quot;Created&amp;quot;&lt;/span&gt;, c =&amp;gt; c.DateTime(nullable:&lt;span style="color: #0000ff"&gt;false&lt;/span&gt;, defaultValueSql:&lt;span style="color: #006080"&gt;&amp;quot;GetDate()&amp;quot;&lt;/span&gt;));&lt;/pre&gt;
&lt;!--CRLF--&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;We can also use pure SQL in the migration class by using the Sql method:&lt;/p&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"&gt;
    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;override&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Up()&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;{&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;   AddColumn(&lt;span style="color: #006080"&gt;&amp;quot;Posts&amp;quot;&lt;/span&gt;, &lt;span style="color: #006080"&gt;&amp;quot;Abstract&amp;quot;&lt;/span&gt;, c =&amp;gt; c.String());&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;&amp;#160;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;   Sql(&lt;span style="color: #006080"&gt;&amp;quot;UPDATE Posts SET Abstract = LEFT(Content, 100) WHERE Abstract IS NULL&amp;quot;&lt;/span&gt;);&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;}&lt;/pre&gt;
&lt;!--CRLF--&gt;&lt;/div&gt;
&lt;/div&gt;









&lt;p&gt;Other method that can be used are for example: RenameTable, RenameColumn, CreateTable add and remove index etc.&lt;/p&gt;

&lt;p&gt;Now when we have added our AddBlogCreted migration to just simply add a new column, we want to run our migration. We can do it by using the Update-Database command in the Package Manager Console:&lt;/p&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"&gt;
    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;PM&amp;gt; Update-Database&lt;/pre&gt;
&lt;!--CRLF--&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The Update-Database will now execute all migrations that is added and not “executed” since last update. The timestamp prefix of the migration files as mentioned earlier is used to execute the migration in a correct order. If we run this command we will now have a new column called “Created” in our Blog table.&lt;/p&gt;

&lt;p&gt;If we also want to see the SQL of the migration we can add the –Verbose parameter after the Update-Database:&lt;/p&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"&gt;
    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;PM&amp;gt; Update-Database -Verbose&lt;/pre&gt;
&lt;!--CRLF--&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;To go to a specific migration, we can use the Update-Database and use the –TargetMigration parameter, for example:&lt;/p&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"&gt;
    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;PM&amp;gt; Update-Database –TargetMigration:&lt;span style="color: #006080"&gt;&amp;quot;AddBlogCreated&amp;quot;&lt;/span&gt;&lt;/pre&gt;
&lt;!--CRLF--&gt;&lt;/div&gt;
&lt;/div&gt;



&lt;p&gt;This will take us to the “AddBlogCreated” migration state. At the moment we are at this state so nothing will happen. We can try it by going back to a previous state, because we only have one migration we need to back to the first state of the migration (initial state), this is done by set the –TargetMigration value to “$InitialDatabase”:&lt;/p&gt;

&lt;p&gt;
  &lt;br /&gt;

  &lt;div id="codeSnippetWrapper"&gt;
    &lt;div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"&gt;
      &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;PM&amp;gt; Update-Database –TargetMigration:$InitialDatabase&lt;/pre&gt;
&lt;!--CRLF--&gt;&lt;/div&gt;
  &lt;/div&gt;
&lt;/p&gt;

&lt;p&gt;When we run the command above, we can see in the Package Manager Console that our AddBlogCreated migration is reverted. If we look at our database we can see that our Created column is removed. Now if run the Update-Database command and sets the –TargetMigration to “AddBlogCreated”, we now moves to the “AddBlogCreated” migration state and our Created column is now added.&lt;/p&gt;

&lt;p&gt;We can also execute the Update-Database command and get SQL script and pending migrations etc from code. This can be done by using the DbMigrator class and the MigratorScriptingDecorator etc. Here is an example where a migration is updated and the SQL script is displayed in a Console application:&lt;/p&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"&gt;
    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;class&lt;/span&gt; Program&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;{&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;   &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Main(&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;[] args)&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;   {&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;      var configuration = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Configuration();&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;      var migrator = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; DbMigrator(configuration);&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;&amp;#160;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;      var scriptor = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; MigratorScriptingDecorator(migrator);&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;      var script = scriptor.ScriptUpdate(sourceMigration: &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;, targetMigration: &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;);&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;      Console.WriteLine(script);&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;           &lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;      migrator.Update();&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;           &lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;      var pending = migrator.GetPendingMigrations();&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;&amp;#160;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;      Console.ReadLine();&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;&amp;#160;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;   }&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"&gt;}&lt;/pre&gt;
&lt;!--CRLF--&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In this blog post we have seen how we can use the new Entity Framework 4.3 Database Migration and use it without even use Entity Framework as our OR-M. We have seen how to install and configure the migration, also how to apply a migration and reverse it.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Ps. If you want to know when I post another blog post, please follow me on twitter &lt;a href="http://twitter.com/#!/fredrikn"&gt;@fredrikn&lt;/a&gt;&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=8296862" width="1" height="1"&gt;</description><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/.NET+4.0/default.aspx">.NET 4.0</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/Entity+Framework/default.aspx">Entity Framework</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/Database+Migration/default.aspx">Database Migration</category></item><item><title>Build, first day</title><link>http://weblogs.asp.net/fredriknormen/archive/2011/09/14/build-first-day.aspx</link><pubDate>Wed, 14 Sep 2011 13:21:00 GMT</pubDate><guid isPermaLink="false">c06e2b9d-981a-45b4-a55f-ab0d8bbfdc1c:7952346</guid><dc:creator>Fredrik N</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://weblogs.asp.net/fredriknormen/rsscomments.aspx?PostID=7952346</wfw:commentRss><comments>http://weblogs.asp.net/fredriknormen/archive/2011/09/14/build-first-day.aspx#comments</comments><description> 

It was an interesting day at the Microsoft Build Conference. I will in this blog post share some of the things that were presented during the first Keynote and big screen day.
&lt;br&gt;&lt;br&gt;The keynote started to present Windows 8, and the Metro (The new GUI). Focus was on the new user experience and UI. As many of you have probably already seen, the UI is similar to Windows Phone 7 and is created for touch. The idea of the Metro UI is to bring everything in front of the user, easy to find what they want and need.

Microsoft wanted to make Windows 7 even better. Everything that runs on Windows 7 runs on Windows 8.&lt;br&gt;&lt;br&gt;They reimage Windows to experience a new range of capabilities, scenarios, and factors. Windows 8 uses about 281 Mb memories and in the size an antivirus program is also running.


One feature I like the most was the Spell Checking through the whole system
Windows 8 will be a great new platform for developers.&lt;br&gt;&lt;br&gt;Developers can use the new WinRT API to build great apps, they can use different kind of languages, like HTML/CSS and Java-script, XAML and C# or VB, C or C++. The interesting part is HTML and Java-script. It will make it much easier to move web developers into writing Mobile apps and Windows 8 apps in an easy way.


App developers want rich connectivity and sharing capabilities, connection to customers. Reach every customer using Windows. Touch will be the future, and the WinRT deliver it all. Developer can use the WinRT APIs for Communication &amp;amp; Data, Graphics &amp;amp; Media, Devices and Printing. 


Contracts can be used to make app communicate with each other, an example of an Contract is the "Search Contract", that can be used to hook up an app into the Windows 8 "search engine". There are different ways apps can communicate with each other, loacaly, Scheduled or with Push (using Windows Push Notification WSN). With Tiles developer can extend the apps with information instead of using an icon.&lt;br&gt;&lt;br&gt;Developers will get a set of great of tools for writing Windows 8 apps. With Visual Studio 11 and Expression Blend 5, developers can be up and running in a short time by using predefined templates. Expression Blend 5 will now handle HTML and Java-script, and Blend is now integrated into Visual Studio 11. Visual Studio 11 also has a simulation feature when it comes to debugging, so developers could select for example a Slate and hit debug, and a simulation of a Slate will appear.

&lt;br&gt;&lt;br&gt;The new platform will have a great set of Could Services to make it easier to share images etc with friends over the cloud, apps working together. Apps are connected to each other and the cloud. Pull information from other apps. A tiny API can be used for this for developers.


Microsoft will also give developers and customers access to Windows Store, it will make it much easier to buy and sell apps. This will probably also boost and increase development of apps for Windows 8. Within Visual Studio 11, developers can easily package apps and publish them to the Windows Store; they just use the Store menu in Visual Studio 11.&lt;br&gt;&lt;br&gt;Everyone at Build got a Developer Preview of Samsung’s iCore5 Slate with a Developer Preview of Windows 8, Expression Blend 5 and Visual Studio 11 Express. So now the fun can begin.


You can download the bits by yourself at the Windows developer center: &lt;a href="http://dev.windows.com" mce_href="http://dev.windows.com"&gt;http://dev.windows.com&lt;/a&gt;. If you follow me on twitter (&lt;a href="http://www.twitter.com/fredrikn" mce_href="http://www.twitter.com/fredrikn"&gt;@fredrikn&lt;/a&gt;), you can read more about what will be presented during the conference. Tomorrow there will be a keynote, and then a lot of sessions, I will probably attend the HTML5 sessions and some other sessions like ASP.NET 4.5 and C# 5 etc.&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=7952346" width="1" height="1"&gt;</description><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/HTML/default.aspx">HTML</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/Javascript/default.aspx">Javascript</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/Build/default.aspx">Build</category><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/Windows+8/default.aspx">Windows 8</category></item><item><title>Update on ASP.NET Vulnerability</title><link>http://weblogs.asp.net/fredriknormen/archive/2010/09/25/update-on-asp-net-vulnerability.aspx</link><pubDate>Sat, 25 Sep 2010 07:15:36 GMT</pubDate><guid isPermaLink="false">c06e2b9d-981a-45b4-a55f-ab0d8bbfdc1c:7620144</guid><dc:creator>Fredrik N</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://weblogs.asp.net/fredriknormen/rsscomments.aspx?PostID=7620144</wfw:commentRss><comments>http://weblogs.asp.net/fredriknormen/archive/2010/09/25/update-on-asp-net-vulnerability.aspx#comments</comments><description>&lt;p&gt;Scott Guthrie updated his blog with more info about the ASP.NTE Vulnerability, check it out here: &lt;a title="http://weblogs.asp.net/scottgu/archive/2010/09/24/update-on-asp-net-vulnerability.aspx" href="http://weblogs.asp.net/scottgu/archive/2010/09/24/update-on-asp-net-vulnerability.aspx"&gt;http://weblogs.asp.net/scottgu/archive/2010/09/24/update-on-asp-net-vulnerability.aspx&lt;/a&gt;&lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=7620144" width="1" height="1"&gt;</description><category domain="http://weblogs.asp.net/fredriknormen/archive/tags/ASP.Net/default.aspx">ASP.Net</category></item><item><title>Vulnerability in ASP.Net</title><link>http://weblogs.asp.net/fredriknormen/archive/2010/09/18/vulnerability-in-asp-net.aspx</link><pubDate>Sat, 18 Sep 2010 08:18:58 GMT</pubDate><guid isPermaLink="false">c06e2b9d-981a-45b4-a55f-ab0d8bbfdc1c:7614584</guid><dc:creator>Fredrik N</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://weblogs.asp.net/fredriknormen/rsscomments.aspx?PostID=7614584</wfw:commentRss><comments>http://weblogs.asp.net/fredriknormen/archive/2010/09/18/vulnerability-in-asp-net.aspx#comments</comments><description>&lt;p&gt;I would recommend all of you who are managed ASP.Net application to read this:&lt;/p&gt;  &lt;p&gt;&lt;a title="http://blogs.technet.com/b/msrc/archive/2010/09/17/security-advisory-2416728-released.aspx" href="http://blogs.technet.com/b/msrc/archive/2010/09/17/security-advisory-2416728-released.aspx"&gt;http://blogs.technet.com/b/msrc/archive/2010/09/17/security-advisory-2416728-released.aspx&lt;/a&gt;&lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=7614584" width="1" height="1"&gt;</description></item></channel></rss>