XAML と C# を使った Windows ストアアプリ(LOB)構築のためのtips Prism 4.5 & Kona project 等のご紹介

193 Views

March 16, 13

スライド概要

profile-image

ヴイエムウェア株式会社 ソリューションアーキテクト本部 プリンシパルエンタープライズアーキテクト。 Microsoft で13年間、テクニカルエバンジェリストとして .NET、Visual Studio、Windows、iOS、Android、Microsoft Azure 等の開発者向け最新技術啓発活動を実施。その後、Dell、Accenture、Elastic で開発者向け技術啓発活動等を経て現職。 モダンアプリケーション開発、マルチクラウド対応、アーキテクチャ策定等を中心に、技術者向けに最新技術の啓発活動を実施中。 2019年4月〜2021年8月迄、内閣官房 IT 総合戦略室 政府 CIO 補佐官を兼務、2021年9月〜2024年3月迄、デジタル庁 PjM ユニット ソリューションアーキテクトを兼務。

シェア

またはPlayer版

埋め込む »CMSなどでJSが使えない場合

関連スライド

各ページのテキスト
1.

XAML /C# を使った Windows ストアアプリ(LOB)構築 TIPS - Prism 4.5 & Kona Project 等のご紹介 鈴木 章太郎 テクニカルエバンジェリスト 兼 MTC アーキテクト 日本マイクロソフト株式会社 http://blogs.msdn.com/b/shosuz/

2.

https://www.facebook.com/shosuz テクニカルエバンジェリスト http://blogs.msdn.com/b/shosuz MTC アーキテクト http://www.microsoft.com/ja-jp/business/mtc/ads.aspx 呟きネタは主に、Windows Azure, Windows、 Windows Phone, RIA, HTML5, MVVM, iOS/Android x Windows Azure連携, Guitar … 等 ASPIC 執行役員 (‘05 ~) Wipse モバイル x クラウド部会長(’11 ~) 2005-2012 早稲田大学大学院非常勤講師、 2008-2010 中央大学非常勤講師 Microsoft 軽音楽部 広報担当 (Gt./Key./DAW) (2012 ~)

3.

アジェンダ     

5.

Windows ストア LOB アプリ  LOB アプリケーションにも本格導入検討中の企業が多い  課題としては      既存のアプリケーションとの共存の方法 開発リソースの確保、技術研修等 既存アプリケーションの互換性確認の問題 Windows RT か Windows 8 Pro/Enterprise か 配布の方法(Windows ストア、SCCM、Active Directory、 Intune、他)

7.

データソースとしての選択肢  ストアアプリケーションは基本的にデータベース直接接続不可  LOB アプリケーションはヘテロな環境に追加される     新規に構築する and/or 既存のリレーショナルデータベース 新規に公開する and/or 既存の Web サービス 新規に構築する and/or 既存のコンテンツサーバー マスターデータが置かれているサーバー, etc.  ASP.NET MVC4 Web API か WCF Data Services か     データベース(特に SQL Server )は Data Services サービスの公開だと Web API が有用だが、LINQ で制限あり Data Services は RDBMS、Web API はそれ以外のもの 組み合わせて使う(Windows Azure の場合は Mobile Services もあり)

8.

百貨店の店舗用商品カタログのフロー例 XML-RPC マスター情報を検索 商品情報 を検索 REST 7:37 AM 画像 URLを 含む商品情 報を取得 画像 URL を検索 REST SharePoint Site se ar ch username http://sharepoint/url Site Actions Browse Page Parent > Parent > Current Page Page Title 画像情報を リクエスト 画像情報を 返す Current Page Page One Libraries Site Pages Shared Documents 画像 URL を取得 Drop Off Library Custom library Page Two This Site: site search マスター 情報を取得

11.

Entity Framework + Code First  クラスを作成してデータベースを作成     System.ComponentModel.DataAnnotations スキーマ修正、マイグレーション可能 テストデータを入れられる 新規サービス立ち上げやマッシュアップサービスの構築ニーズに合致  ASP.NET MVC4 Web API でも WCF Data Services でも利用可能  ただし前者の場合は、使いやすいようにクラス設計をすべき

13.

Web API によるサービスの公開  簡単に自動生成可能  コントローラ名決定  スキャフォールディング  オプションから選択  テンプレート  モデルクラス  データコンテキストクラス  クラスを適宜修正・追加  メソッドの追加、等

16.

Kona プロジェクトとは? • • •

17.

Kona Project とは? http://konaguidance.codeplex.com  CodePlex に公開された MVVM フレームワーク  Prism 4.5の一部を利用  C# / XAML に特化  Windows ストア LOB アプリ開発 のために最適化     設定・検索チャーム 各フレームへの遷移 バリデーション その他順次追加予定

