예제 #1
0
        /// <summary>
        /// Uploads a file to azure store.
        /// </summary>
        /// <param name="storageName">Store which file will be uploaded to</param>
        /// <param name="storageKey">Store access key</param>
        /// <param name="filePath">Path to file which will be uploaded</param>
        /// <param name="blobRequestOptions">The request options for blob uploading.</param>
        /// <returns>Uri which holds locates the uploaded file</returns>
        /// <remarks>The uploaded file name will be guid</remarks>
        public static Uri UploadFile(string storageName, string storageKey, string filePath, BlobRequestOptions blobRequestOptions)
        {
            string baseAddress = General.BlobEndpointUri(storageName);
            var credentials = new StorageCredentialsAccountAndKey(storageName, storageKey);
            var client = new CloudBlobClient(baseAddress, credentials);
            string blobName = Guid.NewGuid().ToString();

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

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

            return new Uri(
                string.Format(
                    CultureInfo.InvariantCulture,
                    "{0}{1}{2}{3}",
                    client.BaseUri,
                    ContainerName,
                    client.DefaultDelimiter,
                    blobName));
        }
예제 #2
0
 public Encoder(CloudMediaContext context, StorageCredentialsAccountAndKey storageCredentials, MediaEncoding mediaEncoding, TextWriter textWriter)
 {
     this.context            = context;
     this.storageCredentials = storageCredentials;
     this.MediaEncoding      = mediaEncoding;
     this.textWriter         = textWriter;
 }
        /// <summary>
        /// Connect to an Azure subscription and upload a package to blob storage.
        /// </summary>
        protected override void AzureExecute()
        {
            string storageKey  = this.StorageKeys.Get(this.ActivityContext).Primary;
            string storageName = this.StorageServiceName.Get(this.ActivityContext);
            string filePath    = this.LocalPackagePath.Get(this.ActivityContext);

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

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

            CloudBlobContainer container = client.GetContainerReference(ContainerName);

            container.CreateIfNotExist();
            CloudBlob blob = container.GetBlobReference(blobName);

            UploadBlobStream(blob, filePath);

            this.PackageUrl.Set(this.ActivityContext, string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}", client.BaseUri, ContainerName, client.DefaultDelimiter, blobName));
        }
        private CloudBlobContainer InitContainer()
        {
            // Get a handle on account, create a blob service client and get container proxy

            StorageCredentialsAccountAndKey credentials    = new StorageCredentialsAccountAndKey(ConfigurationManager.AppSettings["storageAccount"], ConfigurationManager.AppSettings["storageKey"]);
            CloudStorageAccount             storageAccount = new CloudStorageAccount(credentials, false);
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            var container = blobClient.GetContainerReference(ConfigurationManager.AppSettings["containerName"]);

            try
            {
                container.CreateIfNotExist();
            }
            catch (StorageClientException sce)
            {
                if (sce.ErrorCode.Equals(StorageErrorCode.ContainerAlreadyExists))
                {
                    //nothing, already there;
                }
                else
                {
                    throw sce;
                }
            }

            var permissions = container.GetPermissions();

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

            return(container);
        }
