Querying Netflix OData Service using Silverlight 4

Posted by: Suprotim Agarwal , on 8/15/2010, in Category Silverlight 2, 3, 4 and 5
Views: 41874
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:
AddServiceReference
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"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400" Loaded="MainPage_Loaded">
    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="30"/>
         </Grid.RowDefinitions>
        <sdk:DataGrid AutoGenerateColumns="False" Name="gridTitles" Grid.Row="0" >
                    <sdk:DataGrid.Columns>
                    </sdk:DataGrid.Columns>
                </sdk:DataGrid>
                <Button Name="btnGetRecords" Content="Fetch" Click="btnGetRecords_Click" Grid.Row="1" Width="100"/>
    </Grid>
</UserControl>
 
Step 4: In the MainPage.xaml.cs/vb, add two namespaces:
C#
using System.Data.Services.Client;
using SilverlightODataREST.ODataNetflixService;
 
VB.NET
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
C#
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);
}
 
VB.NET
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
C#
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);
 
        titlecoll.LoadAsync(titlescol);
        btnGetRecords.IsEnabled = false;
    }
}
 
VB.NET
 
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)
 
            titlecoll.LoadAsync(titlescol)
            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
C#
void Title_LoadCompleted(object sender, LoadCompletedEventArgs e)
{
    if (e.Error == null)
    {
        if (titlecoll.Continuation != null)
        {
            titlecoll.LoadNextPartialSetAsync();
        }
        else
        {
            // Bind the DataGrid to the collection
            gridTitles.ItemsSource = titlecoll;
            gridTitles.UpdateLayout();
        }
    }
    else
    {
        MessageBox.Show(e.Error.Message);
    }
}
 
VB.NET
Private Sub Title_LoadCompleted(ByVal sender As Object, ByVal e As LoadCompletedEventArgs)
      If e.Error Is Nothing Then
            If titlecoll.Continuation IsNot Nothing Then
                  titlecoll.LoadNextPartialSetAsync()
            Else
                  ' Bind the DataGrid to the collection
                  gridTitles.ItemsSource = titlecoll
                  gridTitles.UpdateLayout()
            End If
      Else
            MessageBox.Show(e.Error.Message)
      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" >
<sdk:DataGrid.Columns>
    <sdk:DataGridTemplateColumn>
        <sdk:DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <Image Source="{Binding BoxArt.MediumUrl}"  />
            </DataTemplate>
        </sdk:DataGridTemplateColumn.CellTemplate>
    </sdk:DataGridTemplateColumn>
    <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>
</sdk:DataGrid.Columns>
</sdk:DataGrid>
 
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:
Name
Conclusion
 
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 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 eBook 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 the 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+

Author
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 ten consecutive times. 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.

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook