<?xml version="1.0"?>
<rss version="2.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:media="http://search.yahoo.com/mrss/" xmlns:yt="http://gdata.youtube.com/schemas/2007" xmlns:atom="http://www.w3.org/2005/Atom">
   <channel>
      <title>Superexpert Blog</title>
      <description>Pipes Output</description>
      <link>http://pipes.yahoo.com/pipes/pipe.info?_id=874ca9249aa4965241676885c8cac652</link>
      <atom:link rel="next" href="http://pipes.yahoo.com/pipes/pipe.run?_id=874ca9249aa4965241676885c8cac652&amp;_render=rss&amp;page=2"/>
      <pubDate>Thu, 01 Oct 2015 19:23:29 +0000</pubDate>
      <generator>http://pipes.yahoo.com/pipes/</generator>
      <item>
         <title>Top 10 Changes in ASP.NET 5 and MVC 6</title>
         <link>http://feedproxy.google.com/~r/StephenWalther/~3/AyXlL8xCUxc/top-10-changes-in-asp-net-5-and-mvc-6</link>
         <description>Update on April, 30 2015 When I wrote this blog post, I wrote that Microsoft was not planning to support VB.NET in ASP.NET 5/MVC 6. That was true when I wrote the blog post, but this blog post generated some strong reactions from the VB.NET community. Well, it looks like VB.NET is back! http://www.infoq.com/news/2015/04/VB-Core I [&amp;#8230;]</description>
         <guid isPermaLink="false">http://stephenwalther.com/?p=962</guid>
         <pubDate>Tue, 24 Feb 2015 02:40:03 +0000</pubDate>
         <content:encoded><![CDATA[<div style="background-color:lightyellow;padding:10px;border:solid 2px black;margin:10px;">
<h3>Update on April, 30 2015</h3>
<p>When I wrote this blog post, I wrote that Microsoft was not planning to support VB.NET in ASP.NET 5/MVC 6. That was true when I wrote the blog post, but this blog post generated some strong reactions from the VB.NET community. Well, it looks like VB.NET is back!</p>
<p><a rel="nofollow" target="_blank" href="http://www.infoq.com/news/2015/04/VB-Core">http://www.infoq.com/news/2015/04/VB-Core</a></p>
</div>
<p>I spent the last couple of weeks writing sample code for ASP.NET 5/MVC 6 and I was surprised by the depth of the changes in the current beta release of ASP.NET 5. ASP.NET 5 is the most significant new release of ASP.NET in the history of the ASP.NET framework &#8212; it has been rewritten from the ground up.</p>
<p>In this blog post, I list what I consider to be the top 10 most significant changes in ASP.NET 5. This is a highly opinionated list. If other changes strike you as more significant, please describe the change in a comment.</p>
<h1>1. ASP.NET on OSX and Linux</h1>
<p><img src="http://stephenwalther.com/wp-content/uploads/2015/02/01LinuxOSX.png" alt="Linux and OSX" width="252" height="142" class="alignnone size-full wp-image-966"/></p>
<p>For the first time in the history of ASP.NET, you can run ASP.NET 5 applications on OSX and Linux. Let me repeat this. ASP.NET 5 apps can run on Windows, OSX, and Linux. This fact opens up ASP.NET to a whole new audience of developers and designers.</p>
<p>The traditional audience for ASP.NET is professional developers working in a corporation. Corporate customers are welded to their Windows machines. </p>
<p>Startups, in stark contrast, tend to use OSX/Linux. Whenever I attend a startup conference, the only machines that I see in the audience are Macbook Pros.  These people are not the traditional users of ASP.NET.</p>
<p>Furthermore, designers and front-end developers – at least when they are outside the corporate prison – also tend to use Macbook Pros. Whenever I attend a jQuery conference, I see Macbook Pros everywhere (the following picture is from the jQuery blog). </p>
<p><img src="http://stephenwalther.com/wp-content/uploads/2015/02/02jQuery-300x225.png" alt="jQuery Conference" width="300" height="225" class="alignnone size-medium wp-image-965"/></p>
<p>Enabling ASP.NET 5 to run on Windows, OSX, and Linux changes everything. For the first time, all developers and designers can start building apps with ASP.NET 5. And, they can use their favorite development environments such as Sublime Text and WebStorm when working with ASP.NET apps (No Visual Studio required).</p>
<p>Take a look at the OmniSharp project to see how you can use editors such as Sublime Text, Atom, Emacs, and Brackets with ASP.NET 5:</p>
<p><a rel="nofollow" target="_blank" href="http://www.omnisharp.net/">http://www.omnisharp.net/</a></p>
<h1>2. No More Web Forms</h1>
<p><img src="http://stephenwalther.com/wp-content/uploads/2015/02/03WebForms.jpeg" alt="ASP.NET Unleashed" width="160" height="197" class="alignnone size-full wp-image-964"/></p>
<p>I love ASP.NET Web Forms. I’ve spent hundreds – if not thousands – of hours of my life building Web Forms applications. However, it is finally time to say goodbye.  ASP.NET Web Forms is not part of ASP.NET 5.</p>
<p>You can continue to build Web Forms apps in Visual Studio 2015 by targeting the .NET 4.6 framework. However, Web Forms apps cannot take advantage of any of the cool new features of ASP.NET 5 described in this list.  If you don’t want to be left behind as history marches forward then it is finally time for you to rewrite your Web Forms app into ASP.NET MVC.</p>
<h1>3. No More Visual Basic</h1>
<p><img src="http://stephenwalther.com/wp-content/uploads/2015/02/04VisualBasic-300x141.jpeg" alt="Visual Basic" width="300" height="141" class="alignnone size-medium wp-image-969"/></p>
<p>It is also time to say goodbye to Visual Basic. ASP.NET 5 only supports C# and Visual Basic is left behind. </p>
<p>My hope is that this change won’t be too painful. I believe that there are only two people in the entire world who are building MVC apps in Visual Basic. It is time for both of you to stop it.  There are good automatic converters for going from Visual Basic to C#:</p>
<p><a rel="nofollow" target="_blank" href="http://converter.telerik.com/">http://converter.telerik.com/</a></p>
<h1>4.  Tag Helpers</h1>
<p>Tag Helpers is the one feature that might have the biggest impact on the way that you create your views in an ASP.NET MVC application. Tag Helpers are a better alternative to using traditional MVC helpers.</p>
<p>Consider the following MVC view that contains a form for creating a new product:</p>
<pre>
@model MyProject.Models.Product


@using (Html.BeginForm())
{
    &lt;div&gt;
        @Html.LabelFor(m =&gt; p.Name, &quot;Name:&quot;)
        @Html.TextBoxFor(m =&gt; p.Name)
    &lt;/div&gt;
    &lt;input type=&quot;submit&quot; value=&quot;Create&quot; /&gt;
}
</pre>
<p>In the view above, the Html.BeginForm(), Html.LabelFor(), and Html.TextBoxFor() helpers are used to create the form. These helpers would not be familiar to an HTML designer.</p>
<p>Here’s how the exact same form can be created by using Tag Helpers:</p>
<pre>
@model MyProject.Models.Product
@addtaghelper &quot;Microsoft.AspNet.Mvc.TagHelpers&quot;

&lt;form asp-controller=&quot;Products&quot; asp-action=&quot;Create&quot; method=&quot;post&quot;&gt;
    &lt;div&gt;
        &lt;label asp-for=&quot;Name&quot;&gt;Name:&lt;/label&gt;
        &lt;input asp-for=&quot;Name&quot; /&gt;
    &lt;/div&gt;

    &lt;input type=&quot;submit&quot; value=&quot;Save&quot; /&gt;
&lt;/form&gt;
</pre>
<p>Notice that this new version of the form contains only (what looks like) HTML elements.  For example, the form contains an INPUT element instead of an Html.TextBoxFor() helper. A front-end designer would be fine with this page.</p>
<p>The only thing special about this view is the special asp-for attributes. These attributes are used to extend the elements with server-side ASP.NET MVC functionality.</p>
<p>Damien Edwards put together an entire sample site that uses nothing but Tag Helpers here:</p>
<p><a rel="nofollow" target="_blank" href="https://github.com/DamianEdwards/TagHelperStarterWeb">https://github.com/DamianEdwards/TagHelperStarterWeb</a></p>
<h1>5. View Components</h1>
<p>Goodbye subcontrollers and hello View Components!<br />
In previous versions of ASP.NET MVC, you used the Html.Action() helper to invoke a subcontroller. For example, imagine that you want to display banner ads in multiple views. In that case, you would create a subcontroller that contained the logic for returning a particular banner advertisement and call the subcontroller by invoking Html.Action() from a view.</p>
<p>Subcontrollers – the Html.Action() helper &#8212; are not included in the current beta of MVC 6. Instead, MVC 6 includes an alternative technology called View Components.</p>
<p>Here’s how you can create a View Component that displays one of two banner advertisements depending on the time of day:</p>
<pre>
using Microsoft.AspNet.Mvc;
using System;

namespace Partials.Components
{
    public class BannerAd : ViewComponent
    {
        public IViewComponentResult Invoke()
        {
            var adText = &quot;Buy more coffee!&quot;;

            if (DateTime.Now.Hour &gt; 18)
            {
                adText = &quot;Buy more warm milk!&quot;;
            }
            return View(&quot;_Advertisement&quot;, adText);
        }
    }
} 
</pre>
<p>If the time is before 5:00pm then the View Component returns a partial named _Advertisement with the advertisement text “Buy more coffee!”. If the time is after 5:00pm then the text changes to “Buy more warm milk!”.</p>
<p>Here’s what the _Advertisement partial looks like:</p>
<pre>
@model string

&lt;div style=&quot;border:2px solid green;padding:15px&quot;&gt;
    @Model
&lt;/div&gt;
</pre>
<p>Finally, here is how you can use the BannerAd View Component in an MVC view:</p>
<pre>

  @Component.Invoke(&quot;BannerAd&quot;)

</pre>
<p>View Components are very similar to subcontrollers. However, subcontrollers were always a little odd. They were pretending to be controller actions but they were not really controller actions. View Components just seem more natural.</p>
<h1>6.  GruntJS, NPM, and Bower Support</h1>
<p><img src="http://stephenwalther.com/wp-content/uploads/2015/02/05GruntJS.png" alt="GruntJS" width="227" height="243" class="alignnone size-full wp-image-968"/></p>
<p>Front-end development gets a lot of love in ASP.NET 5 through its support for GruntJS (and eventually Gulp).</p>
<p>GruntJS is a task runner that enables you to build front-end resources such as JavaScript and CSS files. For example, you can use GruntJS to concatenate and minify your JavaScript files whenever you perform a build in Visual Studio.</p>
<p>There are thousands of GruntJS plugins that enable you to do an amazing variety of different tasks (there are currently 4,334 plugins listed in the GruntJS plugin repository):</p>
<p><a rel="nofollow" target="_blank" href="http://gruntjs.com/plugins">http://gruntjs.com/plugins</a></p>
<p>For example, there are plugins for running JavaScript unit tests, for validating the code quality of your JavaScript (jshint), compiling LESS and Sass files into CSS, compiling TypeScript into JavaScript, and minifying images.</p>
<p>In order to support GruntJS, Microsoft needed to support two new package managers (beyond NuGet). First, because GruntJS plugins are distributed as NPM packages, Microsoft added support for NPM packages. </p>
<p>Second, because many client-side resources – such as Twitter Bootstrap, jQuery, Polymer, and AngularJS – are distributed through Bower, Microsoft added support for Bower.</p>
<p>This means that you can run GruntJS using plugins from NPM and client resources from Bower.</p>
<h1>7.  Unified MVC and Web API Controllers</h1>
<p>In previous versions of ASP.NET MVC, MVC controllers were different than Web API controllers. An MVC controller used the System.Web.MVC.Controller base class and a Web API controller used the System.Web.Http.ApiController base class.</p>
<p>In MVC 6, there is one and only one Controller class that is the base class for both MVC and Web API controllers. There is only the Microsoft.AspNet.Mvc.Controller class.</p>
<p>MVC 6 controllers return an IActionResult. When used as an MVC controller, the IActionResult might be a view. When used as a Web API controller, the IActionResult might be data (such as a list of products).  The same controller might have actions that return both views and data.</p>
<p>In MVC 6, both MVC controllers and Web API controllers use the same routes. You can use either convention-based routes or attribute routes and they apply to all controllers in a project.</p>
<h1>8. AngularJS</h1>
<p>AngularJS is one of the most popular client-side frameworks for building Single Page Applications (SPAs). Visual Studio 2015 includes templates for creating AngularJS modules, controllers, directives, and factories.</p>
<p><img src="http://stephenwalther.com/wp-content/uploads/2015/02/06AngularJS-300x208.png" alt="AngularJS" width="300" height="208" class="alignnone size-medium wp-image-967"/> </p>
<p>The support in ASP.NET 5 for GruntJS makes ASP.NET an excellent server-side framework for building client-side AngularJS apps. You can combine and minify all of your AngularJS files automatically whenever you perform a build. You can interact with an MVC 6 controller from an AngularJS $resource using REST.</p>
<h1>9. ASP.NET Dependency Injection Framework</h1>
<p>ASP.NET 5 has built-in support for Dependency Injection and the Service Locator pattern. This means that you no longer need to rely on third-party Dependency Injection frameworks such as Ninject or AutoFac.</p>
<p>Imagine, for example, that you have created an IRepository interface and an EFRepository class that implements that interface. In that case, you can bind the EFRepository class to the IRepository interface in the ConfigureServices() method of the Startup.cs class like this:</p>
<pre>
services.AddTransient&lt;IRepository, EFRepository&gt;();
</pre>
<p>After you bind EFRepository and IRepository then you can use constructor dependency injection in your MVC controllers (and any other class) using code like this:</p>
<pre>
public class ProductsController : Controller
{
    private IRepository _repo;

    public ProductsController(IRepository repo)
    {
        _repo = repo;
    }
}
</pre>
<p>In the code above, the IRepository interface is passed to the constructor for the ProductsController. The built-in ASP.NET Dependency Injection framework passes EFRepository to the ProductsController because IRepository was bound to EFRepository.</p>
<p>You also can use the Service Locator pattern. Wherever you can access the HttpContext, you can access any registered services. For example, you can retrieve the EFRepository by using the following code inside of an MVC controller action:</p>
<pre>
var repo = this.Context.ApplicationServices.GetRequiredService&lt;IRepository&gt;();
</pre>
<h1>10. xUnit.net</h1>
<p>Goodbye Visual Studio Unit Testing Framework and hello xUnit.net!</p>
<p>In previous versions of ASP.NET MVC, the default testing framework was the Visual Studio Unit Testing Framework (sometimes called mstest). This framework uses the [TestClass] and [TestMethod] attributes to describe a unit test:</p>
<pre>
[TestClass]
public class CalculatorTests {

    [TestMethod]
    public void TestAddNumbers() {
        // Arrange
        var calc = new Calculator();

        // Act
        var result = calc.AddNumbers(0, 0);

        // Assert
        Assert.AreEqual(0, result);

    }

}
</pre>
<p>ASP.NET 5 uses xUnit.net as its unit test framework. This framework uses the [Fact] attribute instead of the [TestMethod] attribute (and no [TestClass] attribute]):</p>
<pre>
public class CalculatorTests
{
    [Fact]
    public void AddNumbers()
    {
        // Arrange
        var calculator = new Calculator();

        // Act
        var result = calculator.AddNumbers(1, 1);

        // Assert
        Assert.Equal(result, 13);
    }
}
</pre>
<p>If you look at the source code for ASP.NET 5 then you’ll see that xUnit.net is used to test ASP.NET extensively. For example, the MVC repository contains unit tests written with xUnit.net. You can take a look at the MVC repository (and its unit tests) here:</p>
<p><a rel="nofollow" target="_blank" href="http://github.com/aspnet/mvc">http://github.com/aspnet/mvc</a></p>
<p>ASP.NET uses a fork of xUnit.net that is located here:</p>
<p><a rel="nofollow" target="_blank" href="http://github.com/aspnet/xunit">https://github.com/aspnet/xunit</a></p>
<div class="feedflare">
<a rel="nofollow" target="_blank" href="http://feeds.feedburner.com/~ff/StephenWalther?a=AyXlL8xCUxc:ZKH1cVi-m6E:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/AyXlL8xCUxc" height="1" width="1" alt=""/>]]></content:encoded>
      </item>
      <item>
         <title>ASP.NET 5 Deep Dive: Routing</title>
         <link>http://feedproxy.google.com/~r/StephenWalther/~3/zx6eqPIT_oI/asp-net-5-deep-dive-routing</link>
         <description>In this blog post, I focus on how routing is implemented in ASP.NET 5 and MVC 6. I explain how to create routes, use RESTful routes, and use route constraints. While researching this blog post, I took full advantage of the open-source code for ASP.NET 5 located at the following GitHub repositories: https://github.com/aspnet Routing in [&amp;#8230;]</description>
         <guid isPermaLink="false">http://stephenwalther.com/?p=956</guid>
         <pubDate>Sat, 07 Feb 2015 22:26:25 +0000</pubDate>
         <content:encoded><![CDATA[<p>In this blog post, I focus on how routing is implemented in ASP.NET 5 and MVC 6. I explain how to create routes, use RESTful routes, and use route constraints.</p>
<p>While researching this blog post, I took full advantage of the open-source code for ASP.NET 5 located at the following GitHub repositories:</p>
<p><a rel="nofollow" target="_blank" href="https://github.com/aspnet">https://github.com/aspnet</a></p>
<h2>Routing in Previous Versions of ASP.NET</h2>
<p>Previous versions of ASP.NET supported two types of routing: convention-based routing and attribute-based routing. When using convention-based routing, you could define your routes in your application RouteConfig.cs file like this:</p>
<pre>
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute(&quot;{resource}.axd/{*pathInfo}&quot;);

        routes.MapRoute(
            name: &quot;Default&quot;,
            url: &quot;{controller}/{action}/{id}&quot;,
            defaults: new { controller = &quot;Home&quot;, action = &quot;Index&quot;, id = UrlParameter.Optional }
        );
    }
}
</pre>
<p>The code above defines a Default route that maps a request like “/products/details” to the ProductsController.Details() action.</p>
<p>ASP.NET MVC 5 introduced support for attribute-based routing. The primary advantage of attribute-based routing is that it allowed you to define your routes in the same file as your controller. For example, here’s an example of creating a ProductsController that includes both a [RoutePrefix] and [Route] attribute used for routing:</p>
<pre>
[RoutePrefix(&quot;Products&quot;)]
public class ProductsController : Controller
{
    [Route(&quot;Index&quot;)]
    public ActionResult Index()
    {
        return View();
    }
}
</pre>
<p>Regardless of whether you used convention-based routing or attribute-based routing, all of your routes ended up in a static collection located at RouteTable.Routes.</p>
<p>If you used the ASP.NET Web API then routing worked in a similar way.  You could define convention-based routes in the WebApiConfig.cs file and add attribute-based routes to your Web API controller classes.</p>
<p>However, there were two important differences between routing in MVC and the Web API. First, the Web API supported RESTful routes by default. If you gave a Web API controller action a name that started with Get, Post, Put, Delete then you could invoke the action by performing an HTTP GET, POST, PUT, or DELETE request. For example, you could invoke a Web API action named PostMovie() simply by performing an HTTP POST.</p>
<p>The other important difference between MVC and the Web API was subtler. Behind the scenes, MVC and the Web API did not share the same routing framework. Routing in MVC and the Web API followed similar patterns, but routing was implemented with different code (originally written by different Microsoft teams). </p>
<p>Everything in ASP.NET 5 and MVC 6 has been rewritten from the ground up. This includes the routing framework used by both MVC and the Web API. There are several important changes to routing that I discuss in this blog post.</p>
<p>First, in ASP.NET 5, there is no longer a distinction between MVC and Web API controllers. Both MVC and Web API controllers derive from the very same Controller base class.</p>
<p>This means that the same routing framework is used for both MVC and the Web API. With ASP.NET 5, anything that is true of routing for MVC is also true for the Web API.</p>
<p>Second, unlike earlier versions of MVC, default routes are created for you automatically. You don’t need to configure anything to route a request to a controller action. A set of default routes is created for you automatically.</p>
<p>Third and finally, in MVC 6, you are provided with a rich set of inline constraints and parameter options that you can use with both convention-based and attributed-based routing.  For example, you can constrain the data type of your route parameters, mark a parameter as optional, and provide default values for your parameters right within your route templates.</p>
<h2>Creating Routes</h2>
<p>Let’s start with the very basics. I’m going to show you the minimal amount of code that you need to use routing in an ASP.NET 5 application. I won’t even assume that you are using MVC.</p>
<p>Here’s my Startup class:</p>
<pre>
using System;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Routing;
using Microsoft.AspNet.Routing.Template;
using Microsoft.Framework.DependencyInjection;

