コード例 #1
0
        public async void FileWriting(string message, CloudBlobContainer container)
        {
            //write exception to cloud storage
            string localPath     = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            string localFileName = "Exceptions" + Guid.NewGuid().ToString() + ".txt";
            string sourceFile    = Path.Combine(localPath, localFileName);

            File.WriteAllText(sourceFile, DateTime.Now.ToString() + " " + message);
            //write to cloud
            CloudBlockBlob cloudBlockBlob = container.GetBlockBlobReference(localFileName);
            await cloudBlockBlob.UploadFromFileAsync(sourceFile);
        }
コード例 #2
0
        public void StoreInContainer(CloudStorageAccount account, string message)
        {
            //Create the CloudBlobClient that represents the
            // Blob storage endpoint for the storage account

            // Create a container called 'quickstartblobs' and
            // append a GUID value to it to make the name unique.
            Uri uri = new Uri("https://sportsappexceptions.blob.core.windows.net/sportsexceptions");
            CloudBlobContainer cloudBlobContainer = new CloudBlobContainer(uri);

            //Write to the new cloud container
            FileWriting(message, cloudBlobContainer);
        }
コード例 #3
0
ファイル: AzureBlobHelper.cs プロジェクト: GreenPotato1/o2
        public static async Task <string> UploadFileToStorage(Stream fileStream, string fileName, TypeTable typeTable)
        {
            try
            {
                // Create storagecredentials object by reading the values from the configuration (appsettings.json)
                StorageCredentials storageCredentials = new StorageCredentials(accountName: CloudStorage.Instance.GetAccountCloudStorage(typeTable).AccountName,
                                                                               CloudStorage.Instance.GetAccountCloudStorage(typeTable).AccountKey);

                // Create cloudstorage account by passing the storagecredentials
                CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true);

                // Create the blob client.
                CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

                // Get reference to the blob container by passing the name by reading the value from the configuration (appsettings.json)
                CloudBlobContainer container = blobClient.GetContainerReference(CloudStorage.Instance.GetAccountCloudStorage(typeTable).Container);
                container.CreateIfNotExists();

                // Get the reference to the block blob from the container
                CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);
                string         ext       = System.IO.Path.GetExtension(fileName).ToLower();
                blockBlob.Properties.ContentType = MimeTypes.GetMimeType(ext);
                // Upload the file
                await blockBlob.UploadFromStreamAsync(fileStream);

                string sas = blockBlob.GetSharedAccessSignature(
                    new SharedAccessBlobPolicy()
                {
                    Permissions            = SharedAccessBlobPermissions.Read,
                    SharedAccessStartTime  = DateTime.Now.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTime.Now.AddYears(999)
                });

                var url = blockBlob.Uri + sas;

                return(url);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
コード例 #4
0
ファイル: AzureBlobHelper.cs プロジェクト: GreenPotato1/o2
        public static void ClearStorage(TypeTable typeTable)
        {
            // Create storagecredentials object by reading the values from the configuration (appsettings.json)
            StorageCredentials storageCredentials = new StorageCredentials(accountName: CloudStorage.Instance.GetAccountCloudStorage(typeTable).AccountName,
                                                                           CloudStorage.Instance.GetAccountCloudStorage(typeTable).AccountKey);

            // Create cloudstorage account by passing the storagecredentials
            CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true);

            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Get reference to the blob container by passing the name by reading the value from the configuration (appsettings.json)
            CloudBlobContainer container = blobClient.GetContainerReference(CloudStorage.Instance.GetAccountCloudStorage(typeTable).Container);

            if (container.Exists())
            {
                container.Delete();
            }
        }
