Esempio n. 1
0
        public async Task <ActionResult> PostProfilePicture([FromRoute] int IDUser)
        {
            var connectionString = _configuration.GetConnectionString("AzureStorageConnection");
            BlobServiceClient   blobServiceClient = new BlobServiceClient(connectionString);
            string              containerName     = "profilePics";
            BlobContainerClient containerClient   = await blobServiceClient.CreateBlobContainerAsync(containerName);

            try
            {
                var httpRequest = HttpContext.Request;
                if (httpRequest.Form.Files.Count > 0)
                {
                    foreach (var file in httpRequest.Form.Files)
                    {
                        var filePath = Path.Combine(_environment.ContentRootPath, "uploads");
                        if (!Directory.Exists(filePath))
                        {
                            Directory.CreateDirectory(filePath);
                        }

                        using (var memoryStream = new MemoryStream())
                        {
                            await file.CopyToAsync(memoryStream);

                            System.IO.File.WriteAllBytes(Path.Combine(filePath,
                                                                      IDUser + "-profilePic-" + file.FileName), memoryStream.ToArray());
                        }
                        return(Ok());
                    }
                }
                return(BadRequest());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex));
            }
        }
        private async Task CreateSampleBlobs()
        {
            BlobServiceClient   blobServiceClient   = CreateServiceClient(BlobStorageConnectionString);
            BlobContainerClient blobContainerClient = blobServiceClient.GetBlobContainerClient("sources");

            if (!await blobContainerClient.ExistsAsync())
            {
                blobContainerClient = await blobServiceClient.CreateBlobContainerAsync("sources");
            }
            // Create two sample blobs we will pull down later
            BlobClient blobClient = blobContainerClient.GetBlobClient("sample.dat");

            if (!await blobClient.ExistsAsync())
            {
                await using var sampleData = new MemoryStream(Encoding.UTF8.GetBytes("sample"));
                await blobClient.UploadAsync(sampleData, false);
            }
            blobClient = blobContainerClient.GetBlobClient("sample2.dat");
            if (!await blobClient.ExistsAsync())
            {
                await using var sampleData = new MemoryStream(Encoding.UTF8.GetBytes("sample2"));
                await blobClient.UploadAsync(sampleData, false);
            }
        }
        public async Task CreateContainerShortcut()
        {
            string connectionString = this.ConnectionString;
            string containerName    = Randomize("sample-container");

            // use extra variable so the snippet gets variable declarations but we still get the try/finally
            var containerClientTracker = new BlobServiceClient(connectionString).GetBlobContainerClient(containerName);

            try
            {
                #region Snippet:SampleSnippetsBlobMigration_CreateContainerShortcut
                BlobServiceClient   blobServiceClient = new BlobServiceClient(connectionString);
                BlobContainerClient containerClient   = await blobServiceClient.CreateBlobContainerAsync(containerName);

                #endregion

                // pass if success
                containerClient.GetProperties();
            }
            finally
            {
                await containerClientTracker.DeleteIfExistsAsync();
            }
        }
Esempio n. 4
0
        public async Task SetUp()
        {
            NServiceBus.AcceptanceTesting.Customization.Conventions.EndpointNamingConvention = t =>
            {
                var classAndEndpoint = t.FullName.Split('.').Last();

                var testName = classAndEndpoint.Split('+').First();

                testName = testName.Replace("When_", "");

                var endpointBuilder = classAndEndpoint.Split('+').Last();

                testName = Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(testName);

                testName = testName.Replace("_", "");

                return(testName + "-" + endpointBuilder);
            };

            tableNamePrefix      = $"Att{Path.GetFileNameWithoutExtension(Path.GetTempFileName())}{DateTime.UtcNow.Ticks}".ToLowerInvariant();
            timeoutTableName     = tableNamePrefix + TimeoutTableName;
            timeoutContainerName = tableNamePrefix + "timeoutsstate";

            connectionString = Environment.GetEnvironmentVariable(EnvironmentVariables.AzureStorageConnectionString);

            var account = CloudStorageAccount.Parse(connectionString);

            tableClient = account.CreateCloudTableClient();


            timeoutTable = tableClient.GetTableReference(timeoutTableName);
            await timeoutTable.CreateIfNotExistsAsync();

            blobServiceClient = new BlobServiceClient(connectionString);
            await blobServiceClient.CreateBlobContainerAsync(timeoutContainerName);
        }
