File Upload in Silverlight Using WCF

Published:
In previous Articles, we have discussed how we can upload a file using .asmx web service and isolated storage space. Here, in continuation to the topic, I am going to discuss how we can use WCF for the same purpose.

Steps:
1.Create the silverlight project with FileUploadWCF as the name.
2.Make these important changes in the properties of the FileUploadWCF.Web project:
   a.Right-click on FileUploadWCF.Web.
   b.Select Properties.
   c.Under the Web tab, Select Specific port and give the port number (e.g., I am using port number 1366).

Note: we are using specific port so that every time we need not to run the
web service its address will be unchanged. Either we need to host service on IIS if you don t want to use specific port or update the service reference each time before running the application.


    d.Save The Properties Page and close it.
3.Now Add a silverlight compatible WCF to the Project and name it as uploadService.
4.Include the name space System.IO :
using System.IO;

Open in new window


5.Add an operation Contract as :
[OperationContract]
                      public List<string> UploadFiles(string strFileName,byte[] byFile, string strFileNo)
                      {
                          List<string> result = new List<string>();
                          try
                         {
                              //if file length is greater than 0    
                              if (byFile.Length > 0)
                             {
                                  //set the location in a string variable where to save the file
                                 string strFilePath = "D:\\meet\\" + strFileName;
                                  //create a filestream
                                System.IO.FileStream fs = new FileStream(strFilePath,FileMode.Create, FileAccess.Write);
                                  //write the file at the specified location
                                 fs.Write(byFile, 0, byFile.Length);
                                  //close file stream
                                 fs.Close();
                                 result.Add(strFileNo);
                                  //returm file number
                                 return result;  
                             }
                             else
                             { 
                                  result.Add(""); 
                                  return result;
                              }
                          }
                          catch
                         {       
                              result.Add("");
                              return result;   
                         }
                      }

Open in new window


6.Create A class "FilesClass" in the FileUploadWCF project :
public class FilesClass
                      {
                          public FilesClass()
                         {
                              //do nothing
                         }
                         string strStatus = "";
                         string strNo = "";
                         FileInfo strFileName = null;
                         public string PropNumber
                        {
                              get { return strNo;}
                              set {strNo = value;} 
                        }
                        public FileInfo PropFileName   
                        {
                              get {return strFileName;}
                              set {strFileName = value;}   
                        }
                        public string PropStatus
                        {
                              get {return strStatus;}
                              set {strStatus = value;}
                         }
                      } 

Open in new window


7.Create Two Buttons in the Mainpage.xaml:
        a.To Choose File.
        b.To Upload File at the specified folder in the web service.

The Code will look like :
<Grid
                      x:Name="LayoutRoot"
                      Background="White"
                      Width="400" Height="50">
                      
                      <Button
                      Content="Choose"
                      Height="20" Width="150"
                      Click="Button_Click"
                      Margin="10,0,10,10"
                      VerticalAlignment="Bottom"
                      d:LayoutOverrides="Width,
                      Height" HorizontalAlignment="Left"
                      Background="#FF2770AF"></Button>
                      
                      <Button
                      Content="Upload"
                      Height="20" Width="150"
                      Click="Button_Click_1"
                      Margin="20,0,10,10"
                      VerticalAlignment="Bottom"
                      d:LayoutOverrides="Width,
                      Height" HorizontalAlignment="Right"
                      Background="#FF2770AF"></Button>
                      
                      </Grid>

Open in new window


8.Add the service reference to the silverlight project and name it uploadService.
9.Navigating to the event for the choose button :
private void Button_Click(object sender, RoutedEventArgs e)
                      {
                          //create an object for file open dialog
                          OpenFileDialog op = new
                          OpenFileDialog();
                          //show the file browser dialog to select file
                         op.ShowDialog();
                          //if any file is selected
                         if (op.File != null && op.File.Name != "")
                        {
                              //check the file size. It shoud be less than 1MB 
                             if (op.File.Length < 1048576)
                             {
                                  //create a new fill class object to maintain the file content 
                                 FilesClass obj = new
                                 FilesClass();
                                  //assign file 
                                 obj.PropFileName = op.File;
                                  //assing file number
                                  obj.PropNumber = iFileCount.ToString();
                                  //add the file object to files list collection 
                                 fl.Add(obj);
                                iFileCount++;
                             }
                              //IF size is greater then 1 MB show the message
                             else
                             {
                                  MessageBox.Show("Max file size is 1 MB");
                             }
                         }
                          //display message to the user if no file is selected
                         else
                         {
                              MessageBox.Show("Select File");
                         }
                      }

Open in new window


10.Now Lets code for the upload event (navigate to the event) :
private void Button_Click_1(object sender, RoutedEventArgs e)
                      {
                          if (fl.Count > 0)
                         {
                              //loop through the files and upload the files by passing it to web service.
                             for (int count =0; count < fl.Count; count++)
                             { 
                                 uploadService.uploadServiceClient x =
                                 new uploadService.uploadServiceClient();
                                  //read the file from file class
                                 FilesClass obj = (FilesClass)fl[count];
                                 System.IO.FileStream str =
                                 obj.PropFileName.OpenRead();
                                 byte[] by = new
                                 byte[str.Length];
                                 str.Read(by, 0, by.Length);
                                 str.Close();
                                  //call the upload file methods async event, which will upload the files asynchronously
                                 x.UploadFilesAsync(obj.PropFileName.Name, by, obj.PropNumber);
                                  //here is the event hadndler, whihc will be invoked for every file upload
                                 x.UploadFilesCompleted += new EventHandler<FileUploadWCF.uploadService.UploadFilesCompletedEventArgs>(UploadFileComplted);       
                             }
                        }
                      }
                      private void UploadFileComplted(object sender, uploadService.UploadFilesCompletedEventArgs e)
                      {
                          if (e.Result.ElementAt(0).ToString()!="")
                          {
                              MessageBox.Show("File Uploaded");
                           }
                      }

Open in new window



The final code is available for download for your convenience.  Enjoy the file handling!

Thanks and regards,
Meetu Choudhary


References:

File Upload In silverlight using Web service (.asmx)
https://www.experts-exchange.com/A_1519.html

Isolated Storage in the Silverlight Application
https://www.experts-exchange.com/A_1382.html

2
6,866 Views

Comments (1)

Kevin CrossChief Technology Officer
CERTIFIED EXPERT
Most Valuable Expert 2011

Commented:
Nice work, Meetu.
Voted yes above!

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.