SlideShare a Scribd company logo
MVC
A new Web Project Type for
ASP.NET.
An option.
More control over your <html/>
A more easily Testable
Framework.
Not for everyone.
“ScottGu”
“The Gu”
“His Gu-ness”
“Sir”
“Master Chief Gu”
This is not Web Forms 4.0
  It’s about alternatives. Car vs. Motorcycle.
Flexible
  Extend it. Or not.
Fundamental
  Part of System.Web and isn’t going anywhere.
Plays Well With Others
  Feel free to use NHibernate for Models, Brail
  for Views and Whatever for Controllers.
Keep it simple and DRY
Maintain Clean Separation of Concerns
  Easy Testing
  Red/Green TDD
  Highly maintainable applications by default
Extensible and Pluggable
  Support replacing any component of the
  system
Enable clean URLs and HTML
  SEO and REST friendly URL structures
Great integration within ASP.NET
  All the same providers still work
  Membership, Session, Caching, etc.
  ASP.NET Designer Surface in VS2008
MVC
Microsoft Visual Business
Enabler Studio 2008R3v2
September Technical
Preview Refresh
MSVBES2k8R3v2lptrczstr
for short
MVC




      27
Model




View           Controller
•Browser requests /Products/
       Model          •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
View           Controller     Controllers
• You can futz at each step
Request
             in the process


 HTTP      Http
                      Controller   Response
Routing   Handler




           Route        View
 Route                               View
          Handler      Engine
MVC
Developers adds Routes to a global RouteTable
   Mapping creates a RouteData - a bag of key/values
RouteTable.Routes.Add(
  new Route(quot;blog/bydate/{year}/{month}/{day}quot;,
    new MvcRouteHandler()){
    Defaults = new RouteValueDictionary {
     {quot;controllerquot;, quot;blogquot;}, {quot;actionquot;, quot;showquot;}
    },
    Constraints = new RouteValueDictionary {
       {quot;yearquot;, @quot;d{1.4}quot;},
       {quot;monthquot;, @quot;d{1.2}quot;},
       {quot;dayquot;, @quot;d{1.2}quot;}}
  })
Views
Controllers
Models
Routes

…are all Pluggable
View Engines render output
You get WebForms by default
Can implement your own
  MVCContrib has ones for Brail, Nvelocity
  NHaml is an interesting one to watch
View Engines can be used to
  Offer new DSLs to make HTML easier
  Generate totally different mime/types
   Images, RSS, JSON, XML, OFX, VCards,
   whatever.
ViewEngineBase
public abstract class ViewEngineBase {
    public abstract void RenderView(ViewContext viewContext);
}
<%@ Page Language=quot;C#quot; MasterPageFile=quot;~/Views/Shared/Site.Masterquot;
   AutoEventWireup=quot;truequot;
    CodeBehind=quot;List.aspxquot;
   Inherits=quot;MvcApplication5.Views.Products.Listquot; Title=quot;Productsquot; %>
<asp:Content ContentPlaceHolderID=quot;MainContentPlaceHolderquot;
   runat=quot;serverquot;>
  <h2><%= ViewData.CategoryName %></h2>
  <ul>
    <% foreach (var product in ViewData.Products) { %>
       <li>
         <%= product.ProductName %>
         <div class=quot;editlinkquot;>
            (<%= Html.ActionLink(quot;Editquot;, new { Action=quot;Editquot;,
   ID=product.ProductID })%>)
         </div>
       </li>
    <% } %>
  </ul>
  <%= Html.ActionLink(quot;Add New Productquot;, new { Action=quot;Newquot; }) %>
</asp:Content>
%h2= ViewData.CategoryName
  %ul
    - foreach (var product in ViewData.Products)
    %li = product.ProductName
      .editlink
         = Html.ActionLink(quot;Editquot;,
             new { Action=quot;Editquot;,
             ID=product.ProductID })
         = Html.ActionLink(quot;Add New Productquot;,
             new { Action=quot;Newquot; })
MVC
Mockable Intrinsics
  HttpContextBase,
  HttpResponseBase,
  HttpRequestBase
Extensibility
  IController
  IControllerFactory
  IRouteHandler
  ViewEngineBase
