Consuming OData services

This recipe demonstrates how to access OData using a simple URI. For this recipe, we will use the DataSvcUtil to generate the proxy classes instead of adding a reference.

Getting ready

For this sample, we will be using an OData API exposed by Netflix, an online movie rental company. At the time of writing the book, this service was in preview mode; please refer to the online documentation for the latest changes:

  1. Using your browser you can navigate to http://developer.netflix.com/docs/oData_Catalog to find all the documentation about the OData API.
  2. You can browse OData using http://odata.netflix.com/catalog/. We will be using this link to consume the data in this recipe.
  3. There are several features available for us to consume the data. At the resource level, we can get Catalog Titles (Catalog/Titles), People (Catalog/People), Languages (Catalog/Languages), and Genres (Catalog/Genres).
  4. We can use $filter to get the lowest rated titles available to watch instantly or the highest rated titles.
  5. Some of the parameters supported by Neflix are filter, format, top/skip, orderby, expand, inlinecount, and select.
  6. Filter operators supported are ge (greater than or equal to), gt (greater than), le (less than or equal to), lt (less than), eq (equal to), and ne (not equal to).
  7. Filter functions supported are Date (year, month, day, hour, minute, second), String (indexOf, replace, toLower, toUpper, trim, substring, concat, and length), and Math (Round, Ceiling, and Floor).

How to do it...

In this recipe we first generate the proxy class and then we add this file to the project. We then call the Netflix API to get the results, which are displayed in the listbox control.

  1. Open a New Project and using the Windows Phone Application template create the project and name it Recipe1_Netflix under the solution folder Ch4_Recipes.
  2. To consume the Netflix OData, we first need to generate the proxy class using the utility tool DataSvcUtil, which is a part of the Windows Phone 7.1 SDK. Use the following command line to generate the proxy class NetflixModel:

    datasvcutil /uri:http://odata.netflix.com/v1/Catalog/ /out:.NetflixModel.cs /Version:2.0 /DataServiceCollection
    

    How to do it...
  3. Now let's add the proxy file, NetflixModel.cs, which we generated into the project by right-clicking and choosing Add Existing Item. Alternatively, from Windows Explorer you can just copy and paste to the project.
  4. Add a reference to the System.Data.Services.Client assembly, which comes with the SDK for the project.
  5. Open the MainPage.xaml file, add a TextBlock control inside the ListBox and bind the control to Name. The title of the movie is the property Name returned from the Netflix Service.
    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent" DataContext="{Binding}">
    <Grid.RowDefinitions>
    <RowDefinition Height="Auto"/>
    <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <!--TitlePanel contains the name of the application and page title-->
    <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
    <TextBlock x:Name="ApplicationTitle" Text= "Ch4 Recipes" Style="{StaticResource PhoneTextNormalStyle}"/>
    <TextBlock x:Name="PageTitle" Text="Movie Titles" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
    </StackPanel>
    <!--ContentPanel - place additional content here-->
    <Grid x:Name="ContentPanel" Margin="12,0,12,-13" Grid.Row="1">
    <ListBox x:Name ="lstTasks" Grid.Row="3" Grid.Column ="1">
    <ListBox.ItemTemplate>
    <DataTemplate>
    <Grid>
    <Grid.RowDefinitions>
    <RowDefinition Height="*" />
    <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
    <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <TextBlock Grid.Row="0" TextWrapping="Wrap" Text="{Binding Name}" FontWeight="Bold" FontStretch="Expanded" Foreground="OrangeRed"/>
    </Grid>
    </DataTemplate>
    </ListBox.ItemTemplate>
    </ListBox>
    </Grid>
    </Grid>
    
  6. Open the MainPage.xaml.cs file and include the following two references:
    using NetflixCatalog.Model;
    using System.Data.Services.Client;
    
  7. Let's add the loaded event to the page from the MainPage.xaml file and click on<New Eventhandler>. Give it the name MainPage_Loaded. Check the last line in the following code:
    <phone:PhoneApplicationPage
    x:Class="Recipe1_Netflix.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/ xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls; assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell; assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/ markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True" Loaded="MainPage_Loaded">
    
  8. Now right-click on MainPage_Loaded and select Navigate to Event Handler. This creates the method MainPage_Loaded.
    How to do it...
  9. In the MainPage_Loaded method, we will add the code to navigate to the service URI. Here we create an instance of Uri with the Netflix service URI. Then, we will use the generic DataServiceCollection to get the Titles from the model. Then we will call the LoadAsync method with the query "Titles":
    public MainPage_Loaded(object sender,RoutedEventArgs e) {
    Uri svcUri = new Uri(@"http://odata.netflix.com/v1/Catalog/");
    var query = "Titles";
    // create context
    NetflixCatalog.Model.NetflixCatalog ctx = new NetflixCatalog.Model.NetflixCatalog(svcUri);
    DataServiceCollection<NetflixCatalog.Model.Title> rslts = new DataServiceCollection<NetflixCatalog.Model.Title>(ctx);
    rslts.LoadAsync(new Uri(query,UriKind.Relative));
    lstTasks.ItemsSource = rslts;
    }
    
  10. Press F5 to run. If there are no errors, then you should see all the movies in a list:
    How to do it...

