利用 Windows Azure Mobile Services 輕鬆擴展 HTML App 的延展性

本文將介紹如何利用 Windows Azure Mobile Services 輕鬆擴展 HTML 網頁的延展性。

致謝

感謝點部落團隊舉辦 HTML 5 & JavaScript 程式開發實戰贈書活動,讓筆者有幸可以獲得這本好書。

摘要

Windows Azure Mobile Services 提供強大的推送(Push)、資料(Data)、排程器(Scheduler Preview)等多項功能來支援現在執行於各項行動裝置的 App,不只如此就連 HTML 網頁也可以輕鬆與 Mobile Services 整合,本文將介紹利用 Windows Azure 管理入口網站來建置與 Mobile Services 整合的 HTML 網頁並提升其延展性。

建立 Mobile Service

若您還沒有 Windows Azure 訂閱帳戶,建議可以去申請免費試用,申請完畢之後登入至 Windows Azure 管理入口網站後,依照下圖的步驟建立您的第一個 Mobile Service。

image

在【NEW MOBILE SERVICE】視窗中您需要輸入一個全球唯一的名稱,在輸入的同時 Windows Azure 會去檢查名稱是否可以使用,您的 Mobile Service 完整名稱會是【自訂名稱.azure-mobile.net】。另外您還必須建立一個 SQL Database,您可以選擇使用現在免費提供給您的 20 MB 的儲存空間,或是使用您現有的 SQL Database,然後選擇適當的 Windows Azure 訂閱帳戶之後就是選擇您的服務要使用哪個區域的資料中心,建議選擇離您將來目標使用者最近的資料中心,以台灣為例最近的資料中心是 East Asia。

image

預設的 SQL Database 名稱為【mobile_service名稱_db】,本文所使用的範例是免費的 20MB SQL Database 儲存空間,由於是第一次使用所以您必須建立 SQL Database Server(相當於企業內部部署 SQL Server時候的執行個體),接著輸入相關的登入資訊,在這個步驟所建立的登入名稱為 SQL Database Server 的管理員(相當於 sa),最後選擇資料中心建議使用和 Mobile Service 相同的區域。

image

按下上圖的完成後 Windows Azure 便會開始幫您建立 Mobile Service,此時 STASUS 會是處於 Creating 的狀態。

image

等 STATUS 變成 Ready 就表示 Mobile Service 已經建立完成,接著點選下圖中向右的箭頭來切換至 Mobile Service 的歡迎畫面。

image

建立新的 HTML App

每個 Windows Azure 上所提供的服務都有精心安排資訊相當豐富的歡迎畫面,Mobile Services 當然也不例外。當您進到您所建立的 Mobile Service 歡迎畫面中您可看到,Mobile Service 支援各種平台的 App 與之介接,就連非 Microsoft 陣營的 iOS、Andriod 也都支援,而本文著重在 HTML/JavaScript App,所以在歡迎畫面中點選【HTML/JavaScript > CREATE A NEW HTML APP】,Mobile Service 所提供的 App 範例是一個代辦事項的應用範例,因此必須先點選【Create TodoItem Table】來建立儲存代辦事項的資料表,稍等一下後出現 We have created the TodoItem table for you. 表示資料表已建立完成。

image

您可以點選頁面上方的【Data】來查看您的 Mobile Service 中有那些資料表。

image

第二個步驟便是下載 Mobile Service 幫您準備好的 HTML App, 請點選下圖的 Download。

image

下載的檔案會被打包為一個 ZIP 檔,解開之後您會看到如下圖的資料夾結構。

若您使用 Windows 平台請執行 server 資料夾中的 launch-windows 捷徑,如果是 MAC  平台則是執行 launch-mac.command,Linux 平台則是執行 launch-linux.sh。本文以 Windows 平台來做示範,執行 launch-windows 捷徑之後會開啟 IIS Express,來 host 您的 HTML App,預設網址為 http://localhost:8000。

打開瀏覽器輸入預設網址您會看到如下圖的畫面,在文字方塊中輸入您的代辦事項後按 Add,您所輸入的內容會透過 Mobile Service 來寫入到 SQL Database。

您可以在 Windows Azure 管理入口網站中看到上圖所建立的資料,如下圖:

也可以利用 SQL Database 管理入口網站來查看透過 HTML App 所輸入的資料,預設 TodoItem 的結構描述名稱為您的 Mobile Service 名稱。

重點剖析

Windows Azure Mobile Services 幫您建立的 HTML App 已經具備對 SQL Database 的 CRUD 功能,怎麼做的呢?其實重點在 page.js 這支 JavaScript,它使用 WindowsAzure.MobileServiceClient 來建立與 Mobile Service 的連接,只需要傳入 Mobile Service 的 URL以及 Application Key 兩個參數即可,接下來便是透過 getTable 來存取 SQL Database 上的資料表。

    var client = new WindowsAzure.MobileServiceClient('https://html5test.azure-mobile.net/', 'ybGTUMKeVYwPTCiYDoTNuOaLHVkFCo43'),
        todoItemTable = client.getTable('todoitem');

    // Read current data and rebuild UI.
    // If you plan to generate complex UIs like this, consider using a JavaScript templating library.
    function refreshTodoItems() {
        var query = todoItemTable.where({ complete: false });

        query.read().then(function(todoItems) {
            var listItems = $.map(todoItems, function(item) {
                return $('<li>')
                    .attr('data-todoitem-id', item.id)
                    .append($('<button class="item-delete">Delete</button>'))
                    .append($('<input type="checkbox" class="item-complete">').prop('checked', item.complete))
                    .append($('<div>').append($('<input class="item-text">').val(item.text)));
            });

            $('#todo-items').empty().append(listItems).toggle(listItems.length > 0);
            $('#summary').html('<strong>' + todoItems.length + '</strong> item(s)');
        }, handleError);
    }

    function handleError(error) {
        var text = error + (error.request ? ' - ' + error.request.status : '');
        $('#errorlog').append($('<li>').text(text));
    }

    function getTodoItemId(formElement) {
        return Number($(formElement).closest('li').attr('data-todoitem-id'));
    }

    // Handle insert
    $('#add-item').submit(function(evt) {
        var textbox = $('#new-item-text'),
            itemText = textbox.val();
        if (itemText !== '') {
            todoItemTable.insert({ text: itemText, complete: false }).then(refreshTodoItems, handleError);
        }
        textbox.val('').focus();
        evt.preventDefault();
    });

    // Handle update
    $(document.body).on('change', '.item-text', function() {
        var newText = $(this).val();
        todoItemTable.update({ id: getTodoItemId(this), text: newText }).then(null, handleError);
    });

    $(document.body).on('change', '.item-complete', function() {
        var isComplete = $(this).prop('checked');
        todoItemTable.update({ id: getTodoItemId(this), complete: isComplete }).then(refreshTodoItems, handleError);
    });

    // Handle delete
    $(document.body).on('click', '.item-delete', function () {
        todoItemTable.del({ id: getTodoItemId(this) }).then(refreshTodoItems, handleError);
    });

    // On initial load, start by fetching the current data
    refreshTodoItems();
});

其他 page.js 中的 JavaScript 為利用 jQuery 來針對 TodoItem 資料表的 CRUD,筆者在此就不多作介紹。

參考資料

- HTML5 & JavaScript 程式開發實戰 - 導讀

- Windows Azure Mobile Services

- Get started with Mobile Services

- Mobile Services Reference Docs

- 小朱® 的技術隨手寫 - Mobile Service

- 天空的垃圾場 - Windows Azure