static async Task CreateCORSPolicy(CloudBlobClient cloudBlobClient)
        {
            ServiceProperties serviceProperties = new ServiceProperties();

            serviceProperties.Cors = new CorsProperties();

            CorsRule corsRule = new CorsRule();

            corsRule.AllowedHeaders = new List <string>()
            {
                "*"
            };
            corsRule.ExposedHeaders = new List <string>()
            {
                "*"
            };
            corsRule.AllowedMethods = CorsHttpMethods.Post;
            corsRule.AllowedOrigins = new List <string>()
            {
                "https://localhost:8080/Books"
            };
            corsRule.MaxAgeInSeconds = 3600;

            serviceProperties.Cors.CorsRules.Add(corsRule);
            //try
            //{
            await cloudBlobClient.SetServicePropertiesAsync(serviceProperties);

            //}
            //catch(Exception ex)
            //{
            //    Console.WriteLine($"Error encountered in setting up the policy: {ex}");
            //}
        }
示例#2
0
        protected async Task SetCorsAsync(CloudBlobClient blobClient)
        {
            ServiceProperties blobServiceProperties = await blobClient.GetServicePropertiesAsync();

            blobServiceProperties.Cors = new CorsProperties();

            blobServiceProperties.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>()
                {
                    "*"
                },
                MaxAgeInSeconds = 1800 // 30 minutes
            });

            await blobClient.SetServicePropertiesAsync(blobServiceProperties);
        }
示例#3
0
        public async Task <OperationResult> SetGETCors(string key, string[] cors)
        {
            try
            {
                CloudBlobContainer bucket     = _client.GetContainerReference(key);
                ServiceProperties  properties = await _client.GetServicePropertiesAsync();

                properties.Cors.CorsRules.Clear();
                properties.Cors.CorsRules.Add(
                    new CorsRule()
                {
                    AllowedMethods = CorsHttpMethods.Get,
                    AllowedOrigins = cors.ToList(),
                    AllowedHeaders = new List <string>()
                    {
                        "*"
                    }
                });
                await _client.SetServicePropertiesAsync(properties);

                return(new OperationResult(true, "", HttpStatusCode.OK));
            }
            catch (Exception e)
            {
                return(new OperationResult(false, e.Message, HttpStatusCode.BadRequest));
            }
        }
        public async Task <string> UploadImageStreamAsync(Stream file, string folder, string extension)
        {
            if (file == null || file.Length == 0)
            {
                return(string.Empty);
            }

            string path      = string.Empty;
            string folderSub = DateTime.Now.ToString("ddMMyyyy") + "/" + DateTime.Now.ToString("HH");

            try
            {
                // Create the blob client and reference the container
                CloudBlobClient blobClient        = storageAccount.CreateCloudBlobClient();
                var             serviceProperties = await blobClient.GetServicePropertiesAsync();

                serviceProperties.Cors.CorsRules.Clear();
                serviceProperties.Cors.CorsRules.Add(new CorsRule
                {
                    AllowedHeaders = new List <string> {
                        "*"
                    },
                    AllowedMethods = CorsHttpMethods.Get | CorsHttpMethods.Head,
                    AllowedOrigins = new List <string> {
                        "*"
                    },
                    ExposedHeaders = new List <string> {
                        "*"
                    }
                });
                await blobClient.SetServicePropertiesAsync(serviceProperties);

                CloudBlobContainer container = blobClient.GetContainerReference(_container);

                // Create a unique name for the images we are about to upload
                string imageName = folder + "/" + folderSub + "/" + String.Format("{0}.{1}",
                                                                                  Guid.NewGuid().ToString(),
                                                                                  extension);

                // Upload image to Blob Storage
                CloudBlockBlob blockBlob = container.GetBlockBlobReference(imageName);
                blockBlob.Properties.ContentType = String.Format("image/{0}",
                                                                 Guid.NewGuid().ToString(),
                                                                 extension);
                await blockBlob.UploadFromStreamAsync(file);

                // Convert to be HTTP based URI (default storage path is HTTPS)
                path = imageName;
            }
            catch (Exception ex)
            {
            }

            return(path);
        }
