public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();
            if (ShouldProcess("BlobDeleteRetentionPolicy", "Disable"))
            {
                switch (ParameterSetName)
                {
                case AccountObjectParameterSet:
                    this.ResourceGroupName  = StorageAccount.ResourceGroupName;
                    this.StorageAccountName = StorageAccount.StorageAccountName;
                    break;

                case PropertiesResourceIdParameterSet:
                    ResourceIdentifier blobServicePropertiesResource = new ResourceIdentifier(ResourceId);
                    this.ResourceGroupName  = blobServicePropertiesResource.ResourceGroupName;
                    this.StorageAccountName = PSBlobServiceProperties.GetStorageAccountNameFromResourceId(ResourceId);
                    break;

                default:
                    // For AccountNameParameterSet, the ResourceGroupName and StorageAccountName can get from input directly
                    break;
                }
                BlobServiceProperties serviceProperties = this.StorageClient.BlobServices.GetServiceProperties(this.ResourceGroupName, this.StorageAccountName);

                serviceProperties.DeleteRetentionPolicy.Enabled = false;
                serviceProperties.DeleteRetentionPolicy.Days    = null;

                serviceProperties = this.StorageClient.BlobServices.SetServiceProperties(this.ResourceGroupName, this.StorageAccountName, serviceProperties);

                if (PassThru)
                {
                    WriteObject(new PSDeleteRetentionPolicy(serviceProperties.DeleteRetentionPolicy));
                }
            }
        }
Exemplo n.º 2
0
        //---------------------------------------------------
        // Configure CORS
        //---------------------------------------------------

        public void ConfigureCORS()
        {
            // <Snippet_ConfigureCORS>

            var connectionString = Constants.connectionString;

            BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);

            BlobServiceProperties sp = blobServiceClient.GetProperties();

            // Set the service properties.
            sp.DefaultServiceVersion = "2013-08-15";
            BlobCorsRule bcr = new BlobCorsRule();

            bcr.AllowedHeaders = "*";

            bcr.AllowedMethods  = "GET,POST";
            bcr.AllowedOrigins  = "http://www.contoso.com";
            bcr.ExposedHeaders  = "x-ms-*";
            bcr.MaxAgeInSeconds = 5;
            sp.Cors.Clear();
            sp.Cors.Add(bcr);
            blobServiceClient.SetProperties(sp);

            // </Snippet_ConfigureCORS>
        }
Exemplo n.º 3
0
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();
            if (ShouldProcess("BlobLastAccessTimeTracking", "Disable"))
            {
                switch (ParameterSetName)
                {
                case AccountObjectParameterSet:
                    this.ResourceGroupName  = StorageAccount.ResourceGroupName;
                    this.StorageAccountName = StorageAccount.StorageAccountName;
                    break;

                default:
                    // For AccountNameParameterSet, the ResourceGroupName and StorageAccountName can get from input directly
                    break;
                }
                BlobServiceProperties serviceProperties = new BlobServiceProperties();

                serviceProperties.LastAccessTimeTrackingPolicy        = new LastAccessTimeTrackingPolicy();
                serviceProperties.LastAccessTimeTrackingPolicy.Enable = false;

                serviceProperties = this.StorageClient.BlobServices.SetServiceProperties(this.ResourceGroupName, this.StorageAccountName, serviceProperties);

                if (PassThru)
                {
                    WriteObject(true);
                }
            }
        }
 public static void DisableStaticWebSite(this BlobServiceProperties properties)
 {
     properties.StaticWebsite.Enabled = false;
     // Avoid error "Element IndexDocument is only expected when StaticWebsite/Enabled is enabled."
     properties.StaticWebsite.ErrorDocument404Path = null;
     properties.StaticWebsite.IndexDocument        = null;
 }
