public Tracker(string accountName, string keyValue)
        {
            _applicationId = IdUtil.ApplicationId();
            _deviceId = IdUtil.DeviceId();
            _anid = IdUtil.GetAnidFromOs();
            _appTitle = IdUtil.ApplicationName();
            _adsRefreshRate = 3;
            _pubCenterAdsId = new List<string>();
            _adsReady = false;

            // Due to Disallowed key in RowKey, /, \, #, ? needs to be removed
            // And excel cannot allow "=" at the beginning
            foreach (var s in _invalidRowKeyChar) {
                _deviceId = _deviceId.Replace(s, string.Empty);
                if (_deviceId.Substring(0, 1) == "=") {
                    _deviceId = "x" + _deviceId;
                }
            }

            GetAdAssemblyVersion();
            RefreshIpInfo();

            _storageCredentials = new StorageCredentials(accountName, keyValue);
            _storageAccount = new CloudStorageAccount(_storageCredentials, false);
            _tableClient = _storageAccount.CreateCloudTableClient();

            EnsureTablesCreated();
        }
Ejemplo n.º 2
0
        void RemoveFromTable()
        {
            try
            {
                //Setup connection to the azure table
                Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["TableConnectionString"].ConnectionString);
                CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
                CloudTable       entryTable  = tableClient.GetTableReference(tableName);

                //Query all rows then calls them to be deleted
                var entities = entryTable.ExecuteQuery(new TableQuery <DynamicTableEntity>()).ToList();
                foreach (var row in entities)
                {
                    TableOperation deleteOP = TableOperation.Delete(row);
                    entryTable.ExecuteAsync(deleteOP);
                }

                //Print update status to user
                Results1.Text += "<br />Removed from Azure Table";
            }
            catch (Exception ex)
            {
                Error1.Text = "Failed to remove from table";
            }
        }
Ejemplo n.º 3
0
 public TestDataController()
 {
     _storageAccount = ControllerUtil.CreateStorageAccount();
     _storage = new TestResultStorage(_storageAccount);
     _stats = new TestCacheStats(_storage, _storageAccount.CreateCloudTableClient());
     _statsUtil = ControllerUtil.GetOrCreateCounterStatsUtil(_storageAccount);
 }
        public CloudBlobContainer GetBlobContainer(string container)
        {
            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(
                StorageConnectionString);

            ServicePoint tableServicePoint = ServicePointManager.FindServicePoint(storageAccount.TableEndpoint);

            tableServicePoint.UseNagleAlgorithm = false;

            Microsoft.WindowsAzure.Storage.Blob.CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve a reference to a container.
            CloudBlobContainer blobContainer = blobClient.GetContainerReference(container);

            // Create the container if it doesn't already exist.
            blobContainer.CreateIfNotExistsAsync().Wait();

            blobContainer.SetPermissionsAsync(
                new BlobContainerPermissions
            {
                PublicAccess =
                    BlobContainerPublicAccessType.Blob
            }).Wait();

            return(blobContainer);
        }
Ejemplo n.º 5
0
        public void Cleanup()
        {
            StorageCredentials storageCredentials = new StorageCredentials(storageAccountName, storageAccessKey);
            CloudStorageAccount account = new CloudStorageAccount(storageCredentials, true);

            CloudBlobClient blobClient = account.CreateCloudBlobClient();

            CloudBlobContainer container = blobClient.GetContainerReference(containerName);

            Console.WriteLine("Deleting blob storage files in {0}/{1} older than {2} days", storageAccountName, containerName, minDaysOld);

            DateTime referenceDate = DateTime.UtcNow;
            var blobQuery = from b in container.ListBlobs(null, recursive).OfType<ICloudBlob>()
                            where b.Properties.LastModified <= referenceDate.AddDays(-minDaysOld)
                            select b;

            var blobList = blobQuery.ToList();

            if (blobList.Count == 0)
            {
                Console.WriteLine("No files found in {0}/{1} older than {2} days", storageAccountName, containerName, minDaysOld);
                return;
            }

            foreach (ICloudBlob blob in blobList)
            {
                double blobAgeInDays = (referenceDate - blob.Properties.LastModified.Value).TotalDays;
                Console.WriteLine("Deleting blob storage file {0}/{1}, {2} days old", containerName, blob.Name, Math.Round(blobAgeInDays, 3));
                blob.DeleteIfExists();
            }

            Console.WriteLine("{0} blob storage files deleted in {1}/{2} older than {3} days", blobList.Count, storageAccountName, containerName, minDaysOld);
        }
Ejemplo n.º 6
0
        public CloudBlobContainer GetCloudBlobContainer()
        {
            // Retrieve storage account from connection-string
            //    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
            //CloudConfigurationManager.GetSetting("StorageConnectionString"));
            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("StorageConnectionString"));

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

            // Retrieve a reference to a container

            CloudBlobContainer blobContainer = blobClient.GetContainerReference(ContainerName);

            blobContainer.CreateIfNotExists();

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

            return(blobContainer);
        }
Ejemplo n.º 7
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string          requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            StockNamesModel data        = JsonConvert.DeserializeObject <StockNamesModel>(requestBody);


            if (data.stockNames == null || data.stockNames.Count <= 0)
            {
                return(new BadRequestResult());
            }

            var connectionString = "DefaultEndpointsProtocol=https;AccountName=storageaccount4471b6a6;AccountKey=dX2VUCuxC0EcRnyZ7Srg+XIKLLagAO30kkpcBcsv9bq91rG+h2FomX6EHP/IByNzKSxVdRIqq6phUYDQ3PAPnw==;EndpointSuffix=core.windows.net";

            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
            CloudTable       table       = tableClient.GetTableReference("stocksinfo");


            var comparisonList = new StockComparisonInfo();

            foreach (var s in data.stockNames)
            {
                var info = StockSummary.GetSummary(table, s);
                comparisonList.StockSummaries.Add(info);
            }

            return(new OkObjectResult(JsonConvert.SerializeObject(comparisonList)));
        }
        internal void UploadFromString(string accountName, string accountKey, string containerName, string fileName, string sourceFileName, string fileContentType, string content)   //, string name, string fileDescription) {
        {
            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount =
                Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(
                    string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1};BlobEndpoint=https://{0}.blob.core.windows.net/", accountName, accountKey)
                    );
            Microsoft.WindowsAzure.Storage.Blob.CloudBlobClient    blobClient = storageAccount.CreateCloudBlobClient();
            Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer container  = blobClient.GetContainerReference(containerName);
            container.CreateIfNotExists();
            string ext = System.IO.Path.GetExtension(sourceFileName);

            //string fileName = String.Format(

            Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);
            blockBlob.Properties.ContentType = fileContentType;
            //blockBlob.Metadata.Add("name", name);
            blockBlob.Metadata.Add("originalfilename", sourceFileName);
            //blockBlob.Metadata.Add("userid", userId.ToString());
            //blockBlob.Metadata.Add("ownerid", userId.ToString());
            DateTime created = DateTime.UtcNow;

            // https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
            // http://stackoverflow.com/questions/114983/given-a-datetime-object-how-do-i-get-a-iso-8601-date-in-string-format
            //blockBlob.Metadata.Add("username", userName);
            blockBlob.Metadata.Add("created", created.ToString("yyyy-MM-ddTHH:mm:ss"));  // "yyyy-MM-ddTHH:mm:ssZ"
            blockBlob.Metadata.Add("modified", created.ToString("yyyy-MM-ddTHH:mm:ss")); // "yyyy-MM-ddTHH:mm:ssZ"
            blockBlob.Metadata.Add("fileext", ext);

            blockBlob.UploadText(content, Encoding.UTF8); // .UploadFromStream(fileInputStream);

            blockBlob.SetMetadata();
        }
        /// <summary>
        /// Get the service properties
        /// </summary>
        /// <param name="account">Cloud storage account</param>
        /// <param name="type">Service type</param>
        /// <param name="options">Request options</param>
        /// <param name="operationContext">Operation context</param>
        /// <returns>The service properties of the specified service type</returns>
        public XSCLProtocol.ServiceProperties GetStorageServiceProperties(StorageServiceType type, IRequestOptions options, XSCL.OperationContext operationContext)
        {
            XSCL.CloudStorageAccount account = StorageContext.StorageAccount;
            try
            {
                switch (type)
                {
                case StorageServiceType.Blob:
                    return(account.CreateCloudBlobClient().GetServicePropertiesAsync((BlobRequestOptions)options, operationContext).Result);

                case StorageServiceType.Queue:
                    return(account.CreateCloudQueueClient().GetServicePropertiesAsync((QueueRequestOptions)options, operationContext).Result);

                case StorageServiceType.File:
                    FileServiceProperties          fileServiceProperties = account.CreateCloudFileClient().GetServicePropertiesAsync((FileRequestOptions)options, operationContext).Result;
                    XSCLProtocol.ServiceProperties sp = new XSCLProtocol.ServiceProperties();
                    sp.Clean();
                    sp.Cors          = fileServiceProperties.Cors;
                    sp.HourMetrics   = fileServiceProperties.HourMetrics;
                    sp.MinuteMetrics = fileServiceProperties.MinuteMetrics;
                    return(sp);

                default:
                    throw new ArgumentException(Resources.InvalidStorageServiceType, "type");
                }
            }
            catch (AggregateException e) when(e.InnerException is XSCL.StorageException)
            {
                throw e.InnerException;
            }
        }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            try
            {
                //hace la cuenta
                StorageCredentials creds = new StorageCredentials(accountName, accountKey);
                CloudStorageAccount account = new CloudStorageAccount(creds, useHttps: true);
                //crea el cliente
                CloudBlobClient client = account.CreateCloudBlobClient();
                //crae el contenedor
                CloudBlobContainer sampleContainer = client.GetContainerReference("music");
                sampleContainer.CreateIfNotExists();
                //
                CloudBlockBlob blob = sampleContainer.GetBlockBlobReference("9.mp3");
                using (System.IO.Stream file = System.IO.File.OpenRead("C:\\Users\\Andres\\Downloads\\9.mp3"))
                {
                    blob.UploadFromStream(file);
                }

                /*CloudBlockBlob blob = sampleContainer.GetBlockBlobReference("APictureFile.jpg");
                using (Stream outputFile = new FileStream("Downloaded.jpg", FileMode.Create))
                {
                    blob.DownloadToStream(outputFile);
                }*/

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            Console.Read();
        }
Ejemplo n.º 11
0
        public bool Post(CommitBlobRequest commitRequest)
        {

            var result = false;

            commitRequest.FileName = commitRequest.FileName.ToLower();
            commitRequest.ContainerName = commitRequest.ContainerName.ToLower();
            var accountAndKey = new StorageCredentials(AppSettings.StorageAccountName, AppSettings.StorageAccountKey);
            var storageaccount = new CloudStorageAccount(accountAndKey, true);
            var blobClient = storageaccount.CreateCloudBlobClient();
            CloudBlobContainer container = blobClient.GetContainerReference(commitRequest.ContainerName);
            container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
            CloudBlockBlob blob = container.GetBlockBlobReference(commitRequest.FileName);

            try
            {
                blob.PutBlockList(commitRequest.blobParts);
                blob.Properties.ContentType = commitRequest.type;
                blob.Properties.ContentDisposition = "attachment";
                blob.SetProperties();

                result = true;
            }
            catch (Exception ex)
            {
                //Trace.TraceError("BuildFileSasUrl throw excaption", ex.Message);
            }
              

            return result;



        }
 private static void InitStorage()
 {
     var credentials = new StorageCredentials(resources.AccountName, resources.AccountKey);
     var storageAccount = new CloudStorageAccount(credentials, true);
     var blobClient = storageAccount.CreateCloudBlobClient();
     imagesContainer = blobClient.GetContainerReference("images");
 }
Ejemplo n.º 13
0
 public StorageHelper()
 {
     var storageCred = new StorageCredentials(AppSettings.StorageAccountName, AppSettings.StorageAccountKey);
      storageAccount = new CloudStorageAccount(storageCred, true);
     configureCors(storageAccount);
   
 }
 public StorageTableAccessor(CloudStorageAccount storageAccount)
 {
     CloudTableClient tableClient = new CloudTableClient(storageAccount.TableStorageUri, storageAccount.Credentials);
     this.table = tableClient.GetTableReference(messageTableName);
     this.table.CreateIfNotExists();
     ReadFirstEntry();
 }
Ejemplo n.º 15
0
        private string FileToUpload(HttpPostedFileBase file, string FolderId, string uniqueBlobName)
        {
            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(Microsoft.Azure.CloudConfigurationManager.GetSetting(StorageProjectFiles));
            CloudBlobClient    blobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container  = blobClient.GetContainerReference(FolderId);

            try
            {
                container.CreateIfNotExists();
            }
            catch (StorageException)
            {
                throw;
            }

            /*
             * CloudBlockBlob blockBlob = container.GetBlockBlobReference(newinfo.Name);
             * await blockBlob.UploadFromFileAsync(newinfo.FullName, FileMode.Open);
             */
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(uniqueBlobName);

            blockBlob.Properties.ContentType = file.ContentType;
            blockBlob.UploadFromStream(file.InputStream);
            return(blockBlob.Uri.AbsoluteUri);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Constructs a container shared access signature.
        /// </summary>
        /// <param name="storageAccountName">The Azure Storage account name.</param>
        /// <param name="storageAccountKey">The Azure Storage account key.</param>
        /// <param name="storageEndpoint">The Azure Storage endpoint.</param>
        /// <param name="containerName">The container name to construct a SAS for.</param>
        /// <returns>The container URL with the SAS.</returns>
        public static string ConstructContainerSas(
            string storageAccountName,
            string storageAccountKey,
            string storageEndpoint,
            string containerName)
        {
            //Lowercase the container name because containers must always be all lower case
            containerName = containerName.ToLower();

            StorageCredentials credentials = new StorageCredentials(storageAccountName, storageAccountKey);
            CloudStorageAccount storageAccount = new CloudStorageAccount(credentials, storageEndpoint, true);

            CloudBlobClient client = storageAccount.CreateCloudBlobClient();

            CloudBlobContainer container = client.GetContainerReference(containerName);

            DateTimeOffset sasStartTime = DateTime.UtcNow;
            TimeSpan sasDuration = TimeSpan.FromHours(2);
            DateTimeOffset sasEndTime = sasStartTime.Add(sasDuration);

            SharedAccessBlobPolicy sasPolicy = new SharedAccessBlobPolicy()
                                                   {
                                                       Permissions = SharedAccessBlobPermissions.Read,
                                                       SharedAccessExpiryTime = sasEndTime
                                                   };

            string sasString = container.GetSharedAccessSignature(sasPolicy);
            return string.Format("{0}{1}", container.Uri, sasString); ;
        }
        public AzureTableStorageStatusTraceListener(String initializeData) : base(initializeData)
        {
            string connectionString = null;
            string tableName = "status";

            if (initializeData != null)
            {
                foreach (String keyValuePair in initializeData.Split(','))
                {
                    String[] parts = keyValuePair.Split('*');
                    if (parts.Length == 2)
                    {
                        if (parts[0].Equals("tablestorage", StringComparison.InvariantCultureIgnoreCase))
                        {
                            connectionString = parts[1].Trim();
                        }
                        else if (parts[0].Equals("table", StringComparison.InvariantCultureIgnoreCase))
                        {
                            tableName = parts[1].Trim();
                        }
                    }
                }
            }

            if (String.IsNullOrWhiteSpace(connectionString))
            {
                throw new ArgumentNullException("tablestorage", "The initializeData string must specify the Azure table storage connection string in the tablestorage field.");
            }

            this._storageAccount = CloudStorageAccount.Parse(connectionString);
            this._tableClient = this._storageAccount.CreateCloudTableClient();
            this._table = this._tableClient.GetTableReference(tableName);
            this._table.CreateIfNotExists();
        }
 public AzureAsyncAppender(CloudStorageAccount storage, string container, AzureBlobAppenderOptions options = null)
 {
     this.storage = storage;
     this.container = container;
     this.options = options;
     this.client = this.storage.CreateCloudBlobClient().GetContainerReference(container);
 }
Ejemplo n.º 19
0
 public AzureService(string account, string azureKey, string blobUri)
 {
     _account = account;
     var storageAccount = new CloudStorageAccount(new StorageCredentials(account, azureKey), new Uri(blobUri),
                                                  null, null);
     _client = storageAccount.CreateCloudBlobClient();
 }
Ejemplo n.º 20
0
        public string DefaultUrl()
        {
            // Retrieve storage account from connection string.
            Microsoft.WindowsAzure.Storage.CloudStorageAccount StorageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(Convert.ToString(ConfigurationManager.AppSettings["StorageConnectionString"]));

            return(Convert.ToString(StorageAccount.BlobStorageUri.PrimaryUri));
        }
Ejemplo n.º 21
0
        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 
            }

        }