How it works...

In the first step, we created a Uri object with the OData provider URI. We used two arguments, /Version and /DataServiceCollection. The version is 2.0, which is the latest. DataServiceCollection supports a read/write model that tracks changes automatically. In the MainPage_Loaded event method, we created instances of the DataServiceCollection and the Context objects. Then, we sent the request using the LoadAsync method by passing the query string Titles. Finally, we loaded the results to the ListBox.

There's more...

The Netflix API reference provides us with many different options to consume the data for customizing the client. You can add more features to your own app or to one of the recipes discussed in this chapter.

Using Reference to create the proxy class

In the last recipe, we learned how to consume the OData service by generating proxy classes using DataSvcUtil. Now with Phone 7.1 SDK, adding the reference to the project creates the proxy classes automatically. Let's repeat the same sample in the following steps:

  1. Add a new project by right-clicking the preceding solution, Ch4_Recipes, and create a new Phone 7 project and name it Recipe1_MyFlicks1. Pick the SDK version 7.1 in the dialog box.
  2. Right-click the project in the solution explorer and select Add Service Reference…. In the dialog box type the address http://odata.netflix.com/Catalog/ and click on Go. You should see the list of available service APIs in the Netflix Catalog. Change the default service reference name to NetflixReference. All the available entities exposed by the Netflix service are displayed in the left listbox. This is shown in the following screenshot:
    Using Reference to create the proxy class
  3. After you complete adding the reference, you should see both References and Service References folders updated as shown in the following screenshot:
    Using Reference to create the proxy class
  4. Now open the MainPage.xaml file and copy the XAML shown in the following code snippet, which will add a listbox control with a text block control:
    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent" DataContext="{Binding}">
    <Grid.RowDefinitions>
    <RowDefinition Height="Auto"/>
    <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <!--TitlePanel contains the name of the application and page title-->
    <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
    <TextBlock x:Name="ApplicationTitle" Text= "Ch4 Recipes" Style="{StaticResource PhoneTextNormalStyle}"/>
    <TextBlock x:Name="PageTitle" Text="Movie Titles" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
    </StackPanel>
    <!--ContentPanel - place additional content here-->
    <Grid x:Name="ContentPanel" Margin="12,0,12,-13" Grid.Row="1">
    <ListBox x:Name ="lstTasks" Grid.Row="3" Grid.Column ="1">
    <ListBox.ItemTemplate>
    <DataTemplate>
    <Grid>
    <Grid.RowDefinitions>
    <RowDefinition Height="*" />
    <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
    <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <TextBlock Grid.Row="0" TextWrapping="Wrap" Text="{Binding Name}" FontWeight="Bold" FontStretch="Expanded" Foreground="OrangeRed"/>
    </Grid>
    </DataTemplate>
    </ListBox.ItemTemplate>
    </ListBox>
    </Grid>
    </Grid>
    
  5. Open the MainPage.xaml.cs file and add using references at the top of the page to the System.Data.Services.Client and Recipe2_Netflix.NetflixReferece:
    using System.Data.Services.Client;
    using Recipe2_Netflix.NetflixReference;
    
  6. In the MainPage.xaml file, add the loaded event by right-clicking the<New EventHandler>. Navigate to the event handler PhoneApplicationPage_Loaded.
    private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
    {
    }
    
  7. Now, let's add the code to the preceding loaded event. Here we create an instance of NetflixCatalog using the service Uri. Then, using the DataServiceCollection, we get the genre as a list and call the LoadCompleted event. Using LINQ to Objects, we query all the genres and pass the query to the LoadAsync method.
    private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
    {
    Uri svcUri = new Uri(@"http://odata.netflix.com/Catalog/");
    ctx= new NetflixCatalog(svcUri);
    lstGenres = new DataServiceCollection<Genre>();
    lstGenres.LoadCompleted += new EventHandler <LoadCompletedEventArgs>(lstGenres_LoadCompleted);
    var query = from g in ctx.Genres select g;
    lstGenres.LoadAsync(query);
    }
    
  8. Next, we add the new event method, lstGenres_LoadCompleted. In this method, we assign the genre list lstGenres to lstBoxItems.ItemsSource:
    void lstGenres_LoadCompleted(object sender, LoadCompletedEventArgs e)
    {
    if (lstGenres.Continuation != null)
    {
    lstGenres.LoadNextPartialSetAsync();
    }
    else
    {
    this.lstBoxItems.ItemsSource = lstGenres;
    }
    }
    
  9. Press F5. You should see the list of all genres available in the Netflix database:
    Using Reference to create the proxy class

See also

Check the next recipe for more on how to search the Netflix catalog. Also, check the following online resources to understand more on OData support in Phone 7.1 SDK: http://msdn.microsoft.com/en-us/library/gg521146(v=vs.92).aspx.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset