html5-img
1 / 55

8/13 現在の PPT です。 セッション当日の PPT と 内容が異なる場合があります。 ご了承 ください 。

8/13 現在の PPT です。 セッション当日の PPT と 内容が異なる場合があります。 ご了承 ください 。. セッション ID : T6-307. ASP.NET MVC 2 Web 開発 ~ 全貌と応用、そして vNext に向けて ~. マイクロソフト株式会社 デベロッパー & プラットフォーム統括本部 エバンジェリスト 井上 章 ( いのうえ あきら ). セッションの目的とゴール Session Objectives and Takeaways. 目的

carlota
Download Presentation

8/13 現在の PPT です。 セッション当日の PPT と 内容が異なる場合があります。 ご了承 ください 。

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. 8/13 現在の PPT です。 セッション当日の PPT と内容が異なる場合があります。 ご了承ください。

  2. セッション ID : T6-307 ASP.NET MVC 2 Web 開発~ 全貌と応用、そして vNextに向けて ~ マイクロソフト株式会社 デベロッパー & プラットフォーム統括本部 エバンジェリスト 井上 章 (いのうえ あきら)

  3. セッションの目的とゴールSessionObjectives and Takeaways • 目的 • ASP.NET MVCの全体像や応用方法についてご理解を深めていただきます • デモを通して Web 開発の楽しさをお伝えします • ゴール • ASP.NET MVC の全体像や応用方法を説明できるようになる • ASP.NET MVC Web アプリケーション開発がおこなえるようになる • クラウドを意識したインターネット向け Web アプリケーションを構築できるようになる

  4. アジェンダ~ 全貌、応用、v.Next~ • Introduction • Tech・Ed Japan 2009 を振り返ったり ... • 全貌編 • ASP.NET MVC 2 オーバービューなど ... • 応用編 • 拡張ポイントやセキュリティなど ... • v.Nextへ向けて • ASP.NET MVC 3 と Razor など ... • MVC 事例紹介 • まとめ

  5. Introduction

  6. Introductionセッション ことはじめ ... • 昨年の Tech·Ed Japan 2009 では ... • T2-306: ASP.NET MVC アプリケーション開発 • ASP.NET MVC 2 サンプル ソース コードは ... • Edtter (エドったー) : http://edtter.codeplex.com/ • Hands-on Lab で MVC を試すなら ... • H-316: ASP.NET MVC 2 と jQueryによる Web 開発~ Edtterを作ろう ~ • Twitter でつぶやくなら ... • ハッシュ タグ:#techedjp #T6-307 #MVC • その他、私事で恐縮ですが ... • Blog: http://blogs.msdn.com/chack/ • Twitter: http://twitter.com/chack411

  7. ASP.NET 4フレームワーク構成 jQuery ASP.NET ASP.NET MVC Web フォーム ASP.NET AJAX Dynamic Data コア サービス

  8. 全貌編

  9. 全貌 MVC オーバービューWeb アプリにおける MVC パターン データとビジネス ロジック Model 入力と制御 プレゼンテーション Controller View Request Response

  10. 全貌 ASP.NET MVC 2新しい Web アプリ開発フレームワーク • 2010 年 3 月 RTM リリース (for VS 2008 SP1) • Visual Studio 2010に標準搭載 • オープン ソース (CodePlex)

  11. 各モジュールが 疎結合 に ...Why ?

  12. 全貌 Controller と View の命名ルールコンセプト「規約は設定に勝る」 • CoC (Convention over Configuration) • 命名ルールによってモジュール間の結合を疎に • コードや設定ファイルなどで関連付けない Controller クラス • publicclassHomeController : Controller • { • publicActionResult Index() • { • ViewData["Message"] = "MVC"; • return View(); • } • } Controller 名 アクション名

  13. 全貌 テスト駆動開発 (TDD)Controller Action の単体テストが容易に • 単体テストには IIS などの Web サーバー は不要 • Visual Studio 2008/2010 Professional 以上 • NUnit, MBUnit, XUnitなども利用可能 • テスト プロジェクトも同時に作成可能 • テスト コードの雛型が自動生成 [TestMethod] publicvoid Index() { HomeController ctrl = newHomeController(); ViewResultresult = ctrl.Index() asViewResult; ViewDataDictionaryviewData = result.ViewData; Assert.AreEqual("Hello", viewData["Message"]); }

  14. HTML ベース のページ開発が 容易に ...Why ?

  15. 全貌 View の特徴と HTML 生成埋め込みコード ブロックの利用 • View における HTML 生成 (View エンジン) は既定でWeb フォーム (.aspx)を使用 • System.Web.Mvc.WebFormViewEngineクラス • 基本的に Web サーバー コントロールは使用しない(ポストバックやViewStateは使用しない) • ヘルパー メソッドで HTML タグ ブロックを生成 埋め込みコード ブロック View (.aspx) <html> <div><%:DateTime.Now.ToString() %></div> <div><%:Html.TextBox("data", Model.data) %></div> </html>

  16. 全貌 HTML ヘルパー メソッドHTML 生成を助ける関数群 ※ 上記は HTML ヘルパー メソッドの一部 ※ System.Mvc.HtmlHelperクラスを参照 使用例 <%:Html.ActionLink("Go to Home", "Index") %> • <%:Html.TextBox("message", model.Message) %> • <%:Html.TextBoxFor(model => model.Message) %>

  17. 全貌 URL ルーティングクリーン URL で SEO 対策 • ASP.NET MVC では既定でルーティングが有効 • System.Web.Routing名前空間 例: http://example.com/Products/Car/Details/5 static void RegisterRoutes(RouteCollection routes) { routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller= "Car", action = "List", id = UrlParameter.Optional } ); } void Application_Start() { RegisterRoutes(RouteTable.Routes); } ルーティング定義 既定値 (省略時の値)

  18. 全貌 出力キャッシュの利用冗長なサーバー処理の回避 • OutputCacheAttribute (ActionFilter) を利用 • Controller Action の無駄な実行を制御 • アプリケーション パフォーマンスの改善 • キャッシュ プロファイル を利用した設定 • アプリケーションを再ビルドすることなく設定変更可 [OutputCache(Duration=3600, VaryByParam="id")] public ActionResult Details(int id) { return View(myModel.GetData(id)); } id 毎に1 時間キャッシュ [OutputCache(CacheProfile="MyCache")] public ActionResult Index() {…} • Web.config - <system.web><caching><outputCacheSettings> <outputCacheProfiles> <add name="MyCache" duration="3600" … /> </outputCacheProfiles>

  19. 全貌 Data Annotation バリデーションModel 中心の入力検証 • 宣言型で コードすっきり バリデーション Model 属性ベースで検証ルールを指定 • publicclassMyData{ • [DisplayName("年齢")] • [Required(ErrorMessage = "{0}を入力してね")] • [Range(0, 100)] • publicint Age { get; set; } • } エラー メッセージも指定可能 View <%:Html.TextBoxFor(model => model.Age) %> <%:Html.ValidationMessageFor(model => model.Age) %> Controller publicActionResult Create(MyDatamyData) { if(ModelState.IsValid) { … }} モデル バインドと検証実行

  20. 全貌 Templated Helpers (1)HTML ヘルパーにおけるテンプレートの利用 • テンプレート • データ型やクラスに基づいた 部分 View の定義 • 既定の View エンジンでは .ascxファイルで記述

  21. 全貌 Templated Helpers (2)型ベース 及び 名前付き テンプレート A) データ型やクラスに基づいたテンプレートの利用 • <%@ Page Inherits="ViewPage<MyData>" %> • <%:Html.DisplayForModel() %> B) 名前付きテンプレートの利用 • <%:Html.DisplayFor(m => m.Name, "NameTemplate") %> View (*.aspx) : ViewPage<MyData> View (*.aspx) <%: DisplayFor(m => m.name, "NameTemplate") %> <%: DisplayForModel() %> DisplayTemplates\MyData.ascx : ViewUserControl<MyData> DisplayTemplates\NameTemplate.ascx : ViewUserControl<String> <p><%: Model.Name%></p> <p><%: Model %></p>

  22. 全貌 RenderPartialと RenderActionView の部分レンダリング • RenderPartial • 部分 View をレンダリング • RenderAction • コントローラー アクションの実行結果をレンダリング • Html.RenderPartial(ViewName, … ) • Html.RenderAction(ActionName, … ) View (.aspx) View (.aspx) M M <html> <% RenderPartial(…); %> </html> <html> <% RenderAction(…); %> </html> M View (.ascx) Controller M <div>…</div> ActionResult Ad() ※ M は Model の略

  23. 全貌 AsyncController非同期コントローラーの利用 • AsyncControllerクラス • 命名規約による容易な非同期処理の実装が可能※ View 名には Async / Completedの文字は不要 • 利点 • Web サーバーの他のリクエスト処理がブロックされない • 時間のかかるネットワーク I/O (Web API 呼び出し等) に有効 • 注意点 • 非同期処理はオーバーヘッドが大きい • 同期処理においてボトル ネックになる部分に適用 • 開始 :void ActionNameAsync() • 終了 : ActionResultActionNameCompleted() :AsyncController object1: 1: 開始 他の処理 2: 完了

  24. 全貌 ASP.NET MVC 2その他の機能 • Areas (区分) • 単一 MVC プロジェクト内でアプリケーションを分割 • AreaRegistration.RegisterAllAreas() • アクション メソッドのデフォルト値 • HTTP Method 属性 • HttpPost, HttpGet, HttpPut, HttpDelete ActionResult Index([DefaultValue(1)] int id) ActionResult Index(int id = 1) [HttpPost] publicActionResult Create(MyDatamyData) { … }

  25. 応用編

  26. 応用 MVC フレームワークの拡張多くの拡張ポイントと容易なカスタマイズ ValidationAttribute Model ModelBinder ActionFilter ActionResult ViewEngine HtmlHelper Controller View Request Response Routing

  27. 応用 ASP.NET MVC パイプラインフレームワーク内部処理の流れ HTTPRequest Controller Model View HTTP Response

  28. 応用 View エンジンのカスタマイズ (1)ViewEngine = HTML 生成テンプレート エンジン • View エンジンのカスタマイズが可能 • View エンジンの変更 (Razor, NHaml, Spark, ...) • オリジナル View エンジンの作成 • View の検索パスの変更 • 等々... View Engine WebForm Controller View Razor Request Response NHaml Spark ...

  29. 応用 View エンジンのカスタマイズ (2)さまざまなView エンジンの記法 • WebFormViewEngine (.aspx既定) • NHaml - http://code.google.com/p/nhaml/ • Rails Haml View エンジンの .NET 実装版 • Spark - http://sparkviewengine.com/ • Castle Project- MonoRail向け View エンジン • <h1><%:product.ProductName%></h1> • <p><%:Html.ActionLink("Add...", "Add") %></p> • %h1=product.ProductName • %p=Html.ActionLink("Add...", "Add") • <h1>${ product.ProductName}</h1> • <p>${ Html.ActionLink("Add...", "Add") }</p>

  30. 応用 セキュリティ対策ASP.NET MVC でも忘れずに • Controller 実行時の認証の要求 • [Authorize] 属性 (ActionFilter) • HTML Encoding 構文 (WebFormViewEngine) • <%:SomeStringData%> • Cross Site Scripting (XSS) • Microsoft Web Protection Library http://wpl.codeplex.com/ • Cross Site Request Forgeries (CSRF) • Html.AntiForgeryToken() • [ValidateAntiForgeryToken] • JSON Hijacking • JsonResult • return Json(data, JsonRequestBehavior.DenyGet);

  31. 応用 ASP.NET MVC 拡張ライブラリもっと活用したい ! あなたのために ... • MVC Contribhttp://mvccontrib.codeplex.com/ • 様々な拡張ライブラリ群 • HTML Helper, Model Binder, Controller, Routing, Action Result, ActionFilter, Unit Test Helper, ... • T4MVChttp://mvccontrib.codeplex.com/releases/view/41582 • T4 テンプレートを利用した自動コード生成 • View や Controller コード内のリテラル文字列を排除 • インテリセンス利用可 & 容易なコード メンテナンス • <% Html.RenderPartial("Banner"); %> • <% Html.RenderPartial(MVC.Home.Views.Banner); %>

  32. v.Nextへ向けて

  33. Next ASP.NET MVC 3新機能 概要 • Preview 1 (2010年 7 月 27 日 リリース)http://go.microsoft.com/fwlink/?LinkID=157073 • 新機能 • Razor, ASPX, … などのView エンジンの選択機能 • ダイナミック View / ViewModelプロパティ • グローバル Action Filters • JsonValueProviderFactoryと JSON モデル バインド • ValidationAttribute と IValidatableObject • 新しい ActionResult型 と Permanent Redirect • Dependency Injection (DI) サポート • ランタイム • ASP.NET 4 & Visual Studio 2010 以降

  34. Next MVC 3 と Razor View エンジンSmall, Simple, Seamless • 新しい "Razor 構文" View エンジンの追加 • Razor プロジェクト テンプレート • [ View の追加 ] ダイアログ での View エンジン選択 • View 毎に使用するエンジンを選択可能 • Razor View 拡張子 (※変更の可能性あり) • .cshtml (C#) / .vbhtml (VB)

  35. Next "Razor" 構文Small, Simple, Seamless New ! • Web ページ (View) の新しい記述構文 • シンプル & クリーン • タイピング量とコード サイズの低減 (vs. PHP,ASPX) • 便利な HTML ヘルパーと容易な拡張 • C#, Visual Basic をサポート .cshtml • @{ string title = "Hello Razor"; } • <h1>@title</h1> • <ul> • @foreach (var item in Model) { • <li>@item.Message</li> • } • </ul> • <p>Time is @DateTime.Now</p> • <p>@Html.ActionLink("Add...", "Add")</p>

  36. MVC 事例紹介

  37. 事例 ASP.NET MVC の採用事例続々と増加中... • StackOverflow.com • http://stackoverflow.com/ • Ruth's Chris Steakhouse • http://www.ruthschris.com/ • MarketWatch • http://www.marketwatch.com/ • Kelley Blue Book • http://www.kbb.com/ • CodePlex - Open Source Project • http://www.codeplex.com/ • Windows Live • http://home.live.com/ • Bing Shopping • http://www.bing.com/shopping/

  38. 事例 Orchard新しい .NET ベース CMS • Orchard (オーチャード) • 2010 年 8 月 3 日 v.0.5 (Beta) リリース • http://orchardproject.net/ • http://orchard.codeplex.com/ (ソース コード等) • 軽量な CMS (Contents Management System) • Web サイト、ブログ、ドキュメント管理など ... • ASP.NET MVC 2 ベース • 容易なセットアップ (Web PI) • 容易な拡張とカスタマイズ (Visual Studio, WebMatrix)

  39. 事例 国内採用事例のご紹介こちらも続々と増えてます ... • 現場入退場管理システム「デイリ」 • 携帯コールによる遠隔地の現場労働時間管理システム • コムテックス株式会社様 開発 • http://www.ctx.co.jp/deiri_pr/index.html • システム構成 • Windows Azure (Web Role + SQL Azure) • ASP.NET MVC + jQuery • ASP.NET メンバーシップ & ロール管理 • オンプレミス連携 (電話着信処理など)

  40. まとめ

  41. ASP.NET MVC 2Small + Simple + Seamless =Smart ! Simple Small ASPX, Razor, ... Seamless M V C Smart な Web 開発を ...

  42. Appendix

  43. 全貌 Model / View / Controller実装コード例 Model と Controller Model の準備 publicclassHomeController : Controller { MyModelServicemyModel = newMyModelService(); publicActionResultEdit(int id) { MyDatamd = myModel.GetData(id); returnView(md); } } HTTP リクエストによるメソッドの実行 (例: Home/Edit/5) ロジックの実行と データ取得 View の呼び出し HTML タグ生成とデータの埋め込み View (Edit.aspx) • <html> • <p><%:Html.TextBox("data", Model.data) %></p> • </html>

  44. 応用 ModelBinderとは ?HTTP リクエスト データの自動バインド • アクション メソッド 引数への自動バインド • 既定のバインドは DefaultModelBinder • 以下のオブジェクト型をバインド • Model クラス • プリミティブ型 (String, DateTime, ...) • コレクション (ICollection<T>, IList<T>, ...) バインドありの場合 ActionResultCreate(MyDatamyData) { if (ModelState.IsValid) { string name = myData.Name; ... MyDataへバインド バインドなしの場合 ActionResultCreate() { stringname = Request["Name"]; ...

  45. 応用 ModelBinder 拡張カスタム機能の追加 • インターフェース : IModelBinder • ベース クラス : DefaultModelBinder 主な拡張ポイント objectBindModel(…); // モデル バインド実行 objectCreateModel(…); // モデル型オブジェクト生成 boolOnModelUpdating(…); // モデル更新開始 voidOnModelUpdated(…); // モデル更新完了 boolOnPropertyValidating(…); // プロパティ検証開始 voidOnPropertyValidated(…); // プロパティ検証完了 ModelBinderの登録 // Application_Start() で下記のいずれかで指定 ModelBinders.Binders.DefaultBinder= newMyBinder(); ModelBinders.Binders.Add(typeof(MyData),newMyBinder()); // または、引数の属性で指定 [ModelBinder(typeof(MyBinder))]

  46. 応用 ActionFilter拡張アクション メソッド実行時の拡張ポイント • アクション メソッドの実行前後に独自機能を追加 • ベース クラスActionFilterAttribute : FilterAttribute • 既存の FilterAttribute派生クラスAuthorizeAttribute, ValidateAntiForgeryTokenAttribute, ChildActionOnlyAttribute, RequireHttpsAttribute ... 使用例 public classLogAttribute : ActionFilterAttribute { public override voidOnActionExecuting(…) {…} public override voidOnResultExecuted(…) {…} } [Log] public classHomeController : Controller{…} Controller や Action に属性を指定

  47. Microsoft Web Platform ホームまずはここからスタート ! www.microsoft.com/web • Web プラットフォームの紹介 • サーバー • フレームワーク • データ ベース • ツール • Web App Gallery • ダウンロード • プログラム紹介 • ホスティング情報 • 事例紹介 • などなど ...

  48. Web Platform Installer(Web PI)コンポーネントやアプリの一括管理ツール • 様々な Web 開発ツールやコンポーネント、オープンソースの Web アプリのインストールなどを一括管理する無償ツール • IIS, Visual Web Developer, SQL Server Express, .NET Framework ... • WordPress, XOOPS Cube Legacy, SugarCRM, DotNetNuke... • Web PI ダウンロードhttp://www.microsoft.com/web/downloads/platform.aspx

  49. プログラム特典: 開発ツール Visual Studio 2010 Professional x 3 Expression Studio 4 x 1 Expression Web 4 x 2 サーバー ソフトウェア(検証、デモ用) Windows Web Server 2008 R2 x 3 SQL Server 2008 WebEdition x 3 ※これらのソフトウェアは MSDN サブスクリプションのダウンロード サイトから提供させていただきます 技術サポート 技術サポートを 2 インシデント無償提供 その他 参加企業の露出機会の提供 技術資料、トレーニングマテリアルなどの提供 WebsiteSparkWeb 開発会社様 支援プログラム Web 開発に必要なマイクロソフトの製品を 3 年間無償で利用できます! • 参加要件: • Web 開発ビジネスを主業務としていること(個人事業主を含む) • 従業員数が 25 名以下であること • プログラム加盟後、6 か月以内に Windows プラットフォームを用いた新しいドメインのWeb サイトを開発すること。 • 期間:最大 3 年間 • 費用:無料(プログラム終了時にプログラム提供料として 100 米ドルお支払いいただきます) www.microsoft.com/web/websitespark

  50. 最新テクノロジーと Web 開発新しいプラットフォームも続々と ... • WebMatrix (Beta) • http://www.microsoft.com/web/webmatrix/ • 軽量な Web サイトを構築・管理する統合ツール • オープン ソースの Web アプリのインストールやカスタマイズ • Visual Studio LightSwitch (Beta) • http://www.microsoft.com/visualstudio/en-us/lightswitch/ • ベーシックな業務アプリケーションを迅速に構築 • 基本コードはテンプレートから自動生成 • Internet Explorer 9 (Preview) • http://ie.microsoft.com/testdrive/ • Web 標準への準拠、次世代規格 HTML5, CSS3 への対応

More Related