Exemplo n.º 1
0
        public void CreateDirectoryIfNotExists(string path)
        {
            path = AzureBlobsLogsInterface.PathFixer(path);
            var logClient = _blobsContainerClient.GetAppendBlobClient(path);

            if (!logClient.Exists())
            {
                logClient.Create();
            }
        }
Exemplo n.º 2
0
        protected override AppendBlobClient GetResourceClient(BlobContainerClient container, string resourceName = null, BlobClientOptions options = null)
        {
            Argument.AssertNotNull(container, nameof(container));

            string blobName = resourceName ?? GetNewResourceName();

            if (options == null)
            {
                return(container.GetAppendBlobClient(blobName));
            }

            container = InstrumentClient(new BlobContainerClient(container.Uri, Tenants.GetNewSharedKeyCredentials(), options ?? ClientBuilder.GetOptions()));
            return(InstrumentClient(container.GetAppendBlobClient(blobName)));
        }
        /// <summary>
        /// Sends the events.
        /// </summary>
        /// <param name="events">The events that need to be send.</param>
        /// <remarks>
        /// <para>
        /// The subclass must override this method to process the buffered events.
        /// </para>
        /// </remarks>
        protected override void SendBuffer(LoggingEvent[] events)
        {
            AppendBlobClient appendBlob = _cloudBlobContainer.GetAppendBlobClient(Filename(_directoryName));

            if (!appendBlob.Exists())
            {
                appendBlob.Create();
            }
            else
            {
                _lineFeed = Environment.NewLine;
            }

            Parallel.ForEach(events, ProcessEvent);
        }
Exemplo n.º 4
0
        public async Task CreateAppendBlob_ImmutableStorageWithVersioning()
        {
            // Arrange
            AppendBlobClient appendBlob = InstrumentClient(_containerClient.GetAppendBlobClient(GetNewBlobName()));

            BlobImmutabilityPolicy immutabilityPolicy = new BlobImmutabilityPolicy
            {
                ExpiresOn  = Recording.UtcNow.AddMinutes(5),
                PolicyMode = BlobImmutabilityPolicyMode.Unlocked
            };

            // The service rounds Immutability Policy Expiry to the nearest second.
            DateTimeOffset expectedImmutabilityPolicyExpiry = RoundToNearestSecond(immutabilityPolicy.ExpiresOn.Value);

            AppendBlobCreateOptions options = new AppendBlobCreateOptions
            {
                ImmutabilityPolicy = immutabilityPolicy,
                HasLegalHold       = true
            };

            // Act
            Response <BlobContentInfo> createResponse = await appendBlob.CreateAsync(options);

            // Assert
            Response <BlobProperties> propertiesResponse = await appendBlob.GetPropertiesAsync();

            Assert.AreEqual(expectedImmutabilityPolicyExpiry, propertiesResponse.Value.ImmutabilityPolicy.ExpiresOn);
            Assert.AreEqual(immutabilityPolicy.PolicyMode, propertiesResponse.Value.ImmutabilityPolicy.PolicyMode);
            Assert.IsTrue(propertiesResponse.Value.HasLegalHold);
        }
