Social Icons

Wednesday, November 21, 2012

File Attachment and saving on serving in Silverlight, Using Relay Command in MVVM Structure

Add Relay Command in View Model


///
/// Rlc Command for Attach Command
///
public RelayCommand rlcAttach
{
  get
  {
     return new RelayCommand(AttachCommand);

   }
}

Property for FilesList to upload
///
/// Property for List of Files To upload
///
public List<FileInfo> FilesToUpload
{
     get { return lstFilesToUpload; }
     set
     {
                lstFilesToUpload = value;
                RaisePropertyChanged("FilesToUpload");
     }
}


Method getting file information in List FilesToUpload
///
/// Method for go to Attach Command
///
protected void AttachCommand()
{
try
      {
                  OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Multiselect = true;
            //.doc, .xls, .csv, .txt
            fileDialog.Filter = "Word 2003 Format (*.doc)|*.doc|Text Files(*.txt)|*.txt|CSV Files(*.csv)|*.csv|Excel Files (*.xlsx)|*.xlsx|Excel Files 2003 Format(*.xls)|*.xls|Word Files(*.docx)|*.docx|All Files(*.*)|*.*";
            if (fileDialog.ShowDialog() == true)
            {
                    FilesToUpload = fileDialog.Files.ToList();
            }
      }
      catch (Exception ex)
      {
         //MessageBox.Show(ex.Message);
      }

          
}


Finally Method To send Files over the server using file handler in Web Project.
///
/// Method for go to Save Command
///
protected void SaveCommand()
{
    try
    {
      foreach (FileInfo file in FilesToUpload)
      {
          //Define the Url object for the Handler
          String ApplicationURL =    System.Windows.Browser.HtmlPage.Document.DocumentUri.ToString();
          String UploderHandlerURI = ApplicationURL.Substring(0, ApplicationURL.LastIndexOf('/') + 1) + "UploadFileHandler.ashx";
          UriBuilder handlerUrl = new UriBuilder(UploderHandlerURI);
          //Set the QueryString
          handlerUrl.Query = "InputFile=" + file.Name;
          FileStream FsInputFile = file.OpenRead();
          //Define the WebClient for Uploading the Data
          WebClient webClient = new WebClient();
          //An async class for writing the file to the server
          webClient.OpenWriteCompleted += (s, evt) =>
          {
               UploadFileData(FsInputFile, evt.Result);
               evt.Result.Close();
               FsInputFile.Close();
          };
          webClient.OpenWriteAsync(handlerUrl.Uri);
          Attachments.Add(file.Name);
         }
       }
       catch (Exception)
      {
                //MessageBox.Show(ex.Message);
      }
}

Supporting Method UploadFileData in above lines....
///
/// The Below Method read the data from the input file stream
/// and write into the out stream
///
///
///
private void UploadFileData(Stream inputFile, Stream resultFile)
{
    byte[] fileData = new byte[4096];
    int fileDataToRead;
while ((fileDataToRead =inputFile.Read(fileData, 0, fileData.Length)) != 0)
   {
                resultFile.Write(fileData, 0, fileDataToRead);
   }
}



File Handler in Web Project...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace DistributionExpress.Web
{
    ///
    /// Summary description for UploadFileHandler
    ///
    public class UploadFileHandler : IHttpHandler
    {

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

            using (FileStream fileStream = File.Create(context.Server.MapPath("~/FilesServer/" + filename)))
            {
                byte[] bufferData = new byte[4096];
                int bytesToBeRead;
                while ((bytesToBeRead = context.Request.InputStream.Read(bufferData, 0, bufferData.Length)) != 0)
                {
                    fileStream.Write(bufferData, 0, bytesToBeRead);
                }
                fileStream.Close();
            }
        }

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




No comments:

Post a Comment

 

Sample text

Sample Text