Windows 8 アプリとデータベース/サービスとの連携 – ② バックエンド Web サービス作成

皆様、こんにちは!

引き続き、9/2(火) タッチ/ペン対応アプリの開発とクラウドを活用した既存サービスとの接続方法のセミナーでの、私が担当したセッション ”Windows 8 アプリでのデータベース/サービスとの接続 “ の詳細情報とコードにつき、ご紹介していきたいと思います。

Web サービス作成とデータ公開

Windows ストアアプリからリモートデータを使用するためには、なんらかの REST または SOAP サービスが公開されている必要があります。ASP.NET Web APIは、ASP.NET MVC 4からサポートされたHTTPによるリクエストを受けるRESTfulなサービスです。このサンプルでは、ASP.NET Web API を使って、Windows ストアアプリから基本的なデータ操作ができるようなサービスを作成します。

image

当該ソリューションを右クリックし、新しいプロジェクトの追加、を選択しクリックします。Web テンプレートから、ASP.NET Web Application を選択し、名前を適当につけ(ここでは RestService)、OK ボタンをクリックします。

 

image

次に出てくるダイアログボックスで、Web API を選択し、OKをクリックします。

※ この図を見て戴くとお分かりの通り、Windows Azure の箇所で、クラウド内のホストにチェックが入っていますが、ここではまだクラウドには発行しないので、チェックを外しておいてください。

image

これで、RestService の初期のスケルトンが作成されます。ここでいったんソリューションのビルドを行ってください。

コントローラーの実装

次に、このプロジェクトから**TimeSale** **プロジェクトに参照設定を追加**し、次いで、コントローラーを実装します。RESTService プロジェクトのController フォルダーを右クリック->追加->コントローラーを選択します。

image

スキャフォールディングの追加からEntity Framework を使用したアクションがあるWebAPI 2コントローラーを選んで、

image

コントローラー名は、TimeAppSaleController という名前にして、データコンテキストには自動的にTimeSaleAppContextが入っているのを確認して、モデルクラスからは、 ProductWithPriceを選びます。 コントローラー名の下の 非同期コントローラーアクションを使用します にチェックを入れて、OK をクリックします。

image

そうすると、下記のコントローラーが自動生成されます。

    1: using System;
    2: using System;
    3: using System.Collections.Generic;
    4: using System.Data;
    5: using System.Data.Entity;
    6: using System.Data.Entity.Infrastructure;
    7: using System.Linq;
    8: using System.Net;
    9: using System.Net.Http;
   10: using System.Web;
   11: using System.Web.Http;
   12: using TimeSale;
   13:  
   14: namespace RESTService.Controllers
   15: {
   16:     public class TimeSaleAppController : ApiController
   17:     {
   18:         private TimeSaleAppContext db = new TimeSaleAppContext();
   19:  
   20:         // GET api/TimeSaleApp
   21:         public IEnumerable<ProductwithPrice> GetProductwithPrices()
   22:         {
   23:             return db.ProductwithPrices.AsEnumerable();
   24:         }
   25:  
   26:         // GET api/TimeSaleApp/5
   27:         public ProductwithPrice GetProductwithPrice(int id)
   28:         {
   29:             ProductwithPrice productwithprice = db.ProductwithPrices.Find(id);
   30:             if (productwithprice == null)
   31:             {
   32:                 throw new HttpResponseException
   33: (Request.CreateResponse(HttpStatusCode.NotFound));
   34:             }
   35:  
   36:             return productwithprice;
   37:         }
   38:  
   39:         // PUT api/TimeSaleApp/5
   40:         public HttpResponseMessage PutProductwithPrice(int id, ProductwithPrice 
   41: productwithprice)
   42:         {
   43:             if (ModelState.IsValid && id == productwithprice.StoreId)
   44:             {
   45:                 db.Entry(productwithprice).State = EntityState.Modified;
   46:  
   47:                 try
   48:                 {
   49:                     db.SaveChanges();
   50:                 }
   51:                 catch (DbUpdateConcurrencyException)
   52:                 {
   53:                     return Request.CreateResponse(HttpStatusCode.NotFound);
   54:                 }
   55:  
   56:                 return Request.CreateResponse(HttpStatusCode.OK);
   57:             }
   58:             else
   59:             {
   60:                 return Request.CreateResponse(HttpStatusCode.BadRequest);
   61:             }
   62:         }
   63:  
   64:         // POST api/TimeSaleApp
   65:         public HttpResponseMessage PostProductwithPrice(ProductwithPrice 
   66: productwithprice)
   67:         {
   68:             if (ModelState.IsValid)
   69:             {
   70:                 db.ProductwithPrices.Add(productwithprice);
   71:                 db.SaveChanges();
   72:  
   73:                 HttpResponseMessage response = 
   74: Request.CreateResponse
   75: (HttpStatusCode.Created, productwithprice);
   76:                 response.Headers.Location = new Uri
   77: (Url.Link("DefaultApi", new { id = productwithprice.StoreId }));
   78:                 return response;
   79:             }
   80:             else
   81:             {
   82:                 return Request.CreateResponse(HttpStatusCode.BadRequest);
   83:             }
   84:         }
   85:  
   86:         // DELETE api/TimeSaleApp/5
   87:         public HttpResponseMessage DeleteProductwithPrice(int id)
   88:         {
   89:             ProductwithPrice productwithprice = db.ProductwithPrices.Find(id);
   90:             if (productwithprice == null)
   91:             {
   92:                 return Request.CreateResponse(HttpStatusCode.NotFound);
   93:             }
   94:  
   95:             db.ProductwithPrices.Remove(productwithprice);
   96:  
   97:             try
   98:             {
   99:                 db.SaveChanges();
  100:             }
  101:             catch (DbUpdateConcurrencyException)
  102:             {
  103:                 return Request.CreateResponse(HttpStatusCode.NotFound);
  104:             }
  105:  
  106:             return Request.CreateResponse(HttpStatusCode.OK, productwithprice);
  107:         }
  108:  
  109:         protected override void Dispose(bool disposing)
  110:         {
  111:             db.Dispose();
  112:             base.Dispose(disposing);
  113:         }
  114:     }
  115: }

RESTServiceスタートアッププロジェクトに設定して、実行します。

image

Internet Explorer が起動したら、下記のアドレスを入力します : ※ ポート番号は適宜読み替えてください。

https://localhost:61495/api/TimeSaleApp

image

”ファイルを開く”を選択するとメモ帳が立ち上がり、データベースから全ての Products が取得できます。

image

このデータは、前回実行した TimeSaleTest コンソールアプリケーションが挿入したものです。

※ .json ファイルを、メモ帳にあらかじめ関連付けしてあります。

以上です。次回は最後の箇所、Windows ストアアプリとの連携で、このデータをコントロールに張り付けて、CRUD処理を追加します。

鈴木 章太郎