protected void SetContainerPermission(CloudBlobContainer container, BlobContainerPublicAccessType perimssion)
 {
     container.SetPermissionsAsync(new BlobContainerPermissions
     {
         PublicAccess = perimssion
     });
 }
        public async Task CloudBlobClientListContainersWithPublicAccessAsync()
        {
            string             name       = GetRandomContainerName();
            CloudBlobClient    blobClient = GenerateCloudBlobClient();
            CloudBlobContainer container  = blobClient.GetContainerReference(name);

            try
            {
                await container.CreateAsync();

                BlobContainerPublicAccessType[] accessValues = { BlobContainerPublicAccessType.Container, BlobContainerPublicAccessType.Off, BlobContainerPublicAccessType.Blob };
                BlobContainerPermissions        permissions  = new BlobContainerPermissions();
                foreach (BlobContainerPublicAccessType access in accessValues)
                {
                    permissions.PublicAccess = access;
                    await container.SetPermissionsAsync(permissions);

                    Assert.AreEqual(access, container.Properties.PublicAccess);

                    CloudBlobContainer container2 = blobClient.GetContainerReference(name);
                    Assert.IsFalse(container2.Properties.PublicAccess.HasValue);
                    await container2.FetchAttributesAsync();

                    Assert.AreEqual(access, container2.Properties.PublicAccess);

                    CloudBlobContainer       container3      = blobClient.GetContainerReference(name);
                    BlobContainerPermissions containerAccess = await container3.GetPermissionsAsync();

                    Assert.AreEqual(access, containerAccess.PublicAccess);
                    Assert.AreEqual(access, container3.Properties.PublicAccess);

                    List <CloudBlobContainer> listedContainers = new List <CloudBlobContainer>();
                    BlobContinuationToken     token            = null;
                    do
                    {
                        ContainerResultSegment resultSegment = await blobClient.ListContainersSegmentedAsync(name, token);

                        foreach (CloudBlobContainer returnedContainer in resultSegment.Results)
                        {
                            listedContainers.Add(returnedContainer);
                        }
                        token = resultSegment.ContinuationToken;
                    }while (token != null);

                    Assert.AreEqual(1, listedContainers.Count());
                    Assert.AreEqual(access, listedContainers.First().Properties.PublicAccess);
                }
            }
            finally
            {
                container.DeleteAsync().GetAwaiter().GetResult();
            }
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Creates a private container with the given name
 /// </summary>
 /// <param name="containerName"></param>
 /// <returns></returns>
 public async Task<bool> CreateContainerAsync(string containerName, bool isPublic)
 {
     // Create the container if it doesn't exist.
     blobContainer = blobClient.GetContainerReference(containerName);
     if (isPublic)
     {
         var returnData = await blobContainer.CreateIfNotExistsAsync();
         if (returnData)
             await blobContainer.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
         return returnData;
     }
     return await blobContainer.CreateIfNotExistsAsync();
 }
Ejemplo n.º 4
0
        public void Sync(CloudBlobContainer container, string localPath)
        {
            Console.WriteLine("Syncing localPath: '{0}', to container: '{1}'.", localPath, container.Uri);
            container.CreateIfNotExists();
            container.SetPermissionsAsync(new BlobContainerPermissions {
                PublicAccess = BlobContainerPublicAccessType.Blob
            });

            SyncLocalDirToBlob(localPath, container);
            Console.WriteLine(
                @"Total new: {0}, updated: {1}, deleted {2}."
                , _new.Count
                , _changed.Count
                , _deleted.Count
            );
        }
        public async Task CloudBlobContainerSetPermissionsAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                BlobContainerPermissions permissions = await container.GetPermissionsAsync();

                Assert.AreEqual(BlobContainerPublicAccessType.Off, permissions.PublicAccess);
                Assert.AreEqual(0, permissions.SharedAccessPolicies.Count);

                // We do not have precision at milliseconds level. Hence, we need
                // to recreate the start DateTime to be able to compare it later.
                DateTime start = DateTime.UtcNow;
                start = new DateTime(start.Year, start.Month, start.Day, start.Hour, start.Minute, start.Second, DateTimeKind.Utc);
                DateTime expiry = start.AddMinutes(30);

                permissions.PublicAccess = BlobContainerPublicAccessType.Container;
                permissions.SharedAccessPolicies.Add("key1", new SharedAccessBlobPolicy()
                {
                    SharedAccessStartTime  = start,
                    SharedAccessExpiryTime = expiry,
                    Permissions            = SharedAccessBlobPermissions.List,
                });
                await container.SetPermissionsAsync(permissions);

                await Task.Delay(30 * 1000);

                CloudBlobContainer container2 = container.ServiceClient.GetContainerReference(container.Name);
                permissions = await container2.GetPermissionsAsync();

                Assert.AreEqual(BlobContainerPublicAccessType.Container, permissions.PublicAccess);
                Assert.AreEqual(1, permissions.SharedAccessPolicies.Count);
                Assert.IsTrue(permissions.SharedAccessPolicies["key1"].SharedAccessStartTime.HasValue);
                Assert.AreEqual(start, permissions.SharedAccessPolicies["key1"].SharedAccessStartTime.Value.UtcDateTime);
                Assert.IsTrue(permissions.SharedAccessPolicies["key1"].SharedAccessExpiryTime.HasValue);
                Assert.AreEqual(expiry, permissions.SharedAccessPolicies["key1"].SharedAccessExpiryTime.Value.UtcDateTime);
                Assert.AreEqual(SharedAccessBlobPermissions.List, permissions.SharedAccessPolicies["key1"].Permissions);
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
 /// <summary>
 /// Return a task that asynchronously set the container permission
 /// </summary>
 /// <param name="container">CloudBlobContainer object</param>
 /// <param name="permissions">Container permission</param>
 /// <param name="accessCondition">Access condition</param>
 /// <param name="requestOptions">Blob request option</param>
 /// <param name="operationContext">Operation context</param>
 /// <param name="cmdletCancellationToken">cancellation token</param>
 /// <returns>Return a task that asynchronously set the container permission</returns>
 public Task SetContainerPermissionsAsync(CloudBlobContainer container, BlobContainerPermissions permissions, AccessCondition accessCondition, BlobRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken)
 {
     return container.SetPermissionsAsync(permissions, accessCondition, requestOptions, operationContext, cancellationToken);
 }
        private async Task <(bool, string)> UploadToBlob(string filename, byte[] imageBuffer = null, Stream stream = null)
        {
            Microsoft.WindowsAzure.Storage.CloudStorageAccount     storageAccount     = null;
            Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer cloudBlobContainer = null;
            string storageConnectionString = _configuration["storageconnectionstring"];

            // Check whether the connection string can be parsed.
            if (Microsoft.WindowsAzure.Storage.CloudStorageAccount.TryParse(storageConnectionString, out storageAccount))
            {
                try
                {
                    // Create the CloudBlobClient that represents the Blob storage endpoint for the storage account.
                    Microsoft.WindowsAzure.Storage.Blob.CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();

                    // Create a container called 'uploadblob' and append a GUID value to it to make the name unique.
                    cloudBlobContainer = cloudBlobClient.GetContainerReference("womeninworkforce");// ("uploadblob" + Guid.NewGuid().ToString());
                    await cloudBlobContainer.CreateIfNotExistsAsync();

                    // 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.
                    CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(filename);
                    List <Task>    tasks          = new List <Task>();
                    int            count          = 0;
                    if (imageBuffer != null)
                    {
                        // OPTION A: use imageBuffer (converted from memory stream)
                        await cloudBlockBlob.UploadFromByteArrayAsync(imageBuffer, 0, imageBuffer.Length);

                        //tasks.Add(cloudBlockBlob.UploadFromByteArrayAsync(imageBuffer, 0, options, null).ContinueWith((t) =>
                        //{
                        //    sem.Release();
                        //    Interlocked.Increment(ref completed_count);
                        //}));
                        //count++;
                    }
                    else if (stream != null)
                    {
                        // OPTION B: pass in memory stream directly
                        await cloudBlockBlob.UploadFromStreamAsync(stream);
                    }
                    else
                    {
                        return(false, null);
                    }

                    return(true, cloudBlockBlob.SnapshotQualifiedStorageUri.PrimaryUri.ToString());
                }
                catch (Microsoft.WindowsAzure.Storage.StorageException ex)
                {
                    return(false, null);
                }
                finally
                {
                    // OPTIONAL: Clean up resources, e.g. blob container
                    //if (cloudBlobContainer != null)
                    //{
                    //    await cloudBlobContainer.DeleteIfExistsAsync();
                    //}
                }
            }
            else
            {
                return(false, null);
            }
        }
        /// <summary>
        /// Creates a shared access policy on the container.
        /// </summary>
        /// <param name="container">A CloudBlobContainer object.</param>
        /// <param name="policyName">The name of the stored access policy.</param>
        /// <returns>A Task object.</returns>
        private static async Task CreateSharedAccessPolicyAsync(CloudBlobContainer container, string policyName)
        {
            // Create a new shared access policy and define its constraints.
            // The access policy provides create, write, read, list, and delete permissions.
            SharedAccessBlobPolicy sharedPolicy = new SharedAccessBlobPolicy()
            {
                // When the start time for the SAS is omitted, the start time is assumed to be the time when the storage service receives the request. 
                // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
                SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
                Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.List |
                    SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Create | SharedAccessBlobPermissions.Delete
            };

            // Get the container's existing permissions.
            BlobContainerPermissions permissions = await container.GetPermissionsAsync();

            // Add the new policy to the container's permissions, and set the container's permissions.
            permissions.SharedAccessPolicies.Add(policyName, sharedPolicy);
            await container.SetPermissionsAsync(permissions);
        }
        /// <summary>
        /// Sets the anonymous access level.
        /// </summary>
        /// <param name="container">The container.</param>
        /// <param name="accessType">Type of the access.</param>
        /// <returns>A Task object.</returns>
        private static async Task SetAnonymousAccessLevelAsync(CloudBlobContainer container, BlobContainerPublicAccessType accessType)
        {
            try
            {
                // Read the existing permissions first so that we have all container permissions. 
                // This ensures that we do not inadvertently remove any shared access policies while setting the public access level.
                BlobContainerPermissions permissions = await container.GetPermissionsAsync();

                // Set the container's public access level.
                permissions.PublicAccess = BlobContainerPublicAccessType.Container;
                await container.SetPermissionsAsync(permissions);

                Console.WriteLine("Container public access set to {0}", accessType.ToString());
                Console.WriteLine();
            }
            catch (StorageException e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
                throw;
            }
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Test container reads and writes, expecting success.
 /// </summary>
 /// <param name="testContainer">The container.</param>
 /// <param name="testAccessCondition">The access condition to use.</param>
 private async Task ContainerReadWriteExpectLeaseSuccessAsync(CloudBlobContainer testContainer, AccessCondition testAccessCondition)
 {
     await testContainer.FetchAttributesAsync(testAccessCondition, null /* options */, null);
     await testContainer.GetPermissionsAsync(testAccessCondition, null /* options */, null);
     await testContainer.SetMetadataAsync(testAccessCondition, null /* options */, null);
     await testContainer.SetPermissionsAsync(new BlobContainerPermissions(), testAccessCondition, null /* options */, null);
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Test container reads and writes, expecting lease failure.
        /// </summary>
        /// <param name="testContainer">The container.</param>
        /// <param name="testAccessCondition">The failing access condition to use.</param>
        /// <param name="expectedErrorCode">The expected error code.</param>
        /// <param name="description">The reason why these calls should fail.</param>
        private async Task ContainerReadWriteExpectLeaseFailureAsync(CloudBlobContainer testContainer, AccessCondition testAccessCondition, HttpStatusCode expectedStatusCode, string expectedErrorCode, string description)
        {
            OperationContext operationContext = new OperationContext();

            // FetchAttributes is a HEAD request with no extended error info, so it returns with the generic ConditionFailed error code.
            await TestHelper.ExpectedExceptionAsync(
                async () => await testContainer.FetchAttributesAsync(testAccessCondition, null /* options */, operationContext),
                operationContext,
                description + "(Fetch Attributes)",
                HttpStatusCode.PreconditionFailed);

            await TestHelper.ExpectedExceptionAsync(
                async () => await testContainer.GetPermissionsAsync(testAccessCondition, null /* options */, operationContext),
                operationContext,
                description + " (Get Permissions)",
                expectedStatusCode,
                expectedErrorCode);
            await TestHelper.ExpectedExceptionAsync(
                async () => await testContainer.SetMetadataAsync(testAccessCondition, null /* options */, operationContext),
                operationContext,
                description + " (Set Metadata)",
                expectedStatusCode,
                expectedErrorCode);
            await TestHelper.ExpectedExceptionAsync(
                async () => await testContainer.SetPermissionsAsync(new BlobContainerPermissions(), testAccessCondition, null /* options */, operationContext),
                operationContext,
                description + " (Set Permissions)",
                expectedStatusCode,
                expectedErrorCode);
        }
Ejemplo n.º 12
0
 /// <summary>
 /// Test container reads and writes, expecting success.
 /// </summary>
 /// <param name="testContainer">The container.</param>
 /// <param name="testAccessCondition">The access condition to use.</param>
 private void ContainerReadWriteExpectLeaseSuccessTask(CloudBlobContainer testContainer, AccessCondition testAccessCondition)
 {
     testContainer.FetchAttributesAsync(testAccessCondition, null /* options */, null /* operationContext */).Wait();
     testContainer.GetPermissionsAsync(testAccessCondition, null /* options */, null /* operationContext */).Wait();
     testContainer.SetMetadataAsync(testAccessCondition, null /* options */, null /* operationContext */).Wait();
     testContainer.SetPermissionsAsync(new BlobContainerPermissions(), testAccessCondition, null /* options */, null /* operationContext */).Wait();
 }
Ejemplo n.º 13
0
 static async Task CopyContainer(CloudBlobContainer sourceContainer, CloudBlobContainer destContainer)
 {
     await sourceContainer.FetchAttributesAsync();
     var access = await sourceContainer.GetPermissionsAsync();
     await destContainer.CreateIfNotExistsAsync(access.PublicAccess, null, null);
     await destContainer.SetPermissionsAsync(access);
     destContainer.Metadata.Clear();
     foreach (var metadatum in sourceContainer.Metadata)
     {
         destContainer.Metadata.Add(metadatum);
     }
     await destContainer.SetMetadataAsync();
 }