Exemplo n.º 5
0
        public async Task SetPropertiesAsync_StaticWebsite()
        {
            // Arrange
            BlobServiceClient     service    = GetServiceClient_SharedKey();
            BlobServiceProperties properties = await service.GetPropertiesAsync();

            BlobStaticWebsite originalBlobStaticWebsite = properties.StaticWebsite;

            string errorDocument404Path     = "error/404.html";
            string defaultIndexDocumentPath = "index.html";

            properties.StaticWebsite = new BlobStaticWebsite
            {
                Enabled = true,
                ErrorDocument404Path     = errorDocument404Path,
                DefaultIndexDocumentPath = defaultIndexDocumentPath
            };

            // Act
            await service.SetPropertiesAsync(properties);

            // Assert
            properties = await service.GetPropertiesAsync();

            Assert.IsTrue(properties.StaticWebsite.Enabled);
            Assert.AreEqual(errorDocument404Path, properties.StaticWebsite.ErrorDocument404Path);
            Assert.AreEqual(defaultIndexDocumentPath, properties.StaticWebsite.DefaultIndexDocumentPath);

            // Cleanup
            properties.StaticWebsite = originalBlobStaticWebsite;
            await service.SetPropertiesAsync(properties);
        }
 /// <summary>
 /// The <see cref="SetPropertiesInternal"/> operation sets properties for
 /// a storage account’s Blob service endpoint, including properties
 /// for Storage Analytics, CORS (Cross-Origin Resource Sharing) rules
 /// and soft delete settings.  You can also use this operation to set
 /// the default request version for all incoming requests to the Blob
 /// service that do not have a version specified.
 ///
 /// For more information, see <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-service-properties"/>.
 /// </summary>
 /// <param name="properties">The blob service properties.</param>
 /// <param name="async">
 /// Whether to invoke the operation asynchronously.
 /// </param>
 /// <param name="cancellationToken">
 /// Optional <see cref="CancellationToken"/> to propagate
 /// notifications that the operation should be cancelled.
 /// </param>
 /// <returns>
 /// A <see cref="Response"/> describing
 /// the service properties.
 /// </returns>
 /// <remarks>
 /// A <see cref="StorageRequestFailedException"/> will be thrown if
 /// a failure occurs.
 /// </remarks>
 private async Task <Response> SetPropertiesInternal(
     BlobServiceProperties properties,
     bool async,
     CancellationToken cancellationToken)
 {
     using (Pipeline.BeginLoggingScope(nameof(BlobServiceClient)))
     {
         Pipeline.LogMethodEnter(
             nameof(BlobServiceClient),
             message:
             $"{nameof(Uri)}: {Uri}\n" +
             $"{nameof(properties)}: {properties}");
         try
         {
             return(await BlobRestClient.Service.SetPropertiesAsync(
                        Pipeline,
                        Uri,
                        properties,
                        async : async,
                        operationName : Constants.Blob.Service.SetPropertiesOperationName,
                        cancellationToken : cancellationToken)
                    .ConfigureAwait(false));
         }
         catch (Exception ex)
         {
             Pipeline.LogException(ex);
             throw;
         }
         finally
         {
             Pipeline.LogMethodExit(nameof(BlobServiceClient));
         }
     }
 }
Exemplo n.º 7
0
        public async Task ExecuteAction()
        {
            if (bool.TryParse(ArgumentContext.Instance.GetValue(ArgumentEnum.EnableStaticWebSite), out bool enabled))
            {
                Azure.Response <BlobServiceProperties> response = await BlobServiceClientSingleton.Instance.GetBlobServiceClient().GetPropertiesAsync();

                BlobServiceProperties properties = response.Value;
                properties.EnableStaticWebSite(enabled);

                await BlobServiceClientSingleton.Instance.GetBlobServiceClient().SetPropertiesAsync(properties);

                Console.WriteLine("***");

                if (enabled)
                {
                    Console.WriteLine("Enabled Static Web Site:");
                    Console.WriteLine($"IndexDocument: {properties.StaticWebsite.IndexDocument}");
                    Console.WriteLine($"ErrorDocument404Path: {properties.StaticWebsite.ErrorDocument404Path}");
                }
                else
                {
                    Console.WriteLine("Disabled Static Web Site:");
                }

                Console.WriteLine("***");
            }
        }
Exemplo n.º 8
0
 /// <summary>
 /// The <see cref="SetPropertiesAsync"/> operation sets properties for
 /// a storage account’s Blob service endpoint, including properties
 /// for Storage Analytics, CORS (Cross-Origin Resource Sharing) rules
 /// and soft delete settings.  You can also use this operation to set
 /// the default request version for all incoming requests to the Blob
 /// service that do not have a version specified.
 ///
 /// For more information, see <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-service-properties"/>.
 /// </summary>
 /// <param name="properties">The blob service properties.</param>
 /// <param name="cancellation">
 /// Optional <see cref="CancellationToken"/> to propagate
 /// notifications that the operation should be cancelled.
 /// </param>
 /// <returns>
 /// A <see cref="Task{Response{BlobServiceProperties}}"/> describing
 /// the service properties.
 /// </returns>
 /// <remarks>
 /// A <see cref="StorageRequestFailedException"/> will be thrown if
 /// a failure occurs.
 /// </remarks>
 public async Task <Response> SetPropertiesAsync(
     BlobServiceProperties properties,
     CancellationToken cancellation = default)
 {
     using (this._pipeline.BeginLoggingScope(nameof(BlobServiceClient)))
     {
         this._pipeline.LogMethodEnter(
             nameof(BlobServiceClient),
             message:
             $"{nameof(this.Uri)}: {this.Uri}\n" +
             $"{nameof(properties)}: {properties}");
         try
         {
             return(await BlobRestClient.Service.SetPropertiesAsync(
                        this._pipeline,
                        this.Uri,
                        properties,
                        cancellation : cancellation)
                    .ConfigureAwait(false));
         }
         catch (Exception ex)
         {
             this._pipeline.LogException(ex);
             throw;
         }
         finally
         {
             this._pipeline.LogMethodExit(nameof(BlobServiceClient));
         }
     }
 }
 public void Setup()
 {
     blobServiceProperties = new BlobServiceProperties
     {
         StaticWebsite = new BlobStaticWebsite()
     };
 }
Exemplo n.º 10
0
 /// <summary>
 /// The <see cref="SetProperties"/> operation sets properties for
 /// a storage account’s Blob service endpoint, including properties
 /// for Storage Analytics, CORS (Cross-Origin Resource Sharing) rules
 /// and soft delete settings.  You can also use this operation to set
 /// the default request version for all incoming requests to the Blob
 /// service that do not have a version specified.
 ///
 /// For more information, see <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-service-properties"/>.
 /// </summary>
 /// <param name="properties">The blob service properties.</param>
 /// <param name="cancellationToken">
 /// Optional <see cref="CancellationToken"/> to propagate
 /// notifications that the operation should be cancelled.
 /// </param>
 /// <returns>
 /// A <see cref="Response"/> describing
 /// the service properties.
 /// </returns>
 /// <remarks>
 /// A <see cref="StorageRequestFailedException"/> will be thrown if
 /// a failure occurs.
 /// </remarks>
 public virtual Response SetProperties(
     BlobServiceProperties properties,
     CancellationToken cancellationToken = default) =>
 this.SetPropertiesAsync(
     properties,
     false,     // async
     cancellationToken)
 .EnsureCompleted();
