Build a Hybrid Application with the Ionic Framework and Azure Mobile Services, Part 3: Wiring Up The Backend

In Part 2 of this series I discussed how to set up our mobile user interface with Ionic and we prepared our Angular controllers and views to accept data from our Azure Mobile Service backend. In this article, we are going to create our Azure Mobile Service, publish it to the cloud, and start sending and receiving real data from within our Ionic application. Without further ado, let’s get started!

Creating the Azure Mobile Service

Prerequisite: To follow along you will need a Windows Azure account. All services utilized in this tutorial are free.

Before we make any modifications to our Ionic application we need to first create our Azure Mobile Service. To do this, log into your account and proceed to the Azure portal. From here, follow these steps:

1.) In the left pane, click on Mobile Services.
2.) In the bottom left corner, click New beside the + sign.
3.) Select Compute > Mobile Service > Create

Create Mobile Service

Create Mobile Service

4.) Enter the requested URL for your mobile service and select the database and region. Azure offers a free 20mb SQL server database to get you started. For backend select .NET as that is what we will be using for this demo. (JavaScript backend is also an extremely viable option and is generally easier to get up and running.)

Database Options

Database Options

5.) Next, enter a login and password for your mobile service database.

*At this point Azure will take a minute or so to create your database and mobile service. Once complete, click on the mobile service tab and select your service from this list provided.

6.) Under Get Started select Connect an existing HTML app.
7.) Select and download the provided solution under ‘Download and publish your service to the cloud‘.

Download Solution

Download Solution

8.) Before you exit, select Configure from the top navigation menu. Scroll down to Cross-Origin Resource Sharing (cors) and add an allowed origin of *. This will allow our mobile application (with the proper API-KEY) to access our service. *Update* As pointed out in the comments below Android users may also need to install the cordova whitelist plugin to properly fetch the data from our AMS API.

Configure CORS

Configure CORS

Configure and Publish the Mobile Service

Open the solution that you downloaded from step 7 in the previous section. In it you will find the basic boilerplate needed to get started creating our backend service using .NET and Entity Framework code first. Let’s begin customizing this solution to fit our needs.

1.) As a quick cleanup, delete the sample Todo model and controller that came with the solution.
2.) Next, under the Data Objects folder, let’s create our Goal entity that we will use in our Goal Setter application.

3.) Under the Models folder, edit your DbContext class to include your Goal DbSet (and delete the Todo DbSet). This will tell Entity Framework code first to create this as a table in our database.

4.) At this point we are ready to scaffold our database using Entity Framework Code First Migrations. Open up the Package Manager Console and run the following commands.

5.) Now that we have our database, let’s add a pre-built Azure Mobile Service controller. Right click on the controllers folder and select Add > Controller > Microsoft Azure Mobile Services Table Controller. This will give us all we need to start performing CRUD operations against our database through our Ionic mobile application. For more advanced scenarios and custom use cases, it will likely be best to create your own custom Web API controllers to fit the needs of your business or application.

6.) To test that everything is working, hit F5 to run the project. When the browser window appears click Try it out. Your service end points will be automatically documented for you and sample request and response for each endpoint provided. It’s time to publish our solution to the cloud!

Automatic Documentation

Automatic Documentation

Publishing to Windows Azure

Now that we have our mobile service solution built, let’s publish it to the cloud so we can hit it from within our Goal Setter application.
1.) From within Visual Studio right-click on your main project file and select Publish. Since we are using the solution preconfigured for us when we created our mobile service our publish profile will already be completed with the appropriate information.

2.) Click on the Preview tab and select Publish. After a minute or so a browser window will pop up and if all went well you will see a message stating your mobile service is up and running. Now let’s hook up our mobile application to talk to our newly published service!

Publish Confirmation

Publish Confirmation

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

Wiring Up the Mobile Application

From within your favorite IDE open up the GoalSetter project. It’s time to swap out our fake data with the legitimate backend we just created.

1.) Download the required Azure Mobile Services JavaScript file and add it to your project.

2.) To make interacting with our service through Angular more straightforward let’s also download and include a helper library from Terry Moorell, Angular-Azure. This Angular module will wrap our Azure service calls in Angular promises, making it dead simple to send and receive our application data.

3.) Add a reference to the Angular-Azure module in your main app.js module as well as an app wide constant for your API URL and API Key. This information can be found under your Azure mobile service on portal > Get Started > Connect an Exisiting HTML App > Connect your app and store data in your service.

 

4.) Next, let’s update our GoalSetterFactory.js to make calls to our cloud service. First, inject the ‘Azureservice’ module we included in the previous step then modify the public API to use this service. We will also include $ionicLoading in order to display a ‘Loading…’ message while our data is being sent and retrieved.

5.) It’s time to update our Goal controller to interact with our mobile service. Please note we will also need to modify the goal dates returned from our service to compare and display as MM/DD/YYYY format. I added a GoalSetterHelper factory to the project to contain this logic and any other basic functions that may be needed throughout the application. All other changes to the controller are minimal.

5.)Next, we need to update our create-goal.html page with some basic validation to require both fields and ensure a date is being entered in a valid format. To accomplish this we will use Angular’s built in form validation and disable the submit button while the form is not valid using ng-disabled.

6.) The last thing we need to do is update our Statistics controller to properly adjust the dates being returned from our service.

Test Run the App!
Now that all of our adjustments are complete and our Azure Mobile Service is up and running, let’s see it in action to ensure everything is working properly. Open up your command line from the root of the Goal Setter application and run these commands.

Navigate to the Goals tab and select Add New Goal. Fill out the form and submit, you will now see the newly added goal appear in your Goal’s page, straight from our Azure Mobile Service. Checking and unchecking the goal will also update the goal’s status in your database.

Add Goal Screen

Add Goal Screen

Goal Added to DB

Goal Added to DB

Conclusion
We now have a fully functional mobile application communicating with an Azure Mobile Service backend. In the next article, we will discuss how to add caching to our application as well as incorporating ngCordova to store our data locally to the device. All code for this article can be found on GitHub. As always, if you have any questions or run into any issues feel free to drop me a comment. Until next time, happy coding!

 

[출처] http://briantroncone.com/?p=391

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
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
» 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
25 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