Consuming ODATA in Silverlight 4.0

ODATA is everywhere and so is Silverlight. In this post, I will show, How ODATA can be consumed in Silverlight? “

OData URL

I will be using NorthWind OData URL. You can access that URL from below link.

http://services.odata.org/Northwind/Northwind.svc/

We are going to fetch Customers table from NorthWind DataBase.

Create Project and Add Service Reference

Create a Silverlight project

image

Choose Silverlight 4 as version

clip_image001

Right click on project and add Service Reference

In Address you need to give URL of OData. As we discussed in previous steps, here I am giving OData URL of NorthWind Database hosted by OData.org.

clip_image003

Add below namespaces on MainPage.Xaml.cs page

clip_image004

Please make sure about second namespace. Since, I have added service reference of OData with name ServiceReference1 and name of project is ODatainMangoUpdated.

Globally defined below variables

clip_image006

In constructor of MainPage,

  1. Create instance of NorthWindEntities
  2. Create instance of DataServiceCollection passing context
  3. Write the LINQ query.
  4. Attach event handler LoadCompleted on DataServiceCollection object.
  5. Fetch the result asynchronously

image

On the completed event

  1. Check whether next page exist or not , if yes load automatically
  2. Set the DataContext of layout as result.

image

Design Page and Bind List Box

Here you need to create a ListBox and in Data Template put three TextBlock vertically. Bind the different columns of table to the text blocks

image

For your reference full source codes are given below. Feel free to use them Smile

MainPage.Xaml


<UserControl xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"  x:Class="ODATAWithSilverLight.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">
    <Grid x:Name="LayoutRoot" Background="White">
        <ListBox x:Name="MainListBox" Margin="0,0,-12,0"
                 ItemsSource="{Binding}"
                 Height="350"
                 Width="250"
                 ScrollViewer.VerticalScrollBarVisibility="Visible">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Margin="0,0,0,17" Width="432">
                        <TextBlock Text="{Binding Path=CompanyName}"
                                          TextWrapping="NoWrap"
                                       />
                        <TextBlock Text="{Binding Path=ContactName}"
                                         TextWrapping="NoWrap"
                                       Margin="12,-6,12,0" />
                        <TextBlock Text="{Binding Path=Phone}"
                                          TextWrapping="NoWrap"
                                       Margin="12,-6,12,0"
                                       />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</UserControl>

MainPage.Xaml.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ODATAWithSilverLight.ServiceReference1;
using System.Data.Services.Client;

namespace ODATAWithSilverLight
{
    public partial class MainPage : UserControl
    {

        private NorthwindEntities context;
        private readonly Uri ODataUri = new Uri("http://services.odata.org/Northwind/Northwind.svc/");
        private DataServiceCollection<Customer> lstCustomers;

        public MainPage()
        {
            InitializeComponent();
            context = new NorthwindEntities(ODataUri);

            lstCustomers = new DataServiceCollection<Customer>(context);
            var result = from r in context.Customers select r;
            lstCustomers.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(lstCustomers_LoadCompleted);
            lstCustomers.LoadAsync(result);

        }

        void lstCustomers_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            if (lstCustomers.Continuation != null)
            {
                lstCustomers.LoadNextPartialSetAsync();
            }
            else
            {
                this.LayoutRoot.DataContext = lstCustomers;
            }

        }

    }
}

Run Application

Press F5 to run the application. You should get all the records from Customer table in List box.

image

I Hope this post was useful. Thanks for reading Smile



********************

Add to FacebookAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Yahoo BuzzAdd to Newsvine

One response to “Consuming ODATA in Silverlight 4.0”

Leave a comment

Create a website or blog at WordPress.com