예제 #5
0
        static void Main(string[] args)
        {
            //Replace the credentials with your own.
            StorageCredentialsAccountAndKey credentials = new StorageCredentialsAccountAndKey("silverliningstorage1",
                                                                                              "ZXdXkdkUa7EMxoTtygmbC8CV9keeMxWrBOQaFCfYHNZYjj8DX56y0DofQaaC3DmgCGf049C/SSgEnhapWWoTjT1/zXPAi==");

            //Create a storage account instance
            CloudStorageAccount storageAccount = new CloudStorageAccount(credentials, true);

            //Create a new blob client instance
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            //Create a new container instance
            CloudBlobContainer container = blobClient.GetContainerReference("mycdn");

            //Create the container if it does not exist
            container.CreateIfNotExist();

            //Specify that the container is publicly accessible. This is a requirement for CDN
            BlobContainerPermissions containerPermissions = new BlobContainerPermissions();

            containerPermissions.PublicAccess = BlobContainerPublicAccessType.Container;
            container.SetPermissions(containerPermissions);

            //Create a new blob
            CloudBlob blob = blobClient.GetBlobReference("mycdn/mytestblob.txt");

            blob.UploadText("My first CDN Blob.");

            //Set the Cache-Control header property of the blob and specify your desired refresh interval (in seconds).
            blob.Properties.CacheControl = "public, max-age=30036000";
            blob.SetProperties();
        }
        /// <summary>
        /// Set analytics settings
        /// </summary>
        /// <param name="baseUri"></param>
        /// <param name="credentials"></param>
        /// <param name="settings"></param>
        /// <param name="useSharedKeyLite"></param>
        public static void SetSettings(Uri baseUri, StorageCredentials credentials, AnalyticsSettings settings, Boolean useSharedKeyLite)
        {
            UriBuilder builder = new UriBuilder(baseUri);

            builder.Query = string.Format(
                CultureInfo.InvariantCulture,
                "comp=properties&restype=service&timeout={0}",
                DefaultTimeout.TotalSeconds);

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(builder.Uri);

            request.Headers.Add(VersionHeaderName, Sep2009Version);
            request.Method = "PUT";

            StorageCredentialsAccountAndKey accountAndKey = credentials as StorageCredentialsAccountAndKey;

            using (MemoryStream buffer = new MemoryStream())
            {
                XmlTextWriter writer = new XmlTextWriter(buffer, Encoding.UTF8);
                SettingsSerializerHelper.SerializeAnalyticsSettings(writer, settings);
                writer.Flush();
                buffer.Seek(0, SeekOrigin.Begin);
                request.ContentLength = buffer.Length;

                if (useSharedKeyLite)
                {
                    credentials.SignRequestLite(request);
                }
                else
                {
                    credentials.SignRequest(request);
                }

                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(buffer.GetBuffer(), 0, (int)buffer.Length);
                }

                try
                {
                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        Console.WriteLine("Response Request Id = {0} Status={1}", response.Headers[RequestIdHeaderName], response.StatusCode);
                        if (HttpStatusCode.Accepted != response.StatusCode)
                        {
                            throw new Exception("Request failed with incorrect response status.");
                        }
                    }
                }
                catch (WebException e)
                {
                    Console.WriteLine(
                        "Response Request Id={0} Status={1}",
                        e.Response != null ? e.Response.Headers[RequestIdHeaderName] : "Response is null",
                        e.Status);
                    throw;
                }
            }
        }
예제 #7
0
        internal static string GetInitExceptionDescription(StorageCredentialsAccountAndKey table, Uri tableBaseUri, StorageCredentialsAccountAndKey blob, Uri blobBaseUri)
        {
            StringBuilder builder = new StringBuilder();

            builder.Append(GetInitExceptionDescription(table, tableBaseUri, "table storage configuration"));
            builder.Append(GetInitExceptionDescription(blob, blobBaseUri, "blob storage configuration"));
            return(builder.ToString());
        }
        /// <summary>
        /// Get analytics settings
        /// </summary>
        /// <param name="baseUri"></param>
        /// <param name="credentials"></param>
        /// <param name="useSharedKeyLite"></param>
        /// <returns></returns>
        public static AnalyticsSettings GetSettings(Uri baseUri, StorageCredentials credentials, bool useSharedKeyLite)
        {
            UriBuilder builder = new UriBuilder(baseUri);

            builder.Query = string.Format(
                CultureInfo.InvariantCulture,
                "comp=properties&restype=service&timeout={0}",
                DefaultTimeout.TotalSeconds);

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(builder.Uri);

            request.Headers.Add(VersionHeaderName, Sep2009Version);
            request.Method = "GET";

            StorageCredentialsAccountAndKey accountAndKey = credentials as StorageCredentialsAccountAndKey;

            if (useSharedKeyLite)
            {
                credentials.SignRequestLite(request);
            }
            else
            {
                credentials.SignRequest(request);
            }

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    Console.WriteLine("Response Request Id={0} Status={1}", response.Headers[RequestIdHeaderName], response.StatusCode);

                    if (HttpStatusCode.OK != response.StatusCode)
                    {
                        throw new Exception("expected HttpStatusCode.OK");
                    }

                    using (Stream stream = response.GetResponseStream())
                    {
                        using (StreamReader streamReader = new StreamReader(stream))
                        {
                            string responseString = streamReader.ReadToEnd();
                            Console.WriteLine(responseString);

                            XmlReader reader = XmlReader.Create(new MemoryStream(ASCIIEncoding.UTF8.GetBytes(responseString)));
                            return(SettingsSerializerHelper.DeserializeAnalyticsSettings(reader));
                        }
                    }
                }
            }
            catch (WebException e)
            {
                Console.WriteLine(
                    "Response Request Id={0} Status={1}",
                    e.Response != null ? e.Response.Headers[RequestIdHeaderName] : "Response is null",
                    e.Status);
                throw;
            }
        }
        public static CloudStorageAccount GetStorageAccount()
        {
            StorageCredentials crendentials = new StorageCredentialsAccountAndKey(AzureBlobServiceSettings.Instance.AccountName
                                                                                  , AzureBlobServiceSettings.Instance.AccountKey);
            Uri blobEndpoint = new Uri(AzureBlobServiceSettings.Instance.Endpoint);
            CloudStorageAccount storageAccount = new CloudStorageAccount(crendentials, blobEndpoint, null, null);

            return(storageAccount);
        }
예제 #10
0
        public static CloudStorageAccount GetStorageAccount()
        {
            StorageCredentials crendentials = new StorageCredentialsAccountAndKey(SiteOnAzureTableSettings.Instance.AccountName
                                                                                  , SiteOnAzureTableSettings.Instance.AccountKey);
            Uri tableEndpoint = new Uri(SiteOnAzureTableSettings.Instance.Endpoint);
            CloudStorageAccount storageAccount = new CloudStorageAccount(crendentials, null, null, tableEndpoint);

            return(storageAccount);
        }
예제 #11
0
        public WindowsAzureStorageHelperWA(string accountName, string accountKey, bool isLocal, string blobEndpointURI, string queueEndpointURI, string tableEndpointURI)
        {
            ContainerName = CONTAINER_NAME;

            StorageCredentials sc = new StorageCredentialsAccountAndKey(accountName, accountKey);

            StorageAccountInfo = new CloudStorageAccount(sc, new Uri(blobEndpointURI), new Uri(queueEndpointURI), new Uri(tableEndpointURI));
            InitStorage(StorageAccountInfo);
        }
        public BlobFactory(string accountName, string key)
        {
            //Specify storage credentials.
            StorageCredentialsAccountAndKey credentials = new StorageCredentialsAccountAndKey(accountName, key);

            //Create a reference to your storage account, passing in your credentials.
            CloudStorageAccount storageAccount = new CloudStorageAccount(credentials, true);

            _blobClient = GetBlobClient(storageAccount);
        }
예제 #13
0
파일: Utilities.cs 프로젝트: argodev/stahc
        public static string UploadFileToCloud(
            string accountName,
            string accountKey,
            string containerName,
            string targetPath,
            string localPath)
        {
            var credentials = new StorageCredentialsAccountAndKey(accountName, accountKey);

            return(UploadFileToCloud(credentials, containerName, targetPath, localPath));
        }
