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

Producing and Consuming OData in a Silverlight and Windows Phone 7 application (Part 3)

(24 votes)
Michael Crump
>
Michael Crump
Joined Nov 12, 2010
Articles:   18
Comments:   17
More Articles
21 comments   /   posted on Apr 05, 2011
Categories:   Data Access , Windows Phone
This article is Part 3 of the series “Producing and Consuming OData in a Silverlight and Windows Phone 7 application.”.

To refresh your memory on what OData is:

The Open Data Protocol (OData) is simply an open web protocol for querying and updating data. It allows for the consumer to query the datasource (usually over HTTP) and retrieve the results in Atom, JSON or plain XML format, including pagination, ordering or filtering of the data.

To recap what we learned in the previous section:

  • We began by creating the User Interface and setting up our bindings on our elements. 
  • We added a service reference pointing to our OData Data Service inside our project. 
  • Finally, we added code behind to sort and filter the data coming from our OData Data Source into our Silverlight 4 Application.

In this article, I am going to show you how to consume an OData Data Source using Windows Phone 7. Read the complete series of articles to have a deep understanding of OData and how you may use it in your own applications.

See the video tutorial 
Download the source code for part 3 | Download the slides

Testing the OData Data Service before getting started…

Hopefully you have completed part 1 and 2 of the series, if you have not you may continue with this exercise by downloading the completed source code to Part 2 and continue. I would recommend watching the video to part 1 and part 2  in order to have a better understanding of where you can add OData to your own applications.

Go ahead and load the SLShowODataCompleted project inside of Visual Studio 2010, and look under Solution Explorer. Now right click CustomerService.svc and Select “View in Browser”.

If everything is up and running properly, then you should see the following screen (assuming you are using IE8).

Please note that any browser will work. I chose to use IE8 for demonstration purposes only.

2

If you got the screen listed above then we know everything is working properly and can continue. If not download the completed solution and continue with the rest of the article.

At this point, leave this instance of Visual Studio running, we are going to use this OData Data Service in the “Getting Started” part. You may also want to copy and paste the address URL which should be similar to the following:

http://localhost:6844/CustomerService.svc/

Downloading the tools…

In order to retrieve the data from an OData Data Source into Windows Phone 7, we are going to need to download the OData WP7 Library from CodePlex.

So, go ahead and navigate to http://odata.codeplex.com/.

3

We are only interested in the binaries, so click on the Downloads page then look for Other Available Downloads and select ODataClient_BinariesAndCodeGenToolForWinPhone.zip as shown below.

After the download completes, you will have the following files:

An explanation is provided below:

  • DavaSvcUtil.exe – is the utility that will create our class file from our OData Service.
  • Readme.txt – provides a sample command line for creating the class file from the Netflix OData Data Service.
  • System.Data.Services.Client.dll and System.Data.Services.Design.dll are the class libraries that we will add to our Windows Phone 7 Project.

 

Getting Started

Now that we have tested our OData Data Service and downloaded the tools, let’s get started by creating the proxy that our Windows Phone 7 Application will use.

We will need to go to a command prompt in order to generate our proxy. If you are using Windows 7 then you can quickly get to a command prompt by click Start –> and typing command in the search box.

Once you have a command prompt, simply navigate to the directory in which you extracted the directory to and type the following command:

datasvcutil /uri:http://localhost:6844/CustomerService.svc/ /out:.\CustomersModel.cs /Version:2.0 /DataServiceCollection

(Note: You will need the URI of the OData Data Service that we talked about in the first section of this article. I have bolded the paragraph at the top of this article that describes this.)

Quick Tip: You may also want to create a batch file and copy/paste the line above into it to quickly generate proxies in the future.

After this is complete, your screen should look similar to the following:

Notice that we have 0 errors and 0 warnings. If you have an error then step through each part of this tutorial again to make sure you have not left anything out. If all else fails, you can download a completed solution by scrolling to the top of this article.

If we navigate back into the folder that we extracted the .zip into, we will find a new file called CustomersModel.cs. This is our proxy that we will add to our Visual Studio 2010 Project.

Note: You will also note that I created a .bat file called “createclassfile.bat” to quickly generate this proxy again the future.

At this point, we are ready to create our Windows Phone 7 Application. So open up a new instance of Visual Studio 2010 and select File –> New Project.

Select Silverlight for Windows Phone –> Windows Phone Panorama Application and give it the name, SLShowODataP3 and finally click OK.

10

Once the project is loaded, the first thing we will need to do is add a reference to the System.Data.Services.Client.dll that we unpacked earlier.

