Exemplo n.º 1
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.º 2
0
        /// <summary>
        /// Use a connection string to connect to a Storage account.
        ///
        /// A connection string includes the authentication information
        /// required for your application to access data in an Azure Storage
        /// account at runtime using Shared Key authorization.
        /// </summary>
        public AzureBlobAdapter(IAzureBlobSettings azureBlobSettings)
        {
            Path = new PathWrapper(this);

            AzureBlobSettingsData = azureBlobSettings;

            //authentication methods
            //https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/storage/Azure.Storage.Blobs/samples/Sample02_Auth.cs
            // Create a BlobServiceClient object which will be used to create a container client
            BlobServiceClientObject = new BlobServiceClient(azureBlobSettings.ConnectionString);

            // Make a service request to verify we've successfully authenticated
            var servicePropertiesResponse = BlobServiceClientObject.GetProperties();

            BlobServicePropertiesObject = servicePropertiesResponse.Value;

            StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential(
                azureBlobSettings.StorageAccountName, azureBlobSettings.Key);

            DataLakeServiceClientObject = new DataLakeServiceClient(new Uri(azureBlobSettings.StorageAccountUrl), sharedKeyCredential);

            File      = new AzureFile(this);
            DriveInfo = new AzureDriveInfoFactory(this);
            Directory = new AzureDirectory(this);
        }
        public void AuthWithConnectionString()
        {
            string connectionString = this.ConnectionString;

            #region Snippet:SampleSnippetsBlobMigration_ConnectionString
            BlobServiceClient service = new BlobServiceClient(connectionString);
            #endregion

            service.GetProperties();
            Assert.Pass();
        }
        public void AuthWithTokenCredential()
        {
            string serviceUri = this.StorageAccountBlobUri.ToString();

            #region Snippet:SampleSnippetsBlobMigration_TokenCredential
            BlobServiceClient client = new BlobServiceClient(new Uri(serviceUri), new DefaultAzureCredential());
            #endregion

            client.GetProperties();
            Assert.Pass();
        }
        public void AuthWithSharedKey()
        {
            string accountName    = StorageAccountName;
            string accountKey     = StorageAccountKey;
            string blobServiceUri = StorageAccountBlobUri.ToString();

            #region Snippet:SampleSnippetsBlobMigration_SharedKey
            StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey);
            BlobServiceClient          service    = new BlobServiceClient(new Uri(blobServiceUri), credential);
            #endregion

            service.GetProperties();
            Assert.Pass();
        }
Exemplo n.º 6
0
        public void ConfigureRetries()
        {
            // Get a connection string to our Azure Storage account.
            string connectionString = ConnectionString;

            // Create our client options and customize our retries
            BlobClientOptions options = new BlobClientOptions();

            options.Retry.MaxRetries = 5;

            // Create our client and make a simple request
            BlobServiceClient client = new BlobServiceClient(connectionString, options);

            client.GetProperties();
        }
Exemplo n.º 7
0
        public void ApplyServerTimeout()
        {
            // Get a connection string to our Azure Storage account.
            string connectionString = ConnectionString;

            // Create our client options and customize our retries
            BlobClientOptions options = new BlobClientOptions();

            options.Retry.MaxRetries = 5;

            // Create our client and make a simple request
            #region Snippet:Sample_StorageServerTimeout
            BlobServiceClient client = new BlobServiceClient(connectionString, options);
            using (StorageExtensions.CreateServiceTimeoutScope(TimeSpan.FromSeconds(10)))
            {
                client.GetProperties();
            }
            #endregion
        }
        //-------------------------------------------------
        // 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.º 9
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.º 10
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>
        }
Exemplo n.º 11
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.º 12
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);
        }
        private static async Task SoftDeleteTest()
        {
            // Retrieve a CloudBlobClient object and enable soft delete
            BlobServiceClient blobClient = GetCloudBlobClient();

            try
            {
                BlobServiceProperties serviceProperties = blobClient.GetProperties();
                serviceProperties.DeleteRetentionPolicy.Enabled = true;
                serviceProperties.DeleteRetentionPolicy.Days    = RetentionDays;
                blobClient.SetProperties(serviceProperties);
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine("Error returned from the service: {0}", ex.Message);
                throw;
            }

            // Create a container
            BlobContainerClient container = blobClient.GetBlobContainerClient("softdelete-" + System.Guid.NewGuid().ToString());

            try
            {
                await container.CreateIfNotExistsAsync();
            }
            catch (RequestFailedException)
            {
                Console.WriteLine("If you are using the storage emulator, please make sure you have started it. Press the Windows key and type Azure Storage to select and run it from the list of applications - then restart the sample.");
                Console.ReadLine();
                throw;
            }

            try
            {
                // Upload
                Console.WriteLine("\nUpload:");
                BlobClient blockBlob = container.GetBlobClient("HelloWorld");
                await blockBlob.UploadAsync(ImageToUpload, overwrite : true);

                PrintBlobsInContainer(container, BlobTraits.All);

                // Overwrite
                Console.WriteLine("\nOverwrite:");
                await blockBlob.UploadAsync(TextToUpload, overwrite : true);

                PrintBlobsInContainer(container, BlobTraits.All);

                // Snapshot
                Console.WriteLine("\nSnapshot:");
                await blockBlob.CreateSnapshotAsync();

                PrintBlobsInContainer(container, BlobTraits.All);

                // Delete (including snapshots)
                Console.WriteLine("\nDelete (including snapshots):");
                blockBlob.Delete(DeleteSnapshotsOption.IncludeSnapshots);
                PrintBlobsInContainer(container, BlobTraits.All);

                // Undelete
                Console.WriteLine("\nUndelete:");
                await blockBlob.UndeleteAsync();

                PrintBlobsInContainer(container, BlobTraits.All);

                // Recover
                Console.WriteLine("\nCopy the most recent snapshot over the base blob:");
                blockBlob.StartCopyFromUri(blockBlob.Uri);
                PrintBlobsInContainer(container, BlobTraits.All);
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine("Error returned from the service: {0}", ex.Message);
                throw;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.WriteLine("\nDone.\n\nEnter 'd' to cleanup resources. Doing so will also turn off the soft delete feature. Enter any other key to leave the container intact.");
            String cleanup = Console.ReadLine();

            if (cleanup == "d")
            {
                try
                {
                    // Delete the container
                    await container.DeleteIfExistsAsync();

                    Console.WriteLine("\nContainer deleted.");

                    // Turn off soft delete
                    BlobServiceProperties serviceProperties = blobClient.GetProperties();
                    serviceProperties.DeleteRetentionPolicy.Enabled = false;
                    blobClient.SetProperties(serviceProperties);
                }
                catch (RequestFailedException ex)
                {
                    Console.WriteLine("Error returned from the service: {0}", ex.Message);
                    throw;
                }
            }
        }