Exemplo n.º 5
0
        private async Task WriteToDataFabric(string routeKey, Stream stream, CancellationToken cancellationToken)
        {
            if (_diagnostic != null && _diagnostic.IsEnabled() && _diagnostic.IsEnabled(DiagnosticOperations.MessageProcess))
            {
                _diagnostic.Write(DiagnosticOperations.DataFabricWrite, _config);
            }

            //Create a unique name for the blob
            var containerName = $"{_config.ContainerNamePrefix}-{routeKey}";

            var containerClient = new BlobContainerClient(_config.StorageConnectionString, containerName);

            await containerClient.CreateIfNotExistsAsync(cancellationToken : cancellationToken);

            var blobName =
                $"{_config.BlobNamePrefix}-{DateTime.UtcNow.ToString(string.IsNullOrEmpty(_config.BlobNameRollingTimeFormat) ? "yyyyMMdd" : _config.BlobNameRollingTimeFormat)}";

            var blobClient = containerClient.GetAppendBlobClient(blobName);

            var blobInfo =
                await blobClient.CreateIfNotExistsAsync(cancellationToken : cancellationToken);

            Console.WriteLine("Appending to Blob storage as blob:\n\t {0}\n", blobClient.Uri);

            await blobClient.AppendBlockAsync(stream, null,
                                              new AppendBlobRequestConditions { IfMatch = blobInfo?.Value.ETag }, cancellationToken : cancellationToken);
        }
 public static Task <BlobBaseClient> GetBlobReferenceForArgumentTypeAsync(this BlobContainerClient container,
                                                                          string blobName, Type argumentType, CancellationToken cancellationToken)
 {
     if (argumentType == typeof(BlobClient))
     {
         BlobBaseClient blob = container.GetBlobClient(blobName);
         return(Task.FromResult(blob));
     }
     else if (argumentType == typeof(BlockBlobClient))
     {
         BlobBaseClient blob = container.GetBlockBlobClient(blobName);
         return(Task.FromResult(blob));
     }
     else if (argumentType == typeof(PageBlobClient))
     {
         BlobBaseClient blob = container.GetPageBlobClient(blobName);
         return(Task.FromResult(blob));
     }
     else if (argumentType == typeof(AppendBlobClient))
     {
         BlobBaseClient blob = container.GetAppendBlobClient(blobName);
         return(Task.FromResult(blob));
     }
     else
     {
         return(GetExistingOrNewBlockBlobReferenceAsync(container, blobName, cancellationToken));
     }
 }
Exemplo n.º 7
0
            private async Task <IEnumerable <T> > ConvertBlobs(IAsyncEnumerable <BlobItem> blobItems, BlobContainerClient blobContainerClient)
            {
                var list = new List <T>();

                await foreach (var blobItem in blobItems.ConfigureAwait(false))
                {
                    BlobBaseClient src = null;
                    switch (blobItem.Properties.BlobType)
                    {
                    case BlobType.Block:
                        src = blobContainerClient.GetBlockBlobClient(blobItem.Name);
                        break;

                    case BlobType.Append:
                        src = blobContainerClient.GetAppendBlobClient(blobItem.Name);
                        break;

                    case BlobType.Page:
                        src = blobContainerClient.GetPageBlobClient(blobItem.Name);
                        break;

                    default:
                        throw new InvalidOperationException($"Unexpected blob type {blobItem.Properties.BlobType}");
                    }

                    var funcCtx  = new FunctionBindingContext(Guid.Empty, CancellationToken.None);
                    var valueCtx = new ValueBindingContext(funcCtx, CancellationToken.None);

                    var converted = await _converter(src, null, valueCtx).ConfigureAwait(false);

                    list.Add(converted);
                }

                return(list);
            }
Exemplo n.º 8
0
        public void WithSnapshot()
        {
            var containerName = GetNewContainerName();
            var blobName      = GetNewBlobName();

            BlobServiceClient service = GetServiceClient_SharedKey();

            BlobContainerClient container = InstrumentClient(service.GetBlobContainerClient(containerName));

            AppendBlobClient blob = InstrumentClient(container.GetAppendBlobClient(blobName));

            var builder = new BlobUriBuilder(blob.Uri);

            Assert.AreEqual("", builder.Snapshot);

            blob = InstrumentClient(blob.WithSnapshot("foo"));

            builder = new BlobUriBuilder(blob.Uri);

            Assert.AreEqual("foo", builder.Snapshot);

            blob = InstrumentClient(blob.WithSnapshot(null));

            builder = new BlobUriBuilder(blob.Uri);

            Assert.AreEqual("", builder.Snapshot);
        }
Exemplo n.º 9
0
        private async Task <AppendBlobClient> CreateBlob(BlobContainerClient containerClient)
        {
            AppendBlobClient appendBlobClient = containerClient.GetAppendBlobClient(_fileName);
            await appendBlobClient.CreateIfNotExistsAsync();

            return(appendBlobClient);
        }
