Beispiel #1
0
        public void CopyFromToRestoreSnapshot(BlobContext context, string containerName, string blobName)
        {
            string oldText = "Old stuff";
            string newText = "New stuff";

            StorageCredentials  accountAndKey = new StorageCredentials(context.Account, context.Key);
            CloudStorageAccount account       = new CloudStorageAccount(accountAndKey, false);
            CloudBlobClient     blobClient    = new CloudBlobClient(new Uri(context.Address), account.Credentials);
            CloudBlobContainer  container     = blobClient.GetContainerReference(containerName);
            CloudBlockBlob      blob          = container.GetBlockBlobReference(blobName);

            BlobTestBase.UploadText(blob, oldText, Encoding.UTF8);
            CloudBlockBlob snapshot = blob.CreateSnapshot();

            Assert.IsNotNull(snapshot.SnapshotTime);
            BlobTestBase.UploadText(blob, newText, Encoding.UTF8);

            Uri sourceUri = new Uri(snapshot.Uri.AbsoluteUri + "?snapshot=" + BlobRequest.ConvertDateTimeToSnapshotString(snapshot.SnapshotTime.Value));
            OperationContext opContext = new OperationContext();
            HttpWebRequest   request   = BlobHttpWebRequestFactory.CopyFrom(blob.Uri, 30, sourceUri, null, null, opContext);

            Assert.IsTrue(request != null, "Failed to create HttpWebRequest");
            BlobTests.SignRequest(request, context);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Assert.AreEqual <HttpStatusCode>(response.StatusCode, HttpStatusCode.Accepted);

            string text = BlobTestBase.DownloadText(blob, Encoding.UTF8);

            Assert.AreEqual <string>(text, oldText);

            blob.Delete(DeleteSnapshotsOption.IncludeSnapshots, null, null);
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            const string        fileToUpload   = "input.txt";
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=azstorageaccountlearn;AccountKey=AWU6npF4KDZm2cL29Rxpztz3KEaR9Hnc9CqysUzBkNdN84JyStD9UfQzt76pKUXeBw/gGBlDlbjHk8jsVaht4w==;EndpointSuffix=core.windows.net");
            CloudBlobClient     blobClient     = storageAccount.CreateCloudBlobClient();

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

            try
            {
                container.CreateIfNotExists();
            }
            catch (Exception exe)
            {
            }

            CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileToUpload);

            blockBlob.UploadFromFile(fileToUpload);

            blockBlob.Metadata["Author"]   = "Client Code";
            blockBlob.Metadata["Priority"] = "High";

            blockBlob.SetMetadata();
            blockBlob.CreateSnapshot();
            blockBlob.DownloadToFile(string.Format("./CopyOf{0}", fileToUpload), System.IO.FileMode.Create);

            blockBlob.Delete();
        }
        /// <summary>
        /// Create a snapshot of a block blob. A snapshot is a copy of the blob for the moment it is created. It
        /// is a read only object.
        /// </summary>
        /// <returns>Return true on success, false if unable to create, throw exception on error</returns>
        public bool SnapshotBlockBlob(string containerName, string blobName, Stream stream)
        {
            try
            {
                CloudBlobContainer container = _blobClient.GetContainerReference(containerName);
                CloudBlockBlob     blob      = container.GetBlockBlobReference(blobName);
                CloudBlockBlob     cloudBlob = blob.CreateSnapshot();
                cloudBlob.DownloadToStream(stream);

                return(true);
            }
            catch (StorageException ex)
            {
                if (ex.RequestInformation.HttpStatusCode == 404)
                {
                    return(false);
                }

                throw;
            }
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            CloudStorageAccount storageAccount = EncryptionShared.Utility.CreateStorageAccountFromConnectionString();
            CloudBlobClient     client         = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer  container      = client.GetContainerReference(CloudConfigurationManager.GetSetting("Container"));

            try
            {
                container.CreateIfNotExists();

                Console.WriteLine("Blob encryption sample");
                int    size   = 5 * 1024 * 1024;
                byte[] buffer = new byte[size];
                Random rand   = new Random();
                rand.NextBytes(buffer);
                CloudBlockBlob blob = container.GetBlockBlobReference("blockblob");
                blob.CreateSnapshot();
                // Create the IKey used for encryption.
                RsaKey key = new RsaKey("private:key1");

                // Create the encryption policy to be used for upload.
                BlobEncryptionPolicy uploadPolicy = new BlobEncryptionPolicy(key, null);

                // Set the encryption policy on the request options.
                BlobRequestOptions uploadOptions = new BlobRequestOptions()
                {
                    EncryptionPolicy = uploadPolicy
                };

                Console.WriteLine("Uploading the encrypted blob.");

                // Upload the encrypted contents to the blob.
                using (MemoryStream stream = new MemoryStream(buffer))
                {
                    blob.UploadFromStream(stream, size, null, uploadOptions, null);
                }

                // Download the encrypted blob.
                // For downloads, a resolver can be set up that will help pick the key based on the key id.
                LocalResolver resolver = new LocalResolver();
                resolver.Add(key);

                BlobEncryptionPolicy downloadPolicy = new BlobEncryptionPolicy(null, resolver);

                // Set the decryption policy on the request options.
                BlobRequestOptions downloadOptions = new BlobRequestOptions()
                {
                    EncryptionPolicy = downloadPolicy
                };

                Console.WriteLine("Downloading the encrypted blob.");

                // Download and decrypt the encrypted contents from the blob.
                using (MemoryStream outputStream = new MemoryStream())
                {
                    blob.DownloadToStream(outputStream, null, downloadOptions, null);
                }
                Console.WriteLine("Press enter key to exit");
                //Console.ReadLine();
                #region folder
                //folder creation
                CloudBlobDirectory directory = container.GetDirectoryReference("directoryName");
                CloudBlockBlob     blockblob = directory.GetBlockBlobReference("sample");
                blockblob.UploadFromFile(@"C:\Users\RINGEL\Downloads\Angular.txt", FileMode.Open);
                //listof Directories &files
                DirectoryFile(container);
                #endregion folder

                #region  sas
                var sasPolicy = new SharedAccessBlobPolicy()
                {
                    Permissions            = SharedAccessBlobPermissions.Read,
                    SharedAccessStartTime  = DateTime.Now.AddMinutes(-10),
                    SharedAccessExpiryTime = DateTime.Now.AddMinutes(30)
                };
                var    sasTokenforcontainer = container.GetSharedAccessSignature(sasPolicy);
                string sasTokenforblob      = blob.GetSharedAccessSignature(sasPolicy);
                #endregion sas
            }
            finally
            {
                container.DeleteIfExists();
            }
        }