예제 #14
0
        public CloudQueueClient GetCloudQueueClient()
        {
            StorageCredentials credentials = new StorageCredentialsAccountAndKey(accountName, accountKey);

            CloudStorageAccount storageAccountInfo = new CloudStorageAccount(credentials, blobEndpoint, queueEndpoint, tableEndpoint);

            CloudQueueClient cloudQueueClient = storageAccountInfo.CreateCloudQueueClient();

            cloudQueueClient.Timeout = new TimeSpan(0, 30, 0);
            return(cloudQueueClient);
        }
예제 #15
0
파일: Utilities.cs 프로젝트: argodev/stahc
        public static string UploadFileToCloud(
            StorageCredentialsAccountAndKey credentials,
            string containerName,
            string targetPath,
            string localPath)
        {
            // instantiate the Cloud blob client
            var account = new CloudStorageAccount(credentials, false);
            var client  = account.CreateCloudBlobClient();

            // ensure that the target container exists
            var container = client.GetContainerReference(containerName);

            container.CreateIfNotExist();

            // upload the file
            var blob = container.GetBlockBlobReference(targetPath);

            // we should check to see if the file exists prior to
            // uploading. If it is already there, don't waste the upload time
            try
            {
                blob.FetchAttributes();

                // if we get a valid value back for the length, we know that the file
                // already exists and we can likely continue on w/o re-uploading
                if (blob.Attributes.Properties.Length > 0)
                {
                    // does the remote file size match the local file size?
                    long remoteLength = blob.Attributes.Properties.Length;
                    long localLength  = (new FileInfo(localPath)).Length;

                    // file already exists... can we avoid re-uploading?
                    if (remoteLength != localLength)
                    {
                        blob.ParallelUploadFile(localPath, null, 1048576);
                    }
                }
                else
                {
                    blob.ParallelUploadFile(localPath, null, 1048576);
                }
            }
            catch (StorageClientException)
            {
                // most often due to the blob not existing. Squash
                // and continue.
                blob.ParallelUploadFile(localPath, null, 1048576);
            }

            // return the URL
            return(blob.Uri.ToString());
        }
예제 #16
0
        private static AssetHelper GetAssetHelper(TextWriter textWriter)
        {
            textWriter.WriteLine("Instantiating the classes required to ingest, encode and locate a video file.");
            textWriter.WriteLine();

            var cloudMediaContext  = new CloudMediaContext(Config.MEDIA_ACCOUNT_NAME, Config.MEDIA_ACCESS_KEY);
            var restServices       = new RestServices(Config.MEDIA_ACCOUNT_NAME, Config.MEDIA_ACCESS_KEY);
            var storageCredentials = new StorageCredentialsAccountAndKey(Config.STORAGE_ACCOUNT_NAME, Config.STORAGE_ACCESS_KEY);
            var encoder            = new Encoder(cloudMediaContext, storageCredentials, MediaEncodings.H264_HD_720p_Vbr, textWriter);

            return(new AssetHelper(cloudMediaContext, encoder, restServices, textWriter));
        }
예제 #17
0
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            //Open the dialog box
            System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog();
            dialog.InitialDirectory = "C:/";
            dialog.Multiselect      = true;
            dialog.RestoreDirectory = true;
            System.Windows.Forms.DialogResult Result = dialog.ShowDialog();

            string[] files;
            //Load the image to the load image picture box
            if (Result == System.Windows.Forms.DialogResult.OK)
            {
                files = dialog.FileNames;

                string blobUri = SettingsValues.BLOB_URL;
                string key     = SettingsValues.BLOB_KEY;
                string account = SettingsValues.BLOB_ACCOUNT;
                StorageCredentialsAccountAndKey credentials = new StorageCredentialsAccountAndKey(account, key);
                CloudBlobClient client = new CloudBlobClient(blobUri, credentials);

                string             containerName = "container";
                CloudBlobContainer blobContainer = client.GetContainerReference(containerName);
                bool created = blobContainer.CreateIfNotExist();

                resourceFiles = new List <ResourceFile>();

                foreach (string strFile in files)
                {
                    string[] chunks   = strFile.Split('\\');
                    string   blobName = chunks[chunks.Length - 1];
                    string   filePath = strFile.Substring(0, strFile.Length - blobName.Length);

                    CloudBlob blob = blobContainer.GetBlobReference(blobName);
                    //System.Windows.MessageBox.Show(string.Format("filepath: {0}", strFile));
                    blob.UploadFile(strFile);

                    SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
                    policy.Permissions            = SharedAccessBlobPermissions.Read;
                    policy.SharedAccessExpiryTime = DateTime.Now.AddHours(1);

                    string token            = blob.GetSharedAccessSignature(policy);
                    string resourceBlobPath = blobUri + "/" + containerName + "/" + blobName + token;

                    System.Windows.MessageBox.Show("Uploading file complete");

                    DataRow row = dataTable1.NewRow();;
                    row.ItemArray = new object[] { blobName, resourceBlobPath };
                    dataView1.Table.Rows.Add(row);
                }
            }
        }
