Uploader for Silverlight
Step 2 of 4: Adding Code to the Project

In the last step you set up a Silverlight application, but if you run your application now, the button and panel do nothing. In this step we continue in Visual Studio by adding code to your project to implement the C1Uploader class.

To implement the C1Uploader class, complete the following steps:

  1. Navigate to the Solution Explorer, right-click the MainPage.xaml file, and select View Code to switch to Code view.
  2. In Code view, add the following import statements to the top of the page if they are not included:
    Visual Basic
    Copy Code
    Imports System.Windows.Controls
    Imports System.IO
    Imports System.Diagnostics
    Imports C1.Silverlight
    Imports C1.Silverlight.Uploader
    

     

    C#
    Copy Code
    using System.Windows.Controls;
    using System.IO;
    using System.Diagnostics;
    using C1.Silverlight;
    using C1.Silverlight.Uploader;
    
  3. Add the following event handler to the MainPage.xaml.cs file, below all of the other methods in the MainPage class:
    Visual Basic
    Copy Code
    Private Sub Upload_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        ' Configure OpenFileDialog
        Dim dlg As New OpenFileDialog()
        dlg.Filter = "All|*.*|Images|*.jpg;*.png;*.gif"
        dlg.FilterIndex = 2
        dlg.Multiselect = True
     
        ' Show OpenFileDialog
        If CBool(dlg.ShowDialog()) Then
            Try
            ' Check that the files really are images
            For Each fdi As FileInfo In dlg.Files
                Dim img As New System.Windows.Media.Imaging.BitmapImage()
                img.SetSource(fdi.OpenRead())
            Next
            Catch
            C1MessageBox.Show("Sorry, at least one of the selected files is not an image.", 
                    "Upload Canceled", C1MessageBoxButton.OK, C1MessageBoxIcon.Warning)
            Exit Sub
            End Try
     
            ' Create and configure uploader
            Dim uri As Uri = BuildAbsoluteUri("photoUpload.ashx")
            Dim uploader As C1Uploader = New C1UploaderPost(uri)
            AddHandler uploader.UploadProgressChanged, AddressOf uploader_UploadProgressChanged
            AddHandler uploader.UploadCompleted, AddressOf uploader_UploadCompleted
     
            ' Upload selected files
            uploader.AddFiles(dlg.Files)
            uploader.BeginUploadFiles()
        End If
    End Sub 
    

     

    C#
    Copy Code
    private void Upload_Click(object sender, RoutedEventArgs e)
    {
        // Configure OpenFileDialog
        OpenFileDialog dlg = new OpenFileDialog();
        dlg.Filter = "All|*.*|Images|*.jpg;*.png;*.gif";
        dlg.FilterIndex = 2;
        dlg.Multiselect = true;
     
        // Show OpenFileDialog
        if ((bool)dlg.ShowDialog())
        {
            try
            {
                // Check that the files really are images
                foreach (FileInfo fdi in dlg.Files)
                {
                    System.Windows.Media.Imaging.BitmapImage img = new System.Windows.Media.Imaging.BitmapImage();
                    img.SetSource(fdi.OpenRead());
                }
            }
            catch
            {
                C1MessageBox.Show(
                "Sorry, at least one of the selected files doesn't appear to be an image.",
                "Upload Canceled", C1MessageBoxButton.OK, C1MessageBoxIcon.Warning);
                return;
            }
     
            // Create and configure uploader
            Uri uri = BuildAbsoluteUri("photoUpload.ashx");
            C1Uploader uploader = new C1UploaderPost(uri);
            uploader.UploadProgressChanged += uploader_UploadProgressChanged;
            uploader.UploadCompleted += uploader_UploadCompleted;
     
            // Upload selected files
            uploader.AddFiles(dlg.Files);
            uploader.BeginUploadFiles();
        }
    }
    
    This event handler initially displays an OpenFileDialog for the user to select files to upload. Silverlight runs in a secure sandbox environment, and you cannot get direct access to the file system. But the OpenFileDialog class grants access to specific files explicitly selected by the user. You can also get access to files in the IsolatedStorage area.
    Once the files areselected, the code checks whether the files really are images. It does this by creating BitmapImage objects and loading the files into the objects. If the file does not contain an image, then an exception occurs and the process is aborted. This check prevents users from uploading files of the wrong type, either by mistake or with malicious intent. Later, we also perform a similar security check on the server.
    After the files are validated, the code creates a new C1UploaderPost object. There are two types of C1Uploader object, the C1UploaderPost and C1UploaderWebService. The difference between the two is how files are received on the server. C1UploaderPost uses a multipart POST protocol that is very convenient, as you can see in the next steps.
  4. Add the following event handler to your project:
    Visual Basic
    Copy Code
    Public Shared Function BuildAbsoluteUri(ByVal relativeUri As String) As Uri
        ' Get current absolute Uri; this depends on where the app is deployed
        Dim uri As Uri = System.Windows.Browser.HtmlPage.Document.DocumentUri
        Dim uriString As String = uri.AbsoluteUri
     
        ' Replace page name with relative service Uri
        Dim ls As Integer = uriString.LastIndexOf("/"c)
        uriString = uriString.Substring(0, ls + 1) + relativeUri
     
        ' Return new Uri
        Return New Uri(uriString, UriKind.Absolute)
    End Function
    

     

    C#
    Copy Code
    public static Uri BuildAbsoluteUri(string relativeUri)
    {
        // Get current absolute Uri; this depends on where the app is deployed
        Uri uri = System.Windows.Browser.HtmlPage.Document.DocumentUri;
        string uriString = uri.AbsoluteUri;
     
        // Replace page name with relative service Uri
        int ls = uriString.LastIndexOf('/');
        uriString = uriString.Substring(0, ls + 1) + relativeUri;
     
        // Return new Uri
        return new Uri(uriString, UriKind.Absolute);
    }
    
    The C1UploaderPost constructor requires a parameter that specifies the Uri of the handler that processes the files on the server. Silverlight requires an absolute Uri, so the code uses a helper method called BuildAbsoluteUri that works whether the application is running on a development machine or on a production server.
    The code also attaches event handlers to the UploadProgressChanged and UploadCompleted events of the new C1Uploader. The code you add in the next step uses the first to check the progress of the upload process, and the second to display the files that are uploaded.
  5. Add the following event handlers to your project:
    Visual Basic
    Copy Code
    Private Sub uploader_UploadProgressChanged(ByVal sender As Object, ByVal e As C1.Silverlight.Uploader.UploadProgressChangedEventArgs)
        Debug.WriteLine("uploaded {0} of {1} bytes, {2}%", e.BytesUploaded, e.TotalBytesToUpload, e.ProgressPercentage)
    End Sub
    Private Sub uploader_UploadCompleted(ByVal sender As Object, ByVal e As UploadCompletedEventArgs)
        If e.Success Then
            For Each fileName As String In e.Files
            ' Holder for picture and title
            Dim picHolder As New StackPanel()
            picHolder.Width = 200
     
            ' Create Image to show the picture
            Dim bmp As New System.Windows.Media.Imaging.BitmapImage()
            bmp.UriSource = BuildAbsoluteUri("Pictures/" & fileName)
            Dim img As New Image()
            img.Source = bmp
            img.Margin = New Thickness(10, 10, 10, 0)
            picHolder.Children.Add(img)
     
            ' Create image title
            Dim tb As New TextBlock()
            tb.Text = fileName
            tb.FontSize = 12
            tb.HorizontalAlignment = HorizontalAlignment.Center
            tb.Margin = New Thickness(10, 0, 10, 10)
            picHolder.Children.Add(tb)
     
            ' Add picture holder to panel
            PicturePanel.Children.Add(picHolder)
            Next
        Else
            Debug.WriteLine("Upload failed: {0}", If(e.[Error] IsNot Nothing, e.[Error].Message, "??"))
        End If
    End Sub
    

     

    C#
    Copy Code
    void uploader_UploadProgressChanged(object sender, C1.Silverlight.Uploader.UploadProgressChangedEventArgs e)
    {
        Debug.WriteLine("uploaded {0} of {1} bytes, {2}%",
        e.BytesUploaded,
        e.TotalBytesToUpload,
        e.ProgressPercentage);
    }
    void uploader_UploadCompleted(object sender, UploadCompletedEventArgs e)
    {
        if (e.Success)
        {
            foreach (string fileName in e.Files)
            {
                // Holder for picture and title
                StackPanel picHolder = new StackPanel();
                picHolder.Background = new SolidColorBrush(Colors.LightGray);
                picHolder.Margin = new Thickness(10);
                picHolder.Width = 200;
     
                // Create Image to show the picture
                System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
                bmp.UriSource = BuildAbsoluteUri("Pictures/" + fileName);
                Image img = new Image();
                img.Source = bmp;
                img.Margin = new Thickness(10, 10, 10, 0);
                picHolder.Children.Add(img);
     
                // Create image title
                TextBlock tb = new TextBlock();
                tb.Text = fileName;
                tb.FontSize = 12;
                tb.HorizontalAlignment = HorizontalAlignment.Center;
                tb.Margin = new Thickness(10, 0, 10, 10);
                picHolder.Children.Add(tb);
     
                // Add picture holder to panel
                PicturePanel.Children.Add(picHolder);
            }
        }
        else
        {
            Debug.WriteLine("Upload failed: {0}", e.Error != null ? e.Error.Message : "??");
        }
    }
    
    This code checks whether the upload is successful, and then loops through the files to create a new Image element for each one. The Image elements are configured to show the images, assuming they are stored under a "Pictures" folder on the server.

What You've Accomplished

You've successfully created a Silverlight application and added controls to the page. If you run the project now and try to upload some pictures, you get an error. That is because the C1Uploader is sending files to the server, but you have not implemented the server code yet. In the next step we implement the server code.

See Also

 

 


Copyright (c) GrapeCity, inc. All rights reserved.

Product Support Forum  |  Documentation Feedback