0

I have a web api that uses a bunch of appSettings files to load test data. I want to shift the location of that data to an Azure Blob. Based on the test infrastructure, I'd like to convert the Blob into an IConfiguration object.

To accomplish this, I wanted to use the AddJsonStream onto a ConfigurationBuilder.

I created this method to go out and grab the blob and convert it to a stream:

    public static Stream GetBlobAsStream(Uri blobURI)
    {
        var storageAccount = CloudStorageAccount.Parse(AZURE_STORAGE_CONNECTION_STRING);
        var cloudBlobClient = storageAccount.CreateCloudBlobClient();
        var cloudBlobContainer = cloudBlobClient.GetContainerReference(blobContainer);
        var cloudBlob = cloudBlobContainer.GetBlockBlobReference(blobName);
        var stream = cloudBlob.OpenRead();
        return stream;
    }

Now this method uses a bunch of hard coded constants - which I'd like to remove. How can I remove the hard coding, and find the needed azure info based on the Environment in which it's being run? Or have I programmed myself into a corner here?

Rolan
  • 2,924
  • 7
  • 34
  • 46
  • Two questions: 1) I am assuming that your `AZURE_STORAGE_CONNECTION_STRING` is coming from settings. Correct? and 2) How does your `blobUri` look like? Is it `https://account.blob.core.windows.net/container-name/blob-name`? – Gaurav Mantri May 01 '20 at 03:05
  • @GauravMantri-AIS 1) It's coming from a hard-coded string in my code. 2) Yep, that's exactly what it looks like. – Rolan May 01 '20 at 04:10
  • Thanks. And if I understand correctly, you would want to use this blob url and the connection string to get the blob content. Is that correct? – Gaurav Mantri May 01 '20 at 04:14
  • Yep, that's right. – Rolan May 01 '20 at 04:17
  • Provided an answer. Hope this is what you're looking for. – Gaurav Mantri May 01 '20 at 04:23

1 Answers1

1

You could try to create an instance of CloudBlockBlob using the Blob URI and Blob Client by doing something like:

public static Stream GetBlobAsStream(Uri blobURI)
{
    var storageAccount = CloudStorageAccount.Parse(AZURE_STORAGE_CONNECTION_STRING);
    var cloudBlobClient = storageAccount.CreateCloudBlobClient();
    var cloudBlob = new CloudBlockBlob(blobURI, cloudBlobClient);
    var stream = cloudBlob.OpenRead();
    return stream;
}

or create an instance of CloudBlockBlob using the Blob URI and Storage Credentials by doing something like:

public static Stream GetBlobAsStream(Uri blobURI)
{
    var storageAccount = CloudStorageAccount.Parse(AZURE_STORAGE_CONNECTION_STRING);
    var cloudBlob = new CloudBlockBlob(blobURI, storageAccount.Credentials);
    var stream = cloudBlob.OpenRead();
    return stream;
}
Gaurav Mantri
  • 128,066
  • 12
  • 206
  • 241
  • Looks good. I'll just throw those strings into a local json file, and use the approaches you listed. Thanks! – Rolan May 01 '20 at 17:09