示例#5
0
        private static async Task SetAzureStorageServiceProperties(string storageKey, ConfigurationFile config)
        {
            CloudStorageAccount storageAccount        = new CloudStorageAccount(new StorageCredentials(config.StorageAccount, storageKey), true);
            CloudBlobClient     blobClient            = storageAccount.CreateCloudBlobClient();
            ServiceProperties   blobServiceProperties = new ServiceProperties();

            blobServiceProperties.StaticWebsite = new StaticWebsiteProperties
            {
                Enabled              = true,
                IndexDocument        = "index.html",
                ErrorDocument404Path = "404.html"
            };
            await blobClient.SetServicePropertiesAsync(blobServiceProperties);
        }
        public void CreateCORSPolicy()
        {
            ServiceProperties sp = new ServiceProperties();

            sp.Cors.CorsRules.Add(new CorsRule()
            {
                AllowedMethods = CorsHttpMethods.Get,
                AllowedOrigins = new List <string>()
                {
                    "http://localhost:8080/"
                },
                MaxAgeInSeconds = 3600
            });
            _blobClient.SetServicePropertiesAsync(sp).GetAwaiter().GetResult();
            Console.WriteLine("Cors Policy Set !!!");
        }
示例#7
0
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(env.ContentRootPath)
                          .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                          .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                          .AddEnvironmentVariables();

            if (env.IsDevelopment())
            {
                // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
                builder.AddUserSecrets();
            }
            Configuration = builder.Build();


            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Configuration["StorageConnectionString"]);
            CloudBlobClient     blobClient     = storageAccount.CreateCloudBlobClient();

            blobClient.SetServicePropertiesAsync(
                new ServiceProperties
            {
                Cors = new CorsProperties()
                {
                    CorsRules =
                    {
                        new CorsRule()
                        {
                            AllowedOrigins  = { "*" },
                            AllowedMethods  = CorsHttpMethods.Get | CorsHttpMethods.Options,
                            AllowedHeaders  = { "*" },
                            ExposedHeaders  = { "*" },
                            MaxAgeInSeconds = 31536000,
                        }
                    }
                }
            });

            CloudBlobContainer container = blobClient.GetContainerReference("replays");

            container.CreateIfNotExistsAsync().Wait();
            container.SetPermissionsAsync(new BlobContainerPermissions {
                PublicAccess = BlobContainerPublicAccessType.Blob
            }).Wait();
        }
示例#8
0
        private async Task <ServiceProperties> SetServiceProperties()
        {
            var serviceProperties = await blobClient.GetServicePropertiesAsync();

            serviceProperties.Cors.CorsRules.Clear();
            serviceProperties.Cors.CorsRules.Add(new CorsRule()
            {
                AllowedHeaders  = { "*" },
                AllowedMethods  = CorsHttpMethods.Get | CorsHttpMethods.Head | CorsHttpMethods.Post | CorsHttpMethods.Put | CorsHttpMethods.Delete,
                AllowedOrigins  = { "*" },
                ExposedHeaders  = { "*" },
                MaxAgeInSeconds = 1800
            });

            await blobClient.SetServicePropertiesAsync(serviceProperties);

            return(serviceProperties);
        }
        public static async Task EnableLoggingAsync(CloudBlobClient blobClient, CancellationToken cancellationToken)
        {
            ServiceProperties serviceProperties = await blobClient.GetServicePropertiesAsync(cancellationToken);

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

            if (loggingProperties.LoggingOperations == LoggingOperations.None)
            {
                // First activating. Be sure to set a retention policy if there isn't one.
                loggingProperties.RetentionDays      = 7;
                loggingProperties.LoggingOperations |= LoggingOperations.Write;

                // Leave metrics untouched

                await blobClient.SetServicePropertiesAsync(serviceProperties, cancellationToken);
            }
        }
        public static async Task SetCORSPropertiesOnBlobService(this CloudStorageAccount storageAccount,
                                                                Func <CorsProperties, CorsProperties> alterCorsRules)
        {
            Log.Information("Configuring CORS.");

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

            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            ServiceProperties serviceProperties = await blobClient.GetServicePropertiesAsync();

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

            await blobClient.SetServicePropertiesAsync(serviceProperties);
        }
示例#11
0
        public async Task <BlobUriWithSasDto> GetBlobUrl(FileUploadDetailRequestDto dto)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_connectionString);
            CloudBlobClient     blobClient     = storageAccount.CreateCloudBlobClient();

            #region setting cors

            // Given a BlobClient, download the current Service Properties
            ServiceProperties blobServiceProperties = await blobClient.GetServicePropertiesAsync();

            // Enable and Configure CORS
            ConfigureCors(blobServiceProperties);
            // Commit the CORS changes into the Service Properties
            await blobClient.SetServicePropertiesAsync(blobServiceProperties);

            #endregion


            CloudBlobContainer container = blobClient.GetContainerReference(dto.ContainerName);
            var containerUri             = container.Uri; // finds required container and returns url for that container

            // Create the container if it doesn't already exist
            await container.CreateIfNotExistsAsync();

            var blob = container.GetBlockBlobReference(dto.BlobName);

            // create signature that will allow to write for next 10 mins
            var sas = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy()
            {
                Permissions            = SharedAccessBlobPermissions.Write,
                SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(10),
            });

            return(new BlobUriWithSasDto()
            {
                Sas = sas,
                BaseUri = containerUri.ToString(),
                BlobName = dto.BlobName,
            });
        }
示例#12
0
        public async Task <string> EnableCORS()
        {
            // Enable CORS
            CorsProperties corsProps = new CorsProperties();

            corsProps.CorsRules.Add(new CorsRule
            {
                AllowedHeaders = new List <string> {
                    "*"
                },
                AllowedMethods = CorsHttpMethods.Get,
                AllowedOrigins = new List <string> {
                    "*"
                },
                ExposedHeaders = new List <string> {
                    "*"
                },
                MaxAgeInSeconds = 200
            });

            ServiceProperties serviceProps = new ServiceProperties
            {
                Cors    = corsProps,
                Logging = new LoggingProperties
                {
                    Version = "1.0",
                },
                HourMetrics = new MetricsProperties
                {
                    Version = "1.0"
                },
                MinuteMetrics = new MetricsProperties
                {
                    Version = "1.0"
                },
            };
            await blobClient.SetServicePropertiesAsync(serviceProps);

            return("Successfully set CORS policy, allowing GET on all origins.  See https://msdn.microsoft.com/en-us/library/azure/dn535601.aspx for more.");
        }
        private async Task SetUpCorsRules()
        {
            var serviceProperties = await _client.GetServicePropertiesAsync();

            serviceProperties.Cors.CorsRules.Clear();

            serviceProperties.Cors.CorsRules.Add(new CorsRule
            {
                AllowedHeaders = new List <string> {
                    "x-ms-blob-type", "x-ms-blob-content-type", "content-type", "accept", "authorization", "origin", "x-requested-with"
                },
                AllowedMethods = CorsHttpMethods.Put | CorsHttpMethods.Get | CorsHttpMethods.Options,
                // note: this should be changed to the site's URL
                AllowedOrigins = new List <string> {
                    "*"
                },
                // set to the same length as the SAS token's expiration
                MaxAgeInSeconds = 15 * 60,
                ExposedHeaders  = new List <string> {
                    "*"
                }
            });
            await _client.SetServicePropertiesAsync(serviceProperties);
        }
 /// <inheritdoc />
 public Task SetServicePropertiesAsync(ServiceProperties properties, CancellationToken cancellationToken)
 {
     return(_sdk.SetServicePropertiesAsync(properties, requestOptions: null, operationContext: null, cancellationToken: cancellationToken));
 }