コード例 #5
0
        public void CloudBlobSoftDeleteSnapshotTask()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                //Enables a delete retention policy on the blob with 1 day of default retention days
                container.ServiceClient.EnableSoftDelete();
                container.Create();

                // Upload some data to the blob.
                MemoryStream    originalData = new MemoryStream(GetRandomBuffer(1024));
                CloudAppendBlob appendBlob   = container.GetAppendBlobReference(BlobName);
                appendBlob.UploadFromStream(originalData);

                CloudBlob blob = container.GetBlobReference(BlobName);

                //create snapshot via api
                CloudBlob snapshot = blob.Snapshot();
                //create snapshot via write protection
                appendBlob.UploadFromStream(originalData);

                //we should have 2 snapshots 1 regular and 1 deleted: there is no way to get only the deleted snapshots but the below listing will get both snapshot types
                int blobCount            = 0;
                int deletedSnapshotCount = 0;
                int snapShotCount        = 0;
                BlobContinuationToken ct = null;

                do
                {
                    Task <BlobResultSegment> resultSegments = container.ListBlobsSegmentedAsync
                                                                  (null, true, BlobListingDetails.Snapshots | BlobListingDetails.Deleted, null, ct, null, null);
                    List <IListBlobItem> blobs = resultSegments.Result
                                                 .Results
                                                 .ToList();
                    ct = resultSegments.Result.ContinuationToken;

                    foreach (IListBlobItem item in blobs)
                    {
                        CloudAppendBlob blobItem = (CloudAppendBlob)item;
                        Assert.AreEqual(blobItem.Name, BlobName);
                        if (blobItem.IsSnapshot)
                        {
                            snapShotCount++;
                        }
                        if (blobItem.IsDeleted)
                        {
                            Assert.IsNotNull(blobItem.Properties.DeletedTime);
                            Assert.AreEqual(blobItem.Properties.RemainingDaysBeforePermanentDelete, 0);
                            deletedSnapshotCount++;
                        }
                        blobCount++;
                    }
                } while (ct != null);

                Assert.AreEqual(3, blobCount);
                Assert.AreEqual(deletedSnapshotCount, 1);
                Assert.AreEqual(snapShotCount, 2);

                blobCount = 0;
                ct        = null;
                do
                {
                    foreach (IListBlobItem item in container.ListBlobsSegmentedAsync
                                 (null, true, BlobListingDetails.Snapshots, null, ct, null, null)
                             .Result
                             .Results
                             .ToList())
                    {
                        CloudAppendBlob blobItem = (CloudAppendBlob)item;
                        Assert.AreEqual(blobItem.Name, BlobName);
                        Assert.IsFalse(blobItem.IsDeleted);
                        Assert.IsNull(blobItem.Properties.DeletedTime);
                        Assert.IsNull(blobItem.Properties.RemainingDaysBeforePermanentDelete);
                        blobCount++;
                    }
                } while (ct != null);

                Assert.AreEqual(blobCount, 2);

                //Delete Blob and snapshots
                blob.Delete(DeleteSnapshotsOption.IncludeSnapshots);
                Assert.IsFalse(blob.Exists());
                Assert.IsFalse(snapshot.Exists());

                blobCount = 0;
                ct        = null;
                do
                {
                    foreach (IListBlobItem item in container.ListBlobsSegmentedAsync
                                 (null, true, BlobListingDetails.All, null, ct, null, null)
                             .Result
                             .Results
                             .ToList())
                    {
                        CloudAppendBlob blobItem = (CloudAppendBlob)item;
                        Assert.AreEqual(blobItem.Name, BlobName);
                        Assert.IsTrue(blobItem.IsDeleted);
                        Assert.IsNotNull(blobItem.Properties.DeletedTime);
                        Assert.AreEqual(blobItem.Properties.RemainingDaysBeforePermanentDelete, 0);
                        blobCount++;
                    }
                }while(ct != null);

                Assert.AreEqual(blobCount, 3);

                blob.Undelete();

                blob.FetchAttributes();
                Assert.IsFalse(blob.IsDeleted);
                Assert.IsNull(blob.Properties.DeletedTime);
                Assert.IsNull(blob.Properties.RemainingDaysBeforePermanentDelete);

                blobCount = 0;
                ct        = null;
                do
                {
                    foreach (IListBlobItem item in container.ListBlobsSegmentedAsync
                                 (null, true, BlobListingDetails.All, null, ct, null, null)
                             .Result
                             .Results
                             .ToList())
                    {
                        CloudAppendBlob blobItem = (CloudAppendBlob)item;
                        Assert.AreEqual(blobItem.Name, BlobName);
                        Assert.IsFalse(blobItem.IsDeleted);
                        Assert.IsNull(blobItem.Properties.DeletedTime);
                        Assert.IsNull(blobItem.Properties.RemainingDaysBeforePermanentDelete);
                        blobCount++;
                    }
                }while(ct != null);

                Assert.AreEqual(blobCount, 3);
            }
            finally
            {
                container.ServiceClient.DisableSoftDelete();
                container.DeleteIfExists();
            }
        }
コード例 #6
0
        public void CloudBlobSoftDeleteNoSnapshotAPM()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                //Enables a delete retention policy on the blob with 1 day of default retention days
                container.ServiceClient.EnableSoftDelete();
                container.Create();

                // Upload some data to the blob.
                MemoryStream    originalData = new MemoryStream(GetRandomBuffer(1024));
                CloudAppendBlob appendBlob   = container.GetAppendBlobReference(BlobName);
                appendBlob.CreateOrReplace();
                appendBlob.AppendBlock(originalData, null);


                CloudBlob blob = container.GetBlobReference(BlobName);
                Assert.IsFalse(blob.IsDeleted);

                IAsyncResult result;
                using (AutoResetEvent waitHandle = new AutoResetEvent(false))
                {
                    result = blob.BeginDelete(DeleteSnapshotsOption.None, null, null, null, ar => waitHandle.Set(), null);
                    waitHandle.WaitOne();
                    blob.EndDelete(result);
                }

                Assert.IsFalse(blob.Exists());

                int blobCount = 0;
                foreach (IListBlobItem item in container.ListBlobs(null, true, BlobListingDetails.All))
                {
                    CloudAppendBlob blobItem = (CloudAppendBlob)item;
                    Assert.AreEqual(blobItem.Name, BlobName);
                    Assert.IsTrue(blobItem.IsDeleted);
                    Assert.IsNotNull(blobItem.Properties.DeletedTime);
                    Assert.AreEqual(blobItem.Properties.RemainingDaysBeforePermanentDelete, 0);
                    blobCount++;
                }

                Assert.AreEqual(1, blobCount);

                using (AutoResetEvent waitHandle = new AutoResetEvent(false))
                {
                    result = blob.BeginUndelete(ar => waitHandle.Set(), null);
                    waitHandle.WaitOne();
                    blob.EndUndelete(result);
                }

                blob.FetchAttributes();
                Assert.IsFalse(blob.IsDeleted);
                Assert.IsNull(blob.Properties.DeletedTime);
                Assert.IsNull(blob.Properties.RemainingDaysBeforePermanentDelete);

                blobCount = 0;
                foreach (IListBlobItem item in container.ListBlobs(null, true, BlobListingDetails.All))
                {
                    CloudAppendBlob blobItem = (CloudAppendBlob)item;
                    Assert.AreEqual(blobItem.Name, BlobName);
                    Assert.IsFalse(blobItem.IsDeleted);
                    Assert.IsNull(blobItem.Properties.DeletedTime);
                    Assert.IsNull(blobItem.Properties.RemainingDaysBeforePermanentDelete);
                    blobCount++;
                }

                Assert.AreEqual(blobCount, 1);
            }
            finally
            {
                container.ServiceClient.DisableSoftDelete();
                container.DeleteIfExists();
            }
        }
