locked
upload and download file using silverlight wcf ria services? RRS feed

  • Question

  • Can you provide a sample for how to upload and download files to database using silverlight wcf ria services. I need to store file in database not in a physical location. and retrieve the file from this database.

    Tuesday, November 22, 2011 7:45 AM

Answers

  • Hye Ajin,

    find below the complete code to upload and download image in silverlight using WCF RIA Services from database.

    the structure of table in database, i am giving create script for the table just run this script in SQL server database.


    GO

    /****** Object: Table [dbo].[FileTable] Script Date: 11/23/2011 12:23:07 ******/
    SET ANSI_NULLS ON
    GO

    SET QUOTED_IDENTIFIER ON
    GO

    CREATE TABLE [dbo].[FileTable](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [FileName] [nvarchar](50) NULL,
    [FileData] [nvarchar](max) NULL,
    [Extension] [nvarchar](50) NOT NULL,
    CONSTRAINT [PK_FileTable] PRIMARY KEY CLUSTERED
    (
    [Id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]

    GO


    <UserControl x:Class="DownloadUploadImageFromDatabase.MainPage"
        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"
        mc:Ignorable="d"
        d:DesignHeight="300" d:DesignWidth="400">
    
        <Grid x:Name="LayoutRoot" Background="White">       
            <Button x:Name="BtnDownload" Click="BtnDownload_Click" Height="25" Content="Download" Width="80" Margin="160,12,160,263"></Button>
            <Button x:Name="BtnUpload" Content="Upload" Width="60" Height="25" Margin="90,12,249,263" Click="BtnUpload_Click"></Button>
        </Grid>
    </UserControl>
    
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.ServiceModel.DomainServices.Client;
    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 DownloadUploadImageFromDatabaseWeb;
    
    namespace DownloadUploadImageFromDatabase
    {
        public partial class MainPage : UserControl
        {
            DomainService1 _domainService = new DomainService1();
            private SaveFileDialog _saveFileDialog = null;
            public MainPage ()
            {
                InitializeComponent();
            }
    
            private void BtnDownload_Click (object sender, RoutedEventArgs e)
            {
                _saveFileDialog = new SaveFileDialog();
                _saveFileDialog.Filter = "All Files(.jpg)|*.jpg|All Files|*.*";
                _saveFileDialog.ShowDialog();
                
    
                if (!string.IsNullOrEmpty(_saveFileDialog.SafeFileName))
                {
                    var filetables = _domainService.GetFileTablesQuery();
                    _domainService.Load(filetables, LoadFileTableMethod, null);
                }
    
    
            }
    
            public void LoadFileTableMethod (LoadOperation<FileTable> filetable)
            {
               
                var filetables = filetable.Entities;
              
                 byte[] bytes = Convert.FromBase64String(filetables.FirstOrDefault().FileData);
                 using (System.IO.Stream stream = _saveFileDialog.OpenFile())
                 {
    
                     stream.Write(bytes, 0, bytes.Length);
                     stream.Close();
                 }
    
             }
    
            private void BtnUpload_Click (object sender, RoutedEventArgs e)
            {
                try
                {
                    var openFileDialog = new OpenFileDialog();
                    openFileDialog.ShowDialog();
    
                    var stream = openFileDialog.File.OpenRead();
    
                    var bytes = new byte[stream.Length];
    
                    stream.Read(bytes, 0, (int)stream.Length);
    
                    var bytesinstring = Convert.ToBase64String(bytes);
    
                    var fileTable = new FileTable();
                    fileTable.FileName = openFileDialog.File.Name;
                    fileTable.Extension = openFileDialog.File.Extension;
                    fileTable.FileData = bytesinstring;
    
    
                    _domainService.FileTables.Add(fileTable);
                    _domainService.SubmitChanges();
                }
    
                catch (Exception)
                {
    
                }
            }
        }
    } 
    Wednesday, November 23, 2011 1:58 AM

All replies

  • Hye Ajin,

    find below the complete code to upload and download image in silverlight using WCF RIA Services from database.

    the structure of table in database, i am giving create script for the table just run this script in SQL server database.


    GO

    /****** Object: Table [dbo].[FileTable] Script Date: 11/23/2011 12:23:07 ******/
    SET ANSI_NULLS ON
    GO

    SET QUOTED_IDENTIFIER ON
    GO

    CREATE TABLE [dbo].[FileTable](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [FileName] [nvarchar](50) NULL,
    [FileData] [nvarchar](max) NULL,
    [Extension] [nvarchar](50) NOT NULL,
    CONSTRAINT [PK_FileTable] PRIMARY KEY CLUSTERED
    (
    [Id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]

    GO


    <UserControl x:Class="DownloadUploadImageFromDatabase.MainPage"
        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"
        mc:Ignorable="d"
        d:DesignHeight="300" d:DesignWidth="400">
    
        <Grid x:Name="LayoutRoot" Background="White">       
            <Button x:Name="BtnDownload" Click="BtnDownload_Click" Height="25" Content="Download" Width="80" Margin="160,12,160,263"></Button>
            <Button x:Name="BtnUpload" Content="Upload" Width="60" Height="25" Margin="90,12,249,263" Click="BtnUpload_Click"></Button>
        </Grid>
    </UserControl>
    
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.ServiceModel.DomainServices.Client;
    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 DownloadUploadImageFromDatabaseWeb;
    
    namespace DownloadUploadImageFromDatabase
    {
        public partial class MainPage : UserControl
        {
            DomainService1 _domainService = new DomainService1();
            private SaveFileDialog _saveFileDialog = null;
            public MainPage ()
            {
                InitializeComponent();
            }
    
            private void BtnDownload_Click (object sender, RoutedEventArgs e)
            {
                _saveFileDialog = new SaveFileDialog();
                _saveFileDialog.Filter = "All Files(.jpg)|*.jpg|All Files|*.*";
                _saveFileDialog.ShowDialog();
                
    
                if (!string.IsNullOrEmpty(_saveFileDialog.SafeFileName))
                {
                    var filetables = _domainService.GetFileTablesQuery();
                    _domainService.Load(filetables, LoadFileTableMethod, null);
                }
    
    
            }
    
            public void LoadFileTableMethod (LoadOperation<FileTable> filetable)
            {
               
                var filetables = filetable.Entities;
              
                 byte[] bytes = Convert.FromBase64String(filetables.FirstOrDefault().FileData);
                 using (System.IO.Stream stream = _saveFileDialog.OpenFile())
                 {
    
                     stream.Write(bytes, 0, bytes.Length);
                     stream.Close();
                 }
    
             }
    
            private void BtnUpload_Click (object sender, RoutedEventArgs e)
            {
                try
                {
                    var openFileDialog = new OpenFileDialog();
                    openFileDialog.ShowDialog();
    
                    var stream = openFileDialog.File.OpenRead();
    
                    var bytes = new byte[stream.Length];
    
                    stream.Read(bytes, 0, (int)stream.Length);
    
                    var bytesinstring = Convert.ToBase64String(bytes);
    
                    var fileTable = new FileTable();
                    fileTable.FileName = openFileDialog.File.Name;
                    fileTable.Extension = openFileDialog.File.Extension;
                    fileTable.FileData = bytesinstring;
    
    
                    _domainService.FileTables.Add(fileTable);
                    _domainService.SubmitChanges();
                }
    
                catch (Exception)
                {
    
                }
            }
        }
    } 
    Wednesday, November 23, 2011 1:58 AM
  • can u provide the function "Load"

    _domainService.Load(filetables, LoadFileTableMethod, null);
    Wednesday, November 23, 2011 3:00 AM
  • there is no function called Load, but this method calls the callback method named LoadFileTableMethod.

    thats it, i gave everything, just copy and run the code.

     

    Wednesday, November 23, 2011 3:31 AM
  • Hi syed,

    I copied your code and run it. it works in uploading. but in downloading when i upload a picture and download it it gets downloads.then i upload another file and try to download it, the first file get downloaded. how can i download the one that i uploaded. i mean the uploaded files are listed in a datagrid. in each rows there is a button to download that file. 

    Wednesday, November 23, 2011 6:01 AM
  • I modified the code to fetch the data with fileid. now i got what i required.

    Thanks for the help syed.....

    Wednesday, November 23, 2011 6:12 AM
  • Hi Syed, One more question

    how to change the code, if i need to apply  "multiple select" of files

    Wednesday, November 23, 2011 6:42 AM
  • you cant upload or download multiples files, you need zip or rar the multiples files.

    Wednesday, November 23, 2011 8:07 AM
  • You CAN upload multiple files.  I'm doing it now.  The OpenFileDialog allows multiple files to be selected if you set the Multiselect property to true.

    After I have the file information for the files selected, I use my own upload service, but upload the files in sequence one at a time.  The code is based on using:

    webrequest        := HttpWebRequest( WebRequest.Create( ub.Uri ) );
    webrequest.Method := 'POST';
    webrequest.BeginGetRequestStream( new AsyncCallback( WriteCallback ), webrequest );
          

    I don't think download is possible without having a separate SaveFileDialog for each one.  I only allow downloading 1 at a time currently.

    Wednesday, November 23, 2011 8:51 AM
  • Hi how to update the files that are uploaded.

    I mean I have a dataform which is binded to a class and i can upload files to the table as followed the method in this post. but when i try to update the file( a dataform loads and try to enter values) and press commit button,it shows filecontent is required........

    Friday, November 25, 2011 8:33 AM
  • Hi,

    I would be very grateful if you can provide a sample app or blog post implementing this solution.

    I need it very badly.

    RAM31

    Wednesday, April 27, 2016 12:24 PM
  • Hello Syed,

    I wanted to use file server instead of a database, can you help me with the changes to be made. Our solution is built in Silverligh 5 using WCF Ria Services for your information.

    What are the changes to be made to get this working for file server to store the images, only upload images (.png, .jpeg and .bmp)

    Any help on this is greatly appreciated!!

    Thursday, October 19, 2017 4:15 PM