GetContainerReference() public method

Returns a reference to a CloudBlobContainer object with the specified address.
public GetContainerReference ( string containerAddress ) : CloudBlobContainer
containerAddress string The name of the container, or an absolute URI to the container.
return CloudBlobContainer
Ejemplo n.º 1
0
        public Storage(CloudStorageAccount account)
        {
            this.account = account;

            fileStorage = account.CreateCloudBlobClient();

            /* Initialize file container */
            container = fileStorage.GetContainerReference(filesContainer);
            container.CreateIfNotExist();

            var permissions = container.GetPermissions();
            /* Full permissions. From MSDN, Container-level public access. Anonymous clients can
             * read blob content and metadata and container metadata, and can list the blobs within the container.
             *
             * Other alternatives are Blob (can read content but not metadata) and Off (no
             * anonymous access).
             */
            // permissions.PublicAccess = BlobContainerPublicAccessType.Container;
            permissions.PublicAccess = BlobContainerPublicAccessType.Off;

            permissions.SharedAccessPolicies.Remove("basic");
            permissions.SharedAccessPolicies.Add("basic", new SharedAccessPolicy()
            {
            });

            container.SetPermissions(permissions);

            /* Initialize table (for file metadata) */
            CloudTableClient.CreateTablesFromModel(
                typeof(FileDataContext),
                account.TableEndpoint.AbsoluteUri,
                account.Credentials);
        }
        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 100;

            //Initialize Indexer
            storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("CrawlerStorage"));

            //Initialize URL Queue
            urlQueueClient = storageAccount.CreateCloudQueueClient();
            urlQueue = urlQueueClient.GetQueueReference("urlqueue");
            if (urlQueue.CreateIfNotExist())
            {
                //Add first URL to the queue
                CloudQueueMessage firstURL = new CloudQueueMessage(startURL);
                urlQueue.AddMessage(firstURL);
            }

            //Initialize Index Queue
            indexQueueClient = storageAccount.CreateCloudQueueClient();
            indexQueue = indexQueueClient.GetQueueReference("indexqueue");
            indexQueue.CreateIfNotExist();

            //Initialize Database Blob
            databaseClient = storageAccount.CreateCloudBlobClient();
            databaseContainer = databaseClient.GetContainerReference("wordfrequencies");
            databaseContainer.CreateIfNotExist();
            var permission = databaseContainer.GetPermissions();
            permission.PublicAccess = BlobContainerPublicAccessType.Container;
            databaseContainer.SetPermissions(permission);

            return base.OnStart();
        }
Ejemplo n.º 3
0
        internal static bool InitializeStorage()
        {
            try
            {
                // 仅为测试目的,如果我们不在计算仿真程序中运行该服务,我们始终使用 dev 存储.
                if (RoleEnvironment.IsAvailable)
                {
                    CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
                    {
                        configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
                    });
                    StorageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
                }
                else
                {
                    StorageAccount = CloudStorageAccount.DevelopmentStorageAccount;
                }

                CloudBlobClient blobClient = new CloudBlobClient(StorageAccount.BlobEndpoint, StorageAccount.Credentials);
                CloudBlobContainer container = blobClient.GetContainerReference("videostories");
                container.CreateIfNotExist();
                CloudQueueClient queueClient = new CloudQueueClient(StorageAccount.QueueEndpoint, StorageAccount.Credentials);
                CloudQueue queue = queueClient.GetQueueReference("videostories");
                queue.CreateIfNotExist();
                CloudTableClient tableClient = new CloudTableClient(StorageAccount.TableEndpoint.AbsoluteUri, StorageAccount.Credentials);
                tableClient.CreateTableIfNotExist("Stories");
                return true;
            }
            catch (Exception ex)
            {
                Trace.Write("错误初始化存储: " + ex.Message, "Error");
                return false;
            }
        }
        /// <summary>
        /// Connect to an Azure subscription and upload a package to blob storage.
        /// </summary>
        protected override void AzureExecute()
        {
            string storageKey = this.StorageKeys.Get(this.ActivityContext).Primary;
            string storageName = this.StorageServiceName.Get(this.ActivityContext);
            string filePath = this.LocalPackagePath.Get(this.ActivityContext);

            var baseAddress = string.Format(CultureInfo.InvariantCulture, ConfigurationConstants.BlobEndpointTemplate, storageName);
            var credentials = new StorageCredentialsAccountAndKey(storageName, storageKey);
            var client = new CloudBlobClient(baseAddress, credentials);

            const string ContainerName = "mydeployments";
            string blobName = string.Format(
                CultureInfo.InvariantCulture,
                "{0}_{1}",
                DateTime.UtcNow.ToString("yyyyMMdd_HHmmss", CultureInfo.InvariantCulture),
                Path.GetFileName(filePath));

            CloudBlobContainer container = client.GetContainerReference(ContainerName);
            container.CreateIfNotExist();
            CloudBlob blob = container.GetBlobReference(blobName);

            UploadBlobStream(blob, filePath);

            this.PackageUrl.Set(this.ActivityContext, string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}", client.BaseUri, ContainerName, client.DefaultDelimiter, blobName));
        }