Navigate to the directory containing the System.Data.Services.Client.dll file and double click it or select OK.

Now we will need to add the proxy that the DataSvcUtil.exe tool created.

Right click your project and select Add then Existing Item.

13

Navigate to the directory containing the CustomersModel.cs file and double click it or select Add.

Now we will need to create the User Interface and write the code behind to pull the data into our application.

Double click on the MainPage.xaml file and replace the contents of <—Panorama item one---> with the following code snippet:

 1: <!--Panorama item one-->
 2: <controls:PanoramaItem Header="first item">
 3:     <!--Double line list with text wrapping-->
 4:     <ListBox x:Name="lst" Margin="0,0,-12,0" ItemsSource="{Binding}">
 5:         <ListBox.ItemTemplate>
 6:             <DataTemplate>
 7:                 <StackPanel Margin="0,0,0,17" Width="432">
 8:                     <TextBlock Text="{Binding FirstName}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
 9:                     <TextBlock Text="{Binding LastName}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
 10:                     <TextBlock Text="{Binding Address}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
 11:                     <TextBlock Text="{Binding City}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
 12:                     <TextBlock Text="{Binding State}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
 13:                     <TextBlock Text="{Binding Zip}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
 14:                 </StackPanel>
 15:             </DataTemplate>
 16:         </ListBox.ItemTemplate>
 17:     </ListBox>
 18: </controls:PanoramaItem>

This xaml should be very straightforward. This ListBox contains a DataTemplate with a StackPanel that each TextBlock is binding to an element from our collection. This includes the FirstName, LastName, Address, City, State and Zip Code.

Now that we are finished with our UI and adding our Service Reference, let’s add some code behind to call our OData Data Service and retrieve the data into our Windows Phone 7 Application.

Now would be a good time to go ahead and Build our project. Select Build from the Menu and Build Solution. Now we can Double click on the MainPage.xaml.cs file and add the following code snippet, after replacing the MainPage() Constructor.

 1: public MainPage()
 2: {
 3:     InitializeComponent();
 4:     this.Loaded += new RoutedEventHandler(MainPage_Loaded);
 5: }
 6:  
 7: private void MainPage_Loaded(object sender, RoutedEventArgs e)
 8: {
 9:     var ctx = new CustomersEntities(new Uri("http://localhost:6844/CustomerService.svc/"));
 10:     var coll = new DataServiceCollection<CustomerInfo>(ctx);
 11:     lst.ItemsSource = coll;
 12:  
 13:     coll.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(coll_LoadCompleted);
 14:  
 15:     var qry = "/CustomerInfoes";
 16:     coll.LoadAsync(new Uri(qry, UriKind.Relative));
 17: }
 18:  
 19: void coll_LoadCompleted(object sender, LoadCompletedEventArgs e)
 20: {
 21:     if (e.Error != null)
 22:     {
 23:         MessageBox.Show(e.Error.Message);
 24:     }
 25: }

Lines 1-5 is the standard code generated except for the Loaded event. The Loaded Event created a new Event Handler called Main_Page Loaded.

Line 9 creates a new context with our CustomersEntities (which was generated by using the DataSvcUtil tool that we downloaded earlier) and passes the URI of our data service, which is located in our ASP.NET Project that we have running called CustomerService.svc.

Line 10 creates a DataServiceCollection which provides notification if an item is added, deleted or the list is refreshed. It is expecting a collection that was also created using the DataSvcUtil tool.

Line 11 sets the ItemSource of our ListBox to the collection.

Lines 15 simply creates a query that returns all records in our collection. We will modify this shortly to create a where and an orderby example.

Finally lines 19-25 are checking for an error and displaying a MessageBox. Of course, in a production application you may want to log that error instead of interrupting the user with a message they shouldn’t be concerned with.

If we go ahead and run this application, we would get the following screen.

Let’s add a query to filter the data. So go back to your MainPage.xaml.cs file and change this line:

 1: var qry = "/CustomerInfoes";

to

 1: var qry = "/CustomerInfoes?$filter=ID gt 3&$orderby=FirstName";

Now if we run this project you will notice that we only have 2 results returned and ordered by the FirstName. So in this example, Craig is listed first.

16

If you stop and notice that we are not using LINQ to produce the query where we were earlier in the Silverlight 4 Application. Instead we are writing the query manually. That is because this early implementation of OData on the Windows Phone 7 does not support the LINQ method in the current release. But do not worry as this will probably be addressed in a later release.

Conclusion