Exemplo n.º 11
0
 /// <summary>
 /// The <see cref="SetPropertiesAsync"/> operation sets properties for
 /// a storage account’s Blob service endpoint, including properties
 /// for Storage Analytics, CORS (Cross-Origin Resource Sharing) rules
 /// and soft delete settings.  You can also use this operation to set
 /// the default request version for all incoming requests to the Blob
 /// service that do not have a version specified.
 ///
 /// For more information, see <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-service-properties"/>.
 /// </summary>
 /// <param name="properties">The blob service properties.</param>
 /// <param name="cancellationToken">
 /// Optional <see cref="CancellationToken"/> to propagate
 /// notifications that the operation should be cancelled.
 /// </param>
 /// <returns>
 /// A <see cref="Task{Response}"/> describing
 /// the service properties.
 /// </returns>
 /// <remarks>
 /// A <see cref="StorageRequestFailedException"/> will be thrown if
 /// a failure occurs.
 /// </remarks>
 public virtual async Task <Response> SetPropertiesAsync(
     BlobServiceProperties properties,
     CancellationToken cancellationToken = default) =>
 await this.SetPropertiesAsync(
     properties,
     true,     // async
     cancellationToken)
 .ConfigureAwait(false);
Exemplo n.º 12
0
 public static void EnableStaticWebSite(this BlobServiceProperties properies, bool enable)
 {
     properies.StaticWebsite.Enabled = enable;
     if (enable)
     {
         properies.StaticWebsite.ErrorDocument404Path = ERRORDOCUMENT404PATH;
         properies.StaticWebsite.IndexDocument        = INDEXDOCUMENT;
     }
 }
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();
            if (ShouldProcess("BlobServiceProperties", "Update"))
            {
                switch (ParameterSetName)
                {
                case AccountObjectParameterSet:
                    this.ResourceGroupName  = StorageAccount.ResourceGroupName;
                    this.StorageAccountName = StorageAccount.StorageAccountName;
                    break;

                case PropertiesResourceIdParameterSet:
                    ResourceIdentifier blobServicePropertiesResource = new ResourceIdentifier(ResourceId);
                    this.ResourceGroupName  = blobServicePropertiesResource.ResourceGroupName;
                    this.StorageAccountName = PSBlobServiceProperties.GetStorageAccountNameFromResourceId(ResourceId);
                    break;

                default:
                    // For AccountNameParameterSet, the ResourceGroupName and StorageAccountName can get from input directly
                    break;
                }
                BlobServiceProperties serviceProperties = new BlobServiceProperties();

                if (DefaultServiceVersion != null)
                {
                    serviceProperties.DefaultServiceVersion = this.DefaultServiceVersion;
                }
                if (enableChangeFeed != null)
                {
                    serviceProperties.ChangeFeed         = new ChangeFeed();
                    serviceProperties.ChangeFeed.Enabled = enableChangeFeed;
                    if (this.changeFeedRetentionInDays != null)
                    {
                        serviceProperties.ChangeFeed.RetentionInDays = this.changeFeedRetentionInDays;
                    }
                }
                else
                {
                    if (this.changeFeedRetentionInDays != null)
                    {
                        throw new ArgumentException("ChangeFeed RetentionInDays can only be specified when enable Changefeed.", "ChangeFeedRetentionInDays");
                    }
                }
                if (isVersioningEnabled != null)
                {
                    serviceProperties.IsVersioningEnabled = isVersioningEnabled;
                }

                serviceProperties = this.StorageClient.BlobServices.SetServiceProperties(this.ResourceGroupName, this.StorageAccountName, serviceProperties);

                //Get the full service properties for output
                serviceProperties = this.StorageClient.BlobServices.GetServiceProperties(this.ResourceGroupName, this.StorageAccountName);

                WriteObject(new PSBlobServiceProperties(serviceProperties));
            }
        }
