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();
        }
        public CloudQueue(StorageUri queueAddress, StorageCredentials credentials)
#endif
        {
            this.ParseQueryAndVerify(queueAddress, credentials);
            this.Metadata = new Dictionary<string, string>();
            this.EncodeMessage = true;
        }
 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");
 }
        /// <summary>
        /// Creates the web request.
        /// </summary>
        /// <param name="uri">The request Uri.</param>
        /// <param name="timeout">The timeout.</param>
        /// <param name="builder">The builder.</param>
        /// <returns>A web request for performing the operation.</returns>
        internal static StorageRequestMessage CreateRequestMessage(HttpMethod method, Uri uri, int? timeout, UriQueryBuilder builder, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            if (builder == null)
            {
                builder = new UriQueryBuilder();
            }

            if (timeout.HasValue && timeout.Value > 0)
            {
                builder.Add("timeout", timeout.ToString());
            }

#if WINDOWS_RT && !NETCORE
            // Windows Phone does not allow the caller to disable caching, so a random GUID
            // is added to every URI to make it look like a different request.
            builder.Add("randomguid", Guid.NewGuid().ToString("N"));
#endif

            Uri uriRequest = builder.AddToUri(uri);

            StorageRequestMessage msg = new StorageRequestMessage(method, uriRequest, canonicalizer, credentials, credentials.AccountName);
            msg.Content = content;

            return msg;
        }
예제 #5
0
 public StorageHelper()
 {
     var storageCred = new StorageCredentials(AppSettings.StorageAccountName, AppSettings.StorageAccountKey);
      storageAccount = new CloudStorageAccount(storageCred, true);
     configureCors(storageAccount);
   
 }
        protected StorageCredentials GetStorageCredentials(String resourceGroupName, String storageAccountName)
        {
            StorageCredentials credentials = null;

            if (StorageClient != null && StorageClient.StorageAccounts != null)
            {
                var keys = StorageClient.StorageAccounts.ListKeys(resourceGroupName, storageAccountName);

                if (keys != null && keys.StorageAccountKeys != null)
                {
                    var storageAccountKey = string.IsNullOrEmpty(keys.StorageAccountKeys.Key1) ? keys.StorageAccountKeys.Key2 : keys.StorageAccountKeys.Key1;

                    credentials = new StorageCredentials(storageAccountName, storageAccountKey);
                }
            }

            if (credentials == null)
            {
                ThrowTerminatingError(
                    new ErrorRecord(
                        new UnauthorizedAccessException(Properties.Resources.AzureVMDscDefaultStorageCredentialsNotFound),
                        "CredentialsNotFound",
                        ErrorCategory.PermissionDenied,
                        null));
            }

            if (string.IsNullOrEmpty(credentials.AccountName))
            {
                ThrowInvalidArgumentError(Properties.Resources.AzureVMDscStorageContextMustIncludeAccountName);
            }

            return credentials;
        }
예제 #7
0
        /// <summary>
        /// Initiates the SolCat Azure blob data sync.  
        /// </summary>
        public static void CopyBlobData()
        {
            // Authentication Credentials for Azure Storage:
            var credsSrc
                = new StorageCredentials(
                    ConfigHelper.GetConfigValue("HubContainerName"),
                    ConfigHelper.GetConfigValue("HubContainerKey"));

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

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

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

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

            // Call the blob copy master method:
            CopyBlobs(_srcContainer, _destContainer);
        }
예제 #8
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;
        }
예제 #9
0
        private async void button3_Click(object sender, EventArgs e)
        {
            string AccountSid = "ACd489d0930dc658a3384b1b52a28cbced";
            string AuthToken = "b4f632beb8bbf85f696693d0df69dba3";
            FaceServiceClient faceClient = new FaceServiceClient("0e58dbc56e5445ac8fcdfa9ffbf5ef60");
            if (!cam.IsRunning)
            {
                System.Threading.Thread.Sleep(1000);
            }
            bit.Save(@"C:\Users\ma_eg_000\Desktop\PrincetonHack\pic.jpg");
            Thread.Sleep(1000);
            StorageCredentials storageCredentials = new StorageCredentials("faceimage", "DYrgou0cTTp6J7KDdMVVxR3BDtM31zh393oyf0CfWdTuihRUgDwyryQuIqj203SnPHMJVK7VvLGm/KtfIpUncw==");

            CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true);

            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            CloudBlobContainer container = blobClient.GetContainerReference("facecontainer");
            container.CreateIfNotExistsAsync();
            CloudBlockBlob blockBlob = container.GetBlockBlobReference("pic.jpg");

            using (var fileStream = System.IO.File.OpenRead(@"C:\Users\ma_eg_000\Desktop\PrincetonHack\pic.jpg"))
            {
                blockBlob.UploadFromStream(fileStream);
            }
            using (var fileStream = System.IO.File.OpenRead(@"C:\Users\ma_eg_000\Desktop\PrincetonHack\pic.jpg"))
            {
                blockBlob.UploadFromStream(fileStream);
            }
            double[] ages = await UploadAndDetectFaceAges(@"C:\Users\ma_eg_000\Desktop\PrincetonHack\pic.jpg", faceClient);
            string[] genders = await UploadAndDetectFaceGender(@"C:\Users\ma_eg_000\Desktop\PrincetonHack\pic.jpg", faceClient);
            Guid[] ids = await UploadAndDetectFaceId(@"C:\Users\ma_eg_000\Desktop\PrincetonHack\pic.jpg", faceClient);

            InsertData(ids[0].ToString(), genders[0], ages[0].ToString(), textBox1.Text);
        }