18.

その前に Prism – 元々は… WPF, Silverlight, Windows Phone 開発用 • • • • • •

19.

Prism は Windows ストアアプリ向きか? • • • • • • Modularity UI Composition Region Navigation Decoupled Communication Commands MVVM Support

22.

1. Windows Phone 開発の経験を十分に活用する Windows Phone アプリ Windows ストアアプリ Deactivate/Tombstoned/Reactiv Suspend/Terminate/Resume ate Microsoft Push Notification Service (MPN) Windows Push Notification Service (WNS) Windows Phone Marketplace certification Windows Store app certification & Application Excellence Review (AER) App manifest declares capabilities App manifest declares capabilities

23.

2. AttachedBehavior にフォーカスする • AttachedBehavior の経験を活 かし、それにフォーカス  後からコントロールに動作を追加できる • • Blend のBehavior<T> → 使わない Expressions のバインディング → 使わない

24.

3. Push 通知には要 Windows ストア開発者登録 Windows ストアに、開発した アプリを申請し、正しいクレ デンシャルを取得する (SID 及びシークレットキー) • 完全にサイドローディングで 配布する前提で設計・開発を 行ったアプリからは、WNS (Windows Notification Service)を使ったプッシュ配 信はできない → 通知ハブ? •

25.
[beta]
4. .NET 4.5 の async と await を活用する
async Task<int> AccessTheWebAsync()
{
HttpClient client = new HttpClient();

Task<string> getStringTask =
client.GetStringAsync("http://msdn.microsoft.com");
DoIndependentWork();
string urlContents = await getStringTask;
return urlContents.Length;
}

26.

ページ遷移とナビゲーション

27.

5. LayoutAwarePage クラスの使用 ページ遷移、状態管理、および Visual State の管理のため Navigation support protected virtual void GoHome(object sender, RoutedEventArgs e) protected virtual void GoBack(object sender, RoutedEventArgs e) protected virtual void GoForward(object sender, RoutedEventArgs e) Visual state switching public void StartLayoutUpdates(object sender, RoutedEventArgs e) public void StopLayoutUpdates(object sender, RoutedEventArgs e) Process lifetime management protected override void OnNavigatedTo(NavigationEventArgs e) protected override void OnNavigatedFrom(NavigationEventArgs e) protected virtual void LoadState(Object navigationParameter, Dictionary<String, Object> pageState) protected virtual void SaveState(Dictionary<String, Object> pageState)

28.
[beta]
Navigation と Visual State のサポート
XAML:
<Button Click="GoBack"
IsEnabled="{Binding Frame.CanGoBack,
ElementName=pageRoot}

"Style="{StaticResource BackButtonStyle}“
/>

<UserControl
Loaded="StartLayoutUpdates"
Unloaded="StopLayoutUpdates“
>

29.
[beta]
LoadState と SaveState : SuspensionManager
protected override void SaveState(System.Collections.Generic.Dictionary<string, object> pageState)
{
var virtualizingStackPanel =
VisualTreeUtilities.GetVisualChild<VirtualizingStackPanel>(itemGridView);

if (virtualizingStackPanel != null && pageState != null)
{
pageState["virtualizingStackPanelHorizontalOffset"] = virtualizingStackPanel.HorizontalOffset;
}
}
protected override void LoadState(object navigationParameter,
System.Collections.Generic.Dictionary<string, object> pageState)
{
if (pageState != null && pageState.ContainsKey("virtualizingStackPanelHorizontalOffset"))
{
double.TryParse(pageState["virtualizingStackPanelHorizontalOffset"].ToString(),
out virtualizingStackPanelHorizontalOffset);
}
}

30.

6. Visual State のサポートによる landscape, portrait, fill, and snap <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="ApplicationViewStates"> <VisualState x:Name="FullScreenLandscape"/> <VisualState x:Name="Filled"/> <VisualState x:Name="FullScreenPortrait"> <Storyboard> ... </Storyboard> </VisualState> <VisualState x:Name="Snapped"> <Storyboard> ... </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups>

31.

グローバル対応

32.

7.グローバル対応 ロケールごとに分離されたリソース <ToolTip x:Uid=“PreviewCartoonizeAppBarButtonToolTip” Content=“Preview Cartoonization” … />

33.

Model-View-ViewModel Pattern

34.

8. ページ遷移: View First かViewModel First か View First: this.Frame.Navigate(typeof(ItemDetailPage), itemId); ViewModel First: Var itemDetailPageViewModel = new ItemDetailPageViewModel(…) { ItemId = itemId }; navigationService.Navigate(itemDetailPageViewModel);

