Example #1
0
        private void InitContainers()
        {
            var service         = new BlobServiceClient(AppConstants.AzureStorageConnectionString);
            var containers      = service.GetBlobContainers();
            var draftsExists    = false;
            var publishedExists = false;

            foreach (var c in containers)
            {
                if (c.Name == DRAFTS)
                {
                    draftsExists = true;
                }
                if (c.Name == PUBLISHED)
                {
                    publishedExists = true;
                }

                if (draftsExists && publishedExists)
                {
                    break;
                }
            }

            if (!draftsExists)
            {
                service.CreateBlobContainer(DRAFTS);
            }

            if (!publishedExists)
            {
                service.CreateBlobContainer(PUBLISHED);
            }
        }
        public BlobStorageServiceTest()
        {
            _testContainerName = DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString();
            BlobServiceClient blobServiceClient = new BlobServiceClient(_connectionString);

            _blobContainerClient = blobServiceClient.CreateBlobContainer(_testContainerName);
        }
        public CreatedID Create(ScriptCreate apiModel)
        {
            string scriptURL = null;
            Script sc        = _aviBL.GetScriptByPilotID(apiModel.PilotID);

            if (sc != null)
            {
                scriptURL = sc.ScriptURL;
                _aviBL.DeleteScriptIfExists(apiModel.PilotID);
            }
            _aviBL.DeleteScenesIfExists(apiModel.PilotID);
            foreach (SceneCreate sceneApiModel in apiModel.Scenes)
            {
                sceneApiModel.PilotID = apiModel.PilotID;
                _aviBL.AddScene(sceneApiModel.ToDLModel());
            }
            BlobContainerClient containerClient = _blobSC.GetBlobContainerClient($"pilot{apiModel.PilotID}");

            if (!containerClient.Exists())
            {
                containerClient = _blobSC.CreateBlobContainer($"pilot{apiModel.PilotID}", Azure.Storage.Blobs.Models.PublicAccessType.BlobContainer);
            }
            else if (scriptURL != null)
            {
                containerClient.DeleteBlob(scriptURL.Substring(scriptURL.LastIndexOf('/') + 1));
            }
            BlobClient blobClient = containerClient.GetBlobClient($"script{Guid.NewGuid().ToString()}.html");

            blobClient.Upload(GenerateStreamFromString(apiModel.ScriptBody));
            apiModel.ScriptURL = blobClient.Uri.AbsoluteUri;
            return(new CreatedID {
                ID = _aviBL.AddScript(apiModel.ToDLModel()).ID
            });
        }
        public Uri StoragePost(IFormFile image)
        {
            BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);

            BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient("fotos-posts");

            if (containerClient == null)
            {
                blobServiceClient.CreateBlobContainer("fotos-posts");
            }

            BlobClient blobClient = containerClient.GetBlobClient(image.FileName);


            blobClient.UploadAsync(image.OpenReadStream());


            //try
            //{
            //    var fotoStream = image.OpenReadStream();

            //    await blobClient.UploadAsync(fotoStream, true);

            //    fotoStream.Close();
            //}
            //catch (Exception)
            //{
            //    throw;
            //}
            return(blobClient.Uri);
        }
