Example #1
0
        public void EnableCORS()
        {
            CorsHttpMethods allowedMethods = CorsHttpMethods.None;

            allowedMethods = allowedMethods | CorsHttpMethods.Get;
            allowedMethods = allowedMethods | CorsHttpMethods.Put;
            allowedMethods = allowedMethods | CorsHttpMethods.Post;
            allowedMethods = allowedMethods | CorsHttpMethods.Delete;
            allowedMethods = allowedMethods | CorsHttpMethods.Options;

            var          delimiter      = new[] { "," };
            CorsRule     corsRule       = new CorsRule();
            const string allowedOrigins = "*";
            const string allowedHeaders = "*";
            const string exposedHeaders = "";

            string[] allAllowedOrigin = allowedOrigins.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
            string[] allExpHeaders    = exposedHeaders.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
            string[] allAllowHeaders  = allowedHeaders.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);

            List <string> corsAllowedOrigin = new List <string>();

            foreach (var item in allAllowedOrigin)
            {
                if (!string.IsNullOrWhiteSpace(item))
                {
                    corsAllowedOrigin.Add(item.Trim());
                }
            }
            List <string> corsExposedHeaders = new List <string>();

            foreach (var item in allExpHeaders)
            {
                if (!string.IsNullOrWhiteSpace(item))
                {
                    corsExposedHeaders.Add(item.Trim());
                }
            }
            List <string> corsAllowHeaders = new List <string>();

            foreach (var item in allAllowHeaders)
            {
                if (!string.IsNullOrWhiteSpace(item))
                {
                    corsAllowHeaders.Add(item.Trim());
                }
            }
            corsRule.MaxAgeInSeconds = 200;
            corsRule.AllowedMethods  = allowedMethods;
            corsRule.AllowedHeaders  = corsAllowHeaders;
            corsRule.AllowedOrigins  = corsAllowedOrigin;
            corsRule.ExposedHeaders  = corsExposedHeaders;
            ServiceProperties properties = blobClient.GetServiceProperties();

            properties.Cors.CorsRules.Clear();
            properties.Cors.CorsRules.Add(corsRule);
            blobClient.SetServiceProperties(properties);
        }
Example #2
0
        public void FixServiceProperties()
        {
            ServiceProperties properties = cloudBlobClient.GetServiceProperties();

            properties.DefaultServiceVersion = "2019-02-02";
            cloudBlobClient.SetServiceProperties(properties);

            properties = cloudBlobClient.GetServiceProperties();
        }
Example #3
0
        private static void EnableCors(CloudBlobClient client)
        {
            var serviceProperties = client.GetServiceProperties();

            serviceProperties.Cors = new CorsProperties();
            serviceProperties.Cors.CorsRules.Add(new CorsRule()
            {
                AllowedHeaders = new List <string>()
                {
                    "*"
                },
                AllowedMethods = CorsHttpMethods.Get | CorsHttpMethods.Head,
                AllowedOrigins = new List <string>()
                {
                    "*"
                },
                ExposedHeaders = new List <string>()
                {
                    "*"
                },
                MaxAgeInSeconds = 1800 // 30 minutes
            });

            client.SetServiceProperties(serviceProperties);
        }
        // http://geekswithblogs.net/EltonStoneman/archive/2014/10/09/configure-azure-storage-to-return-proper-response-headers-for-blob.aspx
        private static void UpdateAzureServiceVersion(CloudBlobClient blobClient)
        {
            var props = blobClient.GetServiceProperties();

            props.DefaultServiceVersion = "2014-02-14";
            blobClient.SetServiceProperties(props);
        }
