Example #1
0
        public string DownloadPublicBlob(string UserId, string BlobName, bool PublicAccess = true)
        {
            //Retrieve a reference to a container.
            //Retrieve storage account from connection string.
            Microsoft.WindowsAzure.Storage.CloudStorageAccount StorageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(Convert.ToString(ConfigurationManager.AppSettings["StorageConnectionString"]));

            // Create the blob client.
            Microsoft.WindowsAzure.Storage.Blob.CloudBlobClient blobClient = StorageAccount.CreateCloudBlobClient();

            // Retrieve a reference to a container.
            Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer container = blobClient.GetContainerReference(UserId);

            // Create the container if it doesn't exist.
            container.CreateIfNotExists();


            //Set permission to public
            if (PublicAccess)
            {
                container.SetPermissions(
                    new Microsoft.WindowsAzure.Storage.Blob.BlobContainerPermissions
                {
                    PublicAccess =
                        Microsoft.WindowsAzure.Storage.Blob.BlobContainerPublicAccessType.Blob
                });
            }
            else
            {
                container.SetPermissions(
                    new Microsoft.WindowsAzure.Storage.Blob.BlobContainerPermissions
                {
                    PublicAccess =
                        Microsoft.WindowsAzure.Storage.Blob.BlobContainerPublicAccessType.Off
                });
            }



            // Retrieve reference to a blob named

            Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob blockBlob = container.GetBlockBlobReference(BlobName);

            //var sasToken = blockBlob.GetSharedAccessSignature(new SharedAccessBlobPolicy()
            //{
            //    Permissions = SharedAccessBlobPermissions.Read,
            //    SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(10),//assuming the blob can be downloaded in 10 miinutes
            //}, new SharedAccessBlobHeaders()
            //{
            //    ContentDisposition = "attachment; filename=file-name"
            //});

            //return string.Format("{0}{1}", blockBlob.Uri, sasToken);

            return(blockBlob.Uri.ToString());
        }
Example #2
0
        public BlobContainer(string name)
        {
            // hämta connectionsträngen från config // RoleEnviroment bestämmer settingvalue runtime
            //var connectionString = RoleEnvironment.GetConfigurationSettingValue("PhotoAppStorage");
            //var connectionString = CloudConfigurationManager.GetSetting("CloudStorageApp");
            // hämtar kontot utfrån connectionsträngens värde
            //var account = CloudStorageAccount.Parse(connectionString);

            //var account = CloudStorageAccount.DevelopmentStorageAccount;

            var cred = new StorageCredentials("jholm",
                "/bVipQ2JxjWwYrZQfHmzhaBx1p1s8BoD/wX6VWOmg4/gpVo/aALrjsDUKqzXsFtc9utepPqe65NposrXt9YsyA==");
            var account = new CloudStorageAccount(cred, true);

            // skapar en blobclient
            _client = account.CreateCloudBlobClient();

            m_BlobContainer = _client.GetContainerReference(name);

            // Om det inte finns någon container med det namnet
            if (!m_BlobContainer.Exists())
            {
                // Skapa containern
                m_BlobContainer.Create();
                var permissions = new BlobContainerPermissions()
                {
                    PublicAccess = BlobContainerPublicAccessType.Blob
                };
                // Sätter public access till blobs
                m_BlobContainer.SetPermissions(permissions);
            }
        }
Example #3
0
        /// <summary>
        /// Initiates the SolCat Azure blob data sync.  
        /// </summary>
        public static void CopyBlobData()
        {
            // Authentication Credentials for Azure Storage:
            var credsSrc
                = new StorageCredentials(
                    ConfigHelper.GetConfigValue("HubContainerName"),
                    ConfigHelper.GetConfigValue("HubContainerKey"));

            var credsDest
                = new StorageCredentials(
                    ConfigHelper.GetConfigValue("NodeContainerKey"),
                    ConfigHelper.GetConfigValue("NodeContainerKey"));

            // Source Container: Hub (Development)
            _srcContainer =
                new CloudBlobContainer(
                    new Uri(ConfigHelper.GetConfigValue("HubContainerUri")),
                    credsSrc);

            // Destination Container: Node (Production)
            _destContainer =
                new CloudBlobContainer(
                    new Uri(ConfigHelper.GetConfigValue("NodeContainerUri")),
                    credsDest);

            // Set permissions on the container:
            var permissions = new BlobContainerPermissions {PublicAccess = BlobContainerPublicAccessType.Blob};
            _srcContainer.SetPermissions(permissions);
            _destContainer.SetPermissions(permissions);

            // Call the blob copy master method:
            CopyBlobs(_srcContainer, _destContainer);
        }
Example #4
0
        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections.
            ServicePointManager.DefaultConnectionLimit = 12;

            // Read database connection string and open database.
            var dbConnString = CloudConfigurationManager.GetSetting("TCWAdminPortalDbConnectionString");
            _dbContext = new TCWAdminContext(dbConnString);

            // Open storage account using credentials from .cscfg file.
            var storageAccount = CloudStorageAccount.Parse
                (RoleEnvironment.GetConfigurationSettingValue("StorageConnectionString"));

            Trace.TraceInformation("Creating images blob container");
            var blobClient = storageAccount.CreateCloudBlobClient();
            _imagesBlobContainer = blobClient.GetContainerReference("images");
            if (_imagesBlobContainer.CreateIfNotExists())
            {
                // Enable public access on the newly created "images" container.
                _imagesBlobContainer.SetPermissions(
                    new BlobContainerPermissions
                    {
                        PublicAccess = BlobContainerPublicAccessType.Blob
                    });
            }

            Trace.TraceInformation("Creating images queue");
            CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
            _imagesQueue = queueClient.GetQueueReference("images");
            _imagesQueue.CreateIfNotExists();

            Trace.TraceInformation("Storage initialized");
            return base.OnStart();
        }
        public BlobStorage(BlobSettings appSettings)
        {
            try
            {
                if (appSettings.ImageSize != null)
                    ResizeLayer = new ResizeLayer(appSettings.ImageSize, ResizeMode.Min);

                UploadThumbnail = appSettings.UploadThumbnail;

                StorageAccountName = appSettings.StorageAccountName;
                StorageAccountAccessKey = appSettings.StorageAccountAccessKey;

                // Create a blob client and retrieve reference to images container
                BlobClient = StorageAccount.CreateCloudBlobClient();
                Container = BlobClient.GetContainerReference(appSettings.ContainerName);

                // Create the "images" container if it doesn't already exist.
                if (Container.CreateIfNotExists())
                {
                    // Enable public access on the newly created "images" container
                    Container.SetPermissions(
                        new BlobContainerPermissions
                        {
                            PublicAccess =
                                BlobContainerPublicAccessType.Blob
                        });
                }

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }
        public AzureFileSystem(string containerName, string root, bool isPrivate, CloudStorageAccount storageAccount) {
            // Setup the connection to custom storage accountm, e.g. Development Storage
            _storageAccount = storageAccount;
            ContainerName = containerName;
            _root = String.IsNullOrEmpty(root) ? "": root + "/";
            _absoluteRoot = Combine(Combine(_storageAccount.BlobEndpoint.AbsoluteUri, containerName), _root);

            //using ( new HttpContextWeaver() ) 
            {

                BlobClient = _storageAccount.CreateCloudBlobClient();
                // Get and create the container if it does not exist
                // The container is named with DNS naming restrictions (i.e. all lower case)
                Container = BlobClient.GetContainerReference(ContainerName);

                Container.CreateIfNotExists();

                Container.SetPermissions(isPrivate
                                             ? new BlobContainerPermissions
                                                   {PublicAccess = BlobContainerPublicAccessType.Off}
                                             : new BlobContainerPermissions
                                                   {PublicAccess = BlobContainerPublicAccessType.Blob}); // deny listing 
            }

        }
 protected void SetContainerPermission(CloudBlobContainer container, BlobContainerPublicAccessType perimssion)
 {
     container.SetPermissions(new BlobContainerPermissions
     {
         PublicAccess = perimssion
     });
 }
Example #8
0
 public void InitializeContainer(string container)
 {
     var blobClient = StorageAccount.CreateCloudBlobClient();
     blobContainer = blobClient.GetContainerReference(container);
     blobContainer.CreateIfNotExists();
     blobContainer.SetPermissions(new BlobContainerPermissions() { PublicAccess = BlobContainerPublicAccessType.Blob });
 }
Example #9
0
        public HomeController()
        {
            storageAccount = CloudStorageAccount.Parse(
            ConfigurationManager.AppSettings["StorageConnectionString"]);

            tableClient = storageAccount.CreateCloudTableClient();

            table = tableClient.GetTableReference("fouramigos");

            table.CreateIfNotExists();

            blobClient = storageAccount.CreateCloudBlobClient();

            container = blobClient.GetContainerReference("fouramigos");

            container.CreateIfNotExists();

            BlobContainerPermissions permissions = container.GetPermissions();
            permissions.PublicAccess = BlobContainerPublicAccessType.Container;
            container.SetPermissions(permissions);


            //lägga till nya
            //var tablemodels = new TableModel("Brutus", "Uggla") { Location = "T4", Description="Uggla i träd", Type="Foto" };
            //var tablemodels1 = new TableModel("brutus", "Örn") { Location = "T4", Description="Örn som flyger", Type = "Foto" };

            //var opreation = TableOperation.Insert(tablemodels);
            //var operation2 = TableOperation.Insert(tablemodels1);

            //table.Execute(opreation);
            //table.Execute(operation2);
        }
Example #10
0
 public async Task OpenAsync(PartitionContext context)
 {
     if (!WebJobsHelper.RunAsWebJobs)
         Console.WriteLine(string.Format("EventProcessor initialization. Partition: '{0}', Offset: '{1}'",
             context.Lease.PartitionId, context.Lease.Offset));
     partitionContext = context;
     var retries = 3;
     while (retries > 0)
     {
         var s = string.Empty;
         try
         {
             retries--;
             s = "storage";
             storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["SigfoxDemoStorage"].ConnectionString);
             var blobClient = storageAccount.CreateCloudBlobClient();
             blobContainer = blobClient.GetContainerReference("device");
             blobContainer.SetPermissions(new BlobContainerPermissions() { PublicAccess = BlobContainerPublicAccessType.Off });
             blobContainer.CreateIfNotExists();
             s = "cache";
             cacheConnection = await ConnectionMultiplexer.ConnectAsync(ConfigurationManager.ConnectionStrings["SigfoxDemoCache"].ConnectionString);
             cacheDatabase = cacheConnection.GetDatabase();
             s = "database";
             sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SigfoxDemoDatabase"].ConnectionString);
             sqlConnection.Open();
             sqlCommand = new SqlCommand("InsertMessage", sqlConnection) { CommandType = CommandType.StoredProcedure };
             sqlCommand.Parameters.Add(new SqlParameter("@Device", SqlDbType.VarChar));
             sqlCommand.Parameters.Add(new SqlParameter("@Data", SqlDbType.VarChar));
             sqlCommand.Parameters.Add(new SqlParameter("@Mode", SqlDbType.TinyInt));
             sqlCommand.Parameters.Add(new SqlParameter("@Periode", SqlDbType.TinyInt));
             sqlCommand.Parameters.Add(new SqlParameter("@FrameType", SqlDbType.TinyInt));
             sqlCommand.Parameters.Add(new SqlParameter("@Battery", SqlDbType.Float));
             sqlCommand.Parameters.Add(new SqlParameter("@Temperature", SqlDbType.Float));
             sqlCommand.Parameters.Add(new SqlParameter("@Humidity", SqlDbType.Float));
             sqlCommand.Parameters.Add(new SqlParameter("@ILS", SqlDbType.Bit));
             sqlCommand.Parameters.Add(new SqlParameter("@Light", SqlDbType.Float));
             sqlCommand.Parameters.Add(new SqlParameter("@Version", SqlDbType.VarChar));
             sqlCommand.Parameters.Add(new SqlParameter("@AlertCount", SqlDbType.Int));
             sqlCommand.Parameters.Add(new SqlParameter("@TimeStamp", SqlDbType.DateTime));
             sqlCommand.Parameters.Add(new SqlParameter("@Duplicate", SqlDbType.Bit));
             sqlCommand.Parameters.Add(new SqlParameter("@Signal", SqlDbType.Float));
             sqlCommand.Parameters.Add(new SqlParameter("@Station", SqlDbType.VarChar));
             sqlCommand.Parameters.Add(new SqlParameter("@AvgSignal", SqlDbType.Float));
             sqlCommand.Parameters.Add(new SqlParameter("@Latitude", SqlDbType.Float));
             sqlCommand.Parameters.Add(new SqlParameter("@Longitude", SqlDbType.Float));
             sqlCommand.Parameters.Add(new SqlParameter("@Rssi", SqlDbType.Float));
             sqlCommand.Parameters.Add(new SqlParameter("@SeqNumber", SqlDbType.Int));
             retries = 0;
         }
         catch (Exception e)
         {
             Console.Error.WriteLine("Error opening destination Event Hub: " + e.Message + "(" + s + ")");
             if (retries == 0)
                 throw;
         }
     }
     checkpointStopWatch = new Stopwatch();
     checkpointStopWatch.Start();
 }
 public StorageBlob.CloudBlobContainer CreateContainer(string containerName, StorageBlob.BlobContainerPublicAccessType permission)
 {
     StorageBlob.CloudBlobContainer       container           = CreateContainer(containerName);
     StorageBlob.BlobContainerPermissions containerPermission = new StorageBlob.BlobContainerPermissions();
     containerPermission.PublicAccess = permission;
     container.SetPermissions(containerPermission);
     return(container);
 }