No requirement to test within ASP.NET runtime.
        Use RhinoMocks or TypeMock
        Create 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(quot;showpostquot;,viewEngine.LastRequestedView);
    Assert.IsTrue(repository.GetPostByIdWasCalled);
    Assert.AreEqual(2, repository.LastRequestedPostId);
}
This is not Web Forms 4.0
  It’s about alternatives. Car vs. Motorcycle.
Flexible
  Extend it. Or not.
Fundamental
  Part of System.Web and isn’t going anywhere.
Plays Well With Others
  Feel free to use NHibernate for Models, Brail
  for Views and Whatever for Controllers.
Keep it simple and DRY
HAI!
IM IN YR Northwind
HOW DUZ I ListProducts YR id
PRODUCTS = GETPRODUCTS id
OMG FOUND YR PRODUCTS
IF U SEZ
IM OUTTA YR Northwind
HAI!
WTF:
I HAS A STRING
GIMMEH STRING
IM IN YR VAR UPPIN YR 0
   TIL LENGTH OF STRING
VISIBLE “GIMMEE A ” STRING!!VAR
STEPPIN
IM OUTTA YR VAR
OMGWTF
HALP!
© 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.
MVC
Base Controller Class
   Basic Functionality most folks will use
IController Interface
   Ultimate Control for the Control Freak
IControllerFactory
   For plugging in your own stuff (IOC, etc)
Scenarios, 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(quot;showpostquot;, p);
     } else {
         RenderView(quot;nosuchpostquot;, id);
     }
}
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);
}
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);
}
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);
}
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);
}
Scenarios, 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 View
   Loosely typed or strongly typed data
View Engines render output
You get WebForms by default
Can implement your own
  MVCContrib has ones for Brail, Nvelocity
  NHaml is an interesting one to watch
View Engines can be used to
  Offer new DSLs to make HTML easier to write
  Generate totally different mime/types
    Images
    RSS, JSON, XML, OFX, etc.
    VCards, whatever.
ViewEngineBase
public abstract class ViewEngineBase {
    public abstract void RenderView(ViewContext viewContext);
}
<%@ Page Language=quot;C#quot; MasterPageFile=quot;~/Views/Shared/Site.Masterquot;
   AutoEventWireup=quot;truequot;
    CodeBehind=quot;List.aspxquot;
   Inherits=quot;MvcApplication5.Views.Products.Listquot; Title=quot;Productsquot;
<asp:Content ContentPlaceHolderID=quot;MainContentPlaceHolderquot;
   runat=quot;serverquot;>
  <h2><%= ViewData.CategoryName %></h2>
  <ul>
    <% foreach (var product in ViewData.Products) { %>
      <li>
        <%= product.ProductName %>
        <div class=quot;editlinkquot;>
          (<%= Html.ActionLink(quot;Editquot;, new { Action=quot;Editquot;,
   ID=product.ProductID })%>)
        </div>
      </li>
    <% } %>
  </ul>
  <%= Html.ActionLink(quot;Add New Productquot;, new { Action=quot;Newquot; }) %>
</asp:Content>
%h2= ViewData.CategoryName
  %ul
    - foreach (var product in ViewData.Products)
    %li = product.ProductName
      .editlink
         = Html.ActionLink(quot;Editquot;,
             new { Action=quot;Editquot;,
             ID=product.ProductID })
         = Html.ActionLink(quot;Add New Productquot;,
             new { Action=quot;Newquot; })
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));
}
Scenarios, Goals and Design:
     Mock out views for testing
     Replace ASPX with other technologies
public interface IViewEngine {
    void RenderView(ViewContext context);
}

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

   RenderView(quot;fooquot;, myData);

More Related Content

What's hot

What's hot (20)

Hybrid apps - Your own mini Cordova
Hybrid apps - Your own mini CordovaHybrid apps - Your own mini Cordova
Hybrid apps - Your own mini Cordova
 
React on es6+
React on es6+React on es6+
React on es6+
 
Introduction to Google Guice
Introduction to Google GuiceIntroduction to Google Guice
Introduction to Google Guice
 
