Vous êtes sur la page 1sur 70

Chapitre 2

Introduction au Framework .NET

INSAT 2022 – GL3


.NET ?

• C’est un framework, une plate-forme informatique pour


développement d'applications
• Propose une approche unifiée pour la conception
d'applications Web, Mobile, Serveur et Windows.
• Une plate-forme de déploiement et d’exécution
• Code stocké et exécuté localement, exécuté localement
mais distribué sur Internet ou exécuté à distance
• Framework .NET : Gratuit & intégré à Windows
Versions
Livré avec
Version CLR Sortie
Visual Studio

1.0 1.0 13/02/2002 .NET 2002

1.1 1.1 24/04/2003 .NET 2003

2.0 07/11/2005 2005

3.0 2.0 06/11/2006

3.5 3.5 19/11/2007 2008

4.0 12/04/2010 2010

4.5 15/08/2012 2012

4 4.5.1 4.0 17/10/2013 2013

4.6 20/07/2015 2015

4.7 05/04/2017 2017


Architecture
Architecture
Les langages

• Grâce au CLR, la plate-forme .NET est indépendante de tout


langage de programmation et supporte nativement un
grand nombre de langages de programmation

• Ada, • C++, • Oz,


• APL, • Cobol, • Pascal,
• C#, • Eiffel, • Perl,
• C • Fortran, • Python,
• Mercury, • Haskell, • Scheme,
• Oberon, • ML, • SmallTalk,
• Objective Caml, • J#, • Visual Basic
Les langages

• Les langages génèrent un langage intermédiaire (MSIL)

• MSIL est non exécutable et indépendant de la plateforme

• Le Microsoft Intermediate Language est un langage bas


niveau qui résulte de la compilation d'un programme .NET.

• C'est ce langage qui sera compris et compilé en code natif par


le Common Language Runtime (CLR) lors de l'exécution.
De la programmation à l’exécution
MSIL, un langage ?
Les types dans .NET

• Vérifiés par CLR, par Common Type System (CTS)


• CTS définit les types de données que le Runtime .NET
comprend et que les applications .NET peuvent utiliser.
• Les types doivent être implémentés par les langages
• Les langages définissent des alias
• Exemple: La table suivante
• Un programme qui utilise des types de la CLS peut interagir
avec un autre programme .NET écrit dans un autre langage.
• Exemple : une classe C# peut hériter d'une classe VB .NET
Les types dans .NET
.NET Assembly

• Un assembly .NET est une collection de types et de


ressources qui représente une unité logique de
fonctionnalités.
• Cela peut être une dll ou bien un exécutable (Jar de Java).
.NET Assemblies
Introduction to Web Based
Applications
Introducing Web Applications
Web Page Static web page
• This type of web page consists of
HTML code typed directly into text
or a web page editor
Static Dynamic • It is saved as an .htm or .html
file
• The content (text, images, hyperlinks, and so on) and
appearance of a static web page is always the same.

• These web pages do not utilize any database or any


other technology that dynamically builds up pages or
content at runtime based on their visitors input.
8
How Are Static Web Pages Served ?
WEB SERVER
3. Web Server locates
1. Author
.html file
writes
HTML

4. HTML stream( from the


.html page) returned to
the browser

2. Client requests
the web page
5. Browser processes
HTML and displays
page

CLIENT
9
Dynamic web page
• Dynamic Web sites provide its visitors to modify the content of
the web page based on their input.
• They utilize databases and other mechanisms that enable to
– identify their visitors
– present them with customized greeting messages
– restructure the content according to user input etc..
• Examples:
– Online shopping stores,
– search engines
– email
– chat, community portals etc.

10
Dynamic web page
• Dynamic Web sites make use of “server-side
technology”.
• Server-side technologies add an extra layer to the
static web page that enables the Web Server to
generate HTML on the fly.
• The web server will first
– interpret the server-side code present in web
pages,
– generate the appropriate HTML and then
– send the response to the web browser.
11
How Are Dynamic Web Pages Served?
3. Web Server collects the contents
(code + HTML) of the web page
WEB SERVER and parses the contents to
produce HTML.
2. The Web Server
searches for the
requested page 4. The HTML stream is
sent back to the
requesting browser