コード例 #7
0
        public void CloudBlobSoftDeleteNoSnapshotTask()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                //Enables a delete retention policy on the blob with 1 day of default retention days
                container.ServiceClient.EnableSoftDelete();
                container.CreateAsync().Wait();

                // Upload some data to the blob.
                MemoryStream    originalData = new MemoryStream(GetRandomBuffer(1024));
                CloudAppendBlob appendBlob   = container.GetAppendBlobReference(BlobName);
                appendBlob.CreateOrReplaceAsync().Wait();
                appendBlob.AppendBlockAsync(originalData, null).Wait();


                CloudBlob blob = container.GetBlobReference(BlobName);
                Assert.IsTrue(blob.ExistsAsync().Result);
                Assert.IsFalse(blob.IsDeleted);

                blob.DeleteAsync().Wait();
                Assert.IsFalse(blob.ExistsAsync().Result);

                int blobCount            = 0;
                BlobContinuationToken ct = null;
                do
                {
                    foreach (IListBlobItem item in container.ListBlobsSegmentedAsync
                                 (null, true, BlobListingDetails.All, null, ct, null, null)
                             .Result
                             .Results
                             .ToList())
                    {
                        CloudAppendBlob blobItem = (CloudAppendBlob)item;
                        Assert.AreEqual(blobItem.Name, BlobName);
                        Assert.IsTrue(blobItem.IsDeleted);
                        Assert.IsNotNull(blobItem.Properties.DeletedTime);
                        Assert.AreEqual(blobItem.Properties.RemainingDaysBeforePermanentDelete, 0);
                        blobCount++;
                    }
                } while (ct != null);

                Assert.AreEqual(blobCount, 1);

                blob.UndeleteAsync().Wait();

                blob.FetchAttributes();
                Assert.IsFalse(blob.IsDeleted);
                Assert.IsNull(blob.Properties.DeletedTime);
                Assert.IsNull(blob.Properties.RemainingDaysBeforePermanentDelete);

                blobCount = 0;
                ct        = null;
                do
                {
                    foreach (IListBlobItem item in container.ListBlobsSegmentedAsync
                                 (null, true, BlobListingDetails.All, null, ct, null, null)
                             .Result
                             .Results
                             .ToList())
                    {
                        CloudAppendBlob blobItem = (CloudAppendBlob)item;
                        Assert.AreEqual(blobItem.Name, BlobName);
                        Assert.IsFalse(blobItem.IsDeleted);
                        Assert.IsNull(blobItem.Properties.DeletedTime);
                        Assert.IsNull(blobItem.Properties.RemainingDaysBeforePermanentDelete);
                        blobCount++;
                    }
                } while (ct != null);
                Assert.AreEqual(blobCount, 1);
            }
            finally
            {
                container.ServiceClient.DisableSoftDelete();
                container.DeleteIfExists();
            }
        }
コード例 #8
0
        public void CloudBlobSoftDeleteNoSnapshot()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                //Enables a delete retention policy on the blob with 1 day of default retention days
                container.ServiceClient.EnableSoftDelete();
                Shared.Protocol.ServiceProperties props = container.ServiceClient.GetServiceProperties();
                container.Create();
                // Upload some data to the blob.
                MemoryStream    originalData = new MemoryStream(GetRandomBuffer(1024));
                CloudAppendBlob appendBlob   = container.GetAppendBlobReference(BlobName);
                appendBlob.CreateOrReplace();
                appendBlob.AppendBlock(originalData, null);


                CloudBlob blob = container.GetBlobReference(BlobName);

                Assert.IsTrue(blob.Exists());
                Assert.IsFalse(blob.IsDeleted);

                blob.Delete();
                Assert.IsFalse(blob.Exists());

                int blobCount = 0;
                foreach (IListBlobItem item in container.ListBlobs(null, true, BlobListingDetails.Snapshots | BlobListingDetails.Deleted))
                {
                    CloudAppendBlob blobItem = (CloudAppendBlob)item;
                    Assert.AreEqual(blobItem.Name, BlobName);
                    Assert.IsTrue(blobItem.IsDeleted);
                    Assert.IsNotNull(blobItem.Properties.DeletedTime);
                    Assert.AreEqual(blobItem.Properties.RemainingDaysBeforePermanentDelete, 0);
                    blobCount++;
                }

                Assert.AreEqual(blobCount, 1);

                blob.Undelete();

                blob.FetchAttributes();
                Assert.IsFalse(blob.IsDeleted);
                Assert.IsNull(blob.Properties.DeletedTime);
                Assert.IsNull(blob.Properties.RemainingDaysBeforePermanentDelete);

                blobCount = 0;
                foreach (IListBlobItem item in container.ListBlobs(null, true, BlobListingDetails.All))
                {
                    CloudAppendBlob blobItem = (CloudAppendBlob)item;
                    Assert.AreEqual(blobItem.Name, BlobName);
                    Assert.IsFalse(blobItem.IsDeleted);
                    Assert.IsNull(blobItem.Properties.DeletedTime);
                    Assert.IsNull(blobItem.Properties.RemainingDaysBeforePermanentDelete);
                    blobCount++;
                }

                Assert.AreEqual(blobCount, 1);
            }
            finally
            {
                container.ServiceClient.DisableSoftDelete();
                container.DeleteIfExists();
            }
        }