示例#15
0
        public static async Task BlobActions()
        {
            // Get a reference to the storage account from the connection string.
            CloudStorageAccount storageAccount = Common.CreateStorageAccountFromConnectionString();

            // Create service client for credentialed access to the Blob service.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            CloudBlobContainer container             = null;
            ServiceProperties  userServiceProperties = null;

            try
            {
                // Save the user's current service property/storage analytics settings.
                // This ensures that the sample does not permanently overwrite the user's analytics settings.
                // Note however that logging and metrics settings will be modified for the duration of the sample.
                userServiceProperties = await blobClient.GetServicePropertiesAsync();

                // Get a reference to a sample container.
                container = await CreateContainer(blobClient);

                // list all containers and blobs within the container
                //ListAllContainers(blobClient);

                //await ListBlobsFlatListing(blobClient.GetContainerReference(DropContainerName), 10);

                //Console.WriteLine("3. List Blobs in Container");
                //foreach (IListBlobItem blob in container.ListBlobs())
                //{
                //    // Blob type will be CloudBlockBlob, CloudPageBlob or CloudBlobDirectory
                //    // Use blob.GetType() and cast to appropriate type to gain access to properties specific to each type
                //    Console.WriteLine("- {0} (type: {1})", blob.Uri, blob.GetType());
                //}

                //// copying bolobs
                //CloudBlobContainer sourcecontrainer = null;
                //sourcecontrainer = blobClient.GetContainerReference(DropContainerName);

                //CloudBlobContainer targetcontrainer = null;
                //targetcontrainer = blobClient.GetContainerReference(IngestContainerName);

                //CloudBlockBlob source = sourcecontrainer.GetBlockBlobReference("CSTwit.csv");
                //CloudBlockBlob target = targetcontrainer.GetBlockBlobReference("123/CSTwit22222222222222.csv");

                //await target.StartCopyAsync(source);

                //string BlobName = "CSTwit.csv";
                //await CopyBlobs(blobClient, DropContainerName, IngestContainerName, BlobName);

                await CopyBlobsListing(blobClient, blobClient.GetContainerReference(DropContainerName));

                //await DeleteBlobs(blobClient, DropContainerName, "CSTwit.csv");
            }
            catch (StorageException e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
                throw;
            }
            finally
            {
                // Delete the sample container created by this session.
                //if (container != null)
                //{
                //    await container.DeleteIfExistsAsync();
                //}

                // The sample code deletes any containers it created if it runs completely. However, if you need to delete containers
                // created by previous sessions (for example, if you interrupted the running code before it completed),
                // you can uncomment and run the following line to delete them.
                // await DeleteContainersWithPrefix(blobClient, ContainerPrefix);

                // Return the service properties/storage analytics settings to their original values.
                await blobClient.SetServicePropertiesAsync(userServiceProperties);
            }
        }
示例#16
0
 public static Task SetServicePropertiesAsync(this CloudBlobClient sdk, ServiceProperties properties, CancellationToken cancellationToken)
 {
     return(sdk.SetServicePropertiesAsync(properties, requestOptions: null, operationContext: null, cancellationToken: cancellationToken));
 }