Exemplo n.º 10
0
        private async Task PushToDataFabric(string routingKey, Stream stream, CancellationToken stoppingToken)
        {
            stoppingToken.ThrowIfCancellationRequested();

            //Create a unique name for the blob
            var containerName = $"{_config.ContainerNamePrefix}-{routingKey}";

            var containerClient = new BlobContainerClient(_config.StorageConnectionString, containerName);

            await containerClient.CreateIfNotExistsAsync(cancellationToken : stoppingToken);

            stoppingToken.ThrowIfCancellationRequested();

            var blobName =
                $"{_config.BlobNamePrefix}-{DateTime.UtcNow.ToString(string.IsNullOrEmpty(_config.BlobNameRollingTimeFormat) ? "yyyyMMdd" : _config.BlobNameRollingTimeFormat)}";

            var blobClient = containerClient.GetAppendBlobClient(blobName);

            var blobInfo =
                await blobClient.CreateIfNotExistsAsync(cancellationToken : stoppingToken);

            stoppingToken.ThrowIfCancellationRequested();

            _logger.LogInformation("Appending to Blob storage as blob:\n\t {0}\n", blobClient.Uri);

            await blobClient.AppendBlockAsync(stream, null,
                                              new AppendBlobRequestConditions { IfMatch = blobInfo?.Value.ETag }, cancellationToken : stoppingToken);
        }
Exemplo n.º 11
0
            /// <summary>
            /// Initializes the BLOB.
            /// </summary>
            /// <param name="blobName">Name of the BLOB.</param>
            private async Task <AppendBlobClient> InitializeBlob(string blobName, BlobContainerClient blobContainer, string contentType, CancellationToken cancellationToken)
            {
                var appendBlob = blobContainer.GetAppendBlobClient(blobName);

                var blobExits = await appendBlob.ExistsAsync(cancellationToken).ConfigureAwait(false);

                if (blobExits)
                {
                    return(appendBlob);
                }

                var blobCreateOptions = new Azure.Storage.Blobs.Models.AppendBlobCreateOptions();
                var httpHeaders       = new Azure.Storage.Blobs.Models.BlobHttpHeaders()
                {
                    ContentType     = contentType,
                    ContentEncoding = Encoding.UTF8.WebName,
                };

                blobCreateOptions.HttpHeaders = httpHeaders;
                blobCreateOptions.Metadata    = _blobMetadata;  // Optional custom metadata to set for this append blob.
                blobCreateOptions.Tags        = _blobTags;      // Options tags to set for this append blob.

                await appendBlob.CreateIfNotExistsAsync(blobCreateOptions, cancellationToken).ConfigureAwait(false);

                return(appendBlob);
            }
Exemplo n.º 12
0
        public async Task UploadRangeFromUriAsync_SourceBearerTokenFail()
        {
            // Arrange
            BlobServiceClient blobServiceClient = InstrumentClient(new BlobServiceClient(
                                                                       new Uri(Tenants.TestConfigOAuth.BlobServiceEndpoint),
                                                                       Tenants.GetOAuthCredential(Tenants.TestConfigOAuth),
                                                                       GetBlobOptions()));
            BlobContainerClient containerClient = InstrumentClient(blobServiceClient.GetBlobContainerClient(GetNewShareName()));

            try
            {
                await containerClient.CreateIfNotExistsAsync();

                AppendBlobClient appendBlobClient = InstrumentClient(containerClient.GetAppendBlobClient(GetNewFileName()));
                await appendBlobClient.CreateAsync();

                byte[] data = GetRandomBuffer(Constants.KB);
                using Stream stream = new MemoryStream(data);
                await appendBlobClient.AppendBlockAsync(stream);

                ShareServiceClient serviceClient = SharesClientBuilder.GetServiceClient_OAuthAccount_SharedKey();
                await using DisposingShare test = await GetTestShareAsync(
                                service : serviceClient,
                                shareName : GetNewShareName());

                ShareDirectoryClient directoryClient = InstrumentClient(test.Share.GetDirectoryClient(GetNewDirectoryName()));
                await directoryClient.CreateAsync();

                ShareFileClient fileClient = InstrumentClient(directoryClient.GetFileClient(GetNewFileName()));
                await fileClient.CreateAsync(Constants.KB);

                HttpAuthorization sourceAuthHeader = new HttpAuthorization(
                    "Bearer",
                    "auth token");

                ShareFileUploadRangeFromUriOptions options = new ShareFileUploadRangeFromUriOptions
                {
                    SourceAuthentication = sourceAuthHeader
                };

                HttpRange range = new HttpRange(0, Constants.KB);

                // Act
                await TestHelper.AssertExpectedExceptionAsync <RequestFailedException>(
                    fileClient.UploadRangeFromUriAsync(
                        sourceUri: appendBlobClient.Uri,
                        range: range,
                        sourceRange: range,
                        options: options),
                    e => Assert.AreEqual("CannotVerifyCopySource", e.ErrorCode));
            }
            finally
            {
                await containerClient.DeleteIfExistsAsync();
            }
        }
