Silverlight-Use WebClient to Upload and Download String and Stream

It is usual to upload and download data in silverlight. In this post, I will introduce how to use WebClient upload and download String, upload and download Stream.

What is WebClient class?

Main functions of WebClient:

  • OpenReadAsync: open readable stream which flows to specified resource.
  • OpenWriteAsync: open one stream to write data to secified resource. These methods cannot prevent from calling threads.
  • DownloadStringAsync: download resource located in specified Uri by string.
  • UploadStringAsync: upload specified string to specified resource. These methods cannot prevent from calling threads.

Main Methods of WebClient:

  • OpenReadCompleted: happen when completing to read in asynchronous resource.
  • OpenWritecompleted: happen when completing to open stream to write data to resource.
  • DownloadStringCompleted: happen when completing to download in asynchronous resource.
  • DownloadProgressChanged: happen when completing to download and send part or total data in asynchronous.
  • UploadStringCompleted: happen when completing upload in asynchronous string.
  • UploadProgressChanged: happen when completing to upload and convert part or total data in asynchronous.

Then, there is an example about uploading and download string and stream with WebClient.

Firstly, write xaml foreground code. There are four buttons which stand for uploading String, downloading String, uploading Stream, downloading Stream.

    <Grid x:Name=“LayoutRoot” Background=“White”>
      <Canvas Name=“lRoot”></Canvas>
        <Button Content=“WebClient Download XAP” Height=“23” HorizontalAlignment=“Left” Margin=“410,60,0,0” Name=“button1” VerticalAlignment=“Top” Width=“178” Click=“buttonOpenReadAsync_Click” />
        <Button Content=“DownloadStringAsync Download XML” Height=“23” HorizontalAlignment=“Left” Margin=“410,100,0,0” Name=“button2” VerticalAlignment=“Top” Width=“178” Click=“buttonDownloadStringAsync_Click” />
        <Button Content=“UploadStringAsync Upload String” Height=“23” HorizontalAlignment=“Left” Margin=“410,140,0,0” Name=“button3” VerticalAlignment=“Top” Width=“178” Click=“buttonUploadStringAsync_Click” />
        <Button Content=“OpenWriteAsync Upload Image” Height=“23” HorizontalAlignment=“Left” Margin=“410,180,0,0” Name=“button4” VerticalAlignment=“Top” Width=“178” Click=“buttonOpenWriteAsync_Click” />
    </Grid>
Upload String:

Create TestHandle.ashx and write the following code to it to receive uploaded String in Silverlight.

    ///<summary>
    ///TestHandle Summary
    ///</summary>
    public class TestHandle : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            int bytelength = context.Request.ContentLength;
            byte[] inputbytes = context.Request.BinaryRead(bytelength);
            string message = System.Text.Encoding.Default.GetString(inputbytes);
            context.Response.ContentType = “text/plain”;
            context.Response.Write(“You have submitted data:” + message);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