Exemplo n.º 14
0
 public PSBlobServiceProperties(BlobServiceProperties policy)
 {
     this.ResourceGroupName  = (new ResourceIdentifier(policy.Id)).ResourceGroupName;
     this.StorageAccountName = GetStorageAccountNameFromResourceId(policy.Id);
     this.Id   = policy.Id;
     this.Name = policy.Name;
     this.Type = policy.Type;
     this.Cors = policy.Cors is null ? null : new PSCorsRules(policy.Cors);
     this.DefaultServiceVersion = policy.DefaultServiceVersion;
     this.DeleteRetentionPolicy = policy.DeleteRetentionPolicy is null ? null : new PSDeleteRetentionPolicy(policy.DeleteRetentionPolicy);
 }
        public void BlobServiceTest()
        {
            var handler = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var resourcesClient   = StorageManagementTestUtilities.GetResourceManagementClient(context, handler);
                var storageMgmtClient = StorageManagementTestUtilities.GetStorageManagementClient(context, handler);

                // Create resource group
                var rgName = StorageManagementTestUtilities.CreateResourceGroup(resourcesClient);

                // Create storage account
                string accountName = TestUtilities.GenerateName("sto");
                var    parameters  = StorageManagementTestUtilities.GetDefaultStorageAccountParameters();
                var    account     = storageMgmtClient.StorageAccounts.Create(rgName, accountName, parameters);
                StorageManagementTestUtilities.VerifyAccountProperties(account, true);

                // implement case
                try
                {
                    BlobServiceProperties properties1 = storageMgmtClient.BlobServices.GetServiceProperties(rgName, accountName);
                    Assert.False(properties1.DeleteRetentionPolicy.Enabled);
                    Assert.Null(properties1.DeleteRetentionPolicy.Days);
                    Assert.Null(properties1.DefaultServiceVersion);
                    Assert.Equal(0, properties1.Cors.CorsRulesProperty.Count);
                    Assert.Equal(parameters.Sku.Name, properties1.Sku.Name);
                    //Assert.Null(properties1.AutomaticSnapshotPolicyEnabled);
                    BlobServiceProperties properties2 = properties1;
                    properties2.DeleteRetentionPolicy         = new DeleteRetentionPolicy();
                    properties2.DeleteRetentionPolicy.Enabled = true;
                    properties2.DeleteRetentionPolicy.Days    = 300;
                    properties2.DefaultServiceVersion         = "2017-04-17";
                    //properties2.AutomaticSnapshotPolicyEnabled = true;
                    storageMgmtClient.BlobServices.SetServiceProperties(rgName, accountName, properties2);
                    BlobServiceProperties properties3 = storageMgmtClient.BlobServices.GetServiceProperties(rgName, accountName);
                    Assert.True(properties3.DeleteRetentionPolicy.Enabled);
                    Assert.Equal(300, properties3.DeleteRetentionPolicy.Days);
                    Assert.Equal("2017-04-17", properties3.DefaultServiceVersion);
                    //Assert.True(properties3.AutomaticSnapshotPolicyEnabled);
                }
                finally
                {
                    // clean up
                    storageMgmtClient.StorageAccounts.Delete(rgName, accountName);
                    resourcesClient.ResourceGroups.Delete(rgName);
                }
            }
        }
Exemplo n.º 16
0
        public async Task Ctor_AzureSasCredential()
        {
            // Arrange
            await using DisposingContainer test = await GetTestContainerAsync();

            string sas = GetAccountSasCredentials().SasToken;
            Uri    uri = test.Container.GetParentBlobServiceClient().Uri;

            // Act
            var sasClient = InstrumentClient(new BlobServiceClient(uri, new AzureSasCredential(sas), GetOptions()));
            BlobServiceProperties properties = await sasClient.GetPropertiesAsync();

            // Assert
            Assert.IsNotNull(properties);
        }
Exemplo n.º 17
0
        public async Task SetPropertiesAsync_Error()
        {
            // Arrange
            BlobServiceClient     service        = GetServiceClient_SharedKey();
            BlobServiceProperties properties     = (await service.GetPropertiesAsync()).Value;
            BlobServiceClient     invalidService = InstrumentClient(
                new BlobServiceClient(
                    GetServiceClient_SharedKey().Uri,
                    GetOptions()));

            // Act
            await TestHelper.AssertExpectedExceptionAsync <RequestFailedException>(
                invalidService.SetPropertiesAsync(properties),
                e => { });
        }
 public PSBlobServiceProperties(BlobServiceProperties policy)
 {
     this.ResourceGroupName  = (new ResourceIdentifier(policy.Id)).ResourceGroupName;
     this.StorageAccountName = GetStorageAccountNameFromResourceId(policy.Id);
     this.Id   = policy.Id;
     this.Name = policy.Name;
     this.Type = policy.Type;
     this.Cors = policy.Cors is null ? null : new PSCorsRules(policy.Cors);
     this.DefaultServiceVersion          = policy.DefaultServiceVersion;
     this.DeleteRetentionPolicy          = policy.DeleteRetentionPolicy is null ? null : new PSDeleteRetentionPolicy(policy.DeleteRetentionPolicy);
     this.RestorePolicy                  = policy.RestorePolicy is null ? null : new PSRestorePolicy(policy.RestorePolicy);
     this.ChangeFeed                     = policy.ChangeFeed is null ? null : new PSChangeFeed(policy.ChangeFeed);
     this.IsVersioningEnabled            = policy.IsVersioningEnabled;
     this.ContainerDeleteRetentionPolicy = policy.ContainerDeleteRetentionPolicy is null ? null : new PSDeleteRetentionPolicy(policy.ContainerDeleteRetentionPolicy);
     this.LastAccessTimeTrackingPolicy   = policy.LastAccessTimeTrackingPolicy is null? null : new PSLastAccessTimeTrackingPolicy(policy.LastAccessTimeTrackingPolicy);
 }