示例#17
0
        public static async Task Run([TimerTrigger("0 0 0 1 1 *", RunOnStartup = true)] TimerInfo timer, ExecutionContext context, ILogger log)
        {
            log.LogInformation($"Deployment of Client-App (Demo UI) triggered");

            string          storageConnectionString = Environment.GetEnvironmentVariable(Constants.Configurations.StorageConnectionString);
            CloudBlobClient blobClient = CloudStorageAccount.Parse(storageConnectionString).CreateCloudBlobClient();

            var currentProperties = await blobClient.GetServicePropertiesAsync();

            if (currentProperties?.StaticWebsite?.Enabled == true)
            {
                log.LogInformation($"StorageAccount is already configured for static website hosting");
                return;
            }

            // Update storage account for static website hosting
            ServiceProperties blobServiceProperties = new ServiceProperties();

            blobServiceProperties.StaticWebsite = new StaticWebsiteProperties
            {
                Enabled       = true,
                IndexDocument = IndexDocument
            };
            await blobClient.SetServicePropertiesAsync(blobServiceProperties);

            CloudBlobContainer container = blobClient.GetContainerReference("$web");
            await container.CreateIfNotExistsAsync();

            // Download deployment package from repository
            // Example: https://github.com/garaio/DevCamp-AzureServerless/raw/feature/demo-ui/Foundation/Garaio.DevCampServerless.Deployment/blobs/%24web.zip
            var baseUrl = Environment.GetEnvironmentVariable(Constants.Configurations.RepoUrl).Replace(".git", "");
            var url     = baseUrl + string.Format(Environment.GetEnvironmentVariable(Constants.Configurations.RepoClientAppPackagePattern), Environment.GetEnvironmentVariable(Constants.Configurations.RepoBranch));

            var zipStream = await url.GetStreamAsync();

            // Unpack zip to container and manipulate index.html file
            using (ZipArchive archive = new ZipArchive(zipStream))
            {
                var entries = archive.Entries;
                foreach (var entry in entries)
                {
                    CloudBlockBlob blob = container.GetBlockBlobReference(entry.FullName);

                    using (var stream = entry.Open())
                    {
                        if (entry.FullName == IndexDocument)
                        {
                            var indexHtml   = await new StreamReader(stream).ReadToEndAsync();
                            var pattern     = "<base href=\"/\"><script>api = {{ baseUrl:'{0}', authCode:'{1}' }};</script>";
                            var api         = Environment.GetEnvironmentVariable(Constants.Configurations.ServiceFuncUrl);
                            var code        = Environment.GetEnvironmentVariable(Constants.Configurations.ServiceFuncKeyClient);
                            var replacement = string.Format(pattern, api, code);

                            indexHtml = indexHtml.Replace("<base href=\"/\">", replacement);

                            await blob.UploadTextAsync(indexHtml);
                        }
                        else
                        {
                            await blob.UploadFromStreamAsync(stream);
                        }
                    }

                    blob.Properties.ContentType = MimeUtility.GetMimeMapping(entry.Name);
                    await blob.SetPropertiesAsync();
                }
            }

            log.LogInformation($"Deployment of Client-App (Demo UI) successfully executed");
        }
示例#18
0
 /// <inheritdoc />
 public Task SetServicePropertiesAsync(ServiceProperties properties, CancellationToken cancellationToken)
 {
     return(_sdk.SetServicePropertiesAsync(properties, cancellationToken));
 }
        public async Task <StorageResult> UploadImageBinaryAsync(byte[] fileBinary, string contentType, string fileName)
        {
            StorageResult resultObject = new StorageResult();

            if (fileBinary == null || fileBinary.Length == 0)
            {
                return(null);
            }

            try
            {
                CloudBlobClient blobClient        = storageAccount.CreateCloudBlobClient();
                var             serviceProperties = await blobClient.GetServicePropertiesAsync();

                serviceProperties.Cors.CorsRules.Clear();
                serviceProperties.Cors.CorsRules.Add(new CorsRule
                {
                    AllowedHeaders = new List <string> {
                        "*"
                    },
                    AllowedMethods = CorsHttpMethods.Get | CorsHttpMethods.Head,
                    AllowedOrigins = new List <string> {
                        "*"
                    },
                    ExposedHeaders = new List <string> {
                        "*"
                    }
                });
                await blobClient.SetServicePropertiesAsync(serviceProperties);

                CloudBlobContainer container = blobClient.GetContainerReference(_container);

                if (await container.CreateIfNotExistsAsync())
                {
                    // Enable public access on the newly created "images" container
                    await container.SetPermissionsAsync(
                        new BlobContainerPermissions
                    {
                        PublicAccess =
                            BlobContainerPublicAccessType.Blob
                    });
                }

                using (var stream = new MemoryStream(fileBinary, writable: false))
                {
                    // Upload image to Blob Storage
                    CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);
                    blockBlob.Properties.ContentType = contentType;

                    await blockBlob.UploadFromStreamAsync(stream);

                    resultObject.FileName = fileName;
                    resultObject.Folder   = _container;
                }
            }
            catch (Exception ex)
            {
                return(null);
            }

            return(resultObject);
        }