Ejemplo n.º 5
0
 public AzureOperations(string connectionString)
 {
     CloudStorageAccount account = CloudStorageAccount.Parse(connectionString);
     client = account.CreateCloudBlobClient();
     var container = client.GetContainerReference("$root");
     container.CreateIfNotExist();
 }
Ejemplo n.º 6
0
        //Allows other server code to use the InsertBlobUrl logic.
        //Maximum blob size is 32mb.
        internal static Task<string> InsertBlobUrlHelper(Guid ownerPartyId, Guid fileGuid)
        {
            return AsyncHelper.RunAsync(() =>
            {
                //Create service client for credentialed access to the Blob service.
                var blobClient = new CloudBlobClient(AzureServerHelpers.BlobStorageUrl,
                    new StorageCredentialsAccountAndKey(AzureServerHelpers.AccountName, AzureServerHelpers.AccountKey)) { Timeout = TimeSpan.FromMilliseconds(TimeoutMilliseconds) };

                //Get a reference to a container, which may or may not exist.
                var blobContainer = blobClient.GetContainerReference(AzureServerHelpers.BuildContainerUrl(ownerPartyId));
                //Create a new container, if it does not exist
                blobContainer.CreateIfNotExist(new BlobRequestOptions { Timeout = TimeSpan.FromMilliseconds(TimeoutMilliseconds) });

                //Setup cross domain policy so Silverlight can access the server
                CreateSilverlightPolicy(blobClient);

                //Get a reference to a blob, which may or may not exist.
                var blob = blobContainer.GetBlobReference(fileGuid.ToString());

                blob.UploadByteArray(new byte[] { });

                // Set the metadata into the blob
                blob.Metadata["Submitter"] = ownerPartyId.ToString();
                blob.SetMetadata();

                // Set the properties
                blob.Properties.ContentType = "application/octet-stream";
                blob.SetProperties();

                return blob.GetSharedAccessSignature(new SharedAccessPolicy { Permissions = SharedAccessPermissions.Write, SharedAccessExpiryTime = DateTime.UtcNow + new TimeSpan(0, 30, 0) });
            });
        }
Ejemplo n.º 7
0
        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 12;
            #if DEBUG
            account = CloudStorageAccount.DevelopmentStorageAccount;
            #else
            account = new CloudStorageAccount(accountAndKey, true);
            #endif

            tableContext = new TableServiceContext(account.TableEndpoint.ToString(), account.Credentials);

            //client = new CloudQueueClient(account.BlobEndpoint.ToString(), account.Credentials);
            qclient = account.CreateCloudQueueClient();
            q = qclient.GetQueueReference("icd9mapplotrequests");
            rows = new List<ICD9MapPlotResultEntry>();
            bclient = account.CreateCloudBlobClient();
            container = bclient.GetContainerReference("results");
            container.CreateIfNotExist();
            client = account.CreateCloudTableClient();
            client.CreateTableIfNotExist("ICD9MapPlotResult");
            client.CreateTableIfNotExist("DoctorDetails");
            client.CreateTableIfNotExist("PatientDetails");
            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

            return base.OnStart();
        }
 public static void MyClassInitialize(TestContext testContext)
 {
     CloudStorageAccount storageAccount = CloudStorageAccount.Parse(DevConnectionString);
     blobClient = storageAccount.CreateCloudBlobClient();
     container = blobClient.GetContainerReference(TestContainerName);
     container.CreateIfNotExist();
 }
