1 / 46

ASP.NET MVC Framework

ASP.NET MVC Framework. Simone Chiaretta Solution Developer, Avanade http://codeclimber.net.nz. 24 Ottobre 2008. Agenda. Storia degli strumenti Microsoft per lo sviluppo Web Introduzione ad ASP.NET MVC Pattern MVC ASP.NET MVC nel dettaglio Testing ASP.NET MVC Futuro di ASP.NET MVC.

Télécharger la présentation

ASP.NET MVC 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. ASP.NET MVC Framework Simone ChiarettaSolution Developer, Avanade http://codeclimber.net.nz 24 Ottobre 2008

  2. Agenda • Storiadeglistrumenti Microsoft per lo sviluppo Web • Introduzione ad ASP.NET MVC • Pattern MVC • ASP.NET MVC neldettaglio • Testing ASP.NET MVC • Futurodi ASP.NET MVC

  3. Storiadeglistrumenti Microsoft per lo sviluppo Web

  4. Prima c’era ASP “Classic”

  5. Prima c’era ASP “Classic” - Storia ASP (‘96 – 2000, IIS3 –> ) • Primo framework disviluppo web integratocolwebserver • Introduce le prime astrazioni per facilitarel’interazione con ilwebserver • Request • Response • Server

  6. Prima c’era ASP “Classic” - Problemi • Lasciacompletalibertà al programmatore = • Codice e HTML sonomischiati (“spaghetti code”) • Difficileseparareimplementazione e presentazione <% Set oConn = Server.CreateObject("ADODB.Connection") oConn.Open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" & Server.MapPath("DB.mdb") Set rsUsers = Server.CreateObject("ADODB.Recordset") rsUsers.Open "SELECT * FROM Users", oConn %> <TABLE align="center" border="0" cellpadding="0" cellspacing="0" width="100%"> <% do while not rsUsers.eof %> <tr> <td><%=rsUsers.fields(0)%></td> <td><%=rsUsers.fields(2)%></td> </tr> <% rs.movenext loop %> </table> <% rsUsers = Nothing oConn = Nothing %>

  7. Poi venne ASP.NET - Storia • Cercadirisolvereilproblemadello“spaghetti code” • Rilasciato Gen ‘02 con .NET 1.0 • Permettediadottare un approccioVB6-like per lo sviluppo web. • Nasceilconcettodi WebForm

  8. Poi venne ASP.NET - WebForm

  9. Poi venne ASP.NET - WebForm • Ciclodi vita dellapaginabasatosueventi • Programmazionebasatasueventi • UserControls e Control tree • Nasconde la natura state-less del web

  10. Poi venne ASP.NET - Caratteristiche • HTML e codicesono in due file distinti(code-behind): • .aspx: contiene HTML e webcontrols • .aspx.cs: contieneilcodice per manipolareiwebcontrols <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server“ <title>Sample page</title> </head> <body> <formid="form1" runat="server"> <div> <asp:Labelrunat="server" id="Label1" /> </div> </form> </body> </html> using System; namespace Website { public partial class Page1 : System.Web.UI.Page { protected Label Label1; protected void Page_Load (object sender, EventArgs e) { Label1.Text = "Hello ASP.NET"; } } }

  11. Poi venne ASP.NET - Problemi Page Lifecycle troppocomplesso

  12. Poi venne ASP.NET - Problemi Troppo codice HTML autogenerato

  13. Poi venne ASP.NET - Problemi Troppa “roba” daportare in giro: ViewState

  14. Poi venne ASP.NET - Problemi Inutilmentecomplesso

  15. Poi venne ASP.NET – SoluzioneaiProblemi • Codicetroppoaccoppiato: pattern MVP, WCSF, MonoRail • HTML “brutto”: CSS Adapter Toolkit, templated controls • ViewState“ingombrante”: abilitarloselettivamente Ma tuttociò non è “out-of-the-box”

  16. Introduzione a ASP.NET MVC

  17. ASP.NET MVC to the rescue Ritornoallasemplicità

  18. ASP.NET MVC to the rescue – Storia • Nasce per cercaredirisolvereiproblemidi ASP.NET • Annunciatoda Scott Guthrie alla prima ALT.NET conference di Austin a Ott ‘07 • Attualmente alla versione Beta (1?)(Ottobre ‘08) • “Obbliga” unamaggiorseparazionedelleresponsabilità

  19. ASP.NET MVC – Caratteristiche • Implementail pattern Model-View-Controller • Sviluppato per esseretestabile • Estendibile • URL mapping engine • Puòutilizzareilmodellowebform per quelcheriguardailrendering, ma non per ilpostback • Supportatutte le funzionalità pre-esistenti: autenticazione, autorizzazione, caching, session, providers, ecc…

  20. Il Pattern MVC

  21. MVC in Real Life • Consegnadella pizza • L’utenteparla al controller (prendel’ordine per la pizza)

  22. MVC in Real Life • Il controller delega al model (ilcuocoricevel’ordine)

  23. MVC in Real Life • Quando la pizza è pronta, viene data al controller chedelegaalla view(fattorinoporta la pizza a casa)

  24. Introduzione a MVC • Introdotto per la prima volta in Smalltalk nel ‘79 • “Di moda” negliultimianni grazie a Struts, Spring MVC e Ruby on Rails • Divide l’applicazione in 3 componenti: • Model: la business logic dell’applicazione, checontiene le informazioni sui dati • View: rappresentaidatinella UI visibiledall’utente • Controller: orchestra le operazioni, ricevel’input, decide come recuperareidati e lipassaalla view

  25. Il flussodiun’applicazione MVC Il Controller chiedeidati al Model La richiestaarriva al controller Model 2 1 3 Browser Controller Il Model restituisceidati al controller Il controller formattaidati e lipassaalla view 4 View 5 La view costriusce la paginachevieneinivata al browser

  26. ASP.NET MVC neldettaglio [with Demo]

  27. Flussodellarichiesta

  28. Routing • Parte di ASP.NET 3.5 SP1 • System.Web.Routing.dll • Url con parametri: • {controller}, {action}, {parametri} routes.MapRoute( "Blog", //nome "blog/{date}/{title}", //url /*valori di default per i parametri*/ new { controller = "Blog", //Controller action = "Show", //Action date = DateTime.Now, //Parametri title = "" } );

  29. Controller • Classe con nome<NomeController>Controller • EreditadaController • Un metodopubblico per Action • MetodorestituisceActionResult public classBlogController: Controller { public ActionResult Show(DateTime date, string title) { ViewData["Titolo"] = title; ViewData["Data"] = date; returnView(); //returnView(“<viewName>", <viewdata>); } }

  30. View – Loosely Typed • E’ un normaleWebFormcheereditadaViewPage • DEVE SOLOcostruire la UI HTML • ViewData è +/- unaHashTable public partial class Show : ViewPage { //quasi sempre vuoto } <h2><%= Html.Encode(ViewData["Message"]) %></h2> <%= ((DateTime)ViewData["Data"]).ToLongDateString()%>

  31. View – Strongly Typed • La view puòancheessere strongly typed • Complie time check • Intellisense friendly  • ViewData è unaclasse custom public partial class StrongShow : ViewPage<PresentationModelClass> { //quasi sempre vuoto } <h2><%= Html.Encode(ViewData.Model.Message) %></h2> <%= ViewData.Model.Data.ToLongDateString()%>

  32. View – UI Helpers • UI Helper per aiutare la scritturadicodice HTML • Html.ActionLink • Html.ActionLink<ControllerClass> • Html.BeginForm • Html.BeginForm<ControllerClass> Html.ActionLink(“TestoLink",“ActionName",“Controller", new { parametri }); Html.ActionLink<ControllerClass>( c => c.ActionName(parametri),"Testo Link");

  33. Estendere MVC • Tuttopuòessereesteso • IControllerFactory • StructureMapControllerFactory • UnityControllerFactory • SpringControllerFactory • … • IViewFactory • BooViewEngine • NHamlViewFactory • … • Quasi tutte le integazionisonosviluppateall’internodiMVCContrib: http://www.codeplex.com/MVCContrib

  34. Testare ASP.NET MVC [with Demo]

  35. Testare ASP.NET MVC Ma questa non avrebbedovutoessere la prima slide? 

  36. Testarei controller • No mocking involved [TestClass] public classBlogControllerTest { [TestMethod] public void Show() { BlogController controller = newBlogController(); var result = controller.Show(2010,10,11,"Titolo Post") as RenderViewResult; Assert.IsNotNull(result, "Aspettavo un view da renderizzare"); Assert.AreEqual("Titolo Post", result.ViewData["Titolo"], "Mi aspettavo un altro messaggio"); } }

  37. Altriesempidi test • Testarestrongly-typed view data • Assert.AreEqual(expected, ((BlogModel)result.ViewData.Model).Titolo,…); • Testare Redirect • var result = controller.Show(…) as RedirectToRouteResult;

  38. Wrapping up…

  39. ASP.NET MVC vsWebForms • WebForms • Sviluppo RAD • Paradigmapiù simile allosviluppotradizionale client-side • Ottimo per “prototipare” • Puòdiventareinmantenibile • ASP.NET MVC • Piùcodicedascrivere • “Miglior” architetturadell’applicazione • Maggiorcontrollosu HTML • Abilitausodimetodologie Agile

  40. Statodi ASP.NET MVC • Orasiamoalla Beta • RTW rilasciata in un mesechefinisce in “ember” (Januray-ember?) • Routing ormai “stabile” (parte di ASP.NET 3.5 SP1)

  41. Conclusioni • ASP.NET MVC è un framework checipermettediscriverebuon software by default • ASP.NET WebFormnecessitadi “lavoro” per raggiungere lo stessolivellodipulizia • ASP.NET MVC non è ASP.NET 4.0 • è un’alternativa, non un sostituto

  42. Risorse • http://asp.net/mvc/ - Sitoufficiale, con download Beta, sample, video, ecc. • http://www.codeplex.com/aspnet - Codicesorgente • http://del.icio.us/tag/aspnetmvc - tuttigliarticolisu ASP.NET MVC • http://polymorphicpodcast.com/shows/mvcresources/ - lista “commentata” dirisorse • Blog di MS • ScottGu: http://weblogs.asp.net/scottgu/default.aspx • ScottHa: http://www.hanselman.com/blog/ • PhilHa: http://haacked.com/

  43. Beginning ASP.NET MVC • Simone Chiaretta e Keyvan Nayyeri • Rilascio: Marzo 2009 • Già in prevendita su Amazon • TOC: • MVC • Testing • And more... • http://www.amazon.co.uk/Beginning-ASP-NET-MVC-Simone-Chiaretta/dp/047043399X/

  44. Fun stuff • The MVC Song: • http://www.railsenvy.com/assets/2008/6/3/mvc_song.mp3 • MVC Public Service Announcement Videos • http://www.railsenvy.com/2008/6/3/mvc-videos • http://www.vimeo.com/album/15216

  45. Contatti – Simone Chiaretta • MSN: simone_ch@hotmail.com • Blog: • English: http://codeclimber.net.nz/ • Italiano: http://blogs.ugidotnet.org/piyo/ • Twitter: http://twitter.com/simonech

  46. Q&A

More Related