Ejemplo n.º 22
0
        public FileManager(string ContainerName)
        {
            // Check if Container Name is null or empty
            if (string.IsNullOrEmpty(ContainerName))
            {
                throw new ArgumentNullException("ContainerName", "Container Name can't be empty");
            }
            try
            {
                // Get azure table storage connection string.
                KeyVaultManager keyVaultManager  = new KeyVaultManager();
                string          ConnectionString = keyVaultManager.GetValueFromAzureVault(Constants.SecretName);
                //string ConnectionString = "DefaultEndpointsProtocol=https;AccountName=training2blobstorage;AccountKey=d4swk28SyaP0RkzEssi2Q39Zsg6+rFQ8bv/UvzYfgwHXIqbuYjY1yrUWXXoH50YdTuipEZhnwQ+JS93TMNFRCg==;EndpointSuffix=core.windows.net";

                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionString);

                CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
                blobContainer = cloudBlobClient.GetContainerReference(ContainerName);

                // Create the container and set the permission
                if (blobContainer.CreateIfNotExists())
                {
                    blobContainer.SetPermissions(
                        new BlobContainerPermissions
                    {
                        PublicAccess = BlobContainerPublicAccessType.Blob
                    }
                        );
                }
            }
            catch (Exception ExceptionObj)
            {
                throw ExceptionObj;
            }
        }
 public AuditAzureTableProvider()
 {
     try
     {
         _account = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["AzureStorageConnectionString"]);
         _client = _account.CreateCloudTableClient();
     }
     catch (Exception exp)
     {
         throw new Exception("Error retreiving reference to Azure Storage Account", exp);
     }
     try
     {
         _client = _account.CreateCloudTableClient();
     }
     catch (Exception exp)
     {
         throw new Exception("Error creating Azure Table Client Object", exp);
     }
     try
     {
         _vmAuditTable = _client.GetTableReference("VMAudits");
     }
     catch (Exception exp)
     {
         throw new Exception("Error retreiving reference to Azure Table Object", exp);
     }
 }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["stockName"];

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            name = name ?? data?.stockName;

            if (string.IsNullOrEmpty(name))
            {
                return(new BadRequestResult());
            }

            var connectionString = "DefaultEndpointsProtocol=https;AccountName=storageaccount4471b6a6;AccountKey=dX2VUCuxC0EcRnyZ7Srg+XIKLLagAO30kkpcBcsv9bq91rG+h2FomX6EHP/IByNzKSxVdRIqq6phUYDQ3PAPnw==;EndpointSuffix=core.windows.net";

            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
            CloudTable       table       = tableClient.GetTableReference("stocksinfo");

            var summary = GetSummary(table, name);

            if (summary == null)
            {
                return(new NotFoundResult());;
            }

            return(new OkObjectResult(JsonConvert.SerializeObject(summary)));
        }
Ejemplo n.º 25
0
 public BlobManager(string conStr)
 {
     //RoleEnvironment.GetConfigurationSettingValue("UploadCon")
     Storage = CloudStorageAccount.Parse(conStr);
     BlobClient = Storage.CreateCloudBlobClient();
     QueueClient = Storage.CreateCloudQueueClient();
 }
 private static void InitStorage()
 {
     var credentials = new StorageCredentials(AppKeys.Storage_Account_Name, AppKeys.PrimaryAccessKey);
     var storageAccount = new CloudStorageAccount(credentials, true);
     var blobClient = storageAccount.CreateCloudBlobClient();
     imagesContainer = blobClient.GetContainerReference("images");
 }
 protected AzureBlobPoisonMessageHandler(CloudStorageAccount storageAccount, 
     string containerName)
 {
     _storageAccount = storageAccount;
     _containerName = containerName;
     _blobClient = _storageAccount.CreateCloudBlobClient();
 }
Ejemplo n.º 28
0
        public bool downloadSong(int song_id, string song_name, string song_path)
        {
            bool flag = false;

            //hace la cuenta
            StorageCredentials creds = new StorageCredentials(accountName, accountKey);
            CloudStorageAccount account = new CloudStorageAccount(creds, useHttps: true);

            //crea el cliente
            CloudBlobClient client = account.CreateCloudBlobClient();

            //crae el contenedor
            CloudBlobContainer sampleContainer = client.GetContainerReference("music");

            CloudBlockBlob blob = sampleContainer.GetBlockBlobReference(song_id.ToString() + ".mp3");

            try
            {
                //FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.AllAccess, "C:\\Users\\Andres\\Music");
                Console.WriteLine("Path: {0}", song_path + "\\" + song_name);
                Stream outputFile = new FileStream(song_path + "\\" + song_name, FileMode.Create);

                blob.DownloadToStream(outputFile);
                flag = true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                flag = false;
            }

            return flag;
        }
Ejemplo n.º 29
0
        public void when_writting_to_a_pageBlob_all_data_is_correctly_retrieved()
        {
            var azureAccount = new CloudStorageAccount(new StorageCredentials("valeriob", "2SzgTAaG11U0M1gQ19SNus/vv1f0efwYOwZHL1w9YhTKEYsU1ul+s/ke92DOE1wIeCKYz5CuaowtDceUvZW2Rw=="), true);
            var blobClient = azureAccount.CreateCloudBlobClient();
            var container = blobClient.GetContainerReference("test");
            container.CreateIfNotExists();

            var blob = container.GetPageBlobReference(Guid.NewGuid()+"");

            var helper = new AzurePageBlob(blob);
            //helper.Create_if_does_not_exists();
            helper.OpenAsync().Wait();

            var output = "";
            var input = @"The uniqueifier is NULL for the first instance of each customer_id, and is then populated, in ascending order, for each subsequent row with the same customer_id value. The overhead for rows with a NULL uniqueifier value is, unsurprisingly, zero bytes. This is why min_record_size_in_bytes remained unchanged in the overhead table; the first insert had a uniqueifier value of NULL. This is also why it is impossible to estimate how much additional storage overhead will result from the addition of a uniqueifier, without first having a thorough understanding of the data being stored. For example, a non-unique clustered index on a datetime column may have very little overhead if data is inserted, say, once per minute. However, if that same table is receiving thousands of inserts per minute, then it is likely that many rows will share the same datetime value, and so the uniqueifier will have a much higher overhead.

            If your requirements seem to dictate the use of a non-unique clustered key, my advice would be to look to see if there are a couple of relatively narrow columns that, together, can form a unique key. You'll still see the increase in the row size for your clustering key in the index pages of both your clustered and nonclustered indexes, but you'll at least save the cost of the uniqueifier in the data pages of the leaf level of your clustered index. Also, instead of storing an arbitrary uniqueifier value to the index key, which is meaningless in the context of your data, you would be adding meaningful and potentially useful information to all of your nonclustered indexes.

            A good clustered index is also built upon static, or unchanging, columns. That is, you want to choose a clustering key that will never be updated. SQL Server must ensure that data exists in a logical order based upon the clustering key. Therefore, when the clustering key value is updated, the data may need to be moved elsewhere in the clustered index so that the clustering order is maintained. Consider a table with a clustered index on LastName, and two non-clustered indexes, where the last name of an employee must be updated.";

            helper.Append(input);

            using (var stream = helper.OpenReadonlyStream())
            {
                using (var reader = new StreamReader(stream))
                {
                    output = reader.ReadToEnd();
                }
            }

            Assert.AreEqual(input, output);
        }
 public AzureBlobStorageProvider(CloudStorageAccount storageAccount)
 {
     _storageAccount = storageAccount;
     BlobClient = _storageAccount.CreateCloudBlobClient();
     Containers = new List<CloudBlobContainer>();
     ContainerFactory = CreateContainer;
 }
Ejemplo n.º 31
0
        public bool uploadSong(int song_id, string song_path)
        {
            bool flag = false;

            //hace la cuenta
            StorageCredentials creds = new StorageCredentials(accountName, accountKey);
            CloudStorageAccount account = new CloudStorageAccount(creds, useHttps: true);

            //crea el cliente
            CloudBlobClient client = account.CreateCloudBlobClient();

            //crae el contenedor
            CloudBlobContainer container = client.GetContainerReference("music");
            container.CreateIfNotExists();
            //
            CloudBlockBlob blob = container.GetBlockBlobReference(song_id.ToString() + ".mp3");
            using (System.IO.Stream file = System.IO.File.OpenRead(song_path))
            {
                try
                {
                    blob.UploadFromStream(file);
                    flag = true;

                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    flag = false;
                }

            }

            return flag;
        }
        public WindowsAzureStorageService(ICmsConfiguration config)
        {
            try
            {
                var serviceSection = config.Storage;
                string accountName = serviceSection.GetValue("AzureAccountName");
                string secretKey = serviceSection.GetValue("AzureSecondaryKey");
                bool useHttps = bool.Parse(serviceSection.GetValue("AzureUseHttps"));

                if (!TimeSpan.TryParse(serviceSection.GetValue("AzureTokenExpiryTime"), out tokenExpiryTime))
                {
                    tokenExpiryTime = TimeSpan.FromMinutes(10);
                }

                timeout = serviceSection.ProcessTimeout;
                
                accessControlEnabledGlobally = config.Security.AccessControlEnabled;
                containerName = serviceSection.GetValue("AzureContainerName");
                securedContainerName = serviceSection.GetValue("AzureSecuredContainerName");
                if (string.IsNullOrWhiteSpace(securedContainerName))
                {
                    securedContainerName = containerName;
                }

                cloudStorageAccount = new CloudStorageAccount(new StorageCredentials(accountName, secretKey), useHttps);
            }
            catch (Exception e)
            {
                throw new StorageException(string.Format("Failed to initialize storage service {0}.", GetType()), e);
            }
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Generates the blob container SAS URL.
        /// </summary>
        /// <param name="storageAccount">The storage account.</param>
        /// <param name="dto">The data transfer object.</param>
        private static void GenerateBlobContainerSasUrl(CloudStorageAccount storageAccount, DataDto dto)
        {
            // Create the blob client.
            var blobClient = storageAccount.CreateCloudBlobClient();

            // Use the client's name as container
            var container = blobClient.GetContainerReference("datacontainer");

            // Create the container if it doesn't already exist.
            // TODO: Avoid the next line of code in productive systems, since it makes a call to azure blob storage.
            // It's better to make sure the container always exists from the beginning.
            container.CreateIfNotExists();

            // Set the expiry time and permissions for the container.
            // In this case no start time is specified, so the shared access signature becomes valid immediately.
            var accessBlobPolicy = new SharedAccessBlobPolicy();
            accessBlobPolicy.SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1);
            accessBlobPolicy.Permissions = SharedAccessBlobPermissions.Write;

            // Generate the SAS token. No access policy identifier is used which makes it non revocable.
            // The token is generated without issuing any calls against the Windows Azure Storage.
            string sasToken = container.GetSharedAccessSignature(accessBlobPolicy);

            dto.BlobContainerUrl = container.Uri;
            dto.BlobSasToken = sasToken;
        }
Ejemplo n.º 34
0
 public given_blob_storage()
 {
     var settings = InfrastructureSettings.Read("Settings.xml").BlobStorage;
     this.account = CloudStorageAccount.Parse(settings.ConnectionString);
     this.rootContainerName = Guid.NewGuid().ToString();
     this.sut = new CloudBlobStorage(account, this.rootContainerName);
 }
Ejemplo n.º 35
0
        public override bool Init(IDictionary<string, string> jobArgsDictionary)
        {
            try
            {
                var instrumentationKey = JobConfigurationManager.TryGetArgument(jobArgsDictionary, JobArgumentNames.InstrumentationKey);
                ApplicationInsights.Initialize(instrumentationKey);

                var azureCdnPlatform = JobConfigurationManager.GetArgument(jobArgsDictionary, JobArgumentNames.AzureCdnPlatform);
                var cloudStorageAccountConnectionString = JobConfigurationManager.GetArgument(jobArgsDictionary, JobArgumentNames.AzureCdnCloudStorageAccount);
                var databaseConnectionString = JobConfigurationManager.GetArgument(jobArgsDictionary, JobArgumentNames.StatisticsDatabase);
                _cloudStorageAccount = ValidateAzureCloudStorageAccount(cloudStorageAccountConnectionString);

                _targetDatabase = new SqlConnectionStringBuilder(databaseConnectionString);
                _azureCdnAccountNumber = JobConfigurationManager.GetArgument(jobArgsDictionary, JobArgumentNames.AzureCdnAccountNumber);
                _azureCdnPlatform = ValidateAzureCdnPlatform(azureCdnPlatform);
                _cloudStorageContainerName = ValidateAzureContainerName(JobConfigurationManager.GetArgument(jobArgsDictionary, JobArgumentNames.AzureCdnCloudStorageContainerName));

                return true;
            }
            catch (Exception exception)
            {
                ApplicationInsights.TrackException(exception);
                Trace.TraceError(exception.ToString());
            }
            return false;
        }
 static RebusConfigurer Configure(this RebusConfigurer configurer, CloudStorageAccount storageAccount, string inputQueueAddress,
     string subscriptionTableName = "RebusSubscriptions",
     string sagaIndexTableName = "RebusSagaIndex",
     string sagaContainerName = "RebusSagaStorage",
     string dataBusContainerName = "RebusDataBusData",
     bool isCentralizedSubscriptions = false,
     bool enableDataBus = true,
     bool enableSagaSnapshots = true)
 {
     return configurer
         .Transport(t => t.UseAzureStorageQueues(storageAccount, inputQueueAddress))
         .Subscriptions(t => t.StoreInTableStorage(storageAccount, subscriptionTableName, isCentralizedSubscriptions))
         .Sagas(t => t.StoreInAzureStorage(storageAccount, sagaIndexTableName, sagaContainerName))
         .Options(o =>
         {
             if (enableDataBus)
             {
                 o.EnableDataBus().StoreInBlobStorage(storageAccount, dataBusContainerName);
             }
             if (enableSagaSnapshots)
             {
                 o.EnableSagaAuditing().StoreInBlobStorage(storageAccount, sagaContainerName);
             }
         });
 }
