Blue Theme Orange Theme Green Theme Red Theme
 
Discover the top 5 tips for understanding .NET Interop
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » WCF » File Uplalod from Silver Light application to server location using WCF

File Uplalod from Silver Light application to server location using WCF

This article will explain, How to upload a file from SilverLight client to server location using WCF.

Author Rank :
Page Views : 14059
Downloads : 472
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
FileUpload.zip
 
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Objective:

This article will explain, How to upload a file from SilverLight client to server location using WCF.

To achieve above task, follow the below steps. I am assuming here, that Reader has a basic concept of

  1. WCF
  2. Silver Light
  3. Cross Domain Issue
  4. Hosting of WCF Service

For details on these topics, you could find astronomical number of articles on the Web. To Read articles written by me on above topic please Click Here

Pictorial representation of output

image1.gif

image2.gif

image3.gif

Follow the Steps below


Step 1:

Create and Host the WCF Service.

a. Create the Contract. This got only one method, which is taking as input a file to upload.

IService1.svc

using
System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
 namespace FileUploadService      
{
        [ServiceContract]
    public interface IService1                    
    {

 

        [OperationContract]
        void SaveFile(UploadFile UploadFile);
}
}

b. Create the Data Contract. This is going to contain the information about the uploaded file. You could either put this UploadFile Data Contract in same file with contract or in separate file.

[DataContract]
    public class UploadFile
    {
        [DataMember]
        public string FileName;

        [DataMember]
        public byte[] File;
    }

c. Implement the Service. We are simply creating instance of FileStream in create mode and writing the stream into that.

image4.gif

Service1.svc.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Configuration;
using System.Web;
using System.ServiceModel.Activation;
using System.IO;

namespace FileUploadService
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class Service1 : IService1
    {

        public void SaveFile(UploadFile UploadFile)
        {
            FileStream FileStream = new FileStream("E:\\FileUpload\\" + UploadFile.FileName, FileMode.Create);
            FileStream.Write(UploadFile.File, 0, UploadFile.File.Length);

            FileStream.Close();
            FileStream.Dispose();
        }

    }
}

d. Modify the Web.Config. Binding to be used is basicHttpBinding. I am setting the Buffer size and max Message received size also here.

<system.serviceModel>
 
    <
serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <bindings>
      <
basicHttpBinding>
        <
binding name="ServicesBinding" maxReceivedMessageSize="2000000" maxBufferSize="2000000">
          <readerQuotas maxArrayLength="2000000" maxStringContentLength="2000000"/>
        </binding>
      </
basicHttpBinding>
    </
bindings>
    <
services>
      <
service name="FileUploadService.Service1" behaviorConfiguration="FileUploadService.Service1Behavior">
        <!-- Service Endpoints -->
        <
endpoint address="" binding="basicHttpBinding" contract="FileUploadService.IService1">
          <!--
              Upon deployment, the following identity element should be removed or replaced to reflect the
              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity
              automatically.
         
-->
          <
identity>
            <
dns value="localhost"/>
          </identity>
        </
endpoint>
        <
endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </
services>
    <
behaviors>
      <
serviceBehaviors>
        <
behavior name="FileUploadService.Service1Behavior">
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <
serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <
serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </
serviceBehaviors>
    </
behaviors>
  </system.serviceModel>

e.
Host the service in IIS. Make sure you have put the access policy file at root directory of the server. If you have not done this, you will be getting cross domain error while accessing the service in Silver Light client. After hosting in IIS, browse the service to make sure, service is running and hosted properly.

For details of Cross domain issue read my article http://www.c-sharpcorner.com/UploadFile/dhananjaycoder/wcfandsilverlight04152009051036AM/wcfandsilverlight.aspx

By competing of Step 1, we have successfully created and hosted our service in IIS.

Step 2:

Create the Silver Light Client and consume the service

In belnd , I have just created one button and one text box. On clicking of the Button File Open Dialog Box will get open and user will select the file to uplaod. Text box is used to display the message thet whether file is successfully saved at server or not. If you don't want to use Blend no issue. Just create a simple Silver Light application and add one button and text box on that.

image5.gif

Generated XAML code is as below.

<UserControl
    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" x:Class="FileUpload.MainPage"
    Width="Auto" Height="Auto" mc:Ignorable="d">
    <Grid x:Name="LayoutRoot" Background="#FF241515" Margin="-0.05,0.044,-14.05,-15.956" RenderTransformOrigin="0.5,0.5" UseLayoutRounding="False" d:LayoutRounding="Auto" Width="420" Height="320">

    <Grid.RowDefinitions>
         <RowDefinition Height="0.48*"/>
         <RowDefinition Height="0.52*"/>
    </Grid.RowDefinitions>
    <Grid.RenderTransform>
         <TransformGroup>
             <ScaleTransform/>
             <SkewTransform/>
             <RotateTransform Angle="0.359"/>
             <TranslateTransform/>
         </TransformGroup>
    </Grid.RenderTransform>
    <Button Margin="10,10,10,10" Background="#FF1688E9" BorderThickness="2,2,2,2" FontSize="18" FontWeight="Bold" Content="Click To Upload the File to Server" Click="Button_Click"/>
    <TextBox x:Name="txtFileDisplayName" Margin="32.191,37.471,44.252,41.08" Grid.Row="1" Text="" TextWrapping="Wrap" Foreground="#FFA32929" BorderThickness="3,3,3,3" FontWeight="Bold" FontFamily="Arial Rounded MT Bold" FontSize="18"/>

    </Grid>
