Getting Started with Adobe After Effects - Part 6: Motion Blur


Upload Image Close it
Select File

Browse by Tags · View All
BRH 58
#ASP.NET 55
ASP.NET 50
#DOTNET 49
.NET 40
WCF 21
DOTNET 12
c# 8
windows azure 7
SILVERLIGHT 7

Archive · View All
April 2011 9
March 2011 9
February 2011 8
December 2010 7
November 2010 5
September 2010 5
August 2010 5
May 2011 4
October 2010 4
January 2011 2

File Upload from Silverlight using WCF

Nov 30 2010 8:24AM by Dhananjay Kumar   

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

clip_image002

clip_image004

clip_image006

Follow the Steps below

Step 1:

Create and Host the WCF Service.

  1. 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);
      }
    }
  2. 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;
      }
  3.  Implement the Service. We are simply creating instance of FileStream in create mode and writing the stream into that.

    clip_image001

    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();
      } 
      }
    }
  4.  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>
    
  5. 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.

clip_image012

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.
    clip_image013
  2. 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.
    clip_image014
  3. We are calling the Save File operation of service asynchronously on the proxy instance. Proxy is instance of the Service class.
    clip_image015
  4. We are creating instance of Data Contract and assigning property values by reading the file name through FileOpenDialog and stream by converted stream
    clip_image016

Step 4:

Press F5 to run the application

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

Happy Coding

Tags: #DOTNET, WCF, #ASP.NET, ASP.NET, BRH, .NET, SILVERLIGHT,


Dhananjay Kumar
49 · 4% · 1198
0
Liked
 
0
Lifesaver
 
0
Refreshed
 
0
Learned
 
0
Incorrect



Submit

1  Comments  

  • Hello Dhananjay,

    Really nice article.it helps me a lot but i am having one problem i can see maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" in servicereference.clientconfig file as well i have modify the web,config as you suggest but still i am getting error if i upload large file i am not even able to upload 17 KB file size with your code i am able to upload 3 kb file size but i want to allow user to upload upto 10MB file size i don't know what mistake i am making but it is making me crazy i will appritiate if you help me you can reach me on foramparikh8884@gmail.com as well.

    Here is my code for servicereference.clientconfig

    here is my web.config

      <bindings>
    	  <basicHttpBinding>
    		  <binding name="ServicesBinding" maxReceivedMessageSize="2000000" maxBufferSize="2000000">
    			  <readerQuotas maxArrayLength="2000000" maxStringContentLength="2000000"/>
    		  </binding>
    
    	  </basicHttpBinding>
      </bindings>
    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
      multipleSiteBindingsEnabled="true" />
    
      <services>
    	  <service name="ServiceReference1.fileupload" behaviorConfiguration="ServiceReference1.fileuploadBehavior">
    		  <!-- Service Endpoints -->
    		  <endpoint address="" binding="basicHttpBinding" contract="ServiceReference1.fileupload">
    
    			  <!--
    

    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. -->

    	  </service>
      </services>
      <behaviors>
    	  <serviceBehaviors>
    		  <behavior name="ServiceReference1.fileuploadBehavior">
    			  <!-- 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>
    

    I can only upload 3 or 4 KB file size.

    It is making me crazy i don't know what to do.

    Please advise, Foram

    commented on Nov 23 2011 2:50PM
    foram
    1494 · 0% · 14

Your Comment


Sign Up or Login to post a comment.

    Copyright © Rivera Informatic Private Ltd Contact us      Privacy Policy      Terms of use      Report Abuse      Advertising      [ZULU1097]