Ejemplo n.º 9
0
        //This function is using storage client ddl of blob
        public byte[] DownloadBlobClient(string UserId, string BlobName)
        {
            // Retrieve storage account from connection string.
            Microsoft.WindowsAzure.CloudStorageAccount StorageAccount = Microsoft.WindowsAzure.CloudStorageAccount.Parse(Convert.ToString(ConfigurationManager.AppSettings["StorageConnectionString"]));

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

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

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


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


            // Retrieve reference to a blob named

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


            return(blockBlob.DownloadByteArray());
        }
Ejemplo n.º 10
0
        public static Uri UploadFile(string storageName, string storageKey, string filePath)
        {
            var baseAddress = string.Format(CultureInfo.InvariantCulture, ConfigurationConstants.BlobEndpointTemplate, storageName);
            var credentials = new StorageCredentialsAccountAndKey(storageName, storageKey);
            var client = new CloudBlobClient(baseAddress, credentials);

            string containerName = "mydeployments";
            string blobName = string.Format(
                CultureInfo.InvariantCulture,
                "{0}_{1}",
                DateTime.UtcNow.ToString("yyyyMMdd_HHmmss", CultureInfo.InvariantCulture),
                Path.GetFileName(filePath));

            CloudBlobContainer container = client.GetContainerReference(containerName);
            container.CreateIfNotExist();
            CloudBlob blob = container.GetBlobReference(blobName);

            // blob.UploadFile(filePath);
            UploadBlobStream(blob, filePath);

            return new Uri(
                string.Format(
                    CultureInfo.InvariantCulture,
                    "{0}{1}{2}{3}",
                    client.BaseUri,
                    containerName,
                    client.DefaultDelimiter,
                    blobName));
        }
Ejemplo n.º 11
0
        public BlobEntities()
        {
            if (storageInitialized)
            {
                return;
            }

            lock (gate)
            {
                if (storageInitialized)
                {
                    return;
                }
                    // read account configuration settings
                    var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");

                    // create blob container for images
                    blobStorage = storageAccount.CreateCloudBlobClient();
                    CloudBlobContainer container = blobStorage.GetContainerReference("productimages");
                    container.CreateIfNotExist();

                    // configure container for public access
                    var permissions = container.GetPermissions();
                    permissions.PublicAccess = BlobContainerPublicAccessType.Container;
                    container.SetPermissions(permissions);

                storageInitialized = true;
            }
        }
Ejemplo n.º 12
0
        public AzureStorageClient(CloudStorageAccount account)
        {
            client = account.CreateCloudBlobClient();
            client.DefaultDelimiter = "/";

            container = client.GetContainerReference("documents");
            container.CreateIfNotExist();
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Connects to the storage account and creates the default container 
 /// </summary>
 private void ConnectToBlobStorage()
 {
     storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("StorageConnectionString"));
     blobClient = storageAccount.CreateCloudBlobClient();
     blobContainer = blobClient.GetContainerReference("testcontainer");
     blobContainer.CreateIfNotExist();
     blobContainer.SetPermissions(new BlobContainerPermissions() { PublicAccess = BlobContainerPublicAccessType.Blob });
 }
 public AzureSystemEventStore()
 {
     Streamer = new EventStreamer(new EventSerializer(MessagesProvider.GetKnownEventTypes()));
     CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Settings.Default.AzureConnectionString);
     blobClient = storageAccount.CreateCloudBlobClient();
     container = blobClient.GetContainerReference(Settings.Default.AzureContainerName);
     container.CreateIfNotExist();
 }
