Beispiel #1
0
        static void Main(string[] args)
        {
            //CloudStorageAccount
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageAccount"));
            //CloudBlobClient
            CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
            //Container
            CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("azurecontainer3");

            //Blob
            cloudBlobContainer.CreateIfNotExists();

            SetMetadata(cloudBlobContainer);
            //set permission for container
            cloudBlobContainer.SetPermissions(new BlobContainerPermissions {
                PublicAccess = BlobContainerPublicAccessType.Blob
            });

            //get blob reference
            CloudBlockBlob blob = cloudBlobContainer.GetBlockBlobReference(@"toDownload/image1.jpeg");

            using (var fileStream = System.IO.File.OpenRead(@"C:\ToUpload\Pic1.jpeg"))
            {
                blob.UploadFromStream(fileStream);
            }

            //get blob reference
            CloudBlockBlob blob2 = cloudBlobContainer.GetBlockBlobReference(@"toDownload/image2.jpeg");

            using (var fileStream = System.IO.File.OpenRead(@"C:\ToUpload\Pic2.jpeg"))
            {
                blob2.UploadFromStream(fileStream);
            }
            //download blob
            using (var fileStream = System.IO.File.OpenWrite(@"C:\FromAzure\image1.jpeg"))
            {
                blob.DownloadToStream(fileStream);
            }
            using (var fileStream = System.IO.File.OpenWrite(@"C:\FromAzure\image2.jpeg"))
            {
                blob2.DownloadToStream(fileStream);
            }
            //get blob reference
            CloudBlockBlob blob3copy = cloudBlobContainer.GetBlockBlobReference(@"toDownload/image2copy.jpeg");
            var            cb        = new AsyncCallback(x => Console.WriteLine("blob copy completed!!"));

            blob3copy.BeginStartCopy(blob2, cb, null);

            var directory = cloudBlobContainer.GetDirectoryReference("toDownload");

            //list all blobs
            foreach (var item in directory.ListBlobs(false))
            {
                if (item.GetType() == typeof(CloudBlockBlob))
                {
                    CloudBlockBlob bBlob = (CloudBlockBlob)item;
                    Console.WriteLine(bBlob.Uri);
                }
            }
        }
Beispiel #2
0
        /// <summary>
        /// Moves all blobs from source to destination container
        /// </summary>
        /// <param name="sourceContainer">Source Container</param>
        /// <param name="currentBlobName"> Current Blob name to be retained</param>
        /// <param name="targetContainer">Target Container</param>
        /// <returns>boolean value</returns>
        public bool MoveBlobs(string sourceContainer, string currentBlobName, string targetContainer)
        {
            // Create the blob client.
            this.storageAccountTerrain = this.GetCloudBlobStorageAccount();
            CloudBlobClient blobClientSource = this.storageAccountTerrain.CreateCloudBlobClient();
            CloudBlobClient blobClientTarget = this.storageAccountTerrain.CreateCloudBlobClient();

            // Retrieve a reference to a container.
            CloudBlobContainer blobContainerFrom = blobClientSource.GetContainerReference(sourceContainer);
            CloudBlobContainer blobContainerTo   = blobClientTarget.GetContainerReference(targetContainer);

            IEnumerable <IListBlobItem> listBlob = blobContainerFrom.ListBlobs(null);

            foreach (var blobItem in listBlob)
            {
                CloudBlockBlob blockBlobSource = (CloudBlockBlob)blobItem;
                CloudBlockBlob blockBlob       = blobContainerTo.GetBlockBlobReference(blockBlobSource.Name);
                if (currentBlobName != blockBlobSource.Name)
                {
                    blockBlob.BeginStartCopy(blockBlobSource, null, null);
                    blockBlobSource.Delete();
                }
            }

            return(true);
        }
Beispiel #3
0
        private static void cloneCat(CloudBlobContainer blobContainer)
        {
            CloudBlockBlob block = blobContainer.GetBlockBlobReference("cat.jpg");

            if (block.Exists())
            {
                CloudBlockBlob blockCopy    = blobContainer.GetBlockBlobReference("cloned/cat.jpg");
                AsyncCallback  callbackCopy = new AsyncCallback(x => Console.WriteLine("Blob copy completed!"));

                blockCopy.BeginStartCopy(block, callbackCopy, null);
            }
            else
            {
                Console.WriteLine("Cat was not found!");
            }
        }