Example #5
0
        private void SetCors(CloudBlobClient blobClient)
        {
            var newProperties = blobClient.GetServiceProperties();

            try
            {
                ConfigureCors(newProperties);
                var blobprop = blobClient.GetServiceProperties();
                // "2011-08-18"; // null;
                blobClient.SetServiceProperties(newProperties);
            }
            catch (Exception ex)
            {
                //throw;
            }
        }
        protected void EnsureInitialized()
        {
            if (_storageAccount != null)
            {
                return;
            }

            _storageAccount = CloudStorageAccount.Parse(StorageConnectionString);
            _absoluteRoot   = Combine(Combine(_storageAccount.BlobEndpoint.AbsoluteUri, ContainerName), _root);

            _blobClient = _storageAccount.CreateCloudBlobClient();
            // Get and create the container if it does not exist
            // The container is named with DNS naming restrictions (i.e. all lower case)
            _container = _blobClient.GetContainerReference(ContainerName);

            ////Set the default service version to the current version "2015-12-11" so that newer features and optimizations are enabled on the images and videos stored in the blob storage.
            var properties = _blobClient.GetServiceProperties();

            if (properties.DefaultServiceVersion == null)
            {
                properties.DefaultServiceVersion = "2015-12-11";
                _blobClient.SetServiceProperties(properties);
            }

            _container.CreateIfNotExists(_isPrivate ? BlobContainerPublicAccessType.Off : BlobContainerPublicAccessType.Blob);
        }
Example #7
0
        private static void EnableStorageLogging(CloudBlobClient blobClient)
        {
            var serviceProperties = blobClient.GetServiceProperties();

            serviceProperties.Logging.LoggingOperations = LoggingOperations.All;
            serviceProperties.Logging.RetentionDays     = 365;
            blobClient.SetServiceProperties(serviceProperties);
        }
Example #8
0
        /// <summary>
        /// Enables the storage analytics for blob service.
        /// </summary>
        /// <param name="cloudStorageAccount">The cloud storage account.</param>
        public static void EnableBlobStorageAnalytics(this CloudStorageAccount cloudStorageAccount)
        {
            CloudBlobClient   cloudBlobClient   = cloudStorageAccount.CreateCloudBlobClient();
            ServiceProperties serviceProperties = cloudBlobClient.GetServiceProperties();

            serviceProperties.Metrics.MetricsLevel  = MetricsLevel.Service;
            serviceProperties.Metrics.RetentionDays = RetentionDays.Value;
            cloudBlobClient.SetServiceProperties(serviceProperties);
        }
Example #9
0
        public void Initialize()
        {
            // Given a BlobClient, download the current Service Properties
            ServiceProperties blobServiceProperties = _blobClient.GetServiceProperties();

            // Enable and Configure CORS
            ConfigureCors(blobServiceProperties);

            // Commit the CORS changes into the Service Properties
            _blobClient.SetServiceProperties(blobServiceProperties);
        }
 /// <summary>
 /// Gets the service properties.
 /// </summary>
 /// <returns>Microsoft.WindowsAzure.Storage.Shared.Protocol.ServiceProperties.</returns>
 public ServiceProperties GetServiceProperties()
 {
     try
     {
         return(blobClient.GetServiceProperties());
     }
     catch (Exception ex)
     {
         throw ex.Handle();
     }
 }
Example #11
0
        private void InitTableStorage()
        {
            var blobProperties = _blobClient.GetServiceProperties();

            ConfigureCors(blobProperties);
            _blobClient.SetServiceProperties(blobProperties);

            _table.CreateIfNotExists();
            _blobContainer.CreateIfNotExists(BlobContainerPublicAccessType.Blob);
            _queue.CreateIfNotExists();
        }
Example #12
0
        void UploadBlobInChunks(FileInfo fileInfo, CloudBlockBlob packageBlob, CloudBlobClient blobClient)
        {
            var operationContext = new OperationContext();

            operationContext.ResponseReceived += delegate(object sender, RequestEventArgs args)
            {
                var statusCode        = (int)args.Response.StatusCode;
                var statusDescription = args.Response.StatusDescription;
                log.Verbose("Uploading, response received: " + statusCode + " " + statusDescription);
                if (statusCode >= 400)
                {
                    log.Error("Error when uploading the package. Azure returned a HTTP status code of: " +
                              statusCode + " " + statusDescription);
                    log.Verbose("The upload will be retried");
                }
            };

            blobClient.SetServiceProperties(blobClient.GetServiceProperties(), operationContext: operationContext);

            log.VerboseFormat("Uploading the package to blob storage. The package file is {0}.", fileInfo.Length.ToFileSizeString());

            using (var fileReader = fileInfo.OpenRead())
            {
                var blocklist = new List <string>();

                long uploadedSoFar = 0;

                var data = new byte[1024 * 1024];
                var id   = 1;

                while (true)
                {
                    id++;

                    var read = fileReader.Read(data, 0, data.Length);
                    if (read == 0)
                    {
                        packageBlob.PutBlockList(blocklist);
                        break;
                    }

                    var blockId = Convert.ToBase64String(Encoding.UTF8.GetBytes(id.ToString(CultureInfo.InvariantCulture).PadLeft(30, '0')));
                    packageBlob.PutBlock(blockId, new MemoryStream(data, 0, read, true), null);
                    blocklist.Add(blockId);

                    uploadedSoFar += read;

                    log.Progress((int)((uploadedSoFar * 100) / fileInfo.Length), "Uploading package to blob storage");
                    log.VerboseFormat("Uploading package to blob storage: {0} of {1}", uploadedSoFar.ToFileSizeString(), fileInfo.Length.ToFileSizeString());
                }
            }

            log.Verbose("Upload complete");
        }
