This repository has been archived by the owner on Aug 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileHostedService.cs
52 lines (44 loc) · 1.91 KB
/
FileHostedService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.Blob;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace AzureDockerTest
{
public class FileHostedService : IHostedService
{
readonly ILogger<FileHostedService> _logger;
readonly CloudBlobContainer _container;
readonly string _appendBlobFileName;
public FileHostedService(ILogger<FileHostedService> logger, IConfiguration configuration)
{
_logger = logger;
_container = CloudStorageAccount.Parse(configuration["BlobStorageConnection"])
.CreateCloudBlobClient()
.GetContainerReference(configuration["BlobContainerName"]);
_appendBlobFileName = configuration["AppendBlobFileName"];
}
public async Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Starting!");
await _container.CreateIfNotExistsAsync(cancellationToken);
CloudAppendBlob blob = _container.GetAppendBlobReference(_appendBlobFileName);
if (!await blob.ExistsAsync(cancellationToken))
{
await blob.UploadTextAsync(_appendBlobFileName + "\n", cancellationToken);
blob.Properties.ContentType = "text/plain";
await blob.SetPropertiesAsync(cancellationToken);
}
await blob.AppendTextAsync($"Started {DateTime.UtcNow:G}\n", cancellationToken);
}
public async Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Stopping!");
CloudAppendBlob blob = _container.GetAppendBlobReference(_appendBlobFileName);
await blob.AppendTextAsync($"Ended {DateTime.UtcNow:G}\n", cancellationToken);
}
}
}