-
Notifications
You must be signed in to change notification settings - Fork 5
Azure Storage Example
Tom Longhurst edited this page Nov 25, 2021
·
4 revisions
public class AzureStorageDataStore : IBDTestDataStore
{
private readonly BlobContainerClient _testRunSummariesContainer;
private readonly BlobContainerClient _testDataContainer;
private readonly JsonSerializer _jsonSerializer = JsonSerializer.Create();
public AzureStorageDataStore()
{
var connectionString = "CONNECTION STRING";
var blobClient = new BlobServiceClient(connectionString);
_testRunSummariesContainer = blobClient.GetBlobContainerClient("test-runs-summaries");
_testRunSummariesContainer.CreateIfNotExists();
_testDataContainer = blobClient.GetBlobContainerClient("test-data");
_testDataContainer.CreateIfNotExists();
}
public async Task<BDTestOutputModel> GetTestData(string id)
{
try
{
var blobData = await _testDataContainer.GetBlockBlobClient(id).DownloadAsync();
return _jsonSerializer.Deserialize<BDTestOutputModel>(new JsonTextReader(new StreamReader(blobData.Value.Content)));
}
catch (RequestFailedException e) when(e.Status == 404)
{
return null;
}
}
public async Task<TestRunSummary[]> GetAllTestRunRecords()
{
var testRunSummaries = new List<TestRunSummary>();
await foreach (var blobItem in _testRunSummariesContainer.GetBlobsAsync())
{
// Keep only the last 30 days
if (blobItem.Properties.CreatedOn < DateTimeOffset.UtcNow - TimeSpan.FromDays(30))
{
await DeleteBlobItem(blobItem);
}
else
{
var downloadAsync = await _testRunSummariesContainer.GetBlockBlobClient(blobItem.Name).DownloadAsync();
var testRunSummary = _jsonSerializer.Deserialize<TestRunSummary>(new JsonTextReader(new StreamReader(downloadAsync.Value.Content)));
testRunSummaries.Add(testRunSummary);
}
}
return testRunSummaries.ToArray();
}
public Task DeleteTestData(string id)
{
return _testDataContainer.DeleteBlobIfExistsAsync(id);
}
public Task DeleteTestRunRecord(string id)
{
return _testRunSummariesContainer.DeleteBlobIfExistsAsync(id);
}
public Task StoreTestData(string id, BDTestOutputModel data)
{
return _testDataContainer.GetBlockBlobClient(id).UploadAsync(data.AsStream());
}
public Task StoreTestRunRecord(TestRunSummary testRunSummary)
{
return _testRunSummariesContainer.GetBlockBlobClient(testRunSummary.RecordId).UploadAsync(testRunSummary.AsStream());
}
private async Task DeleteBlobItem(BlobItem blobItem)
{
await Task.WhenAll(
DeleteTestRunRecord(blobItem.Name),
DeleteTestData(blobItem.Name)
);
}
}
public static class StreamExtensions
{
public static Stream AsStream<T>(this T t)
{
return JsonConvert.SerializeObject(t).AsStream();
}
public static Stream AsStream(this string value)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(value);
writer.Flush();
stream.Position = 0;
return stream;
}
}