public void AuthWithSasCredential()
        {
            //setup blob
            string containerName = Randomize("sample-container");
            string blobName      = Randomize("sample-file");
            var    container     = new BlobContainerClient(ConnectionString, containerName);

            try
            {
                container.Create();
                BlobClient blobClient = container.GetBlobClient(blobName);
                blobClient.Upload(BinaryData.FromString("hello world"));

                // build SAS URI for sample
                Uri sasUri = blobClient.GenerateSasUri(BlobSasPermissions.All, DateTimeOffset.UtcNow.AddHours(1));

                #region Snippet:SampleSnippetsBlobMigration_SasUri
                BlobClient blob = new BlobClient(sasUri);
                #endregion

                var stream = new MemoryStream();
                blob.DownloadTo(stream);
                Assert.Greater(stream.Length, 0);
            }
            finally
            {
                container.Delete();
            }
        }
        private static Uri GetSasUriForBlob(BlobClient blobClient, string storedPolicyName = null)
        {
            // Check whether this BlobClient object has been authorized with Shared Key.
            if (blobClient.CanGenerateSasUri)
            {
                // Create a SAS token that's valid for one hour.
                var sasBuilder = new BlobSasBuilder()
                {
                    BlobContainerName = blobClient.GetParentBlobContainerClient().Name,
                    BlobName          = blobClient.Name,
                    Resource          = "b"
                };

                if (storedPolicyName == null)
                {
                    sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(1);
                    sasBuilder.SetPermissions(BlobSasPermissions.Read |
                                              BlobSasPermissions.Write);
                }
                else
                {
                    sasBuilder.Identifier = storedPolicyName;
                }

                var sasUri = blobClient.GenerateSasUri(sasBuilder);
                Console.WriteLine("SAS URI for blob is: {0}\n", sasUri);

                return(sasUri);
            }
            else
            {
                Console.WriteLine(@"BlobClient must be authorized with Shared Key credentials to create a service SAS.");
                return(null);
            }
        }
        public string GetDownloadUrl(string fileName)
        {
            BlobClient blobClient = _containerClient.GetBlobClient(blobName: fileName);
            Uri        uri        = blobClient.GenerateSasUri(Azure.Storage.Sas.BlobSasPermissions.Read, DateTimeOffset.UtcNow.AddDays(1));

            return(uri.ToString());
        }