At this point, we have seen how you would produce and consume an OData Data Source using the web browser, LinqPad, Silverlight 4 and Windows Phone 7. We have learned how to do some basic sorting and filtering using all the same. Now that you are equipped with a solid understanding of producing and consuming OData Data Services, you can begin to use this in your own applications. I want to thank you for reading this series and if you ever have any questions feel free to contact me on the various souces listed below. I also wanted to thank SilverlightShow.Net for giving me the opportunity to share this information  with everyone.

Michael Crump is an MCPD that has been involved with computers in one way or another for as long as he can remember, but started professionally in 2002. After spending years working as a systems administrator/tech support analyst, Michael branched out and started developing internal utilities that automated repetitive tasks and freed up full-time employees. From there, he was offered a job working at McKesson corporation and has been working with some form of .NET and VB/C# since 2003.

He shares his findings in his personal blog: http://michaelcrump.net and he also tweets at:@mbcrump


Subscribe

Comments

  • -_-

    RE: Producing and Consuming OData in a Silverlight and Windows Phone 7 application (Part 3)


    posted by John Wiese on Apr 05, 2011 20:18

    Great series, wondering if you could help me figure out why mine isn't working like yours.  Specifically, when I get to line 10 above, I can't seem to get any of my collections to resolve as <T>?  Here's my service if you'd like to try it out:  http://thegolfleaguesite.com/golfservice.svc/

    Not sure if I did something wrong in setting it up, but the service appears to be working correctly and providing all the data like it should...just can't get the client to work right???

  • mbcrump

    RE: Producing and Consuming OData in a Silverlight and Windows Phone 7 application (Part 3)


    posted by mbcrump on Apr 05, 2011 21:45


    John Wiese: I'm assuming your talking about WP7. More than likely its because you didn't include the /Version:2.0 in your datasvcutil command. This include a necessary OnPropertyChanged that your more than likely missing. 

    Your command should look like the following:

    datasvcutil /uri:http://thegolfleaguesite.com/golfservice.svc/ /out:.\CustomersModel.cs /Version:2.0 /DataServiceCollection

    Let me know if I can be of further help.

  • -_-

    RE: Producing and Consuming OData in a Silverlight and Windows Phone 7 application (Part 3)


    posted by John Wiese on Apr 05, 2011 23:40

    Great series, wondering if you could help me figure out why mine isn't working like yours.  Specifically, when I get to line 10 above, I can't seem to get any of my collections to resolve as <T>?  Here's my service if you'd like to try it out:  http://thegolfleaguesite.com/golfservice.svc/

    Not sure if I did something wrong in setting it up, but the service appears to be working correctly and providing all the data like it should...just can't get the client to work right???

  • -_-

    RE: Producing and Consuming OData in a Silverlight and Windows Phone 7 application (Part 3)


    posted by John Wiese on Apr 05, 2011 23:43
    I did include the /Version:2.0 in my command.  I also just ran the command you put in your reply and the file created is identical (only exception is the comment with the date/time) as my file.  I pulled the tools this morning to ensure they were up to date as well.  Not sure what is going on here.
  • mbcrump

    RE: Producing and Consuming OData in a Silverlight and Windows Phone 7 application (Part 3)


    posted by mbcrump on Apr 05, 2011 23:45

    Can you send me your project and I'll take a look. You can email me at michael [at] michaelcrump [dot] net.

  • -_-

    RE: Producing and Consuming OData in a Silverlight and Windows Phone 7 application (Part 3)


    posted by John Wiese on Apr 05, 2011 23:53
    I did include the /Version:2.0 in my command.  I also just ran the command you put in your reply and the file created is identical (only exception is the comment with the date/time) as my file.  I pulled the tools this morning to ensure they were up to date as well.  Not sure what is going on here.
  • mbcrump

    RE: Producing and Consuming OData in a Silverlight and Windows Phone 7 application (Part 3)


    posted by mbcrump on Apr 05, 2011 23:54

    Can you send me your project and I'll take a look. You can email me at michael [at] michaelcrump [dot] net.

  • -_-

    RE: Producing and Consuming OData in a Silverlight and Windows Phone 7 application (Part 3)


    posted by John Wiese on Apr 06, 2011 00:16
    Ahh, thanks for the help Michael...for anyone else who may be in my boat there is another step that is not in the tutorial that is critical...you need to add a "using" statement for your models namespace.
  • mbcrump

    RE: Producing and Consuming OData in a Silverlight and Windows Phone 7 application (Part 3)


    posted by mbcrump on Apr 06, 2011 00:45

    Note to all: Be careful using Visual Studio's "Resolve Class Names" feature as it may select the wrong one. As always, let me know if you have any problems as I'm more than willing to help.

  • -_-

    RE: Producing and Consuming OData in a Silverlight and Windows Phone 7 application (Part 3)


    posted by Alex on Apr 27, 2011 23:28

    Hi, everything’s been great so far, I was using this guide to create a slightly different app, I'm using a data bound application and I’ve managed to get the equivalent of what you've done with your panoramic application but I can’t figure out what needs to be done to get the data from my online feed into the details page. Have you got any pointers you could help with?

    Thanks

  • -_-

    RE: Producing and Consuming OData in a Silverlight and Windows Phone 7 application (Part 3)


    posted by Alex on Apr 27, 2011 23:39

    Hi, everything’s been great so far, I was using this guide to create a slightly different app, I'm using a data bound application and I’ve managed to get the equivalent of what you've done with your panoramic application but I can’t figure out what needs to be done to get the data from my online feed into the details page. Have you got any pointers you could help with?

    Thanks

  • -_-

    RE: Producing and Consuming OData in a Silverlight and Windows Phone 7 application (Part 3)


    posted by Alex on Apr 27, 2011 23:48

    Hi, everything’s been great so far, I was using this guide to create a slightly different app, I'm using a data bound application and I’ve managed to get the equivalent of what you've done with your panoramic application but I can’t figure out what needs to be done to get the data from my online feed into the details page. Have you got any pointers you could help with?

    Thanks

  • mbcrump

    RE: Producing and Consuming OData in a Silverlight and Windows Phone 7 application (Part 3)


    posted by mbcrump on Apr 28, 2011 05:46

    Can you send the project to michael[at]michaelcrump[dot]net?

  • -_-

    RE: Producing and Consuming OData in a Silverlight and Windows Phone 7 application (Part 3)


    posted by Steve on 20:56

    I've got a string which is called "selectedIndex" and I want to make a query which basically says look in a table for the contents of this string. Does any 1 have any idea how I could do that?

    Thanks

  • wp7agile

    RE: Producing and Consuming OData in a Silverlight and Windows Phone 7 application (Part 3)


    posted by wp7agile on May 04, 2011 14:03
    Live app consuming OData feed for TechEd 2011 here: http://wp7agile.wordpress.com/2011/04/06/odata-wp7-app-for-tech-ed-north-america-2011/
  • kindel

    Re: Producing and Consuming OData in a Silverlight and Windows Phone 7 application (Part 3)


    posted by kindel on Jun 15, 2011 06:24
    hi Michael, this article mainly foucs on read Odata, can you send me some sample codes on how to updata and write OData? thx :)
  • Norbert

    Re: Producing and Consuming OData in a Silverlight and Windows Phone 7 application (Part 3)


    posted by Norbert on Oct 08, 2012 17:49

    Hi Micheal,

    Question about on the consumption of Odata. In your example you showed how to consume database with only one table. I have tried creating a simple data source with a one too many relationship. Could tell or write a tutorial on that subject.

    Thanks

  • Norbert

    Re: Producing and Consuming OData in a Silverlight and Windows Phone 7 application (Part 3)


    posted by Norbert on Oct 08, 2012 18:02

    Hi Micheal,

    Question about on the consumption of Odata. In your example you showed how to consume database with only one table. I have tried creating a simple data source with a one too many relationship. Could tell or write a tutorial on that subject.

    Thanks

  • Norbert

    Re: Producing and Consuming OData in a Silverlight and Windows Phone 7 application (Part 3)


    posted by Norbert on Oct 08, 2012 18:02

    Hi Micheal,

    Question about on the consumption of Odata. In your example you showed how to consume database with only one table. I have tried creating a simple data source with a one too many relationship. Could tell or write a tutorial on that subject.

    Thanks

  • Norbert

    Re: Producing and Consuming OData in a Silverlight and Windows Phone 7 application (Part 3)


    posted by Norbert on Oct 08, 2012 18:15

    Hi Micheal,

    Question about on the consumption of Odata. In your example you showed how to consume database with only one table. I have tried creating a simple data source with a one too many relationship. Could tell or write a tutorial on that subject.

    Thanks

  • Norbert

    Re: Producing and Consuming OData in a Silverlight and Windows Phone 7 application (Part 3)


    posted by Norbert on Oct 08, 2012 20:35

    Hi Micheal,

    Question about on the consumption of Odata. In your example you showed how to consume database with only one table. I have tried creating a simple data source with a one too many relationship. Could tell or write a tutorial on that subject.

    Thanks

Add Comment

Login to comment:
  *      *       

From this series