Ejemplo n.º 15
0
 static AzureHelper()
 {
     var cloudStorageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;AccountName=mintchipmarket;AccountKey=6wtpT0uW75m2LsThfROjp+cMA5zWx8VllZhJ5tM7kPAZZlIbPZ0t7pIXkO0s0AnzZ4sWMnl+rc5+1KjlNWKlfA==");
     var blobClient = new CloudBlobClient(cloudStorageAccount.BlobEndpoint, cloudStorageAccount.Credentials);
     _container = blobClient.GetContainerReference("files");
     _container.CreateIfNotExist();
     _container.SetPermissions(new BlobContainerPermissions() { PublicAccess = BlobContainerPublicAccessType.Off });
 }
Ejemplo n.º 16
0
        public Azure_Stream_Factory(CloudStorageAccount account, string container_Name)
        {
            _container_Name = container_Name;

            _blobClient = account.CreateCloudBlobClient();

            container = _blobClient.GetContainerReference(container_Name);
            container.CreateIfNotExist();
        }
Ejemplo n.º 17
0
 public void deleteFromBlob(string uri, string blobname)
 {
     CloudStorageAccount storageAccount;
     storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("BlobConnectionString"));
     blobClient = storageAccount.CreateCloudBlobClient();
     blobContainer = blobClient.GetContainerReference(blobname);
     var blob = blobContainer.GetBlobReference(uri);
     blob.DeleteIfExists();
 }
Ejemplo n.º 18
0
        public AzureTapeStream(string name, string connectionString, string containerName, ITapeStreamSerializer serializer)
        {
            _serializer = serializer;

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
            blobClient = storageAccount.CreateCloudBlobClient();
            container = blobClient.GetContainerReference(containerName);
            container.CreateIfNotExist();

            _blob = container.GetBlobReference(name);
        }
Ejemplo n.º 19
0
        public AzureBlobRepository()
        {
            var container = CloudConfigurationManager.GetSetting("StorageContainer");           //"queuephotos";
            var connection = CloudConfigurationManager.GetSetting("StorageConnectionString");

            this._storageAccount = CloudStorageAccount.Parse(connection);
            this._blobClient = _storageAccount.CreateCloudBlobClient();
            this._blobContainer = _blobClient.GetContainerReference(container);

            this._blobContainer.SetPermissions(this.GetPermissions());
        }