Esempio n. 5
0
        static async Task Main(string[] args)
        {
            // In real live you would take the conStr from an env var
            // setx AZURE_STORAGE_CONNECTION_STRING "DefaultEndpointsProtocol=https;AccountName=az203storageacct10010;AccountKey=..."
            // string connectionString = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");

            string connectionString = "DefaultEndpointsProtocol=https;AccountName=storage0078;AccountKey=yxe4XysMdEOonXaHhWenbLO3Ar04ceBj6AUyH7XSRdkC1Sh//3jjWImXF5oF7f1rGQxDx5c6asfcB7rsYbREFw==;EndpointSuffix=core.windows.net";

            BlobServiceClient   blobServiceClient = new BlobServiceClient(connectionString);
            string              containerName     = "demo" + Guid.NewGuid().ToString();;
            BlobContainerClient containerClient   = await blobServiceClient.CreateBlobContainerAsync(containerName);

            await
            foreach (BlobItem blobItem in containerClient.GetBlobsAsync())
            {
                Console.WriteLine("\t" + blobItem.Name);
            }

            string localPath     = "./textfiles/";
            string fileName      = "quickstart" + Guid.NewGuid().ToString() + ".txt";
            string localFilePath = Path.Combine(localPath, fileName);

            // Write text to the file
            await File.WriteAllTextAsync(localFilePath, "Hello, World!");

            // Get a reference to a blob
            BlobClient blobClient = containerClient.GetBlobClient(fileName);

            Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", blobClient.Uri);

            // Open the file and upload its data
            using FileStream uploadFileStream = File.OpenRead(localFilePath);
            await blobClient.UploadAsync(uploadFileStream);

            uploadFileStream.Close();
        }
Esempio n. 6
0
 public async Task CreateContainerAsync(string cotainerName) =>
 await _blobServiceClient.CreateBlobContainerAsync(
     blobContainerName : cotainerName,
     publicAccessType : PublicAccessType.BlobContainer);
Esempio n. 7
0
        private static void CreateContainer(string storageConnString, string containerName)
        {
            BlobServiceClient blobServiceClient = new BlobServiceClient(storageConnString);

            blobServiceClient.CreateBlobContainerAsync(containerName).Wait();
        }
Esempio n. 8
0
 public async Task <BlobContainerClient> CreateDirectoryAsync(string directoryName, CancellationToken cancellationToken = default)
 {
     return(await _blobServiceClient.CreateBlobContainerAsync(directoryName, PublicAccessType.BlobContainer));
 }
        public async Task <IActionResult> Upload(Question q, IFormFile file)
        {
            BlobContainerClient containerClient;

            // Create the container and return a container client object
            try
            {
                if (q == Question.Computer)
                {
                    containerClient = await _blobServiceClient.CreateBlobContainerAsync(computerContainerName);
                }
                else
                {
                    containerClient = await _blobServiceClient.CreateBlobContainerAsync(earthContainerName);
                }
                // Give access to public
                containerClient.SetAccessPolicy(Azure.Storage.Blobs.Models.PublicAccessType.BlobContainer);
            }
            catch (RequestFailedException)
            {
                if (q == Question.Computer)
                {
                    containerClient = _blobServiceClient.GetBlobContainerClient(computerContainerName);
                }
                else
                {
                    containerClient = _blobServiceClient.GetBlobContainerClient(earthContainerName);
                }
            }


            try
            {
                // create the blob to hold the data
                var blockBlob = containerClient.GetBlobClient(file.FileName);
                if (await blockBlob.ExistsAsync())
                {
                    await blockBlob.DeleteAsync();
                }

                using (var memoryStream = new MemoryStream())
                {
                    // copy the file data into memory
                    await file.CopyToAsync(memoryStream);

                    // navigate back to the beginning of the memory stream
                    memoryStream.Position = 0;

                    // send the file to the cloud
                    await blockBlob.UploadAsync(memoryStream);

                    memoryStream.Close();
                }

                // add the photo to the database if it uploaded successfully
                var image = new AnswerImage();
                image.Url      = blockBlob.Uri.AbsoluteUri;
                image.FileName = file.FileName;
                image.Question = q;

                _context.Images.Add(image);
                _context.SaveChanges();
            }
            catch (RequestFailedException)
            {
                View("Error");
            }

            return(RedirectToAction("Index"));
        }
Esempio n. 10
0
 public Task CreateBlobAsync(string blobName)
 {
     return(_blobServiceClient.CreateBlobContainerAsync(blobName));
 }
Esempio n. 11
0
 public async Task PostAsync([FromBody] string name)
 {
     BlobContainerClient blobContainer = await _client.CreateBlobContainerAsync(name);
 }
Esempio n. 12
0
 static async Task Container()
 {
     BlobServiceClient   blobServiceClient   = new BlobServiceClient(ConnectionString);
     BlobContainerClient blobContainerClient = await blobServiceClient.CreateBlobContainerAsync(ContainerName);
 }
Esempio n. 13
0
 public async Task <bool> CreateBlobContainer(string containerName) => await Execute(() => _blobServiceClient.CreateBlobContainerAsync(containerName));
