(X) Hide this
    • Login
    • Join
      • Say No Bots Generate New Image
        By clicking 'Register' you accept the terms of use .

Connecting Azure and Windows Phone through OData

(7 votes)
Samidip Basu
>
Samidip Basu
Joined Aug 22, 2011
Articles:   16
Comments:   24
More Articles
3 comments   /   posted on Sep 06, 2011
Categories:   Data Access , Windows Phone
Tweet This!

Windows Azure & Windows Phone seem to be two very popular technologies out of Redmond right now. 

There is obviously a lot of buzz around cloud infrastructure involving Azure solutions and the wonderful developer story that we have for Windows Phone development. But, should these two platforms work together & if so, can they? How can you as a Mobile/Windows Phone developer utilize the cloud?

In this article, we talk about how to leverage Windows Azure to supplement our Windows Phone application. In particular, we will see how SQL Azure can be rather beneficial in providing globally accessible & scalable backend for mobile solutions on Windows Phone & other disparate platforms. The key link we shall leverage is OData Services for providing cross-platform read/write access to a central data repository.

Practicality

First, some caveats.  As you  consider a solution for your Windows Phone application leveraging Azure as the backend, it is always good to do some feasibility checks to make sure that the approach makes sense. As Windows Phone & other mobile platforms have shown us, smartphones do a lot with their small batteries & any work we can offload from their processing power, helps in increasing battery life & hence user experience. So, cloud/external augmentation of mobile solutions makes a lot of sense and Azure can provide a stable & elastic cloud support. However, it may not be suited for all, given the expenses. If you have MSDN licensing, you get a fair amount of Azure benefits free .. find out details here . These Azure benefits should be more than enough for you to play around for feasibility or even keep a couple of simple hosted solutions running 24/7. However, you may be in shady territory if you are making money off of a Windows Phone app with cloud support for which you are using MSDN benefits that have been paid for by your employer. And if you are paying for Azure time out of your pocket, you need to make sure you can economically justify the cost of the cloud support you are utilizing. In essence, what I am saying is Azure can be a wonderful companion to your Windows Phone solution, if you are sure that the economics of it make sense.

What you need to follow along

Here are the software/subscriptions you need to get started:

  • An Active Windows Azure subscription. Utilize your MSDN benefits by starting here or head over here to get a free trial.
  • Visual Studio 2010 with Service Pack 1
  • Windows Phone SDK 7.1 SDK RC found here
  • Optionally, Entity Framework 4.1 available here or as a Nuget

Download Source Code here.

 

Please note that in the Windows Phone project source code, the actual Reference to the Azure OData Service has been dummied up for confidentiality reasons. Everything should compile; but you will have to point the Service Reference to your own similar OData service for it to work.

 
The Prelude

Say, you are trying to write a To-Do/Shopping List application for Windows Phone .. Great! However, as much as we love it, our Windows Phone, or for that matter, any smartphone is not a great form factor for a lot of data entry. So ideally, you may consider giving your users an alternate view of the data that is handled by your application. Wouldn't it be nice if I could log on to a website, and set up my To-Do lists or Shopping lists, only for the same lists to show up on my Windows Phone app? Further, changes made from the Windows Phone app should be reflected back in the data source so you can see the updates from a webpage & vice versa.

To support such an approach, we are going to need a central repository/database which is easily accessible & updateable from multiple platforms like web and Windows Phone or other mobile platforms. This is where Windows Azure may come in very handy!

 

SQL Azure Database & the Backend Service

Let us begin with a SQL Azure data store. You my think of SQL Azure to be almost the same as a regular SQL Server, except it is running as a service in the Azure infrastructure and has a whole lot of plumbing underneath to support failovers, replication, billing & OData services etc. But, for you as a developer, your interaction with a SQL Azure Database should be no different than communicating with a local/remote SQL Server. So essentially, if we can maintain a global Database in SQL Azure, and provide secure access to data to various client platforms, we may be able to achieve what we set out trying .. right?

As you will see in the screenshot below, I have gone to the Azure Developer portal (here), chosen a subscription & created a SQL Azure server:

