Friday, May 31, 2013

Using WCF and Entity Framework with PhoneGap

I blogged before about using VS to edit PhoneGap applications and use chrome emulator to test it. Now we will use jQuery in PhoneGap application to access WCF services and return objects in JSON.

First we created a phonegap application

Then we hosted it on IIS and open in VS
File==>Open Website ==> Local IIS ==> create a new virtual directory
                                                                       Give Alias Name
                                                                         Browse to the project to the folder of the phonegap


Next we will create a new Website in another VS instance, to host the WCF service. It must be created on IIS to be tested on the emulator. So don't create it in the FileSystem must use HTTP.


No I have HelloService created on my IIS.
Delete the Service.svc created by default and then Add new Item to the project ==> Ajax Enabled WCF Service.


Now we have HelloService.svc


Now we will modify the DoWork function to return string


I added [WebGet] attribute to the method to be called using 'GET' method, so that we can test it in the browser. If it is not added and we typed the URL to the method in the browser we get "Method not allowed" error.

Now when tested it gets
The string is sent in a json format, in a member called d.

So now we need to call it from ajax function in PhoneGap app.

The following code does this

First, I used deviceready event from phonegap api. It fires once Cordova has fully loaded. After the device has fired, you can safely make calls to Cordova function.
In its call back function, I used jQuery.ajax method (don't forget to add jQuery library).

 In the url option, you put the url to your WCF service. Do not use localhost, you must use an IP. Since localhost to the emulator means itself.

Now when running the code on the emulator, You must also use IP in the URL to the application.
for example: http://192.168.1.103/Hello/assets/www/index.html




Now if we have an object we need to retrieve.
I created a simple book database and created a new ADO.Net Entity Data Model and called it BookModel.edmx

And used it to return to the application a list of books. Next is the code written in the service method and after it is shown the return when called in the browser.


Next is the javascript code added to the success callback of the ajax request. It took the returned array and created table rows to show the BookId and BookName

The result is


It is better to create light weight versions of the Model objects to send. Since I need only the ID and Name, it is a waste to send all the rest of the data to mobile application. In mobile applications, data send or received means money paid, so we need to be careful .

For example:

class LightBook{
                         int bookId{set; get;}
                         string bookName{set;get;}
}


Thanks,
Nerdy Geeky J!







No comments:

Post a Comment