예제 #18
0
        public static void Initialize(string account, string key)
        {
            Uri blobUri  = new Uri(string.Format("http://{0}.blob.core.windows.net", account));
            Uri queueUri = new Uri(string.Format("http://{0}.queue.core.windows.net", account));
            Uri tableUri = new Uri(string.Format("http://{0}.table.core.windows.net", account));

            s_credentials    = new StorageCredentialsAccountAndKey(account, key);
            s_storageAccount = new CloudStorageAccount(s_credentials, blobUri, queueUri, tableUri);

            s_blobClient  = s_storageAccount.CreateCloudBlobClient();
            s_tableClient = s_storageAccount.CreateCloudTableClient();
            s_queueClient = s_storageAccount.CreateCloudQueueClient();
        }
예제 #19
0
        /// <summary>
        /// Removes file from storage account
        /// </summary>
        /// <param name="storageName">Store which has file to remove</param>
        /// <param name="storageKey">Store access key</param>
        private static void RemoveFile(string storageName, string storageKey)
        {
            var baseAddress = string.Format(CultureInfo.InvariantCulture, AzureBlob.BlobEndpointTemplate, storageName);
            var credentials = new StorageCredentialsAccountAndKey(storageName, storageKey);
            var client      = new CloudBlobClient(baseAddress, credentials);

            CloudBlobContainer container = client.GetContainerReference(containerName);

            if (Exists(container))
            {
                container.Delete();
            }
        }
예제 #20
0
        private static void DownloadVHDFromCloud(Config config)
        {
            StorageCredentialsAccountAndKey creds =
                new StorageCredentialsAccountAndKey(config.Account, config.Key);

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

            blobStorage.ReadAheadInBytes = 0;

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

            // Get the length of the blob
            pageBlob.FetchAttributes();
            long vhdLength       = pageBlob.Properties.Length;
            long totalDownloaded = 0;

            Console.WriteLine("Vhd size:  " + Megabytes(vhdLength));

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

            fileStream.SetLength(vhdLength);

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

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

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

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

                    blobStream.Read(buffer, 0, subRangeSize);
                    fileStream.Write(buffer, 0, subRangeSize);
                    totalDownloaded += subRangeSize;
                }
            }
            Console.WriteLine("Downloaded " + Megabytes(totalDownloaded) + " of " + Megabytes(vhdLength));
        }
예제 #21
0
        public BlobFactory(string azureAccountName, string azureKey)
        {
            // initialize Azure Account
            StorageCredentialsAccountAndKey storageKey   = new StorageCredentialsAccountAndKey(azureAccountName, azureKey);
            CloudStorageAccount             azureAccount = new CloudStorageAccount(storageKey, true);

            // Create blob containers
            CloudBlobClient blobClient = azureAccount.CreateCloudBlobClient();

            userContainer    = blobClient.GetContainerReference("user");
            accountContainer = blobClient.GetContainerReference("account");
            listContainer    = blobClient.GetContainerReference("list");
            msgContainer     = blobClient.GetContainerReference("msg");
        }
