SIGN UP MEMBER LOGIN:    
ARTICLE

Reading files asynchronously using WebClient class in Silverlight

Posted by Dhananjay Kumar Articles | Silverlight with C# March 07, 2011
Let us read a XML file asynchronously using WebClient class.
Reader Level:

WebClient class is used in Silverlight to asynchronously download or read a file from a particular URI. 
  1. WebClient class is under System.Net namespace. 
  2. This can retrieve data from any format of service. This can retrieve data in JSON, POX, and REST etc. format. 
  3. WebClient makes the entire request asynchronously. So it does not block any other operation. 
  4. On basis of data type of response from URI, we can choose class to parse the response data.  If response is JOSN, we can use DataContractJSONSerliazer to parse response data. 
  5. Any type of file including Media, Images, and XML etc. can be downloaded using WebClient class. 
Let us read a XML file asynchronously using WebClient class. 

1. Add XML file named Data.xml in the client bin folder. Right click on client Bin folder and add a new item then select XML file from Data tab. Give name of the file as Data.xml.  

Data.xml 

<?xml version="1.0" encoding="utf-8" ?>
<School>
  <Student>
    <RollNumber>1</RollNumber>
    <Name>John Papa</Name>
  </Student>
  <Student>
    <RollNumber>1</RollNumber>
    <Name>John Papa</Name>
  </Student>
  <Student>
    <RollNumber>2</RollNumber>
    <Name>Scott Gui</Name>
  </Student>
  <Student>
    <RollNumber>3</RollNumber>
    <Name>Jessy Liberty</Name>
  </Student>
  <Student>
    <RollNumber>4</RollNumber>
    <Name>Tim Huer</Name>
  </Student>
  <Student>
    <RollNumber>5</RollNumber>
    <Name>Victor Gud</Name>
  </Student>
  <Student>
    <RollNumber>6</RollNumber>
    <Name>Machesh Chand</Name>
  </Student>
  <Student>
    <RollNumber>7</RollNumber>
    <Name>Pinal Dave</Name>
  </Student>
  <Student>
    <RollNumber>8</RollNumber>
    <Name>Suprotim Agarwal</Name>
  </Student>
  <Student>
    <RollNumber>9</RollNumber>
    <Name>Dhananjay Kumar</Name>
  </Student>
  <Student>
    <RollNumber>10</RollNumber>
    <Name>Kunal Chawudhary</Name>
  </Student>
  <Student>
    <RollNumber>11</RollNumber>
    <Name>Abhijit Jana</Name>
  </Student>
  <Student>
    <RollNumber>12</RollNumber>
    <Name>Shiv Prasad Koirala</Name>
  </Student>
</School>

2. Once Data.xml file is in place inside client bin folder, let us design XAML page.  We will put one Button and one TextBlock. 

On click event of button, we will make asynchronous call to read Data.xml file. After successful reading, we will bind xml response to TextBlock. 

MainPage.xaml 

<UserControl xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"               x:Class="SilverlightApplication5.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">        <StackPanel Orientation="Vertical" Margin="50,50,50,50">         <Button x:Name="btnDemo" Content="Click To get Data From  XML using WebClient" Height="62" Width="362" />             <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" Height="200" Width="300">                 <TextBlock x:Name="txtDataFromXml"  Width="Auto" Height="Auto" />             </ScrollViewer>         </StackPanel>              </Grid> </UserControl>

3. On click event of button, we will read Data.xml file asynchronously.

private void btnDemo_Click(object sender, RoutedEventArgs e)
{
    WebClient client = new WebClient();
    Uri uritoXML = new Uri("Data.xml",UriKind.Relative);           
    client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
    client.OpenReadAsync(uritoXML);
}

At time of creation of URL either we can provide absolute URI or relative.  In our example Data.xml file is in client bin folder so we are providing relative address. 

In OpenReadCompleted event handler, we will parse XML file and bind response to TextBlock. 

void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    Stream s = e.Result;
    StreamReader strReader = new StreamReader(s);
    txtDataFromXml.Text = strReader.ReadToEnd();
    s.Close();
}

For reference full code is given below, 

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 System.IO;

namespace SilverlightApplication5
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            btnDemo.Click +=new RoutedEventHandler(btnDemo_Click);
        }
        private void btnDemo_Click(object sender, RoutedEventArgs e)
        {
            WebClient client = new WebClient();
            Uri uritoXML = new Uri("Data.xml",UriKind.Relative);           
            client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
            client.OpenReadAsync(uritoXML);
        }
        void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            Stream s = e.Result;
            StreamReader strReader = new StreamReader(s);
            txtDataFromXml.Text = strReader.ReadToEnd();
            s.Close();
        }
    }
}

Output 
 
WebClientReadasync.gif

Login to add your contents and source code to this article
share this article :
post comment
 
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
Team Foundation Server Hosting
Become a Sponsor