Azure Mobile後端資料庫存取
當進行跨平台裝置專案開發過程中,大多會需要使用到後端資料庫存取服務,在這個範例中,將會為您說明使用 Microsoft Azure 所提供的 Azure Mobile App 服務。透過這個服務,可以讓開發者輕鬆的存取遠端資料庫或者企業內部的資料、進行AD或者社群身分驗證、線上與離線資料存取、行動裝置的訊息推播等等。
在這裡,僅僅針對如何透過 Azure Mobile Client 這個套件,來存取遠端的資料庫內的資料。
建立標籤式的樣板式頁面方案
- 首先,開啟您的 Visual Studio 2015
- 接著透過 Visual Studio 2015 功能表,選擇這些項目
檔案
>新增
>專案
準備新增一個專案。 - 接著,Visual Studio 2015 會顯示
新增專案
對話窗,請在這個對話窗上,進行選擇Visual C#
>Cross-Platform
>Blank Xaml App (Xamarin.Forms Portable)
- 接著,在最下方的
名稱
文字輸入盒處,輸入XFAzureMA
這個名稱,最後使用滑鼠右擊右下方的確定
按鈕。 - 當專案建立到一半,若您的開發環境還沒有建置與設定完成 Mac 電腦與 Xamarin Studio for Mac 系統,此時會看到
Xamarin Mac Agent Instructions
對話窗出現,這個對話窗是要提醒您進行與 Mac 電腦連線設定,這是因為,您無法在 Windows 作業系統進行 iOS 相關應用程式的建立與設計工作,而是需要透過 Mac 電腦安裝的 XCode 來協助您完成這些 iOS 應用程式的建立工作。不過,這不影響您繼續開發 Xamarin.Forms 的應用程式,只不過此時,您無法編譯與執行 iOS 的應用程式。 - 接著會看到
新的通用Windows專案
對話視窗,此時,您只需要按下確定
按鈕即可,此時,專案精靈會繼續完成相關平台的專案建立工作。 - 最後,整個新的 Xamarin.Forms 專案就建立完成了。
安裝所需 NuGet 套件
請在
方案 'XFAzureMa'
節點上,滑鼠右擊,接著點選 管理方案的 NuGet 套件
選項,接著點選 瀏覽
標籤頁次,在搜尋文字輸入盒中,輸入 Microsoft.Azure.Mobile.Client
這個套件,當找到這個套件之後,請將這個套件安裝到這個方案內的所有專案裡面。原生專案修正
為了要能夠讓
Microsoft.Azure.Mobile.Client
套件可以正常運作,此時,需要修改 XFAzureMA.Droid
,XFAzureMA.iOS
這兩專案內容。也就是要在這兩個專案內,分別加入底下程式碼。Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init();
XFAzureMA.Droid 專案
- 在 Android 專案內找到
MainActivity.cs
並且打開這個檔案 - 將底下程式碼複製到這個檔案內
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace XFAzureMA.Droid
{
[Activity(Label = "XFAzureMA", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init();
LoadApplication(new App());
}
}
}
XFAzureMA.iOS 專案
- 在 iOS 專案內找到
AppDelegate.cs
並且打開這個檔案 - 將底下程式碼複製到這個檔案內
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace XFAzureMA.iOS
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
}
}
MainPage
- 當上述準備工作已經就緒,接下來就可以開始在核心PCL專案內寫相關商業邏輯程式碼了。
- 打開核心PCL 的 MainPage.xaml 檔案,將底下的 XAML 宣告定義複製到這個檔案內。
- 這個頁面宣告內容相當簡單,使用版面配置
StackLayout
將其包含的控制項,以垂直的方式排列 - 後端的資料,將會透過
ListView
控制項來顯示,當需要重新整理資料的時候,可以在ListView
控制項的最上方,使用手勢由上往下滑動,即可抓取後端資料庫內最新的資料,顯示在畫面上了。 - 共有兩個按鈕,一個是會產生新資料,另外一個是將
ListView
點選的項目,予以刪除。
MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:XFAzureMA"
x:Class="XFAzureMA.MainPage">
<StackLayout
Orientation="Vertical">
<ListView x:Name="todoList"
Header="代辦事項"
IsPullToRefreshEnabled="true"
>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout HorizontalOptions="StartAndExpand" Orientation="Horizontal" Padding="15,5,0,0">
<StackLayout Padding="5,0,0,0" VerticalOptions="StartAndExpand" Orientation="Vertical">
<Label Text="{Binding Name}" />
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button x:Name="buttonAdd" Text="新增" Grid.Column="0"/>
<Button x:Name="buttonDel" Text="刪除" Grid.Column="1"/>
</Grid>
</StackLayout>
</ContentPage>
- 請將下列 C# 程式碼複製到 MainPage.xaml.cs內。
- 在
MainPage
類別內,定義了兩個屬性MobileServiceClient
,IMobileServiceTable<DoggyTodo>
,前者將會提供 Azure Mobile App 的服務,後者,則是提供DoggyTodo
這個資料表的存取動作。 - 在建構式內,首先產生
MobileServiceClient
物件,其中,需要 Azure Mobile App 的網址作為產生該物件的參數,當這個物件建立之後,就可以操控這個 Azure Mobile App 所提供的服務。接著,透過MobileServiceClient.GetTable<DoggyTodo>()
取得這個資料表,也就是這個應用程式要存取的代辦事項清單項目紀錄要存放的地方。接著訂閱各控制項需要用到的事件,並且進行相對應的處理。 - 要讀取後端資料,可以透過
await IMobileServiceTable<DoggyTodo>.ToListAsync();
取得,也可以透過 LINQ 進行過濾與排序。 - 要新增後端資料,可以透過
wait IMobileServiceTable<DoggyTodo>.InsertAsync(new DoggyTodo{Name = DateTime.Now.ToString()});
。 - 要刪除後端資料,可以透過
wait IMobileServiceTable<DoggyTodo>.DeleteAsync(fooItem);
。
MainPage.xaml.cs
using Microsoft.WindowsAzure.MobileServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace XFAzureMA
{
public partial class MainPage : ContentPage
{
MobileServiceClient client;
IMobileServiceTable<DoggyTodo> todoTable;
public MainPage()
{
InitializeComponent();
this.client = new MobileServiceClient("http://doggylab.azurewebsites.net");
this.todoTable = client.GetTable<DoggyTodo>();
todoList.Refreshing += TodoList_Refreshing;
buttonAdd.Clicked += async (s, e) =>
{
await todoTable.InsertAsync(new DoggyTodo
{
Name = DateTime.Now.ToString()
});
await Refresh();
};
buttonDel.Clicked += async (s, e) =>
{
if(todoList.SelectedItem != null)
{
var fooItem = (DoggyTodo)todoList.SelectedItem;
await todoTable.DeleteAsync(fooItem);
await Refresh();
}
};
}
private async void TodoList_Refreshing(object sender, EventArgs e)
{
await Refresh();
}
public async Task Refresh()
{
List<DoggyTodo> items = await todoTable.ToListAsync();
todoList.ItemsSource = items;
todoList.EndRefresh();
}
}
}
DoggyTodo 資料模型定義
- 請在 XFAzureMA 核心PCL 專案節點使用滑鼠右擊該節點,選擇
加入
>類別
,當加入新項目 - XFAzureMA
對話窗出現後,點選Visual C#
>類別
,最後在下方名稱欄位的文字輸入盒內,輸入DoggyTodo
。 - 請將底下 C# 程式碼複製到這個檔案內。
DoggyTodo.cs
using Microsoft.WindowsAzure.MobileServices;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace XFAzureMA
{
public class DoggyTodo
{
string id;
string name;
bool done;
[JsonProperty(PropertyName = "id")]
public string Id
{
get { return id; }
set { id = value; }
}
[JsonProperty(PropertyName = "text")]
public string Name
{
get { return name; }
set { name = value; }
}
[JsonProperty(PropertyName = "complete")]
public bool Done
{
get { return done; }
set { done = value; }
}
[Version]
public string Version { get; set; }
}
}
定義 Azure Mobile App 上的 簡易表
若您尚未使用過 Azure Mobile App,您可以參考 建立與設定 Azure Mobile App 文章;一旦,您完成了這篇文章上的操作,接著,就可以透過 Azure Mobile App 產生一個新的簡易表。請點選
簡易表
> Add
,接著在最右方的刀鋒視窗內 Name
欄位下,輸入 DoggyTodo
,最後按下 確定
按鈕。請參考下圖。
實際執行畫面
Android 執行結果
請在方案總管內,滑鼠右擊
XFAzureMA.Droid
專案,選擇 設定為起始專案
,接著按下 F5
開始執行。

底下是在 Azure Mobile App 上查詢 DoggyTodo 資料表的內容。

佈署注意事項
iOS 執行結果
請在方案總管內,滑鼠右擊
XFAzureMA.iOS
專案,選擇 設定為起始專案
,接著按下 F5
開始執行。

底下是在 Azure Mobile App 上查詢 DoggyTodo 資料表的內容。
