Writing to Azure Storage With F#

This last weekend I participated in the "Hack for the Sea" hackathon. As part of that, I needed to store images and structured data to Azure Storage. The process is very straightforward using F#'s async capabilities.

First, you'll need the connection string for your Azure Storage:

Use that to instantiate a CloudStorageAccount object:

let csa = CloudStorageAccount.Parse connectionString

Then, write method(s) to store the data in either Blob storage or Table storage:

    // Put directly in Azure blob storage 
    let photoSubmissionAsync (cloudStorageAccount : CloudStorageAccount) imageType (maybePhoto : IO.Stream option) imageName = 
        async {
            match maybePhoto with 
            | Some byteStream -> 
                let containerName = "marinedebrispix"
                let ctb = cloudStorageAccount.CreateCloudBlobClient()
                let container = ctb.GetContainerReference containerName
                let blob = container.GetBlockBlobReference(imageName) //|> Async.AwaitTask
                blob.Properties.ContentType <- imageType
                do! blob.UploadFromStreamAsync(byteStream) |> Async.AwaitTask
                return true
            | None -> return false
        }

    // Put directly in Azure table storage
    let reportSubmissionAsync (cloudStorageAccount : CloudStorageAccount) report photoName = 
        async {
            let ctc = cloudStorageAccount.CreateCloudTableClient() 
            let table = ctc.GetTableReference("MarineDebris")

            let record = new ReportStorage(report)
            let insertOperation = record |> TableOperation.Insert
            let! tr = table.ExecuteAsync(insertOperation) |> Async.AwaitTask
            return tr.Etag |> Some
        }

The object passed to TableOperation.Insert must be a subclass of TableEntity:

type ReportStorage(report : Report) =
    inherit TableEntity( "MainPartition", report.Timestamp.ToString("o"))

    member val public Report = report |> toJson with get, set