예제 #22
0
        private static CloudStorageAccount GetStorageAccount()
        {
            //Return Storage Account
            CloudStorageAccount storageAccount;

#if DEBUG
            //Debug.WriteLine("Mode=Debug");
            storageAccount = CloudStorageAccount.DevelopmentStorageAccount;
#else
            StorageCredentialsAccountAndKey storageCredentials = new StorageCredentialsAccountAndKey(_AccountName, _AccountKey);
            storageAccount = new CloudStorageAccount(storageCredentials, true);
#endif
            return(storageAccount);
        }
예제 #23
0
        public static void DeletePackageFromBlob(IServiceManagement channel, string storageName, string subscriptionId, Uri packageUri)
        {
            StorageService storageKeys = channel.GetStorageKeys(subscriptionId, storageName);
            string         primary     = storageKeys.StorageServiceKeys.Primary;

            storageKeys = channel.GetStorageService(subscriptionId, storageName);
            EndpointList endpoints = storageKeys.StorageServiceProperties.Endpoints;
            string       str       = ((List <string>)endpoints).Find((string p) => p.Contains(".blob."));
            StorageCredentialsAccountAndKey storageCredentialsAccountAndKey = new StorageCredentialsAccountAndKey(storageName, primary);
            CloudBlobClient cloudBlobClient = new CloudBlobClient(str, storageCredentialsAccountAndKey);
            CloudBlob       blobReference   = cloudBlobClient.GetBlobReference(packageUri.AbsoluteUri);

            blobReference.DeleteIfExists();
        }
예제 #24
0
        public void DownloadFile(String containerName, String fileName, String key)
        {
            StorageCredentials credentials = new StorageCredentialsAccountAndKey(accountName, accountKey);

            CloudStorageAccount storageAccountInfo = new CloudStorageAccount(credentials, blobEndpoint, queueEndpoint, tableEndpoint);

            CloudBlobClient cloudBlobClient = storageAccountInfo.CreateCloudBlobClient();

            cloudBlobClient.Timeout = new TimeSpan(0, 30, 0);

            cloudBlobClient.GetContainerReference(containerName).CreateIfNotExist();
            CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(containerName);

            cloudBlobContainer.GetBlobReference(key).DownloadToFile(fileName);
        }
예제 #25
0
        internal static string GetInitExceptionDescription(StorageCredentialsAccountAndKey info, Uri baseUri, string desc)
        {
            StringBuilder builder = new StringBuilder();

            builder.Append("The reason for this exception is typically that the endpoints are not correctly configured. " + Environment.NewLine);
            if (info == null)
            {
                builder.Append("The current " + desc + " is null. Please specify a table endpoint!" + Environment.NewLine);
            }
            else
            {
                builder.Append("The current " + desc + " is: " + baseUri + Environment.NewLine);
                builder.Append("Please also make sure that the account name and the shared key are specified correctly. This information cannot be shown here because of security reasons.");
            }
            return(builder.ToString());
        }
예제 #26
0
        private CloudBlobClient InitializeStorage(string containerName)
        {
            CloudBlobClient blobStorage = null;

            try
            {
                if (string.IsNullOrEmpty(StorageKey))
                {
                    StorageKey = ConfigurationManager.AppSettings["StorageKey"];
                }

                if (string.IsNullOrEmpty(StorageName))
                {
                    StorageName = ConfigurationManager.AppSettings["StorageAccountName"];
                }

                // Create the storage account object
                StorageCredentialsAccountAndKey key =
                    new StorageCredentialsAccountAndKey(StorageName, StorageKey);
                CloudStorageAccount storageAccount =
                    new CloudStorageAccount(key, useHttps: false);

                blobStorage = storageAccount.CreateCloudBlobClient();

                // Get the container (create it if necessary)
                CloudBlobContainer container =
                    blobStorage.GetContainerReference(containerName.ToLower());
                container.CreateIfNotExist();

                // Assign public access to the blob container
                var permissions = container.GetPermissions();
                permissions.PublicAccess = BlobContainerPublicAccessType.Container;
                container.SetPermissions(permissions);
            }
            catch (Exception ex)
            {
                Console.WriteLine("InitializeStorage failed");
                Console.WriteLine("Error Message: {0} ", ex.Message);
                Console.WriteLine("Source: {0} ", ex.Source);
                Console.WriteLine(ex.StackTrace);
            }

            return(blobStorage);
        }