예제 #10
0
        static public void Upload(string filepath, string blobname, string accountName, string accountKey)
        {
            try
            {
                StorageCredentials creds = new StorageCredentials(accountName, accountKey);
                CloudStorageAccount account = new CloudStorageAccount(creds, useHttps: true);
                CloudBlobClient client = account.CreateCloudBlobClient();
                CloudBlobContainer sampleContainer = client.GetContainerReference("public-samples");
                sampleContainer.CreateIfNotExists();

                // for public access ////
                BlobContainerPermissions permissions = new BlobContainerPermissions();
                permissions.PublicAccess = BlobContainerPublicAccessType.Container;
                sampleContainer.SetPermissions(permissions);
                /////////////////////////

                CloudBlockBlob blob = sampleContainer.GetBlockBlobReference(blobname);
                using (Stream file = File.OpenRead(filepath))
                {
                    blob.UploadFromStream(file);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
예제 #11
0
 public static void ProcessMethod(TextWriter log)
 {
     StorageCredentials credential = new StorageCredentials(ConfigurationManager.AppSettings["AccountName"], ConfigurationManager.AppSettings["AccountKey"]);
     CloudStorageAccount account = new CloudStorageAccount(credential, true);
     string logwrite = UploadToBlog(account);
     log.Write(logwrite);
 }
 private CloudBlobClient GetStorageClient()
 {
     var accountName = StorageAccountName.Contains(".") ? StorageAccountName.Substring(0, StorageAccountName.IndexOf('.')) : StorageAccountName;
     var storageCredentials = new StorageCredentials(accountName, StorageAccountKey);
     var storageAccount = new CloudStorageAccount(storageCredentials, true);
     return storageAccount.CreateCloudBlobClient();
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="CloudQueueClient"/> class.
        /// </summary>
        /// <param name="usePathStyleUris">True to use path style Uris.</param>
        /// <param name="baseUri">The queue service endpoint to use to create the client.</param>
        /// <param name="credentials">The account credentials.</param>
        internal CloudQueueClient(bool? usePathStyleUris, Uri baseUri, StorageCredentials credentials)
        {
            CommonUtils.AssertNotNull("baseUri", baseUri);

            if (credentials == null)
            {
                credentials = new StorageCredentials();
            }

            if (baseUri == null)
            {
                throw new ArgumentNullException("baseUri");
            }

            if (!baseUri.IsAbsoluteUri)
            {
                string errorMessage = string.Format(CultureInfo.CurrentCulture, SR.RelativeAddressNotPermitted, baseUri.ToString());
                throw new ArgumentException(errorMessage, "baseUri");
            }

            this.BaseUri = baseUri;
            this.Credentials = credentials;
            this.RetryPolicy = new ExponentialRetry();
            this.ServerTimeout = Constants.DefaultServerSideTimeout;

            if (usePathStyleUris.HasValue)
            {
                this.UsePathStyleUris = usePathStyleUris.Value;
            }
            else
            {
                // Automatically decide whether to use host style uri or path style uri
                this.UsePathStyleUris = CommonUtils.UsePathStyleAddressing(this.BaseUri);
            }
        }
 public async static void Log(
     string storageAccountName, 
     string storageAccountKey, 
     string exceptionsTableName, 
     string exceptionSource, 
     string exceptionDescription, 
     ILogger logger = null)
 {
     DateTime dt = DateTime.UtcNow;
     try
     {
         StorageCredentials storageCredentials = new StorageCredentials(storageAccountName, storageAccountKey);
         CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true);
         CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
         tableClient.DefaultRequestOptions.RetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(1), 10);
         CloudTable table_AppExceptions = tableClient.GetTableReference(exceptionsTableName);
         await table_AppExceptions.CreateIfNotExistsAsync();
         ExceptionLog entity = new ExceptionLog((DateTime.MaxValue - dt).ToString());
         entity.DT = dt;
         entity.MachineName = Environment.MachineName;
         entity.Application = Assembly.GetEntryAssembly().GetName().Name;
         entity.Source = exceptionSource;
         entity.Description = exceptionDescription;
         await table_AppExceptions.ExecuteAsync(TableOperation.Insert(entity));
     } 
     catch (System.Exception ex)
     {
         if (logger != null)
         {
             logger.Error(exceptionSource + ":" + exceptionDescription + ": " + ex.ToString());
         }
         Console.WriteLine(dt.ToString() + " " + Environment.MachineName + ":" + Assembly.GetEntryAssembly().GetName().Name + ":" + exceptionSource + ":" + exceptionDescription + ": " + ex.ToString());
     } 
 }
예제 #15
0
        public static void CreateClassRooms(int number, int building, int floor, int capacity, string description)
        {
            StorageCredentials creds = new StorageCredentials(accountName, accountKey);
            CloudStorageAccount storageAccount = new CloudStorageAccount(creds, useHttps: true);

            // Create the table client.
            CloudTableClient classRoomClient = storageAccount.CreateCloudTableClient();

            // Create the table if it doesn't exist.
            CloudTable table = classRoomClient.GetTableReference("ClassRoom");
            table.CreateIfNotExists();

            // Create the entity.
            ClassRoomEntity foo = new ClassRoomEntity(number, building);

            foo.Floor = floor;
            foo.Capacity = capacity;
            foo.Description = description;

            // Create the TableOperation that inserts the customer entity.
            TableOperation insertOperation = TableOperation.Insert(foo);

            // Execute the insert operation.
            table.Execute(insertOperation);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudPageBlob"/> class using an absolute URI to the blob.
 /// </summary>
 /// <param name="blobAbsoluteUri">The absolute URI to the blob.</param>
 /// <param name="snapshotTime">The snapshot timestamp, if the blob is a snapshot.</param>
 /// <param name="credentials">The account credentials.</param>
 public CloudPageBlob(Uri blobAbsoluteUri, DateTimeOffset? snapshotTime, StorageCredentials credentials)
 {
     this.attributes = new BlobAttributes();
     this.SnapshotTime = snapshotTime;
     this.ParseQueryAndVerify(blobAbsoluteUri, credentials);
     this.Properties.BlobType = BlobType.PageBlob;
 }
        public virtual Uri UploadFile(
            string storageName,
            Uri blobEndpointUri,
            string storageKey,
            string filePath,
            BlobRequestOptions blobRequestOptions)
        {
            StorageCredentials credentials = new StorageCredentials(storageName, storageKey);
            CloudBlobClient client = new CloudBlobClient(blobEndpointUri, credentials);
            string blobName = string.Format(
                CultureInfo.InvariantCulture,
                "{0}_{1}",
                DateTime.UtcNow.ToString("yyyyMMdd_HHmmss", CultureInfo.InvariantCulture),
                Path.GetFileName(filePath));

            CloudBlobContainer container = client.GetContainerReference(ContainerName);
            container.CreateIfNotExists();
            CloudBlockBlob blob = container.GetBlockBlobReference(blobName);

            BlobRequestOptions uploadRequestOption = blobRequestOptions ?? new BlobRequestOptions();

            if (!uploadRequestOption.ServerTimeout.HasValue)
            {
                uploadRequestOption.ServerTimeout = TimeSpan.FromMinutes(300);
            }

            using (FileStream readStream = File.OpenRead(filePath))
            {
                blob.UploadFromStream(readStream, AccessCondition.GenerateEmptyCondition(), uploadRequestOption);
            }

            return new Uri(string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}", client.BaseUri, ContainerName, client.DefaultDelimiter, blobName));
        }
예제 #18
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;
        }
예제 #19
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Press any key to run sample...");
            Console.ReadKey();

            // Make sure the endpoint matches with the web role's endpoint.
            var tokenServiceEndpoint = ConfigurationManager.AppSettings["serviceEndpointUrl"];

            try
            {
                var blobSas = GetBlobSas(new Uri(tokenServiceEndpoint)).Result;

                // Create storage credentials object based on SAS
                var credentials = new StorageCredentials(blobSas.Credentials);

                // Using the returned SAS credentials and BLOB Uri create a block blob instance to upload
                var blob = new CloudBlockBlob(blobSas.BlobUri, credentials);

                using (var stream = GetFileToUpload(10))
                {
                    blob.UploadFromStream(stream);
                }

                Console.WriteLine("Blob uplodad successful: {0}", blobSas.Name);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            
            Console.WriteLine();
            Console.WriteLine("Done. Press any key to exit...");
            Console.ReadKey();
        }
        public void StorageCredentialsSharedKey()
        {
            StorageCredentials cred = new StorageCredentials(TestBase.TargetTenantConfig.AccountName, TestBase.TargetTenantConfig.AccountKey);

            Assert.AreEqual(TestBase.TargetTenantConfig.AccountName, cred.AccountName, false);
            Assert.IsFalse(cred.IsAnonymous);
            Assert.IsFalse(cred.IsSAS);
            Assert.IsTrue(cred.IsSharedKey);

            Uri testUri = new Uri("http://test/abc?querya=1");
            Assert.AreEqual(testUri, cred.TransformUri(testUri));

            Assert.AreEqual(TestBase.TargetTenantConfig.AccountKey, Convert.ToBase64String(cred.ExportKey()));
            byte[] dummyKey = { 0, 1, 2 };
            string base64EncodedDummyKey = Convert.ToBase64String(dummyKey);
            cred.UpdateKey(base64EncodedDummyKey, null);
            Assert.AreEqual(base64EncodedDummyKey, Convert.ToBase64String(cred.ExportKey()));

#if !RTMD
            dummyKey[0] = 3;
            base64EncodedDummyKey = Convert.ToBase64String(dummyKey);
            cred.UpdateKey(dummyKey, null);
            Assert.AreEqual(base64EncodedDummyKey, Convert.ToBase64String(cred.ExportKey()));
#endif
        }
        public CloudFileDirectory(StorageUri directoryAbsoluteUri, StorageCredentials credentials)
#endif
        {
            this.Metadata = new Dictionary<string, string>();
            this.Properties = new FileDirectoryProperties();
            this.ParseQueryAndVerify(directoryAbsoluteUri, credentials);
        }
        internal static StorageCredentials GetStorageCredentials(this Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet cmdlet, String resourceGroupName, String storageAccountName)
        {
            StorageCredentials credentials = null;
            var storageClient = GetStorageClient(cmdlet);

            if (storageClient != null && storageClient.StorageAccounts != null)
            {
                var keys = storageClient.StorageAccounts.ListKeys(resourceGroupName, storageAccountName);

                if (keys != null && keys.StorageAccountKeys != null)
                {
                    var storageAccountKey = string.IsNullOrEmpty(keys.StorageAccountKeys.Key1) ? keys.StorageAccountKeys.Key2 : keys.StorageAccountKeys.Key1;

                    credentials = new StorageCredentials(storageAccountName, storageAccountKey);
                }
            }

            if (credentials == null)
            {
                cmdlet.ThrowTerminatingError(
                    new ErrorRecord(
                        new UnauthorizedAccessException(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscDefaultStorageCredentialsNotFound),
                        "CredentialsNotFound",
                        ErrorCategory.PermissionDenied,
                        null));
            }

            if (string.IsNullOrEmpty(credentials.AccountName))
            {
                ThrowInvalidArgumentError(cmdlet, Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscStorageContextMustIncludeAccountName);
            }

            return credentials;
        }
예제 #23
0
		public AzureQueueController()
		{
			var credentials = new StorageCredentials(ConfigurationManager.AppSettings["AzureAccountName"], ConfigurationManager.AppSettings["AzureKeyValue"]);
			var azureTableUri = new Uri("https://" + ConfigurationManager.AppSettings["AzureAccountName"] + ".queue.core.windows.net");
			var client = new CloudQueueClient(azureTableUri, credentials);
			_queue = client.GetQueueReference(QueueName);
		}
예제 #24
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;



        }
예제 #25
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);
        }
