示例#1
0
        public async Task <string> GetStorageAccountConString(string accountName)
        {
            StorageAccountGetKeysResponse keys = await storageClient.StorageAccounts.GetKeysAsync(accountName);

            return(String.Format(CultureInfo.InvariantCulture,
                                 "DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1};",
                                 accountName, keys.SecondaryKey));
        }
        public override ProvisionAddOnResult Provision(AddonProvisionRequest request)
        {
            var provisionResult = new ProvisionAddOnResult("");
            var manifest        = request.Manifest;
            var inputDevParams  = request.DeveloperParameters;

            try
            {
                // parse required options here, use developer options class to do so.
                var manifestProperties = manifest.GetProperties();
                // Developer Options will be instantiated first time here (hence, null).
                var devParams = DeveloperParameters.Parse(inputDevParams, manifestProperties);
                // establish MSFT Azure Storage client
                var client = EstablishClient(devParams);

                // ok now we need to understand what the developer wants to do.
                // ------------------------------------------------------------
                // logic:
                //    - if the developer wishes to create a storage account, we go that route first
                //    - if a storage account exists, test it (including above)
                //    - create the blob container
                // ------------------------------------------------------------
                var parameters = CreateStorageAccountParameters(devParams);
                var mResponse  = client.StorageAccounts.Create(parameters);
                do
                {
                    StorageAccountGetResponse verificationResponse = client.StorageAccounts.Get(parameters.Name);

                    if (verificationResponse.StorageAccount.Properties.Status.Equals(StorageAccountStatus.Created))
                    {
                        StorageAccountGetResponse azureconnectioninfo =
                            client.StorageAccounts.Get(devParams.StorageAccountName);
                        StorageAccountGetKeysResponse keysForStorageUnit =
                            client.StorageAccounts.GetKeys(devParams.StorageAccountName);

                        var connectionInfo = new ConnectionInfo
                        {
                            PrimaryKey         = keysForStorageUnit.PrimaryKey,
                            SecondaryKey       = keysForStorageUnit.SecondaryKey,
                            StorageAccountName = azureconnectioninfo.StorageAccount.Name,
                            URI = keysForStorageUnit.Uri.ToString()
                        };
                        provisionResult.ConnectionData = connectionInfo.ToString();
                        // deprovision request of storage account was successful.
                        provisionResult.IsSuccess = true;
                        break;
                    }
                    Thread.Sleep(TimeSpan.FromSeconds(10d));
                } while (true);
            }
            catch (Exception e)
            {
                provisionResult.EndUserMessage = e.Message;
            }

            return(provisionResult);
        }
        private string GetAzureVmSasUri(string vmImageName)
        {
            string mediaLinkUri = null;
            Uri    uri          = null;
            StorageManagementClient storageClient         = null;
            string storageAccountName                     = null;
            StorageAccountGetKeysResponse getKeysResponse = null;
            ErrorRecord            er                     = null;
            StorageCredentials     credentials            = null;
            SharedAccessBlobPolicy accessPolicy           = null;
            CloudPageBlob          pageBlob               = null;
            string sas = null;

            mediaLinkUri       = GetImageUri(vmImageName);
            uri                = new Uri(mediaLinkUri);
            storageClient      = new StorageManagementClient(this.Client.Credentials, this.Client.BaseUri);
            storageAccountName = uri.Authority.Split('.')[0];
            getKeysResponse    = storageClient.StorageAccounts.GetKeys(storageAccountName);

            if (getKeysResponse.StatusCode != System.Net.HttpStatusCode.OK)
            {
                er = RemoteAppCollectionErrorState.CreateErrorRecordFromString(
                    String.Format(Commands_RemoteApp.GettingStorageAccountKeyErrorFormat, getKeysResponse.StatusCode.ToString()),
                    String.Empty,
                    Client.TemplateImages,
                    ErrorCategory.ConnectionError
                    );

                ThrowTerminatingError(er);
            }

            credentials  = new StorageCredentials(storageAccountName, getKeysResponse.SecondaryKey);
            accessPolicy = new SharedAccessBlobPolicy();
            pageBlob     = new CloudPageBlob(uri, credentials);

            accessPolicy.Permissions = SharedAccessBlobPermissions.Read;
            // Sometimes the clocks are 2-3 seconds fast and the SAS is not yet valid when the service tries to use it.
            accessPolicy.SharedAccessStartTime  = DateTime.UtcNow.AddMinutes(-5);
            accessPolicy.SharedAccessExpiryTime = DateTime.UtcNow.AddHours(12);

            sas = pageBlob.GetSharedAccessSignature(accessPolicy);

            if (sas == null)
            {
                er = RemoteAppCollectionErrorState.CreateErrorRecordFromString(
                    Commands_RemoteApp.FailedToGetSasUriError,
                    String.Empty,
                    Client.TemplateImages,
                    ErrorCategory.ConnectionError
                    );

                ThrowTerminatingError(er);
            }

            return(mediaLinkUri + sas);
        }
