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)); } }
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); }
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); }
/// <summary> /// Determines whether Azure Blob is ready /// </summary> public async Task <Status> IsReadyAsync(CancellationToken cancellationToken) { CloudBlobClient blobClient = _account.CreateCloudBlobClient(); ServiceProperties serviceProperties = await blobClient.GetServicePropertiesAsync( new BlobRequestOptions(), default); return(new Status { IsReady = serviceProperties != null, Message = _account.BlobStorageUri.ToString() }); }
private static ServiceProperties CurrentProperties(CloudBlobClient blobClient) { var currentProperties = blobClient.GetServicePropertiesAsync().Result; if (currentProperties?.Cors == null) { return(currentProperties); } for (var index = 0; index < currentProperties.Cors.CorsRules.Count; index++) { var corsRule = currentProperties.Cors.CorsRules[index]; } return(currentProperties); }
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); }
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 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, }); }
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 <ServiceProperties> GetServicePropertiesAsync(CancellationToken cancellationToken) { return(_sdk.GetServicePropertiesAsync(options: null, operationContext: null, cancellationToken: cancellationToken)); }
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"); }
/// <inheritdoc /> public Task <ServiceProperties> GetServicePropertiesAsync(CancellationToken cancellationToken) { return(_sdk.GetServicePropertiesAsync(cancellationToken)); }
public static Task <ServiceProperties> GetServicePropertiesAsync(this CloudBlobClient sdk, CancellationToken cancellationToken) { return(sdk.GetServicePropertiesAsync(options: null, operationContext: null, cancellationToken: cancellationToken)); }
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); } }
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); }