public static IHDInsightSubscriptionCredentials GetAccessTokenCredentials(this IAzureHDInsightCommonCommandBase command, 
            AzureSubscription currentSubscription, AzureAccount azureAccount, AzureEnvironment environment)
        {
            ProfileClient profileClient = new ProfileClient();
            AzureContext azureContext = new AzureContext
            {
                Subscription = currentSubscription,
                Environment = environment,
                Account = azureAccount
            };

            var cloudCredentials = AzureSession.AuthenticationFactory.GetSubscriptionCloudCredentials(azureContext) as AccessTokenCredential;
            if (cloudCredentials != null)
            {
                var field= typeof(AccessTokenCredential).GetField("token", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance);
                var accessToken = field.GetValue(cloudCredentials) as IAccessToken;
                if (accessToken != null)
                {
                    return new HDInsightAccessTokenCredential()
                    {
                        SubscriptionId = currentSubscription.Id,
                        AccessToken = accessToken.AccessToken
                    };
                }
            }
            return null;
        }
 public bool IsStorageServiceAvailable(AzureSubscription subscription, string name)
 {
     EnsureCloudServiceClientInitialized(subscription);
     bool available = this.CloudServiceClient.CheckStorageServiceAvailability(name);
     WriteObject(!available);
     return available;
 }
 /// <summary>
 /// Creates new WebsitesClient
 /// </summary>
 /// <param name="subscription">Subscription containing websites to manipulate</param>
 /// <param name="logger">The logger action</param>
 public WebsitesClient(AzureSubscription subscription, Action<string> logger)
 {
     Logger = logger;
     cloudServiceClient = new CloudServiceClient(subscription, debugStream: logger);
     WebsiteManagementClient = AzureSession.ClientFactory.CreateClient<WebSiteManagementClient>(subscription, AzureEnvironment.Endpoint.ServiceManagement);
     this.subscription = subscription;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ServerDataServiceCertAuth"/> class
 /// </summary>
 /// <param name="subscription">The subscription used to connect and authenticate.</param>
 /// <param name="serverName">The name of the server to connect to.</param>
 private ServerDataServiceCertAuth(
     AzureSubscription subscription,
     string serverName)
 {
     this.serverName = serverName;
     this.subscription = subscription;
 }
 /// <summary>
 /// Validates that the given subscription is valid.
 /// </summary>
 /// <param name="subscription">The <see cref="AzureSubscription"/> to validate.</param>
 public static void ValidateSubscription(AzureSubscription subscription)
 {
     if (subscription == null)
     {
         throw new ArgumentException(
             Common.Properties.Resources.InvalidCurrentSubscription);
     }
 }
        public AutomationClient(AzureSubscription subscription,
            AutomationManagement.IAutomationManagementClient automationManagementClient)
        {
            Requires.Argument("automationManagementClient", automationManagementClient).NotNull();

            this.Subscription = subscription;
            this.automationManagementClient = automationManagementClient;
        }
 private void EnsureCloudServiceClientInitialized(AzureSubscription subscription)
 {
     this.CloudServiceClient = this.CloudServiceClient ?? new CloudServiceClient(
         subscription,
         SessionState.Path.CurrentLocation.Path,
         WriteDebug,
         WriteVerbose,
         WriteWarning);
 }
 public StorSimpleClient(AzureSubscription currentSubscription)
 {
     // Temp code to be able to test internal env.
     ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };//IgnoreCertificateErrorHandler;//delegate { return true; };
     
     this.cloudServicesClient = AzureSession.ClientFactory.CreateClient<CloudServiceManagementClient>(currentSubscription, AzureEnvironment.Endpoint.ServiceManagement);
     
     ResourceCachetimeoutPolicy.AbsoluteExpiration = DateTimeOffset.Now.AddHours(1.0d);
 }
 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),
     };
 }
 public EndpointsCommunicator(AzureSubscription subscription)
 {
     if (subscription != Subscription)
     {
         Subscription = subscription;
         SqlClient = null;
         StorageClient = null;
         ResourcesClient = null;
     }
 }
        public static void SetCurrentContext(AzureSubscription subscription, AzureEnvironment environment, AzureAccount account)
        {
            if (environment == null)
            {
                if (subscription != null && CurrentContext != null &&
                    subscription.Environment == CurrentContext.Environment.Name)
                {
                    environment = CurrentContext.Environment;
                }
                else
                {
                    environment = AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud];
                }

                if (subscription != null)
                {
                    subscription.Environment = environment.Name;
                }
            }

            if (account == null)
            {
                if (subscription != null && CurrentContext != null && subscription.Account != null)
                {
                    if (CurrentContext.Account != null && subscription.Account == CurrentContext.Account.Id)
                    {
                        account = CurrentContext.Account;
                    }
                    else
                    {
                        throw new ArgumentException(Resources.AccountIdDoesntMatchSubscription, "account");
                    }

                    subscription.Account = account.Id;

                }
            }

            if (subscription != null && subscription.Environment != environment.Name)
            {
                throw new ArgumentException(Resources.EnvironmentNameDoesntMatchSubscription, "environment");
            }

            CurrentContext = new AzureContext
            {
                Subscription = subscription,
                Account = account,
                Environment = environment
            };
        }
