Nick's .NET Travels

Continually looking for the yellow brick road so I can catch me a wizard....

Fixing up the Client For Writing to Azure Blob Storage with Shared Access Signature

In my previous post I updated the service logic for retrieving the Shared Access Signature (SAS) to return the full Url of the blob container including the SAS. In order for this to work I also need to update the client logic. This gets much simpler as I can simply construct a new CloudBlockBlob by amending the Url to include the name of the blob to be written to.

private async void CaptureClick(object sender, RoutedEventArgs e)
{
    var picker = new MediaPicker();
    var sas = string.Empty;
    using (var media = await picker.PickPhotoAsync())
    using (var strm = media.GetStream())
    {
        sas = await CurrentViewModel.RetrieveSharedAccessSignature();

        // Append the image file name to the Path (this will
        // retain the SAS as it's in the query string
        var builder = new UriBuilder(sas);
        builder.Path += "/testimage" + Path.GetExtension(media.Path);
        var imageUri = builder.Uri;

        // Upload the new image as a BLOB from the stream.
        var blob = new CloudBlockBlob(imageUri);
        await blob.UploadFromStreamAsync(strm.AsInputStream());
    }
}

But, we can actually do even better…. what we get back is a Url, including the SAS, for the blob container. So we can use the Azure Storage library to create a CloudBlobContainer and then acquire the blob reference from there – this does the work of combining the urls for us.

private async void CaptureClick(object sender, RoutedEventArgs e)
{
    var picker = new MediaPicker();
    var sas = string.Empty;
    using (var media = await picker.PickPhotoAsync())
    using (var strm = media.GetStream())
    {
        sas = await CurrentViewModel.RetrieveSharedAccessSignature();
        var container = new CloudBlobContainer(new Uri(sas));
        var blobFromContainer = container.GetBlockBlobReference("testimage" + Path.GetExtension(media.Path));
        await blobFromContainer.UploadFromStreamAsync(strm.AsInputStream());
    }
}

Pingbacks and trackbacks (1)+

Comments are closed