Ejemplo n.º 37
0
        public static void MyClassInitialize(TestContext testContext)
        {
            Trace.WriteLine("ClassInit");
            Test.FullClassName = testContext.FullyQualifiedTestClassName;

            StorageAccount = TestBase.GetCloudStorageAccountFromConfig();

            //init the blob helper for blob related operations
            BlobHelper = new CloudBlobHelper(StorageAccount);

            // import module
            string moduleFilePath = Test.Data.Get("ModuleFilePath");
            if (moduleFilePath.Length > 0)
                PowerShellAgent.ImportModule(moduleFilePath);

            // $context = New-AzureStorageContext -ConnectionString ...
            PowerShellAgent.SetStorageContext(StorageAccount.ToString(true));

            BlockFilePath = Path.Combine(Test.Data.Get("TempDir"), FileUtil.GetSpecialFileName());
            PageFilePath = Path.Combine(Test.Data.Get("TempDir"), FileUtil.GetSpecialFileName());
            FileUtil.CreateDirIfNotExits(Path.GetDirectoryName(BlockFilePath));
            FileUtil.CreateDirIfNotExits(Path.GetDirectoryName(PageFilePath));

            // Generate block file and page file which are used for uploading
            Helper.GenerateMediumFile(BlockFilePath, 1);
            Helper.GenerateMediumFile(PageFilePath, 1);
        }
Ejemplo n.º 38
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);
            }
        }
        public static void Run(string connectionString, bool disableLogging)
        {
            _connectionString = connectionString;
            _storageAccount = CloudStorageAccount.Parse(connectionString);
            _blobClient = _storageAccount.CreateCloudBlobClient();

            Console.WriteLine("Creating the test blob...");
            CreateTestBlob();

            try
            {
                TimeSpan azureSDKTime = RunAzureSDKTest();
                TimeSpan webJobsSDKTime = RunWebJobsSDKTest(disableLogging);

                // Convert to ulong because the measurment block does not support other data type
                ulong perfRatio = (ulong)((webJobsSDKTime.TotalMilliseconds / azureSDKTime.TotalMilliseconds) * 100);

                Console.WriteLine("--- Results ---");
                Console.WriteLine("Azure SDK:   {0} ms: ", azureSDKTime.TotalMilliseconds);
                Console.WriteLine("WebJobs SDK: {0} ms: ", webJobsSDKTime.TotalMilliseconds);

                Console.WriteLine("Perf ratio (x100, long): {0}", perfRatio);

                MeasurementBlock.Mark(
                    perfRatio,
                    (disableLogging ? BlobNoLoggingOverheadMetric : BlobLoggingOverheadMetric) + ";Ratio;Percent");
            }
            finally
            {
                Cleanup();
            }
        }
 public CloudQueuePublisherBusConfigurationBuilder()
 {
     _senderConfiguration = null;
     _serializer = null;
     _storageAccount = null;
     _subscriptions = new HashSet<Subscription>();
 }
        public VstsInstanceRepository(string azureStorageConnectionString)
        {
            storageAccount         = CloudStorageAccount.Parse(azureStorageConnectionString);
            storageAccountForQueue = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(azureStorageConnectionString);
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            vstsUserCloudTable = tableClient.GetTableReference("VstsInstance");
        }
Ejemplo n.º 42
0
        private string GetFileUri(HttpPostedFileBase file)
        {
            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(Microsoft.Azure.CloudConfigurationManager.GetSetting(StorageProjectFiles));
            CloudBlobClient    blobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container  = blobClient.GetContainerReference(barcelona);
            CloudBlockBlob     blockBlob  = container.GetBlockBlobReference(file.FileName);

            return(blockBlob.Uri.AbsoluteUri);
        }
Ejemplo n.º 43
0
        public CloudBlobContainer GetBlobContainer(string tableName)
        {
            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse("UseDevelopmentStorage=true");
            CloudBlobClient    blobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container  = blobClient.GetContainerReference(tableName);

            container.CreateIfNotExistsAsync();
            return(container);
        }
Ejemplo n.º 44
0
        public CloudQueue GetQueueTable(string tableName)
        {
            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse("UseDevelopmentStorage=true");
            CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
            CloudQueue       queue       = queueClient.GetQueueReference(tableName);

            queue.CreateIfNotExistsAsync();
            return(queue);
        }
Ejemplo n.º 45
0
        private void DeleteBolb(string FileName)
        {
            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(Microsoft.Azure.CloudConfigurationManager.GetSetting(StorageProjectFiles));
            CloudBlobClient    blobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container  = blobClient.GetContainerReference(barcelona);
            CloudBlockBlob     blockBlob  = container.GetBlockBlobReference(FileName);

            blockBlob.DeleteIfExists();
        }
Ejemplo n.º 46
0
        /// <summary>
        /// This method do the housekeeping stuffs
        /// </summary>
        private static void initialize()
        {
            //Return reference to the storage account
            account = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));

            //credentials = new StorageCredentials(accountName, accountKey);
            //account = new CloudStorageAccount(credentials, useHttps: true);

            cloudBlobClient = account.CreateCloudBlobClient();
        }