コード例 #9
0
        public void CloudBlobSnapshot()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                container.Create();

                // Upload some data to the blob.
                MemoryStream    originalData = new MemoryStream(GetRandomBuffer(1024));
                CloudAppendBlob appendBlob   = container.GetAppendBlobReference(BlobName);
                appendBlob.CreateOrReplace();
                appendBlob.AppendBlock(originalData, null);

                CloudBlob blob = container.GetBlobReference(BlobName);
                blob.FetchAttributes();
                Assert.IsFalse(blob.IsSnapshot);
                Assert.IsNull(blob.SnapshotTime, "Root blob has SnapshotTime set");
                Assert.IsFalse(blob.SnapshotQualifiedUri.Query.Contains("snapshot"));
                Assert.AreEqual(blob.Uri, blob.SnapshotQualifiedUri);

                CloudBlob snapshot1 = blob.Snapshot();
                Assert.AreEqual(blob.Properties.ETag, snapshot1.Properties.ETag);
                Assert.AreEqual(blob.Properties.LastModified, snapshot1.Properties.LastModified);
                Assert.IsTrue(snapshot1.IsSnapshot);
                Assert.IsNotNull(snapshot1.SnapshotTime, "Snapshot does not have SnapshotTime set");
                Assert.AreEqual(blob.Uri, snapshot1.Uri);
                Assert.AreNotEqual(blob.SnapshotQualifiedUri, snapshot1.SnapshotQualifiedUri);
                Assert.AreNotEqual(snapshot1.Uri, snapshot1.SnapshotQualifiedUri);
                Assert.IsTrue(snapshot1.SnapshotQualifiedUri.Query.Contains("snapshot"));

                CloudBlob snapshot2 = blob.Snapshot();
                Assert.IsTrue(snapshot2.SnapshotTime.Value > snapshot1.SnapshotTime.Value);

                snapshot1.FetchAttributes();
                snapshot2.FetchAttributes();
                blob.FetchAttributes();
                AssertAreEqual(snapshot1.Properties, blob.Properties, false);

                CloudBlob snapshot1Clone = new CloudBlob(new Uri(blob.Uri + "?snapshot=" + snapshot1.SnapshotTime.Value.ToString("O")), blob.ServiceClient.Credentials);
                Assert.IsNotNull(snapshot1Clone.SnapshotTime, "Snapshot clone does not have SnapshotTime set");
                Assert.AreEqual(snapshot1.SnapshotTime.Value, snapshot1Clone.SnapshotTime.Value);
                snapshot1Clone.FetchAttributes();
                AssertAreEqual(snapshot1.Properties, snapshot1Clone.Properties, false);

                // The query parser should not be case sensitive in detecting a snapshot in the query string
                CloudBlob snapshotParseVerifier = new CloudBlob(new Uri(blob.Uri + "?sNapshOt=" + snapshot1.SnapshotTime.Value.ToString("O")), blob.ServiceClient.Credentials);
                Assert.IsNotNull(snapshotParseVerifier.SnapshotTime, "Snapshot parse verifier did not successfully detect the snapshot time");
                Assert.AreEqual(snapshot1.SnapshotTime.Value, snapshotParseVerifier.SnapshotTime.Value);

                CloudBlob snapshotCopy = container.GetBlobReference("blob2");
                snapshotCopy.StartCopy(TestHelper.Defiddler(snapshot1.Uri));
                WaitForCopy(snapshotCopy);
                Assert.AreEqual(CopyStatus.Success, snapshotCopy.CopyState.Status);

                using (Stream snapshotStream = snapshot1.OpenRead())
                {
                    snapshotStream.Seek(0, SeekOrigin.End);
                    TestHelper.AssertStreamsAreEqual(originalData, snapshotStream);
                }

                //overwriting the blob and creating the 5th snapshot
                appendBlob.CreateOrReplace();
                blob.FetchAttributes();

                using (Stream snapshotStream = snapshot1.OpenRead())
                {
                    snapshotStream.Seek(0, SeekOrigin.End);
                    TestHelper.AssertStreamsAreEqual(originalData, snapshotStream);
                }

                List <IListBlobItem> blobs = container.ListBlobs(null, true, BlobListingDetails.All, null, null).ToList();
                Assert.AreEqual(4, blobs.Count);
                AssertAreEqual(snapshot1, (CloudBlob)blobs[0]);
                AssertAreEqual(snapshot2, (CloudBlob)blobs[1]);
                AssertAreEqual(blob, (CloudBlob)blobs[2]);
                AssertAreEqual(snapshotCopy, (CloudBlob)blobs[3]);
            }
            finally
            {
                container.DeleteIfExists();
            }
        }