Example #12
0
 public BlobHelper(String container)
 {
     // get or create blobContainer to communicate with Azure storage service
     var blobClient = StorageAccount.CreateCloudBlobClient();
     blobContainer = blobClient.GetContainerReference(container);
     blobContainer.CreateIfNotExists();
     blobContainer.SetPermissions(new BlobContainerPermissions() { PublicAccess = BlobContainerPublicAccessType.Blob });
 }
 public void setPublicPermissions(CloudBlobContainer container, BlobContainerPublicAccessType Level)
 {
     container.SetPermissions(
         new BlobContainerPermissions
         {
             PublicAccess = Level
         });
 }
Example #14
0
 public void createContainer()
 {
     container = blobClient.GetContainerReference(Constants.blobContainerName);
     if (container.CreateIfNotExists())
     {
         container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
     }
 }
 public PhotoInBlob()
 {
     storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["StorageConnection"].ConnectionString);
     blobClinet = storageAccount.CreateCloudBlobClient();
     blobContainer = blobClinet.GetContainerReference(ConfigurationManager.AppSettings["blobContainer"].ToString());
     if(blobContainer.CreateIfNotExists())
     {
         blobContainer.SetPermissions(new BlobContainerPermissions() { PublicAccess = BlobContainerPublicAccessType.Blob });
     }
 }
        public AzureFileSystem(CloudBlobContainer container)
        {
            // this is not the constructor you're looking for

            this.container = container;
            container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Container });

            container.CreateIfNotExists();

            CreateDirectory("");
        }
        public AzureFileSystem(ISessionProvider sessionProvider, DatabaseSection config)
        {
            var storageAccount = CloudStorageAccount.Parse(
                ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString);

            this.container = storageAccount.CreateCloudBlobClient().GetContainerReference("le-upload");

            container.CreateIfNotExists();
            container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Container });

            CreateDirectory("/upload/");
        }
