ARTICLE

Consuming ODATA in Silverlight 4.0

Posted by Dhananjay Kumar Articles | Silverlight with C# July 18, 2011
ODATA is everywhere and so is Silverlight. In this post, I will show how ODATA can be consumed in Silverlight
Reader Level:


OData URL

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

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

We are going to fetch the Customers table from the NorthWind Database.

Create Project and Add Service Reference

Create a Silverlight project.

ODATASil1.gif

Choose Silverlight 4 as the version.

ODATASil2.gif

Right-click on the project and add a Service Reference.

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

ODATASil3.gif

Add following namespaces on MainPage.Xaml.cs page:

ODATASil4.gif

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

Globally defined following variables:

ODATASil5.gif

In the constructor of the 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

    ODATASil6.gif

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

    ODATASil7.gif

Design Page and Bind List Box

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

ODATASil8.gif

For your reference the full source code is given below. Feel free to use it.

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 the Customer table in the List box.

ODATASil9.gif
 

Login to add your contents and source code to this article
post comment
     

hi i check your Project is work perfectly thx for your share but i have question we are used this service http://services.odata.org/Northwind/Northwind.svc/ this service from Northwind but my question is how i will do public http://localhost:53626/RaporDataService.svc my link work localy. insted of LocalHost I want Put on My WebSite pls hellp me to make svc public not only on localhost

Posted by serkan Cakmak Aug 30, 2012
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
Join a Chapter
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Get Career Advice from Experts