ASP.Net MVC, Web API, SPA, HoTTowel, Durandal


Published on

Build web sites using single page application technology

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

ASP.Net MVC, Web API, SPA, HoTTowel, Durandal

  2. 2. INDEX Introduction Render (Page, Section, Body ) MVC Framework & Definition Partial View Model & View Model Folder Structuring (Area) Scaffolding HTML Helper Routes & Config Setting Data Annotation Action Verbs Library Example (continue ) Action Results HTML Encoding with Razor Layouts
  3. 3. INTRODUCTION • MVC Pattern: • Model-View-Controller (MVC) is an framework for web platforms including an important architectural pattern in computer science for many years. Originally named Thing-Model-ViewEditor in 1979, simplified to Model-View-Controller. • MVC existing in Java and C++, on Mac and on Windows, and inside other frameworks. • The MVC separates the user interface (UI) of an application into three main aspects: • The Model: A set of classes that describes how the data can be changed and manipulated. • The View: it’s a template to generate HTML. defines how the application’s UI will be displayed. • The Controller: A set of classes that handles communication from the user, overall application flow, and application specific logic.
  6. 6. WHY MVC? • Three layers (Model, View and Controller) Reduced the complexity. • Loose coupling. • Better support for test-driven development (TDD). • Better performance • Easy to maintain.
  7. 7. RELEASE HISTORY Date Version 10 13 16 04 10 06 09 10 13 20 15 31 15 ASP.NET MVC CTP ASP.NET MVC 1.0 ASP.NET MVC 2 RC ASP.NET MVC 2 RC 2 ASP.NET MVC 2 ASP.NET MVC 3 Beta ASP.NET MVC 3 RC ASP.NET MVC 3 RC 2 ASP.NET MVC 3 ASP.NET MVC 4 Developer Preview ASP.NET MVC 4 Beta ASP.NET MVC 4 RC ASP.NET MVC 4 Dec 07 Mar 09 Dec 09 Feb 10 Mar 10 Oct 10 Nov 10 Dec 10 Jan 11 Sep 11 Feb 12 May 12 Aug 12
  8. 8. HISTORY OVERVIEW • ScottGu started first sketch out 2007 (Scalene) • 9 releases, 3 years. MVC2-2010 MVC3-2011 MVC4-2012 (.NET Framework 3.5) MVC1- 2009 (.NET Framework 4.0) (.NET Framework 4.5) • • • • • • JQuery library included but still using Ajax validation • UI helpers , automatic scaffolding , customizable templates • HTML helpers • Client & server model validation • Partioning (areas) • Rendering subsections of a page/site using Html.RenderAction • Asynchronous controllers support • New helper function • Global action filters (authorize) • Used jQuery validation JSON dependency resolver (ease the dependency injection for decoupling the application) Open source libraries (JQuery, Modernizer) • • • • • • ASP.NET Web API. Enhancements to default project templates. Mobile project template using jQuery Mobile. Display Modes (as per browser request change the view) Task support for Asynchronous Controllers. Bundling and minification. New Open source libraries (Json.Net, DotNetOpenAuth ) Other features like (all config in one place app_start, add controller at any where)
  10. 10. DEFINITION • Controllers are the conductors of an MVC application, • Managing the interactions between the user, the model objects, and the views. • They are responsible for responding to user input, manipulating the appropriate model objects, and then selecting the appropriate view to display back to the user in response to the initial input.
  11. 11. ROUTES
  12. 12. BUNDLING AND MINIFICATION Bundling and minification are two techniques you can use in ASP.NET 4.5 to improve request load time. Bundling and minification improves load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript.) Most of the current major browsers limit the number of simultaneous connections per each hostname to six. That means that while six requests are being processed, additional requests for assets on a host will be queued by the browser. Bundling Bundling is a new feature in ASP.NET 4.5 that makes it easy to combine or bundle multiple files into a single file. You can create CSS, JavaScript and other bundles. Fewer files means fewer HTTP requests and that can improve first page load performance.
  13. 13. ACTIONS • Action Filters (Global filter like Error msg) • Action Results (table here) • Action Selectors (Verbs, Names)
  14. 14. ACTION RESULTS Action Result ViewResult Helper Method View Description Renders a view as a Web page. Renders a partial view, which defines a section of a view that can be rendered inside another view. PartialViewResult PartialView RedirectResult Redirect RedirectToRouteResult RedirectToAction ContentResult Content Returns a user-defined content type. JsonResult Json Returns a serialized JSON object. JavaScriptResult JavaScript FileResult File EmptyResult (None) Redirects to another action method by using its URL. Redirects to another action method. Returns a script that can be executed on the client. Returns binary output to write to the response. Represents a return value that is used if the action method must return a null result (void).
  15. 15. VIEWS
  16. 16. VIEW BAG & VIEW DATA • Both can are ViewDatadictionary class • Both Can read and write • ViewData["CurrentTime"] = DateTime.Now; • ViewBag.CurrentTime = DateTime.Now; //view bag dynamic expression can't be passed to extension method as a parameter . • @Html.TextBox("name", ViewBag.Name) • @Html.TextBox("name", (string)ViewBag.Name) ok
  17. 17. LAYOUT
  18. 18. VIEW START • The _ViewStart.cshtml page can be used to remove this redundancy. • The code within this fi le is executed before the code in any view placed in the same directory. • This fi le is also recursively applied to any view within a subdirectory. @{ Layout = "~/Views/Shared/_Layout.cshtml"; }
  19. 19. HTML ENCODING • Web site security vulnerabilities in 2007 XSS (84%) • Razor expressions are automatically HTML encoded and mitigate the risk @{ ViewBag.MSg = "<script>alert('xss');</script>"; } <span>@ViewBag.MSg</span>
  20. 20. RENDER BODY
  22. 22. RENDER PAGE
  23. 23. PARTIAL VIEW • Shared between views • Like widgets, user controls , web parts • HTML & Razor syntax • Preferred (not mandatory) to be in shared folder • Returned fragment of HTML.
  24. 24. VIEW ENGINE (RAZOR) ASP.Net MVC has two main view engines : • Web Forms View Engine • Razor View Engine Why Razor: clean, lightweight, simple just type HTML and hit the @ sign when you want to insert some code.
  25. 25. RAZOR VIEW & WEB FORMS VIEW //Space is not a valid identifier so next will be markup
  26. 26. VIEW MODEL Model : Map directly to a domain model. public class Product { public int ID { get; set; } public string Name { get; set; } public string Description { get; set; } View Model: Flexible to display different information and doesn’t map directly to a domain model. public class { public public public } ShoppingCartViewModel IEnumerable<Product> Products { get; set; } decimal CartTotal { get; set; } string Message { get; set; }
  27. 27. MODEL
  29. 29. SCAFFOLDING • What Is Scaffolding? • Scaffolding in ASP.NET MVC can generate the boilerplate code you need for (CRUD) functionality in an application. • The scaffolding templates can examine the type definition for a model (such as the Album class you’ve created), and then generate a controller and the controller’s associated views. • The scaffolding knows how to name controllers, how to name views, what code needs to go in each component, and where to place all these pieces in the project for the application to work.
  30. 30. SCAFFOLDING & EF IN ASP.NET MVC • A new ASP.NET MVC 4 project will automatically include a reference to the Entity Framework (EF). EF is an object-relational mapping framework and understands how to store .NET objects in a relational database and retrieve those same objects given a LINQ query. • FLEXIBLE DATA OPTIONS • If you don’t want to use the Entity Framework in your ASP.NET MVC application, there is nothing in the framework forcing you to take a dependency on EF. In fact, there is nothing in the framework forcing you to use a database, relational or otherwise. • You can build applications using any data access technology or data source. • If you want to work with comma-delimited text fi les or web services using the full • complement of WS-* protocols, you can! • In this chapter, you work with EF, but many of the topics covered are broadly • applicable to any data source. • EF supports a code-fi rst style of development. Code First means you can start storing and retrieving • information in SQL Server without creating a database schema or opening a Visual Studio designer. • Instead, you
  31. 31. HTML HELPERS @Html.ActionLink("Delete", "Delete", new{ }) • In most cases, an HTML helper is just a method that returns a string. • Like traditional ASP.NET Web Form controls. • HTML helpers are used to modify HTML, • Its more lightweight. Unlike Web Form controls, • Does not have an event model and a view state. • Custom HTML helpers.
  32. 32. HTML HELPERS EXAMPLES ActionLink — Links to an action method. •BeginForm * — Marks the start of a form and links to the action method that renders the form. •CheckBox * — Renders a check box. •DropDownList * — Renders a drop-down list. •Hidden — Embeds information in the form that is not rendered for the user to see. •ListBox — Renders a list box. •Password — Renders a text box for entering a password. •RadioButton * — Renders a radio button. •TextArea — Renders a text area (multi-line text box). •TextBox * — Renders a text box.
  33. 33. IIS EXPRESS 7.5 • It does not require an administrator account to run/debug applications from Visual Studio • It enables a full web-server feature set – including SSL, URL Rewrite, Media Support, and all other IIS 7.x modules • Easier to build, run and test web applications. • It works with all versions of ASP.NET and supports all ASP.NET application types (including obviously both ASP.NET Web Forms and ASP.NET MVC applications) also supports classic asp. • We can build and run your applications just like they’ll work on a real production web-server. In addition to supporting ASP.NET,
  35. 35. JSON & SERIALIZATION • "JSON" (JavaScript Object Notation) is a lightweight text-based open standard designed for humanreadable data interchange. When working together with "jQuery" and "ASP.NET MVC" in building web applications, it provides an efficient mechanism to exchange data between the web browser and the web server
  36. 36. AJAX & MVC
  37. 37. AUTHENTICATION & AUTHORIZATION • Authenticate using Simple Membership Provider • Authorize /allow anonymous • Authorize [users (“”)] • Authorize [Roles(“”)] • HTTPS • Cross Site Request Forgery • OAuth & OpenID
  39. 39. SIMPLE MEMBERSHIP PROVIDER • ASP.NET 2.0 back in 2005 • This schema Universal Providers. (View, SPS, Tables)
  41. 41. HTTP • Short for HyperText Transfer Protocol, the underlying protocol used by the World Wide Web. HTTP defines how messages are formatted and transmitted, and what actions Web servers and browsers should take in response to various commands. For example, when you enter a URL in your browser, this actually sends an HTTP command to the Web server directing it to fetch and transmit the requested Web page. • The other main standard that controls how the World Wide Web works is HTML, which covers how Web pages are formatted and displayed. • HTTP is called a stateless protocol because each command is executed independently, without any knowledge of the commands that came before it. This is the main reason that it is difficult to implement Web sites that react intelligently to user input. This shortcoming of HTTP is being addressed in a number of new technologies, including ActiveX, Java, JavaScript and cookies
  42. 42. HTTP REQUEST HTTP request contains: (For example: GET /Scripts/Global/nph-cc?cc=at HTTP/1.0Here ) 1.A request line, which consists of •An HTTP command, or method •The document path •The HTTP version number. •the method is GET •the document path is /Scripts/Global/nph-cc?cc=at •the HTTP version is HTTP/1.0 2.An optional header section: which informs the server of the configuration of the Web browser and the document formats it will accept. For example: Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */* Accept-Encoding: gzip Accept-Language: en Accept-Charset: iso-8859-1,*,utf-8 The header section ends with a blank line. 3.An optional entity body. POST is one method that uses the entity body, in this case it is used to convey HTML form data. Each line is separated from the next by a carriage return line feed (CRLF). HTTP responses (For example: HTTP/1.0 200 OK ) An HTTP response contains: 1.A status line, which consists of •The HTTP version number. •A status code, indicating whether the request was successful. •A human-readable text that describes the status code 2.An optional header section, which informs the browser of the configuration of the Web server and provides information about the requested document. For example: Date: Fri, 05 Jan 1999 14:23:02 GMT Server: NCSA/1.5 Content-type: text/html The header section ends with a blank line. 3.An optional entity body. The requested document in HTML format is returned in the entity body.
  43. 43. AJAX • Asynchronous JavaScript and XML • Responsive web application (asynchronies communication , not post pack) • ASP.NET MVC 4 is a modern web framework (should support Ajax) • AJAX supported by jQuery JavaScript library features
  44. 44. JQUERY • The most famous open source JavaScript library. • jQuery excels at finding, traversing, and manipulating HTML elements inside DOM. • Write less do more. Support all the browsers. • Supported an integrated with MVC scaffolding templates. • Easy to get the last updates via internet using NuGet. • Found element & write-up event handlers , animate the element, Ajax interaction. • Access the DOM element by (class name, attributes values-id, position,…). • jQuery includes everything you need to send asynchronous requests back to your web server. • Support Send asynchronous requests back to Web server . • POST requests or GET requests. • Support sending and receive XML data.
  45. 45. COMMON SELECTORS jQuery selector syntax derives from CSS 3.0 selectors,
  46. 46. JQUERY METHOD :
  47. 47. WEB FORMS • Without the Internet would be a read-only repository of boring documentation. • Contains Input elements (text box, button, check box, etc.) • The browser takes the input names and values and puts them in the query string. • Web applications generally use GET requests for reads and POST requests for writes (which typically include updates, creates, and deletes).
  48. 48. WEB API • In 2011, a reorganization of teams brought the ASP.NET MVC and WCF Web API teams together WCF WEP API MVC • Scott Guthrie, who was very interested in merging the two efforts so that customers would be able to easily transition their ASP.NET knowledge into writing web APIs. • The teams set out to combine the best ideas of both platforms, and the result ASP.NET Web API — was born, and shipped alongside ASP.NET MVC 4. Web API
  49. 49. WHY ? • Transport data between servers and other devices ( pc, tablet , mobile) • Simplifies web services by implementing REST. • Ideal for JSON , transferring Model to Json and vice versa . • Works for MVC & web Forms
  50. 50. WEB API # ASP Net MVC Web API 1 System.Web.MVC System.Web.Http 2 Accepting form data and generating HTML Accepting ( raw objects) and convert into structured data format like JSON and XML. Using the Content Negotiation feature. 3 Dispatch to actions by name Dispatch to actions by HTTP verb 4 Return raw object & views Returen raw Object Value or Sequence of Values 5 Request is HttpRequestBase from System.Web Request is HttpRequestMessage from System.Net.Http 6 Response is HttpResponseMessage 7 API controllers are expected to return a response object of type HttpResponseMessage. 9
  52. 52. DRUNDAL • View & View model composition . Keep our code modular (build our code inside App folder and durandal will locate it for us) • Load the requested module dynamically as per needed • App Life Cycle events management . • Async programming with Promises • Convention based .
  56. 56. KNOCKOUT
  57. 57. SPA , BIND DATA
  58. 58. FIRST HOT TOWEL SPA PROJECT • Create Empty Web Application • Entity Framework 5.0 . • Entity Framework. SQL Server Compact . • Microsoft Asp.Net Web API (has other dependencies) . • Microsoft Asp.Net Web Optimization . • Microsoft Asp.Net Razor 2 • In PM console Install-package jquery • In PM console Install-package Modernizer • In PM console Install-package Bootstrap • In PM console Install-package FontAwesome • In PM console Install-package durandal • In PM console Install-package toaster