Code for Silverlight Client:

        WebClient Appclient = new WebClient();
        #regionUploadStringAsync Upload String
        private void buttonUploadStringAsync_Click(object sender, RoutedEventArgs e)
        {
            //Start to Call UploadStringAsync asynchronous upload String
            Appclient.UploadStringAsync(new Uri(http://localhost:3993/TestHandle.ashx&#8221;, UriKind.RelativeOrAbsolute), “<TD></TD>”);
            Appclient.UploadStringCompleted += new UploadStringCompletedEventHandler(Appclient_UploadStringCompleted);
        }

        private void Appclient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            MessageBox.Show(e.Result);
            Appclient.UploadStringCompleted -= new UploadStringCompletedEventHandler(Appclient_UploadStringCompleted);
        }
        #endregion

Download String:

Download existed XML file under ClientBin

        #region DownloadStringAsync Download XML
        private void buttonDownloadStringAsync_Click(object sender, RoutedEventArgs e)
        {

            // Start to Call DownloadStringAsync Asynchronous Download Document and Read
            Appclient.DownloadStringAsync(new Uri(http://localhost:3993/ClientBin/222.xml&#8221;, UriKind.RelativeOrAbsolute));
            Appclient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Appclient_DownloadStringCompleted);
        }

        private void Appclient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            MessageBox.Show(e.Result);
            Appclient.DownloadStringCompleted -= new DownloadStringCompletedEventHandler(Appclient_DownloadStringCompleted);
        }
        #endregion

Upload Stream:

Create one AddFileHandle.ashx and write the following code to it to receive uploaded Stream in Silverlight.

    ///<summary>
    ///AddFileHandle Summary
    ///</summary>
    public class AddFileHandle : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            // Get Uploaded Stream
            using (Stream sr = context.Request.InputStream)
            {
                string filename = “Fir”;
                byte[] buffer = new byte[4096];
                int bytesRead = 0;

                // Write Current Stream to Fir.jpg under ClientBin
                using (FileStream fs = File.Create(context.Server.MapPath(“ClientBin/” + filename + “.jpg”), 4096))
                {
                    while ((bytesRead = sr.Read(buffer, 0, buffer.Length)) > 0)
                    {

                        // Write Data to File
                        fs.Write(buffer, 0, bytesRead);
                    }
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

Silverlight reads image data and submits to server. (Note: it is not to verify the uploaded date. If needing, please call OpenFieldDialog.Filter).

        #region  OpenWriteAsync Upload Image
        private void buttonOpenWriteAsync_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            if (dialog.ShowDialog() == true)
            {
                //Start to Call OpenWriteAsync Method to Upload Data
                Appclient.OpenWriteAsync(new Uri(http://localhost:3993/AddFileHandle.ashx&#8221;, UriKind.RelativeOrAbsolute), “POST”, dialog.File.OpenRead());
                Appclient.OpenWriteCompleted += new OpenWriteCompletedEventHandler(Appclient_OpenWriteCompleted);
            }
        }

        private void Appclient_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
        {
            //Send Image Stream to Server
            Stream inputStream = e.UserState as Stream;
            Stream outputStream = e.Result;
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                outputStream.Write(buffer, 0, bytesRead);
            }
            outputStream.Close();
            inputStream.Close();
            MessageBox.Show(“Succeed”);
            Appclient.OpenWriteCompleted -= new OpenWriteCompletedEventHandler(Appclient_OpenWriteCompleted);
        }
        #endregion

Download Stream:

        #region OpenReadAsync Download XAP
        private void buttonOpenReadAsync_Click(object sender, RoutedEventArgs e)
        {
            //1. Use WebClient Download SLRandarHitTest to Asynchronous Read
            Appclient.OpenReadAsync(new Uri(“SLRandarHitTest.xap”, UriKind.Relative));
            Appclient.OpenReadCompleted += new OpenReadCompletedEventHandler(Appclient_OpenReadCompleted);
        }
        private void Appclient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            CreateXAPResource(“SLRandar.dll”, “SLRandar.MainPage”, e.Result);
            Appclient.OpenReadCompleted -= new OpenReadCompletedEventHandler(Appclient_OpenReadCompleted);
        }

        ///<summary>
        ///Create XAP Package Reflection Example and Retrofit to Canvas
        ///</summary>
        ///<param name=”dllStr”>Run DLL when Completing XAP Package Compilation</param>
        ///<param name=”mainStr”>Need Instantiated Start Page</param>
        ///<param name=”resultStream”>Use Downloaded Stream by WebClient</param>

        private void CreateXAPResource(string dllStr, string mainStr, Stream resultStream)
        {
            //2. Get Reresource Stream from other Package
            StreamResourceInfo streamResourceInfo = Application.GetResourceStream(new StreamResourceInfo(resultStream as Stream, null), new Uri(dllStr, UriKind.RelativeOrAbsolute));

            //3. Reflect Stream
            AssemblyPart assemblyPart = new AssemblyPart();
            Assembly assembly = assemblyPart.Load(streamResourceInfo.Stream);

            //4. Create Instance
            var uc = (UserControl)assembly.CreateInstance(mainStr);
            lRoot.Children.Clear();
            lRoot.Children.Add(uc);
        }
        #endregion

Silverlight Components Recommend:

Spire.Doc for Silverlight, a professional Silverlight Word component, is used to operate MS Word document for Silverlight, including basic manipulations (generate, open, edit documents), mail merge and other Word functions manipulations.

Spire.XLS for Silverlight, a professional Silverlight Excel component, is used to operate MS Excel for Silverlight, including basic manipulations (generate, open, edit files), chart creation and data exporting.

Advertisements

6 thoughts on “Silverlight-Use WebClient to Upload and Download String and Stream

  1. cbenac says:

    The post starts with a good description of the topic but when it gets into the code it gets confuse, at least for me, for example:

    In the code bellow, where and what is the “AppClient” ?
    What is “” ? is this the string to be passed?

    Appclient.UploadStringAsync(new Uri(“http://localhost:3993/TestHandle.ashx”, UriKind.RelativeOrAbsolute), “”);

    I think that if the examples can be ironed out the post will be very usefull

  2. travel converter says:

    I’m curious to find out what blog platform you
    appen to be utilizing? I’m having some small security problems
    with my latest blog and I’d like to find something more risk-free.

    Do you have any recommendations?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s