Example #5
0
        /// <summary>
        /// Create a blob container that'll get deleted when it goes out of scope.
        /// </summary>
        /// <param name="containerName">
        /// The name of the container to create.
        /// </param>
        /// <param name="connectionString">
        /// Optional connection string; defaults to using development storage on the emulator.
        /// </param>
        private Deletable <BlobContainerClient> CreateBlobContainer(string containerName, string connectionString = null)
        {
            connectionString = string.IsNullOrEmpty(connectionString) ? DevelopmentConnectionString : connectionString;
            var blobService = new BlobServiceClient(connectionString);

            return(new Deletable <BlobContainerClient>(blobService.CreateBlobContainer(containerName).Value));
        }
        private static void CreateFileAndUploadtoAzureblob(List <Employee> employees, string blobConnString)
        {
            string filepath = @"C:\Users\anavard\Desktop\priyankatest\";
            string fileName = "employeerecord.txt";

            //create and write records to a text file
            using (System.IO.StreamWriter file =
                       new System.IO.StreamWriter(Path.Combine(filepath, fileName)))
            {
                foreach (Employee emp in employees)
                {
                    file.WriteLine($"Id: {emp.ID} Name: {emp.Name} Department {emp.Department} Salary: {emp.Salary} JoinDate {emp.JoinDate.Date}");
                }
            }

            //Upload to azure blob
            BlobServiceClient blobServiceClient = new BlobServiceClient(blobConnString);

            string containerName = $"employeerecordcontainer{Guid.NewGuid().ToString()}";

            BlobContainerClient containerClient = blobServiceClient.CreateBlobContainer(containerName);

            BlobClient blobClient = containerClient.GetBlobClient(fileName);

            using FileStream uploadFileStream = File.OpenRead(Path.Combine(filepath, fileName));
            blobClient.Upload(uploadFileStream, true);
            uploadFileStream.Close();
        }
        public BlobContext(IConfiguration configuration)
        {
            string connectionString = configuration.GetConnectionString("StorageData");
            string containerName    = configuration.GetSection("BlobContainerName").Value;

            if (string.IsNullOrWhiteSpace(connectionString))
            {
                throw new NullReferenceException("Não foi localizado o valor de conexão para o Storage.");
            }

            if (string.IsNullOrWhiteSpace(containerName))
            {
                throw new NullReferenceException("Não foi localizado o valor do nome do container.");
            }

            var blobContainerClient = new BlobServiceClient(connectionString);

            try
            {
                _blobContainerClient = blobContainerClient.CreateBlobContainer(containerName).Value;
            }
            catch
            {
                _blobContainerClient = blobContainerClient.GetBlobContainerClient(containerName);
            }
        }
        protected override void StoreContent(string path, string value)
        {
            var containerClient = _blobServiceClient.GetBlobContainerClient(_container);
            var containerExists = containerClient.Exists();

            if (!containerExists)
            {
                _blobServiceClient.CreateBlobContainer(_container, PublicAccessType.Blob);
            }

            var blockBlob      = containerClient.GetBlobClient(path);
            var blobHttpHeader = new BlobHttpHeaders
            {
                ContentType = MimeTypeMap.GetMimeType(Path.GetExtension(path))
            };

            // set browser caching on the media blobs
            if (PathHelper.IsCacheableFileType(path))
            {
                blobHttpHeader.CacheControl = $"public, max-age={H5PConsts.MediaCacheDurationSecs}";
            }

            var stream = new MemoryStream(Encoding.UTF8.GetBytes(value));

            blockBlob.Upload(stream, blobHttpHeader);
        }
Example #9
0
        /*Creates example container, client side encrypted blob, Key Vault key, and encryption scope for sample
         *
         * NOTE: This program requires the following to be stored in the App.Config file:
         * Subscription ID - subscriptionId
         * Resource Group Name - resourceGroup
         * Storage Account Name - storageAccount
         * Storage Account Connection String- connectionString
         *
         * Creates example objects using names from Constants.cs, which may be edited as needed
         */
        public static void SetupForExample(
            BlobServiceClient blobService,
            string containerName,
            string fileName,
            string encryptionScopeName,
            ClientSideEncryptionOptions clientSideOption,
            string keyVaultName,
            string keyVaultKeyName,
            TokenCredential credential
            )
        {
            //Create example Container and .txt file, upload .txt file as client side encrypted blob
            BlobContainerClient containerClient = blobService.CreateBlobContainer(containerName);
            //Create BlobClient with Client Side Encryption Options to upload client side encrypted data
            BlobClient blobClient = containerClient.GetBlobClient(fileName).WithClientSideEncryptionOptions(clientSideOption);

            //Upload blob with client side encryption
            blobClient.Upload(Path.Combine(Constants.SamplePath, Constants.BlobName));
            Console.WriteLine("Uploaded to Blob storage as blob: \n\t {0}\n", blobClient.Uri);

            //Create key and use created key to create encryption scope
            KeyVaultKey keyVaultKey = Setup.CreateKeyVaultKey(keyVaultName, keyVaultKeyName, credential);

            Setup.CreateEncryptionScopeCMK(encryptionScopeName, keyVaultKey.Id);
        }
        public void CreateBlobProvider_WhenContainerExists_NoExceptionshouldBeThrown()
        {
            var uniqueContainerName = Guid.NewGuid().ToString("N");

            // The container doesn't exist at the beginning
            var blobServiceClient = new BlobServiceClient(ConnectionString);

            var container = blobServiceClient.GetBlobContainerClient(uniqueContainerName);

            Assert.False(container.Exists());

            // create the container
            container = blobServiceClient.CreateBlobContainer(uniqueContainerName);
            Assert.True(container.Exists());

            // no exception should be thrown if the container exists
            _ = GetTestBlobProvider(ConnectionString, uniqueContainerName);

            container = blobServiceClient.GetBlobContainerClient(uniqueContainerName);
            Assert.True(container.Exists());

            // delete the created container
            blobServiceClient.DeleteBlobContainer(uniqueContainerName);
            container = blobServiceClient.GetBlobContainerClient(uniqueContainerName);
            Assert.False(container.Exists());
        }
        public WorkoutsStore()
        {
            _storageConnection = Environment.GetEnvironmentVariable(DeckOfCardsConnectionString);
            var blobServiceClient = new BlobServiceClient(_storageConnection);

            SafeMethod(() => blobServiceClient.CreateBlobContainer(DeckOfCardsWorkoutsContainer));
        }
        public Uri ArmazenarFotoDoPost(IFormFile foto)
        {
            BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);

            BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient("fotos-posts");

            if (containerClient == null)
            {
                blobServiceClient.CreateBlobContainer("fotos-posts");
            }

            BlobClient blobClient = containerClient.GetBlobClient(foto.FileName);

            try
            {
                var fotoStream = foto.OpenReadStream();
                blobClient.UploadAsync(fotoStream, true).Wait();
                fotoStream.Close();
            }
            catch (Exception)
            {
                throw;
            }

            return(blobClient.Uri);
        }
