Tuesday, September 7, 2010

Download a file in Silverlight from the server

For downloading a file form  the server we have several ways .The following  example i have used the traditional asp.net handlers ie the ashx.

All that what we have to do when downloading a file from silverlight is that
we need to navigate to handler that have created for the download.

The  following code sippnet shows the handler

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.UI;

namespace SLMemoryLeakSample.Web
{
    /// 
    /// Summary description for $codebehindclassname$
    /// 
    public class FileDownload : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.Clear();
            context.Response.Buffer = true;
            context.Response.AddHeader("Content-Disposition", "attachment;filename=Test.doc");
            context.Response.ContentType = "application/ms-Excel";
            context.Response.WriteFile("New Microsoft Office Word Document.docx");
            context.Response.Flush();
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
As you can see the the code that have written inside the Process Request basically  we just write the file into the output stream so that the file will be available in the client

Now step is the real magic of the silvelight especally the HyperLink button we have something called the NavigateUri which actually  call this handler

We can set the TagetName property to what ever you want from the avaiable .If we didnt set the target property name we will probably  get an error since the silverlight expects another xaml page

Enjoy coding............................

Export Document in ASP.NET

Here we are exporting the data from a grid to word,

       Response.Clear();
       Response.Buffer = true;
       Response.AddHeader("Content-Disposition", "attachment;filename=Test.doc");
       Response.ContentType = "application/ms-word";
       StringWriter stringWriter = new StringWriter();
       HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
       gvwEmployeeGrid.RenderControl(htmlTextWriter);
       Response.Output.Write(stringWriter.ToString());
       Response.Flush();
       Response.End();



Make EventValidation to false for the page and also override VerifyRenderingInServerForm in code behind,

       public override void VerifyRenderingInServerForm(Control control)

       {

       }


Export a file in ASP.NET

Here we are exporting a file to the client this will ask a open save cancel dialog

    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("Content-Disposition", "attachment;filename=Test.doc");
    Response.ContentType = "application/ms-Excel";
    Response.WriteFile("New Microsoft Office Word Document.docx");
    Response.Flush();
    Response.End();

Monday, September 6, 2010

Writting a file throught Silverlight .

The following code sipnet shows how we can open a file dialog from
the Silverlight Applcation and write to the server .
This is done via in conjection with the Asp.net handlers.


 private void FileUpLoader()
      {
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Multiselect = false;
        bool? retVal = openFileDialog.ShowDialog();

        if (retVal != null && retVal == true)
          {
            UploadFile(openFileDialog.File.Name,openFileDialog.File.OpenRead());
            tblStatus.Text = openFileDialog.File.Name;
          }
        else
          {
             tblStatus.Text = "Please select a file";
          }
       }




 private void UploadFile(string fileName, Stream data)
        {
            UriBuilder uriBuilder =
             new UriBuilder("http://localhost/SLMemoryLeakSample.Web/FileUploader.ashx");
            uriBuilder.Query = string.Format("filename={0}", fileName);

            WebClient webClient = new WebClient();
            webClient.OpenWriteCompleted += (sender, e) =>
            {
                WriteStream(data, e.Result);
                e.Result.Close();
                data.Close();
            };
            webClient.OpenWriteAsync(uriBuilder.Uri);
        }



 private void WriteStream(Stream input, Stream output)
        {

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
            {
                output.Write(buffer, 0, bytesRead);
            }
        }


The FileUploader.ashx will be as following


 public class FileUploader : IHttpHandler
    {

        #region FileUploader
        public void ProcessRequest(HttpContext context)
        {
            string filename = context.Request.QueryString["filename"].ToString();

            using (FileStream fs = File.Create(context.Server.MapPath("~/App_Data/" + filename)))
            {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = context.Request.InputStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    fs.Write(buffer, 0, bytesRead);
                }
            }
        }

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

Enjoy Coding ............................................