Ejemplo n.º 20
0
        // ReSharper restore FunctionNeverReturns
        public override bool OnStart()
        {
            ServicePointManager.DefaultConnectionLimit = 12;

            _connectionString = CloudConfigurationManager.GetSetting("StorageConnectionString");
            _storageAccount = CloudStorageAccount.Parse(_connectionString);
            _blobClient = _storageAccount.CreateCloudBlobClient();
            _container = _blobClient.GetContainerReference(BlobContainer);

            RunMeme();

            return base.OnStart();
        }
 public void CreateClientAccessPolicy(CloudBlobClient blobs)
 {
     var root = blobs.GetContainerReference("$root");
     try
     {
         root.Create();
         root.SetPermissions(new BlobContainerPermissions() { PublicAccess = BlobContainerPublicAccessType.Blob });
     }
     catch (StorageException e)
     {
         if (e.ErrorCode == StorageErrorCode.ContainerAlreadyExists)
         {
             Debug.WriteLine("Root container already exists.  Not setting permissions on it.");
         }
         else
         {
             throw;
         }
     }
     var cap = root.GetBlobReference("clientaccesspolicy.xml");
     cap.Properties.ContentType = "text/xml";
     try
     {
         cap.UploadText(@"<?xml version=""1.0"" encoding=""utf-8""?>
                 <access-policy>
                     <cross-domain-access>
                         <policy>
                             <allow-from>
                                 <domain uri=""*"" />
                                 <domain uri=""http://*"" />
                             </allow-from>
                             <grant-to>
                                 <resource path=""/"" include-subpaths=""true"" />
                             </grant-to>
                         </policy>
                     </cross-domain-access>
                 </access-policy>", Encoding.ASCII, new BlobRequestOptions() { AccessCondition = AccessCondition.IfNoneMatch("*") });
         Debug.WriteLine("Wrote ClientAccessPolicy.xml.");
     }
     catch (StorageException e)
     {
         if (e.ErrorCode == StorageErrorCode.BlobAlreadyExists)
         {
             Debug.WriteLine("ClientAccessPolicy.xml already exists.  Not overwriting.");
         }
         else
         {
             throw;
         }
     }
 }
        public void Delete(string fileUrl)
        {
            //Create service client for credentialed access to the Blob service.
            CloudBlobClient blobClient = new CloudBlobClient(blobEndpoint, new StorageCredentialsAccountAndKey(accountName, accountKey));

            //Get a reference to a container, which may or may not exist.
            CloudBlobContainer container = blobClient.GetContainerReference(containerAddress);

            //Get a reference to a blob, which may or may not exist.
            CloudBlob blob = container.GetBlobReference(fileUrl);

            //Upload content to the blob, which will create the blob if it does not already exist.
            blob.DeleteIfExists();
        }
Ejemplo n.º 23
0
        public AzureBlobFileRepository(IConfigSettings configSettings)
        {
            var setting = configSettings.Get("StorageConnectionString");
            containerName = configSettings.Get("BlobContainerName");
            storageAccount = CloudStorageAccount.Parse(setting);
            blobClient = storageAccount.CreateCloudBlobClient();
            container = blobClient.GetContainerReference(containerName.ToLower());

            container.CreateIfNotExist();
            container.SetPermissions(new BlobContainerPermissions
            {
                PublicAccess = BlobContainerPublicAccessType.Blob
            });
        }
        public void DeletePackageBlob(string csPkgFileLocation,
                                      string blobUrl,
                                      string storageAccountName,
                                      string storageAccountKey)
        {
            StorageCredentials storageCredentails;
            CloudBlobClient blobClient;
            CloudBlobContainer packageContainer;

            storageCredentails = new StorageCredentialsAccountAndKey(storageAccountName, storageAccountKey);
            blobClient = new CloudBlobClient(blobUrl, storageCredentails);

            packageContainer = blobClient.GetContainerReference(_cspkgBlobContainerName);
            packageContainer.Delete();
        }
Ejemplo n.º 25
0
        static void CreateContainer()
        {
            //get blob container
            account = CloudStorageAccount.FromConfigurationSetting("BlobConnectionString");
            client = account.CreateCloudBlobClient();
            container = client.GetContainerReference("userphotos");
            container.CreateIfNotExist();

            BlobContainerPermissions permissions = new BlobContainerPermissions()
            {
                PublicAccess = BlobContainerPublicAccessType.Blob
            };

            container.SetPermissions(permissions);
        }
Ejemplo n.º 26
0
        public override bool OnStart()
        {
            //Initialize Indexer
            storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("CrawlerStorage"));

            //Initialize Database Blob
            databaseClient = storageAccount.CreateCloudBlobClient();
            databaseContainer = databaseClient.GetContainerReference("wordfrequencies");
            databaseContainer.CreateIfNotExist();
            var permission = databaseContainer.GetPermissions();
            permission.PublicAccess = BlobContainerPublicAccessType.Container;
            databaseContainer.SetPermissions(permission);

            return base.OnStart();
        }
Ejemplo n.º 27
0
        private static void DownloadVHDFromCloud(Config config)
        {
            StorageCredentialsAccountAndKey creds =
                   new StorageCredentialsAccountAndKey(config.Account, config.Key);

            CloudBlobClient blobStorage = new CloudBlobClient(config.AccountUrl, creds);
            blobStorage.ReadAheadInBytes = 0;

            CloudBlobContainer container = blobStorage.GetContainerReference(config.Container);
            CloudPageBlob pageBlob = container.GetPageBlobReference(config.Blob);

            // Get the length of the blob
            pageBlob.FetchAttributes();
            long vhdLength = pageBlob.Properties.Length;
            long totalDownloaded = 0;
            Console.WriteLine("Vhd size:  " + Megabytes(vhdLength));

            // Create a new local file to write into
            FileStream fileStream = new FileStream(config.Vhd.FullName, FileMode.Create, FileAccess.Write);
            fileStream.SetLength(vhdLength);

            // Download the valid ranges of the blob, and write them to the file
            IEnumerable<PageRange> pageRanges = pageBlob.GetPageRanges();
            BlobStream blobStream = pageBlob.OpenRead();

            foreach (PageRange range in pageRanges)
            {
                // EndOffset is inclusive... so need to add 1
                int rangeSize = (int)(range.EndOffset + 1 - range.StartOffset);

                // Chop range into 4MB chucks, if needed
                for (int subOffset = 0; subOffset < rangeSize; subOffset += FourMegabyteAsBytes)
                {
                    int subRangeSize = Math.Min(rangeSize - subOffset, FourMegabyteAsBytes);
                    blobStream.Seek(range.StartOffset + subOffset, SeekOrigin.Begin);
                    fileStream.Seek(range.StartOffset + subOffset, SeekOrigin.Begin);

                    Console.WriteLine("Range: ~" + Megabytes(range.StartOffset + subOffset)
                                      + " + " + PrintSize(subRangeSize));
                    byte[] buffer = new byte[subRangeSize];

                    blobStream.Read(buffer, 0, subRangeSize);
                    fileStream.Write(buffer, 0, subRangeSize);
                    totalDownloaded += subRangeSize;
                }
            }
            Console.WriteLine("Downloaded " + Megabytes(totalDownloaded) + " of " + Megabytes(vhdLength));
        }