</
UserControl>

Step 3:

Add the Service Reference
 
To add the Service Reference in the Silver Light, right click on the Service and add Service reference.

Step 4:

Write the code behind

MainPage.Xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
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.ServiceModel;
using System.ServiceModel.Channels;
using System.IO;
using FileUpload.ServiceReference1;
using System.Windows.Browser;

namespace FileUpload
{
    public partial class MainPage : UserControl
    {
        public OpenFileDialog fileDialog = null;
        Service1Client proxy = null;
        public MainPage()
        {
            InitializeComponent();
            proxy = new Service1Client();
        }

        private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            fileDialog = new OpenFileDialog();
            fileDialog.Multiselect = false;
            fileDialog.Filter = "All Files|*.*";
            bool? retval = fileDialog.ShowDialog();
            if (retval != null && retval == true)
            {
 
              Stream strm = fileDialog.File.OpenRead();
                byte[] Buffer = new byte[strm.Length];
                strm.Read(Buffer, 0, (int)strm.Length);
                strm.Dispose();
                strm.Close();
                UploadFile file = new UploadFile();
                file.FileName = fileDialog.File.Name;
                file.File = Buffer;

                proxy.SaveFileAsync(file);
                proxy.SaveFileCompleted += new
EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(proxy_SaveFileCompleted);
 
            }
 
            else
            {
                txtFileDisplayName.Text = " No File Selected ";
            }
                  
        } 

   void proxy_SaveFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
                    if (e.Error == null)
                txtFileDisplayName.Text = fileDialog.File.Name + "Successfully Saved at ServerLocation";
       }

    }
}

Explanation of code

  1. We are here reading the file and converting content of the file in form of stream.

  2. image6.gif
     

  3. We are creating instance of FileDialog to show file dialog to user and then select the file to be saved. Multi select is set to false. It means user can not select more than one file at one time.

    image7.gif
  4. We are calling the Save File operation of service asynchronously on the proxy instance. Proxy is instance of the Service class.

    image8.gif
     
  5. We are creating instance of Data Contract and assigning property values by reading the file name through FileOpenDialog and stream by converted stream

    image19.gif

Step 4:

Press F5 to run the application

How to use Attached ZIP File

  1. Download and unzip somewhere.
  2. Host the FileUploadService (This is WCF service folder) in IIS.
  3. Open FileUpload folder. This is Siliver Light client. Go to reference and remove the attached service reference and add new service reference.
  4. On your local pc create a folder called FileUpload at E drive or modify your desired location in the service where you want to save the file.

Thank you very much for reading this article. I hope, it would have helped you out. Happy Coding.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Dhananjay Kumar
Dhananjay Kumar is a developer who blogs at http://debugmode.net/. He is Microsoft MVP ,Telerik MVP and Mindcracker MVP. You can follow him on twitter  @debug_mode
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
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.
Dynamic PDF
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.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Good Post - Correction Needed by Raghuraman On August 13, 2009
Hi Dhananjay,

This is a good write up. Please correct Uplalod spelling to Upload in the Title.

It would also be good to explain why an interface is needed. Why path's are hard coded ?

Thank you


Reply | Email | Modify 
Re: Good Post - Correction Needed by Dhananjay On August 14, 2009
Thanks for Feedback...

sorry for spelling mistake...

and in my sample , I have taken path as the hard coded .. you could read path from config file also....
Reply | Email | Modify 
Re: Re: Good Post - Correction Needed by Sanjay On July 27, 2011
I downloaded and when i run the application then its showing following error ..... I rebuild slotuion and updated the service also ....But its showing error in rference.cs File ... Can you please help me ....? An error occurred while trying to make a request to URI 'http://localhost:6206/Service1.svc'. This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. You may need to contact the owner of the service to publish a cross-domain policy file and to ensure it allows SOAP-related HTTP headers to be sent. This error may also be caused by using internal types in the web service proxy without using the InternalsVisibleToAttribute attribute. Please see the inner exception for more details.
Reply | Email | Modify 
Not able to upload Image file by Abhijit On September 10, 2009
Hi,
I am not able to upload Image file using this same code it showing me following error

The remote server returned an error: NotFound. in Referance.cs file

Reply | Email | Modify 
Great post! by Utkal On September 2, 2010
Very nice article Dhananjay! The modifications in the WCF web.config file is little bit confusing otherwise everything seems to be PERFECT. Keep up the good work.

Utkal Sharma
Reply | Email | Modify 
File Upload on Ftp Server by Ashish On November 3, 2010
hi Dhananjay,
i'm working on Silverlight4.I am not able to upload file on FTP server.please help to solve my problem.
thanks in advance.
Reply | Email | Modify 
Re: File Upload on Ftp Server by Dhananjay On July 18, 2011
any one able to upload file more than 4 MB following above article ?
Reply | Email | Modify 
Option For Download by benhan On November 26, 2011
Is there any Option to Download the File in server to Local PC
Reply | Email | Modify 
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.