Пример #1
0
 public static void DeletePackageFromBlob(
     StorageManagementClient storageClient,
     string storageName,
     Uri packageUri)
 {
     cloudBlobUtility.DeletePackageFromBlob(storageClient, storageName, packageUri);
 }
 protected void EnsureClientsInitialized(bool useSPN = false)
 {
     if (!m_initialized)
     {
         lock (m_lock)
         {
             if (!m_initialized)
             {
                 var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
                 if (useSPN)
                 {
                     m_ResourcesClient = ComputeManagementTestUtilities.GetResourceManagementClientWithSpn(handler);
                     m_CrpClient = ComputeManagementTestUtilities.GetComputeManagementClientWithSpn(handler);
                     m_SrpClient = ComputeManagementTestUtilities.GetStorageManagementClientSpn(handler);
                     m_NrpClient = ComputeManagementTestUtilities.GetNetworkResourceProviderClientSpn(handler);
                 }
                 else
                 {
                     m_ResourcesClient = ComputeManagementTestUtilities.GetResourceManagementClient(handler);
                     m_CrpClient = ComputeManagementTestUtilities.GetComputeManagementClient(handler);
                     m_SrpClient = ComputeManagementTestUtilities.GetStorageManagementClient(handler);
                     m_NrpClient = ComputeManagementTestUtilities.GetNetworkResourceProviderClient(handler);
                 }
                 m_subId = m_CrpClient.Credentials.SubscriptionId;
                 m_location = ComputeManagementTestUtilities.DefaultLocation;
             }
         }
     }
 }
 public DataLakeAnalyticsManagementHelper(TestBase testBase)
 {
     this.testBase = testBase;
     resourceManagementClient = this.testBase.GetResourceManagementClient();
     storageManagementClient = this.testBase.GetStorageManagementClient();
     dataLakeStoreManagementClient = this.testBase.GetDataLakeStoreManagementClient();
 }
Пример #4
0
 public AEMHelper(Action<ErrorRecord> errorAction, Action<string> verboseAction, Action<string> warningAction,
     PSHostUserInterface ui, StorageManagementClient storageClient, AzureSubscription subscription)
 {
     this._ErrorAction = errorAction;
     this._VerboseAction = verboseAction;
     this._WarningAction = warningAction;
     this._UI = ui;
     this._StorageClient = storageClient;
     this._Subscription = subscription;
 }
Пример #5
0
        protected void SetupManagementClients(MockContext context)
        {
            ResourceManagementClient = context.GetServiceClient <ResourceManagementClient>(TestEnvironmentFactory.GetTestEnvironment());
            SecurityInsightsClient   = context.GetServiceClient <SecurityInsightsClient>(TestEnvironmentFactory.GetTestEnvironment());
            StorageManagementClient  = context.GetServiceClient <StorageManagementClient>(TestEnvironmentFactory.GetTestEnvironment());

            _helper.SetupManagementClients(
                ResourceManagementClient,
                StorageManagementClient,
                SecurityInsightsClient);
        }
 public AzureClientInitializer(
     TokenCredential credential,
     StorageManagementClient storageManagementClient,
     ResourcesManagementClient resourcesManagementClient)
 {
     _credential = credential ?? throw new ArgumentNullException(nameof(credential));
     _storageManagementClient = storageManagementClient
                                ?? throw new ArgumentNullException(nameof(storageManagementClient));
     _resourcesManagementClient = resourcesManagementClient
                                  ?? throw new ArgumentNullException(nameof(resourcesManagementClient));
 }
Пример #7
0
        public VMManagementController(VMManagementControllerParameters parameters)
        {
            _parameters = parameters;

            // To authenticate against the Microsoft Azure service management API we require management certificate
            // load this from a publish settings file and later use it with the Service Management Libraries
            var credentials = GetSubscriptionCloudCredentials(parameters.PublishSettingsFilePath);

            _storageManagementClient = CloudContext.Clients.CreateStorageManagementClient(credentials);
            _computeManagementClient = CloudContext.Clients.CreateComputeManagementClient(credentials);
        }
Пример #8
0
        protected StorageManagementClient GetStorageClient()
        {
            StorageManagementClient client = TestBase.GetServiceClient <StorageManagementClient>(new RDFETestEnvironmentFactory());

            if (HttpMockServer.Mode == HttpRecorderMode.Playback)
            {
                client.LongRunningOperationInitialTimeout = 0;
                client.LongRunningOperationRetryTimeout   = 0;
            }
            return(client);
        }
Пример #9
0
 public AEMHelper(Action <ErrorRecord> errorAction, Action <string> verboseAction, Action <string> warningAction,
                  PSHostUserInterface ui, StorageManagementClient storageClient, IAzureSubscription subscription, String storageEndpoint)
 {
     this._ErrorAction     = errorAction;
     this._VerboseAction   = verboseAction;
     this._WarningAction   = warningAction;
     this._UI              = ui;
     this._StorageClient   = storageClient;
     this._Subscription    = subscription;
     this._StorageEndpoint = storageEndpoint;
 }
Пример #10
0
        private static StorageManagementClient EstablishClient(DeveloperParameters devOptions)
        {
            // set up the credentials for azure
            var creds =
                CertificateAuthenticationHelper.GetCredentials(devOptions.AzureManagementSubscriptionId,
                                                               devOptions.AzureAuthenticationKey);
            // set up the storage management client
            var client = new StorageManagementClient(creds);

            return(client);
        }
Пример #11
0
 /// <summary>
 /// Ctor
 /// </summary>
 /// <param name="commonData"></param>
 /// <param name="context"></param>
 public HDInsightManagementHelper(CommonTestFixture commonData, HDInsightMockContext context)
 {
     resourceManagementClient      = context.GetServiceClient <ResourceManagementClient>();
     storageManagementClient       = context.GetServiceClient <StorageManagementClient>();
     identityManagementClient      = context.GetServiceClient <ManagedServiceIdentityClient>();
     authorizationManagementClient = context.GetServiceClient <AuthorizationManagementClient>();
     keyVaultManagementClient      = context.GetServiceClient <KeyVaultManagementClient>();
     keyVaultClient          = GetKeyVaultClient();
     networkManagementClient = context.GetServiceClient <NetworkManagementClient>();
     this.commonData         = commonData;
 }
Пример #12
0
        private void SetupManagementClients(MockContext context)
        {
            ResourceManagementClient = GetResourceManagementClient(context);
            SearchClient             = GetAzureSearchManagementClient(context);
            StorageManagementClient  = GetStorageManagementClient(context);

            _helper.SetupManagementClients(
                ResourceManagementClient,
                SearchClient,
                StorageManagementClient);
        }
