Querying Netflix OData Service using Silverlight 4

Posted by: Suprotim Agarwal , on 8/15/2010, in Category Silverlight 2, 3, 4 and 5
Views: 44918
Abstract: In this article, we will see how to consume the Netflix OData service and display data in a Silverlight DataGrid control.
Silverlight 4 includes the WCF Data Services client library, using which you can now easily access data from any service that exposes an OData or REST end-points. The ‘Add Service Reference’ feature in Visual Studio 2010 makes this very easy to implement.
The Open Data Protocol (OData) is a Web protocol for querying and updating data that provides a way to unlock your data and free it from silos that exist in applications today. OData does this by applying and building upon Web technologies such as HTTP, Atom Publishing Protocol (AtomPub) and JSON to provide access to information from a variety of applications, services, and store (source)
In this article, we will see how to create a Silverlight client that can consume the Netflix OData service and display data in a Silverlight DataGrid control. Netflix partnered with Microsoft to create an OData API for the Netflix catalog information and announced the availability of this API during Microsoft Mix10.
Let us get started:
Step 1: Open Visual Studio 2010 > File > New Project > Silverlight Application > Rename it to ‘SilverlightODataREST’. Make sure that .NET Framework 4 is selected in the Target Framework. Click Ok.
Step 2: Right click the project SilverlightODataREST > Add Service Reference. In the address box, type http://odata.netflix.com/Catalog/. This is where the Netflix OData service is located. Rename the namespace as ‘ODataNetflixService’ and click Go. You should now be able to see the available services as shown below:
Click OK. Visual Studio generates the code files to be able to access this service.
Step 3: Create a XAML Interface with a Button and DataGrid. We’ll click a button and fetch data from the OData service and display the data in a Grid. We will be add columns to the DataGrid in a short while
<UserControl xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"  x:Class="SilverlightODataREST.MainPage"
    d:DesignHeight="300" d:DesignWidth="400" Loaded="MainPage_Loaded">
    <Grid x:Name="LayoutRoot" Background="White">
            <RowDefinition Height="*"/>
            <RowDefinition Height="30"/>
        <sdk:DataGrid AutoGenerateColumns="False" Name="gridTitles" Grid.Row="0" >
                <Button Name="btnGetRecords" Content="Fetch" Click="btnGetRecords_Click" Grid.Row="1" Width="100"/>
Step 4: In the MainPage.xaml.cs/vb, add two namespaces:
using System.Data.Services.Client;
using SilverlightODataREST.ODataNetflixService;
Imports System.Data.Services.Client
Imports SilverlightODataREST.ODataNetflixService
Now declare two variables – ‘catalog’ that points to the OData service and ‘titlecoll’ which is an instance of DataServiceCollection<Title> and write the following code in the MainPage_Loaded event
private DataServiceCollection<Title> titlecoll;
private NetflixCatalog catalog;
private void MainPage_Loaded(object sender, RoutedEventArgs e)
    catalog = new NetflixCatalog(
    new Uri("http://odata.netflix.com/Catalog/", UriKind.Absolute));
    titlecoll = new DataServiceCollection<Title>(catalog);
    titlecoll.LoadCompleted +=
    new EventHandler<LoadCompletedEventArgs>(Title_LoadCompleted);
Private titlecoll As DataServiceCollection(Of Title)
Private catalog As NetflixCatalog
Private Sub MainPage_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
      catalog = New NetflixCatalog(New Uri("http://odata.netflix.com/Catalog/", UriKind.Absolute))
      titlecoll = New DataServiceCollection(Of Title)(catalog)
      AddHandler titlecoll.LoadCompleted, AddressOf Title_LoadCompleted
End Sub
Step 5: Write the following code in the btnGetRecords_Click event
private void btnGetRecords_Click(object sender, RoutedEventArgs e)
    // check if catalog is not null
    if (catalog != null)
        gridTitles.DataContext = null;
        var titlescol = (from t in catalog.Titles
                            where t.Name.StartsWith("X")
                            select t).Take(10);
        btnGetRecords.IsEnabled = false;
Private Sub btnGetRecords_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
      ' check if catalog is not null
      If catalog IsNot Nothing Then
            gridTitles.DataContext = Nothing
            Dim titlescol = (
                From t In catalog.Titles
                Where t.Name.StartsWith("X")
                Select t).Take(10)
            btnGetRecords.IsEnabled = False
      End If
End Sub
In the button click event, we write a LINQ query to retrieve all the top 10 Titles that start with the alphabet ‘X’ and then pass the query to the LoadAsync method. The LoadAsync() executes the query and parses and loads the entities from the response feed into the binding collection (titlecoll) as Title objects. Finally the LoadCompleted event is raised.
Step 6: Let us code the LoadComplete event
void Title_LoadCompleted(object sender, LoadCompletedEventArgs e)
    if (e.Error == null)
        if (titlecoll.Continuation != null)
            // Bind the DataGrid to the collection
            gridTitles.ItemsSource = titlecoll;
Private Sub Title_LoadCompleted(ByVal sender As Object, ByVal e As LoadCompletedEventArgs)
      If e.Error Is Nothing Then
            If titlecoll.Continuation IsNot Nothing Then
                  ' Bind the DataGrid to the collection
                  gridTitles.ItemsSource = titlecoll
            End If
      End If
End Sub
We first check for errors. If no errors are present, we check to see if the continuation token in the response object is not null. If it is not null, we call LoadNextPartialSetAsync() to load the next page of the feed. If the continuation token is null, that means there are no remaining pages to load. So we go ahead and bind the collection to the DataGrid.
Step 7: The last step is to visually represent the data in the DataGrid. Add the following columns to the DataGrid:
<sdk:DataGrid AutoGenerateColumns="False" Name="gridTitles" Grid.Row="0" >
                <Image Source="{Binding BoxArt.MediumUrl}"  />
    <sdk:DataGridTextColumn Binding="{Binding Name}" Header="Name"></sdk:DataGridTextColumn>
    <sdk:DataGridTextColumn Binding="{Binding ReleaseYear}" Header="ReleaseYear"></sdk:DataGridTextColumn>
    <sdk:DataGridTextColumn Binding="{Binding Type}" Header="Type"></sdk:DataGridTextColumn>
    <sdk:DataGridTextColumn Binding="{Binding Synopsis}" Header="Synopsis"></sdk:DataGridTextColumn>
Run the application and hit the Fetch button. It takes a little time to load the data. The output will be similar to the one shown below:
In this article, we saw how easy it was to consume an OData feed in a Silverlight client application, developed in Visual Studio 2010. If you want to perform CRUD operations, there is an excellent article over here Consuming OData Feeds (Silverlight QuickStart)
The entire source code of this article can be downloaded over here

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Alex Dewitt on Monday, August 16, 2010 1:15 AM
awesome article. awesome site. thanks suprotim for introducing me to odata in silverlight.
Comment posted by Gordon on Saturday, August 21, 2010 7:24 AM
I truly like your blog. I presume you did not filter data in the beginning since you wanted to leave that on the front end to filter and present data?
Comment posted by Sid on Thursday, August 26, 2010 12:35 PM
Trying to access http://odata.netflix.com/Catalog/ but not able to.
Can anyone help ?
Comment posted by Suprotim Agarwal on Friday, August 27, 2010 5:20 AM
Alex, Gordon: Thanks for the kind words :)

Sid: Works fine! Try again.