Exemplo n.º 19
0
        public async Task ExecuteAction()
        {
            if (bool.TryParse(ArgumentContext.Instance.GetValue(ArgumentEnum.EnableStaticWebSite), out bool enabled))
            {
                Azure.Response <BlobServiceProperties> response = await BlobServiceClientSingleton.Instance.GetBlobServiceClient().GetPropertiesAsync();

                BlobServiceProperties properties = response.Value;
                if (enabled)
                {
                    var indexDocument = ArgumentContext.Instance.GetValue(ArgumentEnum.IndexDocument);
                    var errorDocument = ArgumentContext.Instance.GetValue(ArgumentEnum.ErrorDocument);

                    if (string.IsNullOrWhiteSpace(indexDocument))
                    {
                        indexDocument = "index.html";
                    }

                    if (string.IsNullOrWhiteSpace(errorDocument))
                    {
                        indexDocument = "404.html";
                    }

                    properties.EnableStaticWebSite(indexDocument, errorDocument);
                }
                else
                {
                    properties.DisableStaticWebSite();
                }

                await BlobServiceClientSingleton.Instance.GetBlobServiceClient().SetPropertiesAsync(properties);

                Console.WriteLine("***");

                if (enabled)
                {
                    Console.WriteLine("Enabled Static Web Site:");
                    Console.WriteLine($"  IndexDocument: {properties.StaticWebsite.IndexDocument}");
                    Console.WriteLine($"  ErrorDocument404Path: {properties.StaticWebsite.ErrorDocument404Path}");
                }
                else
                {
                    Console.WriteLine("Disabled Static Web Site.");
                }

                Console.WriteLine("***");
            }
        }
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();
            if (ShouldProcess("BlobServiceProperties", "Update"))
            {
                switch (ParameterSetName)
                {
                case AccountObjectParameterSet:
                    this.ResourceGroupName  = StorageAccount.ResourceGroupName;
                    this.StorageAccountName = StorageAccount.StorageAccountName;
                    break;

                case PropertiesResourceIdParameterSet:
                    ResourceIdentifier blobServicePropertiesResource = new ResourceIdentifier(ResourceId);
                    this.ResourceGroupName  = blobServicePropertiesResource.ResourceGroupName;
                    this.StorageAccountName = PSBlobServiceProperties.GetStorageAccountNameFromResourceId(ResourceId);
                    break;

                default:
                    // For AccountNameParameterSet, the ResourceGroupName and StorageAccountName can get from input directly
                    break;
                }
                BlobServiceProperties serviceProperties = null;

                serviceProperties = this.StorageClient.BlobServices.GetServiceProperties(this.ResourceGroupName, this.StorageAccountName);

                if (DefaultServiceVersion != null)
                {
                    serviceProperties.DefaultServiceVersion = this.DefaultServiceVersion;
                }
                if (enableChangeFeed != null)
                {
                    serviceProperties.ChangeFeed         = new ChangeFeed();
                    serviceProperties.ChangeFeed.Enabled = enableChangeFeed;
                }
                if (isVersioningEnabled != null)
                {
                    serviceProperties.IsVersioningEnabled = isVersioningEnabled;
                }

                serviceProperties = this.StorageClient.BlobServices.SetServiceProperties(this.ResourceGroupName, this.StorageAccountName, serviceProperties);

                WriteObject(new PSBlobServiceProperties(serviceProperties));
            }
        }
        //-------------------------------------------------
        // Enable soft delete
        //-------------------------------------------------

        private static void EnableSoftDelete()
        {
            var connectionString = Constants.connectionString;
            BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);

            // Get the blob client's service property settings
            BlobServiceProperties serviceProperties = blobServiceClient.GetProperties().Value;

            // <Snippet_EnableSoftDelete>

            // Configure soft delete
            serviceProperties.DeleteRetentionPolicy.Enabled = true;
            serviceProperties.DeleteRetentionPolicy.Days    = 7;

            // Set the blob client's service property settings
            blobServiceClient.SetProperties(serviceProperties);

            // </Snippet_EnableSoftDelete>
        }