Example #18
0
        /// <summary>
        /// Assign permissions for a download to occur for our readonly permission policy
        /// </summary>
        static void AssignDownloadPolicyContainerPermissions(CloudBlobContainer container)
        {
            // Secure storage. We will provide read tokens for access to blob data on a per-blob basis.
            var containerPermissions = new BlobContainerPermissions();
            containerPermissions.PublicAccess = BlobContainerPublicAccessType.Off;
            containerPermissions.SharedAccessPolicies.Add(DownloadPolicyName, new SharedAccessBlobPolicy
            {
                Permissions = SharedAccessBlobPermissions.Read
            });

            container.SetPermissions(containerPermissions);
        }
Example #19
0
        /// <summary>
        /// Returns the Url of the given File object
        /// </summary>
        public static string GetImageUrl(Models.File file)
        {
            _container = _blobClient.GetContainerReference(file.Container);
            _container.CreateIfNotExists();
            _container.SetPermissions(
                new BlobContainerPermissions
                {
                    PublicAccess = BlobContainerPublicAccessType.Blob
                });

            return _container.GetBlockBlobReference(file.Key).Uri.ToString();
        }
Example #20
0
        //Retrieve Blob Container
        public Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer GetCloudBlobContainer(string ContainerName, Boolean PublicAccess = false)
        {
            // Retrieve storage account from connection string.
            Microsoft.WindowsAzure.Storage.CloudStorageAccount StorageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(Convert.ToString(ConfigurationManager.AppSettings["StorageConnectionString"]));

            // Create the blob client.
            Microsoft.WindowsAzure.Storage.Blob.CloudBlobClient blobClient = StorageAccount.CreateCloudBlobClient();

            // Retrieve a reference to a container.
            Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer container = blobClient.GetContainerReference(ContainerName);

            // Create the container if it doesn't exist.
            container.CreateIfNotExists();


            //Set permission to public
            if (PublicAccess)
            {
                container.SetPermissions(
                    new Microsoft.WindowsAzure.Storage.Blob.BlobContainerPermissions
                {
                    PublicAccess =
                        Microsoft.WindowsAzure.Storage.Blob.BlobContainerPublicAccessType.Blob
                });
            }
            else
            {
                container.SetPermissions(
                    new Microsoft.WindowsAzure.Storage.Blob.BlobContainerPermissions
                {
                    PublicAccess =
                        Microsoft.WindowsAzure.Storage.Blob.BlobContainerPublicAccessType.Off
                });
            }

            return(container);
        }
		/// <summary>
		/// Creates a new BlobStorage object
		/// </summary>
		/// <param name="blobContainerName">The name of the blob to be managed</param>
		/// <param name="storageConnectionString">The connection string pointing to the storage account (this can be local or hosted in Windows Azure</param>
		public BlobStorageAsync(string blobContainerName, string storageConnectionString)
		{
			Validate.BlobContainerName(blobContainerName, "blobContainerName");
			Validate.String(storageConnectionString, "storageConnectionString");

			var cloudStorageAccount = CloudStorageAccount.Parse(storageConnectionString);
			var cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();

			cloudBlobContainer = cloudBlobClient.GetContainerReference(blobContainerName);
			cloudBlobContainer.CreateIfNotExists();

			var permissions = cloudBlobContainer.GetPermissions();
			permissions.PublicAccess = BlobContainerPublicAccessType.Container;
			cloudBlobContainer.SetPermissions(permissions);
		}