namespace RoutePlay
{
    public class Startup
    {

        public void Configure(IApplicationBuilder app)
        {
          RouteCollection routes = new RouteCollection();
          routes.Add(new TemplateRoute(new DebuggerRouteHandler(&quot;RouteHandlerA&quot;), &quot;test/{a}/{b}&quot;, null));
          routes.Add(new TemplateRoute(new DebuggerRouteHandler(&quot;RouteHandlerB&quot;), &quot;test2&quot;, null));
          app.UseRouter(routes);
        }
    }
}
</pre>
<p>In the code above, I’ve created a Configure() method that I use to configure routing. I create a Route collection that contains two routes. Finally, I pass the Route collection to the ApplicationBuilder.UseRouter() method to enable the routes.</p>
<p>The routes are created with the TemplateRoute class. The TemplateRoute class is initialized with a Route Handler and a URL template. The first route – named RouteHandlerA &#8212; matches URLs with the pattern “test/{a}/{b}” and the second route – named RouteHandlerB – matches URLs with the pattern “test2”.</p>
<p>The essence of routing is mapping an incoming browser request to a Route Handler. In the code above, requests are mapped to a custom handler that I created named DebuggerRouteHandler.</p>
<p>Here’s the code for the DebuggerRouteHandler:</p>
<pre>
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Routing;
using System;
using System.Threading.Tasks;

namespace RoutePlay
{
	public class DebuggerRouteHandler : IRouter
	{
		private string _name;

		public DebuggerRouteHandler(string name)
		{
			_name = name;
		}

		public string GetVirtualPath(VirtualPathContext context)
		{
			throw new NotImplementedException();
		}

		public async Task RouteAsync(RouteContext context)
		{
			var routeValues = string.Join(&quot;&quot;, context.RouteData.Values);
            var message = String.Format(&quot;{0} Values={1} &quot;, _name, routeValues);
			await context.HttpContext.Response.WriteAsync(message);
			context.IsHandled = true;
		}
	}
}
</pre>
<p>The DebuggerRouteHandler simply displays the name of the route and any route values extracted from the URL template. For example, if you enter the URL “test/apple/orange” into the address bar of your browser then you get the following response:</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/02/01DebuggerRouteHandler-e1423349099857.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/02/01DebuggerRouteHandler-e1423349099857.png" alt="DebuggerRouteHandler" width="800" height="257" class="alignnone size-full wp-image-960"/></a></p>
<h2>Creating Routes with MVC 6</h2>
<p>When using MVC 6, you don’t create your Route collection yourself. Instead, you let MVC create the route collection for you.</p>
<p>Here’s a Startup class that is configured to use MVC 6:</p>
<pre>
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;

namespace RoutePlay
{
	public class Startup
    {
		public void ConfigureServices(IServiceCollection services)
		{
			services.AddMvc();
		}

		public void Configure(IApplicationBuilder app)
        {
			app.UseMvc();
		}
	}
}
</pre>
<p>The ConfigureServices() method is used to register MVC with the Dependency Injection framework built into ASP.NET 5. The Configure() method is used to register MVC with OWIN.</p>
<p>Here’s what my MVC 6 ProductsController looks like:</p>
<pre>
using Microsoft.AspNet.Mvc;

namespace RoutePlay.Controllers
{
    public class ProductsController : Controller
    {
        public IActionResult Index()
        {
            return Content(&quot;It Works!&quot;);
        }
    }
}
</pre>
<p>Notice that I have not configured any routes. I have not used either convention-based or attribute-based routing, but I don’t need to do this. If I enter the request “/products/index” into my browser address bar then I get the response “It Works!”:</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/02/02DefaultRoutes-e1423348967913.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/02/02DefaultRoutes-e1423348967913.png" alt="Default Routes" width="800" height="255" class="alignnone size-full wp-image-958"/></a></p>
<p>When you call ApplicationBuilder.UseMvc() in the Startup class, the MVC framework adds routes for you automatically.  Here’s what the framework code for the UseMvc() method looks like:</p>
<pre>
public static IApplicationBuilder UseMvc([NotNull] this IApplicationBuilder app)
{
    return app.UseMvc(routes =&gt;
    {
    });
}

public static IApplicationBuilder UseMvc(
    [NotNull] this IApplicationBuilder app,
    [NotNull] Action&lt;IRouteBuilder&gt; configureRoutes)
{
    // Verify if AddMvc was done before calling UseMvc
    // We use the MvcMarkerService to make sure if all the services were added.
    MvcServicesHelper.ThrowIfMvcNotRegistered(app.ApplicationServices);

    var routes = new RouteBuilder
    {
        DefaultHandler = new MvcRouteHandler(),
        ServiceProvider = app.ApplicationServices
    };

    configureRoutes(routes);

    // Adding the attribute route comes after running the user-code because
    // we want to respect any changes to the DefaultHandler.
    routes.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(
        routes.DefaultHandler,
        app.ApplicationServices));

    return app.UseRouter(routes.Build());
}
</pre>
<p>The AttributeRouting.CreateAttributeMegaRoute() does all of the heavy-lifting here (the word “Mega” in its name is very appropriate). The CreateAttributeMegaRoute() method iterates through all of your MVC controller actions and builds routes for you automatically. Thank you CreateAttributeMegaRoute()  &#8212; you are going to save me tons of work!</p>
<h2>Convention-Based Routing</h2>
<p>You can use convention-based routing with ASP.NET MVC 5 by defining the routes in your project’s Startup class.  For example, here is how you would map the requests /Super and /Awesome to the ProductsController.Index() action:</p>
<pre>
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Routing;
using Microsoft.Framework.DependencyInjection;

namespace RoutePlay
{
	public class Startup
    {
		public void ConfigureServices(IServiceCollection services)
		{
			services.AddMvc();
		}

		public void Configure(IApplicationBuilder app)
		{
			app.UseMvc(routes =&gt;
			{
				// route1
				routes.MapRoute(
					name: &quot;route1&quot;,
					template: &quot;super&quot;,
					defaults: new { controller = &quot;Products&quot;, action = &quot;Index&quot; }
				);
				// route2
				routes.MapRoute(
					name: &quot;route2&quot;,
					template: &quot;awesome&quot;,
					defaults: new { controller = &quot;Products&quot;, action = &quot;Index&quot; }
				);
			});
        }
	}
}
</pre>
<p>If you squint your eyes really hard then the code above in the Configure() method for setting up the routes looks similar to the code in a RouteConfig.cs file. </p>
<h2>Attribute-Based Routing</h2>
<p>You also can use attribute-based routing with MVC 6. Here’s how you can modify the ProductsController Index() action so you can invoke it with the “/Things/All” request:</p>
<pre>
using Microsoft.AspNet.Mvc;

namespace RoutePlay.Controllers
{
    [Route(&quot;Things&quot;)]
    public class ProductsController : Controller
    {
        [Route(&quot;All&quot;)]
        public IActionResult Index()
        {
            return Content(&quot;It Works!&quot;);
        }
    }
}
</pre>
<p>Notice that both the ProductsController class and the Index() action are decorated with a [Route] attribute.  The combination of the two attributes enables you to invoke the Index() method by requesting “/Things/All”.</p>
<p>Here’s what a Web API controller looks like in MVC 6:</p>
<pre>
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Mvc;

namespace RoutePlay.Controllers.Api.Controllers
{
    [Route(&quot;api/[controller]&quot;)]
    public class MoviesController : Controller
    {
        // GET: api/values
        [HttpGet]
        public IEnumerable&lt;string&gt; Get()
        {
            return new string[] { &quot;value1&quot;, &quot;value2&quot; };
        }

        // GET api/values/5
        [HttpGet(&quot;{id}&quot;)]
        public string Get(int id)
        {
            return &quot;value&quot;;
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        [HttpPut(&quot;{id}&quot;)]
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete(&quot;{id}&quot;)]
        public void Delete(int id)
        {
        }
    }
}
</pre>
<p>Notice that a Web API controller, just like an MVC controller, derives from the base Controller class. That’s because there is no difference between a Web API controller and MVC controller in MVC 6 – they are the exact same thing.</p>
<p>You also should notice that the Web API controller in the code above is decorated with a [Route] attribute that enables you to invoke the Movies controller with the request “/api/movies”.  The special [controller] and [action] tokens are new to MVC 6 and they allow you to easily refer to the controller and action names in your route templates.</p>
<p>If you mix convention-based and attribute-based routing then attribute-based routing wins. Furthermore, both convention-based and attribute-based routing win over the default routes. </p>
<h2>Creating Restful Routes</h2>
<p>You can use RESTful style routing with both MVC and Web API controllers. Consider the following controller (a mixed MVC and Web API controller):</p>
<pre>
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.WebUtilities.Collections;

namespace RoutePlay.Controllers
{
    [Route(&quot;[controller]&quot;)]
    public class MyController : Controller
    {
		// GET: /my/show
		[HttpGet(&quot;Show&quot;)]
		public IActionResult Show()
		{
			return View();
		}

		// GET: /my
		[HttpGet]
		public IActionResult Get()
		{
			return Content(&quot;Get Invoked&quot;);
		}

		// POST: /my
		[HttpPost]
		public IActionResult Post()
		{
			return Content(&quot;Post Invoked&quot;);
		}

		// POST: /my/stuff
		[HttpPost(&quot;Stuff&quot;)]
		public IActionResult Post([FromBody]string firstName)
		{
			return Content(&quot;Post Stuff Invoked&quot;);
		}


	}
}
</pre>
<p>The MyController has the following four actions:</p>
<ul>
<li>
 Show() – Invoked with an HTTP GET request for “/my/show”
</li>
<li>
  Get() – Invoked with an HTTP GET request for “/my”
</li>
<li>
  Post() – Invoked with an HTTP POST request for “/my”
</li>
<li>
  Post([fromBody]string firstName) – Invoked with an HTTP POST request for “/my/stuff”
</li>
</ul>
<p>Notice that the controller is decorated with a [Route(“[controller]”)] attribute and each action is decorated with a [HttpGet] or [HttpPost] attribute.</p>
<p>If you just use the [HttpPost] attribute on an action then you can invoke the action without using the action name (for example, “/my”). If you use an attribute such as [HttpPost(“stuff”)] that includes a template parameter then you must include the action name when invoking the action (for example, “/my/stuff”).</p>
<p>The Show() action returns the following view:</p>
<pre>
&lt;p&gt;
	&lt;a href=&quot;/my&quot;&gt;GET&lt;/a&gt;
&lt;/p&gt;
&lt;form method=&quot;post&quot; action=&quot;/my&quot;&gt;
	&lt;input type=&quot;submit&quot; value=&quot;POST&quot; /&gt;
&lt;/form&gt;
&lt;form method=&quot;post&quot; action=&quot;/my/stuff&quot;&gt;
	&lt;input name=&quot;firstname&quot; /&gt;
	&lt;input type=&quot;submit&quot; value=&quot;POST STUFF&quot; /&gt;
&lt;/form&gt;
</pre>
<p>If you click the GET link then the Get() action is invoked. If you post the first form then the first Post() action is invoked and if you post the second form then the second Post() action is invoked.</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/02/03RESTful-e1423349040908.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/02/03RESTful-e1423349040908.png" alt="RESTful" width="800" height="399" class="alignnone size-full wp-image-959"/></a></p>
<h2>Creating Route Constraints</h2>
<p>You can use constraints to constrain the types of values that can be passed to a controller action. For example, if you have a controller action that displays product details for a particular product given a particular product id, then you might want to constrain the product id to be an integer:</p>
<pre>
using Microsoft.AspNet.Mvc;

namespace RoutePlay.Controllers
{
    [Route(&quot;[controller]&quot;)]
    public class ProductsController : Controller
    {

