SLightS3 Code Samples

Update: C# Demo project was added and demo applications now updated for version 1.2.0.
Sample projects are available for download at the bottom of this document.  Before testing, please ensure that the proper clientaccesspolicy.xml file has been uploaded to your target bucket.  We've also included a rough XAML sample that will work with the following source code examples.

Setting Up the S3Uploader
The SLightS3 S3Uploader uses the traditional .NET Event model.  To handle events for your S3Uploader, declare it as follows:
Example VB.NET
    Imports parentElement.S3
    Imports parentElement.S3.SLightS3

    Partial Public Class MainPage
        Inherits UserControl

        Protected WithEvents sls3 As New S3Uploader

        ...
Example C#
    using parentElement.S3;
    using parentElement.S3.SLightS3;

    public partial class MainPage : UserControl
    {
        protected S3Uploader sls3 = new S3Uploader();

        ...
Setting the Initial Properties
Once you've created an instance of the S3Uploader, you're ready to start setting the initial properties.
Example VB.NET
    Public Sub New()
        InitializeComponent()

        With sls3
            .AWSAccessKey = "YourAWSAccessKeyHere"
            .BucketName = "yourbucket"
            .Expires = DateTime.Now.AddHours(2.0)
            .ACL = ACL.PublicRead
        End With
    End Sub
Example C#
    public New()
    {
        InitializeComponent();
   
        sls3.AWSAccessKey = "YourAWSAccessKeyHere";
        sls3.BucketName = "yourbucket";
        sls3.Expires = DateTime.Now.AddHours(2.0);
        sls3.ACL = ACL.PublicRead;
    }
Loading a file to upload
The following sample code demonstrates prompting a user to load a file.  S3Uploader currently does not have a mechanism to automatically restrict the size of the loaded file, however it does expose a FileSize property which you can use to check the size of the file before uploading.
Example VB.NET
    'Without file extension filtering   
    If sls3.LoadFile() Then
        'This example just uses the loaded file name as the key.
        sls3.Key = sls3.LoadedFileName
    End If

    'With example filtering for Jpg and Gif images and Txt Text files.  Use
    'the same filter string you would use for a normal OpenFileDialog.
    If sls3.LoadFile("Images|*.jpg;*.gif|Text Files(*.txt) |*.txt") Then
        'This example just uses the loaded file name as the key.
        sls3.Key = sls3.LoadedFileName
    End If
Example C#
     //Without file extension filtering
    if (sls3.LoadFile())
    {
        //This example just uses the loaded file name as the key.
        sls3.Key = sls3.LoadedFileName;
    }

    //With example filtering for Jpg and Gif images and Txt Text files. Use
    //the same filter string you would use for a normal OpenFileDialog.

    if (sls3.LoadFile("Images|*.jpg;*.gif|Text Files(*.txt) |*.txt"))
    {
        //This example just uses the loaded file name as the key.
        sls3.Key = sls3.LoadedFileName;
    }
Starting Your Upload
This example demonstrates how to set the signed policy and start the upload process.  Uploads are handled asynchronously by the S3Uploader object so they will not block your UI or program execution.  In this example, we've used a SignedPolicyGenerator documented on the Policy Signing page.  This is for testing and example purposes only.  We recommend never storing your AWS Secret Key in your Silverlight application or making it accessible to the outside world.  A better solution would be to create a secure web service accessible to your application and use it to sign your policy document.  The example source code for policy generate can be easily used in your web service.
Example VB.NET
    'Set the signed policy. We're using the SLightS3.SignedPolicyGenerator in this example, however we
    'strongly discourage storing your AWS Secret Key in your Silverlight application. A more appropriate
    'approach would be to use a secured external service to generate the policy document.

    sls3.SignedPolicy = SLightS3.SignedPolicyGenerator.GetSignedPolicy(sls3.UnsignedPolicy, "yourAWSSecretKey")

    'We're making our progress bar visible and setting it to 0
    'The progress bar in this example has a range of 0 to 100 (representing % complete)
.
    ProgressBar1.Visibility = Visibility.Visible
    ProgressBar1.Value = 0

    'Start the upload. File upload is handled asynchronously by
    'the S3Uploader object.

    sls3.UploadFile()
Example C#
    //Set the signed policy. We're using the SLightS3.SignedPolicyGenerator in this example, however we
   //strongly discourage storing your AWS Secret Key in your Silverlight application. A more appropriate
   //approach would be to use a secured external service to generate the policy document.

   sls3.SignedPolicy = SLightS3.SignedPolicyGenerator.GetSignedPolicy(sls3.UnsignedPolicy, "yourAWSSecretKey");

   //We're making our progress bar visible and setting it to 0
   //The progress bar in this example has a range of 0 to 100 (representing % complete).

   ProgressBar1.Visibility = Visibility.Visible;
   ProgressBar1.Value = 0;

   //Start the upload. File upload is handled asynchronously by
   //the S3Uploader object.

   sls3.UploadFile();
Handling S3Uploader Events
This example shows how to handle and react to S3Uploader events, such as the UploadAborted event which is fired when the S3Uploader.Abort( ) method is called.  This example shows only some of the values exposed by each event arguments object.  For a complete listing, check out the technical documentation and follow the links to each event arguments page.
Example VB.NET
    Protected Sub UploadStarted(ByVal s As Object, ByVal e As parentElement.S3.SLightS3.UploadStartedEventArgs) Handles sls3.UploadStarted
       Dim totalBytes As Long
       totalBytes = e.TotalBytes
   End Sub

   Protected Sub UploadProgressChanged(ByVal s As Object, ByVal e As parentElement.S3.SLightS3.ProgressChangedEventArgs) Handles sls3.UploadProgressChanged
        ProgressBar1.Value = e.PercentComplete
   End Sub

   Protected Sub UploadComplete(ByVal s As Object, ByVal e As parentElement.S3.SLightS3.UploadCompletedEventArgs) Handles sls3.UploadCompleted
        ProgressBar1.Visibility = Visibility.Collapsed
    End Sub

    Protected Sub UploadAborted(ByVal s As Object, ByVal e As parentElement.S3.SLightS3.UploadAbortedEventArgs) Handles sls3.UploadAborted
        System.Windows.Browser.HtmlPage.Window.Alert("Upload aborted by user. " & e.BytesSent & " bytes of " & e.TotalBytes & " bytes were sent.")
        ProgressBar1.Value = 0   
        ProgressBar1.Visibility = Visibility.Collapsed
    End Sub
Example C#
     protected void UploadStarted(object s, parentElement.S3.SLightS3.UploadStartedEventArgs e)
    {
        long totalBytes;
        totalBytes = e.TotalBytes;
    }

    protected void UploadProgressChanged(object s, parentElement.S3.SLightS3.ProgressChangedEventArgs e)
    {
        ProgressBar1.Value = e.PercentComplete;
     }

    protected void UploadComplete(object s, parentElement.S3.SLightS3.UploadCompletedEventArgs e)
    {
        ProgressBar1.Visibility = Visibility.Collapsed;
        tbProgress.Text = String.Empty;
    }

    protected void UploadAborted(object s, parentElement.S3.SLightS3.UploadAbortedEventArgs e)
    {
        System.Windows.Browser.HtmlPage.Window.Alert("Upload aborted by user. " + e.BytesSent + " bytes of " + e.TotalBytes + " bytes were sent.");
        ProgressBar1.Value = 0;
        ProgressBar1.Visibility = Visibility.Collapsed;
    }
Sample Project XAML 
Here is the XAML for the sample project code above:
Example XAML
     <UserControl x:Class="SLightContainer.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="385" d:DesignWidth="792"
        xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

        <Grid x:Name="LayoutRoot" Background="White" Height="107" Width="625">
            <Button Content="Load File" Height="27" HorizontalAlignment="Left" Margin="260,12,0,0" Name="btnLoad" VerticalAlignment="Top" Width="100" />
            <Button Content="Upload" Height="27" HorizontalAlignment="Left" Margin="12,59,0,0" Name="btnUpload" VerticalAlignment="Top" Width="100" />
            <ProgressBar Height="36" HorizontalAlignment="Left" Margin="126,54,0,0" Name="ProgressBar1" VerticalAlignment="Top" Width="367" />
            <Button Content="Cancel" Height="27" HorizontalAlignment="Right" Margin="0,59,12,0" Name="btnCancel" VerticalAlignment="Top" Width="100" />
        </Grid>
    </UserControl>
Sample Project 
Note: This download contains a Visual Studio 2010 / Silverlight 4 project, but does not contain SLightS3.  You will need to download SLightS3 and add a reference to the project before it will compile.  Please refer to the Readme file included in the download for a link to the SLightS3 download.  In addition, new features were added in version 1.1.0.  These include three new properties (TotalBytes, BytesWritten, IsUploading) which are bindable as the library now implments INotifyPropertyChanged. 

Also available is the OverrideBuffer method, giving you more advanced control over the size of each "chunk" sent to the server and the frequency that the UI is updated.  There is also a new LoadFromFileStream method that allows you to supply your own data stream.

Sample Project (VB .NET)
Sample Project (C#)