Ejemplo n.º 28
0
        public FriendLikesService(string id)
        {
            this.UserId = id;

            account = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("DataConnectionString"));

            // Table Client
            tableClient = new CloudTableClient(account.TableEndpoint.ToString(), account.Credentials);
            tableClient.CreateTableIfNotExist(FRIEND_LIKES_TABLE);

            // Blob Client
            blobClient = new CloudBlobClient(account.BlobEndpoint.ToString(), account.Credentials);
            blobContainer = blobClient.GetContainerReference(FRIEND_LIKES_BLOB_CONTAINER);
            blobContainer.CreateIfNotExist();
            blobContainer.SetPermissions(new BlobContainerPermissions() { PublicAccess = BlobContainerPublicAccessType.Blob });
        }
Ejemplo n.º 29
0
        protected static Uri UploadFile(String path, TimeSpan timeout)
        {
            Console.WriteLine("Uploading " + path + " to " + StorageContainer + " Blob Storage Container");
            StorageCredentialsAccountAndKey credentials = new StorageCredentialsAccountAndKey(StorageAccount, StorageKey);
            string accountUri = string.Format(AzureBlobUriFormat , StorageAccount);
            CloudBlobClient blobStorage = new CloudBlobClient(accountUri, credentials);
            blobStorage.SingleBlobUploadThresholdInBytes = SingleBlobUploadThresholdInBytes;
            CloudBlobContainer container = blobStorage.GetContainerReference(StorageContainer);
            //TODO: Support container properties
            container.CreateIfNotExist();
            CloudBlob blob = container.GetBlobReference(Path.GetFileName(path));
            BlobRequestOptions options = new BlobRequestOptions();
            options.Timeout = timeout;

            blob.UploadFile(path, options);
            return blob.Uri;
        }
Ejemplo n.º 30
0
        public void WriteData(string container, string blobName, string data)
        {
            StorageCredentialsAccountAndKey creds = new StorageCredentialsAccountAndKey(account, key);
            CloudBlobClient blobStorage = new CloudBlobClient(url, creds);

            // get blob container
            CloudBlobContainer blobContainer = blobStorage.GetContainerReference(container);
            if (blobContainer.CreateIfNotExist())
            {
                // configure container for public access
                var permissions = blobContainer.GetPermissions();
                permissions.PublicAccess = BlobContainerPublicAccessType.Container;
                blobContainer.SetPermissions(permissions);
            }

            CloudBlockBlob blob = blobStorage.GetBlockBlobReference(container + "/" + blobName);
            blob.UploadText(data);
        }
Ejemplo n.º 31
0
    /// <summary>
    /// Init Azure Storage if needed
    /// </summary>
    private static void InitAzureStorage()
    {
      if (storageAccount == null)
      {
        storageAccount = CloudStorageAccount.FromConfigurationSetting(connectionString);

        if (blobClient == null)
        {
          blobClient = storageAccount.CreateCloudBlobClient();
          blobContainer = blobClient.GetContainerReference(FilesFolder);
          blobContainer.CreateIfNotExist();

          var permissions = blobContainer.GetPermissions();
          permissions.PublicAccess = BlobContainerPublicAccessType.Container;
          blobContainer.SetPermissions(permissions);
        }
      }
    }