Beispiel #4
0
        private static async Task <string> UploadFileAsync(string connectionString, string blobContainer, string storageId, string filePath)
        {
            BlobClient blob = new BlobClient(
                connectionString,
                blobContainer,
                storageId);

            if (!blob.CanGenerateSasUri)
            {
                throw new NotSupportedException("Blob container doesn't support SAS tokens");
            }
            await blob.UploadAsync(filePath);

            BlobSasBuilder sasBuilder = new BlobSasBuilder()
            {
                BlobContainerName = blobContainer,
                BlobName          = storageId,
                Resource          = "b"
            };

            sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddDays(1);
            sasBuilder.SetPermissions(BlobAccountSasPermissions.Read);

            var sasUri = blob.GenerateSasUri(sasBuilder);

            return(sasUri.ToString());
        }
        private static void FillFileInfo(File file, BlobClient blob, BlobSasBuilder readPermissions)
        {
            file.FileId   = blob.Name;
            file.FullName = blob.Name;

            string[] parts  = blob.Name.Split('/');
            int      length = parts.Length;

            file.Name       = parts[length - 1];
            file.ObjectType = parts[0];
            file.ObjectId   = parts[1];

            string sasUrl = null;

            if (readPermissions != null)
            {
                sasUrl = blob.GenerateSasUri(readPermissions).ToString();
            }

            file.Url = sasUrl ?? blob.Uri.ToString();

            if (!string.IsNullOrWhiteSpace(Settings.FileSecondaryUrl))
            {
                file.SecondaryUrl = sasUrl == null
                    ? $"{Settings.FileSecondaryUrl}{blob.Uri.AbsolutePath}"
                    : $"{Settings.FileSecondaryUrl}{blob.Uri.AbsolutePath}?{sasUrl.Split('?')[1]}";
            }
        }
        // Create a SAS token for the source blob, to enable it to be read by the StartCopyFromUriAsync method
        private static Uri GetSharedAccessUri(string blobName, BlobContainerClient container)
        {
            DateTimeOffset expiredOn = DateTimeOffset.UtcNow.AddMinutes(60);

            BlobClient blob   = container.GetBlobClient(blobName);
            Uri        sasUri = blob.GenerateSasUri(BlobSasPermissions.Read, expiredOn);

            return(sasUri);
        }
        public async Task SasBuilderIdentifier()
        {
            string                     accountName         = StorageAccountName;
            string                     accountKey          = StorageAccountKey;
            string                     containerName       = Randomize("sample-container");
            string                     blobName            = Randomize("sample-blob");
            DateTimeOffset             expiresOn           = DateTimeOffset.UtcNow.AddDays(1);
            DateTimeOffset             startsOn            = DateTimeOffset.UtcNow.AddHours(-1);
            StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential(StorageAccountName, StorageAccountKey);

            // setup blob
            var container = new BlobContainerClient(ConnectionString, containerName);

            try
            {
                await container.CreateAsync();

                BlobClient blobClient = container.GetBlobClient(blobName);
                await container.GetBlobClient(blobName).UploadAsync(BinaryData.FromString("hello world"));

                // Create one or more stored access policies.
                List <BlobSignedIdentifier> signedIdentifiers = new List <BlobSignedIdentifier>
                {
                    new BlobSignedIdentifier
                    {
                        Id           = "mysignedidentifier",
                        AccessPolicy = new BlobAccessPolicy
                        {
                            StartsOn    = startsOn,
                            ExpiresOn   = expiresOn,
                            Permissions = "rw"
                        }
                    }
                };
                // Set the container's access policy.
                await container.SetAccessPolicyAsync(permissions : signedIdentifiers);

                #region Snippet:SampleSnippetsBlobMigration_SasBuilderIdentifier
                // Create BlobSasBuilder and specify parameters
                BlobSasBuilder sasBuilder = new BlobSasBuilder
                {
                    Identifier = "mysignedidentifier"
                };
                #endregion

                // Create full, self-authenticating URI to the resource
                Uri sasUri = blobClient.GenerateSasUri(sasBuilder);

                // successful download indicates pass
                await new BlobClient(sasUri).DownloadToAsync(new MemoryStream());
            }
            finally
            {
                await container.DeleteIfExistsAsync();
            }
        }
Beispiel #8
0
        public Uri GetSasUriForBlob(Uri uri)
        {
            var accuntName = _config["AppSettings:AzureAccountName"];
            var key        = _config["AppSettings:AzureAccountKey"];

            StorageSharedKeyCredential storageCredentials = new StorageSharedKeyCredential(accuntName, key);

            // Create the blob client.
            BlobClient blobClient = new BlobClient(uri, storageCredentials);

            return(blobClient.GenerateSasUri(Azure.Storage.Sas.BlobSasPermissions.Read, DateTimeOffset.Now.AddHours(1)));
        }
