MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A...

66
The ASP.NET MVC Framework Scott Hanselman [email protected] http://www.hanselman.com

Transcript of MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A...

Page 1: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

The ASP.NET MVC Framework

Scott [email protected]://www.hanselman.com

Page 2: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

INTROMVC

Page 3: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

ASP.NET MVC is…

A new Web Project Type for ASP.NET.An option.More control over your <html/>A more easily Testable Framework.Not for everyone.

Page 4: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

“ScottGu”

Page 5: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

When I was born…

Page 6: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

“The Gu”

Page 7: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

“His Gu-ness”

Page 8: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

“Sir”

Page 9: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.
Page 10: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.
Page 11: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

“Master Chief Gu”

Page 12: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Demo – Hello MVC World

Don’t fall asleep, it’ll be worth it.

Page 13: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

What’s the Point?This is not Web Forms 4.0

It’s about alternatives. Car vs. Motorcycle.

FlexibleExtend it. Or not.

FundamentalPart of System.Web and isn’t going anywhere.

Plays Well With OthersFeel free to use NHibernate for Models, Brail for Views and Whatever for Controllers.

Keep it simple and DRY

Page 14: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Goodness – Driving Goals

Maintain Clean Separation of ConcernsEasy Testing Red/Green TDD Highly maintainable applications by default

Extensible and PluggableSupport replacing any component of the system

Page 15: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Goodness – Driving Goals

Enable clean URLs and HTMLSEO and REST friendly URL structures

Great integration within ASP.NETAll the same providers still workMembership, Session, Caching, etc.ASP.NET Designer Surface in VS2008

Page 16: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

RUDE Q&AMVC

Page 17: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Ok, um, a choice. I’m paralyzed.In what cases should I stick with WebForms over MVC?

Page 18: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

What’s up with REST?

I hear ASP.NET MVC can do REST. When would I use MVC vs. ADO Data Extensions (Astoria) vs. WCF?

Page 19: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Haven’t I heard this before?What is the difference between MVP and MVC?

Page 20: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Widgets? Do we have those?What is the component story with MVC?

Page 21: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Ship it.

When will MVC RTM?

Page 22: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Introducing…

Microsoft Visual Business Enabler Studio 2008R3v2 September Technical Preview RefreshMSVBES2k8R3v2lptrczstr for short

Page 23: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Will Ship Soon…

Page 24: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Will Ship Soon…

Page 25: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Is it safe?

What about security?

Page 26: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Does it scale?

What about performance/scalability?

Page 27: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

HOW IT WORKSMVC

27

Page 28: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

MVCModel

ControllerView

Page 29: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

A Little More Detail

Model

Controller

View

• Browser requests /Products/• Route is determined• Controller is activated• Method on Controller is invoke• Controller does some stuff• Renders View, passing in

custom ViewData• URLs are rendered,

pointing to other Controllers

Page 30: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Even More Detail – Request Flow

• You can futz at each step in the process

Request

Page 31: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Demo – Request Lifecycle

Digging deeper…

Page 32: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

FEATURESMVC

Page 33: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

URL Routing – Pretty URIsDevelopers adds Routes to a global RouteTableMapping creates a RouteData - a bag of key/values

RouteTable.Routes.Add( new Route("blog/bydate/{year}/{month}/{day}",

new MvcRouteHandler()){ Defaults = new RouteValueDictionary { {"controller", "blog"}, {"action", "show"} }, Constraints = new RouteValueDictionary { {"year", @"\d{1.4}"}, {"month", @"\d{1.2}"}, {"day", @"\d{1.2}"}} })

Page 34: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Demo – Routing

The route less travelled…

Page 35: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

ExtensibilityViewsControllersModelsRoutes

…are all Pluggable

Page 36: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

ViewEngineBaseView Engines render outputYou get WebForms by defaultCan implement your own

MVCContrib has ones for Brail, NvelocityNHaml is an interesting one to watch

View Engines can be used toOffer new DSLs to make HTML easierGenerate totally different mime/types

Images, RSS, JSON, XML, OFX, VCards, whatever.

Page 37: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

View Engine Base Class

ViewEngineBase

public abstract class ViewEngineBase { public abstract void RenderView(ViewContext

viewContext); }

Page 38: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

NHaml – Extreme Custom Views<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"

AutoEventWireup="true" CodeBehind="List.aspx"

Inherits="MvcApplication5.Views.Products.List" Title="Products" %><asp:Content ContentPlaceHolderID="MainContentPlaceHolder"