Esempio n. 14
0
        static async Task Container()
        {
            BlobServiceClient blobServiceClient = new BlobServiceClient(storageconnstring);

            BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);
        }
Esempio n. 15
0
        public async Task <Response <BlobContainerClient> > CreateContainer(string containerName)
        {
            var response = await _client.CreateBlobContainerAsync(containerName);

            return(response);
        }
        public async Task StartTranslationWithAzureBlob()
        {
            /**
             * FILE: SampleTranslationWithAzureBlob.cs
             * DESCRIPTION:
             *  This sample demonstrates how to use Azure Blob Storage to set up the necessary resources to create a translation
             *  operation. Run the sample to create containers, upload documents, and generate SAS tokens for the source/target
             *  containers. Once the operation is completed, use the storage library to download your documents locally.
             *
             * PREREQUISITE:
             *  This sample requires you install Azure.Storage.Blobs nuget package:
             *  https://www.nuget.org/packages/Azure.Storage.Blobs
             *
             * USAGE:
             *  Set the environment variables with your own values before running the sample:
             *  1) DOCUMENT_TRANSLATION_ENDPOINT - the endpoint to your Document Translation resource.
             *  2) DOCUMENT_TRANSLATION_API_KEY - your Document Translation API key.
             *  3) DOCUMENT_TRANSLATION_CONNECTION_STRING - the connection string to your Storage account
             *  4) AZURE_DOCUMENT_PATH - (optional) the path and file extension of your document in this directory
             *      e.g. "path/mydocument.txt"
             *  Optionally, you can also set the following variables in code:
             *  5) sourceContainerName - the name of your source container
             *  6) targetContainerName - the name of your target container
             **/
#if SNIPPET
            string endpoint = "<Document Translator Resource Endpoint>";
            string apiKey   = "<Document Translator Resource API Key>";
#else
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;
#endif

            var client = new DocumentTranslationClient(new Uri(endpoint), new AzureKeyCredential(apiKey));

            var storageConnectionString = Environment.GetEnvironmentVariable("DOCUMENT_TRANSLATION_CONNECTION_STRING");
#if SNIPPET
            string sourceContainerName = "<Source Container Name>";
            string targetContainerName = "<Target Container Name>";
#else
            string sourceContainerName = GenerateRandomName("source");
            string targetContainerName = GenerateRandomName("target");
#endif
            string documentPath = Environment.GetEnvironmentVariable("AZURE_DOCUMENT_PATH");

            // Create source and target storage containers
            BlobServiceClient   blobServiceClient     = new BlobServiceClient(storageConnectionString);
            BlobContainerClient sourceContainerClient = await blobServiceClient.CreateBlobContainerAsync(sourceContainerName ?? "translation-source-container", PublicAccessType.BlobContainer).ConfigureAwait(false);

            BlobContainerClient targetContainerClient = await blobServiceClient.CreateBlobContainerAsync(targetContainerName ?? "translation-target-container", PublicAccessType.BlobContainer).ConfigureAwait(false);

            // Upload blob (file) to the source container
            BlobClient srcBlobClient = sourceContainerClient.GetBlobClient(!string.IsNullOrWhiteSpace(documentPath) ? Path.GetFileName(documentPath) : "example_source_document.txt");

            if (!string.IsNullOrWhiteSpace(documentPath))
            {
                using (FileStream uploadFileStream = File.OpenRead(documentPath))
                {
                    await srcBlobClient.UploadAsync(uploadFileStream, true).ConfigureAwait(false);
                }
            }
            else
            {
                await srcBlobClient.UploadAsync(new MemoryStream(Encoding.UTF8.GetBytes("Hello.\nThis is a testing text.")), true).ConfigureAwait(false);
            }

            Console.WriteLine($"Uploaded document {srcBlobClient.Uri} to source storage container");

            // Generate SAS tokens for source & target
            Uri srcSasUri = sourceContainerClient.GenerateSasUri(BlobContainerSasPermissions.List | BlobContainerSasPermissions.Read, DateTime.UtcNow.AddMinutes(30));
            Uri tgtSasUri = targetContainerClient.GenerateSasUri(BlobContainerSasPermissions.List | BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Delete, DateTime.UtcNow.AddMinutes(30));

            // Submit the translation operation and wait for it to finish
            var operationRequest = new DocumentTranslationInput(srcSasUri, tgtSasUri, "es");
            DocumentTranslationOperation operationResult = await client.StartTranslationAsync(operationRequest);

            await operationResult.WaitForCompletionAsync();

            Console.WriteLine($"Operation status: {operationResult.Status}");
            Console.WriteLine($"Operation created on: {operationResult.CreatedOn}");
            Console.WriteLine($"Operation last updated on: {operationResult.LastModified}");
            Console.WriteLine($"Total number of translations on documents: {operationResult.DocumentsTotal}");
            Console.WriteLine("\nOf total documents...");
            Console.WriteLine($"{operationResult.DocumentsFailed} failed");
            Console.WriteLine($"{operationResult.DocumentsSucceeded} succeeded");

            await foreach (DocumentStatusResult document in operationResult.GetDocumentStatusesAsync())
            {
                if (document.Status == DocumentTranslationStatus.Succeeded)
                {
                    Console.WriteLine($"Document at {document.SourceDocumentUri} was translated to {document.TranslatedToLanguageCode} language.You can find translated document at {document.TranslatedDocumentUri}");
                }
                else
                {
                    Console.WriteLine($"Document ID: {document.Id}, Error Code: {document.Error.Code}, Message: {document.Error.Message}");
                }
            }
        }