Example #13
0
        /// <summary>
        /// init cloud blob util
        /// </summary>
        /// <param name="account">storage account</param>
        public CloudBlobUtil(CloudStorageAccount account)
        {
            this.account = account;
            client       = account.CreateCloudBlobClient();

            // Enable logging for blob service and enable $logs container
            ServiceProperties properties = client.GetServiceProperties();

            properties.Cors = new CorsProperties(); // Clear all CORS rule to eliminate the effect by CORS cases
            properties.Logging.LoggingOperations = LoggingOperations.All;
            client.SetServiceProperties(properties);

            random = new Random();
        }
Example #14
0
        public static void Enable(string accountname, string accountkey)
        {
            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=" + accountname + ";AccountKey=" + accountkey);

            CloudBlobClient blobClient        = storageAccount.CreateCloudBlobClient();
            var             serviceProperties = blobClient.GetServiceProperties();

            //var queueClient = storageAccount.CreateCloudQueueClient();
            //var serviceProperties = queueClient.GetServiceProperties();

            serviceProperties.Logging.LoggingOperations = Microsoft.WindowsAzure.Storage.Shared.Protocol.LoggingOperations.All;
            serviceProperties.Logging.RetentionDays     = 2;

            blobClient.SetServiceProperties(serviceProperties);
        }
Example #15
0
        public static void DeleteOldVHDs()
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["ARMRenderStorageKey"]);
            CloudBlobClient     blobClient     = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer  container      = blobClient.GetContainerReference("vhds");
            var properties = blobClient.GetServiceProperties();

            properties.DefaultServiceVersion = "2016-05-31";
            blobClient.SetServiceProperties(properties);
            var images = container.ListBlobs();

            foreach (var image in images)
            {
                string blobName = image.Uri.Segments[2];
                //CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);
                CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);

                //Intended to check if Blob is older than 3 days and delete it.
                //However there is a known Azure bug that prevents the fetchattributes from returning the attributes.
                //I have no other ideas on how to get the last modified date. So for now I'm just deleting all blobs.
                //This should be fine because the VHDs being used have a lease on them preventing them from deletion.
                //blockBlob.FetchAttributes();
                //DateTimeOffset threeDaysAgo = DateTimeOffset.Now.AddDays(-3);
                //blockBlob.FetchAttributes();
                //DateTimeOffset? lastModified = blockBlob.Properties.LastModified;
                //if(lastModified!=null)
                //{
                //    if(threeDaysAgo>lastModified)
                //    {
                //        blockBlob.Delete();
                //    }
                //}

                //Even though there is a lease on it. Not a good idea to try and delete our production server.
                if (!blobName.Contains("Prod") && !blobName.Contains("prod"))
                {
                    try
                    {
                        blockBlob.Delete();
                    }
                    catch
                    {
                        //there was a lease on the blob
                    }
                }
            }
        }
Example #16
0
        public static void Initialize(CloudBlobClient blobClient)
        {
            if (blobClient == null)
            {
                throw new ArgumentException("BlobClient is null");
            }

            // CORS should be enabled once at service startup
            // Given a BlobClient, download the current Service Properties
            ServiceProperties blobServiceProperties = blobClient.GetServiceProperties();

            // Enable and Configure CORS
            Configure(blobServiceProperties);

            // Commit the CORS changes into the Service Properties
            blobClient.SetServiceProperties(blobServiceProperties);
        }