Пример #13
0
        public static async Task <List <StorageAccountExt> > GetStorageAccountsForSubscription(string subscriptionId, string token, string subscriptionName, string tenantId)
        {
            List <StorageAccountExt> storageAccounts = new List <StorageAccountExt>();

            try
            {
                TokenCloudCredentials cred     = new TokenCloudCredentials(subscriptionId, token);
                var httpClient                 = new HttpClient(new NativeMessageHandler());
                StorageManagementClient client = new StorageManagementClient(cred, httpClient);
                var response = await client.StorageAccounts.ListAsync();

                var realm = Realm.GetInstance();
                //Save our subscriptions to the realm
                var existingSubscription = realm.Find <Subscription>(subscriptionId);
                if (existingSubscription == null)
                {
                    await realm.WriteAsync(temprealm =>
                    {
                        temprealm.Add(new Subscription(subscriptionName, subscriptionId, tenantId, true), true);
                    });
                }

                foreach (var accnt in response.StorageAccounts)
                {
                    Debug.WriteLine("Storage account: " + accnt.Name);
                    var keys = await GetStorageAccountKeys(subscriptionId, token, accnt.Name);

                    Debug.WriteLine("PRimary key: " + keys.PrimaryKey);
                    StorageAccountExt extendedAccount = new StorageAccountExt(accnt, keys.PrimaryKey, keys.SecondaryKey, subscriptionName);
                    storageAccounts.Add(extendedAccount);
                    var existingStorageAccount = realm.Find <StorageAccountExt>(extendedAccount.Name);
                    if (existingStorageAccount != null && (existingStorageAccount.PrimaryKey != keys.PrimaryKey || existingStorageAccount.SecondaryKey != keys.SecondaryKey))
                    {
                        existingStorageAccount.PrimaryKey   = keys.PrimaryKey;
                        existingStorageAccount.SecondaryKey = keys.SecondaryKey;
                    }
                    else if (existingStorageAccount == null)
                    {
                        await realm.WriteAsync(temprealm =>
                        {
                            temprealm.Add(extendedAccount, true);
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error getting storage accounts for sub: " + subscriptionName);
                Debug.WriteLine("Error getting subscription Storage Account info: " + ex.Message);
                Debug.WriteLine(ex.StackTrace);
            }
            return(storageAccounts);
        }
Пример #14
0
        private static void AssociateReservedIP(ManagementClient managementClient, string usWestLocStr, string location,
                                                StorageManagementClient storageClient, string storageAccountName, ref bool storageAccountCreated,
                                                ComputeManagementClient computeClient, string serviceName, string deploymentName, string reserveIpName,
                                                NetworkTestBase _testFixture, ref bool hostedServiceCreated, ref bool reserveIpCreated)
        {
            if (managementClient.Locations.List().Any(
                    c => string.Equals(c.Name, usWestLocStr, StringComparison.OrdinalIgnoreCase)))
            {
                location = usWestLocStr;
            }

            CreateStorageAccount(location, storageClient, storageAccountName, out storageAccountCreated);

            CreateHostedService(location, computeClient, serviceName, out hostedServiceCreated);

            CreatePaaSDeployment(storageAccountName, computeClient, serviceName, deploymentName);

            NetworkReservedIPCreateParameters reservedIpCreatePars = new NetworkReservedIPCreateParameters
            {
                Name     = reserveIpName,
                Location = "uswest",
                Label    = "SampleReserveIPLabel"
            };

            OperationStatusResponse reserveIpCreate = _testFixture.NetworkClient.ReservedIPs.Create(reservedIpCreatePars);

            Assert.True(reserveIpCreate.StatusCode == HttpStatusCode.OK);
            reserveIpCreated = true;

            NetworkReservedIPGetResponse reserveIpCreationResponse =
                _testFixture.NetworkClient.ReservedIPs.Get(reserveIpName);

            Assert.True(reserveIpCreationResponse.StatusCode == HttpStatusCode.OK);


            NetworkReservedIPMobilityParameters pars = new NetworkReservedIPMobilityParameters
            {
                ServiceName    = serviceName,
                DeploymentName = deploymentName
            };
            OperationStatusResponse responseAssociateRip = _testFixture.NetworkClient.ReservedIPs.Associate(reserveIpName, pars);

            Assert.True(responseAssociateRip.StatusCode == HttpStatusCode.OK);

            NetworkReservedIPGetResponse receivedReservedIpFromRdfe =
                _testFixture.NetworkClient.ReservedIPs.Get(reserveIpName);

            Assert.True(receivedReservedIpFromRdfe.StatusCode == HttpStatusCode.OK);

            Assert.True(serviceName == receivedReservedIpFromRdfe.ServiceName);
            Assert.True(receivedReservedIpFromRdfe.InUse == true);
            Assert.True(deploymentName == receivedReservedIpFromRdfe.DeploymentName);
        }
        public static async Task <string> BeginDeployArmTemplateForImport([ActivityTrigger] ImportRequest request, ILogger log)
        {
            var azureServiceTokenProvider       = new AzureServiceTokenProvider();
            TokenCredentials tokenArmCredential = new TokenCredentials(await azureServiceTokenProvider.GetAccessTokenAsync("https://management.core.windows.net/"));

            ResourceManagementClient resourcesClient = new ResourceManagementClient(tokenArmCredential)
            {
                SubscriptionId = request.SubscriptionId.ToString()
            };
            StorageManagementClient storageMgmtClient = new StorageManagementClient(tokenArmCredential)
            {
                SubscriptionId = request.SubscriptionId.ToString()
            };

            // Get the storage account keys for a given account and resource group
            IList <StorageAccountKey> acctKeys = storageMgmtClient.StorageAccounts.ListKeys(request.ResourceGroupName, request.StorageAccountName).Keys;

            // Get a Storage account using account creds:
            StorageCredentials  storageCred          = new StorageCredentials(request.StorageAccountName, acctKeys.FirstOrDefault().Value);
            CloudStorageAccount linkedStorageAccount = new CloudStorageAccount(storageCred, true);
            CloudBlobContainer  container            = linkedStorageAccount
                                                       .CreateCloudBlobClient()
                                                       .GetContainerReference(request.ContainerName);

            CloudBlockBlob blob = container.GetBlockBlobReference(ArmTemplateFileName);
            string         json = await blob.DownloadTextAsync();

            JObject originalTemplate = JObject.Parse(json);
            JObject importTemplate   = UpdateArmTemplateForImport(originalTemplate, request);

            var deployParams = new Deployment
            {
                Properties = new DeploymentProperties
                {
                    Mode     = DeploymentMode.Incremental,
                    Template = importTemplate
                }
            };

            string deploymentName = request.TargetSqlServerName + "_" + DateTime.UtcNow.ToFileTimeUtc();

            try
            {
                await resourcesClient.Deployments.BeginCreateOrUpdateAsync(request.TargetSqlServerResourceGroupName, deploymentName, deployParams);
            }
            catch (Exception ex)
            {
                log.LogError(ex.ToString());
                throw ex;
            }

            return(deploymentName);
        }
Пример #16
0
 public static Uri UploadPackageToBlob(
     StorageManagementClient storageClient,
     string storageName,
     string packagePath,
     BlobRequestOptions blobRequestOptions)
 {
     return cloudBlobUtility.UploadPackageToBlob(
         storageClient,
         storageName,
         packagePath,
         blobRequestOptions);
 }
Пример #17
0
 private void SetupManagementClients(MockContext context)
 {
     RedisManagementClient       = GetRedisManagementClient(context);
     InsightsManagementClient    = GetInsightsManagementClient(context);
     NewResourceManagementClient = GetResourceManagementClient(context);
     StorageClient = GetStorageManagementClient(context);
     _helper.SetupManagementClients(
         RedisManagementClient,
         StorageClient,
         NewResourceManagementClient,
         InsightsManagementClient);
 }
Пример #18
0
        public StorageMgmtClient(
            string subscriptionId,
            RestClient restClient
            )
        {
            _storageManagementClient = new StorageManagementClient(restClient)
            {
                SubscriptionId = subscriptionId
            };

            _azureEnvironment = restClient.Environment;
        }
Пример #19
0
 public static Uri UploadPackageToBlob(
     StorageManagementClient storageClient,
     string storageName,
     string packagePath,
     BlobRequestOptions blobRequestOptions)
 {
     return(cloudBlobUtility.UploadPackageToBlob(
                storageClient,
                storageName,
                packagePath,
                blobRequestOptions));
 }
Пример #20
0
        /// <summary>
        /// Updates the storage account
        /// </summary>
        /// <param name="rgname">Resource Group Name</param>
        /// <param name="acctName">Account Name</param>
        /// <param name="storageMgmtClient"></param>
        private static void UpdateStorageAccount(string rgname, string acctName, StorageManagementClient storageMgmtClient)
        {
            Console.WriteLine("Updating storage account...");
            // Update storage account type
            var parameters = new StorageAccountUpdateParameters
            {
                AccountType = AccountType.StandardLRS
            };
            var response = storageMgmtClient.StorageAccounts.Update(rgname, acctName, parameters);

            Console.WriteLine("Account type on storage account updated to " + response.StorageAccount.AccountType);
        }
Пример #21
0
        private HostedServiceGetDetailedResponse ProvisionHostedService(string newServiceName)
        {
            ComputeManagementClient computeClient = TestBase.GetServiceClient <ComputeManagementClient>();
            StorageManagementClient storageClient = TestBase.GetServiceClient <StorageManagementClient>();

            string computeLocation = GetLocation("Compute");

            var createHostedServiceResp = computeClient.HostedServices.Create(new HostedServiceCreateParameters()
            {
                ServiceName = newServiceName,
                Location    = computeLocation
            });

            Assert.Equal(HttpStatusCode.Created, createHostedServiceResp.StatusCode);

            string newStorageAccountName = TestUtilities.GenerateName("storage");
            string storageLocation       = GetLocation("Storage");

            var createStorageResp = storageClient.StorageAccounts.Create(new StorageAccountCreateParameters
            {
                Location    = storageLocation,
                Name        = newStorageAccountName,
                AccountType = "Standard_GRS"
            });

            Assert.Equal(HttpStatusCode.OK, createStorageResp.StatusCode);

            var blobUri = StorageTestUtilities.UploadFileToBlobStorage(newStorageAccountName, "deployments",
                                                                       @"SampleService\SMNetTestAppProject.cspkg");
            var configXml = File.ReadAllText(@"SampleService\ServiceConfiguration.Cloud.cscfg");

            string deploymentName = TestUtilities.GenerateName("deployment");

            // create the hosted service deployment
            var deploymentResult = computeClient.Deployments.Create(newServiceName,
                                                                    DeploymentSlot.Production,
                                                                    new DeploymentCreateParameters
            {
                Configuration          = configXml,
                Name                   = deploymentName,
                Label                  = "label1",
                StartDeployment        = true,
                ExtensionConfiguration = null,
                PackageUri             = blobUri
            });

            Assert.Equal(HttpStatusCode.OK, deploymentResult.StatusCode);

            var detailedStatus = computeClient.HostedServices.GetDetailedAsync(newServiceName).Result;

            return(detailedStatus);
        }
Пример #22
0
        public void TestDisassociateReserveIP()
        {
            using (var undoContext = AZT.UndoContext.Current)
            {
                undoContext.Start();
                using (NetworkTestBase _testFixture = new NetworkTestBase())
                {
                    ComputeManagementClient computeClient = _testFixture.GetComputeManagementClient();
                    StorageManagementClient storageClient = _testFixture.GetStorageManagementClient();
                    var  managementClient      = _testFixture.ManagementClient;
                    bool storageAccountCreated = false;
                    bool hostedServiceCreated  = false;
                    bool reserveIpCreated      = false;

                    string       storageAccountName = HttpMockServer.GetAssetName("teststorage1234", "teststorage").ToLower();
                    string       serviceName        = AZT.TestUtilities.GenerateName("testsvc");
                    string       deploymentName     = string.Format("{0}Prod", serviceName);
                    string       reserveIpName      = HttpMockServer.GetAssetName("rip", "testrip").ToLower();
                    string       location           = managementClient.GetDefaultLocation("Storage", "Compute");
                    const string usWestLocStr       = "West US";
                    try
                    {
                        AssociateReservedIP(managementClient, usWestLocStr, location, storageClient, storageAccountName,
                                            ref storageAccountCreated, computeClient, serviceName, deploymentName, reserveIpName,
                                            _testFixture, ref hostedServiceCreated, ref reserveIpCreated);
                        Assert.True(storageAccountCreated);
                        Assert.True(hostedServiceCreated);
                        Assert.True(reserveIpCreated);
                        DisassociateReservedIP(_testFixture, reserveIpName, serviceName, deploymentName);
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                    finally
                    {
                        if (storageAccountCreated)
                        {
                            storageClient.StorageAccounts.Delete(storageAccountName);
                        }
                        if (hostedServiceCreated)
                        {
                            computeClient.HostedServices.DeleteAll(serviceName);
                        }
                        if (reserveIpCreated)
                        {
                            _testFixture.NetworkClient.ReservedIPs.Delete(reserveIpName);
                        }
                    }
                }
            }
        }
Пример #23
0
        internal MediaStorage(string authToken, MediaStorageAccount storageAccount) : base(storageAccount.Type, storageAccount.Id)
        {
            TokenCredentials        azureToken    = AuthToken.AcquireToken(authToken, out string subscriptionId);
            StorageManagementClient storageClient = new StorageManagementClient(azureToken)
            {
                SubscriptionId = subscriptionId
            };
            string accountName = Path.GetFileName(storageAccount.Id);
            IEnumerable <StorageAccount> storageAccounts = storageClient.StorageAccounts.List();

            storageAccounts = storageAccounts.Where(s => s.Name.Equals(accountName, StringComparison.OrdinalIgnoreCase));
            _storageAccount = storageAccounts.SingleOrDefault();
        }
Пример #24
0
        private static async Task ProcessResourceGroup(TokenCloudCredentials subscriptionCredential, ResourceGroupExtended resourceGroupExtended, ILogger log, CancellationToken ct)
        {
            log.LogInformation($"Resource Group {resourceGroupExtended.Id}");

            var storageManagementClient    = new StorageManagementClient(credentials: subscriptionCredential);
            var storageAccountListResponse = await storageManagementClient.StorageAccounts.ListByResourceGroupAsync(resourceGroupName : resourceGroupExtended.Name, cancellationToken : ct);

            foreach (var account in storageAccountListResponse.StorageAccounts)
            {
                var keys = await storageManagementClient.StorageAccounts.ListKeysAsync(resourceGroupName : resourceGroupExtended.Name, accountName : account.Name);
                await ProcessStorageAccountAsync(account, keys, log, ct);
            }
        }
Пример #25
0
 public static StorageManagementClient GetStorageManagementClient(MockContext context, RecordedDelegatingHandler handler)
 {
     if (IsTestTenant)
     {
         return(null);
     }
     else
     {
         handler.IsPassThrough = true;
         StorageManagementClient storageClient = context.GetServiceClient <StorageManagementClient>(handlers: handler);
         return(storageClient);
     }
 }
Пример #26
0
        /// <summary>
        /// Main program.
        /// </summary>
        static async Task <int> Main()
        {
            string subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");

            var credential = new DefaultAzureCredential();

            // Azure.ResourceManager.Resources is currently in preview.
            var resourcesManagementClient = new ResourcesManagementClient(subscriptionId, credential);

            // Azure.ResourceManager.Storage is currently in preview.
            var storageManagementClient = new StorageManagementClient(subscriptionId, credential);

            int       repeat = 0;
            const int total  = 3;

            while (++repeat <= total)
            {
                Console.WriteLine("Repeat #{0}...", repeat);
                try
                {
                    // Create a Resource Group
                    string resourceGroupName = await CreateResourceGroupAsync(resourcesManagementClient);

                    // Create a Storage account
                    string storageName = await CreateStorageAccountAsync(storageManagementClient, resourceGroupName);

                    // Create a container and upload a blob using a storage connection string
                    await UploadBlobUsingStorageConnectionStringAsync(storageManagementClient, resourceGroupName, storageName);

                    // Upload a blob using Azure.Identity.DefaultAzureCredential
                    await UploadBlobUsingDefaultAzureCredentialAsync(storageManagementClient, resourceGroupName, storageName, credential);

                    Console.WriteLine("Delete the resources...");

                    // Delete the resource group
                    await DeleteResourceGroupAsync(resourcesManagementClient, resourceGroupName);
                }
                catch (RequestFailedException ex)
                {
                    Console.WriteLine($"Request failed! {ex.Message} {ex.StackTrace}");
                    return(-1);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Unexpected exception! {ex.Message} {ex.StackTrace}");
                    return(-1);
                }
            }
            Console.WriteLine("Success!");
            return(0);
        }
        /// <summary>
        /// Checks for the existence of a specific storage container, if it doesn't exist it will create it.
        /// It also checks for a specific storage account that suits the system, if it doesn't exist in the subscription
        /// it will create it before attempting to create the container.
        /// </summary>
        /// <param name="client">The <see cref="StorageManagementClient"/> that is performing the operation.</param>
        /// <param name="model">The DevOpsFlex rich model object that contains everything there is to know about this database spec.</param>
        /// <returns>The async <see cref="Task"/> wrapper.</returns>
        public static async Task CreateContainerIfNotExistsAsync(this StorageManagementClient client, AzureStorageContainer model)
        {
            Contract.Requires(client != null);
            Contract.Requires(model != null);
            Contract.Requires(model.System != null);

            string accountName;

            lock (StorageAccountGate)
            {
                FlexStreams.BuildEventsObserver.OnNext(new CheckForParentResourceEvent(AzureResource.StorageAccount, AzureResource.StorageContainer, model.Name));
                accountName = FlexConfiguration.StorageAccountChooser.Choose(client, model.System.StorageType.GetEnumDescription()).Result;
                StorageAccountGetResponse account = null;

                try
                {
                    account = client.StorageAccounts.Get(accountName);
                }
                catch
                {
                    // ignored
                }

                if (account == null)
                {
                    accountName = (model.System.LogicalName + FlexDataConfiguration.StorageAccountString + FlexDataConfiguration.Branch).ToLower();

                    client.StorageAccounts.Create(
                        new StorageAccountCreateParameters
                    {
                        Name        = accountName,
                        Location    = model.System.Location.GetEnumDescription(),
                        AccountType = model.System.StorageType.GetEnumDescription()
                    });

                    FlexStreams.BuildEventsObserver.OnNext(new ProvisionEvent(AzureResource.StorageAccount, accountName));
                }
                else
                {
                    accountName = account.StorageAccount.Name;
                    FlexStreams.BuildEventsObserver.OnNext(new FoundExistingEvent(AzureResource.StorageAccount, accountName));
                }
            }

            await client.CreateContainerIfNotExistsAsync(
                accountName,
                FlexConfiguration.GetNaming <AzureStorageContainer>()
                .GetSlotName(model, FlexDataConfiguration.Branch, FlexDataConfiguration.Configuration),
                model.PublicAccess,
                model.Acl);
        }
Пример #28
0
        public static async Task <String> GetStorageAccountConnectionString(string resourceGroupName, string accountName)
        {
            string token = await GetOAuthTokenFromAADAsync();

            var tenantTokenCreds = new TokenCredentials(token);
            StorageManagementClient storageMgmtClient = new StorageManagementClient(tenantTokenCreds)
            {
                SubscriptionId = SubscriptionId
            };
            IList <StorageAccountKey> accountKeys = storageMgmtClient.StorageAccounts.ListKeys(resourceGroupName, accountName).Keys;
            string connectionString = String.Format("DefaultEndpointsProtocol={0};AccountName={1};AccountKey={2}", "https", accountName, accountKeys[0].Value);

            return(connectionString);
        }
        protected override bool CheckExistence()
        {
            if (Parameters.Properties.ResourceGroupExists)
            {
                using (var storageClient = new StorageManagementClient(GetCredentials()))
                {
                    var availabilityResult = storageClient.StorageAccounts.CheckNameAvailabilityAsync(Parameters.Tenant.SiteName).Result;

                    return !availabilityResult.NameAvailable;
                }
            }

            return false;
        }
Пример #30
0
        string GetStorageAccountPrimaryKey(SubscriptionCloudCredentials credentials, string storageAccountName, string serviceManagementEndpoint)
        {
            using (var cloudClient = new StorageManagementClient(credentials, new Uri(serviceManagementEndpoint)))
            {
                var getKeysResponse = cloudClient.StorageAccounts.GetKeys(storageAccountName);

                if (getKeysResponse.StatusCode != HttpStatusCode.OK)
                {
                    throw new Exception(string.Format("GetKeys for storage-account {0} returned HTTP status-code {1}", storageAccountName, getKeysResponse.StatusCode));
                }

                return(getKeysResponse.PrimaryKey);
            }
        }
Пример #31
0
        static void Main(string[] args)
        {
            string token = GetAuthorizationHeader();
            TokenCloudCredentials    credential        = new TokenCloudCredentials(subscriptionId, token);
            ResourceManagementClient resourcesClient   = new ResourceManagementClient(credential);
            StorageManagementClient  storageMgmtClient = new StorageManagementClient(credential);

            try
            {
                //Create a new resource group
                CreateResourceGroup(rgName, resourcesClient);

                //Create a new account in a specific resource group with the specified account name
                CreateStorageAccount(rgName, accountName, storageMgmtClient);

                //Get all the account properties for a given resource group and account name
                StorageAccount storAcct = storageMgmtClient.StorageAccounts.GetProperties(rgName, accountName).StorageAccount;

                //Get a list of storage accounts within a specific resource group
                IList <StorageAccount> storAccts = storageMgmtClient.StorageAccounts.ListByResourceGroup(rgName).StorageAccounts;

                //Get all the storage accounts for a given subscription
                IList <StorageAccount> storAcctsSub = storageMgmtClient.StorageAccounts.List().StorageAccounts;

                //Get the storage account keys for a given account and resource group
                StorageAccountKeys acctKeys = storageMgmtClient.StorageAccounts.ListKeys(rgName, accountName).StorageAccountKeys;

                //Regenerate the account key for a given account in a specific resource group
                StorageAccountKeys regenAcctKeys = storageMgmtClient.StorageAccounts.RegenerateKey(rgName, accountName, KeyName.Key1).StorageAccountKeys;

                //Update the storage account for a given account name and resource group
                UpdateStorageAccount(rgName, accountName, storageMgmtClient);

                //Check if the account name is available
                bool nameAvailable = storageMgmtClient.StorageAccounts.CheckNameAvailability(accountName).NameAvailable;

                //Delete a storage account with the given account name and a resource group
                DeleteStorageAccount(rgName, accountName, storageMgmtClient);
            }
            catch (Hyak.Common.CloudException ce)
            {
                Console.WriteLine(ce.Message);
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }
        }
Пример #32
0
        public static async Task DeleteStorageAsync(string accountName)
        {
            var subscription  = TestUtility.EventHubsSubscription;
            var resourceGroup = TestUtility.EventHubsResourceGroup;
            var token         = await AquireManagementTokenAsync();

            using (var client = new StorageManagementClient(TestUtility.ResourceManager, new TokenCredentials(token))
            {
                SubscriptionId = subscription
            })
            {
                await CreateRetryPolicy().ExecuteAsync(() => client.StorageAccounts.DeleteAsync(resourceGroup, accountName));
            }
        }
Пример #33
0
        protected async Task RunTest(
            Func <DataShareManagementClient, Task> initialAction,
            Func <DataShareManagementClient, Task> finallyAction,
            [CallerMemberName] string methodName = "")
        {
            const string modeEnvironmentVariableName = "AZURE_TEST_MODE";
            const string playback = "Playback";

            using (MockContext mockContext = MockContext.Start(Type, methodName))
            {
                string mode = Environment.GetEnvironmentVariable(modeEnvironmentVariableName);

                if (mode != null && mode.Equals(playback, StringComparison.OrdinalIgnoreCase))
                {
                    HttpMockServer.Mode = HttpRecorderMode.Playback;
                }

                //this.ResourceGroupName = TestUtilities.GenerateName(ScenarioTestBase<T>.ResourceGroupNamePrefix);
                this.ResourceGroupName = ScenarioTestBase <T> .ResourceGroupNamePrefix;

                // this.AccountName = TestUtilities.GenerateName(ScenarioTestBase<T>.AccountNamePrefix);
                this.AccountName = ScenarioTestBase <T> .AccountNamePrefix;

                this.Client =
                    mockContext.GetServiceClient <DataShareManagementClient>(
                        TestEnvironmentFactory.GetTestEnvironment());

                ResourceManagementClient resourceManagementClient =
                    mockContext.GetServiceClient <ResourceManagementClient>(TestEnvironmentFactory.GetTestEnvironment());

                resourceManagementClient.ResourceGroups.CreateOrUpdate(
                    this.ResourceGroupName,
                    new ResourceGroup()
                {
                    Location = ScenarioTestBase <T> .AccountLocation
                });

                StorageManagementClient storageManagementClient = mockContext.GetServiceClient <StorageManagementClient>(TestEnvironmentFactory.GetTestEnvironment());
                CreateStorageAccount(this.ResourceGroupName, storageActName, storageManagementClient);

                await initialAction(this.Client);

                if (finallyAction != null)
                {
                    await finallyAction(this.Client);
                }

                resourceManagementClient.ResourceGroups.Delete(this.ResourceGroupName);
            }
        }
Пример #34
0
        internal MediaStorage(MediaAccount mediaAccount, MediaStorageAccount storageAccount) : base(storageAccount.Type, storageAccount.Id)
        {
            ServiceClientCredentials clientCredentials = ApplicationTokenProvider.LoginSilentAsync(mediaAccount.DirectoryTenantId, mediaAccount.ServicePrincipalId, mediaAccount.ServicePrincipalKey).Result;
            StorageManagementClient  storageClient     = new StorageManagementClient(clientCredentials)
            {
                SubscriptionId = mediaAccount.SubscriptionId
            };

            _storageAccountName = Path.GetFileName(storageAccount.Id);
            IEnumerable <StorageAccount> storageAccounts = storageClient.StorageAccounts.List();

            storageAccounts = storageAccounts.Where(s => s.Name.Equals(_storageAccountName, StringComparison.OrdinalIgnoreCase));
            _storageAccount = storageAccounts.SingleOrDefault();
        }
Пример #35
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);
 }
        protected override bool CheckExistence()
        {
            if (Parameters.Properties.ResourceGroupExists)
            {
                using (var storageClient = new StorageManagementClient(GetCredentials()))
                {
                    var availabilityResult = storageClient.StorageAccounts.CheckNameAvailabilityAsync(Parameters.Tenant.SiteName).Result;

                    return(!availabilityResult.NameAvailable);
                }
            }

            return(false);
        }
        private async Task <StorageContainerInfo> CreateStorageContainer(SqlManagementTestContext context, ResourceGroup resourceGroup)
        {
            StorageManagementClient storageClient  = context.GetClient <StorageManagementClient>();
            StorageAccount          storageAccount = await storageClient.StorageAccounts.CreateAsync(
                resourceGroup.Name,
                accountName : SqlManagementTestUtilities.GenerateName(prefix: "sqlvatest"),
                parameters : new StorageAccountCreateParameters(
                    new Microsoft.Azure.Management.Storage.Models.Sku(SkuName.StandardLRS, SkuTier.Standard),
                    Kind.BlobStorage,
                    resourceGroup.Location,
                    accessTier: AccessTier.Cool));

            StorageAccountListKeysResult keys =
                storageClient.StorageAccounts.ListKeys(resourceGroup.Name, storageAccount.Name);
            string key = keys.Keys.First().Value;

            string containerName = "vulnerability-assessment";
            var    sasToken      = string.Empty;

            // Create container
            // Since this is a data-plane client and not an ARM client it's harder to inject
            // HttpMockServer into it to record/playback, but that's fine because we don't need
            // any of the response data to continue with the test.
            if (HttpMockServer.Mode == HttpRecorderMode.Record)
            {
                CloudStorageAccount storageAccountClient = new CloudStorageAccount(
                    new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(
                        storageAccount.Name,
                        key),
                    useHttps: true);
                CloudBlobClient    blobClient         = storageAccountClient.CreateCloudBlobClient();
                CloudBlobContainer containerReference = blobClient.GetContainerReference(containerName);
                await containerReference.CreateIfNotExistsAsync();

                SharedAccessBlobPolicy sharedAccessPolicy = new SharedAccessBlobPolicy
                {
                    SharedAccessExpiryTime = new DateTimeOffset(DateTime.UtcNow.Add(TimeSpan.FromHours(1))),
                    Permissions            = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.List
                };

                // Generate the SAS Token
                sasToken = containerReference.GetSharedAccessSignature(sharedAccessPolicy);
            }

            return(new StorageContainerInfo
            {
                StorageAccountSasKey = sasToken,
                StorageContainerPath = new Uri(storageAccount.PrimaryEndpoints.Blob + containerName)
            });
        }
Пример #38
0
 public virtual void DeletePackageFromBlob(
     StorageManagementClient storageClient,
     string storageName,
     Uri packageUri)
 {
     StorageAccountGetKeysResponse keys = storageClient.StorageAccounts.GetKeys(storageName);
     string storageKey = keys.PrimaryKey;
     var storageService = storageClient.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();
 }
        private void SetPrimaryStorageKey()
        {
            using (var storageClient = new StorageManagementClient(GetCredentials()))
            {
                // Get Primary Storage Key
                var keyResult = storageClient.StorageAccounts.ListKeysAsync(Parameters.Tenant.SiteName, Parameters.Tenant.SiteName).Result;

                Parameters.Tenant.StoragePrimaryKey = keyResult.StorageAccountKeys.Key1;
            }
        }
        public static string CreateStorageAccount(StorageManagementClient storageMgmtClient, string rgname)
        {
            string accountName = TestUtilities.GenerateName("sto");
            StorageAccountCreateParameters parameters = GetDefaultStorageAccountParameters();

            var createRequest = storageMgmtClient.StorageAccounts.Create(rgname, accountName, parameters);

            return accountName;
        }
        private void SetSecondaryLocation()
        {
            using (var storageClient = new StorageManagementClient(GetCredentials()))
            {
                // Get Secondary Location
                var propertyResult = storageClient.StorageAccounts.GetProperties(Parameters.Tenant.SiteName, Parameters.Tenant.SiteName);

                Parameters.Properties.LocationSecondary = propertyResult.StorageAccount.SecondaryLocation;
            }
        }
Пример #42
0
        internal CloudServiceClient(
            WindowsAzureSubscription subscription,
            ManagementClient managementClient,
            StorageManagementClient storageManagementClient,
            ComputeManagementClient computeManagementClient)
            : this((string)null, null, null, null)
        {
            Subscription = subscription;
            CurrentDirectory = null;
            DebugStream = null;
            VerboseStream = null;
            WarningStream = null;

            CloudBlobUtility = new CloudBlobUtility();
            ManagementClient = managementClient;
            StorageClient = storageManagementClient;
            ComputeClient = computeManagementClient;
        }
 /// <summary>
 /// Updates the storage account
 /// </summary>
 /// <param name="rgname">Resource Group Name</param>
 /// <param name="acctName">Account Name</param>
 /// <param name="storageMgmtClient"></param>
 private static void UpdateStorageAccount(string rgname, string acctName, StorageManagementClient storageMgmtClient)
 {
     Console.WriteLine("Updating storage account...");
     // Update storage account type
     var parameters = new StorageAccountUpdateParameters
     {
         AccountType = AccountType.StandardLRS
     };
     var response = storageMgmtClient.StorageAccounts.Update(rgname, acctName, parameters);
     Console.WriteLine("Account type on storage account updated to " + response.StorageAccount.AccountType);
 }
        private void CreateStorageAccount()
        {
            using (var storageClient = new StorageManagementClient(GetCredentials()))
            {
                // Create the Storage Account
                var checkResult = storageClient.StorageAccounts.CheckNameAvailabilityAsync(Parameters.Tenant.SiteName).Result;

                if (checkResult.NameAvailable)
                {
                    var createResult = storageClient.StorageAccounts.CreateAsync(
                        Parameters.Tenant.SiteName,
                        Parameters.Tenant.SiteName,
                        new StorageAccountCreateParameters
                        {
                            AccountType = AccountType.StandardGRS,
                            Location = Parameters.Location(Position)
                        }).Result;
                }
            }
        }
        protected string GetSasUrlStr(string storageName, string storageKey, string containerName, string blobName)
        {
            var storageClient = new StorageManagementClient();
            var cred = new StorageCredentials(storageName, storageKey);
            var storageAccount = string.IsNullOrEmpty(this.StorageEndpointSuffix)
                               ? new CloudStorageAccount(cred, true)
                               : new CloudStorageAccount(cred, this.StorageEndpointSuffix, true);

            var blobClient = storageAccount.CreateCloudBlobClient();
            var container = blobClient.GetContainerReference(containerName);
            var cloudBlob = container.GetBlockBlobReference(blobName);
            var sasToken = cloudBlob.GetSharedAccessSignature(
                new SharedAccessBlobPolicy()
                {
                    SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24.0),
                    Permissions = SharedAccessBlobPermissions.Read
                });

            // Try not to use a Uri object in order to keep the following
            // special characters in the SAS signature section:
            //     '+'   ->   '%2B'
            //     '/'   ->   '%2F'
            //     '='   ->   '%3D'
            return cloudBlob.Uri + sasToken;
        }
        protected string GetStorageKey(string storageName)
        {
            string storageKey = string.Empty;

            if (!string.IsNullOrEmpty(storageName))
            {
                var storageClient = new StorageManagementClient();

                var storageAccount = storageClient.StorageAccounts.GetProperties(this.ResourceGroupName, storageName);

                if (storageAccount != null)
                {
                    var keys = storageClient.StorageAccounts.ListKeys(this.ResourceGroupName, storageName);
                    if (keys != null && keys.StorageAccountKeys != null)
                    {
                        storageKey = !string.IsNullOrEmpty(keys.StorageAccountKeys.Key1) ? keys.StorageAccountKeys.Key1 : keys.StorageAccountKeys.Key2;
                    }
                }
            }

            return storageKey;
        }
        private static void HandleDeploy(Options options, AuthenticationContext authContext, AuthenticationResult token, ResourceManagementClient resourceManagementClient)
        {
            if (!string.IsNullOrWhiteSpace(options.Deploy))
            {
                ResourceGroupExtended rg = GetResourceGroup(options, resourceManagementClient);
                //Fix location to displayname from template
                using (var subscriptionClient = new SubscriptionClient(new TokenCloudCredentials(token.AccessToken)))
                {
                    var a = subscriptionClient.Subscriptions.ListLocations(options.SubscriptionId);
                    rg.Location = a.Locations.Single(l => l.Name == rg.Location).DisplayName;
                }

                var graphtoken = authContext.AcquireToken("https://graph.windows.net/", options.ClientID, new Uri(options.RedirectUri), PromptBehavior.Auto);
                var graph = new ActiveDirectoryClient(new Uri("https://graph.windows.net/" + graphtoken.TenantId), () => Task.FromResult(graphtoken.AccessToken));
                var principal = graph.ServicePrincipals.Where(p => p.AppId == options.ApplicaitonId).ExecuteSingleAsync().GetAwaiter().GetResult();


                DeploymentExtended deploymentInfo = null;
                if (!resourceManagementClient.Deployments.CheckExistence(options.ResourceGroup, options.DeployName).Exists)
                {

                    var deployment = new Deployment
                    {
                        Properties = new DeploymentProperties
                        {
                            Mode = DeploymentMode.Incremental, //Dont Delete other resources
                            Template = File.ReadAllText(options.Deploy),
                            Parameters = new JObject(
                                new JProperty("siteName", CreateValue(options.SiteName)),
                                new JProperty("hostingPlanName", CreateValue(options.HostingPlanName)),
                                new JProperty("storageAccountType", CreateValue(options.StorageAccountType)),
                                new JProperty("siteLocation", CreateValue(rg.Location)),
                                new JProperty("sku", CreateValue(options.WebsitePlan)),
                                new JProperty("tenantId", CreateValue(token.TenantId)),
                                new JProperty("objectId", CreateValue(token.UserInfo.UniqueId)),
                                new JProperty("appOwnerTenantId", CreateValue(principal.AppOwnerTenantId.Value.ToString())),
                                new JProperty("appOwnerObjectId", CreateValue(principal.ObjectId))
                                ).ToString(),

                        }
                    };

                    var result = resourceManagementClient.Deployments.CreateOrUpdate(options.ResourceGroup, options.DeployName, deployment);
                    deploymentInfo = result.Deployment;
                }
                else
                {
                    var deploymentStatus = resourceManagementClient.Deployments.Get(options.ResourceGroup, options.DeployName);
                    deploymentInfo = deploymentStatus.Deployment;

                }

                while (!(deploymentInfo.Properties.ProvisioningState == "Succeeded" || deploymentInfo.Properties.ProvisioningState == "Failed"))
                {
                    var deploymentStatus = resourceManagementClient.Deployments.Get(options.ResourceGroup, options.DeployName);
                    deploymentInfo = deploymentStatus.Deployment;
                    Thread.Sleep(5000);
                }
                Console.WriteLine(deploymentInfo.Properties.Outputs);
                var outputs = JObject.Parse(deploymentInfo.Properties.Outputs);
                var storageAccountName = outputs["storageAccount"]["value"].ToString();
                var keyvaultName = outputs["keyvault"]["value"].ToString();

                using (var client = new KeyVaultManagementClient(new TokenCloudCredentials(options.SubscriptionId, token.AccessToken)))
                {
                    using (var storageClient = new StorageManagementClient(new TokenCloudCredentials(options.SubscriptionId, token.AccessToken)))
                    {
                        var keys = storageClient.StorageAccounts.ListKeys(options.ResourceGroup, storageAccountName);

                        var vaultInfo = client.Vaults.Get(options.ResourceGroup, keyvaultName);
                        //CHEATING (using powershell application id to get token on behhalf of user);
                        var vaultToken = authContext.AcquireToken("https://vault.azure.net", "1950a258-227b-4e31-a9cf-717495945fc2", new Uri("urn:ietf:wg:oauth:2.0:oob"));
                        var keyvaultClient = new KeyVaultClient((_, b, c) => Task.FromResult(vaultToken.AccessToken));

                        var secrets = keyvaultClient.GetSecretsAsync(vaultInfo.Vault.Properties.VaultUri).GetAwaiter().GetResult();
                        if (secrets.Value == null || !secrets.Value.Any(s => s.Id == vaultInfo.Vault.Properties.VaultUri + "secrets/storage"))
                        {
                            keyvaultClient.SetSecretAsync(vaultInfo.Vault.Properties.VaultUri, "storage", $"{storageAccountName}:{keys.StorageAccountKeys.Key1}").GetAwaiter().GetResult();
                            keyvaultClient.SetSecretAsync(vaultInfo.Vault.Properties.VaultUri, "storage", $"{storageAccountName}:{keys.StorageAccountKeys.Key2}").GetAwaiter().GetResult();


                            var secret = keyvaultClient.GetSecretVersionsAsync(vaultInfo.Vault.Properties.VaultUri, "storage").GetAwaiter().GetResult();
                        }
                    }



                }


            }
        }
        private StorageAccount TryToChooseExistingStandardStorageAccount(StorageManagementClient client)
        {
            var storageAccountList = client.StorageAccounts.ListByResourceGroup(this.ResourceGroupName);
            if (storageAccountList == null)
            {
                return null;
            }

            try
            {
                return storageAccountList.StorageAccounts.First(
                e => e.AccountType.HasValue
                    && !e.AccountType.Value.ToString().ToLowerInvariant().Contains("premium"));
            }
            catch (InvalidOperationException e)
            {
                WriteWarning(string.Format(
                            Properties.Resources.ErrorDuringChoosingStandardStorageAccount, e.Message));
                return null;
            }
        }
        private Uri CreateStandardStorageAccount(StorageManagementClient client)
        {
            string storageAccountName;

            var i = 0;
            do
            {
                storageAccountName = GetRandomStorageAccountName(i);
                i++;
            }
            while (i < 10 && !client.StorageAccounts.CheckNameAvailability(storageAccountName).NameAvailable);

            var storaeAccountParameter = new StorageAccountCreateParameters
            {
                AccountType = AccountType.StandardGRS,
                Location = this.Location ?? this.VM.Location,
            };

            try
            {
                client.StorageAccounts.Create(this.ResourceGroupName, storageAccountName, storaeAccountParameter);
                var getresponse = client.StorageAccounts.GetProperties(this.ResourceGroupName, storageAccountName);
                WriteWarning(string.Format(Properties.Resources.CreatingStorageAccountForBootDiagnostics, storageAccountName));

                return getresponse.StorageAccount.PrimaryEndpoints.Blob;
            }
            catch (Exception e)
            {
                // Failed to create a storage account for boot diagnostics.
                WriteWarning(string.Format(Properties.Resources.ErrorDuringCreatingStorageAccountForBootDiagnostics, e));
                return null;
            }
        }
 public StorageCredentialsFactory(StorageManagementClient client, WindowsAzureSubscription currentSubscription)
 {
     this.client = client;
     this.currentSubscription = currentSubscription;
 }
 /// <summary>
 /// Updates the storage account
 /// </summary>
 /// <param name="rgname">Resource Group Name</param>
 /// <param name="acctName">Account Name</param>
 /// <param name="storageMgmtClient"></param>
 private static void UpdateStorageAccountSku(string rgname, string acctName, SkuName skuName, StorageManagementClient storageMgmtClient)
 {
     Console.WriteLine("Updating storage account...");
     // Update storage account sku
     var parameters = new StorageAccountUpdateParameters
     {
         Sku = new Sku(skuName)
     };
     var storageAccount = storageMgmtClient.StorageAccounts.Update(rgname, acctName, parameters);
     Console.WriteLine("Sku on storage account updated to " + storageAccount.Sku.Name);
 }
 public StorageCredentialsFactory(string resourceGroupName, StorageManagementClient client, AzureSubscription currentSubscription)
 {
     this.resourceGroupName = resourceGroupName;
     this.client = client;
     this.currentSubscription = currentSubscription;
 }
 /// <summary>
 /// Deletes a storage account for the specified account name
 /// </summary>
 /// <param name="rgname"></param>
 /// <param name="acctName"></param>
 /// <param name="storageMgmtClient"></param>
 private static void DeleteStorageAccount(string rgname, string acctName, StorageManagementClient storageMgmtClient)
 {
     Console.WriteLine("Deleting a storage account...");
     var deleteRequest = storageMgmtClient.StorageAccounts.Delete(rgname, acctName);
     Console.WriteLine("Storage account " + acctName + " deleted");
 }
        private StorageAccount TryToChooseExistingStandardStorageAccount(StorageManagementClient client)
        {
            var storageAccountList = client.StorageAccounts.ListByResourceGroup(this.ResourceGroupName);
            if (storageAccountList == null)
            {
                return null;
            }

            try
            {
                return storageAccountList.StorageAccounts.First(
                e => e.AccountType.HasValue
                    && !e.AccountType.Value.ToString().ToLowerInvariant().Contains("premium"));
            }
            catch (InvalidOperationException e)
            {
                if (e.Message.Contains("Sequence contains no matching element"))
                {
                    return null;
                }
                throw;
            }
        }
Пример #55
0
        internal int? GetDiskSizeGbFromBlobUri(string sBlobUri)
        {
            var storageClient = new StorageManagementClient();
            var blobMatch = Regex.Match(sBlobUri, "https?://(\\S*?)\\..*?/(.*)");
            if (!blobMatch.Success)
            {
                WriteError("Blob URI of disk does not match known pattern {0}", sBlobUri);
                throw new ArgumentException("Blob URI of disk does not match known pattern");
            }
            var accountName = blobMatch.Groups[1].Value;

            BlobUri blobUri;
            if (BlobUri.TryParseUri(new Uri(sBlobUri), out blobUri))
            {
                try
                {
                    var account = this.GetStorageAccountFromCache(accountName);
                    var resGroupName = this.GetResourceGroupFromId(account.Id);
                    StorageCredentialsFactory storageCredentialsFactory = new StorageCredentialsFactory(resGroupName,
                        this._StorageClient, this._Subscription);
                    StorageCredentials sc = storageCredentialsFactory.Create(blobUri);
                    CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(sc, true);
                    CloudBlobClient blobClient = cloudStorageAccount.CreateCloudBlobClient();
                    CloudBlobContainer blobContainer = blobClient.GetContainerReference(blobUri.BlobContainerName);
                    var cloudBlob = blobContainer.GetPageBlobReference(blobUri.BlobName);
                    var sasToken = cloudBlob.GetSharedAccessSignature(
                        new SharedAccessBlobPolicy()
                        {
                            SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24.0),
                            Permissions = SharedAccessBlobPermissions.Read
                        });
                    cloudBlob.FetchAttributes();

                    return (int?)(cloudBlob.Properties.Length / (1024 * 1024 * 1024));
                }
                catch (Exception)
                {
                    this.WriteWarning("Could not determine OS Disk size.");
                }
            }

            return null;
        }
        static void Main(string[] args)
        {
            string token = GetAuthorizationHeader();
            TokenCloudCredentials credential = new TokenCloudCredentials(subscriptionId, token);
            ResourceManagementClient resourcesClient = new ResourceManagementClient(credential);
            StorageManagementClient storageMgmtClient = new StorageManagementClient(credential);

            try
            {
                //Create a new resource group
                CreateResourceGroup(rgName, resourcesClient);

                //Create a new account in a specific resource group with the specified account name
                CreateStorageAccount(rgName, accountName, storageMgmtClient);

                //Get all the account properties for a given resource group and account name
                StorageAccount storAcct = storageMgmtClient.StorageAccounts.GetProperties(rgName, accountName).StorageAccount;

                //Get a list of storage accounts within a specific resource group
                IList<StorageAccount> storAccts = storageMgmtClient.StorageAccounts.ListByResourceGroup(rgName).StorageAccounts;

                //Get all the storage accounts for a given subscription
                IList<StorageAccount> storAcctsSub = storageMgmtClient.StorageAccounts.List().StorageAccounts;

                //Get the storage account keys for a given account and resource group
                StorageAccountKeys acctKeys = storageMgmtClient.StorageAccounts.ListKeys(rgName, accountName).StorageAccountKeys;

                //Regenerate the account key for a given account in a specific resource group
                StorageAccountKeys regenAcctKeys = storageMgmtClient.StorageAccounts.RegenerateKey(rgName, accountName, KeyName.Key1).StorageAccountKeys;

                //Update the storage account for a given account name and resource group
                UpdateStorageAccount(rgName, accountName, storageMgmtClient);

                //Check if the account name is available
                bool nameAvailable = storageMgmtClient.StorageAccounts.CheckNameAvailability(accountName).NameAvailable;

                //Delete a storage account with the given account name and a resource group
                DeleteStorageAccount(rgName, accountName, storageMgmtClient);
            }
            catch (Hyak.Common.CloudException ce)
            {
                Console.WriteLine(ce.Message);
                Console.ReadLine();
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }
        }
 /// <summary>
 /// Create a new Storage Account. If one already exists then the request still succeeds
 /// </summary>
 /// <param name="rgname">Resource Group Name</param>
 /// <param name="acctName">Account Name</param>
 /// <param name="storageMgmtClient"></param>
 private static void CreateStorageAccount(string rgname, string acctName, StorageManagementClient storageMgmtClient)
 {
     StorageAccountCreateParameters parameters = GetDefaultStorageAccountParameters();
     Console.WriteLine("Creating a storage account...");
     var storageAccountCreateResponse = storageMgmtClient.StorageAccounts.Create(rgname, acctName, parameters);
     Console.WriteLine("Storage account created with name " + storageAccountCreateResponse.StorageAccount.Name);
 }
Пример #58
0
 public void CreateStorageAccount()
 {
     using (var storageManagementClient = new StorageManagementClient(azureLogin.Credentials))
     {
         var sacp = new StorageAccountCreateParameters()
         {
             AccountType = AccountType.StandardLRS,
             Location = demo.Location,
         };
         HandleResult("Create Storage Account", 
             () => storageManagementClient.StorageAccounts.Create(demo.Group, demo.Storage, sacp),
             t => t.Status.ToString());
     }
 }
        static void Main(string[] args)
        {
            string token = GetAuthorizationHeader();
            TokenCredentials credential = new TokenCredentials(token);
            ResourceManagementClient resourcesClient = new ResourceManagementClient(credential) { SubscriptionId = subscriptionId };
            StorageManagementClient storageMgmtClient = new StorageManagementClient(credential) { SubscriptionId = subscriptionId };

            try
            {
                //Register the Storage Resource Provider with the Subscription
                RegisterStorageResourceProvider(resourcesClient);

                //Create a new resource group
                CreateResourceGroup(rgName, resourcesClient);

                //Create a new account in a specific resource group with the specified account name
                CreateStorageAccount(rgName, accountName, storageMgmtClient);

                //Get all the account properties for a given resource group and account name
                StorageAccount storAcct = storageMgmtClient.StorageAccounts.GetProperties(rgName, accountName);

                //Get a list of storage accounts within a specific resource group
                IEnumerable<StorageAccount> storAccts = storageMgmtClient.StorageAccounts.ListByResourceGroup(rgName);

                //Get all the storage accounts for a given subscription
                IEnumerable<StorageAccount> storAcctsSub = storageMgmtClient.StorageAccounts.List();

                //Get the storage account keys for a given account and resource group
                IList<StorageAccountKey> acctKeys = storageMgmtClient.StorageAccounts.ListKeys(rgName, accountName).Keys;

                //Regenerate the account key for a given account in a specific resource group
                IList<StorageAccountKey> regenAcctKeys = storageMgmtClient.StorageAccounts.RegenerateKey(rgName, accountName, "key1").Keys;

                //Update the storage account for a given account name and resource group
                UpdateStorageAccountSku(rgName, accountName, SkuName.StandardLRS, storageMgmtClient);

                //Check if the account name is available
                bool? nameAvailable = storageMgmtClient.StorageAccounts.CheckNameAvailability(accountName).NameAvailable;

                //Delete a storage account with the given account name and a resource group
                DeleteStorageAccount(rgName, accountName, storageMgmtClient);

                Console.ReadLine();
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }
        }
Пример #60
-1
 /// <summary>
 /// Creates storage account
 /// </summary>
 /// <param name="credentials">Credentials to authorize application</param>
 /// <param name="subscriptionId">SubscriptionID that identifies subscription to create resoruce in</param>
 /// <param name="resourceGroup">Name of resource group</param>
 /// <param name="location">Location for resource</param>
 /// <param name="storageAccountName">Globally unique name. Will be part of Fully Qualified Domain Name, FQDN, for Storage Account, i.e. storageAccountnName.blob.core.windows.net, etc.</param>
 /// <param name="accountType">Type of storage account to create</param>
 /// <returns>Awaitable task</returns>
 private static async Task<StorageAccount> CreateStorageAccountAsync(TokenCredentials credentials, string subscriptionId, string resourceGroup, string location, string storageAccountName, AccountType accountType = AccountType.StandardLRS)
 {
     Console.WriteLine("Creating Storage Account");
     var storageClient = new StorageManagementClient(credentials) { SubscriptionId = subscriptionId };
     return await storageClient.StorageAccounts.CreateAsync(resourceGroup, storageAccountName,
         new StorageAccountCreateParameters
         {
             Location = location,
             AccountType = accountType,
         });
 }