Example #22
0
        public FileService()
        {
            var storageAccount =
                CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));

            var blobClient = storageAccount.CreateCloudBlobClient();

            _container = blobClient.GetContainerReference(CloudConfigurationManager.GetSetting("FileContainer"));
            _container.CreateIfNotExists();
            _container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Off });

            _publicContainer = blobClient.GetContainerReference(CloudConfigurationManager.GetSetting("PublicImageContainer"));
            _publicContainer.CreateIfNotExists();
            _publicContainer.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Container });
        }
        public BlobStoargeService()
        {
            var storageConnectionString =
            string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}",
                  CloudConfigurationManager.GetSetting("AzureStorageAccountName"),
                  CloudConfigurationManager.GetSetting("AzureStorageKey"));

            var storageAccount = CloudStorageAccount.Parse(storageConnectionString);

            var blobClient = storageAccount.CreateCloudBlobClient();

            _container = blobClient.GetContainerReference(CloudConfigurationManager.GetSetting("AzureContainerName"));
            _container.CreateIfNotExists();
            _container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Off });
        }
Example #24
0
        // Overriding OnStartup to be able to store azure-specific data outside the logic.
        // Data is reachable in code through (App.Current as App).[variable]
        protected override async void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            csa = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("stacConnectionString"));
            cbc = csa.CreateCloudBlobClient();
            blobcontainer = cbc.GetContainerReference("lexiconblobs");
            bro.RetryPolicy = new LinearRetry(TimeSpan.FromSeconds(2), 3);
            // If connection is established
            if (await checkConnection())
            {
                blobcontainer.CreateIfNotExists();
                blobcontainer.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
                ping = getPing();//await checkConnection();
            }
        }