SQL Azure Server

 

As you can see above, the highlighted URL showing the “Fully Qualified DNS Name” is important. This is what you will use in the Connection String if you had to connect to this SQL Server instance remotely, along with your Azure credentials. Also, you will notice that I have created a Database called “Demo”, which we shall use as our primary backend database. Now, I can hit the “Manage” link to go inside my database and handle Tables/Stored Procedures etc., as shown in the screenshot below:

Team Table in Database

You’ll notice that once inside my Database, I have created a simple table called “Team”, with its schema showing on the right. Essentially, I want to maintain a list of Team Members, and hang on to “Name” & “TwitterHandle” for each; the “ID” column is the unique Primary Key & is self-incrementing. The graphical tools provided should make it fairly easy to setup your database tables just the way you want; alternatively you can do all of this from SQL Server Management Studio if you connect remotely. Now, let’s go ahead and add some dummy data to our table, shall we?

Team Table Data

So, now we have some data in SQL Azure, which is to be our Global repository .. how do we access it from a Windows Phone app? Super simple – OData! If you had a local data store, you could make an OData service out of it by adding ADO.NET Data Model & a WCF Data Service on top of it. With your data in SQL Azure, this comes free!!

Before we proceed, may be let’s take a step back & define what we are dealing with here. “In very simple terms, OData is a resource-based Web protocol for querying and updating data. OData defines operations on resources using HTTP verbs (PUT, POST, UPDATE and DELETE), and it identifies those resources using a standard URI syntax. Data is transferred over HTTP using the AtomPub or JSON standards.” (Source: MSDN Magazine, June 2010 Issue). One of the best places to start learning about OData is this; you can learn about all the public Producers, Consumers and OData Client SDK for various platforms.

Now, let's head over to the SQL Azure Labs (still CTP) site here, which requires signing in with your Live credentials .. the same one that is tied to the Azure subscription/trial that your are using. Then, if you select the "SQL Azure OData Service", you should see all your Databases from the SQL Azure server you created. Let’s select the “Demo” database, and then one checkbox is all it takes to open up OData service on top of it!! Make sure you select "dbo" to have the service openly accessible for this demo and copy the resulting OData Service URL:

Enable OData for Database

That's it! Let's grab the Service URL and try it in our browser. Notice below that I appended the collection name “Teams” at the end of the service URL. Our data from the "Team" table is now perfectly accessible through the OData service from SQL Azure! Yay -- now we are ready to interact with this data in our Windows Phone application.

Team Data as OData Service

The Windows Phone Client

For the Windows Phone app to consume the OData service out of SQL Azure, we start with a simple UI to accommodate only what is needed. So, we have one page that shows a list of all "Team" members from the OData service, in turn, coming directly out of the Team table in the SQL Azure database. From this initial page listing Team members, one may add new Team members or edit/delete existing Team members. The goal is to demonstrate CRUD [Create, Read, Update & Delete] operations against the OData service and have it reflected in the underlying data store in our SQL Azure Table. Here are few screenshots of how the Windows Phone client looks like:

WP7 Team List Screen     Add Team Member

New Team Member Added    New Member in List

As you can see, two simple XAML pages is what makes up the UI. For the sake of the length of this post, I'm going to skip showing most of the XAML code driving the UI; you have access to it from the downloadable source code. Let's talk about how this thing works, shall we?

Now, since this is a demo application, I don't have any fancy UI or Progress Bars; I simply try to load up my list of Team Members from the OData service as the "TeamList.xaml" page loads up in its frame. Before writing any code though, we need to let the Windows Phone project know where it can find a Reference to the Team collection; essentially register the OData service in the project so we can have a proxy built & can perform operations against the service. Here's how we add reference:

Add Service Reference

You'll notice that I used the same URL that SQL Azure Labs had created for exposing OData service on top of the "Demo" database for us to have access to "Team" table data. Once we have the Service Reference in place, half the work is done! One thing to note is adding an OData Service directly as a reference is supported in Windows Phone SDK 7.1 onwards. If using previous versions, you could still interact with an OData Service; but would just have to build out your proxy classes manually using the OData Client for Windows Phone, found here and the “DataSvcUtil.exe” utility.