runat="server"> <h2><%= ViewData.CategoryName %></h2> <ul> <% foreach (var product in ViewData.Products) { %> <li> <%= product.ProductName %> <div class="editlink"> (<%= Html.ActionLink("Edit", new { Action="Edit",

ID=product.ProductID })%>) </div> </li> <% } %> </ul> <%= Html.ActionLink("Add New Product", new { Action="New" }) %></asp:Content>

Page 39: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

NHaml – Extreme Custom Views

%h2= ViewData.CategoryName %ul

- foreach (var product in ViewData.Products) %li = product.ProductName .editlink = Html.ActionLink("Edit", new { Action="Edit", ID=product.ProductID }) = Html.ActionLink("Add New Product", new { Action="New" })

Page 40: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

HOW TO TEST ITMVC

Page 41: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Interfaces and TDDMockable Intrinsics

HttpContextBase, HttpResponseBase, HttpRequestBase

Extensibility IControllerIControllerFactoryIRouteHandlerViewEngineBase

Page 42: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Testing Controller ActionsNo requirement to test within ASP.NET runtime.

Use RhinoMocks or TypeMockCreate Test versions of the parts of the runtime you want to stub

[TestMethod]public void ShowPostsDisplayPostView() { TestPostRepository repository = new TestPostRepository(); TestViewEngine viewEngine = new TestViewEngine();

BlogController controller = new BlogController(…); controller.ShowPost(2);

Assert.AreEqual("showpost",viewEngine.LastRequestedView); Assert.IsTrue(repository.GetPostByIdWasCalled); Assert.AreEqual(2, repository.LastRequestedPostId);}

Page 43: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Demo – TDD

Wasn’t this demo technically supposed to be first?

Page 44: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Demo – Complete Application

It’s your thing. Do what you wanna do.

Page 45: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

What’s the Point?This is not Web Forms 4.0

It’s about alternatives. Car vs. Motorcycle.

FlexibleExtend it. Or not.

FundamentalPart of System.Web and isn’t going anywhere.

Plays Well With OthersFeel free to use NHibernate for Models, Brail for Views and Whatever for Controllers.

Keep it simple and DRY

Page 46: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.
Page 47: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.
Page 48: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.
Page 49: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

HAI!IM IN YR NorthwindHOW DUZ I ListProducts YR idPRODUCTS = GETPRODUCTS idOMG FOUND YR PRODUCTSIF U SEZIM OUTTA YR Northwind

LOLCODE.NET

Page 50: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

HAI!WTF:I HAS A STRINGGIMMEH STRINGIM IN YR VAR UPPIN YR 0 TIL LENGTH OF STRINGVISIBLE “GIMMEE A ” STRING!!VARSTEPPINIM OUTTA YR VAROMGWTFHALP!

LOLCODE.NET

Page 51: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Be well,write good code,and stay in touch

[email protected]://hanselman.com

Page 52: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

© 2008 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.

The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after

the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Page 53: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

APPENDIXMVC

Page 54: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Controller

Base Controller ClassBasic Functionality most folks will use

IController InterfaceUltimate Control for the Control Freak

IControllerFactoryFor plugging in your own stuff (IOC, etc)

Page 55: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Basic Controller HandlingScenarios, Goals and Design

URLs route to controller “actions”, not pages – mark actions in Controller.Controller executes logic, chooses view.All public methods are accessible

public void ShowPost(int id) { Post p = PostRepository.GetPostById(id); if (p != null) { RenderView("showpost", p); } else { RenderView("nosuchpost", id); }}

Page 56: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Controller Base Classpublic class Controller : IController { … protected virtual void Execute(ControllerContext

controllerContext); protected virtual void HandleUnknownAction(string

actionName); protected virtual bool InvokeAction(string actionName); protected virtual void InvokeActionMethod(MethodInfo

methodInfo); protected virtual bool OnError(string actionName, MethodInfo methodInfo, Exception exception); protected virtual void

OnActionExecuted(FilterExecutedContext filterContext);

protected virtual bool OnActionExecuting(FilterExecutedContext filterContext);

protected virtual void RedirectToAction(object values); protected virtual void RenderView(string viewName, string masterName, object viewData);}