Example #25
0
        public FileService(IRepositoryWithTypedId<Attachment, Guid> attachmentRepository)
        {
            _attachmentRepository = attachmentRepository;

            var storageConnectionString =
                string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}",
                              CloudConfigurationManager.GetSetting("AzureStorageAccountName"),
                              CloudConfigurationManager.GetSetting("AzureStorageKey"));

            var storageAccount = CloudStorageAccount.Parse(storageConnectionString);

            var blobClient = storageAccount.CreateCloudBlobClient();

            _container = blobClient.GetContainerReference("oppattachments");
            _container.CreateIfNotExists();
            _container.SetPermissions(new BlobContainerPermissions {PublicAccess = BlobContainerPublicAccessType.Off});
        }
		public static void Create(string account, string key, string containerName, bool publicAccess)
		{
			if (string.IsNullOrEmpty(containerName))
				return;

			CloudBlobClient blobClient = Client.GetBlobClient(account, key);
			Uri uri = new Uri(string.Format(blobClient.BaseUri + "{0}", containerName));
			CloudBlobContainer cont = new CloudBlobContainer(uri, blobClient.Credentials);
			cont.Create();

			if (publicAccess)
			{
				BlobContainerPermissions permissions = new BlobContainerPermissions();
				permissions.PublicAccess = BlobContainerPublicAccessType.Container;
				cont.SetPermissions(permissions);
			}
		}
Example #27
0
        static void CreateSharedAccessPolicy(CloudBlobClient blobClient, CloudBlobContainer container, string policyName)
        {
            //Create a new stored access policy and define its constraints.
            SharedAccessBlobPolicy sharedPolicy = new SharedAccessBlobPolicy()
            {
                SharedAccessExpiryTime = DateTime.UtcNow.AddHours(10),
                Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.List
            };

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

            //Add the new policy to the container's permissions.
            permissions.SharedAccessPolicies.Clear();
            permissions.SharedAccessPolicies.Add(policyName, sharedPolicy);
            container.SetPermissions(permissions);
        }
        public void Initialize()
        {
            string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

            CloudStorageAccount account = CloudStorageAccount.Parse(connectionString);

            CloudBlobClient client = account.CreateCloudBlobClient();

            Container = client.GetContainerReference("images");
            Container.CreateIfNotExists();

            Container.SetPermissions(
                new BlobContainerPermissions
                {
                    PublicAccess =
                        BlobContainerPublicAccessType.Blob
                });
        }
Example #29
0
        public void CloudBlobContainerSetPermissions()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                container.Create();

                BlobContainerPermissions permissions = container.GetPermissions();
                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,
                });
                container.SetPermissions(permissions);
                Thread.Sleep(30 * 1000);

                CloudBlobContainer container2 = container.ServiceClient.GetContainerReference(container.Name);
                permissions = container2.GetPermissions();
                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.DeleteIfExists();
            }
        }