ASP.NET MVC Internals
ASP.NET MVC InternalsASP.NET MVC Internals
ASP.NET MVC Internals
 
A gently introduction to AngularJS
A gently introduction to AngularJSA gently introduction to AngularJS
A gently introduction to AngularJS
 
Speed up your GWT coding with gQuery
Speed up your GWT coding with gQuerySpeed up your GWT coding with gQuery
Speed up your GWT coding with gQuery
 
Workshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIWorkshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte III
 
Angular2 & ngrx/store: Game of States
Angular2 & ngrx/store: Game of StatesAngular2 & ngrx/store: Game of States
Angular2 & ngrx/store: Game of States
 
React, Flux and a little bit of Redux
React, Flux and a little bit of ReduxReact, Flux and a little bit of Redux
React, Flux and a little bit of Redux
 
MongoDB Stitch Tutorial
MongoDB Stitch TutorialMongoDB Stitch Tutorial
MongoDB Stitch Tutorial
 
Advanced Dagger talk from 360andev
Advanced Dagger talk from 360andevAdvanced Dagger talk from 360andev
Advanced Dagger talk from 360andev
 
Google Web Toolkits
Google Web ToolkitsGoogle Web Toolkits
Google Web Toolkits
 
React & Redux
React & ReduxReact & Redux
React & Redux
 
Introduction to AJAX and DWR
Introduction to AJAX and DWRIntroduction to AJAX and DWR
Introduction to AJAX and DWR
 
Learn react-js
Learn react-jsLearn react-js
Learn react-js
 
Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4
 
Controller Testing: You're Doing It Wrong
Controller Testing: You're Doing It WrongController Testing: You're Doing It Wrong
Controller Testing: You're Doing It Wrong
 
React & Redux
React & ReduxReact & Redux
React & Redux
 
Intro to ReactJS
Intro to ReactJSIntro to ReactJS
Intro to ReactJS
 
AngularJS Workshop
AngularJS WorkshopAngularJS Workshop
AngularJS Workshop
 

Similar to Developing ASP.NET Applications Using the Model View Controller Pattern

Controllers & actions
Controllers & actionsControllers & actions
Controllers & actions
Eyal Vardi
 
Windows Store app using XAML and C#: Enterprise Product Development
Windows Store app using XAML and C#: Enterprise Product Development Windows Store app using XAML and C#: Enterprise Product Development
Windows Store app using XAML and C#: Enterprise Product Development
Mahmoud Hamed Mahmoud
 
Spring 3.x - Spring MVC
Spring 3.x - Spring MVCSpring 3.x - Spring MVC
Spring 3.x - Spring MVC
Guy Nir
 
ASP.NET MVC Controllers & Actions
ASP.NET MVC Controllers & ActionsASP.NET MVC Controllers & Actions
ASP.NET MVC Controllers & Actions
onsela
 

Similar to Developing ASP.NET Applications Using the Model View Controller Pattern (20)

Asp.Net Mvc
Asp.Net MvcAsp.Net Mvc
Asp.Net Mvc
 
Asp.Net MVC Intro
Asp.Net MVC IntroAsp.Net MVC Intro
Asp.Net MVC Intro
 
Controllers & actions
Controllers & actionsControllers & actions
Controllers & actions
 
ASP .net MVC
ASP .net MVCASP .net MVC
ASP .net MVC
 
Mvc - Titanium
Mvc - TitaniumMvc - Titanium
Mvc - Titanium
 
Asp.net mvc
Asp.net mvcAsp.net mvc
Asp.net mvc
 
ASP.NET Internals
ASP.NET InternalsASP.NET Internals
ASP.NET Internals
 
CTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVCCTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVC
 
Windows Store app using XAML and C#: Enterprise Product Development
Windows Store app using XAML and C#: Enterprise Product Development Windows Store app using XAML and C#: Enterprise Product Development
Windows Store app using XAML and C#: Enterprise Product Development
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
 
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXJava Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAX
 
Asp.net mvc
Asp.net mvcAsp.net mvc
Asp.net mvc
 
Spring 3.x - Spring MVC
Spring 3.x - Spring MVCSpring 3.x - Spring MVC
Spring 3.x - Spring MVC
 
