Exemplo n.º 1
0
        private void LoadAccountTenants(ref AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
        {
            var commonTenantToken = AzureSession.AuthenticationFactory.Authenticate(ref account, environment,
                                                                                    AuthenticationFactory.CommonAdTenant, password, promptBehavior);

            if (environment.IsEndpointSet(AzureEnvironment.Endpoint.ResourceManager))
            {
                using (var subscriptionClient = AzureSession.ClientFactory
                                                .CreateCustomClient <Azure.Subscriptions.SubscriptionClient>(
                           new TokenCloudCredentials(commonTenantToken.AccessToken),
                           environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
                {
                    account.SetOrAppendProperty(AzureAccount.Property.Tenants,
                                                subscriptionClient.Tenants.List().TenantIds.Select(ti => ti.TenantId).ToArray());
                }
            }
            else
            {
                using (var subscriptionClient = AzureSession.ClientFactory
                                                .CreateCustomClient <WindowsAzure.Subscriptions.SubscriptionClient>(
                           new TokenCloudCredentials(commonTenantToken.AccessToken),
                           environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement)))
                {
                    var subscriptionListResult = subscriptionClient.Subscriptions.List();
                    account.SetOrAppendProperty(AzureAccount.Property.Tenants,
                                                subscriptionListResult.Subscriptions.Select(s => s.ActiveDirectoryTenantId).Distinct().ToArray());
                }
            }
        }
Exemplo n.º 2
0
        private string[] LoadAccountTenants(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
        {
            var commonTenantToken = AzureSession.AuthenticationFactory.Authenticate(account, environment,
                                                                                    AuthenticationFactory.CommonAdTenant, password, promptBehavior);

            if (environment.IsEndpointSet(AzureEnvironment.Endpoint.ResourceManager))
            {
                using (CSMSubscriptionClient csmSubscriptionClient = AzureSession.ClientFactory
                                                                     .CreateCustomClient <CSMSubscriptionClient>(
                           new TokenCloudCredentials(commonTenantToken.AccessToken),
                           environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
                {
                    return(csmSubscriptionClient.Tenants.List().TenantIds.Select(ti => ti.TenantId).ToArray());
                }
            }
            else
            {
                using (RDFESubscriptionClient rdfeSubscriptionClient = AzureSession.ClientFactory
                                                                       .CreateCustomClient <RDFESubscriptionClient>(
                           new TokenCloudCredentials(commonTenantToken.AccessToken),
                           environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement)))
                {
                    var subscriptionListResult = rdfeSubscriptionClient.Subscriptions.List();
                    return(subscriptionListResult.Subscriptions.Select(s => s.ActiveDirectoryTenantId).Distinct().ToArray());
                }
            }
        }
Exemplo n.º 3
0
        static async Task MainAsync()
        {
            // Set Environment - Choose between Azure public cloud, china cloud and US govt. cloud
            _environment = AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud];

            // Get the credentials
            TokenCloudCredentials cloudCreds = GetCredsFromServicePrincipal();

            var tokenCreds = new TokenCredentials(cloudCreds.Token);

            var loggingHandler = new LoggingHandler(new HttpClientHandler());

            // Create our own HttpClient so we can do logging
            var httpClient = new HttpClient(loggingHandler);

            // Use the creds to create the clients we need
            _resourceGroupClient = new ResourceManagementClient(_environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager), tokenCreds, loggingHandler);
            _resourceGroupClient.SubscriptionId = cloudCreds.SubscriptionId;
            _websiteClient = new WebSiteManagementClient(_environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager), tokenCreds, loggingHandler);
            _websiteClient.SubscriptionId = cloudCreds.SubscriptionId;

            await ListResourceGroupsAndSites();

            // Note: site names are globally unique, so you may need to change it to avoid conflicts
            await CreateSite("MyResourceGroup", "MyAppServicePlan", "SampleSiteFromAPI", "West US");

            // Upload certificate to resource group
            await UpdateLoadCertificate("MyResourceGroup", "CertificateName", "West US", "PathToPfxFile", "CertificatePassword");

            // Bind certificate to resource group
            await BindCertificateToSite("MyResourceGroup", "SiteName", "CertificateName", "hostName");
        }
Exemplo n.º 4
0
        private IEnumerable <AzureSubscription> ListSubscriptionsForTenant(AzureAccount account, AzureEnvironment environment,
                                                                           SecureString password, ShowDialog promptBehavior, string tenantId)
        {
            IAccessToken accessToken = null;

            try
            {
                accessToken = AcquireAccessToken(account, environment, tenantId, password, promptBehavior);
            }
            catch
            {
                WriteWarningMessage(string.Format(Microsoft.Azure.Commands.Profile.Properties.Resources.UnableToAqcuireToken, tenantId));
                return(new List <AzureSubscription>());
            }

            using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient <SubscriptionClient>(
                       new TokenCloudCredentials(accessToken.AccessToken),
                       environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
            {
                var subscriptions = subscriptionClient.Subscriptions.List();
                if (subscriptions != null && subscriptions.Subscriptions != null)
                {
                    return
                        (subscriptions.Subscriptions.Select(
                             (s) =>
                             s.ToAzureSubscription(new AzureContext(_profile.Context.Subscription, account,
                                                                    environment, CreateTenantFromString(tenantId, accessToken.TenantId)))));
                }

                return(new List <AzureSubscription>());
            }
        }
Exemplo n.º 5
0
        private List <AzureTenant> ListAccountTenants(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
        {
            List <AzureTenant> result = new List <AzureTenant>();

            try
            {
                var commonTenantToken = AcquireAccessToken(account, environment, AuthenticationFactory.CommonAdTenant,
                                                           password, promptBehavior);

                using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient <SubscriptionClient>(
                           new TokenCloudCredentials(commonTenantToken.AccessToken),
                           environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
                {
                    //TODO: Fix subscription client to not require subscriptionId
                    result = account.MergeTenants(subscriptionClient.Tenants.List().TenantIds, commonTenantToken);
                }
            }
            catch
            {
                WriteWarningMessage(string.Format(Microsoft.Azure.Commands.Profile.Properties.Resources.UnableToAqcuireToken, AuthenticationFactory.CommonAdTenant));
                if (account.IsPropertySet(AzureAccount.Property.Tenants))
                {
                    result =
                        account.GetPropertyAsArray(AzureAccount.Property.Tenants)
                        .Select(ti => new AzureTenant()
                    {
                        Id     = new Guid(ti),
                        Domain = AccessTokenExtensions.GetDomain(account.Id)
                    }).ToList();
                }
            }

            return(result);
        }
Exemplo n.º 6
0
        public static void StorageAccountTestInit(TestContext testContext)
        {
            TestBase.TestClassInitialize(testContext);

            if (isResourceMode)
            {
                NodeJSAgent.AgentConfig.UseEnvVar = false;

                AzureEnvironment environment = Utility.GetTargetEnvironment();
                managementClient = new ManagementClient(Utility.GetCertificateCloudCredential(),
                                                        environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement));

                accountUtils = new AccountUtils(lang, isResourceMode);

                accountName = accountUtils.GenerateAccountName();

                resourceLocation  = isMooncake ? Constants.MCLocation.ChinaEast : allowedLocation;
                resourceManager   = new ResourceManagerWrapper();
                resourceGroupName = accountUtils.GenerateResourceGroupName();
                resourceManager.CreateResourceGroup(resourceGroupName, resourceLocation);

                var parameters = new SRPModel.StorageAccountCreateParameters(new SRPModel.Sku(SRPModel.SkuName.StandardGRS), SRPModel.Kind.StorageV2,
                                                                             isMooncake ? Constants.MCLocation.ChinaEast : allowedLocation);
                accountUtils.SRPStorageClient.StorageAccounts.CreateAsync(resourceGroupName, accountName, parameters, CancellationToken.None).Wait();

                //resourceGroupName = "weitest";
                //accountName = "weitesttemp";
            }
        }
Exemplo n.º 7
0
        private IEnumerable <AzureSubscription> ListResourceManagerSubscriptions(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior, string[] tenants)
        {
            List <AzureSubscription> result = new List <AzureSubscription>();

            if (!environment.IsEndpointSet(AzureEnvironment.Endpoint.ResourceManager))
            {
                return(result);
            }

            foreach (var tenant in tenants)
            {
                try
                {
                    var tenantAccount = new AzureAccount();
                    CopyAccount(account, tenantAccount);
                    var tenantToken = AzureSession.AuthenticationFactory.Authenticate(tenantAccount, environment, tenant, password, ShowDialog.Never);
                    if (string.Equals(tenantAccount.Id, account.Id, StringComparison.InvariantCultureIgnoreCase))
                    {
                        tenantAccount = account;
                    }

                    tenantAccount.SetOrAppendProperty(AzureAccount.Property.Tenants, new string[] { tenant });

                    using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient <CSMSubscriptionClient>(
                               new TokenCloudCredentials(tenantToken.AccessToken),
                               environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
                    {
                        var subscriptionListResult = subscriptionClient.Subscriptions.List();
                        foreach (var subscription in subscriptionListResult.Subscriptions)
                        {
                            AzureSubscription psSubscription = new AzureSubscription
                            {
                                Id          = new Guid(subscription.SubscriptionId),
                                Name        = subscription.DisplayName,
                                Environment = environment.Name
                            };
                            psSubscription.SetProperty(AzureSubscription.Property.SupportedModes, AzureModule.AzureResourceManager.ToString());
                            psSubscription.SetProperty(AzureSubscription.Property.Tenants, tenant);
                            psSubscription.Account = tenantAccount.Id;
                            tenantAccount.SetOrAppendProperty(AzureAccount.Property.Subscriptions, new string[] { psSubscription.Id.ToString() });
                            result.Add(psSubscription);
                        }
                    }

                    AddOrSetAccount(tenantAccount);
                }
                catch (CloudException cEx)
                {
                    WriteOrThrowAadExceptionMessage(cEx);
                }
                catch (AadAuthenticationException aadEx)
                {
                    WriteOrThrowAadExceptionMessage(aadEx);
                }
            }

            return(result);
        }
Exemplo n.º 8
0
 public static IHDInsightSubscriptionCredentials GetSubscriptionCertificateCredentials(this IAzureHDInsightCommonCommandBase command,
                                                                                       AzureSubscription currentSubscription, AzureAccount azureAccount, AzureEnvironment environment)
 {
     return(new HDInsightCertificateCredential
     {
         SubscriptionId = currentSubscription.Id,
         Certificate = ProfileClient.DataStore.GetCertificate(currentSubscription.Account),
         Endpoint = environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement),
     });
 }
Exemplo n.º 9
0
        static async Task MainAsync()
        {
            // Set Environment - Choose between Azure public cloud, china cloud and US govt. cloud
            _environment = AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud];

            // Get the credentials
            TokenCloudCredentials cloudCreds = GetCredsFromServicePrincipal();

            var tokenCreds = new TokenCredentials(cloudCreds.Token);

            var loggingHandler = new LoggingHandler(new HttpClientHandler());

            // Create our own HttpClient so we can do logging
            var httpClient = new HttpClient(loggingHandler);

            // Use the creds to create the clients we need
            _resourceGroupClient = new ResourceManagementClient(_environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager), tokenCreds, loggingHandler);
            _resourceGroupClient.SubscriptionId = cloudCreds.SubscriptionId;
            _websiteClient = new WebSiteManagementClient(_environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager), tokenCreds, loggingHandler);
            _websiteClient.SubscriptionId = cloudCreds.SubscriptionId;
            _dnsClient = new DnsManagementClient(tokenCreds);

            await ListResourceGroupsAndSites();

            // Note: site names are globally unique, so you may need to change it to avoid conflicts
            await CreateSite("MyResourceGroup", "MyAppServicePlan", "SampleSiteFromAPI798", "West US");

            // NOTE: uncomment lines below and change parameters as appropriate

            // if you have a configured  Azure DNS Zone you can add subdomains (i.e. subdomain.mydomain.com )
            //await CreateOrUpdateCNAME("MyResourceGroup", "My DNS Zone", "subdomain", "mywebsite.azurewebsites.net");

            // Upload certificate to resource group
            //await UpdateLoadCertificate("MyResourceGroup", "CertificateName", "West US", "PathToPfxFile", "CertificatePassword");

            // Bind certificate to resource group
            //await BindCertificateToSite("MyResourceGroup", "SiteName", "CertificateName", "hostName");
        }