Exemplo n.º 13
0
        public async Task UploadRangeFromUriAsync_SourceBearerToken()
        {
            // Arrange
            BlobServiceClient blobServiceClient = InstrumentClient(new BlobServiceClient(
                                                                       new Uri(TestConfigOAuth.BlobServiceEndpoint),
                                                                       GetOAuthCredential(TestConfigOAuth),
                                                                       GetBlobOptions()));
            BlobContainerClient containerClient = InstrumentClient(blobServiceClient.GetBlobContainerClient(GetNewShareName()));

            try
            {
                await containerClient.CreateIfNotExistsAsync();

                AppendBlobClient appendBlobClient = InstrumentClient(containerClient.GetAppendBlobClient(GetNewFileName()));
                await appendBlobClient.CreateAsync();

                byte[] data = GetRandomBuffer(Constants.KB);
                using Stream stream = new MemoryStream(data);
                await appendBlobClient.AppendBlockAsync(stream);

                ShareServiceClient serviceClient = GetServiceClient_OAuth_SharedKey();
                await using DisposingShare test = await GetTestShareAsync(
                                service : serviceClient,
                                shareName : GetNewShareName());

                ShareDirectoryClient directoryClient = InstrumentClient(test.Share.GetDirectoryClient(GetNewDirectoryName()));
                await directoryClient.CreateAsync();

                ShareFileClient fileClient = InstrumentClient(directoryClient.GetFileClient(GetNewFileName()));
                await fileClient.CreateAsync(Constants.KB);

                string sourceBearerToken = await GetAuthToken();

                HttpAuthorization sourceAuthHeader = new HttpAuthorization(
                    "Bearer",
                    sourceBearerToken);

                ShareFileUploadRangeFromUriOptions options = new ShareFileUploadRangeFromUriOptions
                {
                    SourceAuthentication = sourceAuthHeader
                };

                HttpRange range = new HttpRange(0, Constants.KB);

                // Act
                await fileClient.UploadRangeFromUriAsync(
                    sourceUri : appendBlobClient.Uri,
                    range : range,
                    sourceRange : range,
                    options : options);
            }
            finally
            {
                await containerClient.DeleteIfExistsAsync();
            }
        }
Exemplo n.º 14
0
        private void ProcessEvent(LoggingEvent loggingEvent)
        {
            AppendBlobClient appendBlob = _cloudBlobContainer.GetAppendBlobClient(Filename(loggingEvent, _directoryName));
            var xml = loggingEvent.GetXmlString(Layout);

            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
            {
                appendBlob.AppendBlock(ms);
            }
        }
Exemplo n.º 15
0
        public async Task AppendBlockAsync_WithUnreliableConnection()
        {
            const int blobSize = 1 * Constants.MB;

            await using DisposingContainer test = await GetTestContainerAsync();

            BlobContainerClient containerFaulty = InstrumentClient(
                new BlobContainerClient(
                    test.Container.Uri,
                    new StorageSharedKeyCredential(
                        TestConfigDefault.AccountName,
                        TestConfigDefault.AccountKey),
                    GetFaultyBlobConnectionOptions()));

            // Arrange
            var blobName = GetNewBlobName();
            AppendBlobClient blobFaulty = InstrumentClient(containerFaulty.GetAppendBlobClient(blobName));
            AppendBlobClient blob       = InstrumentClient(test.Container.GetAppendBlobClient(blobName));

            await blob.CreateAsync();

            var data            = GetRandomBuffer(blobSize);
            var progressList    = new List <long>();
            var progressHandler = new Progress <long>(progress => { progressList.Add(progress); /*logger.LogTrace("Progress: {progress}", progress.BytesTransferred);*/ });
            var timesFaulted    = 0;

            // Act
            using (var stream = new FaultyStream(
                       new MemoryStream(data),
                       256 * Constants.KB,
                       1,
                       new IOException("Simulated stream fault"),
                       () => timesFaulted++))
            {
                await blobFaulty.AppendBlockAsync(stream, progressHandler : progressHandler);
                await WaitForProgressAsync(progressList, data.LongLength);

                Assert.IsTrue(progressList.Count > 1, "Too few progress received");
                // Changing from Assert.AreEqual because these don't always update fast enough
                Assert.GreaterOrEqual(data.LongLength, progressList.Last(), "Final progress has unexpected value");
            }

            // Assert
            Response <BlobDownloadInfo> downloadResponse = await blob.DownloadAsync();

            var actual = new MemoryStream();
            await downloadResponse.Value.Content.CopyToAsync(actual);

            Assert.AreEqual(data.Length, actual.Length);
            TestHelper.AssertSequenceEqual(data, actual.ToArray());
            Assert.AreNotEqual(0, timesFaulted);
        }