Beispiel #9
0
        public async Task <string> UploadFileAsync(string filePath, string container, string blobName, bool overwrite = false, CancellationToken cancellationToken = default)
        {
            BlobContainerClient containerClient = _blobClient.GetBlobContainerClient(container);
            // Create the container if it does not exist.
            await containerClient.CreateIfNotExistsAsync(cancellationToken : cancellationToken);

            await using var stream = File.OpenRead(filePath);
            BlobClient blobClient = containerClient.GetBlobClient(blobName);

            if (overwrite || !await blobClient.ExistsAsync(cancellationToken))
            {
                await blobClient.UploadAsync(stream, overwrite, cancellationToken);
            }
            return(blobClient.GenerateSasUri(BlobSasPermissions.Read, DateTimeOffset.MaxValue).ToString());
        }
        public DownloadSasUriTest(TOptions options) : base(options)
        {
            _blobClient = BlobContainerClient.GetBlobClient("_blobName");

            var sharedKeyBlobClient = new BlobClient(_blobClient.Uri, StorageSharedKeyCredential);

            if (sharedKeyBlobClient.CanGenerateSasUri)
            {
                SasUri = sharedKeyBlobClient.GenerateSasUri(BlobSasPermissions.Read, DateTimeOffset.UtcNow.AddDays(1));
            }
            else
            {
                throw new InvalidOperationException();
            }
        }
        public async Task GenerateSas()
        {
            string accountName   = StorageAccountName;
            string accountKey    = StorageAccountKey;
            string containerName = Randomize("sample-container");
            string blobName      = Randomize("sample-blob");
            StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential(StorageAccountName, StorageAccountKey);

            // setup blob
            var            container  = new BlobContainerClient(ConnectionString, containerName);
            BlobUriBuilder uriBuilder = new BlobUriBuilder(container.Uri)
            {
                BlobName = blobName
            };
            Uri blobUri = uriBuilder.ToUri();

            try
            {
                await container.CreateAsync();

                await container.GetBlobClient(blobName).UploadAsync(BinaryData.FromString("hello world"));

                #region Snippet:SampleSnippetsBlobMigration_GenerateSas
                // Create a BlobClient with a shared key credential
                BlobClient blobClient = new BlobClient(blobUri, sharedKeyCredential);

                Uri sasUri;
                // Ensure our client has the credentials required to generate a SAS
                if (blobClient.CanGenerateSasUri)
                {
                    // Create full, self-authenticating URI to the resource from the BlobClient
                    sasUri = blobClient.GenerateSasUri(BlobSasPermissions.Read, DateTimeOffset.UtcNow.AddHours(1));

                    // Use newly made as SAS URI to download the blob
                    await new BlobClient(sasUri).DownloadToAsync(new MemoryStream());
                }
                #endregion
                else
                {
                    Assert.Fail("Unable to create SAS URI");
                }
            }
            finally
            {
                await container.DeleteIfExistsAsync();
            }
        }
        public async Task GenerateSas_Builder()
        {
            string accountName   = StorageAccountName;
            string accountKey    = StorageAccountKey;
            string containerName = Randomize("sample-container");
            string blobName      = Randomize("sample-blob");
            StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential(StorageAccountName, StorageAccountKey);

            // setup blob
            var            container  = new BlobContainerClient(ConnectionString, containerName);
            BlobUriBuilder uriBuilder = new BlobUriBuilder(container.Uri)
            {
                BlobName = blobName
            };
            Uri blobUri = uriBuilder.ToUri();

            try
            {
                await container.CreateAsync();

                await container.GetBlobClient(blobName).UploadAsync(BinaryData.FromString("hello world"));

                // Create a BlobClient with a shared key credential
                BlobClient blobClient = new BlobClient(blobUri, sharedKeyCredential);
                // Create BlobSasBuilder and specify parameters
                #region Snippet:SampleSnippetsBlobMigration_GenerateSas_Builder
                BlobSasBuilder sasBuilder = new BlobSasBuilder(BlobSasPermissions.Read, DateTimeOffset.UtcNow.AddHours(1))
                {
                    // Since we are generating from the client, the client will have the container and blob name
                    // Specify any optional paremeters here
                    StartsOn = DateTimeOffset.UtcNow.AddHours(-1)
                };

                // Create full, self-authenticating URI to the resource from the BlobClient
                Uri sasUri = blobClient.GenerateSasUri(sasBuilder);
                #endregion

                // Use newly made as SAS URI to download the blob
                await new BlobClient(sasUri).DownloadToAsync(new MemoryStream());
            }
            finally
            {
                await container.DeleteIfExistsAsync();
            }
        }