Beispiel #5
0
        public static void Run()
        {
            #region Obtain a client from the connection string

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
            CloudBlobClient     blobClient     = storageAccount.CreateCloudBlobClient();
            Console.WriteLine("Parsed connection string and created blob client.");

            #endregion

            #region Obtain reference to images container

            CloudBlobContainer docContainer = blobClient.GetContainerReference("docs");
            Console.WriteLine("Obtained reference to docs containers.");

            #endregion

            #region Create a snapshot

            CloudBlockBlob blockBlob     = docContainer.GetBlockBlobReference(@"WhatIsBlobStorage.txt");
            CloudBlockBlob blobSnapshot1 = blockBlob.CreateSnapshot();
            var            snapshotTime  = blobSnapshot1.SnapshotTime.Value;
            Console.WriteLine("Created snapshot '{0}' for WhatIsBlobStorage.txt in docs container.", snapshotTime.ToString("o"));

            Thread.Sleep(TimeSpan.FromMilliseconds(100));
            CloudBlockBlob blobSnapshot2 = blockBlob.CreateSnapshot();
            Thread.Sleep(TimeSpan.FromMilliseconds(100));
            CloudBlockBlob blobSnapshot3 = blockBlob.CreateSnapshot();

            #endregion

            #region List snapshots

            Console.WriteLine("\nListing snapshots");
            var snapshots = docContainer
                            .ListBlobs(useFlatBlobListing: true, blobListingDetails: BlobListingDetails.Snapshots)
                            .Where(blob => ((CloudBlockBlob)blob).SnapshotTime.HasValue);

            foreach (var snapshot in snapshots)
            {
                CloudBlockBlob blob = new CloudBlockBlob(blockBlob.Uri, ((CloudBlockBlob)snapshot).SnapshotTime, blobClient.Credentials);
                blob.FetchAttributes();
                Console.WriteLine(" {0} - {1}", blob.Uri.AbsoluteUri, blob.SnapshotTime);
            }

            #endregion

            #region Modify original blob

            using (var stringStream = new MemoryStream(Encoding.UTF8.GetBytes(@"Replace contents with this random string")))
            {
                blockBlob.UploadFromStream(stringStream);
            }
            Console.WriteLine("\nReplaced contents of WhatIsBlobStorage.txt with random string.");
            Console.WriteLine("Press any key to restore from snapshot ...");
            Console.ReadLine();

            #endregion

            #region Restore from snapshot

            CloudBlockBlob backupSnapshot = new CloudBlockBlob(blockBlob.Uri, snapshotTime, blobClient.Credentials);
            blockBlob.StartCopyFromBlob(backupSnapshot);
            Console.WriteLine("Restored contents of WhatIsBlobStorage.txt from original snapshot.");

            #endregion
        }