Esempio n. 17
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Azure Blob storage: DropBox\n");
            string connectionString = Environment.GetEnvironmentVariable("Storage_Account");

            // Create a BlobServiceClient object which will be used to create a container client
            BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);

            //Create a unique name for the container
            string containerName = "jamilblobs" + Guid.NewGuid().ToString();

            // Create the container and return a container client object
            BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);

            // Upload blobs to a container:

            // Create a local file in the ./data/ directory for uploading and downloading
            string localPath     = "../data/";
            string fileName      = "myFile" + Guid.NewGuid().ToString() + ".txt";
            string localFilePath = Path.Combine(localPath, fileName);

            // Write text to the file
            await File.WriteAllTextAsync(localFilePath, "Hello, Jamil!");

            // Get a reference to a blob
            BlobClient blobClient = containerClient.GetBlobClient(fileName);

            //Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", blobClient.Uri);
            Console.WriteLine($"Uploading to Blob Storage:\n\t {blobClient.Uri}\n");

            // Open the file and upload its data
            using FileStream uploadFileStream = File.OpenRead(localFilePath);
            await blobClient.UploadAsync(uploadFileStream, true);

            uploadFileStream.Close();


            // List all blobs in the container

            Console.WriteLine("Blobs Lists");
            await foreach (BlobItem blobItem in containerClient.GetBlobsAsync())
            {
                Console.WriteLine("\t" + blobItem.Name);
            }

            //Downloading blobs:

            string downloadFilePath = localFilePath.Replace(".txt", "Download.txt");

            Console.WriteLine($"\nDownloading blob to\n\t{ downloadFilePath }\n");

            BlobDownloadInfo download = await blobClient.DownloadAsync();

            using FileStream downloadFileStream = File.OpenWrite(downloadFilePath);

            await download.Content.CopyToAsync(downloadFileStream);

            downloadFileStream.Close();

            //Deleting a Container:

            Console.WriteLine("Type y to Delete or n to exit:\n");

            bool choise = Console.ReadLine() == "y" ? true : false;

            if (choise)
            {
                await containerClient.DeleteAsync();

                File.Delete(localFilePath);

                File.Delete(downloadFilePath);

                Console.WriteLine("Done!");
            }
            else
            {
                Console.WriteLine("Exiting..");
            }


            Console.ReadKey();
        }
Esempio n. 18
0
        public async Task <IBlobStorageService> GetBlobStorageClientAsync(string containerName)
        {
            var blobContainerClient = await _blobServiceClient.CreateBlobContainerAsync(containerName);

            return(new BlobStorageService.BlobStorageService(blobContainerClient));
        }