Example #30
0
        /// <summary>
        /// Receives the users Id for where the pictures are and creates 
        /// a blob storage with that name if it does not exist.
        /// </summary>
        /// <param name="DirecoryUrl"></param>
        public BlobRepo(string DirecoryUrl)
        {
            this._direcoryUrl = DirecoryUrl;
            // Create the blob client.
            _blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve a reference to a container. 
            _container = _blobClient.GetContainerReference(DirecoryUrl);

            // Create the container if it doesn't already exist.
            _container.CreateIfNotExists();

            //Make available to everyone
            _container.SetPermissions(
                new BlobContainerPermissions
                {
                    PublicAccess = BlobContainerPublicAccessType.Blob
                });
        }
        /// <summary>
        /// Creates a new Shared Access Policy for the container
        /// </summary>
        /// <param name="blobClient">The blob client to use for this operation</param>
        /// <param name="container">The container to create the policy for</param>
        /// <param name="policyName">The name of the policy</param>
        static void CreateSharedAccessPolicy(CloudBlobClient blobClient, CloudBlobContainer container,
    string policyName)
        {
            //Create a new shared access policy and define its constraints.
            SharedAccessBlobPolicy sharedPolicy = new SharedAccessBlobPolicy()
            {
                // What is the expiration date of this policy?
                SharedAccessExpiryTime = DateTime.UtcNow.AddYears(1),
                // What permissions does this policy grant?
                Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.List
            };

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

            //Add the new policy to the container's permissions, and set the container's permissions.
            permissions.SharedAccessPolicies.Add(policyName, sharedPolicy);
            container.SetPermissions(permissions);
        }
        public AzurePictureService(IRepository<Picture> pictureRepository,
            IRepository<ProductPicture> productPictureRepository,
            IRepository<Product> productRepository,
            ISettingService settingService,
            IWebHelper webHelper,
            ILogger logger,
            IDbContext dbContext,
            IEventPublisher eventPublisher,
            MediaSettings mediaSettings,
            NopConfig config)
            : base(pictureRepository,
                productPictureRepository,
                productRepository,
                settingService,
                webHelper,
                logger,
                dbContext,
                eventPublisher,
                mediaSettings)
        {
            this._config = config;

            if (String.IsNullOrEmpty(_config.AzureBlobStorageConnectionString))
                throw new Exception("Azure connection string for BLOB is not specified");
            if (String.IsNullOrEmpty(_config.AzureBlobStorageContainerName))
                throw new Exception("Azure container name for BLOB is not specified");
            if (String.IsNullOrEmpty(_config.AzureBlobStorageEndPoint))
                throw new Exception("Azure end point for BLOB is not specified");

            _storageAccount = CloudStorageAccount.Parse(_config.AzureBlobStorageConnectionString);
            if (_storageAccount == null)
                throw new Exception("Azure connection string for BLOB is not wrong");

            //should we do it for each HTTP request?
            blobClient = _storageAccount.CreateCloudBlobClient();
            BlobContainerPermissions containerPermissions = new BlobContainerPermissions();
            containerPermissions.PublicAccess = BlobContainerPublicAccessType.Blob;
            //container.SetPermissions(containerPermissions);
            container_thumb = blobClient.GetContainerReference(_config.AzureBlobStorageContainerName);
            container_thumb.CreateIfNotExists();
            container_thumb.SetPermissions(containerPermissions);
        }
        /// <summary>
        /// Create the container if it doesn't already exist
        /// and changes its permissions to public.
        /// </summary>
        /// <param name="name">Name of the container. 
        /// Must be a valid DNS name</param>
        private static void CreatePublicContainer(string name)
        {
            container = blobClient.GetContainerReference(name);

            // Create the container if it doesn't already exist.
            container.CreateIfNotExists();

            // By default, the new container is private and you must
            // specify your storage access key to download blobs
            container.SetPermissions(
                new BlobContainerPermissions
                {
                    PublicAccess = BlobContainerPublicAccessType.Blob
                });

            Console.WriteLine("{0} created!", name);
            Console.WriteLine("Press any key to continue ...");
            Console.ReadKey();
            Console.Clear();
        }
Example #34
0
 public ImageService()
 {
     CloudStorageAccount storageAccount;
     // Retrieve storage account from connection string.
     if (CloudStorageAccount.TryParse(RoleEnvironment.GetConfigurationSettingValue("ImageStorageAccountConnection"), out storageAccount))
     {
         // Create the blob client.
         CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
         // Retrieve a reference to a container.
         _container = blobClient.GetContainerReference("blobContainer");
         if (_container.CreateIfNotExists())
         {
             _container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
         }
     }
     else
     {
         throw new ApplicationException("Could not find ImageStorageAccountConnection setting");
     }
 }
        public void ProcessMedia()
        {
            // Run the thumbnail job.
            var asset = RunVideoThumbnailJob((string)_mediaObject["mediaName"], "config.json");

            if (asset != null)
            {
                Uri blobUri = new Uri(asset.Uri.ToString());
                Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer container = new Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer(blobUri, _blobCredentials);

                BlobContainerPermissions permissions = container.GetPermissions();
                permissions.PublicAccess = BlobContainerPublicAccessType.Container;
                container.SetPermissions(permissions);
                var summaryVideoUrl = container.Uri.OriginalString + "/" + asset.AssetFiles.FirstOrDefault().Name;
                _log.Info($"Granted public access to {summaryVideoUrl}");

                _dbContext.UpdateSummaryUrl((int)_mediaObject["mediaId"], summaryVideoUrl);
            }
            else
            {
                _log.Info($"No assets found for media name: {_mediaObject["mediaName"]}");
            }
        }