예제 #27
0
        public void StoreFile(String fileName, String containerName, String key)
        {
            StorageCredentials credentials = new StorageCredentialsAccountAndKey(accountName, accountKey);

            CloudStorageAccount storageAccountInfo = new CloudStorageAccount(credentials, blobEndpoint, queueEndpoint, tableEndpoint);

            CloudBlobClient cloudBlobClient = storageAccountInfo.CreateCloudBlobClient();

            cloudBlobClient.Timeout = new TimeSpan(0, 30, 0);

            cloudBlobClient.GetContainerReference(containerName).CreateIfNotExist();
            CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(containerName);

            cloudBlobContainer.GetBlobReference(key).UploadFile(fileName);
            CloudBlob cloudBlob = cloudBlobContainer.GetBlobReference(key);

            cloudBlob.Attributes.Properties.ContentType = "audio/mp3";
            cloudBlob.SetProperties();
        }
예제 #28
0
        public static void WriteDebugBlob(string blobName, string message)
        {
            string destinationAccountName = "";
            string destinationAccessKey   = "";
            string destinationContainer   = "";

            StorageCredentialsAccountAndKey accountAndKey = new StorageCredentialsAccountAndKey(destinationAccountName, destinationAccessKey);
            CloudStorageAccount             account       = new CloudStorageAccount(accountAndKey, false);
            CloudBlobClient    client    = account.CreateCloudBlobClient();
            CloudBlobContainer container = client.GetContainerReference(destinationContainer);

            CloudBlob blob   = container.GetBlobReference(blobName);
            Stream    stream = blob.OpenWrite();

            using (TextWriter writer = new StreamWriter(stream))
            {
                writer.Write("{0} {1}", DateTime.UtcNow, message);
            }
        }
예제 #29
0
파일: Disks.cs 프로젝트: modulexcite/pash-1
        public static void RemoveVHD(IServiceManagement channel, string subscriptionId, Uri mediaLink)
        {
            StorageService storageKeys;

            char[] chrArray = new char[1];
            chrArray[0] = '.';
            string str        = mediaLink.Host.Split(chrArray)[0];
            string components = mediaLink.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);

            using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)channel))
            {
                storageKeys = channel.GetStorageKeys(subscriptionId, str);
            }
            StorageCredentialsAccountAndKey storageCredentialsAccountAndKey = new StorageCredentialsAccountAndKey(str, storageKeys.StorageServiceKeys.Primary);
            CloudBlobClient cloudBlobClient = new CloudBlobClient(components, storageCredentialsAccountAndKey);
            CloudBlob       blobReference   = cloudBlobClient.GetBlobReference(mediaLink.AbsoluteUri);

            blobReference.DeleteIfExists();
        }
예제 #30
0
        public static CloudQueue InitializeQueue(string queueName)
        {
            CloudQueueClient queueStorage = null;

            if (AzureStorageKey == null)
            {
                var clientStorageAccount = CloudStorageAccount.DevelopmentStorageAccount;
                queueStorage = new CloudQueueClient(clientStorageAccount.QueueEndpoint.AbsoluteUri, clientStorageAccount.Credentials);
            }
            else
            {
                byte[] key   = Convert.FromBase64String(AzureStorageKey);
                var    creds = new StorageCredentialsAccountAndKey(AccountName, key);
                queueStorage = new CloudQueueClient(String.Format("http://{0}.queue.core.windows.net", AccountName), creds);
            }

            CloudQueue queue = queueStorage.GetQueueReference(queueName);

            queue.CreateIfNotExist();
            return(queue);
        }