Page 57: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Controller – Regular APIspublic class Controller : IController { … protected virtual void Execute(ControllerContext

controllerContext); protected virtual void HandleUnknownAction(string

actionName); protected virtual bool InvokeAction(string actionName); protected virtual void InvokeActionMethod(MethodInfo

methodInfo); protected virtual bool OnError(string actionName, MethodInfo methodInfo, Exception exception); protected virtual void

OnActionExecuted(FilterExecutedContext filterContext);

protected virtual bool OnActionExecuting(FilterExecutedContext filterContext); protected virtual void RedirectToAction(object values);

protected virtual void RenderView(string viewName, string masterName, object viewData);}

Page 58: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Controller – Customization APIs

public class Controller : IController { … protected virtual void Execute(ControllerContext

controllerContext); protected virtual void HandleUnknownAction(string

actionName); protected virtual bool InvokeAction(string actionName); protected virtual void InvokeActionMethod(MethodInfo

methodInfo); protected virtual bool OnError(string actionName, MethodInfo methodInfo, Exception exception); protected virtual void

OnActionExecuted(FilterExecutedContext filterContext);

protected virtual bool OnActionExecuting(FilterExecutedContext filterContext);

protected virtual void RedirectToAction(object values); protected virtual void RenderView(string viewName, string masterName, object viewData);}

Page 59: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Controller – Test Hooks public class Controller : IController { … protected virtual void Execute(ControllerContext

controllerContext); protected virtual void HandleUnknownAction(string

actionName); protected virtual bool InvokeAction(string actionName); protected virtual void InvokeActionMethod(MethodInfo

methodInfo); protected virtual bool OnError(string actionName, MethodInfo methodInfo, Exception exception); protected virtual void

OnActionExecuted(FilterExecutedContext filterContext);

protected virtual bool OnActionExecuting(FilterExecutedContext filterContext);

protected virtual void RedirectToAction(object values); protected virtual void RenderView(string viewName, string masterName, object viewData);}

Page 60: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Basic ViewsScenarios, Goals and Design:

Are for rendering/output. Pre-defined and extensible rendering helpers

Can use .ASPX, .ASCX, .MASTER, etc.Can replace with other view technologies:

Template engines (NVelocity, Brail, …).Output formats (images, RSS, JSON, …).Mock out for testing.

Controller sets data on the ViewLoosely typed or strongly typed data

Page 61: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

ViewEngineBaseView Engines render outputYou get WebForms by defaultCan implement your own

MVCContrib has ones for Brail, NvelocityNHaml is an interesting one to watch

View Engines can be used toOffer new DSLs to make HTML easier to writeGenerate totally different mime/types

ImagesRSS, JSON, XML, OFX, etc.VCards, whatever.

Page 62: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

View Engine Base Class

ViewEngineBase

public abstract class ViewEngineBase { public abstract void RenderView(ViewContext

viewContext); }

Page 63: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

NHaml – Extreme Custom Views<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"

AutoEventWireup="true" CodeBehind="List.aspx"

Inherits="MvcApplication5.Views.Products.List" Title="Products" %><asp:Content ContentPlaceHolderID="MainContentPlaceHolder"

runat="server"> <h2><%= ViewData.CategoryName %></h2> <ul> <% foreach (var product in ViewData.Products) { %> <li> <%= product.ProductName %> <div class="editlink"> (<%= Html.ActionLink("Edit", new { Action="Edit",

ID=product.ProductID })%>) </div> </li> <% } %> </ul> <%= Html.ActionLink("Add New Product", new { Action="New" }) %></asp:Content>

Page 64: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

NHaml – Extreme Custom Views

%h2= ViewData.CategoryName %ul

- foreach (var product in ViewData.Products) %li = product.ProductName .editlink = Html.ActionLink("Edit", new { Action="Edit", ID=product.ProductID }) = Html.ActionLink("Add New Product", new { Action="New" })

Page 65: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

Controller Factory

Scenarios, Goals and Design:Hook creation of controller instance

Dependency Injection.Object Interception.

public interface IControllerFactory { IController CreateController(RequestContext context, string controllerName);}

protected void Application_Start(object s, EventArgs e) { ControllerBuilder.Current.SetControllerFactory( typeof(MyControllerFactory));}

Page 66: MVC A new Web Project Type for ASP.NET. An option. More control over your More control over your A more easily Testable Framework. Not for everyone.

View Engine

Scenarios, Goals and Design:Mock out views for testingReplace ASPX with other technologies

public interface IViewEngine { void RenderView(ViewContext context); }

Inside controller class: this.ViewEngine = new XmlViewEngine(...);

RenderView("foo", myData);