Beispiel #4
0
        static void CopyBlobAsync()
        {
            Console.WriteLine($"Starting Async Copy Blobs Snippet");
            Console.WriteLine($"Getting test.txt file blob");
            CloudBlockBlob originalBlob = blobContainer.GetBlockBlobReference(TEST_BLOCK_BLOB_NAME);

            Console.WriteLine($"Creating new block blob for copying into");
            CloudBlockBlob newBlob       = blobContainer.GetBlockBlobReference("CopiedBlob");
            var            asyncCallBack = new AsyncCallback(
                x => Console.WriteLine($"*** Async Blob copy completed!"));

            newBlob.BeginStartCopy(
                new Uri(originalBlob.Uri.AbsoluteUri),
                asyncCallBack,
                null);

            Console.WriteLine($"Finished Async Copy Blob Snippet\r\n");
        }
Beispiel #5
0
        static void Main(string[] args)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("StorageConnection"));

            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

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

            container.CreateIfNotExists(BlobContainerPublicAccessType.Blob);

            CloudBlockBlob blockBlob     = container.GetBlockBlobReference("img2.png");
            CloudBlockBlob blockBlobCopy = container.GetBlockBlobReference("png-images/img2.png");
            var            cb            = new AsyncCallback(x => Console.WriteLine("blob copy completed"));

            blockBlobCopy.BeginStartCopy(blockBlob.Uri, cb, null);

            Console.ReadKey();
        }