Esempio n. 19
0
        private async Task <BlobContainerClient> GetClient(CancellationToken ct)
        {
            if (_client == null)
            {
                BlobServiceClient serviceClient = new BlobServiceClient(AccountBlobUri, AccountCredential, BlobOptions);
                _logger.LogInformation($"Attempting to connect to {serviceClient.Uri} to store blobs.");

                BlobContainerClient newClient;
                int attemptCt = 0;
                do
                {
                    try
                    {
                        newClient = serviceClient.GetBlobContainerClient(_containerName);
                        if (!(await newClient.ExistsAsync(ct)).Value)
                        {
                            newClient = (await serviceClient.CreateBlobContainerAsync(_containerName, PublicAccessType.None, metadata: null, ct));
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogWarning(ex, $"Failed to create or access {_containerName}, retrying with new name.");
                        continue;
                    }

                    try
                    {
                        DateTime baseTime = DateTime.UtcNow;
                        // Add the new (or update existing) "download" policy to the container
                        // This is used to mint the SAS tokens without an expiration policy
                        // Expiration can be added later by modifying this policy
                        BlobSignedIdentifier downloadPolicyIdentifier = new BlobSignedIdentifier()
                        {
                            Id           = AccessPolicyDownloadId,
                            AccessPolicy = new BlobAccessPolicy()
                            {
                                Permissions     = "r",
                                PolicyStartsOn  = new DateTimeOffset(baseTime.AddSeconds(-ClockSkewSec)),
                                PolicyExpiresOn = new DateTimeOffset(DateTime.UtcNow.AddDays(_sasValidDays).AddSeconds(ClockSkewSec)),
                            }
                        };
                        _logger.LogInformation($"Writing download access policy: {AccessPolicyDownloadId} to {_containerName}.");
                        await newClient.SetAccessPolicyAsync(PublicAccessType.None, new BlobSignedIdentifier[] { downloadPolicyIdentifier }, cancellationToken : ct);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogWarning(ex, $"Failed to write access policy for {_containerName}, retrying.");
                        continue;
                    }

                    _logger.LogInformation($"Container {_containerName} is ready.");
                    _client = newClient;
                    break;
                } while (++attemptCt < MaxFullLoopRetries);
            }

            if (_client == null)
            {
                _logger.LogError("Failed to create or access container for publishing drop.");
            }
            return(_client);
        }
Esempio n. 20
0
        /// <summary>
        /// Sets up the necessary containers in Azure Blob Storage.
        /// </summary>
        private async Task InitialiseStorageAsync()
        {
            BlobServiceClient = new BlobServiceClient(Configuration["Storage:ConnectionString"]);

            // create containers as necessary
            try
            {
                await BlobServiceClient.CreateBlobContainerAsync(Constants.StorageOriginalContainerName);

                Log.Information($"Server.InitialiseStorageAsync: Created Azure blob storage container: {Constants.StorageOriginalContainerName}");
            }
            catch (RequestFailedException e)
            {
                if (e.ErrorCode == "ContainerAlreadyExists")
                {
                    Log.Information($"Server.InitialiseStorageAsync: Container already exists: {Constants.StorageOriginalContainerName}");
                }
                else
                {
                    // something bad happened
                    throw;
                }
            }

            var spec3840 = ImageFileSpecs.Specs.Single(ifs => ifs.FileSpec == FileSpec.Spec3840);

            try
            {
                await BlobServiceClient.CreateBlobContainerAsync(spec3840.ContainerName);

                Log.Information($"Server.InitialiseStorageAsync: Created Azure blob storage container: {spec3840.ContainerName}");
            }
            catch (RequestFailedException e)
            {
                if (e.ErrorCode == "ContainerAlreadyExists")
                {
                    Log.Information($"Server.InitialiseStorageAsync: Container already exists: {spec3840.ContainerName}");
                }
                else
                {
                    // something bad happened
                    throw;
                }
            }

            var spec1440 = ImageFileSpecs.Specs.Single(ifs => ifs.FileSpec == FileSpec.Spec2560);

            try
            {
                await BlobServiceClient.CreateBlobContainerAsync(spec1440.ContainerName);

                Log.Information($"Server.InitialiseStorageAsync: Created Azure blob storage container: {spec1440.ContainerName}");
            }
            catch (RequestFailedException e)
            {
                if (e.ErrorCode == "ContainerAlreadyExists")
                {
                    Log.Information($"Server.InitialiseStorageAsync: Container already exists: {spec1440.ContainerName}");
                }
                else
                {
                    // something bad happened
                    throw;
                }
            }

            var spec1080 = ImageFileSpecs.Specs.Single(ifs => ifs.FileSpec == FileSpec.Spec1920);

            try
            {
                await BlobServiceClient.CreateBlobContainerAsync(spec1080.ContainerName);

                Log.Information($"Server.InitialiseStorageAsync: Created Azure blob storage container: {spec1080.ContainerName}");
            }
            catch (RequestFailedException e)
            {
                if (e.ErrorCode == "ContainerAlreadyExists")
                {
                    Log.Information($"Server.InitialiseStorageAsync: Container already exists: {spec1080.ContainerName}");
                }
                else
                {
                    // something bad happened
                    throw;
                }
            }

            var spec800 = ImageFileSpecs.Specs.Single(ifs => ifs.FileSpec == FileSpec.Spec800);

            try
            {
                await BlobServiceClient.CreateBlobContainerAsync(spec800.ContainerName);

                Log.Information($"Server.InitialiseStorageAsync: Created Azure blob storage container: {spec800.ContainerName}");
            }
            catch (RequestFailedException e)
            {
                if (e.ErrorCode == "ContainerAlreadyExists")
                {
                    Log.Information($"Server.InitialiseStorageAsync: Container already exists: {spec800.ContainerName}");
                }
                else
                {
                    // something bad happened
                    throw;
                }
            }

            var specLowRes = ImageFileSpecs.Specs.Single(ifs => ifs.FileSpec == FileSpec.SpecLowRes);

            try
            {
                await BlobServiceClient.CreateBlobContainerAsync(specLowRes.ContainerName);

                Log.Information($"Server.InitialiseStorageAsync: Created Azure blob storage container: {specLowRes.ContainerName}");
            }
            catch (RequestFailedException e)
            {
                if (e.ErrorCode == "ContainerAlreadyExists")
                {
                    Log.Information($"Server.InitialiseStorageAsync: Container already exists: {specLowRes.ContainerName}");
                }
                else
                {
                    // something bad happened
                    throw;
                }
            }

            try
            {
                // these pictures can be served straight from their container
                await BlobServiceClient.CreateBlobContainerAsync(Constants.StorageUserPicturesContainerName, PublicAccessType.Blob);

                Log.Information($"Server.InitialiseStorageAsync: Created Azure blob storage container: {Constants.StorageUserPicturesContainerName}");
            }
            catch (RequestFailedException e)
            {
                if (e.ErrorCode == "ContainerAlreadyExists")
                {
                    Log.Information($"Server.InitialiseStorageAsync: Container already exists: {Constants.StorageUserPicturesContainerName}");
                }
                else
                {
                    // something bad happened
                    throw;
                }
            }
        }
Esempio n. 21
0
 private static async Task CreateContainer()
 {
     containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);
 }
        private static async Task LoadFiles(string backupPath)
        {
            try
            {
                string connectionString = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");

                //Creating Container
                string            containerName     = $"mysqlbackup-{DateTime.UtcNow.ToString("ddMyyyy-HHmmss")}";
                BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);

                Console.WriteLine("containerName: " + containerName);

                BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);

                Console.WriteLine($"containerClient {containerClient.Name}");

                // Create a local file in the ./data/ directory for uploading and downloading

                /* string localPath = "./data/";
                 * string fileName = $"quickstart{Guid.NewGuid().ToString()}.txt";
                 * string localFilePath = Path.Combine(localPath, fileName);
                 *
                 * await File.WriteAllTextAsync(localFilePath, "Hello, World!"); */
                string fileName      = "all_databases.sql";
                string localFilePath = Path.Combine(backupPath, fileName);

                // Ger a reference to a blob
                BlobClient blobClient = containerClient.GetBlobClient(fileName);

                Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", blobClient.Uri);

                // Open the file and upload its data
                using (FileStream uploadFileStream = File.OpenRead(localFilePath))
                {
                    await blobClient.UploadAsync(uploadFileStream, true);
                }

                Console.WriteLine("Listing blobs...");

                await foreach (BlobItem blobItem in containerClient.GetBlobsAsync())
                {
                    Console.WriteLine("\t" + blobItem.Name);
                }

                // Download the blob to a local file
                // Append the string "DOWNLOAD" before the .txt extension
                // so you can compare the files in the data directory

                /* string downloadFilePath = localFilePath.Replace(".txt", "_download.txt");
                 * Console.WriteLine($"\nDownloading blob to \n\t{downloadFilePath}");
                 *
                 * // Download the blob's contents and save it to a file
                 * BlobDownloadInfo download = await blobClient.DownloadAsync();
                 *
                 * using (FileStream downloadFileStream = File.OpenWrite(downloadFilePath))
                 * {
                 *  await download.Content.CopyToAsync(downloadFileStream);
                 *  downloadFileStream.Close();
                 * } */

                // Clean up
                // await containerClient.DeleteAsync();
                // File.Delete(localFilePath);
                Console.WriteLine("Backup finished");
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("Error " + ex.Message);
                throw;
            }
        }