Example #17
0
        private static void InitializeCors()
        {
            string conn_str = ConfigurationManager.AppSettings["StorageConnectionString"];
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(conn_str);

            CloudBlobClient BlobClient = storageAccount.CreateCloudBlobClient();

            // CORS should be enabled once at service startup
            // Given a BlobClient, download the current Service Properties
            ServiceProperties blobServiceProperties = BlobClient.GetServiceProperties();

            // Enable and Configure CORS
            ConfigureCors(blobServiceProperties);

            // Commit the CORS changes into the Service Properties
            BlobClient.SetServiceProperties(blobServiceProperties);
        }
Example #18
0
        public void SetLoggingVersion()
        {
            //Blob service
            CloudBlobClient blobClient = StorageAccount.CreateCloudBlobClient();

            GenericSetLoggingVersion(ServiceType.Blob, () => blobClient.GetServiceProperties());

            //Queue service
            CloudQueueClient queueClient = StorageAccount.CreateCloudQueueClient();

            GenericSetLoggingVersion(ServiceType.Queue, () => queueClient.GetServiceProperties());

            //Table service
            CloudTableClient tableClient = StorageAccount.CreateCloudTableClient();

            GenericSetLoggingVersion(ServiceType.Table, () => tableClient.GetServiceProperties());
        }
Example #19
0
        public static void SetCORSPropertiesOnBlobService(this CloudStorageAccount storageAccount,
                                                          Func <CorsProperties, CorsProperties> alterCorsRules)
        {
            CATFunctions.Print("Configuring CORS.", true, true);

            if (storageAccount == null || alterCorsRules == null)
            {
                throw new ArgumentNullException();
            }

            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            ServiceProperties serviceProperties = blobClient.GetServiceProperties();

            serviceProperties.Cors = alterCorsRules(serviceProperties.Cors) ?? new CorsProperties();

            blobClient.SetServiceProperties(serviceProperties);
        }
Example #20
0
        /// <summary>
        /// Pings all servers to obtain their round-trips times and their high timestamps.
        /// </summary>
        public void PingNow()
        {
            Stopwatch watch = new Stopwatch();

            foreach (string server in replicas.Keys)
            {
                // if the server is not reached yet, we perform a dummy operation for it.
                if (!replicas[server].IsContacted())
                {
                    //we perform a dummy operation to get the rtt latency!
                    CloudBlobClient blobClient = ClientRegistry.GetCloudBlobClient(server);
                    long            rtt;
                    watch.Restart();
                    blobClient.GetServiceProperties();
                    rtt = watch.ElapsedMilliseconds;
                    replicas[server].AddRtt(rtt);
                }
            }
        }
Example #21
0
        private void ConfigureCors(CloudBlobClient cloudBlobClient)
        {
            ServiceProperties serviceProperties = cloudBlobClient.GetServiceProperties();

            CorsProperties corsProperties = new CorsProperties();

            corsProperties.CorsRules.Add(new CorsRule()
            {
                AllowedMethods  = CorsHttpMethods.Get,
                AllowedHeaders  = new string[] { "*" },
                AllowedOrigins  = new string[] { "*" },
                ExposedHeaders  = new string[] { "*" },
                MaxAgeInSeconds = 1800                 // 30 minutes
            });

            serviceProperties.Cors = corsProperties;

            cloudBlobClient.SetServiceProperties(serviceProperties);
        }
Example #22
0
        private static void UpdateServiceProperties(CloudBlobClient blobClient, List <string> origins, List <string> headers, List <string> methods)
        {
            ServiceProperties props = blobClient.GetServiceProperties();

            Trace.Write(props.Cors.CorsRules.ToString());

            if (!ContainsOrigin(props.Cors.CorsRules, origins))
            {
                props.Cors.CorsRules.Add(
                    new CorsRule
                {
                    AllowedOrigins  = origins,
                    AllowedHeaders  = headers,
                    AllowedMethods  = ExpandCorsHttpMethods(methods),
                    MaxAgeInSeconds = 1800     // 30 minutes
                });
                blobClient.SetServiceProperties(props);
            }
        }