Beispiel #13
0
        private static Uri GenerateSasURL(string containername, string blobName, BlobContainerClient containerClient)
        {
            BlobClient _client = containerClient.GetBlobClient(blobName);

            BlobSasBuilder _builder = new BlobSasBuilder()
            {
                BlobContainerName = containername,
                BlobName          = blobName,
                Resource          = "b"
            };

            _builder.SetPermissions(BlobAccountSasPermissions.Read | BlobAccountSasPermissions.List);

            _builder.ExpiresOn = DateTime.Now.AddHours(1);

            Uri sasURL = _client.GenerateSasUri(_builder);

            return(sasURL);
        }
        /// <inheritdoc />
        public string CreateSASUrl(string container, string objectName, int tokenDuration)
        {
            var blobClient = new BlobClient(_storageOptions.Value.StorageConnectionString, container, objectName);

            if (blobClient.CanGenerateSasUri)
            {
                var tokenBuilder = new BlobSasBuilder
                {
                    BlobContainerName = container,
                    BlobName          = objectName,
                    Resource          = "b",
                    ExpiresOn         = DateTimeOffset.UtcNow.AddHours(1)
                };
                tokenBuilder.SetPermissions(BlobSasPermissions.Read);
                return(blobClient.GenerateSasUri(tokenBuilder).ToString());
            }

            _logger.LogError("Azure Connection String not authorized with enough permissions to create a SAS");
            throw new InvalidOperationException("Azure Connection String doesn't support creating SAS URLs");
        }
Beispiel #15
0
        /// <summary>
        /// Returns a URI containing a SAS for the blob.
        /// </summary>
        /// <param name="container">A reference to the container.</param>
        /// <param name="blobName">A string containing the name of the blob.</param>
        /// <returns>A string containing the URI for the blob, with the SAS token appended.</returns>
        static Uri GetBlobSasUri(BlobContainerClient container, string blobName)
        {
            //Get a reference to a blob within the container.
            //Note that the blob may not exist yet, but a SAS can still be created for it.
            BlobClient blob = container.GetBlobClient(blobName);

            var policy = new BlobSasBuilder
            {
                BlobContainerName = container.Name,
                BlobName          = blobName,
                Resource          = "b",
                StartsOn          = DateTimeOffset.UtcNow.AddHours(-1),
                ExpiresOn         = DateTimeOffset.UtcNow.AddHours(1),
            };

            policy.SetPermissions(BlobSasPermissions.All);
            Uri sasUri = blob.GenerateSasUri(policy);

            //Return the URI string for the blob, including the SAS token.
            return(sasUri);
        }
Beispiel #16
0
        private static Uri GetServiceSasUriForBlob(ILogger log, BlobClient blobClient,
                                                   string containerName, string blobName,
                                                   string storedPolicyName = null)
        {
            // Check whether this BlobClient object has been authorized with Shared Key.
            log.LogInformation($"trying to get sas blobClient==null?{blobClient==null}. ");

            if (blobClient != null && blobClient.CanGenerateSasUri)
            {
                // Create a SAS token that's valid for one hour.
                BlobSasBuilder sasBuilder = new BlobSasBuilder()
                {
                    BlobContainerName = containerName,
                    BlobName          = blobName,
                    Resource          = "b"
                };

                if (storedPolicyName == null)
                {
                    sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(1);
                    sasBuilder.SetPermissions(BlobSasPermissions.Read |
                                              BlobSasPermissions.Write);
                }
                else
                {
                    sasBuilder.Identifier = storedPolicyName;
                }

                Uri sasUri = blobClient.GenerateSasUri(sasBuilder);

                return(sasUri);
            }
            else
            {
                log.LogError("BlobClient must be authorized with Shared Key credentials to create a service SAS.");
                return(null);
            }
        }
Beispiel #17
0
        static async Task Main(string[] args)
        {
            string connectionString = "CONNECTION_STRING";
            string containerName    = "fileuploadsample";
            string blobFileName     = "sample.png";
            // Upload file to blob
            BlobContainerClient containerClient = new BlobContainerClient(connectionString, containerName);
            await containerClient.CreateIfNotExistsAsync(PublicAccessType.None); //Making blob private.

            BlobClient blobClient = new BlobClient(connectionString, containerName, blobFileName);

            using FileStream fileStream = File.OpenRead(blobFileName);
            await blobClient.UploadAsync(fileStream, true);

            fileStream.Close();

            Console.WriteLine(blobClient.Uri.ToString());

            // Generate SAS URI for blob
            BlobSasBuilder sasBuilder = new BlobSasBuilder()
            {
                BlobContainerName = containerClient.Name,
                Resource          = "b",
                BlobName          = blobClient.Name
            };

            sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(1);
            sasBuilder.SetPermissions(BlobContainerSasPermissions.Read);

            if (blobClient.CanGenerateSasUri)
            {
                Uri blobSasUri = blobClient.GenerateSasUri(sasBuilder);
                Console.WriteLine(blobSasUri.ToString());
            }
            Console.ReadLine();
        }
