1 / 61

Introduction to .NET and ASP.NET Framework

Introduction to .NET and ASP.NET Framework. Politecnico di Torino December 4 th , 2007. Mauro Minella mauro.minella@microsoft.com http://blogs.msdn.com/mauromi Microsoft Certified Solutions Developer Microsoft Certified Systems Engineer + Internet. Agenda. .NET Framework: architecture

cedric
Download Presentation

Introduction to .NET and ASP.NET Framework

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to .NET and ASP.NET Framework Politecnico di Torino December 4th , 2007 Mauro Minella mauro.minella@microsoft.com http://blogs.msdn.com/mauromi Microsoft Certified Solutions Developer Microsoft Certified Systems Engineer + Internet

  2. Agenda • .NET Framework: architecture • WEB extension: ASP.NET 2.0 • DevelopmentTools: Visual Studio 2008 • Membership: roles and controls • Localization, Master Pages, Skins and Themes • AJAX Demo’s/Examples

  3. ASP.NET From HTML to ASP.NET ASP pages CGI apps ISAPI filters HTML

  4. .NET and ASP.NET architecture Win32 SDK .NET Framework ASP.NET Unmanaged Applications Windows Managed Applications (Win Forms, Console, Services, ...) WEB Managed Applications (WEB Forms / WEB Services) Base Class Library Base Class Library Common Language Runtime Common Language Runtime WEB Server (IIS) Sistema Operativo (Windows) CLR interoperability, security, garbage collection, versioning, ... Class Library GUI, collections, threads, networking, reflection, XML, ... WEB Forms Web GUI (object-oriented, event-based, browser-independent) WEB Services Distributed services over RPC (SOAP, HTTP)

  5. .NET FRAMEWORK PROGRAMMING C# • Binarycompatibilityforalllanguages • Isolated code (onlytoallowedmemeryaccess) • Codice type-safe (no buffer overrun) • Just-in-time compiler if (a > b) max = a; else max = b; C# C++ VB J# ... IL IL_0004: ldloc.0 IL_0005: ldloc.1 IL_0006: ble.s IL_000c IL_0008: ldloc.0 IL_0009: stloc.2 IL_000a: br.s IL_000e IL_000c: ldloc.1 IL_000d: stloc.2 compiler compiler compiler compiler compiler IL code (+ metadata) loader Intel code mov ebx,[-4] mov edx,[-8] cmp ebx,edx jle 17 mov ebx,[-4] mov [-12],ebx ... verifier JIT compiler machine code

  6. Indipendence from platform and code langauge • .NET is a CLI implementation • Common Language Infrastructure • CLI is an ECMA standard, defined with the C# • ECMA-334, ECMA-335 • Existing CLI implementations: • SSCLI (Microsoft per Windows, FreeBSD and Macintosh) • Mono (for Linux) • DotGNU • Intel OCL (Open CLI Library) • …

  7. ViewState • Keeps the state at Page level • It’s a name/value dictionary • It’s a Hidden field of the page • Can also be used programmatically • ViewState.Add(“NomeUtente”, “Mauro”) • Can be disabled at page level • <%@ Page ... EnableViewState="false"%> • Be aware: some controls might not work any more!

  8. PostBack protected void Page_Load(..) { if(Page.IsPostBack == false) { // It’s the first access // Let’s open the DB connection! } } • Tipicalusage: code optimiza-tionforaccessinghicost(like DB) resources just once • IsPostBackpropertyistruesincesecondtime on • Page_Loadhappenswhen • Button Submit • Server-sidecontrolswithenabledAutoPostBack • Can beusedtoinitializecontrols

  9. DEMOLet’s buildour first ASP.NETapplication! • Development Tool: Microsoft Notepad • A .aspx page tipically has 3 sections: • Page directives: environment setup, controls registration, assemblies load if not in GAC, namespace registration, code language declaration • Code section: server side business logic; can be in-lin or separated • Page layout: page scheleton, including server side controls, text, HTM tags

  10. Let’s build our first application (cont.) • Create anempty.ASPX file • Preparescheleton • Addcontrols • Makecontrols server-side • ASP.NETruntimeparses the page and createsinstancesof .NET frameworkclassesforeverycontrolwhererunat = “server” • Add: Click evenhandler: OnServerClick="MakeItUpper" ChosenLanguage: <% @Page Language="C#"%> C#, VB o C++ code (whichisnot sent to the client!)

  11. Introduction a Visual Studio / VWD • Free download from Microsoft website http://www.microsoft.com/italy/msdn/prodotti/vs2005/editions/download/wdd.mspx • Let’s explore the IDE • Let’s create a Web Site • Controls and base features • Server-side controls whose output depends on client • Diagnostics page life cycle

  12. Controls • Controlli HTML: • Standard HTML • <a >..., <label>... • Server-side controls • Generated HTML depends on browser • They are tens!! Let’s look at some of them…

  13. Validators • Server-sidecontrolsto validate input • Theycheckif the browser supports client-side validation and in this case sendJScripttoit • RequiredFieldValidator • ValidatorSummary • RangeValidator • RegularExpressionValidator • CompareValidator • CustomValidator (can alsobeusedtosend a JS function back)

  14. Demo • Validators

  15. Debugging (Server-side) • Enabledwithin the web.config file

  16. Debugging (Javascript) • A few more steps: • Use browser settings: Tools – Internet Options - Advanced • You can rundebuggerfrom IE and then set a breakpoint on javascript code • Or fromVisual Studio “attachtoprocess” to IE process • Notsupported on “Express” versions • “Trick”: “debugger;” instruciton in the JS code • Remembernottoleave in production! • server-side vs. client-side: • OnServerClick OnClick (you can haveboth!) • <script runat="server">  <script language="javascript" type="text/javascript"> • Linguaggio vb.net/c#/c++/j#/f#/cobol.net/…  javascript syntax • Il postbackhappensonlyif the functionreturns TRUE

  17. Pagina Life Cycle (hi level view) • PreInit: use it to: • Check IsPostBack property • Create dynamic controls • Apply themes and master pages dynamically • Read/write user profiles • Init: read and initialize control properties • Load: read and update control properties • PreRender: change page contents • UnLoad: fianal closing tasks

  18. Tracing <trace enabled="true" pageOutput="false" /> <%@ Page Language="C#" ... Trace="true"%> • Can be enabled in the web.config or on page level • pageOutput enables output to page or by using trace In you need to write a trace information: Trace.Write (categoria, messaggio, eccezione); Trace.Warn (categoria, messaggio, eccezione); Trace.Write (messaggio); ...

  19. Trace example

  20. Membership, rolesand log-in controls Authentication and Permissions

  21. Authentication: scenarios • Identify who is accessing our web site • Two tipical scenarios: • Intranet: can leverage integrated server control access • e.g. IIS uses Integrated Authentication • Tipically, users are hosted within the Active Directory • Users do not need to provide credentials explicitly • Internet: • can leverage a database to store users and permissions • Users must provide username and password

  22. Authentication: anextensibilemodel Un modello estendibile Controls Login LoginStatus LoginView Other Login Controls Membership API Membership MembershipUser Membership Providers AspNetSqlMembershipProvider Other Membership Providers Membership Data SQL Server Other Data Stores

  23. Log-in controls • Interact with a provider for membership management • Login: allows to do a login providing username + pwd • LoginView: allows different content for authenticated and not-authenticated users • PasswordRecovery: leverage the secret question to regenerate password • LoginStatus: to check is the user is logged or not • LoginName: provides the current logged user • ChangePassword: to change password • CreateUserWizard: to save time in writing lot of code!

  24. Using Web Site Administrationtool (WSA) • Parameters are stored in the web.config file • Authentication type • SMTP server, tracing, debugging, errors, ... • Users handler • Create, Delete, Update ... • Roles and access rules management • Folder by folder • Provider configuration to access database • Can be used through a 7-steps Wizard

  25. WSA: Security section

  26. Membership API by code MembershipCreateStatus ms;MembershipUser user=Membership.CreateUser(    “mauro",    “Password1!",    “mauro.minella@microsoft.com",    “Colore preferito?",    “Blu",     true,out ms); if (user==null)  Label1.Text = "Non è possibile creare un utente";else  Label1.Text = "Utente creato"; if (Membership.ValidateUser(username.Text, password.Text))  FormsAuthentication.RedirectFromLoginPage(username.Text, false);else  Label1.Text = "Username e password non corretti";

  27. Demo • Web Site Creation: • Leverage integrated controls • Login, LoginName and LoginStatus controls • Leverage WSA to create users and groups • Leverage IIS Manager to configure WEB server

  28. Localizzazione, Temi, Skine Pagine Master Come creare una grafica del sito omogenea e consistente

  29. Localizzazione • Usa file di risorse selezionati a run-time da ASP.NET • Due cartelle: • App_LocalResources:i file contengono risorse per una singola pagina • App_GlobalResources: i file possono essere letti da qualsiasi pagina del sito Web • Indicazione della localizzazione nelle direttive di pagina • UICulture="auto" • Naming convention per la pagina: • linguaggio neutrale: pagina.aspx.resx • linguaggio specifico (es. italiano): pagina.aspx.it.resx • Naming convention per le risorse: • meta:resourcekey="ResourceXYZ" nelle proprietà controllo (tag HTML) • Name=ResourceXYZ.<Proprietà> e Value=Valore nei file <page>.resx e <page>.<language>.resx • Impostare nel browser del client lingua e priorità • Tipi di risorse: stringhe, immagini, audio, file, icone, altro DEMO

  30. Temi (CSS e Skin) • Definiscono la grafica della pagina • Sono un superset dei CSS (Cascading Style Sheets) • Sono disponibili solo in ASP.NET 2.0 • Assegnano un insieme di stili e attributi visuali agli elementi personalizzabili del sito • Sono strettamente legati ai temi di XP: impostare un tema è rapido e facile come impostare una proprietà • Si applicano controlli individuali, pagine o siti

  31. Creazione di CSS • Si usa un tool integrato nell’ ambiente, che si attiva dal menu “Stili” dopo avere aggiunto un file CSS

  32. File di Skin - esempio • Creo una cartella per ogni stile sotto App_Themes • Creo un file per ogni skin nella cartella creata sopra • In fondo ad ogni file .skin: <asp:label runat="server" backColor= "Green" SkinID="lblTitolo"/> • Definisco uno SkinID altrimenti lo skin viene applicato a tutti i controlli di quel tipo, e lo seleziono nelle proprietà • Imposto lo skin nella direttiva di pagina StylesheetTheme • Seleziono lo SkinID per il controllo • DEMO

  33. Pagine Master Content Page

  34. Pagine master • Le pagine master definiscono la struttura e i placeholder (<asp:ContentPlaceHolder>) • Le pagine “figlie” referenziano la master e creano il contenuto (<asp:Content>) • Le pagine master sono trasparenti all’utente, il quale invoca solo le pagine content Site.master default.aspx http://.../default.aspx <%@ Master %> <asp:ContentPlaceHolder ID="Main" RunAt="server" /> <%@ Page MasterPage- File=“MasterPage.master" %> <asp:Content ContentPlaceHolderID= "Main" RunAt="server" /> </asp:Content>

  35. La proprietà Page.Master • Ottiene un riferimento alla pagina master dalla pagina figlia • Usata per avere accesso programmatico al contenuto della pagina master • Usare FindControl per weak typing • Usere public property nella master page per strong typing

  36. ASP.NET AJAXConcetti e fondamenti

  37. AJAX • Che cos’è e come funziona • Da dove partire • AJAX ASP.NET Extensions 1.0 • XMLHttpRequest : la base • AJAX Control Toolkit • AJAX Futures CTP

  38. Cos’è AJAX? • AJAX = Asynchronous JavaScript and XML • Unanuovatecnica per lo sviluppodiapplicazioni web • Risolvemoltideiproblemicheaffliggono le moderneapplicazioni web • Eliminail “flickering” dellepagine • UsaXmlHttpRequestper recuperaredatidal server in modoasincrono e il JavaScript per aggiornareilcontenutodellapagina • Nasce con OWA (Outlook Web Access) • Tecnologiaabilitante per il Web 2.0

  39. AJAX: Come funziona? Il browser invia una richiesta HTTP al server 1 Browser Web Server Il server restituisce il contenuto. Il browser ne fa il rendereing 2 IL browser invia una richiesta asincrona XML-HTTP al server. La UI non si blocca e non ha effetti di flickering 3 La richiesta XML-HTTP si conclude. Il JavaScript aggiorna la porzione della pagina interessata 4

  40. XmlHttpRequest • Introdotto nel 1999 con Internet Explorer 5 • Oggetto ActiveX per le chiamate di callback dal Web server • In IE 7 fa parte del modello ad oggetti del browser • Successivamente adottato da Firefox, Safari e altri • In via di standardizzazione dal W3C • http://www.w3.org/TR/XMLHttpRequest/ • Supportatato oggi da circa il 99% dei browser • Circa 85%-95% hanno abilitato il JavaScript

  41. Instanziare XmlHttpRequest varxhr = null; try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { if (typeofXMLHttpRequest != "undefined") { xhr = new XMLHttpRequest(); } }

  42. Verifica supporto AJAX per il client xhr.open ('GET', 'AjaxDemo.aspx?mode=ajax', true); xhr.onreadystatechange = checkForCompletion; xhr.send (); ... function checkForCompletion() { if (xhr.readyState == 4 && xhr.status == 200) { window.alert(xhr.responseText); } }

  43. Che cos’è Microsoft ASP.NET AJAX ? Un FRAMEWORK per realizzare applicazioni WEB, interattive e dalla ricca interfaccia utente • Facilita lo sviluppodiapplicazioni AJAX • Estende e completa ASP.NET 2.0 • Anche se puòessereusato con PHP • Multi-browser • Estendibile

  44. Microsoft AJAX: icomponenti base ASP.NET 2.0 AJAX Futures CTPs ASP.NET AJAX Toolkit ASP.NET 2.0 AJAX Extensions Sviluppato con la community Nuove funzionalità Server Side Client Side Microsoft AJAX Library • Supporto Microsoft standard per le ASP.NET 2.0 AJAX Extension • Supporto della comunity per le Futures CTPs ed il Toolkit.

  45. AJAX: da dove partire

  46. Componenti essenziali di AJAX ASP.NET • Contengono: • Template AJAX per VS/WD 2005 • Controlli lato server • Ajax Library (JavaScript lato client) • Progetto share-source community • Esempi già pronti • SDK per la creazione di nuovi controlli • Richiede ASP.NET Extensions • - Estendono la piattaforma core • - Richiedono le ASP.NET 2.0 AJAX Extensions 1.0 • - Aggiungonofunzionalità come • - Drag-and-Drop • - XML Script • - etc • Possono essere utilizzate anche con server non MS • Fanno parte di ASP.NET Extensions

  47. Microsoft AJAX Library • La parte client di ASP.NET 2.0 AJAX • Tipicamente installata in “%ProgramFiles%\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\v1.0.61025\MicrosoftAjaxLibrary” • Indipendente dal browser e dalla piattaforma • Internet Explorer, Firefox, Mozilla, Safari, etc. • Si astrae dalla piattaforma sottostante • Un JavaScript “arricchito” • Namespaces, classi, interface, ereditarietà, etc. • Un sistema dei tipi • File *.js scaricati una sola volta sul client

  48. ASP.NET AJAX 2.0 Extensions UpdatePanel • È il controllo ASP.NET AJAX più importante • Consente di trasformare facilmente una applicazione ASP.NET 2.0 in un’applicazione AJAX • Permette di fare il rendering di parte della pagina • Converte postbacks in chiamate asincrone • Aggiorna parte della pagina web con il risultato • Non si scrive JavaScript

  49. Passo 1Aggiungere lo ScriptManager Aggiungere ad una pogina aspx: <asp:ScriptManager ID="MyScriptManager" Runat="server" /> Lo ScriptManager genera: <script src="/.../WebResource.axd?d=iQ15p6LHcT2T5QE..." type="text/javascript"></script> Riferimento allo script .js da scaricare

More Related