예제 #26
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();
        }
 /// <summary>
 /// Generates a web request to return the user-defined metadata for this container.
 /// </summary>
 /// <param name="uri">The absolute URI to the container.</param>
 /// <param name="timeout">The server timeout interval.</param>
 /// <param name="accessCondition">The access condition to apply to the request.</param>
 /// <returns>A web request to use to perform the operation.</returns>
 public static StorageRequestMessage GetMetadata(Uri uri, int? timeout, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
 {
     UriQueryBuilder containerBuilder = GetContainerUriQueryBuilder();
     StorageRequestMessage request = HttpRequestMessageFactory.GetMetadata(uri, timeout, containerBuilder, content, operationContext, canonicalizer, credentials);
     request.ApplyAccessCondition(accessCondition);
     return request;
 }
 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");
 }
예제 #29
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);
            }
        }
예제 #30
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); ;
        }
예제 #31
0
        // Helper function to allow Storage Client 1.7 (Microsoft.WindowsAzure.Storage) to utilize this class.
        // Remove this function if only using Storage Client 2.0 (Microsoft.WindowsAzure.Storage).
        public void DownloadBlobAsync(Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob blob, string LocalFile)
        {
            Microsoft.WindowsAzure.Storage.Auth.StorageCredentials account = blob.ServiceClient.Credentials as Microsoft.WindowsAzure.Storage.Auth.StorageCredentials;
            ICloudBlob blob2 = new Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob(blob.Uri, new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(blob.ServiceClient.Credentials.AccountName, account.ExportBase64EncodedKey()));

            DownloadBlobAsync(blob2, LocalFile);
        }