Ejemplo n.º 32
0
        /// <summary>
        /// Configures Azure account and container
        /// </summary>
        /// <param name="bloburl">string with url to the blob</param>
        /// <param name="connectionString">Azure blob connection string</param>
        public void ConfigureAzure(string bloburl, string connectionString)
        {
            // Azure preparations
            DestinationBlobUrl = bloburl;

            // Set storage account
            cloudStorageAccount = CloudStorageAccount.Parse(connectionString);

            // Initialize client
            blobClient = new Microsoft.WindowsAzure.StorageClient.CloudBlobClient(cloudStorageAccount.BlobEndpoint,
                                                                                  cloudStorageAccount.Credentials);

            // Get the container reference.
            blobContainer = blobClient.GetContainerReference(bloburl);
            // Create the container if it does not exist.
            blobContainer.CreateIfNotExist();

            // Set permissions on the container.
            containerPermissions = new BlobContainerPermissions();
            containerPermissions.PublicAccess = BlobContainerPublicAccessType.Blob;
            blobContainer.SetPermissions(containerPermissions);
        }
Ejemplo n.º 33
0
        public static Tuple <bool, Exception> IsValidAccount(string account, string accountKey)
        {
            bool      accountValid = true;
            Exception exception    = null;

            try
            {
                Microsoft.WindowsAzure.CloudStorageAccount              storageAccount = null;
                Microsoft.WindowsAzure.StorageClient.CloudBlobClient    blobClient     = null;
                Microsoft.WindowsAzure.StorageClient.CloudBlobContainer container      = null;

                storageAccount = new Microsoft.WindowsAzure.CloudStorageAccount(new Microsoft.WindowsAzure.StorageCredentialsAccountAndKey(account, accountKey), true);
                blobClient     = storageAccount.CreateCloudBlobClient();
                container      = blobClient.GetContainerReference(AzureConfigContainerName);
                container.CreateIfNotExist();
            }
            catch (Exception e)
            {
                accountValid = false;
                exception    = e;
            }

            return(new Tuple <bool, Exception>(accountValid, exception));
        }
Ejemplo n.º 34
0
        public static bool UploadConfig(string configZipPath, string AzureAccountName, string AzureAccountKey, string orgID, string studyID, string homeID, string desiredConfigFilename, NLog.Logger logger = null)
        {
            Microsoft.WindowsAzure.CloudStorageAccount              storageAccount = null;
            Microsoft.WindowsAzure.StorageClient.CloudBlobClient    blobClient     = null;
            Microsoft.WindowsAzure.StorageClient.CloudBlobContainer container      = null;
            Microsoft.WindowsAzure.StorageClient.CloudBlockBlob     blockBlob      = null;
            string leaseId = null;

            try
            {
                storageAccount = new Microsoft.WindowsAzure.CloudStorageAccount(new Microsoft.WindowsAzure.StorageCredentialsAccountAndKey(AzureAccountName, AzureAccountKey), true);
                blobClient     = storageAccount.CreateCloudBlobClient();
                container      = blobClient.GetContainerReference(AzureConfigContainerName);
                container.CreateIfNotExist();
                blockBlob = container.GetBlockBlobReference(DesiredConfigBlobName(orgID, studyID, homeID, desiredConfigFilename));

                bool blobExists = BlockBlobExists(blockBlob);

                if (blobExists)
                {
                    leaseId = AcquireLease(blockBlob, logger); // Acquire Lease on Blob
                }
                else
                {
                    blockBlob.Container.CreateIfNotExist();
                }

                if (blobExists && leaseId == null)
                {
                    if (null != logger)
                    {
                        logger.Error("AcquireLease on Blob: " + DesiredConfigBlobName(orgID, studyID, homeID, desiredConfigFilename) + " Failed");
                    }
                    return(false);
                }

                string url = blockBlob.Uri.ToString();
                if (blockBlob.ServiceClient.Credentials.NeedsTransformUri)
                {
                    url = blockBlob.ServiceClient.Credentials.TransformUri(url);
                }

                var req = BlobRequest.Put(new Uri(url), AzureBlobLeaseTimeout, new Microsoft.WindowsAzure.StorageClient.BlobProperties(), Microsoft.WindowsAzure.StorageClient.BlobType.BlockBlob, leaseId, 0);

                using (var writer = new BinaryWriter(req.GetRequestStream()))
                {
                    writer.Write(File.ReadAllBytes(configZipPath));
                    writer.Close();
                }

                blockBlob.ServiceClient.Credentials.SignRequest(req);
                req.GetResponse().Close();
                ReleaseLease(blockBlob, leaseId); // Release Lease on Blob
                return(true);
            }
            catch (Exception e)
            {
                if (null != logger)
                {
                    logger.ErrorException("UploadConfig_Azure, configZipPath: " + configZipPath, e);
                }
                ReleaseLease(blockBlob, leaseId);
                return(false);
            }
        }
