Build a Hybrid Application with the Ionic Framework and Microsoft Azure Mobile Services

Introduction

In this post I’ll show you how to create a hybrid mobile application using the open source ionic framework and how to integrate the application securely to a Microsoft Azure Mobile Services backend. By integrating  with azure mobile service you get to connect to reliable cloud storage via a simple JavaScript SDK.

I’ve made the complete source code is available on GitHub  – feel free to fork the code or use it however you like.

Ionic Framework

Ionic is an open source JavaScript and CSS framework for building cross-platform HTML5 mobile applications. It’s built with Cordova and AngularJS and it comes with a nifty command life interface that lets you build  IOS and Android apps. My experience working with ionic has been really good. It is very easy to get started with ionic and there is a strong community behind with about 200 contributors to the codebase. Work is well underway to remove the dependency on AngularJS which means you’ll be able to plug the inoic framework into your JavaScript framework of choice in the near future.

Microsoft Azure Mobile Services

Microsoft Azure Mobile Services is a mobile backend as a service (MBaaS) offering from Microsoft. Almost every mobile application needs to store some data, deal with push notifications, service monitoring and authentication. With microsoft azure mobile services you get all of this as a “platform as a service” offering. You don’t need to spin up a single server to go live with a mobile app, simply provision yourself a mobile services backend in azure and  and you have access to all of these features along with a a fully programmable node.js or .NET backend.

The todo appapp I’ll take you through the key steps and code needed to build a simple todo mobile app. Users will authenticate with a google plus account. Once logged in they’ll be able to create new tasks and maintain a list of outstanding tasks.


Creating the ionic app

First up install apache cordova and the ionic framework via npm

1
2
npm install -g ionic
$ npm install -g cordova

Next,  create a new ionic application using one of the sidemenu starter template

1
$ ionic start Azure-Ionic-App sidemenu

That’s it! if you run the command “ionic serve” a browser will open running your application.The application we are building consists three simple views and controllers – login, add task, and  view all tasks.

Implementing Google Authentication

Firstly, create a new azure mobile service  via the azure portal. If you don’t have an account you can sign up for a free trial here. You’ll get more than enough credits with a trial account to develop  and test an application.

Once your mobile service is provisioned take a note of the mobile service url  on the dashboard page https://ionic-todo.azure-mobile.net this is your unique the API endpoint for your mobile app.

create mobile back end

The process of how to register your app for a google login is already well documented here . You’ll need to login to the google developer console, create a new web project and register for “Google +API” OAuth authentication then in the credentials tab, enter the authorization redirect URL for you application. This will be “your-mobile-services-url/login/google” , in my case its “https://ionic-todo.azure-mobile.net/login/google”google console

Now to associate your google application with the mobile service backend. Go back to the azure portal and enter the google client id and secret on the identity tab..

google register

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

To integrate a google login into your ionic application you’ll need to bundle the mobile services JavaScript client library with your application and add the following AngularJS factory class which returns a mobile service client object .

1
2
3
4
5
6
7
8
angular.module('azure', [])
  .factory('client', [function () {
    var client = new WindowsAzure.MobileServiceClient(
      "your-mobile-services-application-key"
    );
    return client;
  }]);

Using the client object we can take care of the OAuth flow by simply calling client.Login(“google”);

1
2
3
4
5
6
7
8
9
10
11
12
13
14   
//the login controller calls client.login("google") to perform the oAuth dance
angular.module('azure', [])
angular.module('app.controllers', ['azure'])
.controller('LoginCtrl', function(client,$scope, $state) {
    $scope.login = function() {
      client.login("google").then(function succes(data){
        console.log('logged in succesfully..')
        $state.go('app.list');
      }, function(error){
 
        //login failed.
      });
    }
  })

The OAuth flow happens in a separate browser window.You must install the Cordova InAppBrowser plugin from to be able to show the login popup on a mobile device. Run the following command to install the plugin locally

1
$ ionic plugin add cordova-plugin-inappbrowser

then add the plugin to your config.xml file to bundle it as part of the ionic build process.

1
2
3
4
<feature name="InAppBrowser">
  <param name="ios-package" value="CDVInAppBrowser"/>
  <param name="android-package" value="org.apache.cordova.inappbrowser.InAppBrowser"/>
</feature>

Once logged in, a user context is set on the client object. You can access this at any time by simply injecting the client factory class we created earlier into the relevant controller; client.currentUser.userId

We’ll store the unique userId property as part of each todo item in the data store to make the solution multi-tenanted and to ensure you only get to see your own todo list tasks, I know I for one don’t want to complete other peoples tasks!

Storing Data in Azure Mobile Services

When you provisioned a mobile services on azure  you also provisioned a SQL Server backend but chances are you won’t treat the backend like a relational database. When you provision a new table in the database it gets allocated a dynamic schema by default ( very cool but you can turn this off if you like). As you make API calls to store data in a table new columns are generated based on the properties of the JSON object you send to the API.

Go to the data tab in mobile services and a create a table called “Task” to store the todo items. Set the table permissions for insert, update,delete and read operations to “authenticated users”.  You can now read and write data to this table via the mobile services client factory class we created earlier.