Exemplo n.º 22
0
        public void Setup()
        {
            _exceptionHandler        = new TestExceptionHandler();
            _loggerProvider          = new TestLoggerProvider();
            _blobClientMock          = new Mock <BlobServiceClient>(new Uri("https://fakeaccount.blob.core.windows.net/"), null);
            _blobContainerMock       = new Mock <BlobContainerClient>(new Uri("https://fakeaccount.blob.core.windows.net/fakecontainer"), null);
            _secondBlobContainerMock = new Mock <BlobContainerClient>(new Uri("https://fakeaccount.blob.core.windows.net/fakecontainer2"), null);
            _logsContainerMock       = new Mock <BlobContainerClient>(new Uri("https://fakeaccount.blob.core.windows.net/$logs"), null);
            _serviceProperties       = new BlobServiceProperties();
            _blobItems       = new List <BlobItem>();
            _secondBlobItems = new List <BlobItem>();
            var loggerFactory = new LoggerFactory();

            loggerFactory.AddProvider(_loggerProvider);
            _logger = loggerFactory.CreateLogger <BlobListener>();
            _blobClientMock.Setup(x => x.Uri).Returns(new Uri("https://fakeaccount.blob.core.windows.net/"));
            _blobClientMock.Setup(x => x.GetBlobContainerClient("fakecontainer")).Returns(_blobContainerMock.Object);
            _blobClientMock.Setup(x => x.GetBlobContainerClient("fakecontainer2")).Returns(_secondBlobContainerMock.Object);
            _blobClientMock.Setup(x => x.GetBlobContainerClient("$logs")).Returns(_logsContainerMock.Object);
            _blobContainerMock.Setup(x => x.Uri).Returns(new Uri("https://fakeaccount.blob.core.windows.net/fakecontainer"));
            _blobContainerMock.Setup(x => x.Name).Returns(ContainerName);
            _blobContainerMock.Setup(x => x.AccountName).Returns(AccountName);
            _secondBlobContainerMock.Setup(x => x.Uri).Returns(new Uri("https://fakeaccount.blob.core.windows.net/fakecontainer2"));
            _secondBlobContainerMock.Setup(x => x.Name).Returns(SecondContainerName);
            _secondBlobContainerMock.Setup(x => x.AccountName).Returns(AccountName);
            _blobClientMock.Setup(x => x.GetPropertiesAsync(It.IsAny <CancellationToken>())).ReturnsAsync(Response.FromValue(_serviceProperties, null));
            _blobContainerMock.Setup(x => x.GetBlobsAsync(It.IsAny <BlobTraits>(), It.IsAny <BlobStates>(), It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .Returns(() =>
            {
                return(new TestAsyncPageable <BlobItem>(_blobItems));
            });
            _secondBlobContainerMock.Setup(x => x.GetBlobsAsync(It.IsAny <BlobTraits>(), It.IsAny <BlobStates>(), It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .Returns(() =>
            {
                return(new TestAsyncPageable <BlobItem>(_secondBlobItems));
            });
            _logsContainerMock.Setup(x => x.GetBlobsAsync(It.IsAny <BlobTraits>(), It.IsAny <BlobStates>(), It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .Returns(() =>
            {
                return(new TestAsyncPageable <BlobItem>(new List <BlobItem>()));
            });
        }
Exemplo n.º 23
0
        //-------------------------------------------------
        // Enable diagnostic logs
        //-------------------------------------------------

        public void EnableDiagnosticLogs()
        {
            var connectionString = Constants.connectionString;

            BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);

            BlobServiceProperties serviceProperties = blobServiceClient.GetProperties().Value;

            serviceProperties.Logging.Delete = true;

            BlobRetentionPolicy retentionPolicy = new BlobRetentionPolicy();

            retentionPolicy.Enabled = true;
            retentionPolicy.Days    = 2;
            serviceProperties.Logging.RetentionPolicy = retentionPolicy;

            blobServiceClient.SetProperties(serviceProperties);

            Console.WriteLine("Diagnostic logs are now enabled");
        }
Exemplo n.º 24
0
        //-------------------------------------------------
        // Update log retention period
        //-------------------------------------------------

        public void UpdateLogRetentionPeriod()
        {
            var connectionString = Constants.connectionString;

            // <Snippet_ViewRetentionPeriod>
            BlobServiceClient  blobServiceClient  = new BlobServiceClient(connectionString);
            QueueServiceClient queueServiceClient = new QueueServiceClient(connectionString);

            BlobServiceProperties  blobServiceProperties  = blobServiceClient.GetProperties().Value;
            QueueServiceProperties queueServiceProperties = queueServiceClient.GetProperties().Value;

            Console.WriteLine("Retention period for logs from the blob service is: " +
                              blobServiceProperties.Logging.RetentionPolicy.Days.ToString());

            Console.WriteLine("Retention period for logs from the queue service is: " +
                              queueServiceProperties.Logging.RetentionPolicy.Days.ToString());
            // </Snippet_ViewRetentionPeriod>

            // <Snippet_ModifyRetentionPeriod>
            BlobRetentionPolicy blobRetentionPolicy = new BlobRetentionPolicy();

            blobRetentionPolicy.Enabled = true;
            blobRetentionPolicy.Days    = 4;

            QueueRetentionPolicy queueRetentionPolicy = new QueueRetentionPolicy();

            queueRetentionPolicy.Enabled = true;
            queueRetentionPolicy.Days    = 4;

            blobServiceProperties.Logging.RetentionPolicy = blobRetentionPolicy;
            blobServiceProperties.Cors = null;

            queueServiceProperties.Logging.RetentionPolicy = queueRetentionPolicy;
            queueServiceProperties.Cors = null;

            blobServiceClient.SetProperties(blobServiceProperties);
            queueServiceClient.SetProperties(queueServiceProperties);

            Console.WriteLine("Retention policy for blobs and queues is updated");
            // </Snippet_ModifyRetentionPeriod>
        }
        public static async Task EnableLoggingAsync(BlobServiceClient blobClient, CancellationToken cancellationToken)
        {
            BlobServiceProperties serviceProperties = await blobClient.GetPropertiesAsync(cancellationToken).ConfigureAwait(false);

            // Merge write onto it.
            BlobAnalyticsLogging loggingProperties = serviceProperties.Logging;

            if (!loggingProperties.Write)
            {
                // First activating. Be sure to set a retention policy if there isn't one.
                loggingProperties.Write           = true;
                loggingProperties.RetentionPolicy = new BlobRetentionPolicy()
                {
                    Enabled = true,
                    Days    = 7,
                };

                // Leave metrics untouched
                await blobClient.SetPropertiesAsync(serviceProperties, cancellationToken).ConfigureAwait(false);
            }
        }
Exemplo n.º 26
0
        // </Snippet_GetAccountSASToken>

        //-------------------------------------------------
        // Use Account SAS Token
        //-------------------------------------------------

        // <Snippet_UseAccountSAS>

        private static void UseAccountSAS(Uri blobServiceUri, string sasToken)
        {
            var blobServiceClient = new BlobServiceClient
                                        (new Uri($"{blobServiceUri}?{sasToken}"), null);

            BlobRetentionPolicy retentionPolicy = new BlobRetentionPolicy();

            retentionPolicy.Enabled = true;
            retentionPolicy.Days    = 7;

            blobServiceClient.SetProperties(new BlobServiceProperties()
            {
                HourMetrics = new BlobMetrics()
                {
                    RetentionPolicy = retentionPolicy,
                    Version         = "1.0"
                },
                MinuteMetrics = new BlobMetrics()
                {
                    RetentionPolicy = retentionPolicy,
                    Version         = "1.0"
                },
                Logging = new BlobAnalyticsLogging()
                {
                    Write           = true,
                    Read            = true,
                    Delete          = true,
                    RetentionPolicy = retentionPolicy,
                    Version         = "1.0"
                }
            });

            // The permissions granted by the account SAS also permit you to retrieve service properties.

            BlobServiceProperties serviceProperties = blobServiceClient.GetProperties().Value;

            Console.WriteLine(serviceProperties.HourMetrics.RetentionPolicy);
            Console.WriteLine(serviceProperties.HourMetrics.Version);
        }
Exemplo n.º 27
0
        private static string CreateStaticWeb(string storageName, string rgName, string region, IAzure azureContext, ILogger log)
        {
            string connectionString = string.Empty;

            Microsoft.Azure.Management.Storage.Fluent.IStorageAccount storageAccount =
                azureContext.StorageAccounts.Define(storageName).
                WithRegion(region).
                WithExistingResourceGroup(rgName).
                WithGeneralPurposeAccountKindV2().
                Create();
            // Get connection keys
            IReadOnlyList <Microsoft.Azure.Management.Storage.Fluent.Models.StorageAccountKey> saKeys = storageAccount.GetKeys();
            string key = string.Empty;

            foreach (Microsoft.Azure.Management.Storage.Fluent.Models.StorageAccountKey item in saKeys)
            {
                // Use the key1
                if (item.KeyName.Equals(KEY1))
                {
                    key = item.Value;
                }
            }
            // need to set the storage properties to enable static web site
            connectionString = GetStorageConnectionString(key, storageName, log);
            BlobServiceClient     blobServiceClient = new BlobServiceClient(connectionString);
            BlobServiceProperties myProps           = blobServiceClient.GetProperties();

            myProps.StaticWebsite.Enabled              = true;
            myProps.StaticWebsite.IndexDocument        = "index.html";
            myProps.StaticWebsite.ErrorDocument404Path = "error/index.html";
            log.LogInformation(myProps.StaticWebsite.ToString());


            blobServiceClient.SetProperties(myProps);
            log.LogInformation("DeployWeb: got static web enabled");

            return(connectionString);
        }
Exemplo n.º 28
0
        public async Task SetPropertiesAsync()
        {
            // Arrange
            BlobServiceClient     service    = GetServiceClient_SharedKey();
            BlobServiceProperties properties = await service.GetPropertiesAsync();

            BlobCorsRule[] originalCors = properties.Cors.ToArray();
            properties.Cors =
                new[]
            {
                new BlobCorsRule
                {
                    MaxAgeInSeconds = 1000,
                    AllowedHeaders  = "x-ms-meta-data*,x-ms-meta-target*,x-ms-meta-abc",
                    AllowedMethods  = "PUT,GET",
                    AllowedOrigins  = "*",
                    ExposedHeaders  = "x-ms-meta-*"
                }
            };

            // Act
            await service.SetPropertiesAsync(properties);

            // Assert
            properties = await service.GetPropertiesAsync();

            Assert.AreEqual(1, properties.Cors.Count());
            Assert.IsTrue(properties.Cors[0].MaxAgeInSeconds == 1000);

            // Cleanup
            properties.Cors = originalCors;
            await service.SetPropertiesAsync(properties);

            properties = await service.GetPropertiesAsync();

            Assert.AreEqual(originalCors.Count(), properties.Cors.Count());
        }
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();
            switch (ParameterSetName)
            {
            case AccountObjectParameterSet:
                this.ResourceGroupName  = StorageAccount.ResourceGroupName;
                this.StorageAccountName = StorageAccount.StorageAccountName;
                break;

            case PropertiesResourceIdParameterSet:
                ResourceIdentifier blobServicePropertiesResource = new ResourceIdentifier(ResourceId);
                this.ResourceGroupName  = blobServicePropertiesResource.ResourceGroupName;
                this.StorageAccountName = PSBlobServiceProperties.GetStorageAccountNameFromResourceId(ResourceId);
                break;

            default:
                // For AccountNameParameterSet, the ResourceGroupName and StorageAccountName can get from input directly
                break;
            }
            BlobServiceProperties serviceProperties = this.StorageClient.BlobServices.GetServiceProperties(this.ResourceGroupName, this.StorageAccountName);

            WriteObject(new PSBlobServiceProperties(serviceProperties));
        }
Exemplo n.º 30
0
        public void BlobServiceCorsTest()
        {
            var handler = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient   = StorageManagementTestUtilities.GetResourceManagementClient(context, handler);
                var storageMgmtClient = StorageManagementTestUtilities.GetStorageManagementClient(context, handler);

                // Create resource group
                var rgName = StorageManagementTestUtilities.CreateResourceGroup(resourcesClient);

                // Create storage account
                string accountName = TestUtilities.GenerateName("sto");
                var    parameters  = StorageManagementTestUtilities.GetDefaultStorageAccountParameters();
                var    account     = storageMgmtClient.StorageAccounts.Create(rgName, accountName, parameters);
                StorageManagementTestUtilities.VerifyAccountProperties(account, true);

                // implement case
                try
                {
                    BlobServiceProperties properties1 = storageMgmtClient.BlobServices.GetServiceProperties(rgName, accountName);
                    BlobServiceProperties properties2 = new BlobServiceProperties();
                    properties2.DeleteRetentionPolicy         = new DeleteRetentionPolicy();
                    properties2.DeleteRetentionPolicy.Enabled = true;
                    properties2.DeleteRetentionPolicy.Days    = 300;
                    properties2.DefaultServiceVersion         = "2017-04-17";
                    properties2.Cors = new CorsRules();
                    properties2.Cors.CorsRulesProperty = new List <CorsRule>();
                    properties2.Cors.CorsRulesProperty.Add(new CorsRule()
                    {
                        AllowedHeaders  = new string[] { "x-ms-meta-abc", "x-ms-meta-data*", "x-ms-meta-target*" },
                        AllowedMethods  = new string[] { "GET", "HEAD", "POST", "OPTIONS", "MERGE", "PUT" },
                        AllowedOrigins  = new string[] { "http://www.contoso.com", "http://www.fabrikam.com" },
                        ExposedHeaders  = new string[] { "x-ms-meta-*" },
                        MaxAgeInSeconds = 100
                    });
                    properties2.Cors.CorsRulesProperty.Add(new CorsRule()
                    {
                        AllowedHeaders  = new string[] { "*" },
                        AllowedMethods  = new string[] { "GET" },
                        AllowedOrigins  = new string[] { "*" },
                        ExposedHeaders  = new string[] { "*" },
                        MaxAgeInSeconds = 2
                    });
                    properties2.Cors.CorsRulesProperty.Add(new CorsRule()
                    {
                        AllowedHeaders  = new string[] { "x-ms-meta-12345675754564*" },
                        AllowedMethods  = new string[] { "GET", "PUT", "CONNECT" },
                        AllowedOrigins  = new string[] { "http://www.abc23.com", "https://www.fabrikam.com/*" },
                        ExposedHeaders  = new string[] { "x-ms-meta-abc", "x-ms-meta-data*", "x -ms-meta-target*" },
                        MaxAgeInSeconds = 2000
                    });

                    BlobServiceProperties properties3 = storageMgmtClient.BlobServices.SetServiceProperties(rgName, accountName, properties2);
                    Assert.True(properties3.DeleteRetentionPolicy.Enabled);
                    Assert.Equal(300, properties3.DeleteRetentionPolicy.Days);
                    Assert.Equal("2017-04-17", properties3.DefaultServiceVersion);

                    //Validate CORS Rules
                    Assert.Equal(properties2.Cors.CorsRulesProperty.Count, properties3.Cors.CorsRulesProperty.Count);
                    for (int i = 0; i < properties2.Cors.CorsRulesProperty.Count; i++)
                    {
                        CorsRule putRule = properties2.Cors.CorsRulesProperty[i];
                        CorsRule getRule = properties3.Cors.CorsRulesProperty[i];

                        Assert.Equal(putRule.AllowedHeaders, getRule.AllowedHeaders);
                        Assert.Equal(putRule.AllowedMethods, getRule.AllowedMethods);
                        Assert.Equal(putRule.AllowedOrigins, getRule.AllowedOrigins);
                        Assert.Equal(putRule.ExposedHeaders, getRule.ExposedHeaders);
                        Assert.Equal(putRule.MaxAgeInSeconds, getRule.MaxAgeInSeconds);
                    }

                    BlobServiceProperties properties4 = storageMgmtClient.BlobServices.GetServiceProperties(rgName, accountName);
                    Assert.True(properties4.DeleteRetentionPolicy.Enabled);
                    Assert.Equal(300, properties4.DeleteRetentionPolicy.Days);
                    Assert.Equal("2017-04-17", properties4.DefaultServiceVersion);

                    //Validate CORS Rules
                    Assert.Equal(properties2.Cors.CorsRulesProperty.Count, properties4.Cors.CorsRulesProperty.Count);
                    for (int i = 0; i < properties2.Cors.CorsRulesProperty.Count; i++)
                    {
                        CorsRule putRule = properties2.Cors.CorsRulesProperty[i];
                        CorsRule getRule = properties4.Cors.CorsRulesProperty[i];

                        Assert.Equal(putRule.AllowedHeaders, getRule.AllowedHeaders);
                        Assert.Equal(putRule.AllowedMethods, getRule.AllowedMethods);
                        Assert.Equal(putRule.AllowedOrigins, getRule.AllowedOrigins);
                        Assert.Equal(putRule.ExposedHeaders, getRule.ExposedHeaders);
                        Assert.Equal(putRule.MaxAgeInSeconds, getRule.MaxAgeInSeconds);
                    }
                }
                finally
                {
                    // clean up
                    storageMgmtClient.StorageAccounts.Delete(rgName, accountName);
                    resourcesClient.ResourceGroups.Delete(rgName);
                }
            }
        }