コード例 #10
0
        public void CloudBlobSnapshotAPM()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                container.Create();

                MemoryStream    originalData = new MemoryStream(GetRandomBuffer(1024));
                CloudAppendBlob appendBlob   = container.GetAppendBlobReference(BlobName);
                appendBlob.CreateOrReplace();
                appendBlob.AppendBlock(originalData, null);

                CloudBlob blob = container.GetBlobReference(BlobName);
                blob.FetchAttributes();
                IAsyncResult result;
                using (AutoResetEvent waitHandle = new AutoResetEvent(false))
                {
                    result = blob.BeginSnapshot(ar => waitHandle.Set(), null);
                    waitHandle.WaitOne();
                    CloudBlob snapshot1 = blob.EndSnapshot(result);
                    Assert.AreEqual(blob.Properties.ETag, snapshot1.Properties.ETag);
                    Assert.AreEqual(blob.Properties.LastModified, snapshot1.Properties.LastModified);
                    Assert.IsTrue(snapshot1.IsSnapshot);
                    Assert.IsNotNull(snapshot1.SnapshotTime, "Snapshot does not have SnapshotTime set");
                    Assert.AreEqual(blob.Uri, snapshot1.Uri);
                    Assert.AreNotEqual(blob.SnapshotQualifiedUri, snapshot1.SnapshotQualifiedUri);
                    Assert.AreNotEqual(snapshot1.Uri, snapshot1.SnapshotQualifiedUri);
                    Assert.IsTrue(snapshot1.SnapshotQualifiedUri.Query.Contains("snapshot"));

                    result = blob.BeginSnapshot(ar => waitHandle.Set(), null);
                    waitHandle.WaitOne();
                    CloudBlob snapshot2 = blob.EndSnapshot(result);
                    Assert.IsTrue(snapshot2.SnapshotTime.Value > snapshot1.SnapshotTime.Value);

                    snapshot1.FetchAttributes();
                    snapshot2.FetchAttributes();
                    blob.FetchAttributes();
                    AssertAreEqual(snapshot1.Properties, blob.Properties);

                    CloudBlob snapshotCopy = container.GetBlobReference("blob2");
                    result = snapshotCopy.BeginStartCopy(snapshot1.Uri, null, null, null, null, ar => waitHandle.Set(), null);
                    waitHandle.WaitOne();
                    snapshotCopy.EndStartCopy(result);
                    WaitForCopy(snapshotCopy);
                    Assert.AreEqual(CopyStatus.Success, snapshotCopy.CopyState.Status);

                    result = snapshot1.BeginOpenRead(ar => waitHandle.Set(), null);
                    waitHandle.WaitOne();
                    using (Stream snapshotStream = snapshot1.EndOpenRead(result))
                    {
                        snapshotStream.Seek(0, SeekOrigin.End);
                        TestHelper.AssertStreamsAreEqual(originalData, snapshotStream);
                    }

                    result = appendBlob.BeginCreateOrReplace(ar => waitHandle.Set(), null);
                    waitHandle.WaitOne();
                    appendBlob.EndCreateOrReplace(result);
                    result = blob.BeginFetchAttributes(ar => waitHandle.Set(), null);
                    waitHandle.WaitOne();
                    blob.EndFetchAttributes(result);

                    result = snapshot1.BeginOpenRead(ar => waitHandle.Set(), null);
                    waitHandle.WaitOne();
                    using (Stream snapshotStream = snapshot1.EndOpenRead(result))
                    {
                        snapshotStream.Seek(0, SeekOrigin.End);
                        TestHelper.AssertStreamsAreEqual(originalData, snapshotStream);
                    }

                    List <IListBlobItem> blobs = container.ListBlobs(null, true, BlobListingDetails.All, null, null).ToList();
                    Assert.AreEqual(4, blobs.Count);
                    AssertAreEqual(snapshot1, (CloudBlob)blobs[0]);
                    AssertAreEqual(snapshot2, (CloudBlob)blobs[1]);
                    AssertAreEqual(blob, (CloudBlob)blobs[2]);
                    AssertAreEqual(snapshotCopy, (CloudBlob)blobs[3]);
                }
            }
            finally
            {
                container.DeleteIfExists();
            }
        }
コード例 #11
0
        public async Task CloudBlobSnapshotTask()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                MemoryStream    originalData = new MemoryStream(GetRandomBuffer(1024));
                CloudAppendBlob appendBlob   = container.GetAppendBlobReference(BlobName);
                await appendBlob.CreateOrReplaceAsync();

                await appendBlob.AppendBlockAsync(originalData, null);

                CloudBlob blob = container.GetBlobReference(BlobName);
                await blob.FetchAttributesAsync();

                CloudBlob snapshot1 = await blob.SnapshotAsync();

                Assert.AreEqual(blob.Properties.ETag, snapshot1.Properties.ETag);
                Assert.AreEqual(blob.Properties.LastModified, snapshot1.Properties.LastModified);
                Assert.IsTrue(snapshot1.IsSnapshot);
                Assert.IsNotNull(snapshot1.SnapshotTime, "Snapshot does not have SnapshotTime set");
                Assert.AreEqual(blob.Uri, snapshot1.Uri);
                Assert.AreNotEqual(blob.SnapshotQualifiedUri, snapshot1.SnapshotQualifiedUri);
                Assert.AreNotEqual(snapshot1.Uri, snapshot1.SnapshotQualifiedUri);
                Assert.IsTrue(snapshot1.SnapshotQualifiedUri.Query.Contains("snapshot"));

                CloudBlob snapshot2 = await blob.SnapshotAsync();

                Assert.IsTrue(snapshot2.SnapshotTime.Value > snapshot1.SnapshotTime.Value);

                await snapshot1.FetchAttributesAsync();

                await snapshot2.FetchAttributesAsync();

                await blob.FetchAttributesAsync();

                AssertAreEqual(snapshot1.Properties, blob.Properties);

                CloudBlob snapshot1Clone = new CloudBlob(new Uri(blob.Uri + "?snapshot=" + snapshot1.SnapshotTime.Value.ToString("O")), blob.ServiceClient.Credentials);
                Assert.IsNotNull(snapshot1Clone.SnapshotTime, "Snapshot clone does not have SnapshotTime set");
                Assert.AreEqual(snapshot1.SnapshotTime.Value, snapshot1Clone.SnapshotTime.Value);
                await snapshot1Clone.FetchAttributesAsync();

                AssertAreEqual(snapshot1.Properties, snapshot1Clone.Properties);

                CloudBlob snapshotCopy = container.GetBlobReference("blob2");
                await snapshotCopy.StartCopyAsync(snapshot1.Uri, null, null, null, null);
                await WaitForCopyAsync(snapshotCopy);

                Assert.AreEqual(CopyStatus.Success, snapshotCopy.CopyState.Status);

                using (Stream snapshotStream = await snapshot1.OpenReadAsync())
                {
                    snapshotStream.Seek(0, SeekOrigin.End);
                    TestHelper.AssertStreamsAreEqual(originalData, snapshotStream);
                }

                //overwriting will create another snapshot
                await appendBlob.CreateOrReplaceAsync();

                await blob.FetchAttributesAsync();

                using (Stream snapshotStream = await snapshot1.OpenReadAsync())
                {
                    snapshotStream.Seek(0, SeekOrigin.End);
                    TestHelper.AssertStreamsAreEqual(originalData, snapshotStream);
                }

                List <IListBlobItem> blobs =
                    (await container.ListBlobsSegmentedAsync(null, true, BlobListingDetails.All, null, null, null, null))
                    .Results
                    .ToList();
                Assert.AreEqual(5, blobs.Count);
                AssertAreEqual(snapshot1, (CloudBlob)blobs[0]);
                AssertAreEqual(snapshot2, (CloudBlob)blobs[1]);
                Assert.IsTrue(((CloudBlob)blobs[2]).IsDeleted);
                AssertAreEqual(blob, (CloudBlob)blobs[3]);
                AssertAreEqual(snapshotCopy, (CloudBlob)blobs[4]);
            }
            finally
            {
                await container.DeleteIfExistsAsync();
            }
        }
コード例 #12
0
 public void TestInitialize()
 {
     this.testContainer = BlobTestBase.GetRandomContainerReference();
     this.testContainer.CreateIfNotExists();
 }
コード例 #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudBlockBlob"/> class using the specified blob name and
 /// the parent container reference.
 /// If snapshotTime is not null, the blob instance represents a Snapshot.
 /// </summary>
 /// <param name="blobName">Name of the blob.</param>
 /// <param name="snapshotTime">Snapshot time in case the blob is a snapshot.</param>
 /// <param name="container">The reference to the parent container.</param>
 internal CloudBlockBlob(string blobName, DateTimeOffset?snapshotTime, CloudBlobContainer container)
     : base(blobName, snapshotTime, container)
 {
     this.Properties.BlobType = BlobType.BlockBlob;
 }
コード例 #14
0
        public async Task CloudBlobSnapshotAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                MemoryStream   originalData = new MemoryStream(GetRandomBuffer(1024));
                CloudBlockBlob blockBlob    = container.GetBlockBlobReference(BlobName);
                await blockBlob.UploadFromStreamAsync(originalData);

                CloudBlob blob = container.GetBlobReference(BlobName);
                await blob.FetchAttributesAsync();

                Assert.IsFalse(blob.IsSnapshot);
                Assert.IsNull(blob.SnapshotTime, "Root blob has SnapshotTime set");
                Assert.IsFalse(blob.SnapshotQualifiedUri.Query.Contains("snapshot"));
                Assert.AreEqual(blob.Uri, blob.SnapshotQualifiedUri);

                CloudBlob snapshot1 = await blob.SnapshotAsync();

                Assert.AreEqual(blob.Properties.ETag, snapshot1.Properties.ETag);
                Assert.AreEqual(blob.Properties.LastModified, snapshot1.Properties.LastModified);
                Assert.IsTrue(snapshot1.IsSnapshot);
                Assert.IsNotNull(snapshot1.SnapshotTime, "Snapshot does not have SnapshotTime set");
                Assert.AreEqual(blob.Uri, snapshot1.Uri);
                Assert.AreNotEqual(blob.SnapshotQualifiedUri, snapshot1.SnapshotQualifiedUri);
                Assert.AreNotEqual(snapshot1.Uri, snapshot1.SnapshotQualifiedUri);
                Assert.IsTrue(snapshot1.SnapshotQualifiedUri.Query.Contains("snapshot"));

                CloudBlob snapshot2 = await blob.SnapshotAsync();

                Assert.IsTrue(snapshot2.SnapshotTime.Value > snapshot1.SnapshotTime.Value);

                await snapshot1.FetchAttributesAsync();

                await snapshot2.FetchAttributesAsync();

                await blob.FetchAttributesAsync();

                AssertAreEqual(snapshot1.Properties, blob.Properties);

                CloudBlob snapshot1Clone = new CloudBlob(new Uri(blob.Uri + "?snapshot=" + snapshot1.SnapshotTime.Value.ToString("O")), blob.ServiceClient.Credentials);
                Assert.IsNotNull(snapshot1Clone.SnapshotTime, "Snapshot clone does not have SnapshotTime set");
                Assert.AreEqual(snapshot1.SnapshotTime.Value, snapshot1Clone.SnapshotTime.Value);
                await snapshot1Clone.FetchAttributesAsync();

                AssertAreEqual(snapshot1.Properties, snapshot1Clone.Properties);

                // The query parser should not be case sensitive in detecting a snapshot in the query string
                CloudBlob snapshotParseVerifier = new CloudBlob(new Uri(blob.Uri + "?sNapshOt=" + snapshot1.SnapshotTime.Value.ToString("O")), blob.ServiceClient.Credentials);
                Assert.IsNotNull(snapshotParseVerifier.SnapshotTime, "Snapshot parse verifier did not successfully detect the snapshot time");
                Assert.AreEqual(snapshot1.SnapshotTime.Value, snapshotParseVerifier.SnapshotTime.Value);

                CloudBlob snapshotCopy = container.GetBlobReference("blob2");
                await snapshotCopy.StartCopyAsync(TestHelper.Defiddler(snapshot1.Uri));
                await WaitForCopyAsync(snapshotCopy);

                Assert.AreEqual(CopyStatus.Success, snapshotCopy.CopyState.Status);

                using (Stream snapshotStream = (await snapshot1.OpenReadAsync()))
                {
                    snapshotStream.Seek(0, SeekOrigin.End);
                    TestHelper.AssertStreamsAreEqual(originalData, snapshotStream);
                }

                await blockBlob.PutBlockListAsync(new List <string>());

                await blob.FetchAttributesAsync();

                using (Stream snapshotStream = (await snapshot1.OpenReadAsync()))
                {
                    snapshotStream.Seek(0, SeekOrigin.End);
                    TestHelper.AssertStreamsAreEqual(originalData, snapshotStream);
                }

                BlobResultSegment resultSegment = await container.ListBlobsSegmentedAsync(null, true, BlobListingDetails.All, null, null, null, null);

                List <IListBlobItem> blobs = resultSegment.Results.ToList();
                Assert.AreEqual(4, blobs.Count);
                AssertAreEqual(snapshot1, (CloudBlob)blobs[0]);
                AssertAreEqual(snapshot2, (CloudBlob)blobs[1]);
                AssertAreEqual(blob, (CloudBlob)blobs[2]);
                AssertAreEqual(snapshotCopy, (CloudBlob)blobs[3]);
            }
            finally
            {
                container.DeleteIfExistsAsync().Wait();
            }
        }
コード例 #15
0
        public async Task CloudBlobContainerGetBlobReferenceFromServerAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy()
                {
                    Permissions            = SharedAccessBlobPermissions.Read,
                    SharedAccessStartTime  = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                };

                CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb");
                await blockBlob.PutBlockListAsync(new List <string>());

                CloudPageBlob pageBlob = container.GetPageBlobReference("pb");
                await pageBlob.CreateAsync(0);

                CloudAppendBlob appendBlob = container.GetAppendBlobReference("ab");
                await appendBlob.CreateOrReplaceAsync();

                CloudBlobClient client;
                ICloudBlob      blob;

                blob = await container.GetBlobReferenceFromServerAsync("bb");

                Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri));

                CloudBlockBlob blockBlobSnapshot = await((CloudBlockBlob)blob).CreateSnapshotAsync();
                await blob.SetPropertiesAsync();

                Uri blockBlobSnapshotUri = new Uri(blockBlobSnapshot.Uri.AbsoluteUri + "?snapshot=" + blockBlobSnapshot.SnapshotTime.Value.UtcDateTime.ToString("o"));
                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlobSnapshotUri);

                AssertAreEqual(blockBlobSnapshot.Properties, blob.Properties);
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlobSnapshot.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = await container.GetBlobReferenceFromServerAsync("pb");

                Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri));

                CloudPageBlob pageBlobSnapshot = await((CloudPageBlob)blob).CreateSnapshotAsync();
                await blob.SetPropertiesAsync();

                Uri pageBlobSnapshotUri = new Uri(pageBlobSnapshot.Uri.AbsoluteUri + "?snapshot=" + pageBlobSnapshot.SnapshotTime.Value.UtcDateTime.ToString("o"));
                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlobSnapshotUri);

                AssertAreEqual(pageBlobSnapshot.Properties, blob.Properties);
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlobSnapshot.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = await container.GetBlobReferenceFromServerAsync("ab");

                Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob));
                Assert.IsTrue(blob.StorageUri.Equals(appendBlob.StorageUri));

                CloudAppendBlob appendBlobSnapshot = await((CloudAppendBlob)blob).CreateSnapshotAsync();
                await blob.SetPropertiesAsync();

                Uri appendBlobSnapshotUri = new Uri(appendBlobSnapshot.Uri.AbsoluteUri + "?snapshot=" + appendBlobSnapshot.SnapshotTime.Value.UtcDateTime.ToString("o"));
                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(appendBlobSnapshotUri);

                AssertAreEqual(appendBlobSnapshot.Properties, blob.Properties);
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(appendBlobSnapshot.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlob.Uri);

                Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlob.Uri);

                Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(appendBlob.Uri);

                Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob));
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(appendBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlob.StorageUri, null, null, null);

                Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri));

                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlob.StorageUri, null, null, null);

                Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri));

                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(appendBlob.StorageUri, null, null, null);

                Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob));
                Assert.IsTrue(blob.StorageUri.Equals(appendBlob.StorageUri));

                string             blockBlobToken = blockBlob.GetSharedAccessSignature(policy);
                StorageCredentials blockBlobSAS   = new StorageCredentials(blockBlobToken);
                Uri        blockBlobSASUri        = blockBlobSAS.TransformUri(blockBlob.Uri);
                StorageUri blockBlobSASStorageUri = blockBlobSAS.TransformUri(blockBlob.StorageUri);

                string             appendBlobToken = appendBlob.GetSharedAccessSignature(policy);
                StorageCredentials appendBlobSAS   = new StorageCredentials(appendBlobToken);
                Uri        appendBlobSASUri        = appendBlobSAS.TransformUri(appendBlob.Uri);
                StorageUri appendBlobSASStorageUri = appendBlobSAS.TransformUri(appendBlob.StorageUri);

                string             pageBlobToken = pageBlob.GetSharedAccessSignature(policy);
                StorageCredentials pageBlobSAS   = new StorageCredentials(pageBlobToken);
                Uri        pageBlobSASUri        = pageBlobSAS.TransformUri(pageBlob.Uri);
                StorageUri pageBlobSASStorageUri = pageBlobSAS.TransformUri(pageBlob.StorageUri);

                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlobSASUri);

                Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlobSASUri);

                Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(appendBlobSASUri);

                Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob));
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(appendBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlobSASStorageUri, null, null, null);

                Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri));

                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlobSASStorageUri, null, null, null);

                Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri));

                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(appendBlobSASStorageUri, null, null, null);

                Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob));
                Assert.IsTrue(blob.StorageUri.Equals(appendBlob.StorageUri));

                client = new CloudBlobClient(container.ServiceClient.BaseUri, blockBlobSAS);
                blob   = await client.GetBlobReferenceFromServerAsync(blockBlobSASUri);

                Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                client = new CloudBlobClient(container.ServiceClient.BaseUri, pageBlobSAS);
                blob   = await client.GetBlobReferenceFromServerAsync(pageBlobSASUri);

                Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                client = new CloudBlobClient(container.ServiceClient.BaseUri, appendBlobSAS);
                blob   = await client.GetBlobReferenceFromServerAsync(appendBlobSASUri);

                Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob));
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(appendBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                client = new CloudBlobClient(container.ServiceClient.StorageUri, blockBlobSAS);
                blob   = await client.GetBlobReferenceFromServerAsync(blockBlobSASStorageUri, null, null, null);

                Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri));

                client = new CloudBlobClient(container.ServiceClient.StorageUri, pageBlobSAS);
                blob   = await client.GetBlobReferenceFromServerAsync(pageBlobSASStorageUri, null, null, null);

                Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri));

                client = new CloudBlobClient(container.ServiceClient.StorageUri, appendBlobSAS);
                blob   = await client.GetBlobReferenceFromServerAsync(appendBlobSASStorageUri, null, null, null);

                Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob));
                Assert.IsTrue(blob.StorageUri.Equals(appendBlob.StorageUri));
            }
            finally
            {
                container.DeleteIfExistsAsync().Wait();
            }
        }
コード例 #16
0
        private static async Task TestAccessAsync(BlobContainerPublicAccessType accessType, CloudBlobContainer container, CloudBlob inputBlob)
        {
            StorageCredentials credentials = new StorageCredentials();

            container = new CloudBlobContainer(container.Uri, credentials);
            CloudPageBlob      blob    = new CloudPageBlob(inputBlob.Uri, credentials);
            OperationContext   context = new OperationContext();
            BlobRequestOptions options = new BlobRequestOptions();


            if (accessType.Equals(BlobContainerPublicAccessType.Container))
            {
                await blob.FetchAttributesAsync();

                await container.ListBlobsSegmentedAsync(null, true, BlobListingDetails.All, null, null, options, context);

                await container.FetchAttributesAsync();
            }
            else if (accessType.Equals(BlobContainerPublicAccessType.Blob))
            {
                await blob.FetchAttributesAsync();

                await TestHelper.ExpectedExceptionAsync(
                    async() => await container.ListBlobsSegmentedAsync(null, true, BlobListingDetails.All, null, null, options, context),
                    context,
                    "List blobs while public access does not allow for listing",
                    HttpStatusCode.NotFound);

                await TestHelper.ExpectedExceptionAsync(
                    async() => await container.FetchAttributesAsync(null, options, context),
                    context,
                    "Fetch container attributes while public access does not allow",
                    HttpStatusCode.NotFound);
            }
            else
            {
                await TestHelper.ExpectedExceptionAsync(
                    async() => await blob.FetchAttributesAsync(null, options, context),
                    context,
                    "Fetch blob attributes while public access does not allow",
                    HttpStatusCode.NotFound);

                await TestHelper.ExpectedExceptionAsync(
                    async() => await container.ListBlobsSegmentedAsync(null, true, BlobListingDetails.All, null, null, options, context),
                    context,
                    "List blobs while public access does not allow for listing",
                    HttpStatusCode.NotFound);

                await TestHelper.ExpectedExceptionAsync(
                    async() => await container.FetchAttributesAsync(null, options, context),
                    context,
                    "Fetch container attributes while public access does not allow",
                    HttpStatusCode.NotFound);
            }
        }