SlideShare une entreprise Scribd logo
1  sur  66
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);

Contenu connexe

Tendances

Tendances (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
 

Similaire à Developing ASP.NET Applications Using the Model View Controller Pattern

Asp.Net Mvc
Asp.Net MvcAsp.Net Mvc
Asp.Net Mvcmicham
 
Controllers & actions
Controllers & actionsControllers & actions
Controllers & actionsEyal Vardi
 
ASP.NET Internals
ASP.NET InternalsASP.NET Internals
ASP.NET InternalsGoSharp
 
CTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVCCTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVCBarry Gervin
 
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
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVCMaarten Balliauw
 
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 AJAXIMC Institute
 
Spring 3.x - Spring MVC
Spring 3.x - Spring MVCSpring 3.x - Spring MVC
Spring 3.x - Spring MVCGuy Nir
 
ASP.net MVC CodeCamp Presentation
ASP.net MVC CodeCamp PresentationASP.net MVC CodeCamp Presentation
ASP.net MVC CodeCamp Presentationbuildmaster
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVCSunpawet Somsin
 
The WebView Role in Hybrid Applications
The WebView Role in Hybrid ApplicationsThe WebView Role in Hybrid Applications
The WebView Role in Hybrid ApplicationsHaim Michael
 
ASP.NET MVC Controllers & Actions
ASP.NET MVC Controllers & ActionsASP.NET MVC Controllers & Actions
ASP.NET MVC Controllers & Actionsonsela
 
Patterns Are Good For Managers
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For ManagersAgileThought
 
ASP.NET MVC introduction
ASP.NET MVC introductionASP.NET MVC introduction
ASP.NET MVC introductionTomi Juhola
 
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 InternalsLukasz Lysik
 

Similaire à 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
 

Plus de goodfriday

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

Plus de 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
 

Dernier

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 

Dernier (20)

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

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);