Next, we utilize a special class called the "DataServiceCollection" to reference a collection of "Team" members from the OData service. This is a dynamic entity collection that is also an "ObservableCollection" .. this means a “DataServiceCollection” is totally bindable to XAML UI and changes in the underlying list get reflected in the UI automatically through the implementation of "INotifyPropertyChanged" interface. In addition to being an "ObservableCollection", the "DataServiceCollection" also exposes CRUD operations against the backend data store through the “DataContext” class, as we shall see soon. Here's how we hydrate our "Team" collection from the OData service .. remember this is Silverlight; so we cannot lock up the UI thread & have to use Async calls:

 1: using TeamService;
 2: using System.Data.Services.Client;
 3:  
 4: DataServiceContext context;
 5: DataServiceCollection<Team> team;
 6:  
 7: // Instantiate the context & fetch data.
 8: context = new DataServiceContext(new Uri("https://odata.sqlazurelabs.com/OData.svc/v0.1/<Your_Server>/Demo"));
 9: team = new DataServiceCollection<Team>(context);
 10: Uri uriQuery = new Uri("/Teams()", UriKind.Relative);
 11:  
 12: // Asynchronously load the result of the query.
 13: team.LoadAsync(uriQuery);
 14:  
 15: team.LoadCompleted += (sender, args) =>
 16: {
 17:    if (args.Error != null)
 18:    {
 19:       // Do error handling.
 20:    }
 21:    else
 22:    {
 23:       // Success.
 24:       // Do data-binding if needed.
 25:    }
 26: };
 27:  
 28:     

Once we have the "Team" collection hydrated, data binding to our XAML UI is rather simple, as shown below:

 1: <ListBox Name="teamList" Margin="0,0,-12,0" ItemsSource="{Binding Teams}" Foreground="White">
 2:     <ListBox.ItemTemplate>
 3:         <DataTemplate>
 4:             <StackPanel Margin="10,0,0,25" Width="432">
 5:                 <TextBlock Text="{Binding Name}" Style="{StaticResource PhoneTextAccentStyle}" Margin="10,0,0,0" FontSize="42"/>
 6:                 <TextBlock Text="{Binding TwitterHandle}" Margin="20,0,0,0" FontSize="38"/>
 7:             </StackPanel>
 8:         </DataTemplate>
 9:     </ListBox.ItemTemplate>
 10: </ListBox>

Now, adding a record through the OData Service is also very easy .. note this is done entirely in C# code through the beauty of the “DataServiceCollection” & “DataServiceContext” classes:

 1: private void InsertDataThruODataService()
 2: {
 3:     var TeamMember = new Team();
 4:     // Grab user entered info from UI.
 5:     TeamMember.Name = this.txtName.Text.Trim();
 6:     TeamMember.TwitterHandle = this.txtTwitterHandle.Text.Trim();
 7:  
 8:     var collection = new DataServiceCollection<Team>(context);           
 9:     collection.Add(TeamMember);
 10:     context.BeginSaveChanges(new AsyncCallback(SaveDoneCB), null);
 11: }    
 12:  
 13: private void SaveDoneCB(IAsyncResult asynchronousResult)
 14: {
 15:    // Warning: You are on a different thread! 
 16:    Dispatcher.BeginInvoke(() =>
 17:    {
 18:        MessageBox.Show("Voila, Saved to the Cloud :)", "All Done!", MessageBoxButton.OK);
 19:        this.NavigationService.Navigate(new Uri("/TeamList.xaml", UriKind.Relative));
 20:    });
 21: }   
 22:  

The only little thing to note in the code above is that the actual Insert is a Save operation against the context of the OData Service & this has to be done asynchronously. Correspondingly, we wire up an Async event-handler that fires when the Save operation is done. Please note here that if you are trying to update anything on the UI from this CallBack method, you might want to be aware that the Async method is possibly on a different thread for optimization. Hence, we need to do the little marshaling of threads to merge before we update UI pieces.