Beispiel #18
0
            protected override async Task <ZipResult> OnExecuteAsync(ZipRequest request)
            {
                var containerClient = new BlobContainerClient(_storageConnection, request.ContainerName);
                var pages           = containerClient.GetBlobsAsync(prefix: request.BlobPrefix).AsPages();

                const int maxFiles = 10; // to prevent runaway huge files. remember, this is just a little demo
                int       count    = 0;

                using (var outputStream = new MemoryStream())
                {
                    using (var outputZip = new ZipArchive(outputStream, ZipArchiveMode.Create, true))
                    {
                        await foreach (var page in pages)
                        {
                            foreach (var blob in page.Values)
                            {
                                if (blob.Name.EndsWith(".zip"))
                                {
                                    continue;                             // don't include other zip files
                                }
                                count++;
                                if (count > maxFiles)
                                {
                                    break;
                                }

                                var blobClient = new BlobClient(_storageConnection, request.ContainerName, blob.Name);
                                using (var inputStream = await blobClient.OpenReadAsync())
                                {
                                    var entry = outputZip.CreateEntry(blob.Name);
                                    using (var entryStream = entry.Open())
                                    {
                                        await inputStream.CopyToAsync(entryStream);
                                    }
                                }
                            }
                        }
                    }

                    var outputBlobClient = new BlobClient(_storageConnection, request.ContainerName, StringId.New(8, StringIdRanges.Lower | StringIdRanges.Numeric) + ".zip");
                    outputStream.Position = 0;
                    await outputBlobClient.UploadAsync(outputStream, new BlobUploadOptions()
                    {
                        HttpHeaders = new BlobHttpHeaders()
                        {
                            ContentType = "application/zip"
                        }
                    });

                    var expirationDate = DateTime.UtcNow.AddDays(3);

                    var sasUri = outputBlobClient.GenerateSasUri(BlobSasPermissions.Read, expirationDate);

                    return(new ZipResult()
                    {
                        Url = sasUri.ToString(),
                        ExpiresAfter = expirationDate,
                        BlobName = outputBlobClient.Name
                    });
                }
            }
        public static async Task RunAsync([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log)
        {
            //Extracting content type and url of the blob triggering the function
            var jsondata = JsonConvert.SerializeObject(eventGridEvent.Data);
            var tmp      = new { contentType = "", url = "" };
            var data     = JsonConvert.DeserializeAnonymousType(jsondata, tmp);

            //Checking if the trigger was iniatiated for a PDF File.
            if (data.contentType == "application/pdf")
            {
                var pdfUrl = data.url;

                string endpoint = System.Environment.GetEnvironmentVariable("FormsRecognizerEndpoint", EnvironmentVariableTarget.Process);
                string apiKey   = System.Environment.GetEnvironmentVariable("FormsRecognizerKey", EnvironmentVariableTarget.Process);
                string contosoStorageConnectionString = System.Environment.GetEnvironmentVariable("ContosoStorageConnectionString", EnvironmentVariableTarget.Process);
                string cosmosEndpointUrl = System.Environment.GetEnvironmentVariable("CosmosDBEndpointUrl", EnvironmentVariableTarget.Process);
                string cosmosPrimaryKey  = System.Environment.GetEnvironmentVariable("CosmosDBPrimaryKey", EnvironmentVariableTarget.Process);

                //Create a SAS Link to give Forms Recognizer read access to the document
                BlobServiceClient   blobServiceClient = new BlobServiceClient(contosoStorageConnectionString);
                BlobContainerClient container         = new BlobContainerClient(contosoStorageConnectionString, "claims");
                string         blobName   = pdfUrl.Split('/').Last();
                BlobClient     blob       = container.GetBlobClient(blobName);
                BlobSasBuilder sasBuilder = new BlobSasBuilder()
                {
                    BlobContainerName = blob.GetParentBlobContainerClient().Name,
                    BlobName          = blob.Name,
                    Resource          = "b"
                };
                sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(1);
                sasBuilder.SetPermissions(BlobSasPermissions.Read);
                Uri sasUri = blob.GenerateSasUri(sasBuilder);

                var credential = new AzureKeyCredential(apiKey);

                //Get the latest trained model
                var formTrainingClient = new FormTrainingClient(new Uri(endpoint), credential);
                Pageable <CustomFormModelInfo> formsModels = formTrainingClient.GetCustomModels();
                var latestModel = (from inc in formsModels orderby inc.TrainingCompletedOn descending select inc).FirstOrDefault();

                //TODO:Run the document through the model

                //Insert documents into CosmosDB
                var cosmosClient    = new CosmosClient(cosmosEndpointUrl, cosmosPrimaryKey);
                var cosmosDatabase  = (await cosmosClient.CreateDatabaseIfNotExistsAsync("Contoso")).Database;
                var cosmosContainer = (await cosmosDatabase.CreateContainerIfNotExistsAsync("Claims", "/InsuredID")).Container;

                Model.ClaimsDocument processedDocument = new Model.ClaimsDocument();
                processedDocument.DocumentDate = new DateTime(int.Parse(blobName.Substring(0, 4)),
                                                              int.Parse(blobName.Substring(4, 2)), int.Parse(blobName.Substring(6, 2)));
                processedDocument.PatientName = forms[0].Fields["PatientName"].ValueData?.Text;
                processedDocument.InsuredID   = forms[0].Fields["InsuredID"].ValueData?.Text;
                processedDocument.Diagnosis   = forms[0].Fields["Diagnosis"].ValueData?.Text;
                decimal.TryParse(forms[0].Fields["TotalCharges"].ValueData?.Text, out decimal totalCharges);
                processedDocument.TotalCharges = totalCharges;
                DateTime.TryParse(forms[0].Fields["PatientBirthDate"].ValueData?.Text, out DateTime patientBirthDate);
                processedDocument.PatientBirthDate = patientBirthDate;
                decimal.TryParse(forms[0].Fields["AmountPaid"].ValueData?.Text, out decimal amountPaid);
                processedDocument.AmountPaid = amountPaid;
                decimal.TryParse(forms[0].Fields["AmountDue"].ValueData?.Text, out decimal amountDue);
                processedDocument.AmountDue = amountDue;
                processedDocument.FileName  = blobName;
                if (processedDocument.InsuredID == null)
                {
                    processedDocument.Id = Guid.NewGuid().ToString();
                }
                else
                {
                    processedDocument.Id = processedDocument.InsuredID;
                }

                try
                {
                    ItemResponse <Model.ClaimsDocument> cosmosResponse = await
                                                                         cosmosContainer.CreateItemAsync(processedDocument, new PartitionKey(processedDocument.InsuredID));
                }
                catch (CosmosException ex) when(ex.StatusCode == System.Net.HttpStatusCode.Conflict)
                {
                    //Conflicting EnsurerID is silently ignored for demo purposes.
                }
            }
            log.LogInformation(eventGridEvent.Data.ToString());
        }
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            var isAuthorized = await Authenticator.AuthenticateRequestForScopeAndRole(req, "CMS.Articles.Edit", "Articles.Write", log);

            if (!isAuthorized)
            {
                return(new UnauthorizedResult());
            }

            var articleId = req.Query["articleId"];

            if (string.IsNullOrEmpty(articleId))
            {
                log.LogError("GetImageUploadSasToken called without article ID");
                return(new BadRequestObjectResult("articleId required"));
            }

            var fileName = req.Query["fileName"];

            if (string.IsNullOrEmpty(articleId))
            {
                log.LogError("GetImageUploadSasToken called without file name");
                return(new BadRequestObjectResult("fileName required"));
            }


            var article = await CmsDb.GetArticleAsync(articleId);

            if (article == null)
            {
                log.LogError($"GetImageUploadSasToken called with unknown article ID: {articleId}");
                return(new NotFoundObjectResult($"Article ID {articleId} not found."));
            }

            log.LogInformation($"Getting SAS token for image upload {fileName} to article {articleId}.");

            var storageAccountName  = Environment.GetEnvironmentVariable("ImageStorageAccountName");
            var storageAccountKey   = Environment.GetEnvironmentVariable("ImageStorageAccountKey");
            var imagesContainerName = Environment.GetEnvironmentVariable("ImageStorageBlobContainerName");

            var filePath = $"{articleId}/{fileName}";

            var blobEndpoint = $"https://{storageAccountName}.blob.core.windows.net/{imagesContainerName}/{filePath}";

            var storageCredential = new StorageSharedKeyCredential(storageAccountName, storageAccountKey);
            var blobClient        = new BlobClient(new Uri(blobEndpoint), storageCredential);

            var sasBuilder = new BlobSasBuilder(BlobSasPermissions.Write | BlobSasPermissions.Create,
                                                DateTimeOffset.UtcNow.AddMinutes(30));

            sasBuilder.BlobContainerName = blobClient.BlobContainerName;
            sasBuilder.BlobName          = filePath;
            sasBuilder.Resource          = "b";
            sasBuilder.StartsOn          = DateTimeOffset.UtcNow.AddMinutes(-5);

            var blobUri = blobClient.GenerateSasUri(sasBuilder);

            log.LogInformation($"Successfully created SAS token for image upload {fileName} to article {articleId}");

            return(new OkObjectResult(blobUri.ToString()));
        }