Example #36
0
        private static void CloudBlockBlobCopy(bool sourceIsSas, bool destinationIsSas)
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                container.Create();

                // Create Source on server
                CloudBlockBlob source = container.GetBlockBlobReference("source");

                string data = "String data";
                UploadText(source, data, Encoding.UTF8);

                source.Metadata["Test"] = "value";
                source.SetMetadata();

                // Create Destination on server
                CloudBlockBlob destination = container.GetBlockBlobReference("destination");
                destination.PutBlockList(new string[] { });

                CloudBlockBlob copySource      = source;
                CloudBlockBlob copyDestination = destination;

                if (sourceIsSas)
                {
                    // Source SAS must have read permissions
                    SharedAccessBlobPermissions permissions = SharedAccessBlobPermissions.Read;
                    SharedAccessBlobPolicy      policy      = new SharedAccessBlobPolicy()
                    {
                        SharedAccessStartTime  = DateTimeOffset.UtcNow.AddMinutes(-5),
                        SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                        Permissions            = permissions,
                    };
                    string sasToken = source.GetSharedAccessSignature(policy);

                    // Get source
                    StorageCredentials credentials = new StorageCredentials(sasToken);
                    copySource = new CloudBlockBlob(credentials.TransformUri(source.Uri));
                }

                if (destinationIsSas)
                {
                    if (!sourceIsSas)
                    {
                        // Source container must be public if source is not SAS
                        BlobContainerPermissions containerPermissions = new BlobContainerPermissions
                        {
                            PublicAccess = BlobContainerPublicAccessType.Blob
                        };
                        container.SetPermissions(containerPermissions);
                    }

                    // Destination SAS must have write permissions
                    SharedAccessBlobPermissions permissions = SharedAccessBlobPermissions.Write;
                    SharedAccessBlobPolicy      policy      = new SharedAccessBlobPolicy()
                    {
                        SharedAccessStartTime  = DateTimeOffset.UtcNow.AddMinutes(-5),
                        SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                        Permissions            = permissions,
                    };
                    string sasToken = destination.GetSharedAccessSignature(policy);

                    // Get destination
                    StorageCredentials credentials = new StorageCredentials(sasToken);
                    copyDestination = new CloudBlockBlob(credentials.TransformUri(destination.Uri));
                }

                // Start copy and wait for completion
                string copyId = copyDestination.StartCopyFromBlob(TestHelper.Defiddler(copySource));
                WaitForCopy(destination);

                // Check original blob references for equality
                Assert.AreEqual(CopyStatus.Success, destination.CopyState.Status);
                Assert.AreEqual(source.Uri.AbsolutePath, destination.CopyState.Source.AbsolutePath);
                Assert.AreEqual(data.Length, destination.CopyState.TotalBytes);
                Assert.AreEqual(data.Length, destination.CopyState.BytesCopied);
                Assert.AreEqual(copyId, destination.CopyState.CopyId);
                Assert.IsTrue(destination.CopyState.CompletionTime > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1)));

                if (!destinationIsSas)
                {
                    // Abort Copy is not supported for SAS destination
                    TestHelper.ExpectedException(
                        () => copyDestination.AbortCopy(copyId),
                        "Aborting a copy operation after completion should fail",
                        HttpStatusCode.Conflict,
                        "NoPendingCopyOperation");
                }

                source.FetchAttributes();
                Assert.IsNotNull(destination.Properties.ETag);
                Assert.AreNotEqual(source.Properties.ETag, destination.Properties.ETag);
                Assert.IsTrue(destination.Properties.LastModified > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1)));

                string copyData = DownloadText(destination, Encoding.UTF8);
                Assert.AreEqual(data, copyData, "Data inside copy of blob not equal.");

                destination.FetchAttributes();
                BlobProperties prop1 = destination.Properties;
                BlobProperties prop2 = source.Properties;

                Assert.AreEqual(prop1.CacheControl, prop2.CacheControl);
                Assert.AreEqual(prop1.ContentEncoding, prop2.ContentEncoding);
                Assert.AreEqual(prop1.ContentLanguage, prop2.ContentLanguage);
                Assert.AreEqual(prop1.ContentMD5, prop2.ContentMD5);
                Assert.AreEqual(prop1.ContentType, prop2.ContentType);

                Assert.AreEqual("value", destination.Metadata["Test"], false, "Copied metadata not same");

                destination.Delete();
                source.Delete();
            }
            finally
            {
                container.DeleteIfExists();
            }
        }