If the user selected an existing “Team” member, our second page now goes into Edit mode & preloads the selected member’s information for the user to change/delete. Here’s how we load up an existing member:

 1: // Event-Handler on List page UI.
 2: private void teamList_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
 3: {
 4:     if (this.teamList.SelectedItem != null)
 5:     {
 6:         Team selectedMember = (Team)this.teamList.SelectedItem;
 7:     
 8:         // We carry the ID of the selected Team Member.
 9:         this.NavigationService.Navigate(new Uri("/AddOrEdit.xaml?id=" + selectedMember.ID, UriKind.Relative));
 10:     }
 11: }
 12:  
 13: // In the Edit page ..
 14: if (this.NavigationContext.QueryString.ContainsKey("id"))
 15: {
 16:     int teamMemberID = Convert.ToInt16(this.NavigationContext.QueryString["id"]);
 17:  
 18:     // Try finding matching Team Member in collection.
 19:     presentTeamMember = teamCollection.First(x => x.ID == teamMemberID);
 20:  
 21:     if (presentTeamMember != null)
 22:     {
 23:         // Pre-Load Data.
 24:         this.txtName.Text = presentTeamMember.Name;
 25:         this.txtTwitterHandle.Text = presentTeamMember.TwitterHandle;                
 26:     }
 27: }

And once we have an existing “Team” member object at hand, update/delete become equally easy by wiring up ApplicationBar Icon buttons from the UI:

Edit Member

 1: private void SaveDataThruODataService()
 2: {
 3:     presentTeamMember.Name = this.txtName.Text.Trim();
 4:     presentTeamMember.TwitterHandle = this.txtTwitterHandle.Text.Trim();
 5:  
 6:     context.UpdateObject(presentTeamMember);
 7:     context.BeginSaveChanges(new AsyncCallback(SaveDoneCB), null);
 8: }
 9:  
 10: private void DeleteDataThruODataService()
 11: {
 12:     context.DeleteObject(presentTeamMember);
 13:     context.BeginSaveChanges(new AsyncCallback(SaveDoneCB), null);
 14: }

 

 

The only other interesting UI code to note is that when we want to add a new “Team” member from the second screen, we don't want to see the "Delete" Application Bar icon, right? Essentially, we want the App Bar to be dynamic based on the function of the page. Remember, the ApplicationBar is a part of the Phone shell & not a first-class Silverlight citizen. Here's how we refer to buttons in code:

 1: var DeleteButton = this.ApplicationBar.Buttons[1] as ApplicationBarIconButton;
 2: DeleteButton.IsEnabled = false;

That's it! Now we have a simple Windows Phone application that reads & updates data from an OData Service, which in turn gets reflected in the backend table in SQL Azure.

The Web Front-end

Now, we started out with the premise that we wanted access to the same data through a Windows Phone application, as well as a website, right? With our data in SQL Azure, this is pretty simple to do through an MVC type web application. So, we create a simple MVC project from template & add a few files to get the following Solution structure:

MVC Project Structure

The files we need are highlighted. The code – super simple:

 1: // Our Model.
 2: public class Team
 3: {
 4:     public int ID { get; set; }
 5:     public string Name { get; set; }
 6:     public string TwitterHandle { get; set; }
 7: }
 8:  
 9: // Our DBContext.
 10: public class TeamDBContext : DbContext
 11: {        
 12:     public DbSet<Team> Teams { get; set; } 
 13: }
 14:  
 15: // Our Controller.
 16: public class TeamController : Controller
 17: {
 18:    public ActionResult Index()
 19:    {
 20:        using (var db = new TeamDBContext())
 21:        {               
 22:            return View (db.Teams.ToList());
 23:        }
 24:    }
 25:    ....
 26: }

Essentially, we have a Database Context, and simply have the MVC Controller send down a list of “Team” members to the view, which is a Razor view auto-generated through MVC Scaffolding. Now, how does the run-time figure out where to get this Database Context? Glad you asked .. it’s a one liner in the Web.config:

 1: <connectionStrings>
 2:   <add name="TeamDBContext" connectionString="Data Source=<your_SQL_Azure_server>.database.windows.net; Initial Catalog=Demo; User Id=you@<server>.database.windows.net; Password=<your_pwd>; Encrypt=True; Trusted_Connection=false;" 
 3:        providerName="System.Data.SqlClient"/>
 4: </connectionStrings>