Exemplo n.º 10
0
 public AccountUtils(Language language, bool isResourceMode)
 {
     this.language = language;
     if (isResourceMode)
     {
         StorageClient = new StorageManagementClient(Utility.GetCertificateCloudCredential());
     }
     else
     {
         AzureEnvironment environment = Utility.GetTargetEnvironment();
         StorageClient = new StorageManagementClient(Utility.GetCertificateCloudCredential(),
                                                     environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement));
     }
 }
Exemplo n.º 11
0
        private IEnumerable <AzureTenant> ListAccountTenants(AzureAccount account, AzureEnvironment environment, ShowDialog promptBehavior)
        {
            var commonTenantToken = AcquireAccessToken(account, environment, AuthenticationFactory.CommonAdTenant, promptBehavior);

            using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient <SubscriptionClient>(
                       new TokenCloudCredentials(commonTenantToken.AccessToken),
                       environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
            {
                return(subscriptionClient.Tenants.List().TenantIds.Select
                           (_ => new AzureTenant {
                    Id = new Guid(_.TenantId), Domain = commonTenantToken.GetDomain()
                }));
            }
        }
Exemplo n.º 12
0
        private IEnumerable <AzureSubscription> ListServiceManagementSubscriptions(ref AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
        {
            List <AzureSubscription> result = new List <AzureSubscription>();

            if (!environment.IsEndpointSet(AzureEnvironment.Endpoint.ServiceManagement))
            {
                return(result);
            }

            foreach (var tenant in account.GetPropertyAsArray(AzureAccount.Property.Tenants))
            {
                try
                {
                    var tenantToken = AzureSession.AuthenticationFactory.Authenticate(ref account, environment, tenant, password, ShowDialog.Never);

                    using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient <WindowsAzure.Subscriptions.SubscriptionClient>(
                               new TokenCloudCredentials(tenantToken.AccessToken),
                               environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement)))
                    {
                        var subscriptionListResult = subscriptionClient.Subscriptions.List();
                        foreach (var subscription in subscriptionListResult.Subscriptions)
                        {
                            AzureSubscription psSubscription = new AzureSubscription
                            {
                                Id          = new Guid(subscription.SubscriptionId),
                                Name        = subscription.SubscriptionName,
                                Environment = environment.Name
                            };
                            psSubscription.Properties[AzureSubscription.Property.SupportedModes] = AzureModule.AzureServiceManagement.ToString();
                            psSubscription.SetProperty(AzureSubscription.Property.Tenants, subscription.ActiveDirectoryTenantId);

                            AzureSession.SubscriptionTokenCache[Tuple.Create(psSubscription.Id, account.Id)] = tenantToken;

                            result.Add(psSubscription);
                        }
                    }
                }
                catch (CloudException cEx)
                {
                    WriteOrThrowAadExceptionMessage(cEx);
                }
                catch (AadAuthenticationException aadEx)
                {
                    WriteOrThrowAadExceptionMessage(aadEx);
                }
            }

            return(result);
        }