Ejemplo n.º 47
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());
        }
Ejemplo n.º 48
0
        public static async Task Init(string azureStorageConnectionString)
        {
            storageAccount         = CloudStorageAccount.Parse(azureStorageConnectionString);
            storageAccountForQueue = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(azureStorageConnectionString);

            var tableClient = storageAccount.CreateCloudTableClient();
            var queueClient = storageAccountForQueue.CreateCloudQueueClient();

            // Get reference for storage tables and queues
            var countryCloudTable                  = tableClient.GetTableReference("Country");
            var vstsInstanceCloudTable             = tableClient.GetTableReference("VstsInstance");
            var vstsUserCloudTable                 = tableClient.GetTableReference("VstsUser");
            var talentChallengeCloudTable          = tableClient.GetTableReference("TalentChallenges");
            var vstsavailableinstancesWestEurope   = queueClient.GetQueueReference($"vstsavailableinstances-westeurope");
            var vstspendingavailableinstancesQueue = queueClient.GetQueueReference($"vstspendingavailableinstances");

            // Create the storage tables and queues if not exists

            await vstsavailableinstancesWestEurope.CreateIfNotExistsAsync();

            await vstspendingavailableinstancesQueue.CreateIfNotExistsAsync();


            var isCountryInitialized = await countryCloudTable.ExistsAsync();

            var isVSTSInstanceInitialized = await vstsInstanceCloudTable.ExistsAsync();

            var isVSTSUserInitialized = await vstsUserCloudTable.ExistsAsync();

            var isTalentChallengeInitialized = await talentChallengeCloudTable.ExistsAsync();

            // Init data
            if (!isCountryInitialized)
            {
                await countryCloudTable.CreateAsync();
                await InitCountries(countryCloudTable);
            }

            if (!isVSTSInstanceInitialized)
            {
                await vstsInstanceCloudTable.CreateAsync();
                await InitVSTSInstances(vstsInstanceCloudTable, vstspendingavailableinstancesQueue);
            }

            if (!isVSTSUserInitialized)
            {
                await vstsUserCloudTable.CreateAsync();
            }

            if (!isTalentChallengeInitialized)
            {
                await talentChallengeCloudTable.CreateAsync();
            }
        }
Ejemplo n.º 49
0
 static Microsoft.WindowsAzure.Storage.Table.CloudTable GetAzureTable()
 {
     Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageAccount"));
     //create cloud table client
     Microsoft.WindowsAzure.Storage.Table.CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
     //get cloud table
     Microsoft.WindowsAzure.Storage.Table.CloudTable table = tableClient.GetTableReference("customers");
     //cleanup
     table.DeleteIfExists();
     table.CreateIfNotExists();
     return(table);
 }
Ejemplo n.º 50
0
        private void LogError(Exception ex, string message)
        {
            //ConfigurationManager.ConnectionStrings["CineStorageConStr"].ConnectionString
            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("CineStorageConStr"));

            Microsoft.WindowsAzure.Storage.Blob.CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

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

            Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob logBlob = container.GetBlockBlobReference(String.Format(this.LogFile, DateTime.UtcNow.ToString("dd MMM yyyy")));
            try
            {
                using (StreamReader sr = new StreamReader(logBlob.OpenRead()))
                {
                    using (StreamWriter sw = new StreamWriter(logBlob.OpenWrite()))
                    {
                        sw.Write(sr.ReadToEnd());

                        if (ex != null)
                        {
                            sw.Write(System.Environment.NewLine);

                            sw.WriteLine(ex.Message);
                            sw.WriteLine(ex.StackTrace);

                            sw.Write(System.Environment.NewLine);

                            if (ex.InnerException != null)
                            {
                                sw.Write(System.Environment.NewLine);

                                sw.WriteLine(ex.InnerException.Message);
                                sw.WriteLine(ex.InnerException.StackTrace);

                                sw.Write(System.Environment.NewLine);
                            }
                        }

                        if (message != null)
                        {
                            sw.Write(System.Environment.NewLine);

                            sw.WriteLine(message);

                            sw.Write(System.Environment.NewLine);
                        }
                    }
                }
            }
            catch { }
        }
        public Microsoft.WindowsAzure.Storage.Blob.CloudBlobClient GetBlobClient()
        {
            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(
                StorageConnectionString);

            ServicePoint tableServicePoint = ServicePointManager.FindServicePoint(storageAccount.TableEndpoint);

            tableServicePoint.UseNagleAlgorithm = false;

            Microsoft.WindowsAzure.Storage.Blob.CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            return(blobClient);
        }
Ejemplo n.º 52
0
        /// <summary>
        /// Enable logging for storage account
        /// </summary>
        /// <param name="accountname"></param>
        /// <param name="accountkey"></param>
        /// <param name="SnapshotFileName"></param>
        public static void EnableLogging(string accountname, string accountkey, string SnapshotFileName)
        {
            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=" + accountname + ";AccountKey=" + accountkey);

            //var queueClient = storageAccount.CreateCloudQueueClient();
            var blobClient        = storageAccount.CreateCloudBlobClient();
            var serviceProperties = blobClient.GetServiceProperties();

            serviceProperties.Logging.LoggingOperations = Microsoft.WindowsAzure.Storage.Shared.Protocol.LoggingOperations.All;
            serviceProperties.Logging.RetentionDays     = 2;

            blobClient.SetServiceProperties(serviceProperties);
        }