Exemplo n.º 16
0
        protected override async Task <AppendBlobClient> GetResourceClientAsync(
            BlobContainerClient container,
            int resourceLength        = default,
            bool createResource       = default,
            string resourceName       = null,
            BlobClientOptions options = null)
        {
            container = InstrumentClient(new BlobContainerClient(container.Uri, Tenants.GetNewSharedKeyCredentials(), options ?? ClientBuilder.GetOptions()));
            var appendBlob = InstrumentClient(container.GetAppendBlobClient(resourceName ?? GetNewResourceName()));

            if (createResource)
            {
                await appendBlob.CreateAsync();
            }
            return(appendBlob);
        }
Exemplo n.º 17
0
        public async Task AppendLog(string value)
        {
            var blobContainerClient = new BlobContainerClient(_blobStorageSettings.ConnectionString, _blobStorageSettings.ContainerName);

            await blobContainerClient.CreateIfNotExistsAsync();

            var fileSuffix = DateTime.UtcNow.Date.ToString();

            var blob = blobContainerClient.GetAppendBlobClient($"{_blobStorageSettings.FilePrefix}-{fileSuffix}");

            await blob.CreateIfNotExistsAsync();

            var content = $"{value} \n";
            var stream  = new MemoryStream(Encoding.UTF8.GetBytes(content));

            await blob.AppendBlockAsync(stream);
        }
        public async Task DeleteArchivedBlobsAsync(BlobServiceClient blobServiceClient, string blobContainerName, string blobNameFormat, int retainedBlobCountLimit)
        {
            if (retainedBlobCountLimit < 1)
            {
                throw new ArgumentException("Invalid value provided; retained blob count limit must be at least 1 or null.");
            }

            BlobContainerClient blobContainer = blobServiceClient.GetBlobContainerClient(blobContainerName);
            List <BlobItem>     logBlobs      = new List <BlobItem>();

            AsyncPageable <BlobItem> blobItems = blobContainer.GetBlobsAsync();

            IAsyncEnumerator <BlobItem> enumerator = blobItems.GetAsyncEnumerator();

            try
            {
                while (await enumerator.MoveNextAsync())
                {
                    logBlobs.Add(enumerator.Current);
                }
            }
            finally
            {
                await enumerator.DisposeAsync();
            }

            IEnumerable <BlobItem> validLogBlobs = logBlobs.Where(blobItem => DateTime.TryParseExact(
                                                                      RemoveRolledBlobNameSerialNum(blobItem.Name),
                                                                      blobNameFormat,
                                                                      CultureInfo.InvariantCulture,
                                                                      DateTimeStyles.AssumeLocal,
                                                                      out var _date));

            IEnumerable <BlobItem> blobsToDelete = validLogBlobs
                                                   .OrderByDescending(blobItem => blobItem.Name)
                                                   .Skip(retainedBlobCountLimit);

            foreach (var blobItem in blobsToDelete)
            {
                AppendBlobClient blobToDelete = blobContainer.GetAppendBlobClient(blobItem.Name);

                await blobToDelete.DeleteIfExistsAsync();
            }
        }
        public static async Task <(BlobBaseClient, BlobProperties)> GetBlobReferenceFromServerAsync(this BlobContainerClient container, string blobName, CancellationToken cancellationToken = default)
        {
            BlobProperties blobProperties = await container.GetBlobClient(blobName).GetPropertiesAsync(cancellationToken: cancellationToken).ConfigureAwait(false);

            switch (blobProperties.BlobType)
            {
            case BlobType.Append:
                return(container.GetAppendBlobClient(blobName), blobProperties);

            case BlobType.Block:
                return(container.GetBlockBlobClient(blobName), blobProperties);

            case BlobType.Page:
                return(container.GetPageBlobClient(blobName), blobProperties);

            default:
                throw new InvalidOperationException();
            }
        }