Example #23
0
        private static ServiceProperties CurrentProperties(CloudBlobClient blobClient)
        {
            var currentProperties = blobClient.GetServiceProperties();

            if (currentProperties != null)
            {
                if (currentProperties.Cors != null)
                {
                    Console.WriteLine("Cors.CorsRules.Count          : " + currentProperties.Cors.CorsRules.Count);
                    for (int index = 0; index < currentProperties.Cors.CorsRules.Count; index++)
                    {
                        var corsRule = currentProperties.Cors.CorsRules[index];
                        Console.WriteLine("corsRule[index]              : " + index);
                        foreach (var allowedHeader in corsRule.AllowedHeaders)
                        {
                            Console.WriteLine("corsRule.AllowedHeaders      : " + allowedHeader);
                        }
                        Console.WriteLine("corsRule.AllowedMethods      : " + corsRule.AllowedMethods);

                        foreach (var allowedOrigins in corsRule.AllowedOrigins)
                        {
                            Console.WriteLine("corsRule.AllowedOrigins      : " + allowedOrigins);
                        }
                        foreach (var exposedHeaders in corsRule.ExposedHeaders)
                        {
                            Console.WriteLine("corsRule.ExposedHeaders      : " + exposedHeaders);
                        }
                        Console.WriteLine("corsRule.MaxAgeInSeconds     : " + corsRule.MaxAgeInSeconds);
                    }
                }
                Console.WriteLine("DefaultServiceVersion         : " + currentProperties.DefaultServiceVersion);
                Console.WriteLine("HourMetrics.MetricsLevel      : " + currentProperties.HourMetrics.MetricsLevel);
                Console.WriteLine("HourMetrics.RetentionDays     : " + currentProperties.HourMetrics.RetentionDays);
                Console.WriteLine("HourMetrics.Version           : " + currentProperties.HourMetrics.Version);
                Console.WriteLine("Logging.LoggingOperations     : " + currentProperties.Logging.LoggingOperations);
                Console.WriteLine("Logging.RetentionDays         : " + currentProperties.Logging.RetentionDays);
                Console.WriteLine("Logging.Version               : " + currentProperties.Logging.Version);
                Console.WriteLine("MinuteMetrics.MetricsLevel    : " + currentProperties.MinuteMetrics.MetricsLevel);
                Console.WriteLine("MinuteMetrics.RetentionDays   : " + currentProperties.MinuteMetrics.RetentionDays);
                Console.WriteLine("MinuteMetrics.Version         : " + currentProperties.MinuteMetrics.Version);
            }
            return(currentProperties);
        }
Example #24
0
        static void Main(string[] args)
        {
            CloudStorageAccount storageAccount    = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["mafs:StorageConnectionString"]);
            CloudBlobClient     client            = storageAccount.CreateCloudBlobClient();
            ServiceProperties   serviceProperties = client.GetServiceProperties();
            CorsProperties      corsSettings      = serviceProperties.Cors;

            AddRule(corsSettings);
            //corsSettings.CorsRules.RemoveAt(0);

            //serviceProperties.DefaultServiceVersion = "2015-07-08";

            client.SetServiceProperties(serviceProperties);

            Console.WriteLine("DefaultServiceVersion        : " + serviceProperties.DefaultServiceVersion);

            DisplayCorsSettings(corsSettings);

            Console.ReadKey();
        }
Example #25
0
        public void SetMetricsVersion()
        {
            //Blob service
            CloudBlobClient blobClient = StorageAccount.CreateCloudBlobClient();

            GenericSetMetricsVersion(ServiceType.Blob, () => blobClient.GetServiceProperties());

            //Queue service
            CloudQueueClient queueClient = StorageAccount.CreateCloudQueueClient();

            GenericSetMetricsVersion(ServiceType.Queue, () => queueClient.GetServiceProperties());

            //Table service
            CloudTableClient tableClient = StorageAccount.CreateCloudTableClient();

            GenericSetMetricsVersion(ServiceType.Table, () => tableClient.GetServiceProperties());

            //File service
            GenericSetMetricsVersion(ServiceType.File, () => Utility.GetServiceProperties(StorageAccount, ServiceType.File));
        }