35.
[beta]
9. BindableBase クラスの利用による
INotifyPropertyChanged の提供
public abstract class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
{
if (object.Equals(storage, value)) return false;
storage = value;
this.OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var eventHandler = this.PropertyChanged;
if (eventHandler != null)
{
eventHandler(this, new PropertyChangedEventArgs(propertyName));
}
}
}

36.

10. Kona ViewModelLocator の利用 • Convention ベースのルックアップ • • • MyNamespace.MyPage -> MyNamespace.MyPageViewModel ルールに基づく例外により Conventionのオーバーライドが可能 ViewModel をインスタンス化するのにコンテナを活用可能

37.

WPF/Silverlight における 典型的なバリデーション • • Implement INotifyDataErrorInfo UI コントロールでエラーのディクショナリにバインド • NotifyOnValidationError=True <TextBox Text="{Binding Id, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}"/>

38.
[beta]
11. Kona BindableValidator の利用
View:
<TextBox
Text="{Binding Address.FirstName, Mode=TwoWay}"
behaviors:HighlightFormFieldOnErrors.PropertyErrors=

"{Binding Errors[FirstName]}" />
----------------------------------------------------------------------------ViewModel:

_bindableValidator = new BindableValidator(_address);
public BindableValidator Errors
{
get { return _bindableValidator; }
}

39.

Decoupled Eventing • • • “ハリウッド式ペアレンタル スタイルの UI コンポジション” (ユーザーコントロール) 子コントロールは、長時間持続す るサービスにより発生したイベン トをリッスンする必要があるも、 自らそれを、取り外すことはでき ない Prism の EventAggregator 部分 をポーティング

40.

12. 必要に応じて EventAggregator 使用 public SubscriberViewModel(IEventAggregator eventAggregator) { eventAggregator.GetEvent<ShoppingCartUpdatedEvent>() .Subscribe(s => UpdateItemCountAsync()); } public PublisherViewModel(IEventAggregator eventAggregator) { _eventAggregator = eventAggregator; } _eventAggregator.GetEvent<ShoppingCartUpdatedEvent>() .Publish(string.Empty);

41.

Commanding と ViewModel Method Invocation ICommand: void Execute(object) bool CanExecute(object) event EventHandler CanExecuteChanged Command Invoker: ButtonBase ----------------------------------------------------Event -> Action

42.
[beta]
13. コントロールに
ICommand をサポートする DelegateCommand を使用
View:
<Button Content=“Go to shopping cart”
Command="{Binding ShoppingCartNavigationCommand}" />
--------------------------------------------------------------------ViewModel:
ShoppingCartNavigationCommand = new
DelegateCommand(NavigateToShoppingCartPage,
CanNavigateToShoppingCartPage);

ShoppingCartNavigationCommand.RaiseCanExecuteChanged();

43.
[beta]
14. AttachedBehavior や Action を使用する
View:
<GridView x:Name="itemGridView“
ItemsSource="{Binding Source={StaticResource groupedItemsViewSource}}"
ItemTemplate="{StaticResource KonaRI250x250ItemTemplate}"
SelectionMode="None“ IsItemClickEnabled="True"
behaviors:ListViewItemClickedToAction.Action=
"{Binding CategoryNavigationAction}">
---------------------------------------------------------------------------------ViewModel:
CategoryNavigationAction = NavigateToCategory;

44.

Suspend, Resume, 及びTerminate

45.

15. Kona RestorableStateAttribute と MVVM フレームワークの利用 public class MyViewModel : ViewModel, INavigationAware { private string _name; [RestorableState] public string Name { get { return _name; } set { SetProperty(ref _name, value); } } }

46.

16. Visual Studio との統合 Windows Azure Store Windows Phone Store

47.

ALM ソリューションの提供

48.

ALM ソリューションの提供

49.

クライアント Visual Studio Ultimate 2012 アプリケーション ライフサイクル全体を包括的にカバー Visual Studio Premium 2012 統合開発環境とテスト機能を搭載 Visual Studio Professional 2012 Visual Studio Test Professional 2012 開発機能を提供する統合開発環境 包括的なテストの実施と管理を支援 サーバー Visual Studio Team Foundation Server 2012 アプリケーション開発プロジェクトの統合開発基盤

50.

参考情報  Visual Studio 2012 導入事例  http://aka.ms/VS2012-Case  Visual Studio 2012 が提供する統合ソリューション  http://aka.ms/VS2012-Sol  Visual Studio 2012 製品ガイド(PDF, 16MB)  http://aka.ms/VS2012-Prod  Visual Studio 2012 試用版  http://aka.ms/VS2012-Try  Visual Studio 2012 ライセンス ホワイトペーパー  http://aka.ms/VS2012-Lic

51.

Resource  http://konaguidance.codeplex.com  英語版 OS でないと .exe は解凍できない場合あり  Source Code → Download で .zip を落としてください