Beispiel #6
0
        static void AzureStorageBlobExamples()
        {
            // Getting configuration from the App.config file and get access to the CloudStorageAccount.
            // Azure access Key should is stored in the App.config
            String storageKeyValue = CloudConfigurationManager.GetSetting("AzureStorageAccount");

            // Just in case to check whether reading the correct value
            Console.WriteLine("Storage Account Key Used" + storageKeyValue);

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageKeyValue);

            // Getting the Azure Client
            CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();

            // Getting reference for the container
            CloudBlobContainer cloudContainer = cloudBlobClient.GetContainerReference("images");

            // Create the container (folder) if does not exists
            cloudContainer.CreateIfNotExists();

            // Get the reference for the Blob in Azure
            CloudBlockBlob blobCloud = cloudContainer.GetBlockBlobReference("photo.png");


            // Learning 1: Copy a file from local path in to Azure Blob storage

            //Open a local file and upload to the Azure
            using (var fileStream = System.IO.File.OpenRead(@"C:\Users\Administrator\Pictures\photo.jpg"))
            {
                blobCloud.UploadFromStream(fileStream);
                Console.WriteLine("File is uploaded to the cloud");
            }

            // Learning 2: Download a blob from Azure to the local host

            // Just copy a blob from cloud to a local file. Assume the same file which has been uploaded in the previous step
            blobCloud.DownloadToFile(@"C:\Users\Administrator\Pictures\photocopy.jpg", FileMode.CreateNew);

            // Learning 3: List all blob objects URI from a container

            //List all blobs in a container
            var blobs = cloudContainer.ListBlobs();

            foreach (var blob in blobs)
            {
                Console.Write(blob.Uri);
            }

            // Learning 4: List properties of a continer (Folder) and listing metadata of a container

            cloudContainer.FetchAttributes();
            Console.WriteLine(cloudContainer.Properties.LastModified);
            Console.WriteLine(cloudContainer.Properties.ETag);
            var metaData = cloudContainer.Metadata;

            foreach (var metaDataItem in metaData)
            {
                Console.Write("Key " + metaDataItem.Key + " & ");
                Console.WriteLine("Value" + metaDataItem.Value);
            }

            // Learning 5: Setting metaData for a container

            // Method 1
            cloudContainer.Metadata.Add("SampleKey", "SampleValue");
            // Method 2
            cloudContainer.Metadata["SecondSample"] = "Second Value";

            // Dont ask me why FetchAttributes() and SetMetadata() ! why not SetAttributes() or GetMetaData? Microsoft Way!
            cloudContainer.SetMetadata();


            // Learning 6: Setting permission for a container
            BlobContainerPermissions permissions = cloudContainer.GetPermissions();

            Console.WriteLine("Container permission " + permissions.PublicAccess.ToString());
            foreach (var sharedAccessPolicy in permissions.SharedAccessPolicies)
            {
                Console.WriteLine(sharedAccessPolicy.Key.ToString() + " = " + sharedAccessPolicy.Value.ToString());
            }
            // In order to as per the parent container
            permissions.PublicAccess = BlobContainerPublicAccessType.Container;
            // In order to remove the public access
            permissions.PublicAccess = BlobContainerPublicAccessType.Off;
            //Finally set the permission
            cloudContainer.SetPermissions(permissions);



            // Learning 7: Azure copy from one blob to another

            // Create a new Block Blog Reference
            CloudBlockBlob copyBlob = cloudContainer.GetBlockBlobReference("photo-copy.jpg");

            // Copy the original - blobCloud to the copyBlob
            copyBlob.StartCopy(new Uri(blobCloud.Uri.AbsoluteUri));


            // Learning 8: Copy all blobs from one container to another
            CloudBlobContainer sourceContainer = cloudContainer;
            CloudBlobContainer targetContainer = cloudBlobClient.GetContainerReference("newimages");

            targetContainer.CreateIfNotExists();
            foreach (var blob in sourceContainer.ListBlobs())
            {
                var sourceBlob = blob as CloudBlob;
                Console.WriteLine("Source Blob " + sourceBlob.Name);
                CloudBlockBlob newBlob = targetContainer.GetBlockBlobReference(sourceBlob.Name);
                newBlob.StartCopy(new Uri(blob.Uri.AbsoluteUri));
            }


            // Learning 9: Rename the blob
            CloudBlockBlob sourceBlockBlob = cloudContainer.GetBlockBlobReference("photo-copy.jpg");
            CloudBlockBlob targetBlockBlob = cloudContainer.GetBlockBlobReference("copy-photo.jpg");

            targetBlockBlob.StartCopy(new Uri(sourceBlockBlob.Uri.AbsoluteUri));
            while (targetBlockBlob.CopyState.Status == CopyStatus.Pending)
            {
                // Sleep for 3 seconds
                System.Threading.Thread.Sleep(2000);
            }
            sourceBlockBlob.Delete();


            // Learning 10: Appending to a blob
            DateTime           date         = DateTime.Today;
            CloudBlobContainer logContainer = cloudBlobClient.GetContainerReference("logs");
            CloudAppendBlob    logBlog      = logContainer.GetAppendBlobReference(string.Format("{0}{1}", date.ToString("yyyyMMdd"), ".log"));

            logContainer.CreateIfNotExists();

            // If the append blog does not exists, create one
            if (!logBlog.Exists())
            {
                logBlog.CreateOrReplace();
            }

            // AppendText
            logBlog.AppendText(string.Format("{0} : Azure is rocking in the cloud space at ", date.ToString("HH:MM:ss")));
            // Similar to the AppendText, there are
            // logBlog.AppendBlock
            // logBlog.AppendFromByteArray
            // logBlog.AppendFromFile
            // logBlog.AppendFromStream

            // Finally display the content of the log file.
            Console.WriteLine(logBlog.DownloadText());

            // Learning 11: Multiple Chunk of file upload to Azure
            AzureStorageReference.Program.uploadLargeFiles(cloudBlobClient, @"C:\Users\Administrator\Pictures");


            //Learning 12: Upload using Async

            AsyncCallback  callBack  = new AsyncCallback(x => Console.WriteLine("Copy Async Completed"));
            CloudBlockBlob copyAsync = cloudContainer.GetBlockBlobReference("newphoto.png");

            copyAsync.BeginStartCopy(blobCloud, callBack, null);

            Console.WriteLine("Press any key to continue");
            Console.ReadKey();
        }