ASP.net MVC CodeCamp Presentation
ASP.net MVC CodeCamp PresentationASP.net MVC CodeCamp Presentation
ASP.net MVC CodeCamp Presentation
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
 
The WebView Role in Hybrid Applications
The WebView Role in Hybrid ApplicationsThe WebView Role in Hybrid Applications
The WebView Role in Hybrid Applications
 
ASP.NET MVC Controllers & Actions
ASP.NET MVC Controllers & ActionsASP.NET MVC Controllers & Actions
ASP.NET MVC Controllers & Actions
 
Patterns Are Good For Managers
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For Managers
 
ASP.NET MVC introduction
ASP.NET MVC introductionASP.NET MVC introduction
ASP.NET MVC introduction
 
ASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline InternalsASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline Internals
 

More from goodfriday

Narine Presentations 20051021 134052
Narine Presentations 20051021 134052Narine Presentations 20051021 134052
Narine Presentations 20051021 134052
goodfriday
 
09 03 22 easter
09 03 22 easter09 03 22 easter
09 03 22 easter
goodfriday
 
Holy Week Easter 2009
Holy Week Easter 2009Holy Week Easter 2009
Holy Week Easter 2009
goodfriday
 
Holt Park Easter 09 Swim
Holt Park Easter 09 SwimHolt Park Easter 09 Swim
Holt Park Easter 09 Swim
goodfriday
 
Swarthmore Lentbrochure20092
Swarthmore Lentbrochure20092Swarthmore Lentbrochure20092
Swarthmore Lentbrochure20092
goodfriday
 
Eastercard2009
Eastercard2009Eastercard2009
Eastercard2009
goodfriday
 
Easterservices2009
Easterservices2009Easterservices2009
Easterservices2009
goodfriday
 
Bulletin Current
Bulletin CurrentBulletin Current
Bulletin Current
goodfriday
 
March 2009 Newsletter
March 2009 NewsletterMarch 2009 Newsletter
March 2009 Newsletter
goodfriday
 
Lent Easter 2009
Lent Easter 2009Lent Easter 2009
Lent Easter 2009
goodfriday
 
Easterpowersports09
Easterpowersports09Easterpowersports09
Easterpowersports09
goodfriday
 
Easter Trading 09
Easter Trading 09Easter Trading 09
Easter Trading 09
goodfriday
 
Easter Brochure 2009
Easter Brochure 2009Easter Brochure 2009
Easter Brochure 2009
goodfriday
 
March April 2009 Calendar
March April 2009 CalendarMarch April 2009 Calendar
March April 2009 Calendar
goodfriday
 

More from goodfriday (20)

Narine Presentations 20051021 134052
Narine Presentations 20051021 134052Narine Presentations 20051021 134052
Narine Presentations 20051021 134052
 
Triunemar05
Triunemar05Triunemar05
Triunemar05
 
09 03 22 easter
09 03 22 easter09 03 22 easter
09 03 22 easter
 
Holy Week Easter 2009
Holy Week Easter 2009Holy Week Easter 2009
Holy Week Easter 2009
 
Holt Park Easter 09 Swim
Holt Park Easter 09 SwimHolt Park Easter 09 Swim
Holt Park Easter 09 Swim
 
Easter Letter
Easter LetterEaster Letter
Easter Letter
 
April2009
April2009April2009
April2009
 
Swarthmore Lentbrochure20092
Swarthmore Lentbrochure20092Swarthmore Lentbrochure20092
Swarthmore Lentbrochure20092
 
Eastercard2009
Eastercard2009Eastercard2009
Eastercard2009
 
Easterservices2009
Easterservices2009Easterservices2009
Easterservices2009
 
Bulletin Current
Bulletin CurrentBulletin Current
Bulletin Current
 
Easter2009
Easter2009Easter2009
Easter2009
 
Bulletin
BulletinBulletin
Bulletin
 
March 2009 Newsletter
March 2009 NewsletterMarch 2009 Newsletter
March 2009 Newsletter
 
Mar 29 2009
Mar 29 2009Mar 29 2009
Mar 29 2009
 
Lent Easter 2009
Lent Easter 2009Lent Easter 2009
Lent Easter 2009
 
