aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Transport/Web/StorageBlobUploader.cs
blob: 00600c67994a2dd39f18b62c2ddabca2afdb2150 (plain)
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
53
54
55
56
57
58
59
60
61
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.Core.IO;

namespace Tango.Transport.Web
{
    public class StorageBlobUploader : IDisposable
    {
        private bool _disposed;
        private FileStreamWrapper _stream;

        public CloudBlockBlob Blob { get; private set; }

        public event EventHandler<WebFileDownloaderProgressEventArgs> Progress;

        public StorageBlobUploader(CloudBlockBlob blob, String fileName)
        {
            Blob = blob;
            _stream = new FileStreamWrapper(fileName, FileMode.Open, OnProgress);
        }

        public StorageBlobUploader(String blobAddress, String fileName) : this(new CloudBlockBlob(new Uri(blobAddress)), fileName)
        {

        }

        private void OnProgress(long current)
        {
            Progress?.Invoke(this, new WebFileDownloaderProgressEventArgs()
            {
                Current = current,
                Total = _stream.Length,
            });
        }

        public async Task Upload()
        {
            if (_disposed)
            {
                throw new ObjectDisposedException("The storage blob uploader can only be used once.");
            }

            await Blob.UploadFromStreamAsync(_stream);
            Dispose();
        }

        public void Dispose()
        {
            if (!_disposed)
            {
                _disposed = true;
                _stream.Dispose();
            }
        }
    }
}