Notice that the Connection String is what defines what “TeamDBContext” means and this is what points the web application back to the SQL Azure server & the exact Database name. That’s it .. hit F5 and navigate to the Team controller. The result?

MVC WebPage

Voila! We now have a web application pointed to the same global data in our SQL Azure Database and see the data that was pushed from the Windows Phone app. If you implement the CRUD functionality in MVC, you should also be able to update the table data from the website & have it picked up by the Windows Phone application!

As an added cookie, if you have Entity Framework 4.1 installed, you have the “Magic Unicorn” and that means Code-First approach. You may totally start out your solution writing the model class in your web application, without creating a database. When you run the application for the first time, nothing will be found at the Azure server pointed by the Connection String; so the “Demo” database & the “Team” table with the correct schema will be created for you automatically. Then, the Windows Phone app could follow suit just the way we had it. Fun, isn’t it?

Other Mobile Platforms?

So by now, we have a fully-functional Windows Phone application that is leveraging a backend Database hosted inside SQL Azure and we are freely able to perform CRUD operations through the OData Service. All that is great, until your boss demands to see the same data in his iPhone/iPad and a friend desperately wants to utilize the data in his Android application! Well fear not. Simply point them to the OData SDK home (here) and ask them to get the OData client for their respective platforms. These client libraries should function similarly in building proxies to allow operations against the backend OData Service & soon they shall all be able to read/write data from the same data store in Azure. See, we can all live peacefully :)

Conclusion

In this article, we talked about why & how you, as a Windows Phone developer, should consider utilizing Windows Azure as a robust backend for your mobile applications. We saw how easily we could host a central database within SQL Azure & immediately expose the data out as an OData Service. Also, OData services fully support CRUD operations against the backend data and the interoperability of OData makes it a wonderful choice to have the same information be consumed & updated from various platforms.

Thank you very much for reading through this article; hopefully it was somewhat beneficial. If you have any questions or thoughts on how things can be done better in the above context, please feel free to reach out to me through the channels below; I will be happy to get some feedback. Big thank you to SilverlightShow for publishing this article & for all their awesomeness.

 

About the author

ActualPic

Samidip Basu (@samidip ) is a technologist & gadget-lover working as a Manager & Solutions Lead for Sogeti out of the Columbus OH Unit. Having worked on WP7 since CTP days, he now spends much of his time in spreading the word to discover the full potential of the Windows Phone platform & cloud-based mobile solutions in general. He passionately runs the Central Ohio Windows Phone User Group (http://cowpug.org/ ) and can be found with atleast a couple of hobbyist projects at any time. His spare times call for world travel and culinary adventures with the wife. Find out more at http://samidipbasu.com/ .


Subscribe

Comments

  • MikeCoates

    Re: Connecting Azure and Windows Phone through OData


    posted by MikeCoates on Sep 17, 2011 16:40
    Absolutely super article Samidip - easily the most helpful to me as an "enthusiastic amateur" trying to start out building basic business applications which make use of web/ mobile apps combined with azure. I believe tutorials like this will be the making of the cloud as ordinary business idiots like me begin to find it easy to develop and deploy solutions. I hope you keep up the good work. If my wishes could come true I would love to see an addition to this tutorial where we maybe added the users photo (plus maybe gps position). This applications for combining simple text, image, and geographic data are very exciting.
  • samidip

    Re: Connecting Azure and Windows Phone through OData


    posted by samidip on Sep 17, 2011 23:42

    MikeCoates,

    Thank you for  your kind words & glad that you enjoyed the article. I will try to keep your suggestion in mind & may be we could spin up another article in future that talks about the things you mentioned.

    Thanks!

  • hotkool-71

    Re: Connecting Azure and Windows Phone through OData


    posted by hotkool-71 on Nov 30, 2011 16:51
    hotkool-71@hotmail.co.tj

Add Comment

Login to comment:
  *      *       

From this series