Exemplo n.º 20
0
        public async Task AppendBlobSample()
        {
            // Instantiate a new BlobServiceClient using a connection string.
            BlobServiceClient blobServiceClient = new BlobServiceClient(TestConfigurations.DefaultTargetTenant.ConnectionString);

            // Instantiate a new BlobContainerClient
            BlobContainerClient blobContainerClient = blobServiceClient.GetBlobContainerClient("mycontainer4");

            try
            {
                // Create new Container in the Service
                await blobContainerClient.CreateAsync();

                // Instantiate a new PageBlobClient
                AppendBlobClient appendBlobClient = blobContainerClient.GetAppendBlobClient("appendblob");

                // Create PageBlob in the Service
                await appendBlobClient.CreateAsync();

                // Append content to AppendBlob
                using (FileStream fileStream = File.OpenRead("Samples/SampleSource.txt"))
                {
                    await appendBlobClient.AppendBlockAsync(fileStream);
                }

                // Download PageBlob
                using (FileStream fileStream = File.Create("AppendDestination.txt"))
                {
                    Response <BlobDownloadInfo> downloadResponse = await appendBlobClient.DownloadAsync();

                    await downloadResponse.Value.Content.CopyToAsync(fileStream);
                }

                // Delete PageBlob in the Service
                await appendBlobClient.DeleteAsync();
            }
            finally
            {
                // Delete Container in the Service
                await blobContainerClient.DeleteAsync();
            }
        }
Exemplo n.º 21
0
        public AzureBlobsLogWriter(BlobContainerClient blobsContainerClient,
                                   string fileName,
                                   bool appendOpen = false)
        {
            fileName = AzureBlobsLogsInterface.PathFixer(fileName);
            _blobsContainerClient = blobsContainerClient;
            _logClient            = _blobsContainerClient.GetAppendBlobClient(fileName);
            ETag currentETag;

            if (_previousOpenAttempts.ContainsKey(fileName) && appendOpen)
            {
                // We've opened this blob before and want to be non-destructive. We don't need to CreateIfNotExists, which could be VERY slow.
                currentETag = _logClient.GetProperties().Value.ETag;
            }
            else
            {
                try
                {
                    // Create the file non-destructively if needed, guaranteeing write continuity on creation by grabbing the etag of the create, if needed
                    if (appendOpen)
                    {
                        var response = _logClient.CreateIfNotExists();
                        if (response != null)
                        {
                            currentETag = response.Value.ETag;
                        }
                        else
                        {
                            currentETag = _logClient.GetProperties().Value.ETag;
                        }
                    }
                    else
                    {
                        currentETag = _logClient.Create().Value.ETag;
                    }
                }
                catch { currentETag = _logClient.GetProperties().Value.ETag; }
            }
            // Try to grab the blob lease
            _leaseClient = _logClient.GetBlobLeaseClient();
            // The blob hasn't be touched since the last time. This is a candidate for breaking the lease.
            if (_previousOpenAttempts.ContainsKey(fileName) && (_previousOpenAttempts[fileName].ToString().Equals(currentETag.ToString())))
            {
                _previousOpenAttempts[fileName] = currentETag;
                // The blob hasn't been updated. Try to break the lease and reacquire
                var requestConditions = new BlobRequestConditions();
                requestConditions         = new BlobRequestConditions();
                requestConditions.IfMatch = currentETag;
                // If the condition fails in the break, it's because someone else managed to touch the file, so give up
                ETag newETag;
                try
                {
                    newETag = _leaseClient.Break(null, requestConditions).Value.ETag;
                }
                catch (Exception e) { newETag = currentETag; }
                var etagCondition = new RequestConditions();
                etagCondition.IfMatch = newETag;
                // If the condition fails, someone snuck in and grabbed the lock before we could. Give up.
                _curLease = _leaseClient.Acquire(TimeSpan.FromSeconds(-1), etagCondition).Value;
            }
            else
            {
                // Not a candidate for breaking the lease. Just try to acquire.
                _previousOpenAttempts[fileName] = currentETag;
                _curLease = _leaseClient.Acquire(TimeSpan.FromSeconds(-1)).Value;
            }

            _leaseCondition         = new AppendBlobRequestConditions();
            _leaseCondition.LeaseId = _curLease.LeaseId;
            // We got the lease! Set up thread to periodically touch the blob to prevent others from breaking the lease.
            _blobMetadata        = _logClient.GetProperties().Value.Metadata;
            _stopRelockThread    = false;
            _relockThreadStopped = false;
            _leaseRenewThread    = new Thread(() =>
            {
                while (!_stopRelockThread)
                {
                    Thread.Sleep(100);
                    var response = _logClient.SetMetadata(_blobMetadata, _leaseCondition);
                }
                _relockThreadStopped = true;
            })
            {
                IsBackground = true
            };
            _leaseRenewThread.Start();
            _bytesToSend = new MemoryStream();
            Debug.Assert(_logClient.Exists());
        }
