MVC

ASP.NET 5 Is Going To Simplify Your Life and Increase Your Productivity. Honestly, truly.

I made a mistake recently and did my shortest posting ever – basically just a URL – talking about the newest features in ASP.NET 5. Time to explore this in a little more detail. I’m still wading through what I think about ASP.NET 5 from a programming standpoint, so give me time and patience. I also stole liberally a lot of the slide pix below from Channel9, which I’m crediting in the footnotes. Sorry I’m just not that good of a graphics artist guys!

ASP.NET 5 Design Goals

Remember this compilation process?

Here’s the design goals that I see with ASP.NET 5:

  1. Simpler –
    1. No more assembly refs, manage all in NuGet or edit project.json directly. (example, in project.json search Microsoft.AspNet..Http to show Intellisense) – can edit with text editor
    2. Unified programming model that combines MVC, Web API, and Web Pages
    3. Used to have things like System.Web.Http.Routing and System.Web.MVC.Routing. Combining them simplifies runtime significantly. Web Pages, WebAPI and MVC all MVC6. (note, web pages come later)
    4. Ability to self-host or host on IIS
    5. Side-by-side versioning of the .NET Framework
    6. New tools in Visual Studio 2015
  2. Smooth and Powerful
    1. New modular HTTP request pipeline. New pipeline is modular. Not a massive block – can pick and choose so it’s lean. Apps run noticeably faster.
    2. Cloud-ready environment configuration
    3. Ability to see changes without re-building the project using Roslyn compiler (viewbag.Message = “Changed code here”; in controller logic for About
  3. Open Source and Inclusive
  4. New flexible and cross-platform runtime (full, core, cross-platform)
    1. – full is std, Core is cloud-optimized runtime, cross-platform means future Linux/Mac. Right now you’d use Mono for mac .NET dev.
  5. Open source in GitHub
    1. Nothing hidden. Can watch code as it is written, submit extensions yourself. GitHub code repositories are used for all ASP.NET 5 development across the board.

Just for example, look at the duplication below with the three silos we used to have with three unevenly joined frameworks – WebForms, MVC, and WebAPI:

From Web Pages -> MVC -> WebAPI, lots of common elements. HTML Helpers in both Web Pages and MVC. Controllers, Actions, Filters, Model Bidning, DI from MVC to Web API. This meant LOTS and lots of redundancy. Attribute routing is a classic example – two separate implementations. One model now for model, binding, DI – all in common. And they really thought about DI first in this new model.

 

A New Way of Working as a Developer with Roslyn

One DI abstraction that the framework leverages. It’s minimalistic, by design. Pop in your own framework to handle IOC. And one note on authentication – tokens not yet migrated. Katana was our first stop, but OWIN very in your face. Now with vNext moving more to middleware handling of authentication. If you want the bits, the code is at www.asp.net/vnext, and nightly build is at github.com/aspnet/home.

The biggest change in my mind is the new config system – big focus is on moving seamlessly from on-premise to cloud. Big frustration in the past was, you’d configure locally it’d work great, move to cloud and it would blow up. This is an environment-based config system that understands what needs to be enabled based on key/value pairs. Note, all of NuGet packages are in the root, under packages folder. Look at the References node – there are all the dependencies. Browse thru it – ok, MVC depends on Razor, which …. Etc.

And you won’t see any system.web in this app at all! New config system is called out – so you can put name/value pairs for environmental variables (DEV, QA, PROD) iand the config system will pick up the value. Browse through startup.cs – see how it sets up EF, DI, ASP.Net Identity, and MVC. See the mvc routing set up at the bottom.

One of the biggest changes is – you don’t have to do a build, wait… no you modify controller code and hit F5. Try this – comment everything out. Then add an app.UseWelcomePage(); line at the end. Try it again with app.Run(async req => await req.Response.WriteAsync(“bfsfdldaf”));

So get in the habit of doing Edit, Save, F5. This to me was a huge improvement that I didn’t know I need it.

One change in naming conventions with MVC – you used to have to inherit from controller i.e. MyConttrolllerName : Controller. Now you can just declare a class. As long as it has the word Controller at the end, you’re good.

The package publishing is also smoother. Try to publish to a file folder locally. Should be fully self-contained. Could take this on a thumbdrive and pop onto a machine WITHOUT IIS. (Still recommend IIS)

I also dig the .NET compatability profiler. For my customers, this really will hit the mark:

 

Bower, Grunt and Gulp Integration

It’s now much easier to incorporate jQuery, Bootstrap, and Angular client-side packages, and use Build tools like LESS, JS Minification, JSLint, and javascript unit tests.

Curious about what these tools are? They all have to do with JavaScript.

  • Bower – manages client-side packages like Javascriopt/CSS libraries. http://bower.io/
  • Grunt, Gulp are JS-based task runners (which automates routine dev tasks like minification, compilation, unit testing, linting, etc). ASP.NET 5.0 uses Grunt. See this link – note the superior way of handling dependencies to previous versions of .NET. http://gruntjs.com/getting-started
  • Npm – is a packg manager. Bundled with all of the above.

For more on this, and a complete walkthrough, check out http://www.asp.net/vnext/overview/aspnet-vnext/grunt-and-bower-in-visual-studio-2015

MVC Ch-Ch-Ch-Changes

Some link candy for you first to set the stage.

Note some big changes above to deployments and EF migrations. Finally, Microsoft listened and is going Code-First versus the former unworkable and fragile EDMX design pane, where you would drag entities onto a window. This is MUCH more workable and extensible than EF5 shtuff. As a developer, I wouldn’t even mess with anything else. A few simple command line entries:

… and running these commands shows you the migration code you’d be using – for example the model snapshot and migration class. This sets up your entities (no more EDMX files!)

 

And ASP.NET MVC 6 now supports injection into a view from a class. See this link – http://www.asp.net/vnext/overview/aspnet-vnext/vc

And a little more on dependency injection – http://blogs.msdn.com/b/webdev/archive/2014/06/17/dependency-injection-in-asp-net-vnext.aspx

For a WebAPI walkthrough by the EXCELLENT Mike Wasson, see this link: http://www.asp.net/vnext/overview/aspnet-vnext/create-a-web-api-with-mvc-6

WebAPI – the new WCF data services. And KnockoutJs/MVVM explorations.

Here’s a link to the TryOutMVVM project. Enjoy!

There’s a ton of links at the bottom of the page, but in terms of best explanation/clearest walkthrough it’s hard to beat this one as a template. Skip past all the Azure propaganda – about halfway down is where the good stuff is at.

WebAPI is super cool and allows us to do things that the “old” WCF data services only dreamed of – such as returning nested (hierarchical) tables, etc. These days I find it difficult for us to justify building a data layer on anything else. The thrill of being set free from procedural logic/sprocs, I can’t even express!

Here’s a sample return from a WebAPI. (JSON could be set up just as easily.) What’s involved in getting this set up? And can we mess around with linking it up to a web frontend and, I don’t know, sprinkle on some KnockoutJS for asynchronous goodness?

Let’s start with a few words on MVVM versus MVC

In terms of design MVVM is a logical extension of MVC. Model-View-Controller works off abstraction, where the model layer is unaware – completely uncoupled – of the view layer. In MVC, the Controller does all the work for this – and is responsible for determining which View is displayed in response to any action including when the application loads.

MVVM in contrast uses the ViewModel layer as a concept. It includes three key parts:

  1. Model (Business rule, data access, model classes)
  2. View (User interface)
  3. ViewModel (Agent between view and model)

Here the ViewModel acts as an interface and …

  • provides data binding between View and model data.
  • handles all UI actions by using commands.

In MVVM, the ViewModel does not need a reference to a view. The view binds its control value to properties on a ViewModel, which, in turn, exposes data contained in model objects.

Let’s walk through what it will take to implement a one-table MVVM app:

  1. Create a new MVC project, and enable both Webforms, MVC and Web API. Call it “ContactManager”.
  2. Modify _Layout.cshtml with contents (see zip file)
  3. Add a Contacts.cs class in Models folder, and Ctrl-F5 to build. EF uses reflection so these periodic builds will be necessary.
  4. Add a controller. Select MVC Controller with R/W actions Using EF. Call it HomeController; use the Contact model class, and select a <New data context>.
  5. In the Tools menu, open up Package Manager Console. At the prompt enter:
    1. enable-migrations (since we have multiple contexts, enablemigrations -ContextTypeName
      ContactManagerContext)

    2. add-migration-initial
  6. Open up Migrations\configuration.cs, and add the code in the zip file. (this fills in the seed method to populate the database)
  7. Back to Package Manager Console, enter: update-database
  8. Build.
  9. Replace index.cshtml
  10. Add a Contacts.css style sheet to the Content folder.
  11. Add a line to the App_Start\Bundle.config to register knockout.
    1. bundles.Add(new ScriptBundle(“~/bundles/knockout”).Include(“~/Scripts/knockout-{version}.js”));
    2. bundles.Add(new ScriptBundle(“~/bundles/knockout”).Include(“~/Scripts/knockout-{version}.js”));
  12. Add a Web API Controller with R/W actions Using EF. Call it ContactsController. Select Contact for the model, ContactManager context.
  13. Now build it, Ctrl-F5. Check out the new Home controller, at {yourappurl}/api/Contact.

That’s just a quick overview. In more detail, let’s go thru this step by step:

  1. In Visual Studio, create a new Web Application. Call it “TryOutMVVM”, and enable MVC, Webforms and WebAPI in the setup (ignore the test project, we won’t use it here.)
  2. Modify _Layout.cshtml with contents (see zip file)
  3. Add a TryOut.cs class in Models folder, and Ctrl-F5 to build. EF uses reflection so these periodic builds will be necessary.

    See above. This represents a single entity – a ID field, a product and location link (which in an actual application would probably be a related table with a foreign key), and some information about this try out. In this case, this represents a Line Try Out – an engineering change to a production line, including what part numbers are impacted, the person making the change and the description, the location and product it links to, and an identifying #.

  4. Add a controller. Select MVC Controller with R/W actions Using EF. Call it HomeController; use the Contact model class, and select a <New data context>. Note, I got stuck on this a few times and couldn’t figure out what I was doing wrong – the code built, but I was looking at a blank response in Fiddler. Turns out I was selecting the wrong type of controller (kind of like Homer Simpson adjusting Marge’s camera with a drill and hammer. And, my mind just got distracted and a quick youtube search of that episode reminds me of how awesome that show really was back in the day. Ah, sorry, back to reality…) Anyway, and I can’t stress this enough, make sure you select the RIGHT kind of controller for this and the following steps!!! If you get an error message here it’s usually because you haven’t built the project yet (see #3 above) – Ctrl-F5 and THEN add the controller silly! I also usually delete the HomeController first, but go ahead and overwrite if you forget.

  5. In the Tools menu, open up Package Manager Console. At the prompt enter:
    1. enable-migrations (since we have multiple contexts, enablemigrations -ContextTypeName
      ContactManagerContext)

    2. add-migration-initial
  6. Open up Migrations\configuration.cs, and add the code in the zip file. (this fills in the seed method to populate the database)
  7. Back to Package Manager Console, enter: update-database
    1. Here’s a sample of what it will look like in PMC. Check out the Migrations folder for a sample of what will be created:

      And, as long as we’re here, check out Views\Home\Index.cshtml file. Notice all the work that EF handled for us in scaffolding actions:

  8. Build, Ctrl-F5. OHMYGAWDDIDTHISJUSTHAPPEN?!!!?!!

  1. Replace index.cshtml with what’s in the ZIP file.
    1. Some comments. Notice this is plain and simple HTML5/CSS3. Very clean, really, for all it does. In a future version you’d want to move all those javascript functions out to a separate .js script. But this does work:

  1. Add a TryOut.css style sheet to the Content folder, and fill it with the styles in the ZIP. Again, nothing fancy here.
  2. Right click on the project and select Manage NuGet Packages. Search online and add a reference to knockoutjs. Now, look at the Scripts folder and see which version NuGet dropped in there – mine is 3.0.0. Make a note of this, you’ll need it for the next step.
  3. Open up App_Start\Bundle.config.cs and add the following lines:

    bundles.Add(new StyleBundle(“~/Content/css”).Include(

    “~/Content/bootstrap.css”,

    “~/Content/tryout.css”,

    “~/Content/site.css”));

    bundles.Add(new ScriptBundle(“~/bundles/knockout”).Include(

    “~/Scripts/knockout-3.0.0.js”));

  4. We’re actually almost there, can you believe it! Let’s add a service layer using WebAPI. Right click on Controllers and add a Web API Controller with R/W actions Using EF. Call it TryOutController. Select TryOut for the model, TryOutMVVMManager context.

    note, there’s no Views created for this – since its web aPI. All the API calls are right there in our TryOutController.cs method headers.

All that’s left is the building and the screaming. Let’s build it, Ctrl-F5.

Check out the new Home controller, at {yourappurl}/api/Contact.

Have some fun with it. Try

http://localhost:58149/api/Tryout

http://localhost:58149/api/Tryout/1

(where the port # obviously is your URL). Wow!

Notes and Links

I’m not done yet. I want to do some more research about the Repository pattern and how to do Web API the RIGHT way. I think I need to spend more time thinking about the design pattern and get out of the database-first box.

Next, for the frontend, I want to start thinking about KnockoutJS and the MVVM model:

f

The single best example – used as a base for this posting: https://www.windowsazure.com/en-us/develop/net/tutorials/rest-service-using-web-api/#bkmk_createmvc4app

A long post based on a single example, with CRUD operations. I like this ahead of the ones below, for ease of use. http://www.asp.net/web-api/overview/creating-web-apis/creating-a-web-api-that-supports-crud-operations

A good walkthrough to get started: http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application – a student-enrollment-course many to many type relationship sample.

http://www.asp.net/web-api/overview/creating-web-apis/using-web-api-with-entity-framework/using-web-api-with-entity-framework,-part-1 – this is by Mike Wasson, who created the excellent Movies web api sample. This is more of a master/detail page view creation. It’s excellent because it also goes through KnockoutJS, and has a section on using Web API with webforms.

I need to add user authentication and roles – this article contains some great info on hooking up users/roles.

Jason Zander’s blog post – has a nice walkthrough on the Web API: http://blogs.msdn.com/b/jasonz/archive/2012/07/23/my-favorite-features-entity-framework-code-first-and-asp-net-web-api.aspx

Best example I’ve seen yet on Web API – including the otherwise excellent MVC book by Apress – is this post: http://www.dotnetglobe.com/2012/03/crud-operation-using-aspnet-web-api-in.html

See the MSDN article here on Single Page Applications and MVC vs MVVM.

Another article on Web API and how it could be used vs WCF Data Services – http://msdn.microsoft.com/en-us/magazine/dn201742.aspx