Ejemplo n.º 53
0
        /// <summary>
        /// Creates a new instance for the monitor
        /// </summary>
        public ConcurrencyMonitor(string leaseConnectionString)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(leaseConnectionString);
            CloudBlobClient     blobClient     = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer  container      = blobClient.GetContainerReference("leasecontainer");

            container.CreateIfNotExists();
            blob = container.GetBlockBlobReference("leaseblob");
            if (!Exists(blob))
            {
                using (Stream str = new MemoryStream(new byte[] { 0 }))
                {
                    blob.UploadFromStream(str);
                }
            }
        }
        public Microsoft.WindowsAzure.Storage.Queue.CloudQueue GetStorageQueue(string name)
        {
            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(
                StorageConnectionString);

            ServicePoint tableServicePoint = ServicePointManager.FindServicePoint(storageAccount.TableEndpoint);

            tableServicePoint.UseNagleAlgorithm = false;

            Microsoft.WindowsAzure.Storage.Queue.CloudQueueClient client = storageAccount.CreateCloudQueueClient();

            CloudQueue queue = client.GetQueueReference(name);

            queue.CreateIfNotExistsAsync().Wait();

            return(queue);
        }
        public Microsoft.WindowsAzure.Storage.Table.CloudTable GetTable(string tableName)
        {
            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(
                StorageConnectionString);

            ServicePoint tableServicePoint = ServicePointManager.FindServicePoint(storageAccount.TableEndpoint);

            tableServicePoint.UseNagleAlgorithm = false;

            Microsoft.WindowsAzure.Storage.Table.CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            // Create the table if it doesn't exist.
            CloudTable table = tableClient.GetTableReference(tableName);

            table.CreateIfNotExistsAsync().Wait();

            return(table);
        }
Ejemplo n.º 56
0
        /*
         * listContainers():
         * - First connects to a storage account
         * - then lists the containers
         * - then higlights the 1st container,
         *   which triggers event handler that does blob and policy enumeration
         */
        private void listContainers()
        {
            if (accountText.Text.Length > 0 && keyText.Text.Length > 0)
            {
                accountName = accountText.Text;
                accountKey  = keyText.Text;
            }
            else
            {
                MessageBox.Show("Go to Settings tab and make sure Azure storage account and key are set",
                                "Missing storage settings");
                return;
            }
            try
            {
                Uri blobEndpoint = new Uri("https://" + accountName + ".blob.core.windows.net/");

                // create storage account object and blob client
                Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount =
                    new Microsoft.WindowsAzure.Storage.CloudStorageAccount(new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(accountName, accountKey), true);
                blobClient = storageAccount.CreateCloudBlobClient();

                //List all containers in this storage account.
                containerList.Items.Clear();
                foreach (var container in blobClient.ListContainers())
                {
                    containerList.Items.Add(container.Name);
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show("Invalid cloud blob client: " + Ex.Message +
                                " - check storage account credentials",
                                "Blob client error");
                return;
            }
            // highlight the first listbox item
            if (containerList.Items.Count > 0)
            {
                containerList.SetSelected(0, true);
            }
        }
        public string GetTempUrl(string accountName, string accountKey, string fullPath)
        {
            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount =
                Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(
                    string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1};BlobEndpoint=https://{0}.blob.core.windows.net/", accountName, accountKey)
                    );

            Microsoft.WindowsAzure.Storage.Blob.CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            var blob = blobClient.GetBlobReferenceFromServer(new Uri(fullPath));

            var readPolicy = new Microsoft.WindowsAzure.Storage.Blob.SharedAccessBlobPolicy()
            {
                Permissions            = Microsoft.WindowsAzure.Storage.Blob.SharedAccessBlobPermissions.Read, // SharedAccessPermissions.Read,
                SharedAccessExpiryTime = DateTime.UtcNow + TimeSpan.FromMinutes(10)
            };

            string resultUrl = new Uri(blob.Uri.AbsoluteUri + blob.GetSharedAccessSignature(readPolicy)).ToString();

            return(resultUrl);
        }
Ejemplo n.º 58
0
        private DateTime GetLastModified()
        {
            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("CineStorageConStr"));

            Microsoft.WindowsAzure.Storage.Blob.CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

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

            // Retrieve reference to a blob.
            Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob cinemasUKBlob = container.GetBlockBlobReference(CinemasUKFileName);
            if (cinemasUKBlob.Exists())
            {
                DateTimeOffset?dto = cinemasUKBlob.Properties.LastModified;
                if (dto.HasValue)
                {
                    return(dto.Value.DateTime);
                }
            }

            return(DateTime.MinValue);
        }
Ejemplo n.º 59
0
        //zipArchive - blob with scene zip file
        private void extractArchive(string zipArchive)
        {
            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(DocConstants.Get().ConnectionString);
            CloudBlobClient    blobClient     = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer driveContainer = blobClient.GetContainerReference(BlobName.SCENE_BLOB);//sceneBlob = "scenegallery"

            CloudBlockBlob blockBlob = driveContainer.GetBlockBlobReference(zipArchive);
            string         zipPath   = m_directory.FullName + blockBlob.Name;

            Utils.DownloadBlobToFile(blockBlob, zipPath); //download scene zip file to zipPath

            try
            {
                FastZip zip = new FastZip();
                zip.ExtractZip(zipPath, m_directory.FullName, null); //extract from zipPath to Directory
            }
            catch (Exception e)
            {
                string msg = "Extract archive error: " + e.Message;
                throw new Exception(msg);
            }
        }
Ejemplo n.º 60
0
        public static void ProcessFile(string file)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["StorageConnection"].ToString();

            Microsoft.WindowsAzure.Storage.CloudStorageAccount account = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(connectionString);
            StorageCredentialsAccountAndKey cre = new StorageCredentialsAccountAndKey(account.Credentials.AccountName, account.Credentials.ExportBase64EncodedKey());

            Microsoft.WindowsAzure.CloudStorageAccount ac = new Microsoft.WindowsAzure.CloudStorageAccount(cre, true);
            CloudTableClient client = account.CreateCloudTableClient();
            CloudTable       table  = client.GetTableReference("employe");

            table.CreateIfNotExists();
            var dt = DataAccess.DataTable.New.ReadAzureBlob(ac, "fileupload", file);

            foreach (var row in dt.Rows)
            {
                EmployeeTableEntity emp = new EmployeeTableEntity {
                    EmployeeId = Convert.ToInt16(row["EmployeeId"]), FirstName = row["FirstName"], LastName = row["LastName"], ContactNo = row["ContactNo"], EmailId = row["EmailId"], PartitionKey = row["EmployeeId"], RowKey = Guid.NewGuid().ToString()
                };
                TableOperation operation = TableOperation.InsertOrMerge(emp);
                table.Execute(operation);
            }
        }