Easterpowersports09
Easterpowersports09Easterpowersports09
Easterpowersports09
 
Easter Trading 09
Easter Trading 09Easter Trading 09
Easter Trading 09
 
Easter Brochure 2009
Easter Brochure 2009Easter Brochure 2009
Easter Brochure 2009
 
March April 2009 Calendar
March April 2009 CalendarMarch April 2009 Calendar
March April 2009 Calendar
 

Recently uploaded

Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 

Recently uploaded (20)

"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. Startups
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří Karpíšek
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG Evaluation
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 

Developing ASP.NET Applications Using the Model View Controller Pattern

  • 1.
  • 2. MVC
  • 3. A new Web Project Type for ASP.NET. An option. More control over your <html/> A more easily Testable Framework. Not for everyone.
  • 5.
  • 9.
  • 10.
  • 12.
  • 13. This is not Web Forms 4.0 It’s about alternatives. Car vs. Motorcycle. Flexible Extend it. Or not. Fundamental Part of System.Web and isn’t going anywhere. Plays Well With Others Feel free to use NHibernate for Models, Brail for Views and Whatever for Controllers. Keep it simple and DRY
  • 14. Maintain Clean Separation of Concerns Easy Testing Red/Green TDD Highly maintainable applications by default Extensible and Pluggable Support replacing any component of the system
  • 15. Enable clean URLs and HTML SEO and REST friendly URL structures Great integration within ASP.NET All the same providers still work Membership, Session, Caching, etc. ASP.NET Designer Surface in VS2008
  • 16. MVC
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22. Microsoft Visual Business Enabler Studio 2008R3v2 September Technical Preview Refresh MSVBES2k8R3v2lptrczstr for short
  • 23.
  • 24.
  • 25.
  • 26.
  • 27. MVC 27
  • 28. Model View Controller
  • 29. •Browser requests /Products/ Model •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 View Controller Controllers
  • 30. • You can futz at each step Request in the process HTTP Http Controller Response Routing Handler Route View Route View Handler Engine
  • 31.
  • 32. MVC
  • 33. Developers adds Routes to a global RouteTable Mapping creates a RouteData - a bag of key/values RouteTable.Routes.Add( new Route(quot;blog/bydate/{year}/{month}/{day}quot;, new MvcRouteHandler()){ Defaults = new RouteValueDictionary { {quot;controllerquot;, quot;blogquot;}, {quot;actionquot;, quot;showquot;} }, Constraints = new RouteValueDictionary { {quot;yearquot;, @quot;d{1.4}quot;}, {quot;monthquot;, @quot;d{1.2}quot;}, {quot;dayquot;, @quot;d{1.2}quot;}} })
  • 34.
  • 36. View Engines render output You get WebForms by default Can implement your own MVCContrib has ones for Brail, Nvelocity NHaml is an interesting one to watch View Engines can be used to Offer new DSLs to make HTML easier Generate totally different mime/types Images, RSS, JSON, XML, OFX, VCards, whatever.
  • 37. ViewEngineBase public abstract class ViewEngineBase { public abstract void RenderView(ViewContext viewContext); }
  • 38. <%@ Page Language=quot;C#quot; MasterPageFile=quot;~/Views/Shared/Site.Masterquot; AutoEventWireup=quot;truequot; CodeBehind=quot;List.aspxquot; Inherits=quot;MvcApplication5.Views.Products.Listquot; Title=quot;Productsquot; %> <asp:Content ContentPlaceHolderID=quot;MainContentPlaceHolderquot; runat=quot;serverquot;> <h2><%= ViewData.CategoryName %></h2> <ul> <% foreach (var product in ViewData.Products) { %> <li> <%= product.ProductName %> <div class=quot;editlinkquot;> (<%= Html.ActionLink(quot;Editquot;, new { Action=quot;Editquot;, ID=product.ProductID })%>) </div> </li> <% } %> </ul> <%= Html.ActionLink(quot;Add New Productquot;, new { Action=quot;Newquot; }) %> </asp:Content>
  • 39. %h2= ViewData.CategoryName %ul - foreach (var product in ViewData.Products) %li = product.ProductName .editlink = Html.ActionLink(quot;Editquot;, new { Action=quot;Editquot;, ID=product.ProductID }) = Html.ActionLink(quot;Add New Productquot;, new { Action=quot;Newquot; })
  • 40. MVC
  • 41. Mockable Intrinsics HttpContextBase, HttpResponseBase, HttpRequestBase Extensibility IController IControllerFactory IRouteHandler ViewEngineBase
  • 42. No requirement to test within ASP.NET runtime. Use RhinoMocks or TypeMock Create 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(quot;showpostquot;,viewEngine.LastRequestedView); Assert.IsTrue(repository.GetPostByIdWasCalled); Assert.AreEqual(2, repository.LastRequestedPostId); }
  • 43.
  • 44.
  • 45. This is not Web Forms 4.0 It’s about alternatives. Car vs. Motorcycle. Flexible Extend it. Or not. Fundamental Part of System.Web and isn’t going anywhere. Plays Well With Others Feel free to use NHibernate for Models, Brail for Views and Whatever for Controllers. Keep it simple and DRY
  • 46.
  • 47.
  • 48.
  • 49. HAI! IM IN YR Northwind HOW DUZ I ListProducts YR id PRODUCTS = GETPRODUCTS id OMG FOUND YR PRODUCTS IF U SEZ IM OUTTA YR Northwind
  • 50. HAI! WTF: I HAS A STRING GIMMEH STRING IM IN YR VAR UPPIN YR 0 TIL LENGTH OF STRING VISIBLE “GIMMEE A ” STRING!!VAR STEPPIN IM OUTTA YR VAR OMGWTF HALP!
  • 51.
  • 52. © 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.
  • 53. MVC
  • 54. Base Controller Class Basic Functionality most folks will use IController Interface Ultimate Control for the Control Freak IControllerFactory For plugging in your own stuff (IOC, etc)
  • 55. Scenarios, 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(quot;showpostquot;, p); } else { RenderView(quot;nosuchpostquot;, id); } }
  • 56. 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); }
  • 57. 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); }
  • 58. 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); }
  • 59. 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); }
  • 60. Scenarios, 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 View Loosely typed or strongly typed data
  • 61. View Engines render output You get WebForms by default Can implement your own MVCContrib has ones for Brail, Nvelocity NHaml is an interesting one to watch View Engines can be used to Offer new DSLs to make HTML easier to write Generate totally different mime/types Images RSS, JSON, XML, OFX, etc. VCards, whatever.
  • 62. ViewEngineBase public abstract class ViewEngineBase { public abstract void RenderView(ViewContext viewContext); }
  • 63. <%@ Page Language=quot;C#quot; MasterPageFile=quot;~/Views/Shared/Site.Masterquot; AutoEventWireup=quot;truequot; CodeBehind=quot;List.aspxquot; Inherits=quot;MvcApplication5.Views.Products.Listquot; Title=quot;Productsquot; <asp:Content ContentPlaceHolderID=quot;MainContentPlaceHolderquot; runat=quot;serverquot;> <h2><%= ViewData.CategoryName %></h2> <ul> <% foreach (var product in ViewData.Products) { %> <li> <%= product.ProductName %> <div class=quot;editlinkquot;> (<%= Html.ActionLink(quot;Editquot;, new { Action=quot;Editquot;, ID=product.ProductID })%>) </div> </li> <% } %> </ul> <%= Html.ActionLink(quot;Add New Productquot;, new { Action=quot;Newquot; }) %> </asp:Content>
  • 64. %h2= ViewData.CategoryName %ul - foreach (var product in ViewData.Products) %li = product.ProductName .editlink = Html.ActionLink(quot;Editquot;, new { Action=quot;Editquot;, ID=product.ProductID }) = Html.ActionLink(quot;Add New Productquot;, new { Action=quot;Newquot; })
  • 65. 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)); }
  • 66. Scenarios, Goals and Design: Mock out views for testing Replace ASPX with other technologies public interface IViewEngine { void RenderView(ViewContext context); } Inside controller class: this.ViewEngine = new XmlViewEngine(...); RenderView(quot;fooquot;, myData);