Exemplo n.º 13
0
        private string[] LoadAccountTenants(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
        {
            var commonTenantToken = AzureSession.AuthenticationFactory.Authenticate(account, environment,
                                                                                    AuthenticationFactory.CommonAdTenant, password, promptBehavior);

            using (SubscriptionClient SubscriptionClient = AzureSession.ClientFactory
                                                           .CreateCustomClient <SubscriptionClient>(
                       new TokenCloudCredentials(commonTenantToken.AccessToken),
                       environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement)))
            {
                var subscriptionListResult = SubscriptionClient.Subscriptions.List();
                return(subscriptionListResult.Subscriptions.Where(s => s.SubscriptionStatus == WindowsAzure.Subscriptions.Models.SubscriptionStatus.Active ||
                                                                  s.SubscriptionStatus == WindowsAzure.Subscriptions.Models.SubscriptionStatus.Warned)
                       .Select(s => s.ActiveDirectoryTenantId)
                       .Where(s => !string.IsNullOrWhiteSpace(s))
                       .Distinct().ToArray());
            }
        }
Exemplo n.º 14
0
        private int TryGetTenantSubscription(IAccessToken accessToken,
                                             AzureAccount account,
                                             AzureEnvironment environment,
                                             string tenantId,
                                             List <AzureSubscription> azureSubscriptions,
                                             List <string> authtokens)
        {
            using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient <SubscriptionClient>(
                       new TokenCloudCredentials(accessToken.AccessToken),
                       environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
            {
                var subscriptions = (subscriptionClient.Subscriptions.List().Subscriptions ??
                                     new List <Microsoft.Azure.Subscriptions.Models.Subscription>())
                                    .Where(s => "enabled".Equals(s.State, StringComparison.OrdinalIgnoreCase) ||
                                           "warned".Equals(s.State, StringComparison.OrdinalIgnoreCase));

                account.SetProperty(AzureAccount.Property.Subscriptions, subscriptions.Select(i => i.SubscriptionId).ToArray());

                foreach (var subscriptionFromServer in subscriptions)
                {
                    var currentSubscription = new AzureSubscription
                    {
                        Id          = new Guid(subscriptionFromServer.SubscriptionId),
                        Account     = accessToken.UserId,
                        Environment = environment.Name,
                        Name        = subscriptionFromServer.DisplayName,
                        State       = subscriptionFromServer.State,
                        Properties  = new Dictionary <AzureSubscription.Property, string>
                        {
                            { AzureSubscription.Property.Tenants, accessToken.TenantId }
                        }
                    };

                    azureSubscriptions.Add(currentSubscription);
                    authtokens.Add(accessToken.AccessToken);
                }

                return(subscriptions.Count());
            }
        }
Exemplo n.º 15
0
        private IEnumerable <AzureSubscription> ListSubscriptionsForTenant(AzureAccount account, AzureEnvironment environment,
                                                                           SecureString password, ShowDialog promptBehavior, string tenantId)
        {
            var accessToken = AcquireAccessToken(account, environment, tenantId, password, promptBehavior);

            using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient <SubscriptionClient>(
                       new TokenCloudCredentials(accessToken.AccessToken),
                       environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
            {
                var subscriptions = subscriptionClient.Subscriptions.List();
                if (subscriptions != null && subscriptions.Subscriptions != null)
                {
                    return
                        (subscriptions.Subscriptions.Select(
                             (s) =>
                             s.ToAzureSubscription(new AzureContext(_profile.Context.Subscription, account,
                                                                    environment, CreateTenantFromString(tenantId)))));
                }

                return(null);
            }
        }
Exemplo n.º 16
0
        private List <AzureTenant> ListAccountTenants(AzureAccount account, AzureEnvironment environment, ShowDialog promptBehavior)
        {
            List <AzureTenant> result = new List <AzureTenant>();

            try
            {
                var commonTenantToken = AcquireAccessToken(account, environment, AuthenticationFactory.CommonAdTenant, promptBehavior);

                using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient <SubscriptionClient>(
                           new TokenCloudCredentials(commonTenantToken.AccessToken),
                           environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
                {
                    //TODO: Fix subscription client to not require subscriptionId
                    result = MergeTenants(account, subscriptionClient.Tenants.List().TenantIds, commonTenantToken);
                }
            }
            catch
            {
                Console.WriteLine(string.Format("Unable to acquire token for tenant '{0}'", AuthenticationFactory.CommonAdTenant));
            }

            return(result);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Gets the user's Azure account and subscription information
        /// </summary>
        /// <returns>An <see cref="Microsoft.Azure.Common.Authentication.Models.AzureContext"/> instance containing
        /// information about the user's Azure account and subscription.</returns>
        private static AzureContext GetAzureContext()
        {
            AzureAccount azureAccount = new AzureAccount()
            {
                Type = AzureAccount.AccountType.User
            };
            AzureEnvironment environment = AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud];

            IAccessToken accessToken = AzureSession.AuthenticationFactory.Authenticate(
                azureAccount,
                environment,
                AuthenticationFactory.CommonAdTenant,
                null,
                ShowDialog.Auto,  // Auto will use cached credentials. Set this parameter to ShowDialog.Always to always get a login prompt.
                TokenCache.DefaultShared);

            string subscriptionId = null;

            using (SubscriptionClient subscriptionClient = AzureSession.ClientFactory.CreateCustomClient <SubscriptionClient>(
                       new TokenCloudCredentials(accessToken.AccessToken),
                       environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
            {
                subscriptionId = SelectSubscription(subscriptionClient);
            }

            AzureSubscription azureSubscription = new AzureSubscription();

            azureSubscription.Id         = new Guid(subscriptionId);
            azureSubscription.Properties = new Dictionary <AzureSubscription.Property, string> ();
            azureSubscription.Properties.Add(AzureSubscription.Property.Tenants, accessToken.TenantId);

            azureAccount.Properties[AzureAccount.Property.Tenants] = accessToken.TenantId;

            AzureContext context = new AzureContext(azureSubscription, azureAccount, environment);

            return(context);
        }
Exemplo n.º 18
0
        static void Main(string[] args)
        {
            // Set Environment - Choose between Azure public cloud, china cloud and US govt. cloud
            _environment = AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud];

            // Get the credentials
            var tokenCloudCreds = GetCredsFromServicePrincipal();
            var tokenCreds      = new TokenCredentials(tokenCloudCreds.Token);

            // Use credentials to create Scheduler managment client.
            SchedulerManagementClient schedulerManagementClient = new SchedulerManagementClient(_environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager), tokenCreds)
            {
                SubscriptionId = ConfigurationManager.AppSettings["AzureSubscriptionId"]
            };

            CreateJobCollectionAndJobs(schedulerManagementClient);
        }
Exemplo n.º 19
0
        private bool TryGetTenantSubscription(IAccessToken accessToken,
                                              AzureAccount account,
                                              AzureEnvironment environment,
                                              string tenantId,
                                              string subscriptionId,
                                              string subscriptionName,
                                              out AzureSubscription subscription,
                                              out AzureTenant tenant)
        {
            using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient <SubscriptionClient>(
                       new TokenCloudCredentials(accessToken.AccessToken),
                       environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
            {
                Subscriptions.Models.Subscription subscriptionFromServer = null;

                try
                {
                    if (subscriptionId != null)
                    {
                        subscriptionFromServer = subscriptionClient.Subscriptions.Get(subscriptionId).Subscription;
                    }
                    else
                    {
                        var subscriptions = (subscriptionClient.Subscriptions.List().Subscriptions ??
                                             new List <Microsoft.Azure.Subscriptions.Models.Subscription>())
                                            .Where(s => "enabled".Equals(s.State, StringComparison.OrdinalIgnoreCase) ||
                                                   "warned".Equals(s.State, StringComparison.OrdinalIgnoreCase));

                        if (subscriptions.Any())
                        {
                            if (subscriptionName != null)
                            {
                                subscriptionFromServer = subscriptions.FirstOrDefault(
                                    s => s.DisplayName.Equals(subscriptionName, StringComparison.OrdinalIgnoreCase));
                            }
                            else
                            {
                                if (subscriptions.Count() > 1)
                                {
                                    WriteWarningMessage(string.Format(
                                                            "TenantId '{0}' contains more than one active subscription. First one will be selected for further use. " +
                                                            "To select another subscription, use Set-AzureRmContext.",
                                                            tenantId));
                                }
                                subscriptionFromServer = subscriptions.First();
                            }
                        }
                    }
                }
                catch (CloudException ex)
                {
                    WriteWarningMessage(ex.Message);
                }

                if (subscriptionFromServer != null)
                {
                    subscription = new AzureSubscription
                    {
                        Id          = new Guid(subscriptionFromServer.SubscriptionId),
                        Account     = accessToken.UserId,
                        Environment = environment.Name,
                        Name        = subscriptionFromServer.DisplayName,
                        State       = subscriptionFromServer.State,
                        Properties  = new Dictionary <AzureSubscription.Property, string> {
                            { AzureSubscription.Property.Tenants, accessToken.TenantId }
                        }
                    };

                    tenant        = new AzureTenant();
                    tenant.Id     = new Guid(accessToken.TenantId);
                    tenant.Domain = accessToken.GetDomain();
                    return(true);
                }

                subscription = null;

                if (accessToken != null && accessToken.TenantId != null)
                {
                    tenant    = new AzureTenant();
                    tenant.Id = Guid.Parse(accessToken.TenantId);
                    if (accessToken.UserId != null)
                    {
                        var domain = accessToken.UserId.Split(new[] { '@' }, StringSplitOptions.RemoveEmptyEntries);
                        if (domain.Length == 2)
                        {
                            tenant.Domain = domain[1];
                        }
                    }
                    return(true);
                }

                tenant = null;
                return(false);
            }
        }
Exemplo n.º 20
0
        private IEnumerable <AzureSubscription> ListServiceManagementSubscriptions(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior, string[] tenants)
        {
            List <AzureSubscription> result = new List <AzureSubscription>();

            if (!environment.IsEndpointSet(AzureEnvironment.Endpoint.ServiceManagement))
            {
                return(result);
            }

            foreach (var tenant in tenants)
            {
                try
                {
                    var tenantAccount = new AzureAccount();
                    CopyAccount(account, tenantAccount);
                    var tenantToken = AzureSession.AuthenticationFactory.Authenticate(tenantAccount, environment, tenant, password, ShowDialog.Never);
                    if (tenantAccount.Id == account.Id)
                    {
                        tenantAccount = account;
                    }

                    tenantAccount.SetOrAppendProperty(AzureAccount.Property.Tenants, new string[] { tenant });
                    using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient <WindowsAzure.Subscriptions.SubscriptionClient>(
                               new TokenCloudCredentials(tenantToken.AccessToken),
                               environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement)))
                    {
                        var subscriptionListResult = subscriptionClient.Subscriptions.List();
                        foreach (var subscription in subscriptionListResult.Subscriptions)
                        {
                            // only add the subscription if it's actually in this tenant
                            if (subscription.ActiveDirectoryTenantId == tenant)
                            {
                                AzureSubscription psSubscription = new AzureSubscription
                                {
                                    Id          = new Guid(subscription.SubscriptionId),
                                    Name        = subscription.SubscriptionName,
                                    Environment = environment.Name
                                };
                                psSubscription.Properties[AzureSubscription.Property.SupportedModes] =
                                    AzureModule.AzureServiceManagement.ToString();
                                psSubscription.SetProperty(AzureSubscription.Property.Tenants,
                                                           subscription.ActiveDirectoryTenantId);
                                psSubscription.Account = tenantAccount.Id;
                                tenantAccount.SetOrAppendProperty(AzureAccount.Property.Subscriptions,
                                                                  new string[] { psSubscription.Id.ToString() });
                                result.Add(psSubscription);
                            }
                        }
                    }

                    AddOrSetAccount(tenantAccount);
                }
                catch (CloudException cEx)
                {
                    WriteOrThrowAadExceptionMessage(cEx);
                }
                catch (AadAuthenticationException aadEx)
                {
                    WriteOrThrowAadExceptionMessage(aadEx);
                }
            }

            return(result);
        }
Exemplo n.º 21
0
        private bool TryGetTenantSubscription(IAccessToken accessToken,
                                              AzureAccount account,
                                              AzureEnvironment environment,
                                              string tenantId,
                                              string subscriptionId,
                                              string subscriptionName,
                                              out AzureSubscription subscription,
                                              out AzureTenant tenant)
        {
            using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient <SubscriptionClient>(
                       new TokenCloudCredentials(accessToken.AccessToken),
                       environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
            {
                Subscriptions.Models.Subscription subscriptionFromServer = null;

                try
                {
                    if (subscriptionId != null)
                    {
                        subscriptionFromServer = subscriptionClient.Subscriptions.Get(subscriptionId).Subscription;
                    }
                    else
                    {
                        var subscriptions = subscriptionClient.Subscriptions.List().Subscriptions;
                        if (subscriptions != null && subscriptions.Any())
                        {
                            if (subscriptionName != null)
                            {
                                subscriptionFromServer = subscriptions.FirstOrDefault(s => s.DisplayName.Equals(subscriptionName, StringComparison.OrdinalIgnoreCase));
                            }
                            else
                            {
                                if (subscriptions.Count > 1)
                                {
                                    WriteWarningMessage(string.Format(
                                                            "Tenant '{0}' contains more than one subscription. First one will be selected for further use. " +
                                                            "To select another subscription, use Set-AzureRmContext.",
                                                            tenantId));
                                }
                                subscriptionFromServer = subscriptions.First();
                            }
                        }
                    }
                }
                catch (CloudException ex)
                {
                    WriteWarningMessage(ex.Message);
                }

                if (subscriptionFromServer != null)
                {
                    subscription = new AzureSubscription
                    {
                        Id          = new Guid(subscriptionFromServer.SubscriptionId),
                        Account     = accessToken.UserId,
                        Environment = environment.Name,
                        Name        = subscriptionFromServer.DisplayName,
                        Properties  = new Dictionary <AzureSubscription.Property, string> {
                            { AzureSubscription.Property.Tenants, accessToken.TenantId }
                        }
                    };

                    account.Properties[AzureAccount.Property.Tenants] = accessToken.TenantId;
                    tenant        = new AzureTenant();
                    tenant.Id     = new Guid(accessToken.TenantId);
                    tenant.Domain = accessToken.GetDomain();
                    return(true);
                }

                subscription = null;
                tenant       = null;
                return(false);
            }
        }