Example #13
0
        public static async Task <string> WriteBlob([ActivityTrigger] IDurableActivityContext writeBlobContext, ILogger log)
        {
            BlobContainerClient containerClient = null;
            var newMsg = writeBlobContext.GetInput <NewMessage>();

            //log.LogInformation($"Message: {JsonConvert.SerializeObject(newMsg)}");
            //log.LogInformation($"MessageId:{msgId}");

            // Create a BlobServiceClient object which will be used to create a container client
            BlobServiceClient blobServiceClient = new BlobServiceClient(Environment.GetEnvironmentVariable("AzureWebJobsStorage"));

            //Create a container if it does not exist
            string containerName = "durablefunctest";

            if (blobServiceClient.GetBlobContainers().Where(cont => cont.Name.ToLowerInvariant() == containerName).ToList().Count() > 0)
            {
                containerClient = blobServiceClient.GetBlobContainerClient(containerName);
            }
            else
            {
                // Create the container and return a container client object
                containerClient = blobServiceClient.CreateBlobContainer(containerName);
            }

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

            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(newMsg))))
            {
                await blobClient.UploadAsync(stream);
            }

            return(blobClient.Uri.AbsoluteUri);
        }
Example #14
0
 public bool CreateClientContainer(IContainerService clientContainer)
 {
     if (CheckIfContainerExists(clientContainer))
     {
         return(false);
     }
     _blobServiceClient.CreateBlobContainer(clientContainer.GetContainerName(), PublicAccessType.Blob);
     return(true);
 }
Example #15
0
        public static void CreateBlobContainerIfNotExists()
        {
            BlobServiceClient client = new BlobServiceClient(ConnectionString);

            if (client.GetBlobContainers(prefix: ContainerName).Any(container => container.Name.Equals(ContainerName)))
            {
                return;
            }
            client.CreateBlobContainer(ContainerName, PublicAccessType.BlobContainer);
        }
Example #16
0
        private BlobContainerClient GetOrCreateBlobContainer(string containerName)
        {
            var lowerContainerName = containerName.ToLower();
            var containerClient = _blobServiceClient.GetBlobContainerClient(lowerContainerName);
            if (!containerClient.Exists())
            {
                containerClient = _blobServiceClient.CreateBlobContainer(lowerContainerName);
            }

            return containerClient;
        }
Example #17
0
        public AzureFileStorage()
        {
            string connectionString = ConfigurationManager.AppSettings["AzureStorageConnectionString"];

            blobServiceClient = new BlobServiceClient(connectionString);
            containerClient   = blobServiceClient.GetBlobContainerClient(ContainerName);
            if (containerClient == null || !containerClient.Exists())
            {
                containerClient = blobServiceClient.CreateBlobContainer(ContainerName);
            }
        }