1. The Web browser 5. Browser processes


sends a request HTML and displays
page

CLIENT
12
Introduction to ASP.NET
Introduction to ASP.NET
 ASP.NET is part of the Microsoft .NET framework
 ASP.NET is an effective and flexible technology for
creating interactive and dynamic web
pages.
 It is a convergence of two major Microsoft technologies:
– Active Server Pages (ASP)
• Active Server Pages is Microsoft’s server side scripting
technology for building dynamic web pages.
– .NET Framework
• The .NET Framework is a suite of technologies designed by
Microsoft where program development takes place.
14
Introduction to ASP.NET
 It is built on .NET Common Language Runtime
 ASP.NET :
 Provides better user authentication
 Has better language support.
 Has a large set of new controls (web controls)
 Uses compiled code, which increases the performance of the
applications
 It is programmable using any of the .NET languages
(VB.NET, C#, VJ# virtual J# etc).
 The ASP.NET pages are saved with the .aspx
extension. 15
Working of an ASP.NET Application
To execute an ASP.NET file, the
following steps are followed: ASP.NET
1. A web browser sends a Script
request for an ASP.NET file to Engine
the web server by using a
URL.

2. The web server receives the


request and retrieves the WEB
appropriate ASP.NET file from SERVER
the disk or memory.

3. The web server forwards the


file to the ASP.NET script CLIENT
engine for processing.
16
Working of an ASP.NET Application

4. The ASP.NET script engine reads


ASP.NET
the file from top to bottom and
executes it.
Script
Engine
5. The processed ASP.NET file is
generated as an HTML
document and the ASP.NET
script engine sends the HTML
WEB
page to the Web server.
SERVER

6. The Web server then sends the


HTML code to the client which
interprets the output and CLIENT
displays it.
17
ASP.NET MVC
ASP.NET MVC

ASP.Net avant …

4
ASP.NET MVC

No real role responsibility…

Master Page
Control Control
UI
Control Page
Control Presentation Logic
Business Logic
Control Control Data Access

Control Control

Who does what?


How and when?

5
ASP.NET MVC

So how does ASP.NET MVC


differ?

7
ASP.NET MVC

Positionnement

Framework .NET

ASP.NET

Présentation
Dynamic
WebForms MVC Ajax WebPages
Data

8
ASP.NET MVC

Goals of ASP.NET MVC Framework

◼ Enable clean separation of concerns

◼ Flexible, clean url schemes (think SEO)

◼ Support existing ASP.NET runtime features

◼ Support static and dynamic languages

◼ Build on top of System.Web, not replace it.

9
ASP.NET MVC

What is ASP.NET?

ASP.NET WebForms

◼ HttpApplication ◼ Server Lifecycle

◼ HttpContext ◼ Postback

◼ HttpRequest ◼ ViewState

◼ HttpResponse

◼ HttpRuntime

◼ HttpUtility ASPX

◼ IHttpHandler ◼ MasterPages

◼ IHttpModule ◼ Themes, Skins

◼ General Templating
10
What is the ASP.NET MVC
ASP.NET MVC

Framework?
ASP.NET Mvc

◼ HttpApplication ◼ Routes

◼ HttpContext ◼ Controllers

◼ HttpRequest ◼ ViewData

◼ HttpResponse ◼ Filters

◼ HttpRuntime

◼ HttpUtility ASPX

◼ IHttpHandler ◼ MasterPages

◼ IHttpModule ◼ Themes, Skins

◼ General Templating
11
Architecture de ASP.NET MVC
ASP.NET MVC

Le Pattern MVC

http://www.dotnetcurry.com/aspnet-mvc/922/aspnet-mvc-pattern-tutorial-fundamentals

13
ASP.NET MVC

Le Pattern MVC
ASP.NET MVC

ASP.NET MVC Request


ASP.NET MVC

ASP.NET MVC Request


ASP.NET MVC

ASP.NET MVC Request


ASP.NET MVC

ASP.NET MVC Request

14
ASP.NET MVC

Historique de l’évolution de ASP.NET MVC

◼ ASP.NET MVC1
◼ Released on Mar 13, 2009
◼ Runs on .Net 3.5 and with Visual Studio 2008 & Visual Studio 2008 SP1
◼ MVC Pattern architecture with ASPX Engine
◼ Html Helpers/Ajax helpers/Routing/Unit Testing

◼ ASP.NET MVC2
◼ Released on Mar 10, 2010
◼ Runs on .Net 3.5, 4.0 and with Visual Studio 2008 & 2010
◼ Strongly typed HTML helpers means lambda expression based Html Helpers
◼ Templated Helpers/Support for Data Annotations Attribute
◼ Client-side validation/UI helpers with automatic scaffolding & customizable templates
◼ Attribute-based model validation on both client and server
◼ Overriding the HTTP Method Verb including GET, PUT, POST, and DELETE
◼ Areas for partitioning a large applications into modules

◼ ASP.NET MVC3
◼ Released on Jan 13, 2011
◼ Runs on .Net 4.0 and with Visual Studio 2010
◼ The Razor view engine
◼ Improved Support for Data Annotations/Dependency Resolver
◼ Partial-page output caching/Global Action Filters/Better JavaScript support with unobtrusive
JavaScript, jQuery Validation, and JSON binding
16
ASP.NET MVC

Historique de l’évolution de ASP.NET MVC

◼ ASP.NET MVC4
◼ Released on Aug 15, 2012
◼ Runs on .Net 4.0, 4.5 and with Visual Studio 2010SP1 & Visual Studio 2012
◼ ASP.NET Web API
◼ Enhancements to default project templates
◼ Mobile project template using jQuery Mobile
◼ Display Modes
◼ Task support for Asynchronous Controllers
◼ Bundling and minification
◼ Support for the Windows Azure SDK

◼ ASP.NET MVC5
◼ Released on 17 October 2013
◼ Runs on .Net 4.5, 4.5.1 and with Visual Studio 2013
◼ One Asp.Net
◼ Asp.Net Identity
◼ ASP.NET Scaffolding
◼ Authentication filters - run prior to authorization filters in the ASP.NET MVC pipeline
◼ Bootstrap in the MVC template
◼ ASP.NET Web API2
17
Mise en œuvre de ASP.NET
MVC
ASP.NET MVC

Default Structure

Static files (CSS, Images, etc.)

All controllers and actions

JavaScript files (jQuery, Modernizr, knockout, etc.)

View templates

_Layout.cshtml – master page (main template)

Application_Start() – The entry point of the application

Configuration file
19
19
ASP.NET MVC

The controller !

20
ASP.NET MVC

Now The View

21
ASP.NET MVC

Result

22
ASP.NET MVC

ASP.NET MVC Routing


◼ Mapping between patterns and a combination of
controller + action + parameters

◼ Routes are defined as a global list of routes

◼ System.Web.Routing.RouteTable.Routes
◼ In Global.asax in the Application_Start() there is
RoutesConfig.RegisterRoutes(RouteTable.Routes);

◼ RoutesConfig class is located in /App_Start/ in


internet applications template by default

23
ASP.NET MVC

Routing Examples

http://localhost/Products/ById/3

◼ Controller: Products
◼ Action: ById
◼ Id: 3

24
24
ASP.NET MVC

Route Constraints

◼ Constraints are rules on the URL segments


◼ All the constraints are regular expression compatible with class Regex
◼ Defined as one of the routes.MapRoute(…) parameters

25
25
ASP.NET MVC

Controllers

◼ The core component of the MVC pattern


◼ All the controllers should be available in a folder by name
Controllers
◼ Controller naming standard should be "nameController"
(convention)
◼ Routers instantiate controllers in every request
All requests are mapped to a specific action

◼ Every controller should inherit Controller class


Access to Request (context) and HttpContext

26
ASP.NET MVC

Actions

◼ Actions are the ultimate request destination


◼ Public controller methods
◼ Non-static
◼ No return value restrictions
◼ Actions typically return an ActionResult

27
27
ASP.NET MVC

Action Results

◼ Controller action response to a browser request


◼ Inherits from the base ActionResult class
◼ Different results types:

Name Framework Behavior Producing Method


ContentResult Returns a string literal Content

EmptyResult No response
FileContentResult Return the contents of a file File
FilePathResult
FileStreamResult
HttpUnauthorizedResult Returns an HTTP 403 status

JavaScriptResult Returns a script to execute JavaScript


JsonResult Returns data in JSON format Json

RedirectResult Redirects the client to a new URL Redirect / RedirectPermanent

RedirectToRouteResult Redirect to another action, or another RedirectToRoute /


controller’s action RedirectToAction
ViewResult Response is the responsibility of a view View / PartialView
PartialViewResult engine

28
28
ASP.NET MVC

Action Parameters

◼ ASP.NET MVC maps the data from the HTTP request to action
parameters in few ways:
◼ Routing engine can pass parameters to actions
◼ http://localhost/Users/NikolayIT

◼ Routing pattern: Users/{username}

◼ URL query string can contains parameters


◼ /Users/ByUsername?username=NikolayIT

◼ HTTP post data can also contain parameters

29
29
ASP.NET MVC

Action Selectors

◼ ActionName(string name)
◼ AcceptVerbs
◼ HttpPost
◼ HttpGet
◼ HttpDelete
◼ HttpOptions
◼ …
◼ NonAction
◼ RequireHttps
◼ ChildActionOnly – Only for Html.Action()

30
30
ASP.NET MVC

Action Filters

◼ Apply pre- and post-processing logic. Some requirements cut across logical
boundaries are called cross-cutting concerns. Examples include:
◼ Authorization
◼ Logging
◼ Caching

◼There are four different types of filters:


◼ Action filters run before and after the code in the action method
◼ Result filters run before and after a result is returned from an action method
◼ Authorization filters run before any other filter and before the code in the action method
◼ Exception filters run only if the action method or another filter throws an exception

Name Description
OutputCache Cache the output of a controller
ValidateInput(false) Turn off request validation and allow dangerous
input (html tags)

Authorize Restrict an action to authorized users or roles


ValidateAntiForgeryToken Helps prevent cross site request forgeries
HandleError Can specify a view to render in the event of an
unhandled exception

31
31
Le moteur de vue Razor
ASP.NET MVC

Views

◼ HTML templates of the application


◼ A lot of view engines available
◼ View engines execute code and provide
HTML
◼ Provide a lot of helpers to easily generate
HTML
◼ The most popular is Razor and WebForms
◼ We can pass data to views through ViewBag,
ViewData and Model (strongly-typed views)
◼ Views support master pages (layout views)
◼ Other views can be rendered (partial views)

34
34
ASP.NET MVC

Razor

◼ Template markup syntax


◼ Simple-syntax view engine
◼ Based on the C# programming language
◼ Enables the programmer to use an HTML construction workflow
◼ Code-focused templating approach, with minimal transition between HTML
and code
◼ Razor syntax starts code blocks with a @ character and does not require
explicit closing of the code-block

35
35
ASP.NET MVC

Razor Design Goals

◼ Compact, Expressive, and Fluid


◼ Smart enough to differ HTML from code
Template
◼ Easy to Learn
◼ Is not a new language
◼ Works with any Text Editor
Data
◼ Has great Intellisense
◼ Built in Visual Studio
◼ Unit Testable
◼ Without requiring a controller or web-server
Generated
Output

36
36
ASP.NET MVC

Pass Data to a View

◼ With ViewBag (dynamic type):


◼ Action: ViewBag.Message = "Hello World!";
◼ View: @ViewBag.Message
◼ Strongly-typed views:
◼ Action: return View(model);
◼ View: @model ModelDataType;
◼ With ViewData (dictionary)
◼ ViewData["message"] = "Hello World!";
◼ View: @ViewData["message"]

37
37
ASP.NET MVC

How it works?

ByUsername.cshtml HTML
Output

Generated
Template Data
Output
UsersController.cs

UserModel.cs

38
38
ASP.NET MVC

Razor Syntax

◼ @ – For values (HTML encoded)

<p>
Current time is: !!!
Not HTML encoded value:
</p>

◼ @{ … } – For code blocks (keep the view simple!)

<p>Product " " has been added in your shopping cart</p>

39
39
ASP.NET MVC

Razor Syntax (2)

◼ If, else, for, foreach, etc. C# statements


◼ HTML markup lines can be included at any part
◼ @: – For plain text line to be rendered

<div class="products-list">

<p>Sorry, no products found!</p>

@:List of the products found:

<b> , </b>

</div>

40
40
ASP.NET MVC

Razor Syntax (3)


◼ Comments

◼ What about "@" and emails?

<p>
This is the sign that separates email names from domains: @@<br />
And this is how smart Razor is: spam_me@gmail.com
</p>

41
41
ASP.NET MVC

Razor Syntax (4)

◼ @(…) – Explicit code expression

<p>
Current rating(0-10): @Model.Rating / 10.0 @* 6 / 10.0 *@
Current rating(0-1): @(Model.Rating / 10.0) @* 0.6 *@
spam_me@Model.Rating @* spam_me@Model.Rating *@
spam_me@(Model.Rating) @* spam_me6 *@
</p>

◼ @using – for including namespace into view


◼ @model – for defining the model for the view

<p> </p>

42
42
ASP.NET MVC

Layout

◼ Define a common site template


◼ Similar to ASP.NET master pages (but better!)
◼ Razor view engine renders content inside-out
◼ First view is redered, then layout
◼ @RenderBody() –
indicate where we want
the views based on this
layout to “fill in” their
core content at that
location in the HTML

43
43
ASP.NET MVC

View Helpers

◼ Each view inherits WebViewPage


◼ ViewPage has a property named Html
◼ Html property has methods that return
string and can be used to generate
HTML
◼ Create inputs
◼ Create links
◼ Create forms
◼ Other helper properties are also
available
◼ Ajax, Url, custom helpers

46
46
ASP.NET MVC

HTML Helpers

Method Type Description


BeginForm, Form Returns an internal object that represents an HTML form that the
BeginRouteForm system uses to render the <form> tag
EndForm Form A void method, closes the pending </form> tag
CheckBox, CheckBoxFor Input Returns the HTML string for a check box input element
Hidden, HiddenFor Input Returns the HTML string for a hidden input element
Password, PasswordFor Input Returns the HTML string for a password input element
RadioButton, Input Returns the HTML string for a radio button input element
RadioButtonFor
TextBox, TextBoxFor Input Returns the HTML string for a text input element
Label, LabelFor Label Returns the HTML string for an HTML label element
ActionLink, RouteLink Link Returns the HTML string for an HTML link
DropDownList, List Returns the HTML string for a drop-down list
DropDownListFor
ListBox, ListBoxFor List Returns the HTML string for a list box
TextArea, TextAreaFor TextArea Returns the HTML string for a text area
Partial Partial Returns the HTML string incorporated in the specified user control
RenderPartial Partial Writes the HTML string incorporated in the specified user control to
the
output stream
ValidationMessage, Validation Returns the HTML string for a validation message
ValidationMessageFor
ValidationSummary Validation Returns the HTML string for a validation summary message
47
47
ASP.NET MVC

ASP.NET MVC 5 Application Lifecycle

50
ASP.NET MVC

ASP.NET MVC 5 Application Lifecycle

51

Vous aimerez peut-être aussi