예제 #31
0
        public static CloudBlobContainer initContainer(string containerName, ref string baseUri)
        {
            baseUri = null;
            CloudBlobClient blobStorage = null;

            if (AccountKey == null)
            {
                var clientStorageAccount = CloudStorageAccount.DevelopmentStorageAccount; // use storage services in the Developer Fabric, not real cloud
                baseUri     = clientStorageAccount.BlobEndpoint.AbsoluteUri;
                blobStorage = new CloudBlobClient(baseUri, clientStorageAccount.Credentials);
            }
            else
            {
                byte[] key   = Convert.FromBase64String(AccountKey);
                var    creds = new StorageCredentialsAccountAndKey(AccountName, key);
                baseUri     = string.Format("http://{0}.blob.core.windows.net", AccountName);
                blobStorage = new CloudBlobClient(baseUri, creds);
            }

            return(blobStorage.GetContainerReference(containerName));
        }
예제 #32
0
        /// <summary>
        /// Removes file from storage account
        /// </summary>
        /// <param name="storageName">Store which has file to remove</param>
        /// <param name="storageKey">Store access key</param>
        private static void RemoveFile(string storageName, string storageKey)
        {
            string baseAddress = General.BlobEndpointUri(storageName);
            var credentials = new StorageCredentialsAccountAndKey(storageName, storageKey);
            var client = new CloudBlobClient(baseAddress, credentials);

            CloudBlobContainer container = client.GetContainerReference(ContainerName);
            if (Exists(container))
            {
                container.Delete();
            }
        }
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            //Open the dialog box
            System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog();
            dialog.InitialDirectory = "C:/";
            dialog.Multiselect = true;
            dialog.RestoreDirectory = true;
            System.Windows.Forms.DialogResult Result = dialog.ShowDialog();

            string[] files;
            //Load the image to the load image picture box
            if (Result == System.Windows.Forms.DialogResult.OK)
            {
                files = dialog.FileNames;

                string blobUri = SettingsValues.BLOB_URL;
                string key = SettingsValues.BLOB_KEY;
                string account = SettingsValues.BLOB_ACCOUNT;
                StorageCredentialsAccountAndKey credentials = new StorageCredentialsAccountAndKey(account, key);
                CloudBlobClient client = new CloudBlobClient(blobUri, credentials);

                string containerName = "container";
                CloudBlobContainer blobContainer = client.GetContainerReference(containerName);
                bool created = blobContainer.CreateIfNotExist();

                resourceFiles = new List<ResourceFile>();

                foreach (string strFile in files)
                {
                    string[] chunks = strFile.Split('\\');
                    string blobName = chunks[chunks.Length - 1];
                    string filePath = strFile.Substring(0, strFile.Length - blobName.Length);

                    CloudBlob blob = blobContainer.GetBlobReference(blobName);
                    //System.Windows.MessageBox.Show(string.Format("filepath: {0}", strFile));
                    blob.UploadFile(strFile);

                    SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
                    policy.Permissions = SharedAccessBlobPermissions.Read;
                    policy.SharedAccessExpiryTime = DateTime.Now.AddHours(1);
                    
                    string token = blob.GetSharedAccessSignature(policy);
                    string resourceBlobPath = blobUri + "/" + containerName + "/" + blobName + token;

                    System.Windows.MessageBox.Show("Uploading file complete");

                    DataRow row = dataTable1.NewRow(); ;
                    row.ItemArray = new object[]{blobName, resourceBlobPath};
                    dataView1.Table.Rows.Add(row);
                }
            }
        }