Esempio n. 23
0
        public async Task <IActionResult> Upload(IFormFile adImage, string id)
        {
            BlobContainerClient containerClient; // instanciate a class to allow us to manipulate the blob storage we made

            try
            {
                // Attempt to create a new container that will hold our blob images if it already exists we'll get a RequestFailedException
                containerClient = await _blobServiceClient.CreateBlobContainerAsync(containerName);

                // Set the access to the container to be public allowing anyone to upload images to our blob container
                containerClient.SetAccessPolicy(Azure.Storage.Blobs.Models.PublicAccessType.BlobContainer);
            }
            catch (RequestFailedException)
            {
                // We've already made a blob container, continue with the old blob container.
                containerClient = _blobServiceClient.GetBlobContainerClient(containerName);
            }

            try
            {
                // create the blob to hold the data
                var blockBlob = containerClient.GetBlobClient(adImage.FileName);

                // check if the blob already exists
                if (await blockBlob.ExistsAsync())
                {
                    // if so lets delete it.
                    await blockBlob.DeleteAsync();
                }

                // get a new memory stream so we can upload to the storage container.
                using (var memoryStream = new MemoryStream())
                {
                    // copy the file data into memory
                    await adImage.CopyToAsync(memoryStream);

                    // navigate back to the beginning of the memory stream
                    memoryStream.Position = 0;

                    // send the file to the cloud
                    await blockBlob.UploadAsync(memoryStream);

                    memoryStream.Close();
                }

                // add the photo to the database if it uploaded successfully.
                var image = new Advertisement();
                image.Url      = blockBlob.Uri.AbsoluteUri;
                image.FileName = adImage.FileName;

                Community community = null;
                if (id != null)
                {
                    community = await _context.Communities.FindAsync(id);

                    image.CommunityID = community.ID;
                    image.Community   = community;
                }
                else
                {
                    return(NotFound());
                }


                // add it to our array of answer images in our AnswerImageDataContext
                _context.Advertisements.Add(image);
                // update our data in the database with the new data added above.
                _context.SaveChanges();
            }
            catch (RequestFailedException)
            {
                // if the image fails to upload to our storage.
                View("Error");
            }
            // return to our index view.
            return(RedirectToAction(nameof(Index), new { id = id }));
        }