Beispiel #21
0
        public async Task <string> PublishFileAsync(FileMapping fileMap, CancellationToken ct)
        {
            Uri      result      = null;
            int      retriesLeft = MaxFullLoopRetries;
            TimeSpan loopDelay   = FullLoopRetryDelay;
            bool     completed   = false;

            do
            {
                _logger.LogInformation($"Attempting to publish {fileMap.RelativeOutputPath}, {retriesLeft} tries left.");
                try
                {
                    BlobContainerClient client = await GetClient(ct);

                    if (client == null)
                    {
                        // client creation failed, return
                        return(null);
                    }

                    using var srcStream = new FileStream(fileMap.LocalSourcePath, FileMode.Open, FileAccess.Read);

                    BlobClient blobClient = client.GetBlobClient(GetBlobName(_releaseName, fileMap.RelativeOutputPath));

                    await blobClient.UploadAsync(srcStream, overwrite : true, ct);

                    BlobSasBuilder sasBuilder = new BlobSasBuilder()
                    {
                        BlobContainerName = client.Name,
                        BlobName          = blobClient.Name,
                        Identifier        = AccessPolicyDownloadId,
                        Protocol          = SasProtocol.Https
                    };
                    Uri accessUri = blobClient.GenerateSasUri(sasBuilder);

                    using BlobDownloadStreamingResult blobStream = (await blobClient.DownloadStreamingAsync(cancellationToken: ct)).Value;
                    srcStream.Position = 0;
                    completed          = await VerifyFileStreamsMatchAsync(srcStream, blobStream, ct);

                    result = accessUri;
                }
                catch (IOException ioEx) when(!(ioEx is PathTooLongException))
                {
                    _logger.LogWarning(ioEx, $"Failed to publish {fileMap.LocalSourcePath}, retries remaining: {retriesLeft}.");

                    /* Retry IO exceptions */
                    retriesLeft--;
                    loopDelay *= 2;

                    if (retriesLeft > 0)
                    {
                        await Task.Delay(loopDelay, ct);
                    }
                }
                catch (Exception ex)
                {
                    // Azure errors have their own built-in retry logic, so just abort if we got an AzureResponseException
                    _logger.LogWarning(ex, $"Failed to publish {fileMap.LocalSourcePath}, unexpected error, aborting.");
                    return(null);
                }
            } while (retriesLeft > 0 && !completed);

            return(result?.OriginalString);
        }
Beispiel #22
0
        private Uri GenerateSasUri(Uri bloUri)
        {
            var blobClient = new BlobClient(bloUri, _sharedKeyCredential);

            return(blobClient.GenerateSasUri(BlobSasPermissions.Read, DateTimeOffset.Now.AddSeconds(_sasTokenLifetimeSeconds)));
        }