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

Post on 18-Dec-2014

50.588 views 0 download

Tags:

description

Build web sites using single page application technology

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

ASP.NET MVC , SPA , DURANDAL HOTTOWEL, WEB API

PROFESSIONAL ASP.NET MVC BOOK : BY JOHN GALLOWAY.DIFFERENT ARTICLES FROM INTERNET , PLURAL SIGHT LESSONS BY JOHN PAPA .

References:

By Walid Ward, Senior .Net Developer

walidward@gmail.com

INDEX

Introduction

MVC Framework & Definition

Model & View Model

Scaffolding

Routes & Config Setting

Action Verbs

Action Results

HTML Encoding with Razor

Layouts

Render (Page, Section, Body )

Partial View

Folder Structuring (Area)

HTML Helper

Data Annotation

Library Example (continue )

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-View-Editor 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.

ASP.NET FRAMEWORK

MVC FRAMEWORK

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.

RELEASE HISTORY

Date  Version  

10 Dec 07  ASP.NET MVC CTP  13 Mar 09   ASP.NET MVC 1.0 16 Dec 09  ASP.NET MVC 2 RC04 Feb 10  ASP.NET MVC 2 RC 210 Mar 10  ASP.NET MVC 2  06 Oct 10 ASP.NET MVC 3 Beta  09 Nov 10 ASP.NET MVC 3 RC10 Dec 10 ASP.NET MVC 3 RC 213 Jan 11 ASP.NET MVC 320 Sep 11   ASP.NET MVC 4 Developer Preview 15 Feb 12 ASP.NET MVC 4 Beta31 May 12   ASP.NET MVC 4 RC15 Aug 12  ASP.NET MVC 4 

HISTORY OVERVIEWMVC1- 2009

• ScottGu started first sketch out 2007 (Scalene)

• 9 releases, 3 years.

MVC2-2010 (.NET Framework 3.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)

MVC3-2011 (.NET Framework 4.0)

• Used jQuery validation• JSON• dependency resolver

(ease the dependency injection for decoupling the application)

• Open source libraries (JQuery, Modernizer)

MVC4-2012(.NET Framework 4.5)

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

CONTROLLERS

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.

ROUTES

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.

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

BUNDLING AND MINIFICATION

ACTIONS

• Action Filters (Global filter like Error msg)

• Action Results (table here)

• Action Selectors (Verbs, Names)

ACTION RESULTSAction Result Helper Method Description

ViewResult View Renders a view as a Web page.

PartialViewResult PartialView

Renders a partial view, which defines a section of a view that can be rendered inside another view.

RedirectResult RedirectRedirects to another action method by using its URL.

RedirectToRouteResult RedirectToActionRedirects to another action method.

ContentResult Content Returns a user-defined content type.

JsonResult Json Returns a serialized JSON object.

JavaScriptResult JavaScriptReturns a script that can be executed on the client.

FileResult FileReturns binary output to write to the response.

EmptyResult (None)

Represents a return value that is used if the action method must return a null result (void).

VIEWS

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

LAYOUT

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";}

• 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>

HTML ENCODING

RENDER BODY

http://www.codeproject.com/Articles/383145/RenderBody-RenderPage-and-RenderSection-methods-in

RENDER SECTION

http://www.codeproject.com/Articles/383145/RenderBody-RenderPage-and-RenderSection-methods-in

RENDER PAGE

http://www.codeproject.com/Articles/383145/RenderBody-RenderPage-and-RenderSection-methods-in

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.

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.

RAZOR VIEW & WEB FORMS VIEW

//Space is not a valid identifier so next will be markup

VIEW MODEL

public class ShoppingCartViewModel { public IEnumerable<Product> Products { get; set; } public decimal CartTotal { get; set; } public string Message { get; set; } }

View Model: Flexible to display different information and doesn’t map directly to a domain 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; }

MODEL

DATA ACCESS IN EF

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.

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

HTML HELPERS

• 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.

@Html.ActionLink("Delete", "Delete", new{ id=item.id })

HTML HELPERS EXAMPLES

Available HTML Helpers

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.

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,

DATA ANNOTATIONS

JSON & SERIALIZATION

• "JSON" (JavaScript Object Notation) is a lightweight text-based open standard designed for human-readable 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

AJAX & MVC

AUTHENTICATION & AUTHORIZATION

• Authenticate using Simple Membership Provider

• Authorize /allow anonymous

• Authorize [users (“”)]

• Authorize [Roles(“”)]

• HTTPS

• Cross Site Request Forgery

• OAuth & OpenID

SIMPLE MEMBERSHIP PROVIDER

• ASP.NET 2.0 back in 2005

• This schema Universal Providers. (View, SPS, Tables)

SIMPLE MEMBERSHIP PROVIDER

CONFIGURE IIS EXPERSS (APPLICATION HOST.CONFIG) FOR WEB API

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

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:4.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.

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

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.

COMMON SELECTORS

jQuery selector syntax derives from CSS 3.0 selectors,

JQUERY METHOD :

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

WEB API

• In 2011, a reorganization of teams brought the ASP.NET MVC and WCF Web API teams together

• 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.

WCF WEP API

Asp.net MVC

Asp.net Web API

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

# ASP Net MVC Asp.net 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 ContentNegotiation 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

WEB API

WEB API CONVENTIONS

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 .

SPA COMPONENTS

SERVER PACKAGES

CLIENT PACKAGES

KNOCKOUT

SPA , BIND DATA

FIRST HOT TOWEL SPA PROJECT

• Create Empty Asp.net 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