Ejemplo n.º 35
0
        public static bool DownloadConfig(string downloadedZipPath, string AzureAccountName, string AzureAccountKey, string orgID, string studyID, string homeID, string configFilename, NLog.Logger logger = null)
        {
            Microsoft.WindowsAzure.CloudStorageAccount              storageAccount = null;
            Microsoft.WindowsAzure.StorageClient.CloudBlobClient    blobClient     = null;
            Microsoft.WindowsAzure.StorageClient.CloudBlobContainer container      = null;
            Microsoft.WindowsAzure.StorageClient.CloudBlockBlob     blockBlob      = null;
            string leaseId = null;

            try
            {
                storageAccount = new Microsoft.WindowsAzure.CloudStorageAccount(new Microsoft.WindowsAzure.StorageCredentialsAccountAndKey(AzureAccountName, AzureAccountKey), true);
                blobClient     = storageAccount.CreateCloudBlobClient();
                container      = blobClient.GetContainerReference(AzureConfigContainerName);

                if (configFilename == PackagerHelper.ConfigPackagerHelper.actualConfigFileName)
                {
                    blockBlob = container.GetBlockBlobReference(ActualConfigBlobName(orgID, studyID, homeID, configFilename));
                }
                else if (configFilename == PackagerHelper.ConfigPackagerHelper.desiredConfigFileName)
                {
                    blockBlob = container.GetBlockBlobReference(DesiredConfigBlobName(orgID, studyID, homeID, configFilename));
                }

                bool blobExists = BlockBlobExists(blockBlob);

                if (blobExists)
                {
                    leaseId = AcquireLease(blockBlob, logger); // Acquire Lease on Blob
                }
                else
                {
                    return(false);
                }

                if (blobExists && leaseId == null)
                {
                    if (null != logger)
                    {
                        logger.Error("AcquireLease on Blob: " + ActualConfigBlobName(orgID, studyID, homeID, configFilename) + " Failed");
                    }
                    return(false);
                }

                string url = blockBlob.Uri.ToString();
                if (blockBlob.ServiceClient.Credentials.NeedsTransformUri)
                {
                    url = blockBlob.ServiceClient.Credentials.TransformUri(url);
                }

                var req = BlobRequest.Get(new Uri(url), AzureBlobLeaseTimeout, null, leaseId);
                blockBlob.ServiceClient.Credentials.SignRequest(req);

                using (var reader = new BinaryReader(req.GetResponse().GetResponseStream()))
                {
                    FileStream zipFile = new FileStream(downloadedZipPath, FileMode.OpenOrCreate);
                    reader.BaseStream.CopyTo(zipFile);
                    zipFile.Close();
                }
                req.GetResponse().GetResponseStream().Close();

                ReleaseLease(blockBlob, leaseId); // Release Lease on Blob
                return(true);
            }
            catch (Exception e)
            {
                if (null != logger)
                {
                    logger.ErrorException("DownloadConfig_Azure, downloadZipPath: " + downloadedZipPath, e);
                }
                ReleaseLease(blockBlob, leaseId);
                return(false);
            }
        }