Its worth highlighting that the backend API that writes to the database table is fully programmable and you can write node.js scriptlets to validate and transform your data before it gets written to the data store. If you’d prefer to write your data to a MongoDB or DocumentDB data store its pretty easy to swap out the database completely  – more information here

For the purposes of this post we won’t create any server side scriptlets, we’ll let the data go straight through to the tasks table.To keep the ionic application more modular I created a separate AngularJS factory to class to connect to the azure backend.

There’s a few things worth highlighting in the code

  • when saving data in the addTask() function I tack on a userId property.
  • when reading data in the getAll() function I create a filter expression to filter to return the tasks for the logged in user.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
4         8
angular.module('app.services', ['azure'])
  .factory('azureAPI', ['client' ,'$q', '$rootScope', function (client, $q, $rootScope) {
 
    return {
      getAll: function () {
        var deferred = $q.defer();
 
        var userId = client.currentUser.userId;
 
        //filter by user id
        client.getTable('Task').&amp;amp;lt;strong&amp;amp;gt;where({userId:userId})&amp;amp;lt;/strong&amp;amp;gt;.read().then(function () {
          deferred.resolve.apply(this, arguments);
          $rootScope.$apply();
        }, function () {
          deferred.reject.apply(this, arguments);
          $rootScope.$apply();
        });
 
        return deferred.promise;
      },
 
      addTask: function (task) {
 
        &amp;amp;lt;strong&amp;amp;gt;task.userId = client.currentUser.userId;&amp;amp;lt;/strong&amp;amp;gt;
        var deferred = $q.defer();
 
        client.getTable('Task').insert(task).then(function (data) {
          deferred.resolve.apply(this, arguments);
        }, function (error) {
          deferred.reject.apply(this, arguments);
        });
        return deferred.promise;
      },
 
      updateTask: function (task) {
        var deferred = $q.defer();
        task.userId = client.currentUser.userId;
 
        client.getTable('Task').update(task).then(function (data) {
          deferred.resolve.apply(this, arguments);
        }, function (error) {
          deferred.reject.apply(this, arguments);
        });
        return deferred.promise;
      }
 
    };
  }]);

That’s it. We’ve now hooked up google authentication and our mobile is storing data against a microsoft azure mobile services backend.

All the code is available here :

https://github.com/aidancasey/Azure-Ionic-App

Hope this helps

[출처] https://acaseyblog.wordpress.com/2015/10/07/build-a-hybrid-application-with-the-ionic-framework-and-windows-azure-mobile-services/

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
42 Public Key Tokens with sn 졸리운_곰 2017.05.27 188
41 [C#] 개체 참조가 개체의 인스턴스로 설정되지 않았습니다. [출처] C# : 오류 System.NullReferenceException: 개체 참조가 개체의 인스턴스로 설정되지 않았습니다.(오류 System.NullReferenceException) 졸리운_곰 2017.05.27 2354
40 private, public, protected 그리고 internal?? 접근 한정자에 대해 알아보자. 졸리운_곰 2017.05.27 163
39 [.NET Framework] .NET : 368. 닷넷의 어셈블리 서명 데이터 확인 방법 [링크 복사], [링크+제목 복사] file 졸리운_곰 2017.05.27 331
38 [Tips] Visual Studio 에서 특정 어셈블리의 PublicKeyToken 찾는 법 졸리운_곰 2017.05.27 409
37 .net의 publickeytoken 찾는 sn 프로그램 경로 졸리운_곰 2017.05.27 213
36 예외 문제 해결: System.BadImageFormatException 졸리운_곰 2017.05.27 932
35 A replacement for MemoryStream file 졸리운_곰 2017.05.20 197
34 [.net] jni4net 을 이용하여 c# .net 에서 .jar 파일 사용하기 file 졸리운_곰 2017.04.26 384
33 A Simple Crawler Using C# Sockets file 졸리운_곰 2017.04.24 273
32 ILSpy 닷넷 어셈블리 디컴파일러 오픈 소스 file 졸리운_곰 2017.04.22 428
31 C# WinForm "인증서 저장소에서 매니페스트 서명 인증서를 찾을 수 없습니다." file 졸리운_곰 2017.03.18 741
30 Getting started with SQLite in C# file 졸리운_곰 2017.03.18 286
29 C# c샾 c sharp 에서 SQLITE sqlite 사용 file 졸리운_곰 2017.03.18 266
28 Build a Hybrid Application with the Ionic Framework and Azure Mobile Services, Part 3: Wiring Up The Backend file 졸리운_곰 2017.02.06 251
27 Build a Hybrid Application with the Ionic Framework and Azure Mobile Services, Part 2: Creating the User Interface file 졸리운_곰 2017.02.06 224
26 Build a Hybrid Application with the Ionic Framework and Azure Mobile Services, Part 1: Configuring the Project file 졸리운_곰 2017.02.06 350
» Build a Hybrid Application with the Ionic Framework and Microsoft Azure Mobile Services file 졸리운_곰 2017.02.06 231
24 Get started with Ionic 2 apps in Visual Studio file 졸리운_곰 2016.11.20 1512
23 Windows 8.1 (윈도우 10) 에서 Visual Basic 6(VB6) 설치 방법 졸리운_곰 2016.10.16 1460
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED