예제 #1
0
        private async Task <bool> DeleteCSV(int ID)
        {
            bool   result   = false;
            string fileName = null;

            BaseResponseModel CSVResponse = responseService.GetSurveyFilename(ID);

            if (CSVResponse != null)
            {
                fileName = CSVResponse.ResponseCSV.Split("/").Last();
            }

            try
            {
                CloudAppendBlob CSV = CONTAINER.GetAppendBlobReference(fileName);

                if (CSV != null)
                {
                    await CSV.DeleteAsync();

                    result = true;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Exception Caught - " + ex.Message);
                result = false;
            }

            return(result);
        }
예제 #2
0
        private static async Task deleteBlobs()
        {
            Console.Write("Please enter text to delete from blob: ");
            string text = Console.ReadLine();

            // Get a reference to a blob.
            CloudAppendBlob appendBlob = container.GetAppendBlobReference(text);

            // Delete the blob.
            await appendBlob.DeleteAsync();
        }
예제 #3
0
 /// <inheritdoc />
 public Task DeleteAsync(CancellationToken cancellationToken)
 {
     return(_sdk.DeleteAsync(cancellationToken));
 }
예제 #4
0
        private static async Task AppendBlobProcessAsync()
        {
            CloudStorageAccount storageAccount = null;

            CloudBlobContainer cloudBlobContainer = null;

            string sourceFile = null;

            string destinationFile = null;


            // Retrieve the connection string for use with the application. The storage connection string is stored

            // in an environment variable on the machine running the application called storageconnectionstring.

            // If the environment variable is created after the application is launched in a console or with Visual

            // Studio, the shell needs to be closed and reloaded to take the environment variable into account.

            string storageConnectionString = ConfigurationManager.AppSettings["StorageConnectionString"]; //Environment.GetEnvironmentVariable("StorageConnectionString");


            //storageAccount = CloudStorageAccount.DevelopmentStorageAccount;

            // Check whether the connection string can be parsed.

            if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount))
            {
                try

                {
                    // Create the CloudBlobClient that represents the Blob storage endpoint for the storage account.

                    ////CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();

                    //127.0.0.1:10000/devstoreaccount1/testcont

                    // Create a container called 'quickstartblobs' and append a GUID value to it to make the name unique.

                    ////cloudBlobContainer = cloudBlobClient.GetContainerReference("testcontappendblob");// "quickstartblobs" + Guid.NewGuid().ToString());

                    ////await cloudBlobContainer.CreateIfNotExistsAsync();

                    ////Console.WriteLine("Created container '{0}'", cloudBlobContainer.Name);

                    ////Console.WriteLine();



                    ////// Set the permissions so the blobs are public.

                    ////BlobContainerPermissions permissions = new BlobContainerPermissions

                    ////{

                    ////    PublicAccess = BlobContainerPublicAccessType.Blob

                    ////};

                    ////await cloudBlobContainer.SetPermissionsAsync(permissions);

                    // Get a reference to the blob address, then upload the file to the blob.

                    // Use the value of localFileName for the blob name.


                    CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
                    cloudBlobContainer = cloudBlobClient.GetContainerReference("testcont");
                    cloudBlobContainer.CreateIfNotExists();

                    CloudAppendBlob cloudAppendBlob = cloudBlobContainer.GetAppendBlobReference("1.txt");
                    cloudAppendBlob.CreateOrReplace();
                    cloudAppendBlob.AppendText("Content added");
                    cloudAppendBlob.AppendText("More content added");
                    cloudAppendBlob.AppendText("Even more content added");

                    string appendBlobContent = cloudAppendBlob.DownloadText();


                    //cloudAppendBlob.UploadFromFile(sourceFile);



                    // List the blobs in the container.

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

                    BlobContinuationToken blobContinuationToken = null;

                    do

                    {
                        var results = await cloudBlobContainer.ListBlobsSegmentedAsync(null, blobContinuationToken);

                        // Get the value of the continuation token returned by the listing call.

                        blobContinuationToken = results.ContinuationToken;

                        foreach (IListBlobItem item in results.Results)

                        {
                            Console.WriteLine(item.Uri);
                        }
                    } while (blobContinuationToken != null); // Loop while the continuation token is not null.

                    destinationFile = sourceFile.Replace(".txt", "_DOWNLOADED.txt");

                    Console.WriteLine("Downloading blob to {0}", destinationFile);

                    Console.WriteLine();

                    await cloudAppendBlob.DownloadToFileAsync(destinationFile, FileMode.Create);


                    File.WriteAllText(sourceFile, "Hello, World, I am good, how is your health!");

                    await cloudAppendBlob.UploadFromFileAsync(sourceFile);

                    await cloudAppendBlob.DeleteAsync();
                }

                catch (StorageException ex)

                {
                    Console.WriteLine("Error returned from the service: {0}", ex.Message);
                }

                finally

                {
                    // Console.WriteLine("Press any key to delete the sample files and example container.");

                    Console.ReadLine();

                    // Clean up resources. This includes the container and the two temp files.

                    //Console.WriteLine("Deleting the container and any blobs it contains");

                    if (cloudBlobContainer != null)
                    {
                        // await cloudBlobContainer.DeleteIfExistsAsync();
                    }
                    File.Delete(sourceFile);
                    File.Delete(destinationFile);
                }
            }

            else

            {
                Console.WriteLine(

                    "A connection string has not been defined in the system environment variables. " +

                    "Add a environment variable named 'storageconnectionstring' with your storage " +

                    "connection string as a value.");
            }
        }
예제 #5
0
 /// <inheritdoc />
 public Task DeleteAsync(CancellationToken cancellationToken)
 {
     return(_sdk.DeleteAsync(DeleteSnapshotsOption.None, accessCondition: null, options: null, operationContext: null, cancellationToken: cancellationToken));
 }
예제 #6
0
 public static void Delete(this CloudAppendBlob blob)
 {
     blob.DeleteAsync().Wait();
 }
예제 #7
0
        public async Task AppendBlobCleanupAsync()
        {
            BlobContinuationToken continuationToken = null;

            // work through the Blob Segments cleaning up as we go...
            // (NOTE: there's currently no ListBlobsAsync method ;-) )
            do
            {
                var listResult = await _tmpContainer.ListBlobsSegmentedAsync(
                    prefix : null,
                    useFlatBlobListing : true,
                    blobListingDetails : BlobListingDetails.None,
                    maxResults : null,
                    currentToken : continuationToken,
                    options : null,
                    operationContext : null);

                foreach (IListBlobItem b in listResult.Results)
                {
                    // list all blob in temp container, filter the ones that have "copied" metadata
                    if (b.GetType() == typeof(CloudAppendBlob))
                    {
                        CloudAppendBlob item = (CloudAppendBlob)b;
                        item.FetchAttributes();
                        if (item.Metadata.Keys.Contains("copied"))
                        {
                            Console.WriteLine($"Delete blob {item.Uri.ToString()}");
                            await item.DeleteAsync(DeleteSnapshotsOption.IncludeSnapshots,
                                                   accessCondition : null,
                                                   options : null,
                                                   operationContext : null);
                        }
                        else
                        {
                            if (item.Metadata.Keys.Contains("full"))
                            {
                                var targetBlob = await GetTargetBlockBlobAsync(item);
                                await CopyBlobAsync(item, targetBlob);
                                await FlagAsCopiedAysnc(item);
                            }
                        }
                    }
                }

                continuationToken = listResult.ContinuationToken;
            } while (continuationToken != null);


            foreach (IListBlobItem b in _tmpContainer.ListBlobs(null, true))
            {
                // list all blob in temp container, filter the ones that have "copied" metadata
                if (b.GetType() == typeof(CloudAppendBlob))
                {
                    CloudAppendBlob item = (CloudAppendBlob)b;
                    item.FetchAttributes();
                    if (item.Metadata.Keys.Contains("copied"))
                    {
                        Console.WriteLine($"Delete blob {item.Uri.ToString()}");
                        await item.DeleteAsync(DeleteSnapshotsOption.IncludeSnapshots,
                                               accessCondition : null,
                                               options : null,
                                               operationContext : null);
                    }
                    else
                    {
                        if (item.Metadata.Keys.Contains("full"))
                        {
                            var targetBlob = await GetTargetBlockBlobAsync(item);
                            await CopyBlobAsync(item, targetBlob);
                            await FlagAsCopiedAysnc(item);
                        }
                    }
                }
            }
        }
예제 #8
0
        public async Task RunPermissionsTestBlobs(SharedAccessAccountPolicy policy)
        {
            CloudBlobClient blobClient    = GenerateCloudBlobClient();
            string          containerName = "c" + Guid.NewGuid().ToString("N");

            try
            {
                CloudStorageAccount account           = new CloudStorageAccount(blobClient.Credentials, false);
                string              accountSASToken   = account.GetSharedAccessSignature(policy);
                StorageCredentials  accountSAS        = new StorageCredentials(accountSASToken);
                CloudStorageAccount accountWithSAS    = new CloudStorageAccount(accountSAS, blobClient.StorageUri, null, null, null);
                CloudBlobClient     blobClientWithSAS = accountWithSAS.CreateCloudBlobClient();
                CloudBlobContainer  containerWithSAS  = blobClientWithSAS.GetContainerReference(containerName);
                CloudBlobContainer  container         = blobClient.GetContainerReference(containerName);

                // General pattern - If current perms support doing a thing with SAS, do the thing with SAS and validate with shared
                // Otherwise, make sure SAS fails and then do the thing with shared key.

                // Things to do:
                // Create the container (Create / Write perms, Container RT)
                // List containers with prefix (List perms, Service RT)
                // Create an append blob (Create / Write perms, Object RT)
                // Append a block to append blob (Add / Write perms, Object RT)
                // Read the data from the append blob (Read perms, Object RT)
                // Delete the blob (Delete perms, Object RT)
                if ((((policy.Permissions & SharedAccessAccountPermissions.Create) == SharedAccessAccountPermissions.Create) || ((policy.Permissions & SharedAccessAccountPermissions.Write) == SharedAccessAccountPermissions.Write)) &&
                    ((policy.ResourceTypes & SharedAccessAccountResourceTypes.Container) == SharedAccessAccountResourceTypes.Container))
                {
                    await containerWithSAS.CreateAsync();
                }
                else
                {
                    await TestHelper.ExpectedExceptionAsync <StorageException>(async() => await containerWithSAS.CreateAsync(), "Create a container should fail with SAS without Create or Write and Container-level permissions.");

                    await container.CreateAsync();
                }

                Assert.IsTrue(await container.ExistsAsync());

                if (((policy.Permissions & SharedAccessAccountPermissions.List) == SharedAccessAccountPermissions.List) &&
                    ((policy.ResourceTypes & SharedAccessAccountResourceTypes.Service) == SharedAccessAccountResourceTypes.Service))
                {
                    ContainerResultSegment           segment = null;
                    BlobContinuationToken            ct      = null;
                    IEnumerable <CloudBlobContainer> results = null;
                    do
                    {
                        segment = await blobClientWithSAS.ListContainersSegmentedAsync(container.Name, ct);

                        ct      = segment.ContinuationToken;
                        results = segment.Results;
                    }while(ct != null && !results.Any());

                    Assert.AreEqual(container.Name, segment.Results.First().Name);
                }
                else
                {
                    await TestHelper.ExpectedExceptionAsync <StorageException>(async() => { ContainerResultSegment segment = await blobClientWithSAS.ListContainersSegmentedAsync(container.Name, null); segment.Results.First(); }, "List containers should fail with SAS without List and Service-level permissions.");
                }

                string          blobName          = "blob";
                CloudAppendBlob appendBlob        = container.GetAppendBlobReference(blobName);
                CloudAppendBlob appendBlobWithSAS = containerWithSAS.GetAppendBlobReference(blobName);

                //Try creating credentials using SAS Uri directly
                CloudAppendBlob appendBlobWithSASUri = new CloudAppendBlob(new Uri(container.Uri + accountSASToken));

                if ((((policy.Permissions & SharedAccessAccountPermissions.Create) == SharedAccessAccountPermissions.Create) || ((policy.Permissions & SharedAccessAccountPermissions.Write) == SharedAccessAccountPermissions.Write)) &&
                    ((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object))
                {
                    await appendBlobWithSAS.CreateOrReplaceAsync();
                }
                else
                {
                    await TestHelper.ExpectedExceptionAsync <StorageException>(async() => await appendBlobWithSAS.CreateOrReplaceAsync(), "Creating an append blob should fail with SAS without Create or Write and Object-level perms.");

                    await appendBlob.CreateOrReplaceAsync();
                }

                Assert.IsTrue(await appendBlob.ExistsAsync());

                string blobText = "blobText";
                if ((((policy.Permissions & SharedAccessAccountPermissions.Add) == SharedAccessAccountPermissions.Add) || ((policy.Permissions & SharedAccessAccountPermissions.Write) == SharedAccessAccountPermissions.Write)) &&
                    ((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object))
                {
                    using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(blobText)))
                    {
                        await appendBlobWithSAS.AppendBlockAsync(stream);
                    }
                }
                else
                {
                    using (MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(blobText)))
                    {
                        await TestHelper.ExpectedExceptionAsync <StorageException>(async() => await appendBlobWithSAS.AppendBlockAsync(memStream), "Append a block to an append blob should fail with SAS without Add or Write and Object-level perms.");

                        memStream.Seek(0, SeekOrigin.Begin);
                        await appendBlob.AppendBlockAsync(memStream);
                    }
                }

                Assert.AreEqual(blobText, await appendBlob.DownloadTextAsync());

                if (((policy.Permissions & SharedAccessAccountPermissions.Read) == SharedAccessAccountPermissions.Read) &&
                    ((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object))
                {
                    Assert.AreEqual(blobText, await appendBlobWithSAS.DownloadTextAsync());
                }
                else
                {
                    await TestHelper.ExpectedExceptionAsync <StorageException>(async() => await appendBlobWithSAS.DownloadTextAsync(), "Reading a blob's contents with SAS without Read and Object-level permissions should fail.");
                }

                if (((policy.Permissions & SharedAccessAccountPermissions.Delete) == SharedAccessAccountPermissions.Delete) &&
                    ((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object))
                {
                    await appendBlobWithSAS.DeleteAsync();
                }
                else
                {
                    await TestHelper.ExpectedExceptionAsync <StorageException>(async() => await appendBlobWithSAS.DeleteAsync(), "Deleting a blob with SAS without Delete and Object-level perms should fail.");

                    await appendBlob.DeleteAsync();
                }

                Assert.IsFalse(await appendBlob.ExistsAsync());
            }
            finally
            {
                blobClient.GetContainerReference(containerName).DeleteIfExistsAsync().Wait();
            }
        }