예제 #12
0
        internal Subscription(AzureSubscription azureSubscription)
        {
            if (azureSubscription == null)
            {
                throw new ArgumentNullException();
            }

            ProfileClient client = new ProfileClient();
            var environment = client.GetEnvironmentOrDefault(azureSubscription.Environment);

            this.SubscriptionName = azureSubscription.Name;
            this.SubscriptionId = azureSubscription.Id.ToString();
            this.ServiceEndpoint = new Uri(String.Format("{0}/{1}/services/systemcenter/vmm", environment.GetEndpoint(AzureEnvironment.Endpoint.ServiceManagement).TrimEnd(new[] { '/' }), SubscriptionId));
            this.Certificate = FileUtilities.DataStore.GetCertificate(azureSubscription.Account);
            this.CredentialType = CredentialType.UseCertificate;
        }
        /// <summary>
        /// Creates new Scheduler Management Convenience Client
        /// </summary>
        /// <param name="subscription">Subscription containing websites to manipulate</param>
        public SchedulerMgmntClient(AzureSubscription subscription)
        {
            currentSubscription = subscription;
            csmClient = AzureSession.ClientFactory.CreateClient<CloudServiceManagementClient>(subscription, AzureEnvironment.Endpoint.ServiceManagement);
            schedulerManagementClient = AzureSession.ClientFactory.CreateClient<SchedulerManagementClient>(subscription, AzureEnvironment.Endpoint.ServiceManagement);

            //Get RP properties
            IDictionary<string, string> dict = schedulerManagementClient.GetResourceProviderProperties().Properties;

            //Get available regions
            string val = string.Empty;
            if (dict.TryGetValue(SupportedRegionsKey, out val))
            {
                AvailableRegions = new List<string>();
                val.Split(',').ToList().ForEach(s => AvailableRegions.Add(s));
            }

            //Store global counts for max jobs and min recurrence for each plan     
            if (dict.TryGetValue(FreeMaxJobCountKey, out val))
                FreeMaxJobCountValue = Convert.ToInt32(dict[FreeMaxJobCountKey]);

            if (dict.TryGetValue(FreeMinRecurrenceKey, out val))
                FreeMinRecurrenceValue = TimeSpan.Parse(dict[FreeMinRecurrenceKey]);

            if (dict.TryGetValue(StandardMaxJobCountKey, out val))
                StandardMaxJobCountValue = Convert.ToInt32(dict[StandardMaxJobCountKey]);

            if (dict.TryGetValue(StandardMinRecurrenceKey, out val))
                StandardMinRecurrenceValue = TimeSpan.Parse(dict[StandardMinRecurrenceKey]);

            if (dict.TryGetValue(PremiumMaxJobCountKey, out val))
                PremiumMaxJobCountValue = Convert.ToInt32(dict[PremiumMaxJobCountKey]);

            if (dict.TryGetValue(PremiumMinRecurrenceKey, out val))
                PremiumMinRecurrenceValue = TimeSpan.Parse(dict[PremiumMinRecurrenceKey]);
        }
        public static IHDInsightSubscriptionCredentials GetSubscriptionCredentials(
            this IAzureHDInsightCommonCommandBase command,
            AzureSubscription currentSubscription,
            AzureEnvironment environment,
            AzureProfile profile)
        {
            var accountId = currentSubscription.Account;
            Debug.Assert(profile.Accounts.ContainsKey(accountId));

            if (profile.Accounts[accountId].Type == AzureAccount.AccountType.Certificate)
            {
                return GetSubscriptionCertificateCredentials(command, currentSubscription, profile.Accounts[accountId], environment);
            }
            else if (profile.Accounts[accountId].Type == AzureAccount.AccountType.User)
            {
                return GetAccessTokenCredentials(command, currentSubscription, profile.Accounts[accountId], environment);
            }
            else if (profile.Accounts[accountId].Type == AzureAccount.AccountType.ServicePrincipal)
            {
                return GetAccessTokenCredentials(command, currentSubscription, profile.Accounts[accountId], environment);
            }

            throw new NotSupportedException();
        }
        public AzureSubscription SetSubscriptionAsCurrent(Guid id, string accountName)
        {
            if (Guid.Empty == id)
            {
                throw new ArgumentNullException("id", string.Format(Resources.InvalidSubscriptionId, id));
            }

            AzureSubscription currentSubscription = null;
            var subscription = Profile.Subscriptions.Values.FirstOrDefault(s => s.Id == id);

            if (subscription == null)
            {
                throw new ArgumentException(string.Format(Resources.InvalidSubscriptionId, id), "id");
            }
            else
            {
                currentSubscription = new AzureSubscription { Id = subscription.Id };
                currentSubscription = MergeSubscriptionProperties(subscription, currentSubscription);
                var environment = GetEnvironmentOrDefault(subscription.Environment);
                accountName = string.IsNullOrEmpty(accountName) ? subscription.Account : accountName;
                var account = GetAccount(accountName);
                currentSubscription.Account = account.Id;
                AzureSession.SetCurrentContext(currentSubscription, environment, account);
            }

            return currentSubscription;
        }
        public static IJobSubmissionClientCredential GetJobSubmissionClientCredentials(
            this IAzureHDInsightJobCommandCredentialsBase command,
            AzureSubscription currentSubscription,
            AzureEnvironment environment, string cluster,
            AzureProfile profile)
        {
            IJobSubmissionClientCredential clientCredential = null;
            if (command.Credential != null)
            {
                clientCredential = new BasicAuthCredential
                {
                    Server = GatewayUriResolver.GetGatewayUri(cluster),
                    UserName = command.Credential.UserName,
                    Password = command.Credential.GetCleartextPassword()
                };
            }
            else if (currentSubscription.IsNotNull())
            {
                var subscriptionCredentials = GetSubscriptionCredentials(command, currentSubscription, environment, profile);
                var asCertificateCredentials = subscriptionCredentials as HDInsightCertificateCredential;
                var asTokenCredentials = subscriptionCredentials as HDInsightAccessTokenCredential;
                if (asCertificateCredentials.IsNotNull())
                {
                    clientCredential = new JobSubmissionCertificateCredential(asCertificateCredentials, cluster);
                }
                else if (asTokenCredentials.IsNotNull())
                {
                    clientCredential = new JobSubmissionAccessTokenCredential(asTokenCredentials, cluster);
                }
            }

            return clientCredential;
        }
        public void AddOrSetAzureSubscriptionUpdatesInMemory()
        {
            MockDataStore dataStore = new MockDataStore();
            ProfileClient.DataStore = dataStore;
            ProfileClient client = new ProfileClient();

            client.AddOrSetAccount(azureAccount);
            client.AddOrSetEnvironment(azureEnvironment);
            client.AddOrSetSubscription(azureSubscription1);
            AzureSession.SetCurrentContext(azureSubscription1, azureEnvironment, azureAccount);
            azureSubscription1.Properties[AzureSubscription.Property.StorageAccount] = "testAccount";
            Assert.Equal(azureSubscription1.Id, AzureSession.CurrentContext.Subscription.Id);
            Assert.Equal(azureSubscription1.Properties[AzureSubscription.Property.StorageAccount],
                AzureSession.CurrentContext.Subscription.Properties[AzureSubscription.Property.StorageAccount]);

            var newSubscription = new AzureSubscription
            {
                Id = azureSubscription1.Id,
                Environment = azureSubscription1.Environment,
                Account = azureSubscription1.Account,
                Name = azureSubscription1.Name
            };
            newSubscription.Properties[AzureSubscription.Property.StorageAccount] = "testAccount1";

            client.AddOrSetSubscription(newSubscription);
            var newSubscriptionFromProfile = client.Profile.Subscriptions[newSubscription.Id];

            Assert.Equal(newSubscription.Id, AzureSession.CurrentContext.Subscription.Id);
            Assert.Equal(newSubscription.Id, newSubscriptionFromProfile.Id);
            Assert.Equal(newSubscription.Properties[AzureSubscription.Property.StorageAccount],
                AzureSession.CurrentContext.Subscription.Properties[AzureSubscription.Property.StorageAccount]);
            Assert.Equal(newSubscription.Properties[AzureSubscription.Property.StorageAccount],
                newSubscriptionFromProfile.Properties[AzureSubscription.Property.StorageAccount]);
        }
        private PSAzureSubscription ConstructPsAzureSubscription(AzureSubscription subscription)
        {
            PSAzureSubscription psObject = new PSAzureSubscription();

            psObject.SubscriptionId = subscription.Id.ToString();
            psObject.SubscriptionName = subscription.Name;
            psObject.Environment = subscription.Environment;
            psObject.SupportedModes = subscription.GetProperty(AzureSubscription.Property.SupportedModes);
            psObject.DefaultAccount = subscription.Account;
            psObject.Accounts = ProfileClient.Profile.Accounts.Values.Where(a => a.HasSubscription(subscription.Id)).ToArray();
            psObject.IsDefault = subscription.IsPropertySet(AzureSubscription.Property.Default);
            psObject.IsCurrent = AzureSession.CurrentContext.Subscription != null && AzureSession.CurrentContext.Subscription.Id == subscription.Id;
            psObject.CurrentStorageAccountName = subscription.GetProperty(AzureSubscription.Property.StorageAccount);
            psObject.TenantId = subscription.GetPropertyAsArray(AzureSubscription.Property.Tenants).FirstOrDefault();
            return psObject;
        }
 public void CanGetBasicAuthCredentialFromCredentials()
 {
     var getClustersCommand = new GetAzureHDInsightJobCommand();
     getClustersCommand.Credential = GetPSCredential(TestCredentials.AzureUserName, TestCredentials.AzurePassword);
     var waSubscription = new AzureSubscription()
     {
         Id = IntegrationTestBase.TestCredentials.SubscriptionId,
     };
     waSubscription.Account = "test";
     var profile = new AzureProfile();
     var accessTokenCreds = getClustersCommand.GetJobSubmissionClientCredentials(
         waSubscription,
         AzureSession.CurrentContext.Environment,
         IntegrationTestBase.TestCredentials.WellKnownCluster.DnsName, profile);
     Assert.IsInstanceOfType(accessTokenCreds, typeof(BasicAuthCredential));
     var asBasicAuthCredentials = accessTokenCreds as BasicAuthCredential;
     Assert.IsNotNull(asBasicAuthCredentials);
     Assert.AreEqual(IntegrationTestBase.TestCredentials.AzureUserName, asBasicAuthCredentials.UserName);
     Assert.AreEqual(IntegrationTestBase.TestCredentials.AzurePassword, asBasicAuthCredentials.Password);
 }
        private PSAzureSubscriptionExtended ConstructPsAzureSubscriptionExtended(AzureSubscription subscription, IClientFactory clientFactory)
        {
            using (var client = clientFactory.CreateClient<ManagementClient>(subscription, AzureEnvironment.Endpoint.ServiceManagement))
            {
                var response = client.Subscriptions.Get();
                var environment = ProfileClient.GetEnvironmentOrDefault(subscription.Environment);
                var account = DefaultProfileClient.Profile.Accounts[subscription.Account];
                bool isCert = account.Type == AzureAccount.AccountType.Certificate;

                PSAzureSubscriptionExtended result = new PSAzureSubscriptionExtended(ConstructPsAzureSubscription(subscription))
                {
                    AccountAdminLiveEmailId = response.AccountAdminLiveEmailId,
                    ActiveDirectoryUserId = subscription.Account,
                    CurrentCoreCount = response.CurrentCoreCount,
                    CurrentHostedServices = response.CurrentHostedServices,
                    CurrentDnsServers = response.CurrentDnsServers,
                    CurrentLocalNetworkSites = response.CurrentLocalNetworkSites,
                    CurrentStorageAccounts = response.CurrentStorageAccounts,
                    CurrentVirtualNetworkSites = response.CurrentVirtualNetworkSites,
                    MaxCoreCount = response.MaximumCoreCount,
                    MaxDnsServers = response.MaximumDnsServers,
                    MaxHostedServices = response.MaximumHostedServices,
                    MaxLocalNetworkSites = response.MaximumLocalNetworkSites,
                    MaxStorageAccounts = response.MaximumStorageAccounts,
                    MaxVirtualNetworkSites = response.MaximumVirtualNetworkSites,
                    ServiceAdminLiveEmailId = response.ServiceAdminLiveEmailId,
                    SubscriptionRealName = response.SubscriptionName,
                    SubscriptionStatus = response.SubscriptionStatus.ToString(),
                    ServiceEndpoint = environment.GetEndpoint(AzureEnvironment.Endpoint.ServiceManagement),
                    ResourceManagerEndpoint = environment.GetEndpoint(AzureEnvironment.Endpoint.ResourceManager),
                    IsDefault = subscription.GetProperty(AzureSubscription.Property.Default) != null,
                    Account = account,
                    Certificate = isCert ? ProfileClient.DataStore.GetCertificate(subscription.Account) : null,
                    CurrentStorageAccountName = subscription.GetProperty(AzureSubscription.Property.StorageAccount)
                };

                return result;
            }
        }
 public void CanGetJobSubmissionAccessTokenCredentialFromCurrentSubscription()
 {
     var getClustersCommand = new GetAzureHDInsightJobCommand();
     var waSubscription = new AzureSubscription()
     {
         Id = IntegrationTestBase.TestCredentials.SubscriptionId,
         Account = "test"
     };
     ProfileClient profileClient = new ProfileClient();
     profileClient.Profile.Accounts["test"] = new AzureAccount
     {
         Id = "test",
         Type = AzureAccount.AccountType.User,
         Properties =
             new Dictionary<AzureAccount.Property, string>
             {
                 {AzureAccount.Property.Subscriptions, IntegrationTestBase.TestCredentials.SubscriptionId.ToString() }
             }
     };
     profileClient.Profile.Save();
     var accessTokenCreds = getClustersCommand.GetJobSubmissionClientCredentials(
         waSubscription,
         AzureSession.CurrentContext.Environment,
         IntegrationTestBase.TestCredentials.WellKnownCluster.DnsName,
         profileClient.Profile);
     Assert.IsInstanceOfType(accessTokenCreds, typeof(HDInsightAccessTokenCredential));
     var asTokenCreds = accessTokenCreds as HDInsightAccessTokenCredential;
     Assert.IsNotNull(asTokenCreds);
     Assert.AreEqual("abc", asTokenCreds.AccessToken);
 }
        public CloudServiceClientTests()
        {
            AzurePowerShell.ProfileDirectory = Test.Utilities.Common.Data.AzureSdkAppDir;

            storageService = new MockStorageService()
                .Add(a => SetupStorage(serviceName.ToLowerInvariant(), a))
                .Add(a => SetupStorage(storageName.ToLowerInvariant(), a));

            services = new MockServicesHost()
                .Add(s =>
                {
                    s.Name = serviceName;
                    s.AddDeployment(d =>
                    {
                        d.Slot = DeploymentSlot.Production;
                        d.Name = "mydeployment";
                    });
                });

            subscription = new AzureSubscription
            {
                Properties = new Dictionary<AzureSubscription.Property,string> {{AzureSubscription.Property.Default, "True"}},
                Id = Guid.NewGuid(),
                Name = Test.Utilities.Common.Data.Subscription1,
            };

            cloudBlobUtilityMock = new Mock<CloudBlobUtility>();
            cloudBlobUtilityMock.Setup(f => f.UploadPackageToBlob(
                It.IsAny<StorageManagementClient>(),
                It.IsAny<string>(),
                It.IsAny<string>(),
                It.IsAny<BlobRequestOptions>())).Returns(new Uri("http://www.packageurl.azure.com"));

            clientMocks = new ClientMocks(subscription.Id);

            services.InitializeMocks(clientMocks.ComputeManagementClientMock);
            storageService.InitializeMocks(clientMocks.StorageManagementClientMock);

            client = new CloudServiceClient(subscription,
                clientMocks.ManagementClientMock.Object,
                clientMocks.StorageManagementClientMock.Object,
                clientMocks.ComputeManagementClientMock.Object
                )
            {
                CloudBlobUtility = cloudBlobUtilityMock.Object
            };
        }
        /// <summary>
        /// Executes the set subscription cmdlet operation.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            AzureSubscription subscription = null;

            if (!string.IsNullOrEmpty(SubscriptionId) && string.IsNullOrEmpty(SubscriptionName))
            {
                subscription = ProfileClient.GetSubscription(new Guid(SubscriptionId));
                Environment = subscription.Environment;
            }
            else if (string.IsNullOrEmpty(SubscriptionId) && !string.IsNullOrEmpty(SubscriptionName))
            {
                subscription = ProfileClient.GetSubscription(SubscriptionName);
                Environment = subscription.Environment;
            }
            else
            {
                subscription = new AzureSubscription();
                subscription.Id = new Guid(SubscriptionId);
                subscription.Name = SubscriptionName;
            }

            AzureEnvironment environment = ProfileClient.GetEnvironment(Environment, ServiceEndpoint, ResourceManagerEndpoint);
            if (environment == null)
            {
                environment = DefaultProfileClient.GetEnvironment(Environment, ServiceEndpoint, ResourceManagerEndpoint);
            }

            if (environment == null)
            {
                throw new ArgumentException("ServiceEndpoint and ResourceManagerEndpoint values do not "+
                    "match existing environment. Please use Environment parameter.");
            }
            else
            {
                subscription.Environment = environment.Name;
            }

            if (ServiceEndpoint != null || ResourceManagerEndpoint != null)
            {
                WriteWarning("Please use Environment parameter to specify subscription environment. This "+
                    "warning will be converted into an error in the upcoming release.");
            }

            if (Certificate != null)
            {
                ProfileClient.ImportCertificate(Certificate);
                subscription.Account = Certificate.Thumbprint;
                AzureAccount account = new AzureAccount
                {
                    Id = Certificate.Thumbprint,
                    Type = AzureAccount.AccountType.Certificate
                };
                account.SetOrAppendProperty(AzureAccount.Property.Subscriptions, subscription.Id.ToString());
                ProfileClient.AddOrSetAccount(account);

                if (subscription.Account == null)
                {
                    subscription.Account = account.Id;
                }
            }

            if (subscription.Account == null)
            {
                throw new ArgumentException("Certificate is required for creating a new subscription.");
            }

            if (!string.IsNullOrEmpty(CurrentStorageAccountName))
            {
                subscription.Properties[AzureSubscription.Property.StorageAccount] = CurrentStorageAccountName;
            }

            subscription = ProfileClient.AddOrSetSubscription(subscription);

            if (PassThru)
            {
                WriteObject(subscription);
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="PSRecoveryServicesClient" /> class with 
 /// required current subscription.
 /// </summary>
 /// <param name="azureSubscription">Azure Subscription</param>
 public PSRecoveryServicesClient(AzureSubscription azureSubscription)
 {
     this.recoveryServicesClient =
         AzureSession.ClientFactory.CreateClient<RecoveryServicesManagementClient>(azureSubscription, AzureEnvironment.Endpoint.ServiceManagement);
 }
        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 (string.Equals(tenantAccount.Id, account.Id, StringComparison.InvariantCultureIgnoreCase))
                    {
                        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;
        }
 public StorageCredentialsFactory(StorageManagementClient client, AzureSubscription currentSubscription)
 {
     this.client = client;
     this.currentSubscription = currentSubscription;
 }
예제 #27
0
 public SqlClient(AzureSubscription subscription)
 {
     Subscription = subscription;
     Communicator = new EndpointsCommunicator(subscription);
     IgnoreStorage = false;
 }
        public AzureSubscription AddOrSetSubscription(AzureSubscription subscription)
        {
            if (subscription == null)
            {
                throw new ArgumentNullException("Subscription needs to be specified.", "subscription");
            }
            if (subscription.Environment == null)
            {
                throw new ArgumentNullException("Environment needs to be specified.", "subscription.Environment");
            }
            // Validate environment
            GetEnvironmentOrDefault(subscription.Environment);

            if (Profile.Subscriptions.ContainsKey(subscription.Id))
            {
                Profile.Subscriptions[subscription.Id] = MergeSubscriptionProperties(subscription, Profile.Subscriptions[subscription.Id]);
            }
            else
            {
                Debug.Assert(!string.IsNullOrEmpty(subscription.Account));
                if (!Profile.Accounts.ContainsKey(subscription.Account))
                {
                    throw new KeyNotFoundException(string.Format("The specified account {0} does not exist in profile accounts", subscription.Account));
                }

                Profile.Subscriptions[subscription.Id] = subscription;
            }

            // Update in-memory subscription
            if (AzureSession.CurrentContext != null && AzureSession.CurrentContext.Subscription != null &&
                AzureSession.CurrentContext.Subscription.Id == subscription.Id)
            {
                var account = GetAccountOrDefault(subscription.Account);
                var environment = GetEnvironmentOrDefault(subscription.Environment);
                AzureSession.SetCurrentContext(Profile.Subscriptions[subscription.Id], environment, account);
            }

            return Profile.Subscriptions[subscription.Id];
        }
예제 #29
0
 public PSCacheClient(AzureSubscription currentSubscription)
 {
     client = AzureSession.ClientFactory.CreateClient<ManagedCacheClient>(currentSubscription, AzureEnvironment.Endpoint.ServiceManagement);
 }
        private AzureSubscription MergeSubscriptionProperties(AzureSubscription subscription1, AzureSubscription subscription2)
        {
            if (subscription1 == null || subscription2 == null)
            {
                throw new ArgumentNullException("subscription1");
            }
            if (subscription1.Id != subscription2.Id)
            {
                throw new ArgumentException("Subscription Ids do not match.");
            }
            AzureSubscription mergedSubscription = new AzureSubscription
            {
                Id = subscription1.Id,
                Name = subscription1.Name,
                Environment = subscription1.Environment,
                Account = subscription1.Account ?? subscription2.Account
            };

            // Merge all properties
            foreach (AzureSubscription.Property property in Enum.GetValues(typeof(AzureSubscription.Property)))
            {
                string propertyValue = subscription1.GetProperty(property) ?? subscription2.GetProperty(property);
                if (propertyValue != null)
                {
                    mergedSubscription.Properties[property] = propertyValue;
                }
            }

            // Merge RegisteredResourceProviders
            var registeredProviders = subscription1.GetPropertyAsArray(AzureSubscription.Property.RegisteredResourceProviders)
                    .Union(subscription2.GetPropertyAsArray(AzureSubscription.Property.RegisteredResourceProviders), StringComparer.CurrentCultureIgnoreCase);

            mergedSubscription.SetProperty(AzureSubscription.Property.RegisteredResourceProviders, registeredProviders.ToArray());

            // Merge SupportedMode
            var supportedModes = subscription1.GetPropertyAsArray(AzureSubscription.Property.SupportedModes)
                    .Union(subscription2.GetPropertyAsArray(AzureSubscription.Property.SupportedModes), StringComparer.CurrentCultureIgnoreCase);

            mergedSubscription.SetProperty(AzureSubscription.Property.SupportedModes, supportedModes.ToArray());

            // Merge Tenants
            var tenants = subscription1.GetPropertyAsArray(AzureSubscription.Property.Tenants)
                    .Union(subscription2.GetPropertyAsArray(AzureSubscription.Property.Tenants), StringComparer.CurrentCultureIgnoreCase);

            mergedSubscription.SetProperty(AzureSubscription.Property.Tenants, tenants.ToArray());

            return mergedSubscription;
        }