Esempio n. 24
0
        static async Task Main()
        {
            //Connection String form Storage Access
            string connectionString = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");
            // Create a BlobServiceClient object which will be used to create a container client
            BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);

            //Create a unique name for the container
            string containerName = "quickstartblobs" + Guid.NewGuid().ToString();

            // Create the container and return a container client object
            BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);

            // Create a local file in the ./data/ directory for uploading and downloading
            string localPath     = "./data/";
            string fileName      = "quickstart" + Guid.NewGuid().ToString() + ".txt";
            string localFilePath = Path.Combine(localPath, fileName);

            // Write text to the file
            await File.WriteAllTextAsync(localFilePath, "Hello, World!");

            // Get a reference to a blob
            BlobClient blobClient = containerClient.GetBlobClient(fileName);

            Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", blobClient.Uri);

            // Open the file and upload its data
            using FileStream uploadFileStream = File.OpenRead(localFilePath);
            await blobClient.UploadAsync(uploadFileStream, true);

            uploadFileStream.Close();

            Console.WriteLine("Listing blobs...");

            // List all blobs in the container
            await foreach (BlobItem blobItem in containerClient.GetBlobsAsync())
            {
                Console.WriteLine("\t" + blobItem.Name);
            }
            // Download the blob to a local file
            // Append the string "DOWNLOAD" before the .txt extension
            // so you can compare the files in the data directory
            string downloadFilePath = localFilePath.Replace(".txt", "DOWNLOAD.txt");

            Console.WriteLine("\nDownloading blob to\n\t{0}\n", downloadFilePath);

            // Download the blob's contents and save it to a file
            BlobDownloadInfo download = await blobClient.DownloadAsync();

            using (FileStream downloadFileStream = File.OpenWrite(downloadFilePath))
            {
                await download.Content.CopyToAsync(downloadFileStream);

                downloadFileStream.Close();
            }

            // Clean up
            Console.Write("Press any key to begin clean up");
            Console.ReadLine();

            Console.WriteLine("Deleting blob container...");
            await containerClient.DeleteAsync();

            Console.WriteLine("Deleting the local source and downloaded files...");
            File.Delete(localFilePath);
            File.Delete(downloadFilePath);

            Console.WriteLine("Done");
        }
