aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Transport/Web/StorageBlobDownloader.cs
blob: dfbd9f93ad7ea6c4eaf5a13413688cb830c50577 (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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 StorageBlobDownloader : IWebFileDownloader
    {
        private bool _disposed;
        private FileStreamWrapper _stream;
        private long _fileSize;
        private String _fileName;

        public CloudBlockBlob Blob { get; private set; }

        public String Address { get; private set; }

        public event EventHandler<WebFileDownloaderProgressEventArgs> Progress;

        public StorageBlobDownloader(CloudBlockBlob blob, String fileName)
        {
            Blob = blob;
            _fileName = fileName;
        }

        public StorageBlobDownloader(String blobAddress, String fileName) : this(new CloudBlockBlob(new Uri(blobAddress)), fileName)
        {
            Address = blobAddress;
        }

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

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

            await Blob.FetchAttributesAsync();
            _fileSize = Blob.Properties.Length;

            _stream = new FileStreamWrapper(_fileName, FileMode.Create, OnProgress);

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

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

                if (_stream != null)
                {
                    _stream.Dispose();
                }
            }
        }

        public async Task<long> GetFileSize()
        {
            await Blob.FetchAttributesAsync();
            return Blob.Properties.Length;
        }
    }
}