		[HttpGet(&quot;details/{id:int}&quot;)]
		public IActionResult Details(int id)
		{
			return View();
		}

	}
}
</pre>
<p>Notice that the Details() action is decorated with an [HttpGet] attribute that uses the template “details/{0:int}” to constrain the id passed to the action to be an integer. There are plenty of other inline constraints that you use such as alpha, minlength, and regex.</p>
<p>ASP.NET 5 introduces support for optional parameters. You can use a question mark ? in a template to mark a parameter as optional like this:</p>
<pre>
[HttpGet(&quot;details/{id:int?}&quot;)]
public IActionResult Details(int id)
{
	return View();
}
</pre>
<p>You can invoke the Details() action in the controller above using a URL like “/products/details/8” or a URL that leaves out the id like “/products/details” (in that case, id has the value 0).</p>
<p>Finally, ASP.NET 5 introduces support for default parameter values. If you don’t supply a value for the id parameter then the parameter gets the value 99 automatically:</p>
<pre>
[HttpGet(&quot;details/{id:int=99}&quot;)]
public IActionResult Details(int id)
{
	return View();
}
</pre>
<h2>Summary</h2>
<p>ASP.NET 5 (and ASP.NET MVC 6) includes a new routing framework rewritten from the ground up. In this blog post, I’ve provided a deep dive into how this new framework works.</p>
<p>First, I discussed how routing works independently of MVC 6. I explained how you can create a new Route collection in the Startup class.</p>
<p>Next, I demonstrated how you can use MVC 6 default routes, convention-based routes, and attribute routes. I also elaborated on how you can create controllers that follow RESTful conventions.</p>
<p>Finally, I discussed how you can take advantage of inline constraints, optional parameters, and default parameter values.</p>
<p>If you want to dig more deeply into routing then I recommend taking a look at the following two GitHub aspnet repositories:</p>
<p><a rel="nofollow" target="_blank" href="https://github.com/aspnet/Routing">https://github.com/aspnet/Routing</a><br />
<a rel="nofollow" target="_blank" href="https://github.com/aspnet/Mvc">https://github.com/aspnet/Mvc</a></p>
<div class="feedflare">
<a rel="nofollow" target="_blank" href="http://feeds.feedburner.com/~ff/StephenWalther?a=zx6eqPIT_oI:zhDIU7POpNc:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/zx6eqPIT_oI" height="1" width="1" alt=""/>]]></content:encoded>
      </item>
      <item>
         <title>ASP.NET 5 and AngularJS Part 7, Running on a Mac</title>
         <link>http://feedproxy.google.com/~r/StephenWalther/~3/K5qph21HQEg/asp-net-5-and-angularjs-part-7-running-on-a-mac</link>
         <description>This is the seventh part in a multiple part blog series on building ASP.NET 5 (ASP.NET vNext) apps with AngularJS. In this series of blog posts, I show how you can create a simple Movie app using ASP.NET 5, MVC 6, and AngularJS. ASP.NET 5 and AngularJS Part 1, Grunt, Uglify, and AngularJS ASP.NET 5 [&amp;#8230;]</description>
         <guid isPermaLink="false">http://stephenwalther.com/?p=944</guid>
         <pubDate>Tue, 03 Feb 2015 16:27:01 +0000</pubDate>
         <content:encoded><![CDATA[<p>This is the seventh part in a multiple part blog series on building ASP.NET 5 (ASP.NET vNext) apps with AngularJS. In this series of blog posts, I show how you can create a simple Movie app using ASP.NET 5, MVC 6, and AngularJS.</p>
<ul>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 1, Grunt, Uglify, and AngularJS</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 2, Using the MVC 6 Web API</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 3, Adding Client Routing</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 4, Using Entity Framework 7</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 5, Form Validation</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 6, Security</a>
</li>
<li>
  <b><a rel="nofollow">ASP.NET 5 and AngularJS Part 7, Running on a Mac</a></b>
</li>
</ul>
<p>You can download the code discussed in this blog post from GitHub:</p>
<p><a rel="nofollow" target="_blank" href="https://github.com/StephenWalther/MovieAngularJSApp">https://github.com/StephenWalther/MovieAngularJSApp</a></p>
<p>In this blog post, I walk through the steps required to run an ASP.NET 5 app on a Mac. In particular, I setup the Movies app to run on OSX Yosemite on my MacBook Pro. I try to follow the instructions for running ASP.NET 5 on OSX created by the ASP.NET team as closely as possible but I encounter some issues along the way:</p>
<p><a rel="nofollow" target="_blank" href="https://github.com/aspnet/home">https://github.com/aspnet/home</a></p>
<h2>Installing Mono</h2>
<p>Before you can run ASP.NET 5 on a Mac, you must first install Mono. The Mono Project is independent from Microsoft. Mono is an open-source implementation of .NET for different platforms such as Mac OSX and Linux.</p>
<p>In theory, the Homebrew script supplied by the ASP.NET team should install the correct version of Mono automatically, but I couldn’t get this to work. I ended up installing Mono myself by visiting the following page:</p>
<p><a rel="nofollow" target="_blank" href="http://www.mono-project.com/download/">http://www.mono-project.com/download/</a></p>
<p>Installing Mono was painless. They have a nice installer that does all of the work.</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/02/01InstallMono.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/02/01InstallMono.png" alt="Install Mono" width="900" height="637" class="alignnone size-full wp-image-948"/></a> </p>
<h2>Updating Homebrew</h2>
<p>The next step is to use Homebrew to install KVM.  I ran into several problems getting this to work on OSX Yosemite. </p>
<p>The first problem is that the location of Ruby on Yosemite has changed which breaks Homebrew:</p>
<p><a rel="nofollow" target="_blank" href="http://apple.stackexchange.com/questions/153790/how-to-fix-brew-after-its-upgrade-to-yosemite">http://apple.stackexchange.com/questions/153790/how-to-fix-brew-after-its-upgrade-to-yosemite</a></p>
<p>I executed the following sequence of commands to update Homebrew so it works with OSX Yosemite:</p>
<pre>
cd /System/Library/Frameworks/Ruby.framework/Versions 
sudo ln -s Current 1.8 
sudo brew update 
sudo rm 1.8
</pre>
<h2>Installing KVM</h2>
<p>After I got Homebrew into a working state, I used Homebrew to install the ASP.NET 5 KVM. First, you need to execute the following command to associate the aspnet/k GitHub repository with Homebrew:</p>
<pre>
brew tap aspnet/k
</pre>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/02/02TapBrew.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/02/02TapBrew.png" alt="Tap ASPNET" width="900" height="380" class="alignnone size-full wp-image-947"/></a></p>
<p>Next, run the following command to perform the actual install of kvm:</p>
<pre>
brew install kvm
</pre>
<p>After running this command, I ran into an error stating that kvm was installed but “just not linked”. Executing the following command fixed the problem:</p>
<pre>
sudo brew link kvm
</pre>
<p>Leave and re-enter Terminal and execute the following command to verify the installation of kvm and Mono:</p>
<pre>
kvm list
</pre>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/02/03KVMList.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/02/03KVMList.png" alt="KVM List" width="900" height="314" class="alignnone size-full wp-image-946"/></a></p>
<p>Before running the kvm or k command, you need to run the following command first:</p>
<pre>
source kvm.sh
</pre>
<p>You’ll need to run this command once each and every time you open the Terminal app so Terminal knows where to look for kvm and k.</p>
<h2>Installing the Movies App</h2>
<p>Next, I grabbed the source code for the Movies app from my GitHub repository by executing the following command:</p>
<pre>
git clone https://github.com/StephenWalther/MovieAngularJSApp.git
</pre>
<p>The modified Movies app described in this blog post can be found in the Part7 folder.</p>
<p>I used Sublime Text to edit the files in the Movies app while running OSX.</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/02/04Sublime.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/02/04Sublime.png" alt="Sublime Text" width="900" height="654" class="alignnone size-full wp-image-951"/></a>  </p>
<h2>Using the In-Memory Database</h2>
<p>In previous parts of this blog series, I used Entity Framework 7 with Microsoft SQL Server to store my list of movies. This won’t work on a Mac because you cannot run Microsoft SQL Server on a Mac.</p>
<p>You have a few choices here:</p>
<ul>
<li>
<p>
SQLite – SQLite is an open-source database that works on Windows, Windows Phone, OSX, and Linux. According to the description page (http://www.sqlite.org), it is the most widely deployed database in the world.
  </p>
</li>
<li>
<p>
Azure SQL Database – Connect to a Microsoft Azure SQL Database from your app running in OSX. In other words, host the Movies app on OSX and your database in the cloud.
  </p>
</li>
<li>
<p>
In-Memory – Use the In-Memory provider for the Entity Framework to run an in-memory database (which dies and goes away each time you restart your web server).
  </p>
</li>
</ul>
<p>I could not get SQLite to work with the current BETA version of ASP.NET 5. I could not find the UseSQLite() method, so I assume that this provider is not ready yet. You can look at the SQLite repository here:</p>
<p>https://github.com/aspnet/DataCommon.SQLite </p>
<p>Using an Azure SQL Database would be the best choice for a real-world application. However, I did not want to require an external dependency to run the Movies app.</p>
<p>Therefore, I decided to use the In-Memory provider for the Entity Framework. The disadvantage of the In-Memory provider is that the database does not persist. However, the advantage is that it works across Windows, OSX, and Linux.</p>
<p>I had to make two changes to the Movies app to use the In-Memory provider. First, I had to add a reference to EntityFramework.InMemory to the dependencies section of the Movies app project.json file. Adding this dependency pulls in the NuGet package for the In-Memory provider.</p>
<p>Second, I had to make two changes to the Startup class. I updated the ConfigureServices() method in Startup.cs to check whether the app was running on Mono (OSX or Linux). When the Movies app is run on Mono, it uses the In-Memory provider. Otherwise, when the Movies app is run on Windows, it uses Microsoft SQL Server. </p>
<pre>
public void ConfigureServices(IServiceCollection services)
{

	//Sql client not available on mono
    var usingMono = Type.GetType(&quot;Mono.Runtime&quot;) != null;

    // Add EF services to the services container
    if (usingMono)
    {
        services.AddEntityFramework(Configuration)
                .AddInMemoryStore()
                .AddDbContext&lt;MoviesAppContext&gt;();
    } else {
		services.AddEntityFramework(Configuration)
				.AddSqlServer()
				.AddDbContext&lt;MoviesAppContext&gt;(options =&gt;
				{
					options.UseSqlServer(Configuration.Get(&quot;Data:DefaultConnection:ConnectionString&quot;));
				});
	}

	// add ASP.NET Identity
	services.AddIdentity&lt;ApplicationUser, IdentityRole&gt;(Configuration)
		.AddEntityFrameworkStores&lt;MoviesAppContext&gt;();

	// add ASP.NET MVC
	services.AddMvc();
}
</pre>
<p>I also updated the CreateSampleData() method in the Startup class. The Startup class calls EnsureCreatedAsync() to create the database only when you are running the app on Windows and not Mono. You don’t need to create an actual database file when using the In-Memory provider.</p>
<pre>
private static async Task CreateSampleData(IServiceProvider applicationServices)
{
	using (var dbContext = applicationServices.GetService&lt;MoviesAppContext&gt;())
	{
		// ensure SQL Server database created
		var sqlServerDatabase = dbContext.Database as SqlServerDatabase;
		if (sqlServerDatabase != null)
		{
			sqlServerDatabase.EnsureCreatedAsync().Wait();
		}

		// add some movies
		var movies = new List&lt;Movie&gt;
		{
			new Movie {Title=&quot;Star Wars&quot;, Director=&quot;Lucas&quot;},
			new Movie {Title=&quot;King Kong&quot;, Director=&quot;Jackson&quot;},
			new Movie {Title=&quot;Memento&quot;, Director=&quot;Nolan&quot;}
		};
		movies.ForEach(m =&gt; dbContext.Movies.AddAsync(m));

		// add some users
		var userManager = applicationServices.GetService&lt;UserManager&lt;ApplicationUser&gt;&gt;();

		// add editor user
		var stephen = new ApplicationUser
		{
			UserName = &quot;Stephen&quot;
		};
		var result = await userManager.CreateAsync(stephen, &quot;P@ssw0rd&quot;);
		await userManager.AddClaimAsync(stephen, new Claim(&quot;CanEdit&quot;, &quot;true&quot;));

		// add normal user
		var bob = new ApplicationUser
		{
			UserName = &quot;Bob&quot;
		};
		await userManager.CreateAsync(bob, &quot;P@ssw0rd&quot;);
	}
}
</pre>
<h2>Using Kestrel</h2>
<p>You can’t use Internet Information Services (IIS) on OSX. Instead, you need to use the Kestrel web server, which was built by the ASP.NET team to work with both OSX and Linux.</p>
<p>Under the covers, Kestrel is built on top of Libuv, which is also used by NodeJS.  You can read about Libuv here:</p>
<p><a rel="nofollow" target="_blank" href="http://nikhilm.github.io/uvbook/">http://nikhilm.github.io/uvbook/</a></p>
<p>In order to use Kestrel, you must add a dependency on Kestrel to your project.json file. Here’s what my complete dependencies section looks like (the top 2 dependencies are used by OSX):</p>
<pre>
&quot;dependencies&quot;: {
     &quot;Kestrel&quot;: &quot;1.0.0-*&quot;,
     &quot;EntityFramework.InMemory&quot;: &quot;7.0.0-*&quot;, 

     &quot;EntityFramework.SqlServer&quot;: &quot;7.0.0-beta2&quot;,
     &quot;EntityFramework.Commands&quot;: &quot;7.0.0-beta2&quot;,
     &quot;Microsoft.AspNet.Mvc&quot;: &quot;6.0.0-beta2&quot;,
     /* &quot;Microsoft.AspNet.Mvc.WebApiCompatShim&quot;: &quot;6.0.0-beta2&quot;, */
     &quot;Microsoft.AspNet.Diagnostics&quot;: &quot;1.0.0-beta2&quot;,
     &quot;Microsoft.AspNet.Diagnostics.Entity&quot;: &quot;7.0.0-beta2&quot;,
     &quot;Microsoft.AspNet.Identity.EntityFramework&quot;: &quot;3.0.0-beta2&quot;,
     &quot;Microsoft.AspNet.Security.Cookies&quot;: &quot;1.0.0-beta2&quot;,
     &quot;Microsoft.AspNet.Server.IIS&quot;: &quot;1.0.0-beta2&quot;,
     &quot;Microsoft.AspNet.Server.WebListener&quot;: &quot;1.0.0-beta2&quot;,
     &quot;Microsoft.AspNet.StaticFiles&quot;: &quot;1.0.0-beta2&quot;,
     &quot;Microsoft.Framework.ConfigurationModel.Json&quot;: &quot;1.0.0-beta2&quot;,
     &quot;Microsoft.Framework.CodeGenerators.Mvc&quot;: &quot;1.0.0-beta2&quot;,
     &quot;Microsoft.Framework.Logging&quot;: &quot;1.0.0-beta2&quot;,
     &quot;Microsoft.Framework.Logging.Console&quot;: &quot;1.0.0-beta2&quot;,
     &quot;Microsoft.VisualStudio.Web.BrowserLink.Loader&quot;: &quot;14.0.0-beta1&quot;
  },  
</pre>
<p>By the way, a Kestrel is a type of bird (a falcon) that has the special ability of being able to fly in dead air.</p>
<h2>Fetching NuGet Dependencies</h2>
<p>Before we can run our Movies app, we need to pull in all of the NuGet dependencies that we listed in the project.json file. Execute the following command:</p>
<pre> 
kpm restore
</pre>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/02/05KVMRestore.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/02/05KVMRestore.png" alt="KPM Restore" width="900" height="265" class="alignnone size-full wp-image-950"/></a> </p>
<h2>Running Kestrel</h2>
<p>We are finally ready to run the Movies app on OSX. Execute the following command:</p>
<pre>
k kestrel
</pre>
<p>Executing this command will startup the Kestrel web server. </p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/02/06StartKestrel.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/02/06StartKestrel.png" alt="Start Kestrel" width="900" height="264" class="alignnone size-full wp-image-949"/></a> </p>
<p>By default Kestrel runs on port 5104.  You can determine the port being used by Kestrel by taking a look at the commands section of your project.json file.</p>
<p>Open a browser and navigate to the following address and you should see the Movies app:</p>
<p><a rel="nofollow" target="_blank" href="http://localhost:5104">http://localhost:5104</a></p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/02/07MoviesApp.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/02/07MoviesApp.png" alt="Movies App" width="900" height="641" class="alignnone size-full wp-image-953"/></a> </p>
<p>The Movies app is completely functional. You can login using either the Stephen and Bob user (with the password P@ssw0rd). If you login as Stephen then you can add, edit, and delete movies.</p>
<p>Because we are using the In-Memory provider, any changes that we make will disappear when we stop the app. If you want to persist changes then you should use an Azure SQL Database and persist your data to the cloud.</p>
<h2>Stopping Kestrel</h2>
<p>Stopping Kestrel is surprisingly difficult. On OSX, hitting CTRL-C in Terminal won’t do anything and won’t stop the server. Here are the steps that work for me:</p>
<ol>
<li>
<p>
Hit CTRL-Z to stop Kestrel.
  </p>
</li>
<li>
<p>
Type ps to get a list of processes.
  </p>
</li>
<li>
<p>
Type kill followed by the process id to kill the Mono process.
  </p>
</li>
</ol>
<p>There is a StackOverflow description of this issue here:</p>
<p><a rel="nofollow" target="_blank" href="http://stackoverflow.com/questions/25712814/how-to-quit-asp-net-kestrel-web-server-on-a-mac">http://stackoverflow.com/questions/25712814/how-to-quit-asp-net-kestrel-web-server-on-a-mac</a></p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/02/08KillKestrel.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/02/08KillKestrel.png" alt="Kill Kestrel" width="900" height="607" class="alignnone size-full wp-image-952"/></a></p>
<h2>Summary</h2>
<p>The goal of this blog post was to describe the set of steps that I needed to complete to get the Movies app running on OSX. There were some bumps on the way, but it is amazing to see ASP.NET (and the Entity Framework) running outside of Windows.</p>
<div class="feedflare">
<a rel="nofollow" target="_blank" href="http://feeds.feedburner.com/~ff/StephenWalther?a=K5qph21HQEg:Dz6A48qDf3I:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/K5qph21HQEg" height="1" width="1" alt=""/>]]></content:encoded>
      </item>
      <item>
         <title>ASP.NET 5 and AngularJS Part 6, Security</title>
         <link>http://feedproxy.google.com/~r/StephenWalther/~3/cpX2qAdeR58/asp-net-5-and-angularjs-part-6-security</link>
         <description>This is the sixth part in a multiple part blog series on building ASP.NET 5 (ASP.NET vNext) apps with AngularJS. In this series of blog posts, I show how you can create a simple Movie app using ASP.NET 5, MVC 6, and AngularJS. ASP.NET 5 and AngularJS Part 1, Grunt, Uglify, and AngularJS ASP.NET 5 [&amp;#8230;]</description>
         <guid isPermaLink="false">http://stephenwalther.com/?p=937</guid>
         <pubDate>Thu, 29 Jan 2015 18:20:09 +0000</pubDate>
         <content:encoded><![CDATA[<p>This is the sixth part in a multiple part blog series on building ASP.NET 5 (ASP.NET vNext) apps with AngularJS. In this series of blog posts, I show how you can create a simple Movie app using ASP.NET 5, MVC 6, and AngularJS.</p>
<ul>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 1, Grunt, Uglify, and AngularJS</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 2, Using the MVC 6 Web API</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 3, Adding Client Routing</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 4, Using Entity Framework 7</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 5, Form Validation</a>
</li>
<li>
  <b><a rel="nofollow">ASP.NET 5 and AngularJS Part 6, Security</a></b>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 7, Running on a Mac</a>
</li>
</ul>
<p>You can download the code discussed in this blog post from GitHub:</p>
<p><a rel="nofollow" target="_blank" href="https://github.com/StephenWalther/MovieAngularJSApp">https://github.com/StephenWalther/MovieAngularJSApp</a></p>
<p>In this blog post, I explain how you can use ASP.NET Identity to provide different permissions to different users. In particular, I demonstrate how to create two users named Stephen and Bob. Stephen will have edit permissions on the Movies database and Bob will not.</p>
<p>Here’s what Stephen’s screen looks like:</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/01StephenList.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/01StephenList.png" alt="Stephen Screen" width="900" height="612" class="alignnone size-full wp-image-938"/></a></p>
<p>Notice that Stephen can edit, delete, and add movies.</p>
<p>Now, here is what Bob’s screen looks like:</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/02BobList.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/02BobList.png" alt="Bob List" width="900" height="612" class="alignnone size-full wp-image-939"/></a> </p>
<p>Bob cannot do anything except view the list of movies. He is not allowed to edit or add movies.</p>
<h2>Enabling ASP.NET Identity</h2>
<p>The first step is to pull in all of the NuGet packages that we need to use ASP.NET Identity. You need to add the following packages to the dependencies section of your project.json file:</p>
<pre>
  &quot;dependencies&quot;: {
	&quot;EntityFramework.SqlServer&quot;: &quot;7.0.0-beta2&quot;,
	&quot;EntityFramework.Commands&quot;: &quot;7.0.0-beta2&quot;,
	&quot;Microsoft.AspNet.Mvc&quot;: &quot;6.0.0-beta2&quot;,
	/* &quot;Microsoft.AspNet.Mvc.WebApiCompatShim&quot;: &quot;6.0.0-beta2&quot;, */
	&quot;Microsoft.AspNet.Diagnostics&quot;: &quot;1.0.0-beta2&quot;,
	&quot;Microsoft.AspNet.Diagnostics.Entity&quot;: &quot;7.0.0-beta2&quot;,
	&quot;Microsoft.AspNet.Identity.EntityFramework&quot;: &quot;3.0.0-beta2&quot;,
	&quot;Microsoft.AspNet.Security.Cookies&quot;: &quot;1.0.0-beta2&quot;,
	&quot;Microsoft.AspNet.Server.IIS&quot;: &quot;1.0.0-beta2&quot;,
	&quot;Microsoft.AspNet.Server.WebListener&quot;: &quot;1.0.0-beta2&quot;,
	&quot;Microsoft.AspNet.StaticFiles&quot;: &quot;1.0.0-beta2&quot;,
	&quot;Microsoft.Framework.ConfigurationModel.Json&quot;: &quot;1.0.0-beta2&quot;,
	&quot;Microsoft.Framework.CodeGenerators.Mvc&quot;: &quot;1.0.0-beta2&quot;,
	&quot;Microsoft.Framework.Logging&quot;: &quot;1.0.0-beta2&quot;,
	&quot;Microsoft.Framework.Logging.Console&quot;: &quot;1.0.0-beta2&quot;,
	&quot;Microsoft.VisualStudio.Web.BrowserLink.Loader&quot;: &quot;14.0.0-beta1&quot;
  },
</pre>
<p>Notice that I am including the Microsoft.AspNet.Identity.EntityFramework and Microsoft.AspNet.Security.Cookies packages.  These packages pull in additional dependencies such as Microsoft.AspNet.Identity and Microsoft.AspNet.Security.</p>
<p>Next, you need to update the ConfigureServices() method in your Startup.cs file. The ConfigureServices() method is used to register services with the built-in Dependency Injection framework included with ASP.NET 5:</p>
<pre>
public void ConfigureServices(IServiceCollection services)
{
	// add Entity Framework
	services.AddEntityFramework(Configuration)
			.AddSqlServer()
			.AddDbContext&lt;MoviesAppContext&gt;(options =&gt;
			{
				options.UseSqlServer(Configuration.Get(&quot;Data:DefaultConnection:ConnectionString&quot;));
			});

	// add ASP.NET Identity
	services.AddIdentity&lt;ApplicationUser, IdentityRole&gt;(Configuration)
		.AddEntityFrameworkStores&lt;MoviesAppContext&gt;();

	// add ASP.NET MVC
	services.AddMvc();
}
</pre>
<p>Notice that I am adding the Identity service. When I register the service, I specify that I will be use the Identity service with the Entity Framework as my data store for storing usernames and passwords.  If I was running my app outside of Windows – for example, using OSX – then I could use an alternative data store such as SQLite.  </p>
<p>See the following URL for the list of providers that Microsoft plans to support with Entity Framework 7:</p>
<p><a rel="nofollow" target="_blank" href="https://github.com/aspnet/EntityFramework/wiki/Using-EF7-in-Traditional-.NET-Applications">https://github.com/aspnet/EntityFramework/wiki/Using-EF7-in-Traditional-.NET-Applications</a></p>
<p>Finally, we need to update the Configure() method in the Startup.cs file. The Configure() method – unlike the ConfigureServices() method – is used by OWIN to configure the application pipeline. Here’s what our updated Configure() method looks like:</p>
<pre>
public void Configure(IApplicationBuilder app)
{
	app.UseIdentity();
	app.UseMvc();

	CreateSampleData(app.ApplicationServices).Wait();
}
</pre>
<p>Notice that I call app.UseIdentity() to add ASP.NET Identity to the application pipeline. I explain the CreateSampleData() method below.</p>
<h2>Modifying Your DbContext</h2>
<p>In order to take advantage of ASP.NET Identity, we need to modify our DbContext class.  Here’s the updated MoviesAppContext:</p>
<pre>
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Data.Entity;
using System;

namespace MovieAngularJSApp.Models
{
    public class ApplicationUser : IdentityUser {}

    public class MoviesAppContext : IdentityDbContext&lt;ApplicationUser&gt;
    {
		public DbSet&lt;Movie&gt; Movies { get; set; }
	}
}
</pre>
<p>Notice that the modified MoviesAppContext now inherits from the base IdentityDbContext class. Inheriting from this base class adds all of the additional entities required by the Entity Framework. If you open up your database then you can see all of the extra tables that you get after inheriting from IdentityDbContext:</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/03NewTables.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/03NewTables.png" alt="ASP.NET Identity Tables" width="641" height="724" class="alignnone size-full wp-image-940"/></a>  </p>
<p>Notice that I get additional database tables such as the AspNetUsers and AspNetUserClaims tables.<br />
Adding Users at Startup</p>
<p>We want to add the Stephen and Bob users to our database automatically at startup. Therefore, I am going to modify the Startup.cs file so that it creates the database and adds sample data to the database automatically:</p>
<pre>
public void Configure(IApplicationBuilder app)
{
	app.UseIdentity();
	app.UseMvc();

	CreateSampleData(app.ApplicationServices).Wait();
}


private static async Task CreateSampleData(IServiceProvider applicationServices)
{
	using (var dbContext = applicationServices.GetService&lt;MoviesAppContext&gt;())
	{
		var sqlServerDatabase = dbContext.Database as SqlServerDatabase;
		if (sqlServerDatabase != null)
		{
			// Create database in user root (c:&#92;users&#92;your name)
			if (await sqlServerDatabase.EnsureCreatedAsync()) {
				// add some movies
				var movies = new List&lt;Movie&gt;
				{
					new Movie {Title=&quot;Star Wars&quot;, Director=&quot;Lucas&quot;},
					new Movie {Title=&quot;King Kong&quot;, Director=&quot;Jackson&quot;},
					new Movie {Title=&quot;Memento&quot;, Director=&quot;Nolan&quot;}
				};
				movies.ForEach(m =&gt; dbContext.Movies.AddAsync(m));

				// add some users
				var userManager = applicationServices.GetService&lt;UserManager&lt;ApplicationUser&gt;&gt;();

				// add editor user
				var stephen = new ApplicationUser
				{
					UserName = &quot;Stephen&quot;
				};
				var result = await userManager.CreateAsync(stephen, &quot;P@ssw0rd&quot;);
				await userManager.AddClaimAsync(stephen, new Claim(&quot;CanEdit&quot;, &quot;true&quot;));

				// add normal user
				var bob = new ApplicationUser
				{
					UserName = &quot;Bob&quot;
				};
				await userManager.CreateAsync(bob, &quot;P@ssw0rd&quot;);
			}

		}
	}
}
</pre>
<p>Notice that I create an async static method named CreateSampeData(). I need to make the CreateSampleData() method async because the ASP.NET Identity methods are async.</p>
<p>The CreateSampleData() method first ensures that the MoviesDatabase exists. If it does not, the EnsureCreatedAsync() method creates it.</p>
<p>Next, three movies are added to the Movies database table. Each movie is added by calling the dbContext.Movies.AddAsync() method.</p>
<p>Finally, two users are added to the database: Stephen and Bob. The users are added by calling the UserManager.CreateAsync() method.</p>
<p>A claim is added to the Stephen user. Stephen is provided with CanEdit permissions. We’ll use this claim in our Movies app to enable Stephen, but not Bob, to edit movies.</p>
<p>Whenever you want to recreate the sample data, you can just delete the MoviesDatabase database. In Visual Studio, open the SQL Server Object Explorer window, right-click your database, and select the Delete menu option. Make sure that you check Close existing connections or you will be blocked from deleting the database.</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/04DeleteDatabase.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/04DeleteDatabase.png" alt="Delete Database" width="900" height="637" class="alignnone size-full wp-image-941"/></a> </p>
<h2>Forcing Users to Login</h2>
<p>Now that we have the basic setup out of the way, we can force users to login by adding an [Authorize] attribute to our Home controller like this:</p>
<pre>
using Microsoft.AspNet.Mvc;
using System.Security.Claims;

namespace MovieAngularJSApp.Controllers
{
	[Authorize]
	public class HomeController : Controller
    {
        
        public IActionResult Index()
        {
		var user = (ClaimsIdentity)User.Identity;
		ViewBag.Name = user.Name;
		ViewBag.CanEdit = user.FindFirst(&quot;CanEdit&quot;) != null ? &quot;true&quot; : &quot;false&quot;;
		return View();
        }
    }
}
</pre>
<p>If an anonymous user attempts to navigate to the root of our app then the anonymous user will be redirected to the /account/login controller action. Here’s what the Login() methods look like in the AccountController:</p>
<pre>
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using MovieAngularJSApp.Models;
using System.Threading.Tasks;

namespace MovieAngularJSApp.Controllers
{
    public class AccountController : Controller
    {
		private UserManager&lt;ApplicationUser&gt; _userManager;
		private SignInManager&lt;ApplicationUser&gt; _signInManager;


		public AccountController(UserManager&lt;ApplicationUser&gt; userManager, SignInManager&lt;ApplicationUser&gt; signInManager)
		{
			_userManager = userManager;
			_signInManager = signInManager;
		}


		public IActionResult Login()
        {
            return View();
        }

		[HttpPost]
		public async Task&lt;IActionResult&gt; Login(LoginViewModel login, string returnUrl = null)
		{
			var signInStatus = await _signInManager.PasswordSignInAsync(login.UserName, login.Password, false, false);
			if (signInStatus == SignInStatus.Success)
			{
				return Redirect(&quot;/home&quot;);
			}
			ModelState.AddModelError(&quot;&quot;, &quot;Invalid username or password.&quot;);
			return View();
		}


		public IActionResult SignOut()
		{
			_signInManager.SignOut();
			return Redirect(&quot;/home&quot;);
		}

	}
}
</pre>
<p>The UserManager and SignInManager classes are passed to the AccountController through the built-in ASP.NET 5 dependency injection. The Login() method calls the SignInManager.PasswordSignInAsync() method to validate the username and password combination entered by the user.  If the combination validates then the user is redirected back to the Home controller.</p>
<h2>Passing Claims Data to AngularJS</h2>
<p>Stephen can edit movies but not Bob. To make this work, we need to pass the claims data associated with the Stephen and Bob users from the server (ASP.NET) to the client (AngularJS).</p>
<p>In the Home controller, we add the CanEdit claim to the ViewBag like this:</p>
<pre>
using Microsoft.AspNet.Mvc;
using System.Security.Claims;

namespace MovieAngularJSApp.Controllers
{
	[Authorize]
	public class HomeController : Controller
    {
        
        public IActionResult Index()
        {
		var user = (ClaimsIdentity)User.Identity;
		ViewBag.Name = user.Name;
		ViewBag.CanEdit = user.FindFirst(&quot;CanEdit&quot;) != null ? &quot;true&quot; : &quot;false&quot;;
		return View();
        }
    }
}
</pre>
<p>We cast the user identity as a ClaimsIdentity and then we assign the value of the CanEdit claim to the ViewBag.CanEdit property. Because Stephen has the CanEdit claim, the ViewBag.CanEdit property will have the value “true” (we need to use a string here because Boolean.ToString() gets converted to “True” instead of “true” which confuses our JavaScript).</p>
<p>Here’s what our modified Index view looks like:</p>
<pre>
&lt;!DOCTYPE html&gt;
&lt;html ng-app=&quot;moviesApp&quot;&gt;
&lt;head&gt;
	&lt;base href=&quot;/&quot;&gt;
	&lt;meta charset=&quot;utf-8&quot; /&gt;
	&lt;title&gt;Movies&lt;/title&gt;

	&lt;!-- jQuery --&gt;
	&lt;script src=&quot;//code.jquery.com/jquery-1.11.2.min.js&quot;&gt;&lt;/script&gt;

	&lt;!-- AngularJS--&gt;
	&lt;script src=&quot;//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js&quot;&gt;&lt;/script&gt;
	&lt;script src=&quot;//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-resource.js&quot;&gt;&lt;/script&gt;
	&lt;script src=&quot;//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-route.js&quot;&gt;&lt;/script&gt;

	&lt;!-- Bootstrap --&gt;
	&lt;link rel=&quot;stylesheet&quot; href=&quot;https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css&quot;&gt;
	&lt;link rel=&quot;stylesheet&quot; href=&quot;https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css&quot;&gt;
	&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.12.0/ui-bootstrap-tpls.min.js&quot;&gt;&lt;/script&gt;


	&lt;!-- App --&gt;
	&lt;link rel=&quot;stylesheet&quot; href=&quot;/styles.css&quot; /&gt;
	&lt;script src=&quot;/app.js&quot;&gt;&lt;/script&gt;

	&lt;!-- Get Server Data --&gt;
	&lt;script&gt;
		angular.module(&quot;moviesApp&quot;).value(&quot;canEdit&quot;, @ViewBag.CanEdit);
	&lt;/script&gt;

&lt;/head&gt;
&lt;body ng-cloak&gt;

	@ViewBag.Name / &lt;a href=&quot;/account/signout&quot; target=&quot;_self&quot;&gt;sign out&lt;/a&gt;

	&lt;div class=&quot;container-fluid&quot;&gt;
		&lt;ng-view&gt;&lt;/ng-view&gt;
	&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Notice the section of the page labeled Get Server Data. The value of the CanEdit claim is assigned to an AngularJS module value named “canEdit”.  The canEdit value is used in the AngularJS moviesListController like this:</p>
<pre>
/* Movies List Controller  */
MoviesListController.$inject = ['$scope', 'Movie', 'canEdit'];

function MoviesListController($scope, Movie, canEdit) {
    $scope.canEdit = canEdit;
    $scope.movies = Movie.query();
}
</pre>
<p>The canEdit value is injected into the controller and assigned to the controller’s scope. This makes the canEdit value available in the AngularJS list view which is used to display the list of movies:</p>
<pre>
&lt;div&gt;
    &lt;h1&gt;List Movies&lt;/h1&gt;
    &lt;table class=&quot;table table-bordered table-striped&quot;&gt;
        &lt;thead&gt;
            &lt;tr&gt;
                &lt;th ng-show=&quot;canEdit&quot;&gt;&lt;/th&gt;
                &lt;th&gt;Title&lt;/th&gt;
                &lt;th&gt;Director&lt;/th&gt;
            &lt;/tr&gt;
        &lt;/thead&gt;
        &lt;tbody&gt;
            &lt;tr ng-repeat=&quot;movie in movies&quot;&gt;
                &lt;td ng-show=&quot;canEdit&quot;&gt;
                    &lt;a href=&quot;/movies/edit/{{movie.Id}}&quot; class=&quot;btn btn-default btn-xs&quot;&gt;edit&lt;/a&gt;
                    &lt;a href=&quot;/movies/delete/{{movie.Id}}&quot; class=&quot;btn btn-danger btn-xs&quot;&gt;delete&lt;/a&gt;
                &lt;/td&gt;
                &lt;td&gt;{{movie.Title}}&lt;/td&gt;
                &lt;td&gt;{{movie.Director}}&lt;/td&gt;
            &lt;/tr&gt;
        &lt;/tbody&gt;
    &lt;/table&gt;

    &lt;p ng-show=&quot;canEdit&quot;&gt;
        &lt;a href=&quot;/movies/add&quot; class=&quot;btn btn-primary&quot;&gt;Add New Movie&lt;/a&gt;
    &lt;/p&gt;
&lt;/div&gt;
</pre>
<p>Notice that the AngularJS ng-show directive is used twice in the list view. The ng-show directive is used to hide or display the first column of the  HTML table that lists the movies (this hides or shows the Movie edit and delete buttons). The ng-show directive also is used to hide or show the Add New Movie button at the bottom of the view.</p>
<p>Because Stephen has the CanEdit claim, when Stephen opens the List view, Stephen sees the edit, delete, and add buttons:</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/01StephenList.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/01StephenList.png" alt="Stephen Screen" width="900" height="612" class="alignnone size-full wp-image-938"/></a> </p>
<p>However, Bob does not have the CanEdit claim. Therefore, Bob does not get these buttons:</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/02BobList.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/02BobList.png" alt="Bob List" width="900" height="612" class="alignnone size-full wp-image-939"/></a> </p>
<h2>Securing API Controller Actions</h2>
<p>There is one last thing that we need to do to make this all work.  Bob cannot see the edit buttons but Bob could, if he is feeling super sneaky, bypass the views and post new movies directly to the Movies API controller. </p>
<p>Here’s how we block this from happening:</p>
<pre>
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Mvc;
using MovieAngularJSApp.Models;
using System.Security.Claims;

namespace MovieAngularJSApp.API.Controllers
{
    [Route(&quot;api/[controller]&quot;)]
    public class MoviesController : Controller
    {
		private readonly MoviesAppContext _dbContext;

		public MoviesController(MoviesAppContext dbContext) 
		{
			_dbContext = dbContext;
		}

        [HttpGet]
        public IEnumerable&lt;Movie&gt; Get()
        {
			return _dbContext.Movies;
        }


        [HttpGet(&quot;{id:int}&quot;)]
        public IActionResult Get(int id)
        {
			var movie = _dbContext.Movies.FirstOrDefault(m =&gt; m.Id == id);
			if (movie == null) {
				return new HttpNotFoundResult();
			} else {
				return new ObjectResult(movie);
            }
		}


        [HttpPost]
		[Authorize(&quot;CanEdit&quot;, &quot;true&quot;)]
        public IActionResult Post([FromBody]Movie movie)
        {
			if (ModelState.IsValid)
			{
				if (movie.Id == 0)
				{
					_dbContext.Movies.Add(movie);
					_dbContext.SaveChanges();
					return new ObjectResult(movie);
				}
				else
				{
					var original = _dbContext.Movies.FirstOrDefault(m =&gt; m.Id == movie.Id);
					original.Title = movie.Title;
					original.Director = movie.Director;
					original.TicketPrice = movie.TicketPrice;
					original.ReleaseDate = movie.ReleaseDate;
					_dbContext.SaveChanges();
					return new ObjectResult(original);
				}
			}

			// This will work in later versions of ASP.NET 5
			//return new BadRequestObjectResult(ModelState);
			return null;
		}


		[Authorize(&quot;CanEdit&quot;, &quot;true&quot;)]
		[HttpDelete(&quot;{id:int}&quot;)]
        public IActionResult Delete(int id)
        {
			var movie = _dbContext.Movies.FirstOrDefault(m =&gt; m.Id == id);
			_dbContext.Movies.Remove(movie);
			_dbContext.SaveChanges();
            return new HttpStatusCodeResult(200);
        }


    }
}
</pre>
<p>Notice that both the Post() and Delete() actions in the MoviesController in the code above are decorated with [Authorize] attributes. The [Authorize] attributes are used to verify that the person invoking the controller action has the CanEdit claim.</p>
<p>If Bob, who does not have the CanEdit claim, attempts to invoke either action then Bob will be blocked. Bob will get a 302 redirect that redirects the Ajax API call back to the /account/login view:</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/05Redirect.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/05Redirect.png" alt="ASP.NET Identity Redirect" width="900" height="283" class="alignnone size-full wp-image-942"/></a> </p>
<p>Bob’s Ajax request gets redirected because a 401 Status code automatically triggers the ASP.NET framework to redirect the user to the Login page. This is true even when making an Ajax request.</p>
<h2>Summary</h2>
<p>In this blog post, I described how you can use ASP.NET Identity in an ASP.NET 5 app. I demonstrated how you can create users automatically when an ASP.NET app starts. Next, I showed you how you can pass user claims information from the server (ASP.NET) to the client (AngularJS).  We used the CanEdit claim in our AngularJS app to hide or display the movie edit, delete, and add buttons.</p>
<p>In my next blog post, I am going to focus on using ASP.NET 5 outside of Windows. I want to get the Movies app working on my MacBookPro running OSX Yosemite.</p>
<div class="feedflare">
<a rel="nofollow" target="_blank" href="http://feeds.feedburner.com/~ff/StephenWalther?a=cpX2qAdeR58:WHvxl_fbGF4:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/cpX2qAdeR58" height="1" width="1" alt=""/>]]></content:encoded>
      </item>
      <item>
         <title>ASP.NET 5 and AngularJS Part 5, Form Validation</title>
         <link>http://feedproxy.google.com/~r/StephenWalther/~3/D-BCGCMY0TQ/asp-net-5-and-angularjs-part-5-form-validation</link>
         <description>This is the fifth part in a multiple part blog series on building ASP.NET 5 (ASP.NET vNext) apps with AngularJS. In this series of blog posts, I show how you can create a simple Movie app using ASP.NET 5, MVC 6, and AngularJS. ASP.NET 5 and AngularJS Part 1, Grunt, Uglify, and AngularJS ASP.NET 5 [&amp;#8230;]</description>
         <guid isPermaLink="false">http://stephenwalther.com/?p=929</guid>
         <pubDate>Sun, 18 Jan 2015 01:28:49 +0000</pubDate>
         <content:encoded><![CDATA[<p>This is the fifth part in a multiple part blog series on building ASP.NET 5 (ASP.NET vNext) apps with AngularJS. In this series of blog posts, I show how you can create a simple Movie app using ASP.NET 5, MVC 6, and AngularJS.</p>
<ul>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 1, Grunt, Uglify, and AngularJS</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 2, Using the MVC 6 Web API</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 3, Adding Client Routing</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 4, Using Entity Framework 7</a>
</li>
<li>
  <b><a rel="nofollow">ASP.NET 5 and AngularJS Part 5, Form Validation</a></b>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 6, Security</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 7, Running on a Mac</a>
</li>
</ul>
<p>You can download the code discussed in this blog post from GitHub:</p>
<p><a rel="nofollow" target="_blank" href="https://github.com/StephenWalther/MovieAngularJSApp">https://github.com/StephenWalther/MovieAngularJSApp</a></p>
<p>In this blog post, I explain how to implement both client-side and server-side form validation.</p>
<h2>Client-Side Validation</h2>
<p>Let’s start with the client-side validation. We’ll use the built-in features of AngularJS to validate the movie add and edit forms.</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/AddMovie1.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/AddMovie1.png" alt="AddMovie" width="900" height="678" class="alignnone size-full wp-image-931"/></a></p>
<p>Here’s the add.html page:</p>
<pre>
&lt;h1&gt;Add Movie&lt;/h1&gt;
&lt;div class=&quot;row&quot;&gt;
    &lt;div class=&quot;col-md-5&quot;&gt;

        &lt;form name=&quot;formAdd&quot; novalidate ng-submit=&quot;add()&quot;&gt;

			 &lt;ng-include src=&quot;'/partials/_edit.html'&quot;&gt;&lt;/ng-include&gt;

            &lt;a href=&quot;/&quot; class=&quot;btn btn-default&quot;&gt;Cancel&lt;/a&gt;
			&lt;button type=&quot;submit&quot; ng-disabled=&quot;formAdd.$invalid&quot; class=&quot;btn btn-primary&quot;&gt;Save&lt;/button&gt;
        &lt;/form&gt;


    &lt;/div&gt;
&lt;/div&gt;
</pre>
<p>And, here’s the edit.html page:</p>
<pre>
&lt;h1&gt;Edit Movie&lt;/h1&gt;

&lt;div class=&quot;row&quot;&gt;
    &lt;div class=&quot;col-md-5&quot;&gt;

        &lt;form name=&quot;formEdit&quot; novalidate ng-submit=&quot;edit()&quot;&gt;
            
			&lt;ng-include src=&quot;'/partials/_edit.html'&quot;&gt;&lt;/ng-include&gt;

            &lt;a href=&quot;/&quot; class=&quot;btn btn-default&quot;&gt;Cancel&lt;/a&gt;
			&lt;button type=&quot;submit&quot; ng-disabled=&quot;formAdd.$invalid&quot; class=&quot;btn btn-primary&quot;&gt;Save&lt;/button&gt;
        &lt;/form&gt;


    &lt;/div&gt;
&lt;/div&gt;
</pre>
<p>The add and edit forms contain the FORM element and the BUTTON elements for the forms. The FORM element includes a novalidate attribute that disables HTML5 validation. This is necessary because the HTML5 validation attributes conflict with the AngularJS validation directives.</p>
<p>Notice that the BUTTON element includes an ng-disabled directive. This directive is used to prevent a user from submitting the form when there are any client-side validation errors.</p>
<p>You’ll notice that both forms use the ng-include directive to include a partial named _edit.html. The _edit.html contains the actual form fields.</p>
<pre>
&lt;div class=&quot;bg-danger validationErrors&quot; ng-show=&quot;validationErrors&quot;&gt;
	&lt;ul&gt;
		&lt;li ng-repeat=&quot;error in validationErrors&quot;&gt;{{error}}&lt;/li&gt;
	&lt;/ul&gt;
&lt;/div&gt; 

&lt;div class=&quot;form-group&quot;&gt;
	&lt;label for=&quot;Title&quot;&gt;Movie Title&lt;/label&gt;
	&lt;input name=&quot;Title&quot;
		   type=&quot;text&quot;
		   class=&quot;form-control&quot;
		   placeholder=&quot;Enter title&quot;
		   ng-model=&quot;movie.Title&quot;
		   ng-required=&quot;true&quot;
		   ng-minlength=&quot;3&quot; /&gt;
&lt;/div&gt;
&lt;div class=&quot;form-group&quot;&gt;
	&lt;label for=&quot;Director&quot;&gt;Director&lt;/label&gt;
	&lt;input name=&quot;Director&quot; 
		   type=&quot;text&quot; 
		   class=&quot;form-control&quot; 
		   placeholder=&quot;Enter director&quot; 
		   ng-model=&quot;movie.Director&quot;
		   ng-required=&quot;true&quot; /&gt;
&lt;/div&gt;
&lt;div class=&quot;form-group&quot;&gt;
	&lt;label for=&quot;TicketPrice&quot;&gt;Ticket Price&lt;/label&gt;
	&lt;input name=&quot;TicketPrice&quot; 
		   type=&quot;text&quot; 
		   class=&quot;form-control&quot; 
		   placeholder=&quot;Enter ticket price&quot; 
		   ng-model=&quot;movie.TicketPrice&quot;&gt;
&lt;/div&gt;
&lt;div class=&quot;form-group&quot;&gt;
	&lt;label for=&quot;Release&quot;&gt;Release Date&lt;/label&gt;
	&lt;p class=&quot;input-group&quot; ng-controller=&quot;DatePickerController&quot;&gt;
		&lt;input type=&quot;text&quot; 
			   class=&quot;form-control&quot; 
			   datepicker-popup 
			   ng-model=&quot;movie.ReleaseDate&quot; 
			   is-open=&quot;opened&quot; /&gt;	
		&lt;span class=&quot;input-group-btn&quot;&gt;
			&lt;button type=&quot;button&quot;
					class=&quot;btn btn-default&quot;
					ng-click=&quot;open($event)&quot;&gt;
				&lt;i class=&quot;glyphicon glyphicon-calendar&quot;&gt;&lt;/i&gt;
			&lt;/button&gt;
		&lt;/span&gt;
	&lt;/p&gt;
&lt;/div&gt;
</pre>
<p>The _edit.html form contains fields for the movie Title, Director, Ticket Price and Release Date.  AngularJS directives are used to perform the following validation:</p>
<ul>
<li>
<p>
  Title – Required, Must be at least 3 characters.
  </p>
</li>
<li>
<p>
  Director – Required.
  </p>
</li>
<li>
<p>
  TicketPrice – Required.
  </p>
</li>
</ul>
<p>If validation fails, then the ng-invalid CSS class is applied to the field and the field appears with a red background.</p>
<pre>
input.ng-invalid.ng-touched {
    background-color: #FA787E;
}

input.ng-valid.ng-touched {
    background-color: #78FA89;
}
</pre>
<p>I ran into one minor wrinkle when I created the _edit.html partial. When the partial was requested from the server, the web.config file that I created in part 3 of this blog series redirected the request to the index.html page and I got an infinite regression. To flatten this wrinkle, I had to exclude the /partials/ folder from the path rewrite.</p>
<pre>
&lt;!-- from http://stackoverflow.com/questions/25916851/wrapping-staticfilemiddleware-to-redirect-404-errors --&gt;

&lt;configuration&gt;
&lt;system.webServer&gt;
  &lt;modules runAllManagedModulesForAllRequests=&quot;true&quot; /&gt;
  &lt;rewrite&gt;
    &lt;rules&gt;
      &lt;!--Redirect selected traffic to index --&gt;
      &lt;rule name=&quot;Index Rule&quot; stopProcessing=&quot;true&quot;&gt;
        &lt;match url=&quot;.*&quot; /&gt;
        &lt;conditions logicalGrouping=&quot;MatchAll&quot;&gt;
          &lt;add input=&quot;{REQUEST_FILENAME}&quot; matchType=&quot;IsFile&quot; negate=&quot;true&quot; /&gt;
          &lt;add input=&quot;{REQUEST_URI}&quot; matchType=&quot;Pattern&quot; pattern=&quot;^/api/&quot; negate=&quot;true&quot; /&gt;
		  &lt;add input=&quot;{REQUEST_URI}&quot; matchType=&quot;Pattern&quot; pattern=&quot;^/partials/&quot; negate=&quot;true&quot; /&gt;
		&lt;/conditions&gt;
        &lt;action type=&quot;Rewrite&quot; url=&quot;/index.html&quot; /&gt;
      &lt;/rule&gt;
    &lt;/rules&gt;
  &lt;/rewrite&gt;
&lt;/system.webServer&gt;
&lt;/configuration&gt;
</pre>
<h2>Updating the Movie Model</h2>
<p>Client-side validation is only one half of the validation story. The other half of validation is handled by the ASP.NET 5 framework.</p>
<p>Here’s what the updated Movie model looks like:</p>
<pre>
using System;
using System.ComponentModel.DataAnnotations;

namespace MovieAngularJSApp.Models
{
    public class Movie
    {
        public int Id { get; set; }

		[Required(ErrorMessage=&quot;Movie Title is Required&quot;)]
		[MinLength(3, ErrorMessage=&quot;Movie Title must be at least 3 characters&quot;)]
		public string Title { get; set; }

		[Required(ErrorMessage = &quot;Movie Director is Required.&quot;)]
        public string Director { get; set; }

		[Range(0, 100, ErrorMessage =&quot;Ticket price must be between 0 and 100 dollars.&quot;)]
		public decimal TicketPrice { get; set; }

		[Required(ErrorMessage=&quot;Movie Release Date is required&quot;)]
		public DateTime ReleaseDate { get; set; }
	}
}
</pre>
<p>Notice that validation attributes are applied to the properties of the Movies model. For example, the [Required] and [MinLength] attributes are applied to the Title property.</p>
<h2>Updating the Movies Database</h2>
<p>Because I made changes to the Movie model, I need to update the database to match the new model.  I opened up a Command Prompt, navigated to the project folder and ran the following two commands:</p>
<pre>
k ef migration add movieProps
k ef migration apply
</pre>
<p>Unfortunately, the second command threw an exception because I was trying to add a DateTime column to the existing Movies database table. Because the table already contains data, I got the exception. </p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/EFErrors.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/EFErrors.png" alt="EFErrors" width="900" height="419" class="alignnone size-full wp-image-933"/></a> </p>
<p>The easiest fix for this issue is to drop the database. I found the MoviesDatabase.mdf and MoviesDatabase_log.ldf in my c:&#92;users&#92;stephen folder and deleted the two files. When I ran the k ef migration apply command again, everything worked fine.</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/EFWorks.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/EFWorks.png" alt="EFWorks" width="900" height="240" class="alignnone size-full wp-image-934"/></a> </p>
<h2>Updating the Server Controller</h2>
<p>The next step is to update the Web API controller on the server.  The modified MoviesController looks like this:</p>
<pre>
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Mvc;
using MovieAngularJSApp.Models;


namespace MovieAngularJSApp.API.Controllers
{
    [Route(&quot;api/[controller]&quot;)]
    public class MoviesController : Controller
    {
		private readonly MoviesAppContext _dbContext;

		public MoviesController(MoviesAppContext dbContext) 
		{
			_dbContext = dbContext;
		}

        [HttpGet]
        public IEnumerable&lt;Movie&gt; Get()
        {
			return _dbContext.Movies;
        }


        [HttpGet(&quot;{id:int}&quot;)]
        public IActionResult Get(int id)
        {
			var movie = _dbContext.Movies.FirstOrDefault(m =&gt; m.Id == id);
			if (movie == null) {
				return new HttpNotFoundResult();
			} else {
				return new ObjectResult(movie);
            }
		}


        [HttpPost]
        public IActionResult Post([FromBody]Movie movie)
        {
			if (ModelState.IsValid)
			{
				if (movie.Id == 0)
				{
					_dbContext.Movies.Add(movie);
					_dbContext.SaveChanges();
					return new ObjectResult(movie);
				}
				else
				{
					var original = _dbContext.Movies.FirstOrDefault(m =&gt; m.Id == movie.Id);
					original.Title = movie.Title;
					original.Director = movie.Director;
					original.TicketPrice = movie.TicketPrice;
					original.ReleaseDate = movie.ReleaseDate;
					_dbContext.SaveChanges();
					return new ObjectResult(original);
				}
			}
			return new BadRequestObjectResult(ModelState);
			
		}


		[HttpDelete(&quot;{id:int}&quot;)]
        public IActionResult Delete(int id)
        {
			var movie = _dbContext.Movies.FirstOrDefault(m =&gt; m.Id == id);
			_dbContext.Movies.Remove(movie);
			_dbContext.SaveChanges();
            return new HttpStatusCodeResult(200);
        }


    }
}
</pre>
<p>Notice that the Post() method (called by both the Add and Edit forms) checks ModelState. If ModelState is not valid then the following line of code is executed:</p>
<pre>
return new BadRequestObjectResult(ModelState);
</pre>
<p>The BadRequestObjectResult action result returns all of the validation error messages in ModelState to the client. The BadRequestObjectResult also returns a 400 Bad Request status code.</p>
<p>Here’s what the response looks like in Chrome Developer Tools:</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/DeveloperTools.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/DeveloperTools.png" alt="DeveloperTools" width="900" height="165" class="alignnone size-full wp-image-932"/></a> </p>
<p>Be warned that the BadRequestObjectResult is not included in Beta 2 of the ASP.NET 5 framework. You need to switch to Beta 3. I describe how to use the Nightly Builds of ASP.NET 5 in the following blog post:</p>
<p>http://stephenwalther.com/archive/2015/01/15/upgrading-visual-studio-2015-preview-to-asp-net-5mvc-6-rc</p>
<h2>Updating the Client Controllers</h2>
<p>The very final step is to update the client-side controllers to display any validation errors returned from the server. </p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/ModelStateError.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/ModelStateError.png" alt="ModelStateError" width="900" height="647" class="alignnone size-full wp-image-935"/></a> </p>
<p>The moviesControllers.js file below contains updated  MoviesAddController and MoviesEditController functions. </p>
<pre>
(function () {
    'use strict';

    angular
        .module('moviesApp')
        .controller('MoviesListController', MoviesListController)
        .controller('MoviesAddController', MoviesAddController)
        .controller('MoviesEditController', MoviesEditController)
        .controller('MoviesDeleteController', MoviesDeleteController)
        .controller('DatePickerController', DatePickerController);

    /* Movies List Controller  */
    MoviesListController.$inject = ['$scope', 'Movie'];

    function MoviesListController($scope, Movie) {
        $scope.movies = Movie.query();
    }

    /* Movies Create Controller */
    MoviesAddController.$inject = ['$scope', '$location', 'Movie'];

    function MoviesAddController($scope, $location, Movie) {
        $scope.movie = new Movie();
        $scope.add = function () {
        	$scope.movie.$save(
				// success
				function () {
					$location.path('/');
				},
				// error
				function (error) {
					_showValidationErrors($scope, error);
				}
			);
        };

    }

    /* Movies Edit Controller */ 
    MoviesEditController.$inject = ['$scope', '$routeParams', '$location', 'Movie'];

    function MoviesEditController($scope, $routeParams, $location, Movie) {
        $scope.movie = Movie.get({ id: $routeParams.id });
        $scope.edit = function () {
        	$scope.movie.$save(
				// success
				function () {
					$location.path('/');
				},
				// error
				function (error) {
					_showValidationErrors($scope, error);
				}
			);
        };
    }

    /* Movies Delete Controller  */
    MoviesDeleteController.$inject = ['$scope', '$routeParams', '$location', 'Movie'];

    function MoviesDeleteController($scope, $routeParams, $location, Movie) {
        $scope.movie = Movie.get({ id: $routeParams.id });
        $scope.remove = function () {
            $scope.movie.$remove({id:$scope.movie.Id}, function () {
                $location.path('/');
            });
        };
    }

	/* Movies Delete Controller  */
    DatePickerController.$inject = ['$scope'];

    function DatePickerController($scope) {
    	$scope.open = function ($event) {
    		$event.preventDefault();
    		$event.stopPropagation();

    		$scope.opened = true;
    	};
    }


    
	/* Utility Functions */

    function _showValidationErrors($scope, error) {
    	$scope.validationErrors = [];
    	if (error.data &amp;&amp; angular.isObject(error.data)) {
    		for (var key in error.data) {
    			$scope.validationErrors.push(error.data[key][0]);
    		}
    	} else {
    		$scope.validationErrors.push('Could not add movie.');
    	};
    }

})();

</pre>
<p>Notice that both the MoviesAddController and MoviesEditController functions now include an error callback. When a 400 Bad Request is returned from the server, the  error callback is invoked and the _showValidationErrors() function is called.</p>
<p>The _showValidationErrors() function adds the error messages from ModelState to the $scope.validationErrors array. The contents of the validationErrors array is displayed in the _edit.html form:</p>
<pre>
&lt;div class=&quot;bg-danger validationErrors&quot; ng-show=&quot;validationErrors&quot;&gt;
	&lt;ul&gt;
		&lt;li ng-repeat=&quot;error in validationErrors&quot;&gt;{{error}}&lt;/li&gt;
	&lt;/ul&gt;
&lt;/div&gt; 
</pre>
<h2>Summary</h2>
<p>In this blog post, I focused on explaining how you can perform validation when using ASP.NET 5 and AngularJS.  I explained how you can use AngularJS directives – such as the ng-required directive – to perform client-side validation. I also explained how you can take advantage of ModelState and the BadRequestObjectResult when validating data submitted to the ASP.NET Web API.</p>
<p>In the next blog post, I discuss ASP.NET 5 security.</p>
<div class="feedflare">
<a rel="nofollow" target="_blank" href="http://feeds.feedburner.com/~ff/StephenWalther?a=D-BCGCMY0TQ:3Y0sWTlucRY:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/D-BCGCMY0TQ" height="1" width="1" alt=""/>]]></content:encoded>
      </item>
      <item>
         <title>ASP.NET 5 and AngularJS Part 4, Using Entity Framework 7</title>
         <link>http://feedproxy.google.com/~r/StephenWalther/~3/1XmrOur7llc/asp-net-5-and-angularjs-part-4-using-entity-framework-7</link>
         <description>This is the fourth part in a multiple part blog series on building ASP.NET 5 (ASP.NET vNext) apps with AngularJS. In this series of blog posts, I show how you can create a simple Movie app using ASP.NET 5, MVC 6, and AngularJS. ASP.NET 5 and AngularJS Part 1, Grunt, Uglify, and AngularJS ASP.NET 5 [&amp;#8230;]</description>
         <guid isPermaLink="false">http://stephenwalther.com/?p=921</guid>
         <pubDate>Sat, 17 Jan 2015 03:59:43 +0000</pubDate>
         <content:encoded><![CDATA[<p>This is the fourth part in a multiple part blog series on building ASP.NET 5 (ASP.NET vNext) apps with AngularJS. In this series of blog posts, I show how you can create a simple Movie app using ASP.NET 5, MVC 6, and AngularJS.</p>
<ul>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 1, Grunt, Uglify, and AngularJS</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 2, Using the MVC 6 Web API</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 3, Adding Client Routing</a>
</li>
<li>
  <b><a rel="nofollow">ASP.NET 5 and AngularJS Part 4, Using Entity Framework 7</a></b>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 5, Form Validation</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 6, Security</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 7, Running on a Mac</a>
</li>
</ul>
<p>You can download the code discussed in this blog post from GitHub:</p>
<p><a rel="nofollow" target="_blank" href="https://github.com/StephenWalther/MovieAngularJSApp">https://github.com/StephenWalther/MovieAngularJSApp</a></p>
<p>In this blog post, I explain how to use Entity Framework 7 to persist the movie data to a database.</p>
<h2>Adding the Entity Framework NuGet Packages</h2>
<p>Before you can use the Entity Framework, you must add the Entity Framework 7 NuGet packages to your project. Ensure that your project.json file includes the following two dependencies (you’ll get Intellisense while entering the names of the packages and their versions). </p>
<pre>
&quot;EntityFramework.SqlServer&quot;: &quot;7.0.0-beta2&quot;,
&quot;EntityFramework.Commands&quot;: &quot;7.0.0-beta2&quot;,
</pre>
<p>After you complete this step, the Entity Framework packages should appear under References:</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/EFReferences.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/EFReferences.png" alt="EFReferences" width="800" height="642" class="alignnone size-full wp-image-926"/></a> </p>
<h2>Creating the Model and DbContext</h2>
<p>Next, we need to create our Movie model class. This class represents the entity that we want to store in the database. Add the following Movie.cs class to your Models folder:</p>
<pre>
namespace MovieAngularJSApp.Models
{
    public class Movie
    {
        public int Id { get; set; }

        public string Title { get; set; }

        public string Director { get; set; }
    }
}
</pre>
<p>We also need to create an Entity Framework DbContext class. We create this class when using Entity Framework 7 in exactly the same way as we created this class for previous versions of the Entity Framework.</p>
<pre>
using Microsoft.Data.Entity;

namespace MovieAngularJSApp.Models
{
    public class MoviesAppContext:DbContext
    {

		public DbSet&lt;Movie&gt; Movies { get; set; }

	}
}
</pre>
<h2>Registering the Entity Framework Services</h2>
<p>Now that we have our DbContext class, we need to register the DbContext with our application services. Modify your Startup.cs file so it contains the code for registering the Entity Framework in the code below:</p>
<pre>
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Data.Entity;
using MovieAngularJSApp.Models;
using Microsoft.AspNet.Hosting;
using Microsoft.Framework.ConfigurationModel;



namespace MovieAngularJSApp
{
	public class Startup
	{
		public Startup(IHostingEnvironment env)
		{
			// Setup configuration sources.
			Configuration = new Configuration()
				.AddJsonFile(&quot;config.json&quot;)
				.AddEnvironmentVariables();
		}

		public IConfiguration Configuration { get; set; }


		public void ConfigureServices(IServiceCollection services)
		{
			services.AddMvc();

			// Register Entity Framework
			services.AddEntityFramework(Configuration)
				.AddSqlServer()
				.AddDbContext&lt;MoviesAppContext&gt;();
		}

		public void Configure(IApplicationBuilder app)
		{
			app.UseMvc();
        }

	}
}

</pre>
<p>The database connection string is loaded up from the Config.json file (notice the constructor in the Startup.cs file). Here is what the Config.json file looks like:</p>
<pre>
{
    &quot;Data&quot;: {
        &quot;DefaultConnection&quot;: { 
            &quot;ConnectionString&quot;: &quot;Server=(localdb)&#92;&#92;mssqllocaldb;Database=MoviesDatabase;Trusted_Connection=True;MultipleActiveResultSets=true&quot;
        }
    },
    &quot;EntityFramework&quot;: {
        &quot;MoviesAppContext&quot;: {
            &quot;ConnectionStringKey&quot;: &quot;Data:DefaultConnection:ConnectionString&quot;
        }
    }
}
</pre>
<h2>Updating the MoviesController</h2>
<p>Because we registered our MoviesAppContext class as a service, we can take advantage of the built-in ASP.NET 5 Dependency Injection framework to use the MoviesAppContext in our MoviesController. Notice that the MoviesAppContext class is added to the MoviesController using constructor dependency injection in the code below:</p>
<pre>
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Mvc;
using MovieAngularJSApp.Models;


namespace MovieAngularJSApp.API.Controllers
{
    [Route(&quot;api/[controller]&quot;)]
    public class MoviesController : Controller
    {
		private readonly MoviesAppContext _dbContext;

		public MoviesController(MoviesAppContext dbContext) 
		{
			_dbContext = dbContext;
		}

        [HttpGet]
        public IEnumerable&lt;Movie&gt; Get()
        {
			return _dbContext.Movies;
        }


        [HttpGet(&quot;{id:int}&quot;)]
        public IActionResult Get(int id)
        {
			var movie = _dbContext.Movies.FirstOrDefault(m =&gt; m.Id == id);
			if (movie == null) {
				return new HttpNotFoundResult();
			} else {
				return new ObjectResult(movie);
            } 
		}


        [HttpPost]
        public IActionResult Post([FromBody]Movie movie)
        {
			if (movie.Id == 0)
			{
				_dbContext.Movies.Add(movie);
				_dbContext.SaveChanges();
				return new ObjectResult(movie);
			}
			else
			{
				var original = _dbContext.Movies.FirstOrDefault(m =&gt; m.Id == movie.Id);
				original.Title = movie.Title;
				original.Director = movie.Director;
				_dbContext.SaveChanges();
				return new ObjectResult(original);
			}
        }


        [HttpDelete(&quot;{id:int}&quot;)]
        public IActionResult Delete(int id)
        {
			var movie = _dbContext.Movies.FirstOrDefault(m =&gt; m.Id == id);
			_dbContext.Movies.Remove(movie);
			_dbContext.SaveChanges();
            return new HttpStatusCodeResult(200);
        }


    }
}
</pre>
<h2>Performing Database Migrations</h2>
<p>After we complete all of the steps above, our application still won’t work. If we run the Movies app then we will get an error message about not being able to open the MoviesDatabase.</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/NoDBError.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/NoDBError.png" alt="NoDBError" width="900" height="628" class="alignnone size-full wp-image-925"/></a> </p>
<p>Unlike previous versions of the Entity Framework, the Entity Framework 7 does not support database initializers. Instead, you are encouraged to use Database Migrations.</p>
<p>There are two ways to use Migrations with ASP.NET 5: from a Command Prompt or from the NuGet Package Manager Console.  You can read the details about each approach by reading Brice Lam’s blog at the following addresses:</p>
<p><a rel="nofollow" target="_blank" href="http://bricelam.net/2014/10/22/ef7-nuget-commands.html">http://bricelam.net/2014/10/22/ef7-nuget-commands.html</a><br />
<a rel="nofollow" target="_blank" href="http://bricelam.net/2014/09/14/migrations-on-k.html">http://bricelam.net/2014/09/14/migrations-on-k.html</a></p>
<p>Here, I used the Command Prompt approach and I executed the following two commands from the same directory that contains my project.json file:</p>
<pre>
k ef migration add initial
k ef migration apply
</pre>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/KPrompt.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/KPrompt.png" alt="KPrompt" width="900" height="255" class="alignnone size-full wp-image-924"/></a>	 </p>
<p>After you execute the two ef commands above, a new database named MoviesDatabase will be created. You can see the new database by opening up the Visual Studio SQL Server Object Explorer:</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/SQLExplorer.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/SQLExplorer.png" alt="SQLExplorer" width="686" height="375" class="alignnone size-full wp-image-928"/></a> </p>
<p>Executing the ef commands above will also add a new Migrations folder to your project. </p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/Migrations.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/Migrations.png" alt="Migrations" width="665" height="881" class="alignnone size-full wp-image-927"/></a></p>
<p>You now should be able to run the Movies app successfully. When you click the Add button, you should be able to add a new movie to the database. You also should be able to edit and delete movies.</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/MoviesAppWorking.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/MoviesAppWorking.png" alt="MoviesAppWorking" width="900" height="310" class="alignnone size-full wp-image-923"/></a> </p>
<h2>Summary</h2>
<p>In this blog post, I focused on using ASP.NET 5 with Entity Framework 7. I explained how you can add the NuGet packages for Entity Framework 7 and register the Entity Framework services in your Startup.cs file. Finally, I showed you how to use Migrations to initialize a new database.</p>
<p>In the next blog post, I will focus on the topic of client-side and server-side validation.</p>
<div class="feedflare">
<a rel="nofollow" target="_blank" href="http://feeds.feedburner.com/~ff/StephenWalther?a=1XmrOur7llc:kcuqBJkYUe4:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/1XmrOur7llc" height="1" width="1" alt=""/>]]></content:encoded>
      </item>
      <item>
         <title>ASP.NET 5 and AngularJS Part 3, Adding Client Routing</title>
         <link>http://feedproxy.google.com/~r/StephenWalther/~3/GjFsedICi_s/asp-net-5-and-angularjs-part-3-adding-client-routing</link>
         <description>This is the third part in a multiple part blog series on building ASP.NET 5 (ASP.NET vNext) apps with AngularJS. In this series of blog posts, I show how you can create a simple Movie app using ASP.NET 5, MVC 6, and AngularJS. ASP.NET 5 and AngularJS Part 1, Grunt, Uglify, and AngularJS ASP.NET 5 [&amp;#8230;]</description>
         <guid isPermaLink="false">http://stephenwalther.com/?p=915</guid>
         <pubDate>Fri, 16 Jan 2015 21:35:13 +0000</pubDate>
         <content:encoded><![CDATA[<p>This is the third part in a multiple part blog series on building ASP.NET 5 (ASP.NET vNext) apps with AngularJS. In this series of blog posts, I show how you can create a simple Movie app using ASP.NET 5, MVC 6, and AngularJS.</p>
<ul>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 1, Grunt, Uglify, and AngularJS</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 2, Using the MVC 6 Web API</a>
</li>
<li>
  <b><a rel="nofollow">ASP.NET 5 and AngularJS Part 3, Adding Client Routing</a></b>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 4, Using Entity Framework 7</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 5, Form Validation</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 6, Security</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 7, Running on a Mac</a>
</li>
</ul>
<p>You can download the code discussed in this blog post from GitHub:</p>
<p><a rel="nofollow" target="_blank" href="https://github.com/StephenWalther/MovieAngularJSApp">https://github.com/StephenWalther/MovieAngularJSApp</a></p>
<p>In this blog post, I explain how to divide your single page app (SPA) into multiple virtual pages. I’ll use AngularJS routing to create distinct list, add, edit, and delete views.</p>
<h2>Define the Client-Side Routes</h2>
<p>The first step is to define the client-side routes. You define these routes in the same JavaScript file – app.js – in which you created your AngularJS app.</p>
<pre>
(function () {
    'use strict'; 

    config.$inject = ['$routeProvider', '$locationProvider']; 

    angular.module('moviesApp', [
        'ngRoute', 'moviesServices'
    ]).config(config);

    function config($routeProvider, $locationProvider) {
        $routeProvider
            .when('/', {
              templateUrl: '/Views/list.html',
              controller: 'MoviesListController'
            })
            .when('/movies/add', {
                templateUrl: '/Views/add.html',
                controller: 'MoviesAddController'
            })
            .when('/movies/edit/:id', {
                templateUrl: '/Views/edit.html',
                controller: 'MoviesEditController'
            })
            .when('/movies/delete/:id', {
                templateUrl: '/Views/delete.html',
                controller: 'MoviesDeleteController'
            });

        $locationProvider.html5Mode(true); 
    }

})();
</pre>
<p>In the code above, I added 4 routes. For each route I defined a templateUrl that provides the location of the HTML for the route. I also associated each route with an AngularJS controller. </p>
<p>You should also notice that I have added ngRoute as a dependency for the moviesApp. I won’t get any of the routing functionality without adding a dependency on the ngRoute module:</p>
<pre>
angular.module('moviesApp', [
        'ngRoute', 'moviesServices'
    ]).config(config);
</pre>
<p>Finally, notice that I enabled html5Mode in the last line of code. Enabling html5Mode allows you to use natural URLs that look like:</p>
<p><a rel="nofollow">https://movies.com/movies/add/</a></p>
<p>Instead of unnatural hashbang URLs that look like:</p>
<p><a rel="nofollow">http://movies.com/#!/movies/add/</a></p>
<p>Using html5mode is compatible with any browser that supports the HTML5 History API (IE10+ and every other browser).</p>
<h2>Rewrite Requests on the Server</h2>
<p>If you navigate to /movies/add and hit the Reload button, then you’ll get a 404 response from the server. You’ll get a 404 error because /movies/add is a client-side route and not a server-side route.</p>
<p>To fix this issue, you need to configure IIS to redirect all requests back to home.  Add the following web.config file to your wwwroot folder:</p>
<pre>
&lt;!-- from http://stackoverflow.com/questions/25916851/wrapping-staticfilemiddleware-to-redirect-404-errors --&gt;

&lt;configuration&gt;
&lt;system.webServer&gt;
  &lt;modules runAllManagedModulesForAllRequests=&quot;true&quot; /&gt;
  &lt;rewrite&gt;
    &lt;rules&gt;
      &lt;!--Redirect selected traffic to index --&gt;
      &lt;rule name=&quot;Index Rule&quot; stopProcessing=&quot;true&quot;&gt;
        &lt;match url=&quot;.*&quot; /&gt;
        &lt;conditions logicalGrouping=&quot;MatchAll&quot;&gt;
          &lt;add input=&quot;{REQUEST_FILENAME}&quot; matchType=&quot;IsFile&quot; negate=&quot;true&quot; /&gt;
          &lt;add input=&quot;{REQUEST_URI}&quot; matchType=&quot;Pattern&quot; pattern=&quot;^/api/&quot; negate=&quot;true&quot; /&gt;
        &lt;/conditions&gt;
        &lt;action type=&quot;Rewrite&quot; url=&quot;/index.html&quot; /&gt;
      &lt;/rule&gt;
    &lt;/rules&gt;
  &lt;/rewrite&gt;
&lt;/system.webServer&gt;
&lt;/configuration&gt;  
</pre>
<p>Notice that I am also enabling runAllManagedModulesForAllRequests (RAMMFAR). I need to enable RAMMFAR to handle PUT and DELETE requests.</p>
<h2>Creating the Client Controllers</h2>
<p>We need a separate client controller to correspond to each of our routes. Here’s how the client controllers are defined in the moviesController.js file:</p>
<pre>
(function () {
    'use strict';

    angular
        .module('moviesApp')
        .controller('MoviesListController', MoviesListController)
        .controller('MoviesAddController', MoviesAddController)
        .controller('MoviesEditController', MoviesEditController)
        .controller('MoviesDeleteController', MoviesDeleteController);

    /* Movies List Controller  */
    MoviesListController.$inject = ['$scope', 'Movie'];

    function MoviesListController($scope, Movie) {
        $scope.movies = Movie.query();
    }

    /* Movies Create Controller */
    MoviesAddController.$inject = ['$scope', '$location', 'Movie'];

    function MoviesAddController($scope, $location, Movie) {
        $scope.movie = new Movie();
        $scope.add = function () {
            $scope.movie.$save(function () {
                $location.path('/');
            });
        };
    }

    /* Movies Edit Controller */ 
    MoviesEditController.$inject = ['$scope', '$routeParams', '$location', 'Movie'];

    function MoviesEditController($scope, $routeParams, $location, Movie) {
        $scope.movie = Movie.get({ id: $routeParams.id });
        $scope.edit = function () {
            $scope.movie.$save(function () {
                $location.path('/');
            });
        };
    }

    /* Movies Delete Controller  */
    MoviesDeleteController.$inject = ['$scope', '$routeParams', '$location', 'Movie'];

    function MoviesDeleteController($scope, $routeParams, $location, Movie) {
        $scope.movie = Movie.get({ id: $routeParams.id });
        $scope.remove = function () {
            $scope.movie.$remove({id:$scope.movie.Id}, function () {
                $location.path('/');
            });
        };
    }

    
})();
</pre>
<p>Notice that I don&#8217;t create a single controller with multiple actions (as I would in the case of server-side MVC). Instead, I create a separate controller that corresponds to the list, add, edit, and delete actions.</p>
<p>Each controller interacts with the ASP.NET Web API with the help of a Movie resource. For example, the MoviesListController retrieves the list of movies from the server by calling Movie.query(). And, the MoviesAddController posts a new movie to the server by invoking movie.$save().</p>
<p>The Movie resource is defined in a module named moviesServices.js:</p>
<pre>
(function () {
    'use strict';

    angular
        .module('moviesServices', ['ngResource'])
        .factory('Movie', Movie);

    Movie.$inject = ['$resource'];

    function Movie($resource) {
        return $resource('/api/movies/:id');
    }
})();
</pre>
<h2>Creating the Main Layout</h2>
<p>The index.html page in the Movies app now works like a Master Page/Layout Page.  It contains the content that will be shared with all pages. Here’s the updated content for the index.html page:</p>
<pre>
&lt;!DOCTYPE html&gt;
&lt;html ng-app=&quot;moviesApp&quot;&gt;
&lt;head&gt;
    &lt;base href=&quot;/&quot;&gt;
    &lt;meta charset=&quot;utf-8&quot; /&gt;
    &lt;title&gt;Movies&lt;/title&gt;

    &lt;!-- jQuery --&gt;
    &lt;script src=&quot;//code.jquery.com/jquery-1.11.2.min.js&quot;&gt;&lt;/script&gt;

    &lt;!-- Bootstrap --&gt;
    &lt;link rel=&quot;stylesheet&quot; href=&quot;https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css&quot;&gt;
    &lt;link rel=&quot;stylesheet&quot; href=&quot;https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css&quot;&gt;
    &lt;script src=&quot;https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js&quot;&gt;&lt;/script&gt;

    &lt;!-- AngularJS--&gt;
    &lt;script src=&quot;//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-resource.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-route.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;app.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body ng-cloak&gt;
    &lt;div class=&quot;container-fluid&quot;&gt;
        &lt;ng-view&gt;&lt;/ng-view&gt;
    &lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>There are three main things that you should notice about my updated index.html page. First, notice that I have added Twitter Bootstrap to my app by grabbing the Bootstrap styles and script from the maxcdn bootstrap CDN.</p>
<p>Second, notice that I have pulled the AngularJS ngRoute module in from the Google CDN with the following tag:</p>
<pre>
&lt;script src=&quot;//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-route.js&quot;&gt;&lt;/script&gt;
</pre>
<p>Finally, notice that I am using the  AngularJS directive (custom element) to mark where I want the content pages to be added to the index.html page. For example, when I navigate to /movies/add then the add.html page will be loaded into the location marked by the  directive.</p>
<h2>Creating the Virtual Pages</h2>
<p>The Movies app has 4 virtual pages for doing CRUD operations:</p>
<ul>
<li>	list.html – Lists the movies in a grid.</li>
<li>	add.html – Enables you to add new movies.</li>
<li>	edit.html – Enables you to edit existing movies.</li>
<li>	delete.html – Enables you to delete existing movies.</li>
</ul>
<p>Here’s what the list.html page looks like:</p>
<pre>
&lt;div&gt;

    &lt;h1&gt;List Movies&lt;/h1&gt;
    &lt;table class=&quot;table table-bordered table-striped&quot;&gt;
        &lt;thead&gt;
            &lt;tr&gt;
                &lt;th&gt;&lt;/th&gt;
                &lt;th&gt;Title&lt;/th&gt;
                &lt;th&gt;Director&lt;/th&gt;
            &lt;/tr&gt;
        &lt;/thead&gt;
        &lt;tbody&gt;
            &lt;tr ng-repeat=&quot;movie in movies&quot;&gt;
                &lt;td&gt;
                    &lt;a href=&quot;/movies/edit/{{movie.Id}}&quot; class=&quot;btn btn-default btn-xs&quot;&gt;edit&lt;/a&gt;
                    &lt;a href=&quot;/movies/delete/{{movie.Id}}&quot; class=&quot;btn btn-danger btn-xs&quot;&gt;delete&lt;/a&gt;
                &lt;/td&gt;
                &lt;td&gt;{{movie.Title}}&lt;/td&gt;
                &lt;td&gt;{{movie.Director}}&lt;/td&gt;
            &lt;/tr&gt;
        &lt;/tbody&gt;
    &lt;/table&gt;

    &lt;p&gt;
        &lt;a href=&quot;/movies/add&quot; class=&quot;btn btn-primary&quot;&gt;Add New Movie&lt;/a&gt;
    &lt;/p&gt;
&lt;/div&gt;
</pre>
<p>The list.html page uses the ng-repeat directive to display the list of movies in an HTML table. I styled the table with Twitter Bootstrap.</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/ListMovies.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/ListMovies.png" alt="ListMovies" width="900" height="641" class="alignnone size-full wp-image-920"/></a></p>
<p>The add.html page contains an HTML form created with the help of Boostrap:</p>
<pre>
&lt;h1&gt;Add Movie&lt;/h1&gt;
&lt;div class=&quot;row&quot;&gt;
    &lt;div class=&quot;col-md-5&quot;&gt;

        &lt;form ng-submit=&quot;add()&quot;&gt;
            &lt;div class=&quot;form-group&quot;&gt;
                &lt;label for=&quot;Title&quot;&gt;Movie Title&lt;/label&gt;
                &lt;input name=&quot;Title&quot; type=&quot;text&quot; class=&quot;form-control&quot; placeholder=&quot;Enter title&quot; ng-model=&quot;movie.Title&quot;&gt;
            &lt;/div&gt;
            &lt;div class=&quot;form-group&quot;&gt;
                &lt;label for=&quot;Director&quot;&gt;Director&lt;/label&gt;
                &lt;input name=&quot;Director&quot; type=&quot;text&quot; class=&quot;form-control&quot; placeholder=&quot;Enter director&quot; ng-model=&quot;movie.Director&quot;&gt;
            &lt;/div&gt;
            &lt;a href=&quot;/&quot; class=&quot;btn btn-default&quot;&gt;Cancel&lt;/a&gt;
            &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;Save&lt;/button&gt;
        &lt;/form&gt;
    &lt;/div&gt;
&lt;/div&gt;
</pre>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/AddMovie.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/AddMovie.png" alt="AddMovie" width="900" height="641" class="alignnone size-full wp-image-918"/></a></p>
<p>Notice that the &lt;input&gt; elements include ng-model attributes. These attributes create a two-way data-binding between the form fields and the model. When you click the Submit button, the ng-submit attribute on the &lt;form&gt; element invokes the add() method defined in the controller.</p>
<p>The edit.html page looks very similar to the add.html page:</p>
<pre>
&lt;h1&gt;Edit Movie&lt;/h1&gt;

&lt;div class=&quot;row&quot;&gt;
    &lt;div class=&quot;col-md-5&quot;&gt;

        &lt;form ng-submit=&quot;edit()&quot;&gt;
            &lt;div class=&quot;form-group&quot;&gt;
                &lt;label for=&quot;Title&quot;&gt;Movie Title&lt;/label&gt;
                &lt;input name=&quot;Title&quot; type=&quot;text&quot; class=&quot;form-control&quot; placeholder=&quot;Enter title&quot; ng-model=&quot;movie.Title&quot;&gt;
            &lt;/div&gt;
            &lt;div class=&quot;form-group&quot;&gt;
                &lt;label for=&quot;Director&quot;&gt;Director&lt;/label&gt;
                &lt;input name=&quot;Director&quot; type=&quot;text&quot; class=&quot;form-control&quot; placeholder=&quot;Enter director&quot; ng-model=&quot;movie.Director&quot;&gt;
            &lt;/div&gt;
            &lt;a href=&quot;/&quot; class=&quot;btn btn-default&quot;&gt;Cancel&lt;/a&gt;
            &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;Save&lt;/button&gt;
        &lt;/form&gt;


    &lt;/div&gt;
&lt;/div&gt;
</pre>
<p>The ng-model attributes applied to the &lt;input&gt; elements cause the form to be prefilled with the property values of the movie being edited. So we get the title “Star Wars” and director “Lucas” automatically.</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/EditMovie.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/EditMovie.png" alt="EditMovie" width="900" height="641" class="alignnone size-full wp-image-919"/></a></p>
<p>When you submit the edit form, controller the edit() method is invoked.</p>
<p>Finally, the delete.html page is used to confirm that you really want to delete a movie from the database.</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/DeleteMovie.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/DeleteMovie.png" alt="DeleteMovie" width="900" height="641" class="alignnone size-full wp-image-917"/></a> </p>
<p>Here’s the contents of the delete.html page:</p>
<pre>
&lt;div class=&quot;alert alert-warning&quot;&gt;
    Are you sure that you want to permanently delete the movie
    &amp;quot;{{movie.Title}}&amp;quot;?
&lt;/div&gt;

&lt;a href=&quot;/&quot; class=&quot;btn btn-default&quot;&gt;Cancel&lt;/a&gt;
&lt;button class=&quot;btn btn-danger&quot; ng-click=&quot;remove()&quot;&gt;OK&lt;/button&gt;
</pre>
<p>When you click the Delete button, the remove() method is invoked.</p>
<h2>Summary</h2>
<p>In this blog post, I focused on client-side routing using the AngularJS ngRoute module. You learned how to use client-side routing with an ASP.NET 5 app.</p>
<p>Currently, you can’t actually create new movies or edit existing movies. In the next blog post, I’ll explain how you can use Entity Framework 7 to save changes to a database.</p>
<div class="feedflare">
<a rel="nofollow" target="_blank" href="http://feeds.feedburner.com/~ff/StephenWalther?a=GjFsedICi_s:9-NsoRskBl8:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/GjFsedICi_s" height="1" width="1" alt=""/>]]></content:encoded>
      </item>
      <item>
         <title>Upgrading Visual Studio 2015 Preview to ASP.NET 5/MVC 6 RC</title>
         <link>http://feedproxy.google.com/~r/StephenWalther/~3/qFowtIfOxXI/upgrading-visual-studio-2015-preview-to-asp-net-5mvc-6-rc</link>
         <description>UPDATE: When I wrote this blog entry, the RC version was the latest version of the runtime. Recently, BETA 3 was released which is later than the RC. I spent a couple of hours today updating Visual Studio 2015 Preview to use the ASP.NET 5/MVC 6 Nightly Build. Because the process was a little tricky, [&amp;#8230;]</description>
         <guid isPermaLink="false">http://stephenwalther.com/?p=909</guid>
         <pubDate>Thu, 15 Jan 2015 23:13:16 +0000</pubDate>
         <content:encoded><![CDATA[<p>UPDATE: When I wrote this blog entry, the RC version was the latest version of the runtime. Recently,<br />
BETA 3 was released which is later than the RC.</p>
<p>I spent a couple of hours today updating Visual Studio 2015 Preview to use the ASP.NET 5/MVC 6 Nightly Build. Because the process was a little tricky, I wanted to write a brief blog entry to document how I did it.</p>
<h2>Download Visual Studio 2015 Preview</h2>
<p>You can download Visual Studio 2015 Preview from here:</p>
<p><a rel="nofollow" target="_blank" href="http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs.aspx">http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs.aspx</a></p>
<p>Be aware that when you install Visual Studio 2015 Preview, it will use the Beta version of ASP.NET 5 (ASP.NET vNext) and not the Release Candidate version. You’ll need to follow the steps in this blog post to use the Nightly Build.</p>
<p>Configure NuGet</p>
<p>There are two different NuGet feeds that you can use to get the ASP.NET 5 packages:</p>
<ul>
<li>
<p>
  Milestone Builds &#8211; https://www.myget.org/F/aspnetmaster/api/v2
  </p>
</li>
<li>
<p>
  Nightly Builds &#8211; https://www.myget.org/F/aspnetvnext/api/v2/
  </p>
</li>
</ul>
<p>If you want to update Visual Studio 2015 to use the Nightly Builds then follow these steps:</p>
<ol>
<li>
<p>
  Open the menu option Tools, NuGet Package Manager, Package Manager Settings.
  </p>
</li>
<li>
<p>
  Click the Package Sources entry to view the current NuGet Package Manager sources.
  </p>
</li>
<li>
<p>
  Uncheck the source for aspnetmaster.
  </p>
</li>
<li>
<p>
  Create a new source for the Nightly Build at aspnetvnext.
  </p>
</li>
</ol>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/NuGetFeed.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/NuGetFeed.png" alt="NuGetFeed" width="900" height="611" class="alignnone size-full wp-image-914"/></a></p>
<p>You can read more about this on the ASP.NET vNext Wiki:</p>
<p><a rel="nofollow" target="_blank" href="https://github.com/aspnet/Home/wiki/Configuring-the-feed-used-by-kpm-to-restore-packages">https://github.com/aspnet/Home/wiki/Configuring-the-feed-used-by-kpm-to-restore-packages</a></p>
<h2>Update MVC 6 to the Release Candidate</h2>
<p>If you want to use the latest version of MVC 6 then you need to update your project.json file in the root of your project. Here’s what my updated project.json file looks like:</p>
<pre>
{
    &quot;webroot&quot;: &quot;wwwroot&quot;,
    &quot;version&quot;: &quot;1.0.0-*&quot;,
    &quot;exclude&quot;: [
        &quot;wwwroot&quot;
    ],
    &quot;packExclude&quot;: [
        &quot;**.kproj&quot;,
        &quot;**.user&quot;,
        &quot;**.vspscc&quot;
    ],
    &quot;dependencies&quot;: {
        &quot;Microsoft.AspNet.Server.IIS&quot;: &quot;1.0.0-*&quot;,
        &quot;Microsoft.AspNet.Mvc&quot;: &quot;6.0.0-*&quot;
    },
    &quot;frameworks&quot; : {
        &quot;aspnet50&quot; : {},
        &quot;aspnetcore50&quot;: { }
    }
}
</pre>
<p>Notice that I am using “1.0.0-*” for the version of IIS and  “6.0.0-*” for the version of MVC. This will give me the latest versions (the Nightly Build).</p>
<h2>Update the KRuntime for your Machine</h2>
<p>In order to use the Release Candidate of ASP.NET 5, you need to update the runtime itself. Open up a Command Prompt As an Administrator and execute the following powershell command:</p>
<pre>
@powershell -NoProfile -ExecutionPolicy unrestricted -Command &quot;iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/aspnet/Home/dev/kvminstall.ps1'))&quot;
</pre>
<p>Next, run <i>kvm upgrade</i> to install the latest version of the runtime</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/UpdateRuntime.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/UpdateRuntime.png" alt="UpdateRuntime" width="900" height="333" class="alignnone size-full wp-image-913"/></a> </p>
<p>After you complete this step, run <i>kvm list</i> to view all of the runtimes installed on your machine. You should see the rc1 runtime listed.</p>
<p>Finally, perform a <i>kpm restore</i> to get the latest version of all of the packages.</p>
<p>Read more about this step here:</p>
<p><a rel="nofollow" target="_blank" href="https://github.com/aspnet/Home/issues/218">https://github.com/aspnet/Home/issues/218</a></p>
<h2>Update the KRuntime for Your Project</h2>
<p>Next, you need to update your Visual Studio project to use the RC runtime. Follow these steps:</p>
<ol>
<li>
<p>
  Right-click your project in the Solution Explorer Window.
  </p>
</li>
<li>
<p>
  Select the KRE-CLR.x86.1.0.0-rc runtime.
  </p>
</li>
<li>
<p>
  Click the Save button (the floppy disk).
  </p>
</li>
</ol>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/ProjectRuntime.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/ProjectRuntime.png" alt="ProjectRuntime" width="900" height="542" class="alignnone size-full wp-image-912"/></a></p>
<h2>Summary</h2>
<p>After you complete all of the steps above, you should have the latest version of ASP.NET 5 and MVC 6. Your References folder should look like this:</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/References.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/References.png" alt="References" width="863" height="836" class="alignnone size-full wp-image-911"/></a> </p>
<p>Why go through all of this work to upgrade from the Beta to the Release Candidate?  The Release Candidate has lots of interesting new features such as new IActionResults that you can use with controller actions.</p>
<p>Hope this helps!</p>
<div class="feedflare">
<a rel="nofollow" target="_blank" href="http://feeds.feedburner.com/~ff/StephenWalther?a=qFowtIfOxXI:-UvbMuhEWI8:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/qFowtIfOxXI" height="1" width="1" alt=""/>]]></content:encoded>
      </item>
      <item>
         <title>ASP.NET 5 and AngularJS Part 2, Using the MVC 6 Web API</title>
         <link>http://feedproxy.google.com/~r/StephenWalther/~3/uBQ1VAQomfI/asp-net-5-and-angularjs-part-2-using-the-mvc-6-web-api</link>
         <description>This is the second part in a multiple part blog series on building ASP.NET 5 (ASP.NET vNext) apps with AngularJS. In this series of blog posts, I show how you can create a simple Movie app using ASP.NET 5, MVC 6, and AngularJS. ASP.NET 5 and AngularJS Part 1, Grunt, Uglify, and AngularJS ASP.NET 5 [&amp;#8230;]</description>
         <guid isPermaLink="false">http://stephenwalther.com/?p=896</guid>
         <pubDate>Tue, 13 Jan 2015 01:55:12 +0000</pubDate>
         <content:encoded><![CDATA[<p>This is the second part in a multiple part blog series on building ASP.NET 5 (ASP.NET vNext) apps with AngularJS. In this series of blog posts, I show how you can create a simple Movie app using ASP.NET 5, MVC 6, and AngularJS.</p>
<ul>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 1, Grunt, Uglify, and AngularJS</a>
</li>
<li>
  <b><a rel="nofollow">ASP.NET 5 and AngularJS Part 2, Using the MVC 6 Web API</a></b>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 3, Adding Client Routing</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 4, Using Entity Framework 7</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 5, Form Validation</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 6, Security</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 7, Running on a Mac</a>
</li>
</ul>
<p>You can download the code discussed in this blog post from GitHub:</p>
<p><a rel="nofollow" target="_blank" href="https://github.com/StephenWalther/MovieAngularJSApp">https://github.com/StephenWalther/MovieAngularJSApp</a></p>
<p>In this blog post, I explain how to expose data from your server using the MVC 6 Web API. We’ll retrieve a list of movies from the Web API and display the list of movies in our AngularJS app by taking advantage of an AngularJS template.  </p>
<h2>Enabling ASP.NET MVC</h2>
<p>The first step is to enable MVC for our application. There are two files that we need to modify to enable MVC.</p>
<p>First, we need to modify the project.json file so it includes MVC 6:</p>
<pre>
{
    &quot;webroot&quot;: &quot;wwwroot&quot;,
    &quot;version&quot;: &quot;1.0.0-*&quot;,
    &quot;exclude&quot;: [
        &quot;wwwroot&quot;
    ],
    &quot;packExclude&quot;: [
        &quot;**.kproj&quot;,
        &quot;**.user&quot;,
        &quot;**.vspscc&quot;
    ],
    &quot;dependencies&quot;: {
        &quot;Microsoft.AspNet.Server.IIS&quot;: &quot;1.0.0-beta1&quot;,
        &quot;Microsoft.AspNet.Mvc&quot;: &quot;6.0.0-beta1&quot;
    },
    &quot;frameworks&quot; : {
        &quot;aspnet50&quot; : { },
        &quot;aspnetcore50&quot;: { }
    }
}
</pre>
<p>The project.json file is used by the NuGet package manager to determine the packages required by the project. We’ve indicated that we need the MVC 6 (beta1) package. </p>
<p>We also need to modify the Startup.cs file in the root of our MovieAngularJS project.  Change the contents of the Startup.cs file so it looks like this:</p>
<pre>
using System;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.Framework.DependencyInjection;

namespace MovieAngularJSApp
{
    public class Startup
    {

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseMvc();
        }

    }
}
</pre>
<p>The ConfigureServices() method is used to register MVC with the built-in Dependency Injection framework included in ASP.NET 5. The Configure() method is used to register MVC with OWIN.</p>
<h2>Creating the Movie Model</h2>
<p>Let’s create a Movie model class that we can use to pass movies from the server to the browser (from the Web API to AngularJS).  Create a Models folder in the root of the MovieAngularJS project:</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/01Models.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/01Models.png" alt="Models Folder" width="596" height="750" class="alignnone size-full wp-image-900"/></a> </p>
<p>Notice that you create the Models folder outside of the wwwroot folder. Source code does not belong in wwwroot.</p>
<p>Add the following C# class named Movie.cs to the Models folder:</p>
<pre>
using System;

namespace MovieAngularJSApp.Models
{
    public class Movie
    {
        public int Id { get; set; }

        public string Title { get; set; }

        public string Director { get; set; }
    }
}
</pre>
<h2>Creating the Web API Controller</h2>
<p>Unlike earlier versions of ASP.NET, the same controller base class is used for both MVC controllers and Web API controllers. Because we’ve pulled in the NuGet package for MVC 6, we are now ready to start creating Web API controllers.</p>
<p>Add an API folder to the root of your MovieAngularJS project:</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/02API.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/02API.png" alt="API Folder" width="586" height="760" class="alignnone size-full wp-image-899"/></a> </p>
<p>Notice that you don’t add the API folder inside of your wwroot folder. All of your source code – including source code for your controllers – should be located outside of the wwwroot folder.</p>
<p>Next, add a Web API controller by right-clicking the API folder and selecting Add, New Item. Choose the Web API Controller Class template and name the new controller MoviesController.cs:</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/03AddController.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/03AddController.png" alt="Add MVC Controller" width="900" height="623" class="alignnone size-full wp-image-898"/></a> </p>
<p>Enter the following code for the Web API controller:</p>
<pre>
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Mvc;
using MovieAngularJSApp.Models;


namespace MovieAngularJSApp.API.Controllers
{
    [Route(&quot;api/[controller]&quot;)]
    public class MoviesController : Controller
    {
        // GET: api/values
        [HttpGet]
        public IEnumerable&lt;Movie&gt; Get()
        {
            return new List&lt;Movie&gt; {
                new Movie {Id=1, Title=&quot;Star Wars&quot;, Director=&quot;Lucas&quot;},
                new Movie {Id=2, Title=&quot;King Kong&quot;, Director=&quot;Jackson&quot;},
                new Movie {Id=3, Title=&quot;Memento&quot;, Director=&quot;Nolan&quot;}
            };
        }

    }
}
</pre>
<p>In the code above, the Get() action returns a list of movies. You can test whether the action is working by starting your app and navigating to /api/movies in your browser. In Google Chrome, you’ll get an XML representation of the movies:</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/04TestAction.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/04TestAction.png" alt="XML Results" width="708" height="785" class="alignnone size-full wp-image-903"/></a> </p>
<h2>Creating the AngularJS App</h2>
<p>We are going to display the list of movies using an AngularJS template. First, we need to create our AngularJS app.</p>
<p>Right-click on the Scripts folder and select Add, New Item. Select the AngularJS Module template and click the Add button.</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/05AngularModule.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/05AngularModule.png" alt="AngularJS Module" width="900" height="623" class="alignnone size-full wp-image-902"/></a> </p>
<p>Enter the following code for the new AngularJS module:</p>
<pre>
(function () {
    'use strict';

    angular.module('moviesApp', [
        'moviesServices'
    ]);
})();
</pre>
<p>The code above defines a new AngularJS module named moviesApp. The moviesApp has a dependency on another AngularJS module named moviesServices.  We create the moviesServices below.</p>
<h2>Creating the AngularJS Controller</h2>
<p>Our next step is to create a client-side AngularJS controller. Create a new Controllers folder under the Scripts folder:</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/06AngularController.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/06AngularController.png" alt="AngularJS Controller" width="563" height="823" class="alignnone size-full wp-image-901"/></a> </p>
<p>Right-click the Controller folder and select Add, New Item. Add a new AngularJS Controller using $scope named moviesController.js to the Controllers folder. Enter the following content for the moviesController.js file:</p>
<pre>
(function () {
    'use strict';

    angular
        .module('moviesApp')
        .controller('moviesController', moviesController);

    moviesController.$inject = ['$scope', 'Movies'];

    function moviesController($scope, Movies) {
        $scope.movies = Movies.query();
    }
})();
</pre>
<p>The AngularJS controller above depends on a Movies service that supplies the list of movies. The Movies service is passed to the controller using dependency injection. The Movies service is passed as the second parameter to the moviesController() function.</p>
<p>The moviesController.$inject() method call is required to enable the moviesController to work with minification. AngularJS dependency injection works off the name of parameters. In the previous blog post, I setup Grunt and UglifyJS to minify all of the JavaScript files. As part of the process of minification, all function parameter names are shortened (mangled). The $inject() method call enables dependency injection to work even when the parameter names are mangled.</p>
<h2>Creating the AngularJS Movies Service</h2>
<p>We’ll use an AngularJS Movies service to interact with the Web API.  Add a new Services folder to the existing Scripts folder. Next, right-click the Services folder and select Add, New Item. Add a new AngularJS Factory named moviesService.js to the Services folder:</p>
<p>Enter the following code for moviesService.js:</p>
<pre>
(function () {
    'use strict';

    var moviesServices = angular.module('moviesServices', ['ngResource']);

    moviesServices.factory('Movies', ['$resource',
      function ($resource) {
          return $resource('/api/movies/', {}, {
              query: { method: 'GET', params: {}, isArray: true }
          });
      }]);


})();
</pre>
<p>The movieServices depends on the $resource object. The $resource object performs Ajax requests using a RESTful pattern.</p>
<p>In the code above, the moviesServices is associated with the /api/movies/ route on the server. In other words, when you perform a query against the moviesServices in your client code then the Web API MoviesController is invoked to return a list of movies.</p>
<h2>Creating the AngularJS Template</h2>
<p>The final step is to create the AngularJS template that displays the list of movies. Right-click the wwwroot folder and add a new HTML page named index.html. </p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/08Template.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/08Template.png" alt="Add HTML" width="900" height="483" class="alignnone size-full wp-image-905"/></a> </p>
<p>Modify the contents of index.html so it looks like this:</p>
<pre>
&lt;!DOCTYPE html&gt;
&lt;html ng-app=&quot;moviesApp&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;utf-8&quot; /&gt;
    &lt;title&gt;Movies&lt;/title&gt;

    &lt;script src=&quot;//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-resource.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;app.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body ng-cloak&gt;
    &lt;div ng-controller=&quot;moviesController&quot;&gt;

        &lt;table&gt;
            &lt;thead&gt;
                &lt;tr&gt;
                    &lt;th&gt;Title&lt;/th&gt;
                    &lt;th&gt;Director&lt;/th&gt;
                &lt;/tr&gt;
            &lt;/thead&gt;
            &lt;tbody&gt;
                &lt;tr ng-repeat=&quot;movie in movies&quot;&gt;
                    &lt;td&gt;{{movie.Title}}&lt;/td&gt;
                    &lt;td&gt;{{movie.Director}}&lt;/td&gt;
                &lt;/tr&gt;
            &lt;/tbody&gt;
        &lt;/table&gt;

    &lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>There are several things that you should notice about this HTML file:</p>
<ul>
<li>
<p>	Notice that the &lt;html&gt; element includes an ng-app directive. This directive associates the moviesApp with the HTML file.</p>
</li>
<li>
<p>	Notice that &lt;script&gt; tags are used to add the angular and angular-resource JavaScript libraries from the Google CDN.</p>
</li>
<li>
<p>	Notice that the &lt;body&gt; element includes an ng-controller directive. This directive associates the moviesController with the contents of the &lt;div&gt; element.</p>
</li>
<li>
<p>	Notice that the movies are displayed by using an ng-repeat directive. The title and the director are displayed for each movie.</p>
</li>
<li>
<p>	Notice that the &lt;body&gt; element includes an ng-cloak directive. The ng-cloak directive hides an AngularJS template until the data has been loaded and the template has been rendered.</p>
</li>
</ul>
<p>When you open the index.html page in your browser, you can see the list of movies displayed in the HTML table. </p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/09TheResults.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/09TheResults.png" alt="The Results" width="744" height="444" class="alignnone size-full wp-image-904"/></a></p>
<h2>Summary</h2>
<p>In this blog post, we created an AngularJS app that calls a Web API action to retrieve a list of movies. We displayed the list of movies in an HTML table by taking advantage of an AngularJS template.</p>
<p>In the next blog post, I discuss how you can take advantage of AngularJS routing to divide a client-side AngularJS app into multiple virtual pages.</p>
<div class="feedflare">
<a rel="nofollow" target="_blank" href="http://feeds.feedburner.com/~ff/StephenWalther?a=uBQ1VAQomfI:zOrUNOXfiCI:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/uBQ1VAQomfI" height="1" width="1" alt=""/>]]></content:encoded>
      </item>
      <item>
         <title>ASP.NET 5 and AngularJS Part 1, Configuring Grunt, Uglify, and AngularJS</title>
         <link>http://feedproxy.google.com/~r/StephenWalther/~3/HbGQkDlVbu4/asp-net-5-and-angularjs-part-1-configuring-grunt-uglify-and-angularjs</link>
         <description>This is the first part in a multiple part blog series on building ASP.NET 5 (ASP.NET vNext) apps with AngularJS. In this series of blog posts, I show how you can create a simple Movie app using ASP.NET 5, MVC 6, and AngularJS. ASP.NET 5 and AngularJS Part 1, Grunt, Uglify, and AngularJS ASP.NET 5 [&amp;#8230;]</description>
         <guid isPermaLink="false">http://stephenwalther.com/?p=886</guid>
         <pubDate>Mon, 12 Jan 2015 19:01:56 +0000</pubDate>
         <content:encoded><![CDATA[<p>This is the first part in a multiple part blog series on building ASP.NET 5 (ASP.NET vNext) apps with AngularJS. In this series of blog posts, I show how you can create a simple Movie app using ASP.NET 5, MVC 6, and AngularJS.  </p>
<ul>
<li>
  <b><a rel="nofollow">ASP.NET 5 and AngularJS Part 1, Grunt, Uglify, and AngularJS</a></b>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 2, Using the MVC 6 Web API</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 3, Adding Client Routing</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 4, Using Entity Framework 7</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 5, Form Validation</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 6, Security</a>
</li>
<li>
  <a rel="nofollow">ASP.NET 5 and AngularJS Part 7, Running on a Mac</a>
</li>
</ul>
<p>You can download the code discussed in this blog post from GitHub:</p>
<p><a rel="nofollow" target="_blank" href="https://github.com/StephenWalther/MovieAngularJSApp">https://github.com/StephenWalther/MovieAngularJSApp</a></p>
<p>In this blog post, I explain how to setup your ASP.NET 5 project. In particular, I explain how you can setup Grunt to combine and minify your front-end JavaScript files automatically. </p>
<h2>Creating the ASP.NET 5 Project</h2>
<p>The very first thing that you need to do is to create a new ASP.NET 5 project. In this blog post, I’ll show you how to create a new ASP.NET 5 project using Visual Studio 2015 on Windows (In a future blog post, I’ll discuss how you can setup an ASP.NET 5 project on a Mac on OSX with Sublime).</p>
<p>You can download Visual Studio 2015 (Preview) from the following address:</p>
<p><a rel="nofollow" target="_blank" href="http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs.aspx">http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs.aspx</a></p>
<p>Visual Studio 2015 works fine running side-by-side with earlier versions of Visual Studio.</p>
<p>After you install Visual Studio 2015, select File, New Project. Under the Visual C# templates, select ASP.NET Web Application and name the new project “MovieAngularJSApp”.</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/01FileNew.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/01FileNew.png" alt="ASP.NET 5 File, New Project" width="900" height="651" class="alignnone size-full wp-image-887"/></a> </p>
<p>Next, select the ASP.NET 5 Empty project template and click the OK button to create the new project.</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/02EmptyTemplate.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/02EmptyTemplate.png" alt="ASP.NET 5 Empty Project Template" width="900" height="672" class="alignnone size-full wp-image-888"/></a></p>
<p>After you complete these steps, you’ll have an empty ASP.NET 5 project that looks like this:</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/03Solution.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/03Solution.png" alt="ASP.NET 5 Solution" width="563" height="605" class="alignnone size-full wp-image-889"/></a></p>
<p>The layout of an ASP.NET 5 solution is significantly different than earlier versions of ASP.NET. Notice that the solution is divided into two solution folders named Solution Items and src. The src folder contains all of the source code for your project. Currently, the src folder includes our MovieAngularJSApp project. </p>
<p>The MovieAngularJSApp project contains a special folder named wwwroot. The idea here is that the wwwroot folder should contain all of the content of your live website. For example, it includes any HTML files and image assets required for your live website.</p>
<p>You should not place any of your source code in the wwwroot folder. Instead, source code &#8212; such as unminified JavaScript files, Less files, MVC controller source code, and C# model classes – should be placed outside of the wwwroot folder.   </p>
<p>In particular, you want to create a folder in the root of your MovieAngularJSApp project named Scripts. You’ll create all of your app’s JavaScript files in the Scripts folder. We’ll use Grunt to combine and minify the JavaScript files in the Scripts folder and add the result to the wwwroot folder automatically.</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/04ScriptsFolder.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/04ScriptsFolder.png" alt="Scripts Folder" width="574" height="623" class="alignnone size-full wp-image-892"/></a></p>
<h2>Using NPM to Get the Necessary Packages</h2>
<p>Unlike earlier versions of ASP.NET, ASP.NET 5 natively supports three package managers: NuGet, NPM, and Bower.</p>
<p>What is a package manager?  A package manager enables you to easily gather together all of the resources that you need to create a project. For example, instead of navigating around the web and downloading project resources such as jQuery, the Entity Framework, Bootstrap, and AngularJS by hand, you can download all of these resources and their dependencies automatically by taking advantage of a package manager.</p>
<p>Previous versions of ASP.NET supported NuGet and you’ll still use NuGet with ASP.NET 5. You’ll use NuGet to manage .NET packages such as ASP.NET MVC and the Entity Framework. You specify the NuGet packages that you need in your project with the project.json file.</p>
<p>ASP.NET 5 also supports NPM packages. This is new and exciting. The NPM package manager was originally created for managing packages for the open-source NodeJS framework (an alternative web app framework to ASP.NET). You use a file named package.json to manage your project’s NPM packages.</p>
<p>Finally, ASP.NET 5 also supports the Bower package manager. Bower is a package manager created by Twitter that is designed to support front-end development. You can use Bower to manage resources such as AngularJS, jQuery, and Bootstrap.</p>
<p>For our Movie app project, we need to use NPM to gather all of the resources that we need to use Grunt. We’ll use NPM to install Grunt and the Grunt plugins that we need. Follow these steps:</p>
<ol>
<li>
<p>Right-click your MovieAngularJSApp project and select the menu option Add, New Item.</p>
</li>
<li>
<p>Select NPM configuration file.</p>
</li>
<li>
<p>Click the Add button.</p>
</li>
</ol>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/05NPM.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/05NPM.png" alt="Create NPM File" width="900" height="542" class="alignnone size-full wp-image-891"/></a></p>
<p>Completing these steps will add a new file to the root of your MovieAngularJSApp project named package.json. Modify the file so that it looks like this:</p>
<pre>
{
    &quot;version&quot;: &quot;0.0.0&quot;,
    &quot;name&quot;: &quot;MovieAngularJSApp&quot;,
    &quot;devDependencies&quot;: {
        &quot;grunt&quot;: &quot;0.4.5&quot;,
        &quot;grunt-contrib-uglify&quot;: &quot;0.7.0&quot;,
        &quot;grunt-contrib-watch&quot;: &quot;0.6.1&quot;
    }
}
</pre>
<p>In our package.json file, we’ve indicated that we need three NPM packages named grunt, grunt-contrib-uglify, and grunt-contrib-watch. After the name of each package, we’ve specified the version of the package that we need.</p>
<p>Notice that you get Intellisense (autocomplete) support while you edit the package.json file. A matching list of NPM package names and version numbers appear as you type.</p>
<p>After you create the package.json file, a new folder named NPM appears under your project’s Dependencies folder. If you expand the NPM folder then you can see a list of all of the NPM packages that you just added to the package.json file.</p>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/06NPMPackages.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/06NPMPackages.png" alt="NPM Folder" width="683" height="809" class="alignnone size-full wp-image-890"/></a> </p>
<p>Right-click the NPM folder and select Restore Packages to download all of the NPM packages. After you complete this step, the grunt, grunt-contrib-uglify, and grunt-contrib-watch packages will all be installed to a folder named node-modules.</p>
<h2>What about Bower?</h2>
<p>You can use Bower, as I mentioned earlier, to manage all of the packages that you need for front-end development. For example, you can use Bower to install the AngularJS JavaScript library.</p>
<p>I’m not going to use Bower to install AngularJS in this project because I am going to reference AngularJS directly from the Google CDN instead. I am going to add AngularJS to my project Index.html page like this:</p>
<pre>

&lt;script src=&quot;//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js&quot;&gt;&lt;/script&gt;

</pre>
<p>This is controversial, but I believe that you should always use a CDN for standard libraries such as AngularJS, Bootstrap, and jQuery. Using a CDN provides you with the best performance.  </p>
<p>For example, if you visit multiple websites that all reference AngularJS from the same CDN then your browser does not need to download the AngularJS JavaScript library when you visit each website. The browser can retrieve AngularJS from its cache instead.</p>
<p>So I use a CDN for standard libraries such as AngularJS or jQuery that might be used with multiple websites. For app specific files, such as the AngularJS controller files, I use Grunt to combine and minify the files to improve performance. </p>
<h2>Using Grunt to Build Your JavaScript Files</h2>
<p>Grunt is an open-source tool that you can use to build all of the frontend resources for your project. For example, you can use Grunt to compile your Less or Sass files into CSS. You can also use Grunt to combine and minify CSS and JavaScript files.</p>
<p>In this blog post, I’ll show you how to use Grunt to combine and minify your JavaScript files. We’ll configure Grunt so that it will take all of the JavaScript files from the Scripts folder, combine and minify the files, and save the results to a file named app.js in the wwwroot folder.</p>
<p>Follow these steps:</p>
<ol>
<li>
<p>Right-click your MovieAngularJSApp project and select Add, New Item.</p>
</li>
<li>
<p>Select Grunt Configuration file.</p>
</li>
<li>
<p>Click the Add button.</p>
</li>
</ol>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/07GruntFile.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/07GruntFile.png" alt="Create Grunt File" width="900" height="518" class="alignnone size-full wp-image-894"/></a></p>
<p>After you complete these steps, your project will contain a new file named Gruntfile.js. Modify the contents of the Gruntfile.js file so that it looks like this:</p>
<pre>
module.exports = function (grunt) {
    // load Grunt plugins from NPM
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-watch');

    // configure plugins
    grunt.initConfig({
        uglify: {
            my_target: {
                files: { 'wwwroot/app.js': ['Scripts/app.js', 'Scripts/**/*.js'] }
            }
        },

        watch: {
            scripts: {
                files: ['Scripts/**/*.js'],
                tasks: ['uglify']
            }
        }
    });

    // define tasks
    grunt.registerTask('default', ['uglify', 'watch']);
}; 
</pre>
<p>Our Gruntfile contains three sections. The first section is used to load each of the Grunt plugins that we need from the NPM packages that we configured earlier. We need to use a Grunt plugin named grunt-contrib-uglify and a Grunt plugin named grunt-contrib-watch.</p>
<p>Next, we enter the configuration information for each plugin. The Uglify plugin is configured so that it combines and minifies all of the files from the Scripts folder and places the results in a file named app.js in the wwwroot folder:</p>
<pre>
uglify: {
   my_target: {
      files: { 'wwwroot/app.js': ['Scripts/app.js', 'Scripts/**/*.js'] }
   }
},
</pre>
<p>Notice that I use the array [&#8216;Scripts/app.js&#8217;, &#8216;Scripts/**/*.js&#8217;] to specify the source files. I want the contents of the app.js JavaScript file to appear in the combined JavaScript file before the contents of any other JavaScript files because the app.js file contains the declaration of my main AngularJS module.  In other words, if you want to control the order in which Uglify combines JavaScript files then you need to list the order of your JavaScript files explicitly.</p>
<p>The Watch plugin is configured to watch any changes to the JavaScript files in the Scripts folder with the following code:</p>
<pre>
watch: {
   scripts: {
      files: ['Scripts/**/*.js'],
      tasks: ['uglify']
   }
}
</pre>
<p>If any files in the Scripts folder are changed, then the Watch plugin reruns Uglify to generate a new combined and minified app.js file automatically.</p>
<p>The final section of the Grunt file contains a definitions for your tasks. In our Grunt file, we define a single “default” task that runs Uglify and then watches for changes in our JavaScript files.</p>
<p>After you create a Grunt file, you need to run it by using the Visual Studio Task Runner Explorer. Follow these steps:</p>
<ol>
<li>
<p>Select the menu option View, Other Windows, Task Runner Explorer.</p>
</li>
<li>
<p>Click the Refresh button in the Task Runner Explorer window to ensure that the tasks for the MovieAngularJSApp appears.</p>
</li>
<li>
<p>Right-click the Default task and select Run.</p>
</li>
</ol>
<p><a rel="nofollow" target="_blank" href="http://stephenwalther.com/wp-content/uploads/2015/01/08RunGrunt.png"><img src="http://stephenwalther.com/wp-content/uploads/2015/01/08RunGrunt.png" alt="Task Runner Explorer" width="900" height="367" class="alignnone size-full wp-image-893"/></a></p>
<p>After you complete these steps, you can verify that Grunt is working by adding a JavaScript file (any JavaScript file) to the Scripts folder. Whenever you modify any JavaScript file in the Scripts folder then a new app.js file is generated in the wwwroot folder automatically.</p>
<h2>Summary</h2>
<p>In this blog post, I focused on setting up a new ASP.NET 5 and AngularJS project. I configured NPM and Grunt so that my app specific JavaScript files will be combined and minified automatically.  In the next blog post, I’ll explain how you can create AngularJS templates that display movies retrieved from MVC 6 Web API.</p>
<div class="feedflare">
<a rel="nofollow" target="_blank" href="http://feeds.feedburner.com/~ff/StephenWalther?a=HbGQkDlVbu4:boUt4r6RvXI:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/HbGQkDlVbu4" height="1" width="1" alt=""/>]]></content:encoded>
      </item>
   </channel>
</rss>
<!-- fe1.yql.bf1.yahoo.com compressed/chunked Thu Oct  1 19:23:28 UTC 2015 -->