Example #26
0
        public void CreateContainer(IApplicationConfig config)
        {
            try
            {
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(config.BlobConnectionString);
                CloudBlobClient     blobClient     = storageAccount.CreateCloudBlobClient();

                var serviceProperties = blobClient.GetServiceProperties();
                serviceProperties.Cors = new CorsProperties();
                serviceProperties.Cors.CorsRules.Add(new CorsRule()
                {
                    AllowedHeaders = new List <string>()
                    {
                        "*"
                    },
                    AllowedMethods = CorsHttpMethods.Put | CorsHttpMethods.Get | CorsHttpMethods.Head | CorsHttpMethods.Post,
                    AllowedOrigins = new List <string>()
                    {
                        "*"
                    },
                    ExposedHeaders = new List <string>()
                    {
                        "*"
                    },
                });

                blobClient.SetServiceProperties(serviceProperties);

                CloudBlobContainer container = blobClient.GetContainerReference(config.CsvContainer);
                container.CreateIfNotExists();

                //TODO
                container.SetPermissions(new BlobContainerPermissions {
                    PublicAccess = BlobContainerPublicAccessType.Blob
                });
            }
            catch (Exception ex)
            {
                _logger.LogError("Failed to create container in Azure Storage", ex);
            }
        }
        //https://msazure.visualstudio.com/One/_git/AzureStack-Services-Storage?path=%2Fsrc%2Fsdx%2Fbase%2Fwoss%2Ftest%2Ftests%2FWFE%2FHorizontalBVT%2FAccountKeyTests.cs&version=GBmaster&_a=contents
        /// <summary>
        /// Make a couple of requests to the blob, queue, and table services, expecting success.
        /// </summary>
        /// <param name="account">The account through which the services will be accessed.</param>
        internal void MakeServiceRequestsExpectSuccess(CloudStorageAccount account)
        {
            // Make blob service requests
            CloudBlobClient blobClient = account.CreateCloudBlobClient();

            //   blobClient.ListContainersSegmentedAsync();
            blobClient.ListContainers().Count();
            blobClient.GetServiceProperties();

            // Make queue service requests
            CloudQueueClient queueClient = account.CreateCloudQueueClient();

            queueClient.ListQueues().Count();
            queueClient.GetServiceProperties();

            // Make table service requests
            CloudTableClient tableClient = account.CreateCloudTableClient();

            tableClient.ListTables().Count();
            tableClient.GetServiceProperties();
        }
Example #28
0
    void UseAccountSAS(string sasToken)
    {
        // Create new storage credentials using the SAS token.
        StorageCredentials accountSAS = new StorageCredentials(sasToken);
        // Use these credentials and the account name to create a Blob service client.
        CloudStorageAccount accountWithSAS    = new CloudStorageAccount(accountSAS, "simlabitvideos", endpointSuffix: null, useHttps: true);
        CloudBlobClient     blobClientWithSAS = accountWithSAS.CreateCloudBlobClient();

        // Now set the service properties for the Blob client created with the SAS.
        blobClientWithSAS.SetServiceProperties(new ServiceProperties()
        {
            HourMetrics = new MetricsProperties()
            {
                MetricsLevel  = MetricsLevel.ServiceAndApi,
                RetentionDays = 7,
                Version       = "1.0"
            },
            MinuteMetrics = new MetricsProperties()
            {
                MetricsLevel  = MetricsLevel.ServiceAndApi,
                RetentionDays = 7,
                Version       = "1.0"
            },
            Logging = new LoggingProperties()
            {
                LoggingOperations = LoggingOperations.All,
                RetentionDays     = 14,
                Version           = "1.0"
            }
        });

        // The permissions granted by the account SAS also permit you to retrieve service properties.
        ServiceProperties serviceProperties = blobClientWithSAS.GetServiceProperties();

        Console.WriteLine(serviceProperties.HourMetrics.MetricsLevel);
        Console.WriteLine(serviceProperties.HourMetrics.RetentionDays);
        Console.WriteLine(serviceProperties.HourMetrics.Version);
    }
