Contenu connexe Similaire à 透過 Windows Azure Mobile Services 開發各平台 Apps Similaire à 透過 Windows Azure Mobile Services 開發各平台 Apps (20) Plus de Eric ShangKuan (16) 透過 Windows Azure Mobile Services 開發各平台 Apps2. Agenda
• Windows Azure Mobile Service 平台介紹
• 各平台 App 開發實作
• 深入剖析 WAMS
4. Mobile Services
快速建立 app 的「後端」
資料儲存、身份驗證以及推送通知
REST API
目前官方提供 Windows 8, Windows Phone
8 以及 iOS SDK
6. 為什麼要使用 Mobile Services?
• 不必撰寫維護雲端程式
專心在 app 端開發
RESTful API 不限定單一 app 平台使用
• 提供 app 開發的基礎建設
彈性擴充
資料儲存、身份驗證、推播通知
官方釋出主流平台 SDK
9. 開發一個 App…
不使用 WAMS 使用 WAMS
• 開發伺服器應用程式 • 在 Windows Azure 後台建立一個新的
• (server-side) 定義並實作 REST API, WAMS 服務
並且使用 JSON 資料格式 • 下載欲開發平台 SDK
• (server-side) 實作 sql/nosql 處理不 • (client-side) 使用 SDK 直接處理資料儲
同的資料儲存需求 存、身份驗證、推播通知等功能
• (server-side) 實作各身份驗證機制
• (client-side) app 開發,並且直接介
接 REST API
10. 自己寫 Server-side 及 Client-side
Server-side 處理 POST Client-side 寫介接程式碼
// POST api/todo public static async void CreateTodo(Todo todo)
public HttpResponseMessage PostTodo(Todo todo) {
{ string serviceUrl = "http://example.com/path/to/todo";
if (ModelState.IsValid)
{ using (HttpClient client = new HttpClient())
db.Todos.Add(todo); {
db.SaveChanges(); DataContractJsonSerializer serializer = new
DataContractJsonSerializer(typeof(Todo));
HttpResponseMessage response =
Request.CreateResponse(HttpStatusCode.Created, todo); using (MemoryStream stream = new MemoryStream())
response.Headers.Location = {
new Uri(Url.Link("DefaultApi", new { id = serializer.WriteObject(stream, todo);
todo.TodoId })); stream.Seek(0, SeekOrigin.Begin);
return response;
} var json = new StreamReader(stream).ReadToEnd();
else
{ var response = await client.PostAsync(serviceUrl as string,
return new StringContent(json, Encoding.UTF8, "application/json"));
Request.CreateResponse(HttpStatusCode.BadRequest); response.EnsureSuccessStatusCode();
} }
} }
}
11. 使用 Windows Azure Mobile Services
在管理後台設定 Client-side 使用 SDK 寫
public static MobileServiceClient service = new MobileServiceClient(
"https://你的WAMS.azure-mobile.net/",
"這裡放上你的 Key"
);
private IMobileServiceTable<Todo> table =
service.GetTable<Todo>();
private async void InsertTodoItem(Todo todo)
{
await table.InsertAsync(todo);
}
12. 診斷、記錄和擴充
診斷 擴充 - 運算
API 呼叫 向外擴充執行個體計數
CPU 時間 向上擴充 VM 大小
資料輸出
記錄 擴充 - 儲存體
將行動服務租用戶向外擴充到
console.error(…) 專用的 SQL DB
console.log(…)
向上擴充 SQL 資料庫
13. 預覽時期的免費額度
10個行動服務 1GB SQL
資料庫
從 WA 免費試用
在共用執行個體上
執行
預覽期間無 SLA。只能使用小型執行個體。在預覽期間,可以 33% 的折扣從
標準隨用隨付費率升級到保留執行個體。
14. 服務價格
共用執行個體 保留執行個體 預覽階段
(多租用戶環境) (私人 VM) 無 SLA
只提供小型執行個體, 只提供小型執行個體,
可以購買多個執行個體 可以購買多個執行個體 公開上市
99.9%
公開預覽上市時免費 預覽收費將會使用與網站
相同的減價費率
最多 10 個應用程式
最多 10 個應用程式
16. MobileService SDK for Windows 市集應用程式
使用 C# 使用 JavaScript
• 專案中加入 Windows Azure Mobile • 專案中加入 Windows Azure Mobile
Services Managed Client 的參考 Services JavaScript Client 的參考
• Microsoft.WindowsAzure.MobileSer • 引入
vices 的 namespace /MobileServicesJavaScriptClient/Mob
• API 參考文件: ileServices.js 檔案
http://msdn.microsoft.com/en- • API 參考文件:
us/library/windowsazure/jj589724.aspx http://msdn.microsoft.com/en-
us/library/windowsazure/jj554207.aspx
17. 存取資料
使用 C# 使用 JavaScript
// 建立連接 Mobile Service 物件 // 建立 MobileService 的 client 物件
public MobileServiceClient MobileService = new var client = new
MobileServiceClient( Microsoft.WindowsAzure.MobileServices.MobileServiceClient(
"https://你的服務名稱.azure-mobile.net/", "https://你的服務名稱.azure-mobile.net/",
"你服務的存取金鑰" "你服務的存取金鑰"
); );
// 取得資料儲存的 table,並且指名是 TodoItem 的資料結果 // 取得儲存資料的 table
private IMobileServiceTable<TodoItem> todoTable = var todoTable = client.getTable('TodoItem');
MobileService.GetTable<TodoItem>();
// 呼叫 insert 方法將 JavaScript 物件儲存到 table 中,
// 插入資料,並且符合 .net 4.5 的非同步程式撰寫模式 // 會根據物件的欄位來存放資料。並且符合 Windows Store App
await todoTable.InsertAsync(todoItem); // 中的非同步呼叫程式撰寫模式 可結合後續操作
todoTable.insert(todoItem).done(function (item) {
// 讀取資料,並且附上過濾條件 // 完成呼叫後做的事
items = todoTable });
.Where(todoItem => todoItem.Complete == false)
.ToCollectionView(); // 讀取資料並且附上 query 的條件
todoTable.where({ complete: false })
.read()
.done(function (results) {
// 完成呼叫後做的事
});
18. 身份驗證服務
• 簡單完成 Microsoft Account, Facebook, Google 以及 twitter 的
身份驗證機制
• 提供 Callback URL 完成 OAuth 2.0 的驗證流程
不必自行處理 Web Server
• 僅可取得各服務的 User Id (類似流水號),需要取得更詳細的內
容或權限還是要自行實作各服務的 API
可用來配合資料儲存作區別
19. 身份驗證
使用 C# 使用 JavaScript
MobileServiceUser user; var userId = null;
private async void Auth() var login = function () {
{ return new WinJS.Promise(function (complete) {
while (user == null) // 呼叫 login 開始登入及授權流程
{ client.login('facebook').done(function (results) {
try userId = results.userId;
{ // 登入且授權完成
user = await MobileService.LoginAsync( }, function (errors) {
MobileServiceAuthenticationProvider.Facebook); // 登入但不授權
// 登入或授權成功 });
} });
catch (InvalidOperationException) };
{
// 登入或授權失敗 var auth = function () {
} login().then(function () {
} if (userId === null) {
} // 登入或授權失敗
auth(); // 再試一次
}
});
};
auth();
Ref: http://www.windowsazure.com/en-us/develop/mobile/tutorials/get-started-with-users-dotnet/
22. 推播通知 (push notification)
使用 C# 使用 JavaScript
CurrentChannel = await var channel;
PushNotificationChannelManager.CreatePushNotificationChannelF var channelOperation = Windows.Networking.PushNotifications
orApplicationAsync(); .PushNotificationChannelManager
.createPushNotificationChannelForApplicationAsync()
.then(function (newChannel) {
channel = newChannel;
// channel.uri 即可送給 mobile service 作為送推播通知的路徑
}, function (error) { console.log(error.message); });
Ref: http://www.windowsazure.com/en-us/develop/mobile/tutorials/get-started-with-push-
dotnet/
27. REST API
• 在官方尚未釋出該平台或語言的 SDK 時,可直接以呼叫
REST APIs 的形式來使用 WAMS 的服務
任何應用程式 ( web、desktop、…) 都可以運用
• 提供彈性可自行撰寫資料匯入、匯出或是管理界面
• 參考官方文件以瞭解目前的支援:
http://msdn.microsoft.com/library/windowsazure/jj710108.aspx
28. REST API 使用範例 – 新增資料
POST /tables/TodoItem HTTP/1.1
Host: example.azure-mobile.net
Accept: application/json
Content-Type: application/json
Content-Length: 16
X-ZUMO-APPLICATION: THE_APPLICATION_KEY
{"text":"hello"}
200 OK
Content-Type: application/json
Content-Length: 23
{"id":1,"text":"hello"}
30. Android 寫入資料範例
URL url = new URL("https://你服務的名稱.azure-mobile.net/tables/表格名稱");
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setRequestMethod("POST");
urlConn.addRequestProperty("Content-Type", "application/json");
urlConn.addRequestProperty("ACCEPT", "application/json");
// 在 Request Header 填入服務金鑰
urlConn.addRequestProperty("X-ZUMO-APPLICATION", "你的服務金鑰");
DataOutputStream wr = new DataOutputStream(urlConn.getOutputStream());
// 寫入 JSON 格式的資料
wr.writeBytes("{"text":"Hello"}");
wr.flush();
wr.close();
32. 使用 Scripts 管理資料
• JavaScript-based (ECMAScript5)
• 客製資料在 insert, update,
delete, read 時的程序
• 在管理後台上直接修改
• Windows Azure 提供模組及物
件來完成複雜的操作
33. Server Script 使用情境
• 在 CRUD 時要修改欄位,或是其它的特殊處理
• 完成 CRUD 操作後,修改回應的內容
• 自訂 SQL 查詢語法 (透過 mssql.* 模組)
• 發送推播通知 (透過 push.wns.* 模組)
• …