示例#4
0
        public Uri UploadFileToBlob(BlobUploadParameters parameters)
        {
            StorageAccountGetKeysResponse keys = StorageManagementClient.StorageAccounts.GetKeys(parameters.StorageName);
            string storageKey = keys.PrimaryKey;
            StorageAccountGetResponse storageService = StorageManagementClient.StorageAccounts.Get(parameters.StorageName);
            Uri blobEndpointUri = storageService.StorageAccount.Properties.Endpoints[0];

            return(UploadFile(parameters.StorageName,
                              GeneralUtilities.CreateHttpsEndpoint(blobEndpointUri.ToString()),
                              storageKey, parameters));
        }
示例#5
0
        public void DeletePackageFromBlob(string storageName, Uri packageUri)
        {
            StorageAccountGetKeysResponse keys = StorageManagementClient.StorageAccounts.GetKeys(storageName);
            string     storageKey          = keys.PrimaryKey;
            var        storageService      = StorageManagementClient.StorageAccounts.Get(storageName);
            var        blobStorageEndpoint = storageService.StorageAccount.Properties.Endpoints[0];
            var        credentials         = new StorageCredentials(storageName, storageKey);
            var        client = new CloudBlobClient(blobStorageEndpoint, credentials);
            ICloudBlob blob   = client.GetBlobReferenceFromServer(packageUri);

            blob.DeleteIfExists();
        }
示例#6
0
        /// <summary>
        /// Gets the connection string for the given storage account.
        /// </summary>
        /// <param name="storageAccountName">A storage account name.</param>
        /// <returns>The connection string for the given storage account.</returns>
        public string GetConnectionStringForStorageAccount(string storageAccountName)
        {
            // This makes a call to the Azure infrastructure to get the keys.
            // REVIEW: Check status code of the response?
            StorageAccountGetKeysResponse keys = this.storageManager.StorageAccounts.GetKeys(storageAccountName);

            string connectionString = string.Format(
                CultureInfo.InvariantCulture,
                "DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}",
                storageAccountName,
                keys.PrimaryKey);

            return(connectionString);
        }
示例#7
0
        public virtual Uri UploadPackageToBlob(
            StorageManagementClient storageClient,
            string storageName,
            string packagePath,
            BlobRequestOptions blobRequestOptions)
        {
            StorageAccountGetKeysResponse keys = storageClient.StorageAccounts.GetKeys(storageName);
            string storageKey      = keys.PrimaryKey;
            var    storageService  = storageClient.StorageAccounts.Get(storageName);
            Uri    blobEndpointUri = storageService.StorageAccount.Properties.Endpoints[0];

            return(UploadFile(storageName,
                              GeneralUtilities.CreateHttpsEndpoint(blobEndpointUri.ToString()),
                              storageKey, packagePath, blobRequestOptions));
        }
示例#8
0
        private StorageAccountGetKeysResponse GetStorageAccountKeysFromMSAzure(SubscriptionCloudCredentials credentials, string storageAccountName)
        {
            string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            using (var client = new StorageManagementClient(credentials))
            {
                Logger.Info(methodName, string.Format(ProgressResources.GetStorageAccountKeysStarted, storageAccountName), ResourceType.StorageAccount.ToString(), storageAccountName);
                ////Call management API to get keys of storage account.
                StorageAccountGetKeysResponse storageKeyResponse = Retry.RetryOperation(() => client.StorageAccounts.GetKeys(storageAccountName),
                                                                                        (BaseParameters)exportParameters,
                                                                                        ResourceType.StorageAccount, storageAccountName);
                Logger.Info(methodName, string.Format(ProgressResources.GetStorageAccountKeysCompleted, storageAccountName),
                            ResourceType.StorageAccount.ToString(), storageAccountName);
                return(storageKeyResponse);
            }
        }
 /// <summary>
 /// Gets the storage keys for the given storage account.
 /// </summary>
 public Dictionary <Constants.StorageKeyTypes, string> GetStorageKeys(string storageAccountName)
 {
     try
     {
         // intentionally returning a dictinary and not the response object to allow callees not to depand upon the storage module
         StorageAccountGetKeysResponse keys = GetCurrentStorageClient().StorageAccounts.GetKeys(storageAccountName);
         Dictionary <Constants.StorageKeyTypes, String> result = new Dictionary <Constants.StorageKeyTypes, String>();
         result.Add(Constants.StorageKeyTypes.Primary, keys.PrimaryKey);
         result.Add(Constants.StorageKeyTypes.Secondary, keys.SecondaryKey);
         return(result);
     }
     catch
     {
         throw new Exception(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.StorageAccountNotFound, storageAccountName));
     }
 }