Exemplo n.º 22
0
#pragma warning disable CA1806 // Do not ignore method results
        public override void Run(CancellationToken cancellationToken)
        {
            // traverse hierarchy down
            BlobServiceClient.GetBlobContainerClient(ContainerName);
            BlobContainerClient.GetBlobClient(BlobName);
            BlobContainerClient.GetBlobBaseClient(BlobName);
            BlobContainerClient.GetBlockBlobClient(BlobName);
            BlobContainerClient.GetPageBlobClient(BlobName);
            BlobContainerClient.GetAppendBlobClient(BlobName);

            // traverse hierarchy up
            BlobClient.GetParentBlobContainerClient();
            BlobContainerClient.GetParentBlobServiceClient();

            // BlobServiceClient ctors
            new BlobServiceClient(s_connectionString);
            new BlobServiceClient(BlobServiceClient.Uri);
            new BlobServiceClient(BlobServiceClient.Uri, s_azureSasCredential);
            new BlobServiceClient(BlobServiceClient.Uri, s_tokenCredential);
            new BlobServiceClient(BlobServiceClient.Uri, StorageSharedKeyCredential);

            // BlobContainerClient ctors
            new BlobContainerClient(s_connectionString, ContainerName);
            new BlobContainerClient(BlobContainerClient.Uri);
            new BlobContainerClient(BlobContainerClient.Uri, s_azureSasCredential);
            new BlobContainerClient(BlobContainerClient.Uri, s_tokenCredential);
            new BlobContainerClient(BlobContainerClient.Uri, StorageSharedKeyCredential);

            // BlobClient ctors
            new BlobClient(s_connectionString, ContainerName, BlobName);
            new BlobClient(BlobContainerClient.Uri);
            new BlobClient(BlobContainerClient.Uri, s_azureSasCredential);
            new BlobClient(BlobContainerClient.Uri, s_tokenCredential);
            new BlobClient(BlobContainerClient.Uri, StorageSharedKeyCredential);

            // BlobBaseClient ctors
            new BlobBaseClient(s_connectionString, ContainerName, BlobName);
            new BlobBaseClient(BlobContainerClient.Uri);
            new BlobBaseClient(BlobContainerClient.Uri, s_azureSasCredential);
            new BlobBaseClient(BlobContainerClient.Uri, s_tokenCredential);
            new BlobBaseClient(BlobContainerClient.Uri, StorageSharedKeyCredential);

            // AppendBlobClient ctors
            new AppendBlobClient(s_connectionString, ContainerName, BlobName);
            new AppendBlobClient(BlobContainerClient.Uri);
            new AppendBlobClient(BlobContainerClient.Uri, s_azureSasCredential);
            new AppendBlobClient(BlobContainerClient.Uri, s_tokenCredential);
            new AppendBlobClient(BlobContainerClient.Uri, StorageSharedKeyCredential);

            // BlockBlobClient ctors
            new BlockBlobClient(s_connectionString, ContainerName, BlobName);
            new BlockBlobClient(BlobContainerClient.Uri);
            new BlockBlobClient(BlobContainerClient.Uri, s_azureSasCredential);
            new BlockBlobClient(BlobContainerClient.Uri, s_tokenCredential);
            new BlockBlobClient(BlobContainerClient.Uri, StorageSharedKeyCredential);

            // PageBlobClient ctors
            new PageBlobClient(s_connectionString, ContainerName, BlobName);
            new PageBlobClient(BlobContainerClient.Uri);
            new PageBlobClient(BlobContainerClient.Uri, s_azureSasCredential);
            new PageBlobClient(BlobContainerClient.Uri, s_tokenCredential);
            new PageBlobClient(BlobContainerClient.Uri, StorageSharedKeyCredential);
        }