ASP.NET MVC 2 Web

Download Report

Transcript ASP.NET MVC 2 Web

8/13 現在の PPT です。
セッション当日の PPT と
内容が異なる場合があります。
ご了承ください。
セッション ID : T6-307
ASP.NET MVC 2 Web 開発
~ 全貌と応用、そして vNext に向けて ~
マイクロソフト株式会社
デベロッパー & プラットフォーム統括本部
エバンジェリスト
井上 章 (いのうえ あきら)
セッションの目的とゴール
Session Objectives and Takeaways
目的
ASP.NET MVC の全体像や応用方法について
ご理解を深めていただきます
デモを通して Web 開発の楽しさをお伝えします
ゴール
ASP.NET MVC の全体像や応用方法を
説明できるようになる
ASP.NET MVC Web アプリケーション開発が
おこなえるようになる
クラウドを意識したインターネット向け
Web アプリケーションを構築できるようになる
3
アジェンダ
~ 全貌、応用、v.Next ~
Introduction
Tech・Ed Japan 2009 を振り返ったり ...
全貌編
ASP.NET MVC 2 オーバービューなど ...
応用編
拡張ポイントやセキュリティなど ...
v.Next へ向けて
ASP.NET MVC 3 と Razor など ...
MVC 事例紹介
まとめ
4
5
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
6
ASP.NET 4
フレームワーク構成
Web フォーム
コア サービス
7
jQuery
8
MVC オーバービュー
Web アプリにおける MVC パターン
データと
ビジネス ロジック
odel
プレゼン
テーション
入力と制御
Request
9
ontroller
iew
Response
ASP.NET MVC 2
新しい Web アプリ開発フレームワーク
2010 年 3 月 RTM リリース (for VS 2008 SP1)
Visual Studio 2010 に標準搭載
オープン ソース (CodePlex)
各モジュールが 疎結合 に
単体テスト (TDD) が容易に
HTML ベース のページ開発が容易に
URL ルーティング が可能に
10
各モジュールが 疎結合 に ...
Why ?
11
Controller と View の命名ルール
コンセプト「規約は設定に勝る」
CoC (Convention over Configuration)
命名ルールによってモジュール間の結合を疎に
コードや設定ファイルなどで関連付けない
Controller クラス
Controller 名
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "MVC";
return View();
アクション名
}
}
12
テスト駆動開発 (TDD)
Controller Action の単体テストが容易に
単体テストには IIS などの Web サーバー は不要
Visual Studio 2008/2010 Professional 以上
NUnit, MBUnit, XUnit なども利用可能
テスト プロジェクトも同時に作成可能
テスト コードの雛型が自動生成
[TestMethod]
public void Index() {
HomeController ctrl = new HomeController();
ViewResult result = ctrl.Index() as ViewResult;
ViewDataDictionary viewData = result.ViewData;
Assert.AreEqual("Hello", viewData["Message"]);
}
13
HTML ベース のページ開発が
容易に ...
Why ?
14
View の特徴と HTML 生成
埋め込みコード ブロックの利用
View における HTML 生成 (View エンジン) は
既定で Web フォーム (.aspx) を使用
System.Web.Mvc.WebFormViewEngine クラス
View (.aspx)
埋め込み
コード ブロック
<html>
<div><%: DateTime.Now.ToString() %></div>
<div><%: Html.TextBox("data", Model.data) %></div>
</html>
基本的に Web サーバー コントロールは使用しない
(ポストバックや ViewState は使用しない)
ヘルパー メソッドで HTML タグ ブロックを生成
15
HTML ヘルパー メソッド
HTML 生成を助ける関数群
メソッド名
概要
ActionLink
アクション名などから a タグを生成
BeginForm
form タグを生成
TextBox
TextBoxFor
input タグによる入力フィールドを生成
…
…
使用例
<%: Html.ActionLink("Go to Home", "Index") %>
<%: Html.TextBox("message", model.Message) %>
<%: Html.TextBoxFor(model => model.Message) %>
16
URL ルーティング
クリーン URL で SEO 対策
ASP.NET MVC では既定でルーティングが有効
System.Web.Routing 名前空間
例: http://example.com/Products/Car/Details/5
17
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);
}
出力キャッシュの利用
冗長なサーバー処理の回避
OutputCacheAttribute (ActionFilter) を利用
Controller Action の無駄な実行を制御
アプリケーション パフォーマンスの改善
[OutputCache(Duration=3600, VaryByParam="id")]
public ActionResult Details(int id) {
id 毎に
return View(myModel.GetData(id));
1 時間キャッシュ
}
キャッシュ プロファイル を利用した設定
アプリケーションを再ビルドすることなく設定変更可
[OutputCache(CacheProfile="MyCache")]
public ActionResult Index() {…}
Web.config - <system.web><caching><outputCacheSettings>
18
<outputCacheProfiles>
<add name="MyCache" duration="3600" … />
</outputCacheProfiles>
Data Annotation バリデーション
Model 中心の入力検証
宣言型で コードすっきり バリデーション
Model
属性ベースで
検証ルールを指定
public class MyData {
[DisplayName("年齢")]
[Required(ErrorMessage = "{0}を入力してね")]
[Range(0, 100)]
public int Age { get; set; }
エラー メッセージも
}
指定可能
View
<%: Html.TextBoxFor(model => model.Age) %>
<%: Html.ValidationMessageFor(model => model.Age) %>
Controller
19
public ActionResult Create(MyData myData) {
if (ModelState.IsValid) { … }
モデル バインドと
}
検証実行
Templated Helpers (1)
HTML ヘルパーにおけるテンプレートの利用
テンプレート
データ型やクラスに基づいた
部分 View の定義
既定の View エンジンでは
.ascx ファイルで記述
表示用
Views\<Controller>\
テンプレート DisplayTemplates\
格納先
Views\Shared\
DisplayTemplates\
ヘルパー
メソッド
20
編集用
Views\<Controller>\
EditorTemplates\
Views\Shared\
EditorTemplates\
DisplayForModel
EditorForModel
DisplayFor
EditorFor
Display
Editor
Templated Helpers (2)
型ベース 及び 名前付き テンプレート
A) データ型やクラスに基づいたテンプレートの利用
<%@ Page Inherits="ViewPage<MyData>" %>
<%: Html.DisplayForModel() %>
B) 名前付きテンプレートの利用
<%: Html.DisplayFor(m => m.Name, "NameTemplate") %>
21
View (*.aspx)
View (*.aspx)
: ViewPage<MyData>
<%: DisplayForModel() %>
<%: DisplayFor(m => m.name,
"NameTemplate") %>
DisplayTemplates\
MyData.ascx
DisplayTemplates\
NameTemplate.ascx
: ViewUserControl<MyData>
<p><%: Model.Name %></p>
: ViewUserControl<String>
<p><%: Model %></p>
RenderPartial と RenderAction
View の部分レンダリング
RenderPartial
部分 View をレンダリング
Html.RenderPartial(ViewName, … )
RenderAction
コントローラー アクションの実行結果をレンダリング
Html.RenderAction(ActionName, … )
View (.aspx)
View (.aspx)
M
<html>
<% RenderPartial(…); %>
View (.ascx)
</html> <div>…</div>
22
M
<html>
<% RenderAction(…); %>
M
Controller
M
</html> ActionResult Ad()
※ M は Model の略
AsyncController
非同期コントローラーの利用
AsyncController クラス
命名規約による容易な非同期処理の実装が可能
開始 : void ActionNameAsync()
終了 : ActionResult ActionNameCompleted()
※ View 名には Async / Completed の文字は不要
利点
Web サーバーの他のリクエスト
処理がブロックされない
時間のかかるネットワーク I/O
(Web API 呼び出し等) に有効
注意点
:AsyncController
1: 開始
他の処理
2: 完了
非同期処理はオーバーヘッドが大きい
同期処理においてボトル ネックになる部分に適用
23
object1:
ASP.NET MVC 2
その他の機能
Areas (区分)
単一 MVC プロジェクト内で
アプリケーションを分割
AreaRegistration.RegisterAllAreas()
アクション メソッドのデフォルト値
ActionResult Index([DefaultValue(1)] int id)
ActionResult Index(int id = 1)
HTTP Method 属性
HttpPost, HttpGet, HttpPut, HttpDelete
[HttpPost]
public ActionResult Create(MyData myData) { … }
24
25
MVC フレームワークの拡張
多くの拡張ポイントと容易なカスタマイズ
ValidationAttribute
odel
ModelBinder
ActionFilter
ActionResult
Request
Routing
26
ontroller
ViewEngine
HtmlHelper
iew
Response
ASP.NET MVC パイプライン
フレームワーク内部処理の流れ
HTTP
Request
IIS / ASP.NET
URL Routing
Controller
Controller Factory
ModelBinder
ActionFilter
Controller Action
Model
View
ActionResult
27
ViewEngine
Render HTML
HTTP
Response
View エンジンのカスタマイズ (1)
ViewEngine = HTML 生成テンプレート エンジン
View エンジンのカスタマイズが可能
View エンジンの変更 (Razor, NHaml, Spark, ...)
オリジナル View エンジンの作成
View の検索パスの変更
等々...
View Engine
Request
28
ontroller
iew Response
View エンジンのカスタマイズ (2)
さまざまな View エンジンの記法
WebFormViewEngine (.aspx 既定)
<h1><%: product.ProductName %></h1>
<p><%: Html.ActionLink("Add...", "Add") %></p>
NHaml - http://code.google.com/p/nhaml/
Rails Haml View エンジンの .NET 実装版
%h1= product.ProductName
%p= Html.ActionLink("Add...", "Add")
Spark - http://sparkviewengine.com/
Castle Project - MonoRail 向け View エンジン
<h1>${ product.ProductName }</h1>
<p>${ Html.ActionLink("Add...", "Add") }</p>
29
セキュリティ対策
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);
30
ASP.NET MVC 拡張ライブラリ
もっと活用したい ! あなたのために ...
MVC Contrib
http://mvccontrib.codeplex.com/
様々な拡張ライブラリ群
HTML Helper, Model Binder, Controller, Routing,
Action Result, Action Filter, Unit Test Helper, ...
T4MVC
http://mvccontrib.codeplex.com/releases/view/41582
T4 テンプレートを利用した自動コード生成
View や Controller コード内のリテラル文字列を排除
インテリセンス利用可 & 容易なコード メンテナンス
<% Html.RenderPartial("Banner"); %>
<% Html.RenderPartial(MVC.Home.Views.Banner); %>
31
32
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 以降
MVC 3 と Razor View エンジン
Small, Simple, Seamless
新しい "Razor 構文" View エンジンの追加
Razor プロジェクト テンプレート
[ View の追加 ] ダイアログ での View エンジン選択
View 毎に使用するエンジンを選択可能
Razor View 拡張子 (※変更の可能性あり)
.cshtml (C#) / .vbhtml (VB)
34
"Razor" 構文
Small, Simple, Seamless
Web ページ (View) の新しい記述構文
シンプル & クリーン
タイピング量とコード サイズの低減 (vs. PHP, ASPX)
便利な HTML ヘルパーと容易な拡張
C#, Visual Basic をサポート
.cshtml
35
@{ 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
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/
37
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)
38
国内採用事例のご紹介
こちらも続々と増えてます ...
現場入退場管理システム「デイリ」
携帯コールによる遠隔地の現場労働時間管理システム
コムテックス株式会社様 開発
http://www.ctx.co.jp/deiri_pr/index.html
システム構成
Windows Azure (Web Role + SQL Azure)
ASP.NET MVC + jQuery
ASP.NET メンバーシップ & ロール管理
オンプレミス連携 (電話着信処理など)
39
40
ASP.NET MVC 2
Small + Simple + Seamless = Smart !
ASPX, Razor, ...
41
M V
C
42
Model / View / Controller
実装コード例
Model と Controller
public class HomeController : Controller { Model の準備
MyModelService myModel = new MyModelService();
public ActionResult Edit(int id) {
MyData md = myModel.GetData(id);
return View(md);
}
}
View の呼び出し
View (Edit.aspx)
HTTP リクエスト
によるメソッドの
実行
(例: Home/Edit/5 )
ロジックの実行と
データ取得
HTML タグ生成と
データの埋め込み
<html>
<p><%: Html.TextBox("data", Model.data) %></p>
</html>
43
ModelBinder とは ?
HTTP リクエスト データの自動バインド
アクション メソッド 引数への自動バインド
既定のバインドは DefaultModelBinder
以下のオブジェクト型をバインド
Model クラス
プリミティブ型 (String, DateTime, ...)
コレクション (ICollection<T>, IList<T>, ...)
バインドありの場合
ActionResult Create(MyData myData) {
if (ModelState.IsValid) {
MyData へバインド
string name = myData.Name;
...
バインドなしの場合
44
ActionResult Create() {
string name = Request["Name"];
...
ModelBinder 拡張
カスタム機能の追加
インターフェース : IModelBinder
ベース クラス : DefaultModelBinder
主な拡張ポイント
object BindModel(…);
object CreateModel(…);
bool OnModelUpdating(…);
void OnModelUpdated(…);
bool OnPropertyValidating(…);
void OnPropertyValidated(…);
ModelBinder の登録
//
//
//
//
//
//
モデル バインド実行
モデル型オブジェクト生成
モデル更新開始
モデル更新完了
プロパティ検証開始
プロパティ検証完了
// Application_Start() で下記のいずれかで指定
ModelBinders.Binders.DefaultBinder = new MyBinder();
ModelBinders.Binders.Add(typeof(MyData),new MyBinder());
// または、引数の属性で指定
[ModelBinder(typeof(MyBinder))]
45
ActionFilter 拡張
アクション メソッド実行時の拡張ポイント
アクション メソッドの実行前後に独自機能を追加
ベース クラス
ActionFilterAttribute : FilterAttribute
使用例
public class LogAttribute : ActionFilterAttribute {
public override void OnActionExecuting(…) {…}
public override void OnResultExecuted(…) {…}
}
Controller や Action に属性を指定
[Log]
public class HomeController : Controller {…}
既存の FilterAttribute 派生クラス
AuthorizeAttribute, ValidateAntiForgeryTokenAttribute,
ChildActionOnlyAttribute, RequireHttpsAttribute ...
46
Microsoft Web Platform ホーム
まずはここからスタート !
www.microsoft.com/web
Web プラットフォームの紹介
サーバー
フレームワーク
データ ベース
ツール
Web App Gallery
ダウンロード
プログラム紹介
ホスティング情報
事例紹介
などなど ...
47
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
48
WebsiteSpark
Web 開発会社様 支援プログラム
プログラム特典:
開発ツール
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 Web Edition x 3
※これらのソフトウェアは MSDN サブスクリプションの
ダウンロード サイトから提供させていただきます
技術サポート
技術サポートを 2 インシデント無償提供
その他
参加企業の露出機会の提供
技術資料、トレーニングマテリアルなどの提供
参加要件:
• Web 開発ビジネスを主業務としていること
(個人事業主を含む)
• 従業員数が 25 名以下であること
• プログラム加盟後、6 か月以内に Windows
プラットフォームを用いた新しいドメインの
Web サイトを開発すること。
期間:最大 3 年間
費用:無料(プログラム終了時にプログラム提供料
として 100 米ドルお支払いいただきます)
www.microsoft.com/web/websitespark
49
最新テクノロジーと 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 への対応
50
関連セッション
ASP.NET Web 開発はこちら ...
T6-305 : 8/25 15:20 – 16:30 Room D
ASP.NET 4 で実践する Web フォーム開発と配置
T6-306 : 8/26 16:55 – 18:05 Room D
jQuery と ASP.NET AJAX Control Toolkit による
AJAX アプリケーション開発
BOF-10 : 8/27 13:45 – 14:55
マイクロソフトの Web テクノロジ最前線と現実解を語ろう
H-316 : 8/25 – 8/27 各日 1 セッション
ASP.NET MVC 2 と jQuery による Web 開発
~ Edtter を作ろう~
T6-309 : 8/25 16:55 – 18:05 Room C
詳説 ! Visual Basic 10, C# 4.0 の新機能
~ Visual Studio 2010 で進化したコーディング環境 ~
51
リファレンス #1
Microsoft Web Platform
http://www.microsoft.com/web/
MSDN ASP.NET デベロッパー センター
http://msdn.microsoft.com/ja-jp/asp.net/default.aspx
Microsoft Web 開発ガイドライン
http://msdn.microsoft.com/ja-jp/asp.net/ff602016.aspx
ASP.NET MVC チュートリアル
http://msdn.microsoft.com/ja-jp/asp.net/ff630143.aspx
ASP.NET MVC 2 サンプル ソース コード ~ Edtter ~
http://edtter.codeplex.com/
THE TRUTH IS OUT THERE ~ 井上 章のブログ ~
http://blogs.msdn.com/chack/
52
リファレンス #2
ASP.NET MVC: The Official Microsoft ASP.NET Site (英語)
http://www.asp.net/mvc
CodePlex - ASP.NET MVC (英語)
http://aspnet.codeplex.com/wikipage?title=MVC
ScottGu's Blog (英語)
http://weblogs.asp.net/scottgu/default.aspx
Phil Haack's Blog (英語)
http://haacked.com/Default.aspx
Scott Hanselman's Blog (英語)
http://www.hanselman.com/blog/
K. Scott Allen's Blog (英語)
http://odetocode.com/Blogs/scott/default.aspx
53
ご清聴ありがとうございました!
T6-307
アンケートにご協力ください。
© 2010 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.
The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should
not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS,
IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.