Querying a database on Windows Phone 7 using WCF

I had a request to create a proof of concept app on how to connect a Windows Phone 7 Silverlight application to a SQL Server database hosted on a PC. Since the Windows Phone API does not allow the developer to connect directly to the SQL Server, one has to create a WCF (Windows Communication Foundation) service that will expose operations to interact with the database. Let’s do this! Source: http://sdrv.ms/XUd0CN

1. I’ll be using Northwind database for the sample, and I’m including it as part of the files for download. You can use any database you want, of course. First, let’s create a web service application. We’ll be using the ASP.NET empty website template for this matter.
image

2. Let’s create a new ADO.NET Entity Model, in order to use the powerful Entity Framework to do our job. We call it NorthwindModel
image

3. We generate it from database, choose to include sensitive data in our connection string, check the table “Customers” and check “Pluralize or singularize generated object names”.
image

4.We create a new *Silverlight-enabled” web service in our project. We call it “NorthwindService”.
image

5. We write the code for the web service, that queries the database (via the Entity Framework mechanisms) and returns all Customer objects

image

6. We press F5 and our service is ready! Don’t close the browser or stop the project, as we need it to be alive so that we can reference it via our Windows Phone project.

image

7. Let’s create our mobile application. We create a new Windows Phone Silverlight application

image

8. We create a ListBox (giving it the name “lst”) to display ContactName and City of the customers that we will fetch from the WCF service

image

9. We’ll use the “Add Service Reference dialog” so that our application can “see” the web service. We copy the url of the service from the browser, and enter it into the dialog.

image

10. We select to “use” the service reference via C#’s using statement. We also “use” the System.ServiceModel namespace.

image

11. We write the code for the service operation call and the Completed event handler

image

12. We press F5 and we are ready!!!!

image

Download the source here: http://sdrv.ms/XUd0CN

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s