示例#10
0
        private async Task <Dictionary <string, string> > ListStorageAccounts()
        {
            Dictionary <string, string> accountDictionary = new Dictionary <string, string>();

            CertificateCloudCredentials creds    = new CertificateCloudCredentials(_id, _certificate);
            StorageManagementClient     client   = new StorageManagementClient(creds);
            StorageAccountListResponse  accounts = await client.StorageAccounts.ListAsync();

            foreach (var account in accounts)
            {
                StorageAccountGetKeysResponse keys = await client.StorageAccounts.GetKeysAsync(account.Name);

                accountDictionary.Add(account.Name, keys.PrimaryKey);
            }

            return(accountDictionary);
        }
示例#11
0
        private Task <StorageAccountGetKeysResponse> CreateGetKeysResponse(string serviceName)
        {
            Task <StorageAccountGetKeysResponse> resultTask;
            var data = accounts.FirstOrDefault(a => a.Name == serviceName);

            if (data != null)
            {
                var response = new StorageAccountGetKeysResponse
                {
                    PrimaryKey   = data.PrimaryKey,
                    SecondaryKey = data.SecondaryKey,
                    StatusCode   = HttpStatusCode.OK
                };
                resultTask = Tasks.FromResult(response);
            }
            else
            {
                resultTask = Tasks.FromException <StorageAccountGetKeysResponse>(ClientMocks.Make404Exception());
            }
            return(resultTask);
        }
        public override void ExecuteCmdlet()
        {
            MediaServicesClient = MediaServicesClient ?? new MediaServicesClient(Profile, Profile.Context.Subscription, WriteDebug);

            StorageAccountGetKeysResponse storageKeysResponse = null;
            Uri    storageEndPoint   = null;
            string storageAccountKey = null;

            CatchAggregatedExceptionFlattenAndRethrow(() => { storageKeysResponse = MediaServicesClient.GetStorageServiceKeysAsync(StorageAccountName).Result; });
            storageAccountKey = storageKeysResponse.PrimaryKey;

            StorageAccountGetResponse storageGetResponse = null;

            CatchAggregatedExceptionFlattenAndRethrow(() => { storageGetResponse = MediaServicesClient.GetStorageServicePropertiesAsync(StorageAccountName).Result; });

            if (storageGetResponse.StorageAccount.Properties != null && storageGetResponse.StorageAccount.Properties.Endpoints.Count > 0)
            {
                storageEndPoint = storageGetResponse.StorageAccount.Properties.Endpoints[0];
            }
            else
            {
                throw new Exception(string.Format(Resources.EndPointNotFoundForBlobStorage, Name));
            }

            AccountCreationResult result = null;
            var request = new MediaServicesAccountCreateParameters()
            {
                AccountName            = Name,
                BlobStorageEndpointUri = storageEndPoint,
                Region             = Location,
                StorageAccountKey  = storageAccountKey,
                StorageAccountName = StorageAccountName
            };

            CatchAggregatedExceptionFlattenAndRethrow(() => { result = new AccountCreationResult(MediaServicesClient.CreateNewAzureMediaServiceAsync(request).Result); });
            WriteObject(result, false);
        }
 private Task<StorageAccountGetKeysResponse> CreateGetKeysResponse(string serviceName)
 {
     Task<StorageAccountGetKeysResponse> resultTask;
     var data = accounts.FirstOrDefault(a => a.Name == serviceName);
     if (data != null)
     {
         var response = new StorageAccountGetKeysResponse
         {
             PrimaryKey = data.PrimaryKey,
             SecondaryKey = data.SecondaryKey,
             StatusCode = HttpStatusCode.OK
         };
         resultTask = Tasks.FromResult(response);
     }
     else
     {
         resultTask = Tasks.FromException<StorageAccountGetKeysResponse>(ClientMocks.Make404Exception());
     }
     return resultTask;
 }