Esempio n. 25
0
        static async Task Main()
        {
            var          connectionString     = $@"UseDevelopmentStorage=true";
            const string TimeoutDataTableName = "TimeoutData";
            const string PartitionKeyScope    = "yyyy-MM-dd";
            const string ContainerName        = "timeoutsdata";

            var account     = CloudStorageAccount.Parse(connectionString);
            var tableClient = account.CreateCloudTableClient();

            var endpointTimeoutTable = tableClient.GetTableReference(TimeoutDataTableName);
            await endpointTimeoutTable.CreateIfNotExistsAsync().ConfigureAwait(false);

            var blobServiceClient = new BlobServiceClient(connectionString);
            BlobContainerClient blobContainerClient = null;

            try
            {
                blobContainerClient = await blobServiceClient.CreateBlobContainerAsync(ContainerName).ConfigureAwait(false);
            }
            catch (RequestFailedException)
            {
                blobContainerClient = blobServiceClient.GetBlobContainerClient(ContainerName);
            }

            var noOfTimeouts = 5000;

            var cutOffDate = DateTime.Now;

            var allTimeouts = new List <TimeoutDataEntity>(noOfTimeouts);

            var stateAddress = Guid.NewGuid().ToString();

            var blobClient = blobContainerClient.GetBlobClient(stateAddress);
            await blobClient.UploadAsync(new MemoryStream(Encoding.UTF8.GetBytes("{ Topic: bla }"))).ConfigureAwait(false);

            for (var i = 0; i < noOfTimeouts; i++)
            {
                var dateTime = cutOffDate.AddDays(random.Next(1, 20));

                var    sagaId     = Guid.NewGuid();
                string identifier = Guid.NewGuid().ToString();
                // aka timeout entry
                allTimeouts.Add(new TimeoutDataEntity(dateTime.ToString(PartitionKeyScope), identifier)
                {
                    OwningTimeoutManager = "Asp.FakeTimeouts",
                    Destination          = i % 10 == 0 ? "EndpointA" : "EndpointB",
                    SagaId       = sagaId,
                    StateAddress = stateAddress,
                    Time         = dateTime,
                    Headers      = "{}",
                });
                // aka saga entry
                allTimeouts.Add(new TimeoutDataEntity(sagaId.ToString(), identifier)
                {
                    OwningTimeoutManager = "Asp.FakeTimeouts",
                    Destination          = i % 10 == 0 ? "EndpointA" : "EndpointB",
                    SagaId       = sagaId,
                    StateAddress = stateAddress,
                    Time         = dateTime,
                    Headers      = "{}",
                });
                // aka main entry
                allTimeouts.Add(new TimeoutDataEntity(identifier, string.Empty)
                {
                    OwningTimeoutManager = "Asp.FakeTimeouts",
                    Destination          = i % 10 == 0 ? "EndpointA" : "EndpointB",
                    SagaId       = sagaId,
                    StateAddress = stateAddress,
                    Time         = dateTime,
                    Headers      = "{}",
                });
            }

            var tasks = new List <Task>(noOfTimeouts / 100);

            foreach (IGrouping <string, TimeoutDataEntity> byPartition in allTimeouts.GroupBy(x => x.PartitionKey))
            {
 private async Task CreateTestRunContainer()
 {
     BlobServiceClient blobServiceClient = CreateServiceClient(BlobStorageConnectionString);
     await blobServiceClient.CreateBlobContainerAsync(CONTAINER_NAME);
 }
Esempio n. 27
0
 public async Task Initialize()
 {
     // Can't call this repeatedly because it throws an error if it exists
     var container = await _client.CreateBlobContainerAsync(containerName);
 }
Esempio n. 28
0
        static async Task  Main(string[] args)
        {
            Console.WriteLine("Azure Blob storage v12 - .NET  C# Console quickstart sample\n");

            // Retrieve the connection string for use with the application. The storage
            // connection string is stored in an environment variable on the machine
            // running the application called AZURE_STORAGE_CONNECTION_STRING. If the
            // environment variable is created after the application is launched in a
            // console or with Visual Studio, the shell or application needs to be closed
            // and reloaded to take the environment variable into account.
            string connectionString = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");

            Console.WriteLine(string.Concat("connectionString:", connectionString));



            // Create a BlobServiceClient object which will be used to create a container client
            BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);

            //Create a unique name for the container
            string containerName = "test" + Guid.NewGuid().ToString();

            // Create the container and return a container client object
            BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);


            // Create a local file in the ./data/ directory for uploading and downloading
            string localPath     = "./data/";
            string fileName      = "test" + Guid.NewGuid().ToString() + ".txt";
            string localFilePath = Path.Combine(localPath, fileName);

            // Write text to the file
            File.WriteAllText(localFilePath, "Hello, World!");

            // Get a reference to a blob
            BlobClient blobClient = containerClient.GetBlobClient(fileName);

            Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", blobClient.Uri);

            // Open the file and upload its data
            using (FileStream uploadFileStream = File.OpenRead(localFilePath)) {
                await blobClient.UploadAsync(uploadFileStream, true);

                uploadFileStream.Close();
            };



            Console.WriteLine("Listing blobs...");

            // List all blobs in the container
            foreach (BlobItem blobItem in containerClient.GetBlobs())
            {
                Console.WriteLine("\t" + blobItem.Name);
            }

            // Download the blob to a local file
            // Append the string "DOWNLOADED" before the .txt extension
            // so you can compare the files in the data directory
            string downloadFilePath = localFilePath.Replace(".txt", "DOWNLOADED.txt");

            Console.WriteLine("\nDownloading blob to\n\t{0}\n", downloadFilePath);

            // Download the blob's contents and save it to a file
            BlobDownloadInfo download = await blobClient.DownloadAsync();

            using (FileStream downloadFileStream = File.OpenWrite(downloadFilePath))
            {
                await download.Content.CopyToAsync(downloadFileStream);

                downloadFileStream.Close();
            }


            // Clean up
            Console.Write("Press any key to begin clean up");
            Console.ReadLine();

            Console.WriteLine("Deleting blob container...");
            await containerClient.DeleteAsync();

            Console.WriteLine("Deleting the local source and downloaded files...");
            File.Delete(localFilePath);
            File.Delete(downloadFilePath);

            Console.WriteLine("Done");



            Console.ReadLine();
        }
Esempio n. 29
0
        static async Task CreateContainer()
        {
            BlobContainerClient container = await client.CreateBlobContainerAsync(containerName);

            Console.WriteLine("\nContainer Created::" + container.Name);
        }