Example #18
0
        static void Main(string[] args)
        {
            try
            {
                string              connectionString  = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");
                BlobServiceClient   blobServiceClient = new BlobServiceClient(connectionString);
                BlobContainerClient containerClient   = blobServiceClient.CreateBlobContainer("carddeck");
                containerClient.SetAccessPolicy(PublicAccessType.Blob);

                int           numberOfCards = 0;
                DirectoryInfo dir           = new DirectoryInfo(@"Cards");
                foreach (FileInfo f in dir.GetFiles("*.*"))
                {
                    BlobClient blob = containerClient.GetBlobClient(f.Name);
                    using (var fileStream = System.IO.File.OpenRead(@"Cards\" + f.Name))
                    {
                        blob.Upload(fileStream);
                        Console.WriteLine($"Uploading: '{f.Name}' which " +
                                          $"is {fileStream.Length} bytes.");
                    }
                    numberOfCards++;
                }
                Console.WriteLine($"Uploaded {numberOfCards.ToString()} cards.");
                Console.WriteLine();

                numberOfCards = 0;
                foreach (BlobItem item in containerClient.GetBlobs())
                {
                    Console.WriteLine($"Card image url '{containerClient.Uri}/{item.Name}' with length " +
                                      $"of {item.Properties.ContentLength}");
                    numberOfCards++;
                }
                Console.WriteLine($"Listed {numberOfCards.ToString()} cards.");

                Console.WriteLine("If you want to delete the container and its contents enter: " +
                                  "'Yes' and the Enter key");
                var delete = Console.ReadLine();
                if (delete == "Yes")
                {
                    containerClient.Delete();
                    Console.WriteLine("Container deleted.");
                }
                Console.WriteLine("All done, press the Enter key to exit.");
                Console.ReadLine();
            }
            catch (RequestFailedException rfe)
            {
                Console.WriteLine($"RequestFailedException: {rfe.Message}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception: {ex.Message}");
            }
        }
 public Response <BlobContainerClient> CreateContainer(string containerName)
 {
     try
     {
         var creationResult = BlobServiceClient.CreateBlobContainer(containerName);
         RefreshContainerDetails();
         return(creationResult);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Example #20
0
        /// <summary>
        /// Create a named container.
        /// </summary>
        /// <remarks>Returns a created unique name derived from <paramref name="containerName"/> and returns it.</remarks>
        /// <param name="containerName">Container name.</param>
        /// <returns>An unique generated container name.</returns>
        public AzureContainer CreateContainer(
            string containerName)
        {
            if (string.IsNullOrWhiteSpace(containerName))
            {
                throw new ArgumentNullException(paramName: nameof(containerName), message: "Container name must not be null.");
            }

            var uniqueName = $"{containerName}_{Guid.NewGuid():N}";

            this[uniqueName] = new AzureContainer(serviceClient.CreateBlobContainer(containerName));

            return(this[uniqueName]);
        }
        /// <summary>
        /// Create the sprite settings.
        /// </summary>
        /// <param name="spriteFilename">The name of the sprite file that will be created or overwritten.</param>
        /// <param name="spriteUrl">The URL of the sprite file.</param>
        /// <param name="cssFilename">The name of the CSS file that will be created or overwritten.</param>
        /// <param name="connectionString"></param>
        /// <param name="cssContainerName"></param>
        /// <param name="spriteContainerName"></param>
        public AzureStorageSpriteSettings(string spriteFilename, string spriteUrl, string cssFilename, string connectionString, string cssContainerName, string spriteContainerName)
        {
            SpriteFilename      = spriteFilename;
            SpriteUrl           = spriteUrl;
            CssFilename         = cssFilename;
            ConnectionString    = connectionString;
            CssContainerName    = cssContainerName;
            SpriteContainerName = spriteContainerName;

            var blobServiceClient = new BlobServiceClient(ConnectionString);

            var cssBlobContainer = blobServiceClient.GetBlobContainers().FirstOrDefault(x => x.Name == CssContainerName);

            _cssBlobContainerClient = cssBlobContainer == null
                ? blobServiceClient.CreateBlobContainer(CssContainerName)
                : blobServiceClient.GetBlobContainerClient(CssContainerName);

            var spriteBlobContainer = blobServiceClient.GetBlobContainers().FirstOrDefault(x => x.Name == SpriteContainerName);

            _spriteBlobContainerClient = spriteBlobContainer == null
                ? blobServiceClient.CreateBlobContainer(SpriteContainerName)
                : blobServiceClient.GetBlobContainerClient(SpriteContainerName);
        }
Example #22
0
        static BlobContainerClient CreateContainer(string name)
        {
            // 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 = name + "dpor200demo01";

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

            return containerClient;
        }
Example #23
0
        public MainPage()
        {
            this.InitializeComponent();
            storageAccount     = CloudStorageAccount.Parse(connectionString);
            tableClient        = storageAccount.CreateCloudTableClient();
            _blobServiceClient = new BlobServiceClient(connectionString);

            var container = _blobServiceClient.GetBlobContainers().FirstOrDefault(c => c.Name == CONTAINER_NAME);

            if (container is null)
            {
                _blobServiceClient.CreateBlobContainer(CONTAINER_NAME);
            }
        }
Example #24
0
        public Dictionary <string, string> MakeNewContainer()
        {
            var blobServiceClient = new BlobServiceClient(Environment.GetEnvironmentVariable("CONNECT_STR"));
            var TestContainer     = "just_testing_this_out" + Guid.NewGuid().ToString();
            var containerClient   = blobServiceClient.CreateBlobContainer(TestContainer);
            var blobName          = PutDocumentInContainer(containerClient, TestContainer);

            var dict = new Dictionary <string, string>
            {
                { TestContainer, blobName }
            };

            return(dict);
        }
Example #25
0
 public StorageService(IConfiguration config, ILogger <StorageService> logger)
 {
     _client = new BlobServiceClient(config["StorageConnectionString"]);
     _logger = logger;
     // We can afford calling create here, because this service has big lifetime
     // TODO: Check CloudBlobContainer - it has createifnotexists
     try
     {
         _client.CreateBlobContainer(_containerName);
     }
     catch (Azure.RequestFailedException)
     {
         // Ignore that container already exists
     }
 }
        //Creates example container and client side encrypted blob for sample
        public static void SetupForExample(
            BlobServiceClient blobService,
            string containerName,
            string fileName,
            ClientSideEncryptionOptions clientSideOption)
        {
            //Create example Container and .txt file, upload .txt file as client side encrypted blob
            BlobContainerClient containerClient = blobService.CreateBlobContainer(containerName);
            //Create BlobClient with Client Side Encryption Options to upload client side encrypted data
            BlobClient blobClient = containerClient.GetBlobClient(fileName).WithClientSideEncryptionOptions(clientSideOption);

            //Upload blob with client side encryption
            blobClient.Upload(Path.Combine(Constants.SamplePath, Constants.BlobName));
            Console.WriteLine("Uploaded to Blob storage as blob: \n\t {0}\n", blobClient.Uri);
        }
Example #27
0
 public StorageService(IConfiguration config, ILogger <StorageService> logger)
 {
     _client = new BlobServiceClient(config["BLOB_STORAGE_CONNECTION"]);
     _logger = logger;
     // We can afford calling create here, because this service has big lifetime
     try
     {
         _client.CreateBlobContainer(_containerName);
     }
     catch (Azure.RequestFailedException)
     {
         // Ignore that container already exists
     }
     _containerClient = _client.GetBlobContainerClient(_containerName);
 }
Example #28
0
        public CreatedID Create(ScriptCreate apiModel)
        {
            foreach (SceneCreate sceneApiModel in apiModel.Scenes)
            {
                sceneApiModel.PilotID = apiModel.PilotID;
                _aviBL.AddScene(sceneApiModel.ToDLModel());
            }
            BlobContainerClient containerClient = _blobSC.CreateBlobContainer($"pilot{apiModel.PilotID}", Azure.Storage.Blobs.Models.PublicAccessType.BlobContainer);
            BlobClient          blobClient      = containerClient.GetBlobClient($"script{Guid.NewGuid().ToString()}.html");

            blobClient.Upload(GenerateStreamFromString(apiModel.ScriptBody));
            apiModel.ScriptURL = blobClient.Uri.AbsoluteUri;
            return(new CreatedID {
                ID = _aviBL.AddScript(apiModel.ToDLModel()).ID
            });
        }
Example #29
0
        public IActionResult Create([FromForm] FileCreate apiModel)
        {
            BlobContainerClient containerClient = _blobSC.GetBlobContainerClient($"pilot{apiModel.PilotID}");

            if (!containerClient.Exists())
            {
                containerClient = _blobSC.CreateBlobContainer($"pilot{apiModel.PilotID}", Azure.Storage.Blobs.Models.PublicAccessType.BlobContainer);
            }
            BlobClient blobClient = containerClient.GetBlobClient(apiModel.FileName);

            if (blobClient.Exists())
            {
                return(BadRequest(new { error = "File name already taken for this pilot" }));
            }
            blobClient.Upload(apiModel.File.OpenReadStream());
            apiModel.FileURL = blobClient.Uri.AbsoluteUri;
            return(Ok(FileMinimal.FromDLModel(_aviBL.AddFile(apiModel.ToDLModel()))));
        }
Example #30
0
        //-------------------------------------------------
        // Create root container
        //-------------------------------------------------
        private static void CreateRootContainer(BlobServiceClient blobServiceClient)
        {
            try
            {
                // Create the root container or handle the exception if it already exists
                BlobContainerClient container = blobServiceClient.CreateBlobContainer("$root");

                if (container.Exists())
                {
                    Console.WriteLine("Created root container.");
                }
            }
            catch (RequestFailedException e)
            {
                Console.WriteLine("HTTP error code {0}: {1}",
                                  e.Status, e.ErrorCode);
                Console.WriteLine(e.Message);
            }
        }