Example #29
0
        /// <summary>
        /// Tries the get user data capacity metric for blob service.
        /// </summary>
        /// <param name="cloudStorageAccount">The cloud storage account.</param>
        /// <param name="fromDate">Date from which retrieve capacity information.</param>
        /// <param name="analyticsEnabled">if set to <c>true</c> if analytics enabled.</param>
        /// <returns></returns>
        public static IEnumerable <Tuple <DateTime, long> > TryGetBlobUserDataCapacityMetric(this CloudStorageAccount cloudStorageAccount, DateTime fromDate, out bool analyticsEnabled)
        {
            CloudBlobClient blobClient        = cloudStorageAccount.CreateCloudBlobClient();
            var             serviceProperties = blobClient.GetServiceProperties();

            analyticsEnabled = serviceProperties.Metrics.MetricsLevel == MetricsLevel.Service;

            if (!analyticsEnabled)
            {
                return(null);
            }

            var cloudTableClient = cloudStorageAccount.CreateCloudTableClient();
            var table            = cloudTableClient.GetTableReference("$MetricsCapacityBlob");
            //Selecting
            TableQuery <MetricsCapacityBlob> query =
                new TableQuery <MetricsCapacityBlob>().Where(TableQuery.CombineFilters(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.GreaterThan, (fromDate.ToUniversalTime()).ToString("yyyyMMddTHH00")),
                                                                                       TableOperators.And,
                                                                                       TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, "data")));


            return(table.ExecuteQuery(query).Select(c => new Tuple <DateTime, long>(c.Timestamp.Date, c.Capacity)));
        }
Example #30
0
        public static void AddCorsRuleForAzure(this IApplicationBuilder app)
        {
            var corsRule = new CorsRule()
            {
                AllowedHeaders = new List <string> {
                    "*"
                },
                AllowedMethods = CorsHttpMethods.Get,
                AllowedOrigins = new List <string> {
                    "https://localhost:5001"
                },
                MaxAgeInSeconds = 3600,
            };

            string connectionString               = AzureStorageConfiguration.GetConnectionString();
            CloudStorageAccount storageAccount    = CloudStorageAccount.Parse(connectionString);
            CloudBlobClient     client            = storageAccount.CreateCloudBlobClient();
            ServiceProperties   serviceProperties = client.GetServiceProperties();
            CorsProperties      corsSettings      = serviceProperties.Cors;

            corsSettings.CorsRules.Add(corsRule);
            client.SetServiceProperties(serviceProperties);
        }
Example #31
0
        private ServiceProperties CurrentProperties(CloudBlobClient blobClient)
        {
            var currentProperties = blobClient.GetServiceProperties();
            if (currentProperties != null)
            {
                if (currentProperties.Cors != null)
                {
                    Console.WriteLine("Cors.CorsRules.Count          : " + currentProperties.Cors.CorsRules.Count);
                    for (int index = 0; index < currentProperties.Cors.CorsRules.Count; index++)
                    {
                        var corsRule = currentProperties.Cors.CorsRules[index];
                        Console.WriteLine("corsRule[index]              : " + index);
                        foreach (var allowedHeader in corsRule.AllowedHeaders)
                        {
                            Console.WriteLine("corsRule.AllowedHeaders      : " + allowedHeader);
                        }
                        Console.WriteLine("corsRule.AllowedMethods      : " + corsRule.AllowedMethods);

                        foreach (var allowedOrigins in corsRule.AllowedOrigins)
                        {
                            Console.WriteLine("corsRule.AllowedOrigins      : " + allowedOrigins);
                        }
                        foreach (var exposedHeaders in corsRule.ExposedHeaders)
                        {
                            Console.WriteLine("corsRule.ExposedHeaders      : " + exposedHeaders);
                        }
                        Console.WriteLine("corsRule.MaxAgeInSeconds     : " + corsRule.MaxAgeInSeconds);
                    }
                }
                Console.WriteLine("DefaultServiceVersion         : " + currentProperties.DefaultServiceVersion);
                Console.WriteLine("HourMetrics.MetricsLevel      : " + currentProperties.HourMetrics.MetricsLevel);
                Console.WriteLine("HourMetrics.RetentionDays     : " + currentProperties.HourMetrics.RetentionDays);
                Console.WriteLine("HourMetrics.Version           : " + currentProperties.HourMetrics.Version);
                Console.WriteLine("Logging.LoggingOperations     : " + currentProperties.Logging.LoggingOperations);
                Console.WriteLine("Logging.RetentionDays         : " + currentProperties.Logging.RetentionDays);
                Console.WriteLine("Logging.Version               : " + currentProperties.Logging.Version);
                Console.WriteLine("MinuteMetrics.MetricsLevel    : " + currentProperties.MinuteMetrics.MetricsLevel);
                Console.WriteLine("MinuteMetrics.RetentionDays   : " + currentProperties.MinuteMetrics.RetentionDays);
                Console.WriteLine("MinuteMetrics.Version         : " + currentProperties.MinuteMetrics.Version);
            }
            return currentProperties;
        }