Пример #1
0
        /// <summary>
        /// Creates a standard <see cref="ServiceBusManagementClient"/> that targets the Azure subscription
        /// specified in the <see cref="AzureSubscription"/> static class.
        /// </summary>
        /// <returns>
        /// A standard <see cref="ServiceBusManagementClient"/> that targets the Azure subscription
        /// specified in the <see cref="AzureSubscription"/> static class.
        /// </returns>
        internal static ServiceBusManagementClient CreateServiceBusClient()
        {
            var azureSubscription = new AzureSubscription(SettingsPath, SubscriptionId);

            return new ServiceBusManagementClient(
                new CertificateCloudCredentials(
                    SubscriptionId,
                    new X509Certificate2(Convert.FromBase64String(azureSubscription.ManagementCertificate))));
        }
        public virtual void Initialize()
        {
            string subscriptionId = "[YOUR SUBSCRIPTION ID]";
            string certThumbprint = "[YOUR MANAGEMENT CERT THUMBPRINT]";

            // Instantiate the subscription
            subscription = new AzureSubscription(subscriptionId, certThumbprint);

            // Instantiate a base service management class
            baseApi = new BaseApi(subscription);
        }
Пример #3
0
        /// <summary>
        /// Performs the execution of the activity.
        /// </summary>
        /// <param name="context">The execution context under which the activity executes.</param>
        protected override void Execute(CodeActivityContext context)
        {
            var azureSubscription = new AzureSubscription(SettingsPath, SubscriptionId);

            var credentials = new CertificateCloudCredentials(
                SubscriptionId,
                new X509Certificate2(Convert.FromBase64String(azureSubscription.ManagementCertificate)));

            var tasks = VirtualMachines.Get(context).Select(
                async vm =>
                {
                    using (var client = new ComputeManagementClient(credentials))
                    {
                        switch (vm.Size)
                        {
                            case VirtualMachineSize.Stop:
                                await client.DeallocateVmAsync(vm.Name);
                                break;

                            case VirtualMachineSize.Small:
                            case VirtualMachineSize.ExtraSmall:
                            case VirtualMachineSize.Large:
                            case VirtualMachineSize.Medium:
                            case VirtualMachineSize.ExtraLarge:
                            case VirtualMachineSize.A5:
                            case VirtualMachineSize.A6:
                            case VirtualMachineSize.A7:
                            case VirtualMachineSize.A8:
                            case VirtualMachineSize.A9:
                                await client.ResizeVmAsync(vm.Name, vm.Size.GetEnumDescription());
                                break;

                            default:
                                throw new ArgumentOutOfRangeException(
                                    nameof(context),
                                    @"Unknown VM Size, this shouldn't happen, but the enumeration value isn't implemented in the acitivity switch");
                        }
                    }
                });

            Task.WhenAll(tasks);
        }
Пример #4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PSRecoveryServicesClient" /> class with
 /// required current subscription.
 /// </summary>
 /// <param name="azureSubscription">Azure Subscription</param>
 public PSRecoveryServicesClient(AzureProfile azureProfile, AzureSubscription azureSubscription)
 {
     this.Profile = azureProfile;
     this.recoveryServicesClient =
         AzureSession.ClientFactory.CreateClient <RecoveryServicesManagementClient>(azureProfile, azureSubscription, AzureEnvironment.Endpoint.ServiceManagement);
 }
Пример #5
0
        private bool TryGetTenantSubscription(IAccessToken accessToken,
                                              IAzureAccount account,
                                              IAzureEnvironment environment,
                                              string tenantId,
                                              string subscriptionId,
                                              string subscriptionName,
                                              out IAzureSubscription subscription,
                                              out IAzureTenant tenant)
        {
            using (var subscriptionClient = AzureSession.Instance.ClientFactory.CreateCustomArmClient <SubscriptionClient>(
                       environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager),
                       new TokenCredentials(accessToken.AccessToken) as ServiceClientCredentials,
                       AzureSession.Instance.ClientFactory.GetCustomHandlers()))
            {
                Subscription subscriptionFromServer = null;

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

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

                        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    = subscriptionFromServer.SubscriptionId,
                        Name  = subscriptionFromServer.DisplayName,
                        State = subscriptionFromServer.State.ToString()
                    };

                    subscription.SetAccount(accessToken.UserId);
                    subscription.SetEnvironment(environment.Name);
                    subscription.SetTenant(accessToken.TenantId);

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

                subscription = null;

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

                tenant = null;
                return(false);
            }
        }
Пример #6
0
        public void SavingProfileWorks()
        {
            string expected  = @"{
  ""DefaultContextKey"": ""Default"",
  ""EnvironmentTable"": {
    ""testCloud"": {
      ""Name"": ""testCloud"",
      ""OnPremise"": false,
      ""ServiceManagementUrl"": null,
      ""ResourceManagerUrl"": null,
      ""ManagementPortalUrl"": null,
      ""PublishSettingsFileUrl"": null,
      ""ActiveDirectoryAuthority"": ""http://contoso.com"",
      ""GalleryUrl"": null,
      ""GraphUrl"": null,
      ""ActiveDirectoryServiceEndpointResourceId"": null,
      ""StorageEndpointSuffix"": null,
      ""SqlDatabaseDnsSuffix"": null,
      ""TrafficManagerDnsSuffix"": null,
      ""AzureKeyVaultDnsSuffix"": null,
      ""AzureKeyVaultServiceEndpointResourceId"": null,
      ""GraphEndpointResourceId"": null,
      ""DataLakeEndpointResourceId"": null,
      ""AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix"": null,
      ""AzureDataLakeStoreFileSystemEndpointSuffix"": null,
      ""AdTenant"": null,
      ""VersionProfiles"": [],
      ""ExtendedProperties"": {}
    }
  },
  ""Contexts"": {
    ""Default"": {
      ""Account"": {
        ""Id"": ""*****@*****.**"",
        ""Credential"": null,
        ""Type"": ""User"",
        ""TenantMap"": {},
        ""ExtendedProperties"": {
          ""Tenants"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6""
        }
      },
      ""Tenant"": {
        ""Id"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6"",
        ""Directory"": ""contoso.com"",
        ""ExtendedProperties"": {}
      },
      ""Subscription"": {
        ""Id"": ""00000000-0000-0000-0000-000000000000"",
        ""Name"": ""Contoso Test Subscription"",
        ""State"": ""Enabled"",
        ""ExtendedProperties"": {
          ""Account"": ""*****@*****.**"",
          ""Tenants"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6"",
          ""Environment"": ""testCloud""
        }
      },
      ""Environment"": {
        ""Name"": ""testCloud"",
        ""OnPremise"": false,
        ""ServiceManagementUrl"": null,
        ""ResourceManagerUrl"": null,
        ""ManagementPortalUrl"": null,
        ""PublishSettingsFileUrl"": null,
        ""ActiveDirectoryAuthority"": ""http://contoso.com"",
        ""GalleryUrl"": null,
        ""GraphUrl"": null,
        ""ActiveDirectoryServiceEndpointResourceId"": null,
        ""StorageEndpointSuffix"": null,
        ""SqlDatabaseDnsSuffix"": null,
        ""TrafficManagerDnsSuffix"": null,
        ""AzureKeyVaultDnsSuffix"": null,
        ""AzureKeyVaultServiceEndpointResourceId"": null,
        ""GraphEndpointResourceId"": null,
        ""DataLakeEndpointResourceId"": null,
        ""AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix"": null,
        ""AzureDataLakeStoreFileSystemEndpointSuffix"": null,
        ""AdTenant"": null,
        ""VersionProfiles"": [],
        ""ExtendedProperties"": {}
      },
      ""VersionProfile"": null,
      ""TokenCache"": {
        ""CacheData"": ""AgAAAAAAAAA=""
      },
      ""ExtendedProperties"": {}
    }
  },
  ""ExtendedProperties"": {}
}";
            var    path      = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AzureSession.Instance.ARMProfileFile);
            var    dataStore = new MockDataStore();

            AzureSession.Instance.DataStore = dataStore;
            AzureRmProfile profile     = new AzureRmProfile(path);
            var            tenantId    = new Guid("3c0ff8a7-e8bb-40e8-ae66-271343379af6");
            var            environment = new AzureEnvironment
            {
                Name = "testCloud",
                ActiveDirectoryAuthority = "http://contoso.com"
            };
            var account = new AzureAccount
            {
                Id   = "*****@*****.**",
                Type = AzureAccount.AccountType.User,
            };

            account.SetTenants(tenantId.ToString());
            var sub = new AzureSubscription
            {
                Id    = new Guid().ToString(),
                Name  = "Contoso Test Subscription",
                State = "Enabled",
            };

            sub.SetAccount(account.Id);
            sub.SetEnvironment(environment.Name);
            sub.SetTenant(tenantId.ToString());
            var tenant = new AzureTenant
            {
                Id        = tenantId.ToString(),
                Directory = "contoso.com"
            };

            profile.DefaultContext = new AzureContext(sub, account, environment, tenant);
            profile.EnvironmentTable[environment.Name] = environment;
            profile.DefaultContext.TokenCache          = new AuthenticationStoreTokenCache(new AzureTokenCache {
                CacheData = new byte[] { 1, 2, 3, 4, 5, 6, 8, 9, 0 }
            });
            profile.Save();
            string actual = dataStore.ReadFileAsText(path).Substring(1).TrimEnd(new[] { '\0' });

            Assert.Equal(expected, actual);
        }
 /// <summary>
 /// Creates new ExpressRouteClient
 /// </summary>
 /// <param name="subscription">Subscription containing websites to manipulate</param>
 public ExpressRouteClient(AzureSubscription subscription)
     : this(CreateClient <ExpressRouteManagementClient>(subscription))
 {
 }
Пример #8
0
        /// <summary>
        /// Executes the set subscription cmdlet operation.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            IAzureSubscription subscription = null;

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

            IAzureEnvironment environment = ProfileClient.GetEnvironment(Environment, ServiceEndpoint, ResourceManagerEndpoint);

            if (environment == null)
            {
                var profileClient = new ProfileClient(Profile);
                environment = profileClient.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.SetEnvironment(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.SetAccount(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.GetAccount() == null)
                {
                    subscription.SetAccount(account.Id);
                }
            }

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

            if (!string.IsNullOrEmpty(CurrentStorageAccountName) || Context != null)
            {
                ProfileClient.GetAccount(subscription.GetAccount());
                if (Profile.Context != null && Profile.Context.Subscription != null &&
                    Profile.Context.Subscription.Id == subscription.Id)
                {
                    GeneralUtilities.ClearCurrentStorageAccount();
                }
                var context = new AzureContext(subscription, ProfileClient.GetAccount(subscription.GetAccount()), ProfileClient.GetEnvironmentOrDefault(subscription.GetEnvironment()));
                if (Context != null)
                {
                    context.SetCurrentStorageAccount(Context);
                }
                else
                {
                    var client = AzureSession.Instance.ClientFactory.CreateClient <StorageManagementClient>(context,
                                                                                                            AzureEnvironment.Endpoint.ServiceManagement);
                    var account = StorageUtilities.GenerateCloudStorageAccount(client, CurrentStorageAccountName);
                    context.SetCurrentStorageAccount(account.ToString(true));
                }
            }

            subscription = ProfileClient.AddOrSetSubscription(subscription);

            if (PassThru)
            {
                WriteObject(subscription);
            }
        }
Пример #9
0
        public void SetupAzureEnvironmentFromEnvironmentVariables(AzureModule mode)
        {
            TestEnvironment currentEnvironment = null;

            if (mode == AzureModule.AzureResourceManager)
            {
#if !NETSTANDARD
                currentEnvironment = new CSMTestEnvironmentFactory().GetTestEnvironment();
#else
                currentEnvironment = TestEnvironmentFactory.GetTestEnvironment();
#endif
            }
            else
            {
#if !NETSTANDARD
                currentEnvironment = new RDFETestEnvironmentFactory().GetTestEnvironment();
#else
                throw new NotSupportedException("RDFE environment is not supported in .Net Core");
#endif
            }

            if (currentEnvironment.UserName == null)
            {
                currentEnvironment.UserName = "******";
            }

            SetAuthenticationFactory(mode, currentEnvironment);

            AzureEnvironment environment = new AzureEnvironment {
                Name = testEnvironmentName
            };

            Debug.Assert(currentEnvironment != null);
            environment.ActiveDirectoryAuthority = currentEnvironment.Endpoints.AADAuthUri.AbsoluteUri;
            environment.GalleryUrl           = currentEnvironment.Endpoints.GalleryUri.AbsoluteUri;
            environment.ServiceManagementUrl = currentEnvironment.BaseUri.AbsoluteUri;
            environment.ResourceManagerUrl   = currentEnvironment.Endpoints.ResourceManagementUri.AbsoluteUri;
            environment.GraphUrl             = currentEnvironment.Endpoints.GraphUri.AbsoluteUri;
            environment.AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix = currentEnvironment.Endpoints.DataLakeAnalyticsJobAndCatalogServiceUri.OriginalString.Replace("https://", ""); // because it is just a sufix
            environment.AzureDataLakeStoreFileSystemEndpointSuffix        = currentEnvironment.Endpoints.DataLakeStoreServiceUri.OriginalString.Replace("https://", "");                  // because it is just a sufix
#if !NETSTANDARD
            if (!ProfileClient.Profile.EnvironmentTable.ContainsKey(testEnvironmentName))
            {
                ProfileClient.AddOrSetEnvironment(environment);
            }
#endif
            if (!AzureRmProfileProvider.Instance.GetProfile <AzureRmProfile>().EnvironmentTable.ContainsKey(testEnvironmentName))
            {
                AzureRmProfileProvider.Instance.GetProfile <AzureRmProfile>().EnvironmentTable[testEnvironmentName] = environment;
            }

            if (currentEnvironment.SubscriptionId != null)
            {
                testSubscription = new AzureSubscription()
                {
                    Id   = currentEnvironment.SubscriptionId,
                    Name = testSubscriptionName,
                };

                testSubscription.SetEnvironment(testEnvironmentName);
                testSubscription.SetAccount(currentEnvironment.UserName);
                testSubscription.SetDefault();
                testSubscription.SetStorageAccount(Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT"));

                testAccount = new AzureAccount()
                {
                    Id   = currentEnvironment.UserName,
                    Type = AzureAccount.AccountType.User,
                };

                testAccount.SetSubscriptions(currentEnvironment.SubscriptionId);
#if !NETSTANDARD
                ProfileClient.Profile.SubscriptionTable[testSubscription.GetId()] = testSubscription;
                ProfileClient.Profile.AccountTable[testAccount.Id] = testAccount;
                ProfileClient.SetSubscriptionAsDefault(testSubscription.Name, testSubscription.GetAccount());
#endif
                var testTenant = new AzureTenant()
                {
                    Id = Guid.NewGuid().ToString()
                };
                if (!string.IsNullOrEmpty(currentEnvironment.Tenant))
                {
                    Guid tenant;
                    if (Guid.TryParse(currentEnvironment.Tenant, out tenant))
                    {
                        testTenant.Id = currentEnvironment.Tenant;
                    }
                }
                AzureRmProfileProvider.Instance.Profile.DefaultContext = new AzureContext(testSubscription, testAccount, environment, testTenant);
            }
        }
Пример #10
0
 /// <summary>
 /// Creates new ExpressRouteClient
 /// </summary>
 /// <param name="subscription">Subscription containing websites to manipulate</param>
 /// <param name="profile">Azure Profile</param>
 public ExpressRouteClient(AzureSMProfile profile, AzureSubscription subscription)
     : this(CreateClient <ExpressRouteManagementClient>(profile, subscription))
 {
 }
Пример #11
0
 /// <summary>
 /// Initializes the adapter
 /// </summary>
 /// <param name="subscription"></param>
 /// <returns></returns>
 protected override AzureSqlDatabaseActivationAdapter InitModelAdapter(AzureSubscription subscription)
 {
     return(new AzureSqlDatabaseActivationAdapter(DefaultProfile.Context));
 }
 public LocationsApi(AzureSubscription Subscription)
     : base(Subscription)
 {
 }
        public AzureRmProfile Login(
            IAzureAccount account,
            IAzureEnvironment environment,
            string tenantId,
            string subscriptionId,
            string subscriptionName,
            SecureString password,
            bool skipValidation,
            Action <string> promptAction,
            string name = null,
            bool shouldPopulateContextList = true,
            int maxContextPopulation       = Profile.ConnectAzureRmAccountCommand.DefaultMaxContextPopulation)
        {
            IAzureSubscription newSubscription = null;
            IAzureTenant       newTenant       = null;
            string             promptBehavior  =
                (password == null &&
                 account.Type != AzureAccount.AccountType.AccessToken &&
                 account.Type != AzureAccount.AccountType.ManagedService &&
                 !account.IsPropertySet(AzureAccount.Property.CertificateThumbprint))
                ? ShowDialog.Always : ShowDialog.Never;

            SubscritpionClientCandidates.Reset();

            if (skipValidation)
            {
                if (string.IsNullOrEmpty(subscriptionId) || string.IsNullOrEmpty(tenantId))
                {
                    throw new PSInvalidOperationException(Resources.SubscriptionOrTenantMissing);
                }

                newSubscription = new AzureSubscription
                {
                    Id = subscriptionId
                };

                newSubscription.SetOrAppendProperty(AzureSubscription.Property.Tenants, tenantId);
                newSubscription.SetOrAppendProperty(AzureSubscription.Property.Account, account.Id);

                newTenant = new AzureTenant
                {
                    Id = tenantId
                };
            }
            else
            {
                // (tenant and subscription are present) OR
                // (tenant is present and subscription is not provided)
                if (!string.IsNullOrEmpty(tenantId))
                {
                    Guid tempGuid = Guid.Empty;
                    if (!Guid.TryParse(tenantId, out tempGuid))
                    {
                        var tenants     = ListAccountTenants(account, environment, password, promptBehavior, promptAction);
                        var homeTenants = tenants.FirstOrDefault(t => t.IsHome);
                        var tenant      = homeTenants ?? tenants.FirstOrDefault();
                        if (tenant == null || tenant.Id == null)
                        {
                            string baseMessage    = string.Format(ProfileMessages.TenantDomainNotFound, tenantId);
                            var    typeMessageMap = new Dictionary <string, string>
                            {
                                { AzureAccount.AccountType.ServicePrincipal, string.Format(ProfileMessages.ServicePrincipalTenantDomainNotFound, account.Id) },
                                { AzureAccount.AccountType.User, ProfileMessages.UserTenantDomainNotFound },
                                { AzureAccount.AccountType.ManagedService, ProfileMessages.MSITenantDomainNotFound }
                            };
                            string typeMessage = typeMessageMap.ContainsKey(account.Type) ? typeMessageMap[account.Type] : string.Empty;
                            throw new ArgumentNullException(string.Format("{0} {1}", baseMessage, typeMessage));
                        }

                        tenantId = tenant.Id;
                    }


                    var token = AcquireAccessToken(
                        account,
                        environment,
                        tenantId,
                        password,
                        promptBehavior,
                        promptAction);
                    if (TryGetTenantSubscription(
                            token,
                            account,
                            environment,
                            subscriptionId,
                            subscriptionName,
                            true,
                            out newSubscription,
                            out newTenant))
                    {
                        account.SetOrAppendProperty(AzureAccount.Property.Tenants, new[] { newTenant.Id.ToString() });
                    }
                }
                // (tenant is not provided and subscription is present) OR
                // (tenant is not provided and subscription is not provided)
                else
                {
                    var tenants = ListAccountTenants(account, environment, password, promptBehavior, promptAction)
                                  .Select(s => s.Id.ToString()).ToList();
                    account.SetProperty(AzureAccount.Property.Tenants, null);
                    string             accountId        = null;
                    IAzureTenant       tempTenant       = null;
                    IAzureSubscription tempSubscription = null;
                    foreach (var tenant in tenants)
                    {
                        tempTenant       = null;
                        tempSubscription = null;

                        IAccessToken token = null;

                        try
                        {
                            token = AcquireAccessToken(account, environment, tenant, password, ShowDialog.Auto, null);
                            if (accountId == null)
                            {
                                accountId = account.Id;
                                account.SetOrAppendProperty(AzureAccount.Property.Tenants, tenant);
                            }
                            else if (accountId.Equals(account.Id, StringComparison.OrdinalIgnoreCase))
                            {
                                account.SetOrAppendProperty(AzureAccount.Property.Tenants, tenant);
                            }
                            else
                            {   // if account ID is different from the first tenant account id we need to ignore current tenant
                                WriteWarningMessage(string.Format(
                                                        ProfileMessages.AccountIdMismatch,
                                                        account.Id,
                                                        tenant,
                                                        accountId));
                                account.Id = accountId;
                                token      = null;
                            }
                        }
                        catch (Exception e)
                        {
                            WriteWarningMessage(string.Format(ProfileMessages.UnableToAqcuireToken, tenant, e.Message));
                            WriteDebugMessage(string.Format(ProfileMessages.UnableToAqcuireToken, tenant, e.ToString()));
                        }

                        if (token != null &&
                            newTenant == null &&
                            TryGetTenantSubscription(token, account, environment, subscriptionId, subscriptionName, false, out tempSubscription, out tempTenant))
                        {
                            // If no subscription found for the given token/tenant,discard tempTenant value.
                            // Continue to look for matched subscripitons until one subscription retrived by its home tenant is found.
                            if (tempSubscription != null)
                            {
                                newSubscription = tempSubscription;
                                if (tempSubscription.GetTenant() == tempSubscription.GetHomeTenant())
                                {
                                    newTenant = tempTenant;
                                }
                            }
                        }
                    }
                    newSubscription = newSubscription ?? tempSubscription;
                    newTenant       = newTenant ??
                                      (newSubscription != null ? new AzureTenant()
                    {
                        Id = newSubscription.GetTenant()
                    } : tempTenant);
                }
            }

            shouldPopulateContextList &= _profile.DefaultContext?.Account == null;
            if (newSubscription == null)
            {
                if (subscriptionId != null)
                {
                    throw new PSInvalidOperationException(String.Format(ResourceMessages.SubscriptionIdNotFound, account.Id, subscriptionId));
                }
                else if (subscriptionName != null)
                {
                    throw new PSInvalidOperationException(String.Format(ResourceMessages.SubscriptionNameNotFound, account.Id, subscriptionName));
                }

                var newContext = new AzureContext(account, environment, newTenant);
                if (!_profile.TrySetDefaultContext(name, newContext))
                {
                    WriteWarningMessage(string.Format(ProfileMessages.CannotSetDefaultContext, newContext.ToString()));
                }
            }
            else
            {
                var newContext = new AzureContext(newSubscription, account, environment, newTenant);
                if (!_profile.TrySetDefaultContext(name, newContext))
                {
                    WriteWarningMessage(string.Format(ProfileMessages.CannotSetDefaultContext, newContext.ToString()));
                }

                if (!skipValidation && !newSubscription.State.Equals("Enabled", StringComparison.OrdinalIgnoreCase))
                {
                    WriteWarningMessage(string.Format(
                                            ProfileMessages.SelectedSubscriptionNotActive,
                                            newSubscription.State));
                }
            }

            _profile.DefaultContext.TokenCache = _cache;
            if (shouldPopulateContextList && maxContextPopulation != 0)
            {
                var defaultContext = _profile.DefaultContext;
                var subscriptions  = maxContextPopulation > 0 ? ListSubscriptions(tenantId).Take(maxContextPopulation) : ListSubscriptions(tenantId);

                foreach (var subscription in subscriptions)
                {
                    IAzureTenant tempTenant = new AzureTenant()
                    {
                        Id = subscription.GetProperty(AzureSubscription.Property.Tenants)
                    };

                    var tempContext = new AzureContext(subscription, account, environment, tempTenant);
                    tempContext.TokenCache = _cache;
                    string tempName = null;
                    if (!_profile.TryGetContextName(tempContext, out tempName))
                    {
                        WriteWarningMessage(string.Format(Resources.CannotGetContextName, subscription.Id));
                        continue;
                    }

                    if (!_profile.TrySetContext(tempName, tempContext))
                    {
                        WriteWarningMessage(string.Format(Resources.CannotCreateContext, subscription.Id));
                    }
                }

                _profile.TrySetDefaultContext(defaultContext);
                _profile.TryRemoveContext("Default");
            }

            return(_profile.ToProfile());
        }
        /// <summary>
        /// Provisions all the components in the <see cref="DevOpsFlexDbContext"/>.
        /// </summary>
        /// <param name="context">The database context that we want to provision components from.</param>
        /// <param name="subscriptionId">The subscription Id where we want to provision in.</param>
        /// <param name="settingsPath">The path to the settings file with the management certificate.</param>
        /// <returns>The async <see cref="Task"/> wrapper.</returns>
        public static async Task ProvisionAllAsync(this DevOpsFlexDbContext context, string subscriptionId, string settingsPath)
        {
            Contract.Requires(context != null);
            Contract.Requires(string.IsNullOrEmpty(subscriptionId));
            Contract.Requires(string.IsNullOrEmpty(settingsPath));

            var azureSubscription = new AzureSubscription(settingsPath, subscriptionId);
            var azureCert = new X509Certificate2(Convert.FromBase64String(azureSubscription.ManagementCertificate));

            using (var computeClient = new ComputeManagementClient(new CertificateCloudCredentials(subscriptionId, azureCert)))
            using (var networkClient = new NetworkManagementClient(new CertificateCloudCredentials(subscriptionId, azureCert)))
            using (var sbClient = new ServiceBusManagementClient(new CertificateCloudCredentials(subscriptionId, azureCert)))
            using (var sqlClient = new SqlManagementClient(new CertificateCloudCredentials(subscriptionId, azureCert)))
            using (var storageClient = new StorageManagementClient(new CertificateCloudCredentials(subscriptionId, azureCert)))
            using (var webSiteClient = new WebSiteManagementClient(new CertificateCloudCredentials(subscriptionId, azureCert)))
            {
                var tasks = new[]
                {
                    context.Components.OfType<AzureCloudService>().ToList().ProvisionAllAsync(computeClient),
                    context.Components.OfType<AzureCloudService>().ToList().ReserveAllIpsAsync(networkClient),
                    context.Components.OfType<AzureServiceBusNamespace>().ToList().ProvisionAllAsync(sbClient),
                    context.Components.OfType<SqlAzureDb>().ToList().ProvisionAllAsync(sqlClient),
                    context.Components.OfType<AzureStorageContainer>().ToList().ProvisionAllAsync(storageClient),
                    context.Components.OfType<AzureWebSite>().ToList().ProvisionAllAsync(webSiteClient)
                };

                await Task.WhenAll(tasks);
            }
        }
 public AzureContext(AzureSubscription subscription, AzureAccount account, AzureEnvironment environment)
 {
     Subscription = subscription;
     Account = account;
     Environment = environment;
 }
Пример #16
0
 public PSCacheClient(AzureSMProfile profile, AzureSubscription currentSubscription)
 {
     client = AzureSession.ClientFactory.CreateClient <ManagedCacheClient>(profile, currentSubscription, AzureEnvironment.Endpoint.ServiceManagement);
 }
Пример #17
0
        public static RestClient GetRestClient(AzureServicePrincipal servicePrincipal, AzureSubscription azureSubscription)
        {
            var credentials = GetAzureCredentials(servicePrincipal, azureSubscription);

            return(RestClient
                   .Configure()
                   .WithEnvironment(Microsoft.Azure.Management.ResourceManager.Fluent.AzureEnvironment.FromName(azureSubscription.AzureRegion))
                   .WithCredentials(credentials)
                   .Build());
        }
 public TrafficManagerClient(AzureSubscription subscription)
 {
     this.Client = AzureSession.ClientFactory.CreateClient <TrafficManagerManagementClient>(subscription, AzureEnvironment.Endpoint.ServiceManagement);
 }
 public LocationsApi(AzureSubscription Subscription)
     : base(Subscription)
 {
 }
Пример #20
0
        public static AzureCredentials GetAzureCredentials(AzureServicePrincipal servicePrincipal, AzureSubscription azureSubscription)
        {
            if (servicePrincipal == null)
            {
                throw new ArgumentNullException(nameof(servicePrincipal));
            }

            if (azureSubscription == null)
            {
                throw new ArgumentNullException(nameof(azureSubscription));
            }

            if (servicePrincipal.UseManagendIdentity)
            {
                return(new AzureCredentials(new MSILoginInformation(MSIResourceType.AppService), Microsoft.Azure.Management.ResourceManager.Fluent.AzureEnvironment.FromName(azureSubscription.AzureRegion)));
            }


            return(new AzureCredentials(servicePrincipal.ServicePrincipalLoginInformation,
                                        azureSubscription.Tenant, Microsoft.Azure.Management.ResourceManager.Fluent.AzureEnvironment.FromName(azureSubscription.AzureRegion)));
        }
        private void SetupAzureEnvironmentFromEnvironmentVariables(AzureModule mode)
        {
            TestEnvironment rdfeEnvironment    = new RDFETestEnvironmentFactory().GetTestEnvironment();
            TestEnvironment csmEnvironment     = new CSMTestEnvironmentFactory().GetTestEnvironment();
            TestEnvironment currentEnvironment = (mode == AzureModule.AzureResourceManager ? csmEnvironment : rdfeEnvironment);

            if (currentEnvironment.UserName == null)
            {
                currentEnvironment.UserName = "******";
            }

            SetAuthenticationFactory(mode, rdfeEnvironment, csmEnvironment);

            AzureEnvironment environment = new AzureEnvironment {
                Name = testEnvironmentName
            };

            Debug.Assert(currentEnvironment != null);
            environment.ActiveDirectoryAuthority = currentEnvironment.Endpoints.AADAuthUri.AbsoluteUri;
            environment.GalleryUrl = currentEnvironment.Endpoints.GalleryUri.AbsoluteUri;

            if (csmEnvironment != null)
            {
                environment.ResourceManagerUrl = csmEnvironment.BaseUri.AbsoluteUri;
            }

            if (rdfeEnvironment != null)
            {
                environment.ServiceManagementUrl = rdfeEnvironment.BaseUri.AbsoluteUri;
            }

            if (!ProfileClient.Profile.EnvironmentTable.ContainsKey(testEnvironmentName))
            {
                ProfileClient.AddOrSetEnvironment(environment);
            }

            if (currentEnvironment.SubscriptionId != null)
            {
                testSubscription = new AzureSubscription()
                {
                    Id   = currentEnvironment.SubscriptionId,
                    Name = testSubscriptionName,
                };
                testSubscription.SetEnvironment(testEnvironmentName);
                testSubscription.SetAccount(currentEnvironment.UserName);
                testSubscription.SetStorageAccount(Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT"));
                testSubscription.SetDefault();

                testAccount = new AzureAccount()
                {
                    Id   = currentEnvironment.UserName,
                    Type = AzureAccount.AccountType.User,
                };

                testAccount.SetSubscriptions(currentEnvironment.SubscriptionId);

                ProfileClient.Profile.SubscriptionTable[testSubscription.GetId()] = testSubscription;
                ProfileClient.Profile.AccountTable[testAccount.Id] = testAccount;
                ProfileClient.SetSubscriptionAsDefault(testSubscription.Name, testSubscription.GetAccount());
            }
        }
 public static IHDInsightSubscriptionCredentials GetSubscriptionCertificateCredentials(this IAzureHDInsightCommonCommandBase command,
                                                                                       AzureSubscription currentSubscription, AzureAccount azureAccount, AzureEnvironment environment)
 {
     return(new HDInsightCertificateCredential
     {
         SubscriptionId = currentSubscription.Id,
         Certificate = AzureSession.DataStore.GetCertificate(currentSubscription.Account),
         Endpoint = environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement),
     });
 }
Пример #23
0
 internal ResourceGroup(JObject resourceGroupJson, AzureEnvironment azureEnvironment, AzureSubscription azureSubscription)
 {
     _ResourceGroupJson = resourceGroupJson;
     _AzureEnvironment  = azureEnvironment;
     _AzureSubscription = azureSubscription;
 }
Пример #24
0
 /// <summary>
 /// Creation and initialization of the ModelAdapter object
 /// </summary>
 /// <param name="subscription">The AzureSubscription in which the current execution is performed</param>
 /// <returns>An initialized and ready to use ModelAdapter object</returns>
 protected override SqlAuditAdapter InitModelAdapter(AzureSubscription subscription)
 {
     return(new SqlAuditAdapter(DefaultProfile.Context));
 }
Пример #25
0
 public NetworkInterfaceIpConfiguration(AzureSubscription azureSubscription, JToken networkInterfaceIpConfiguration) : base(azureSubscription, networkInterfaceIpConfiguration)
 {
 }
Пример #26
0
 private static ClientType CreateClient <ClientType>(AzureSubscription subscription) where ClientType : ServiceClient <ClientType>
 {
     return(AzureSession.ClientFactory.CreateClient <ClientType>(subscription, AzureEnvironment.Endpoint.ServiceManagement));
 }
 /// <summary>
 /// Initializes the adapter
 /// </summary>
 /// <param name="subscription"></param>
 /// <returns></returns>
 protected override AzureSqlDatabaseActivationAdapter InitModelAdapter(AzureSubscription subscription)
 {
     return(new AzureSqlDatabaseActivationAdapter(Profile, subscription));
 }
Пример #28
0
        public void ProfileSerializeDeserializeWorks()
        {
            var dataStore = new MockDataStore();

            AzureSession.Instance.DataStore = dataStore;
            var profilePath    = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AzureSession.Instance.ARMProfileFile);
            var currentProfile = new AzureRmProfile(profilePath);
            var tenantId       = Guid.NewGuid().ToString();
            var environment    = new AzureEnvironment
            {
                Name = "testCloud",
                ActiveDirectoryAuthority = "http://contoso.com"
            };
            var account = new AzureAccount
            {
                Id   = "*****@*****.**",
                Type = AzureAccount.AccountType.User,
            };

            account.SetTenants(tenantId);
            var sub = new AzureSubscription
            {
                Id   = new Guid().ToString(),
                Name = "Contoso Test Subscription",
            };

            sub.SetAccount(account.Id);
            sub.SetEnvironment(environment.Name);
            sub.SetTenant(tenantId);
            var tenant = new AzureTenant
            {
                Id        = tenantId,
                Directory = "contoso.com"
            };

            currentProfile.DefaultContext = new AzureContext(sub, account, environment, tenant);
            currentProfile.EnvironmentTable[environment.Name] = environment;
            currentProfile.DefaultContext.TokenCache          = new AzureTokenCache {
                CacheData = new byte[] { 1, 2, 3, 4, 5, 6, 8, 9, 0 }
            };

            AzureRmProfile deserializedProfile;
            // Round-trip the exception: Serialize and de-serialize with a BinaryFormatter
            BinaryFormatter bf = new BinaryFormatter();

            using (MemoryStream ms = new MemoryStream())
            {
                // "Save" object state
                bf.Serialize(ms, currentProfile);

                // Re-use the same stream for de-serialization
                ms.Seek(0, 0);

                // Replace the original exception with de-serialized one
                deserializedProfile = (AzureRmProfile)bf.Deserialize(ms);
            }
            Assert.NotNull(deserializedProfile);
            var jCurrentProfile      = currentProfile.ToString();
            var jDeserializedProfile = deserializedProfile.ToString();

            Assert.Equal(jCurrentProfile, jDeserializedProfile);
        }
Пример #29
0
        public void NewAzureVMProcess()
        {
            AzureSubscription   currentSubscription = CurrentContext.Subscription;
            CloudStorageAccount currentStorage      = null;

            try
            {
                currentStorage = currentSubscription.GetCloudStorageAccount();
            }
            catch (Exception ex) // couldn't access
            {
                throw new ArgumentException(Resources.CurrentStorageAccountIsNotAccessible, ex);
            }
            if (currentStorage == null) // not set
            {
                throw new ArgumentException(Resources.CurrentStorageAccountIsNotSet);
            }

            bool serviceExists = DoesCloudServiceExist(this.ServiceName);

            if (!string.IsNullOrEmpty(this.Location))
            {
                if (serviceExists)
                {
                    throw new ApplicationException(Resources.ServiceExistsLocationCanNotBeSpecified);
                }
            }

            if (!string.IsNullOrEmpty(this.AffinityGroup))
            {
                if (serviceExists)
                {
                    throw new ApplicationException(Resources.ServiceExistsAffinityGroupCanNotBeSpecified);
                }
            }

            if (!string.IsNullOrEmpty(this.ReverseDnsFqdn))
            {
                if (serviceExists)
                {
                    throw new ApplicationException(Resources.ServiceExistsReverseDnsFqdnCanNotBeSpecified);
                }
            }

            if (!serviceExists)
            {
                try
                {
                    //Implicitly created hosted service2012-05-07 23:12

                    // Create the Cloud Service when
                    // Location or Affinity Group is Specified
                    // or VNET is specified and the service doesn't exist
                    var parameter = new HostedServiceCreateParameters
                    {
                        AffinityGroup  = this.AffinityGroup,
                        Location       = this.Location,
                        ServiceName    = this.ServiceName,
                        Description    = String.Format("Implicitly created hosted service{0}", DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd HH:mm")),
                        Label          = this.ServiceName,
                        ReverseDnsFqdn = this.ReverseDnsFqdn
                    };

                    ExecuteClientActionNewSM(
                        parameter,
                        CommandRuntime + Resources.QuickVMCreateCloudService,
                        () => this.ComputeClient.HostedServices.Create(parameter));
                }
                catch (CloudException ex)
                {
                    this.WriteExceptionDetails(ex);
                    return;
                }
            }

            if (ParameterSetName.Equals(WindowsParamSet, StringComparison.OrdinalIgnoreCase))
            {
                if (WinRMCertificate != null)
                {
                    if (!CertUtilsNewSM.HasExportablePrivateKey(WinRMCertificate))
                    {
                        throw new ArgumentException(Resources.WinRMCertificateDoesNotHaveExportablePrivateKey);
                    }

                    var operationDescription = string.Format(Resources.QuickVMUploadingWinRMCertificate, CommandRuntime, WinRMCertificate.Thumbprint);
                    var parameters           = CertUtilsNewSM.Create(WinRMCertificate);

                    ExecuteClientActionNewSM(
                        null,
                        operationDescription,
                        () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, parameters),
                        (s, r) => ContextFactory <OperationStatusResponse, ManagementOperationContext>(r, s));
                }

                if (X509Certificates != null)
                {
                    var certificateFilesWithThumbprint = from c in X509Certificates
                                                         select new
                    {
                        c.Thumbprint,
                        CertificateFile = CertUtilsNewSM.Create(c, this.NoExportPrivateKey.IsPresent)
                    };
                    foreach (var current in certificateFilesWithThumbprint.ToList())
                    {
                        var operationDescription = string.Format(Resources.QuickVMUploadingCertificate, CommandRuntime, current.Thumbprint);
                        ExecuteClientActionNewSM(
                            null,
                            operationDescription,
                            () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, current.CertificateFile),
                            (s, r) => ContextFactory <OperationStatusResponse, ManagementOperationContext>(r, s));
                    }
                }
            }

            var vm = CreatePersistenVMRole(currentStorage);

            try
            {
                if (CurrentDeploymentNewSM == null)
                {
                    // If the current deployment doesn't exist set it create it
                    var parameters = new VirtualMachineCreateDeploymentParameters
                    {
                        DeploymentSlot     = DeploymentSlot.Production,
                        Name               = this.ServiceName,
                        Label              = this.ServiceName,
                        VirtualNetworkName = this.VNetName,
                        Roles              = { vm },
                        ReservedIPName     = this.ReservedIPName,
                        DnsSettings        = this.DnsSettings == null ? null : new Microsoft.WindowsAzure.Management.Compute.Models.DnsSettings
                        {
                            DnsServers = (from dns in this.DnsSettings
                                          select new Management.Compute.Models.DnsServer
                            {
                                Name = dns.Name,
                                Address = dns.Address
                            }).ToList()
                        }
                    };

                    ExecuteClientActionNewSM(
                        parameters,
                        string.Format(Resources.QuickVMCreateDeploymentWithVM, CommandRuntime, vm.RoleName),
                        () => this.ComputeClient.VirtualMachines.CreateDeployment(this.ServiceName, parameters));
                }
                else
                {
                    if (!string.IsNullOrEmpty(VNetName) || DnsSettings != null)
                    {
                        WriteWarning(Resources.VNetNameOrDnsSettingsCanOnlyBeSpecifiedOnNewDeployments);
                    }

                    // Only create the VM when a new VM was added and it was not created during the deployment phase.
                    ExecuteClientActionNewSM(
                        vm,
                        string.Format(Resources.QuickVMCreateVM, CommandRuntime, vm.RoleName),
                        () => this.ComputeClient.VirtualMachines.Create(
                            this.ServiceName,
                            this.ServiceName,
                            new VirtualMachineCreateParameters
                    {
                        AvailabilitySetName         = vm.AvailabilitySetName,
                        OSVirtualHardDisk           = vm.OSVirtualHardDisk,
                        DataVirtualHardDisks        = vm.DataVirtualHardDisks,
                        RoleName                    = vm.RoleName,
                        RoleSize                    = vm.RoleSize,
                        VMImageName                 = vm.VMImageName,
                        MediaLocation               = vm.MediaLocation,
                        ProvisionGuestAgent         = vm.ProvisionGuestAgent,
                        ResourceExtensionReferences = vm.ResourceExtensionReferences,
                        ConfigurationSets           = vm.ConfigurationSets
                    }));
                }

                if (WaitForBoot.IsPresent)
                {
                    WaitForRoleToBoot(vm.RoleName);
                }
            }
            catch (CloudException ex)
            {
                if (ex.Response.StatusCode == HttpStatusCode.NotFound)
                {
                    throw new Exception(Resources.ServiceDoesNotExistSpecifyLocationOrAffinityGroup);
                }

                this.WriteExceptionDetails(ex);
            }
        }
Пример #30
0
        public AzureRmProfile Login(
            IAzureAccount account,
            IAzureEnvironment environment,
            string tenantId,
            string subscriptionId,
            string subscriptionName,
            SecureString password,
            bool skipValidation,
            Action <string> promptAction,
            string name = null)
        {
            IAzureSubscription newSubscription = null;
            IAzureTenant       newTenant       = null;
            string             promptBehavior  =
                (password == null &&
                 account.Type != AzureAccount.AccountType.AccessToken &&
                 !account.IsPropertySet(AzureAccount.Property.CertificateThumbprint))
                ? ShowDialog.Always : ShowDialog.Never;

            if (skipValidation)
            {
                if (string.IsNullOrEmpty(subscriptionId) || string.IsNullOrEmpty(tenantId))
                {
                    throw new PSInvalidOperationException(Resources.SubscriptionOrTenantMissing);
                }

                newSubscription = new AzureSubscription
                {
                    Id = subscriptionId
                };

                newSubscription.SetOrAppendProperty(AzureSubscription.Property.Tenants, tenantId);
                newSubscription.SetOrAppendProperty(AzureSubscription.Property.Account, account.Id);

                newTenant = new AzureTenant
                {
                    Id = tenantId
                };
            }

            else
            {
                // (tenant and subscription are present) OR
                // (tenant is present and subscription is not provided)
                if (!string.IsNullOrEmpty(tenantId))
                {
                    var token = AcquireAccessToken(
                        account,
                        environment,
                        tenantId,
                        password,
                        promptBehavior,
                        promptAction);
                    if (TryGetTenantSubscription(
                            token,
                            account,
                            environment,
                            tenantId,
                            subscriptionId,
                            subscriptionName,
                            out newSubscription,
                            out newTenant))
                    {
                        account.SetOrAppendProperty(AzureAccount.Property.Tenants, new[] { newTenant.Id.ToString() });
                    }
                }
                // (tenant is not provided and subscription is present) OR
                // (tenant is not provided and subscription is not provided)
                else
                {
                    var tenants = ListAccountTenants(account, environment, password, promptBehavior, promptAction)
                                  .Select(s => s.Id.ToString()).ToList();
                    account.SetProperty(AzureAccount.Property.Tenants, null);
                    string accountId = null;

                    foreach (var tenant in tenants)
                    {
                        IAzureTenant       tempTenant;
                        IAzureSubscription tempSubscription;

                        IAccessToken token = null;

                        try
                        {
                            token = AcquireAccessToken(account, environment, tenant, password, ShowDialog.Auto, null);
                            if (accountId == null)
                            {
                                accountId = account.Id;
                                account.SetOrAppendProperty(AzureAccount.Property.Tenants, tenant);
                            }
                            else if (accountId.Equals(account.Id, StringComparison.OrdinalIgnoreCase))
                            {
                                account.SetOrAppendProperty(AzureAccount.Property.Tenants, tenant);
                            }
                            else
                            {   // if account ID is different from the first tenant account id we need to ignore current tenant
                                WriteWarningMessage(string.Format(
                                                        ProfileMessages.AccountIdMismatch,
                                                        account.Id,
                                                        tenant,
                                                        accountId));
                                account.Id = accountId;
                                token      = null;
                            }
                        }
                        catch
                        {
                            WriteWarningMessage(string.Format(ProfileMessages.UnableToAqcuireToken, tenant));
                        }

                        if (token != null &&
                            newTenant == null &&
                            TryGetTenantSubscription(token, account, environment, tenant, subscriptionId, subscriptionName, out tempSubscription, out tempTenant))
                        {
                            // If no subscription found for the given token/tenant
                            // discard tempTenant value unless current token/tenant is the last one.
                            if (tempSubscription != null || tenant.Equals(tenants[tenants.Count - 1]))
                            {
                                newTenant       = tempTenant;
                                newSubscription = tempSubscription;
                            }
                        }
                    }
                }
            }

            if (newSubscription == null)
            {
                if (subscriptionId != null)
                {
                    throw new PSInvalidOperationException(String.Format(ResourceMessages.SubscriptionIdNotFound, account.Id, subscriptionId));
                }
                else if (subscriptionName != null)
                {
                    throw new PSInvalidOperationException(String.Format(ResourceMessages.SubscriptionNameNotFound, account.Id, subscriptionName));
                }

                var newContext = new AzureContext(account, environment, newTenant);
                if (!_profile.TrySetDefaultContext(name, newContext))
                {
                    WriteWarningMessage(string.Format(ProfileMessages.CannotSetDefaultContext, newContext.ToString()));
                }
            }
            else
            {
                var newContext = new AzureContext(newSubscription, account, environment, newTenant);
                if (!_profile.TrySetDefaultContext(name, newContext))
                {
                    WriteWarningMessage(string.Format(ProfileMessages.CannotSetDefaultContext, newContext.ToString()));
                }

                if (!skipValidation && !newSubscription.State.Equals("Enabled", StringComparison.OrdinalIgnoreCase))
                {
                    WriteWarningMessage(string.Format(
                                            ProfileMessages.SelectedSubscriptionNotActive,
                                            newSubscription.State));
                }
            }

            _profile.DefaultContext.TokenCache = _cache;

            return(_profile.ToProfile());
        }
Пример #31
0
 /// <summary>
 /// Initializes the adapter
 /// </summary>
 /// <param name="subscription"></param>
 /// <returns></returns>
 protected override AzureSqlElasticPoolRecommendationAdapter InitModelAdapter(AzureSubscription subscription)
 {
     return(new AzureSqlElasticPoolRecommendationAdapter(DefaultProfile.Context));
 }
        private void SetupAzureEnvironmentFromEnvironmentVariables(AzureModule mode)
        {
            TestEnvironment rdfeEnvironment    = new RDFETestEnvironmentFactory().GetTestEnvironment();
            TestEnvironment csmEnvironment     = new CSMTestEnvironmentFactory().GetTestEnvironment();
            TestEnvironment currentEnvironment = (mode == AzureModule.AzureResourceManager ? csmEnvironment : rdfeEnvironment);

            if (currentEnvironment.UserName == null)
            {
                currentEnvironment.UserName = "******";
            }

            SetAuthenticationFactory(mode, rdfeEnvironment, csmEnvironment);

            AzureEnvironment environment = new AzureEnvironment {
                Name = testEnvironmentName
            };

            Debug.Assert(currentEnvironment != null);
            environment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectory] = currentEnvironment.Endpoints.AADAuthUri.AbsoluteUri;
            environment.Endpoints[AzureEnvironment.Endpoint.Gallery]         = currentEnvironment.Endpoints.GalleryUri.AbsoluteUri;

            if (csmEnvironment != null)
            {
                environment.Endpoints[AzureEnvironment.Endpoint.ResourceManager] = csmEnvironment.BaseUri.AbsoluteUri;
            }

            if (rdfeEnvironment != null)
            {
                environment.Endpoints[AzureEnvironment.Endpoint.ServiceManagement] = rdfeEnvironment.BaseUri.AbsoluteUri;
            }

            if (!ProfileClient.Profile.Environments.ContainsKey(testEnvironmentName))
            {
                ProfileClient.AddOrSetEnvironment(environment);
            }

            if (currentEnvironment.SubscriptionId != null)
            {
                testSubscription = new AzureSubscription()
                {
                    Id          = new Guid(currentEnvironment.SubscriptionId),
                    Name        = testSubscriptionName,
                    Environment = testEnvironmentName,
                    Account     = currentEnvironment.UserName,
                    Properties  = new Dictionary <AzureSubscription.Property, string>
                    {
                        { AzureSubscription.Property.Default, "True" },
                        {
                            AzureSubscription.Property.StorageAccount,
                            Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT")
                        },
                    }
                };

                testAccount = new AzureAccount()
                {
                    Id         = currentEnvironment.UserName,
                    Type       = AzureAccount.AccountType.User,
                    Properties = new Dictionary <AzureAccount.Property, string>
                    {
                        { AzureAccount.Property.Subscriptions, currentEnvironment.SubscriptionId },
                    }
                };

                ProfileClient.Profile.Subscriptions[testSubscription.Id] = testSubscription;
                ProfileClient.Profile.Accounts[testAccount.Id]           = testAccount;
                ProfileClient.SetSubscriptionAsDefault(testSubscription.Name, testSubscription.Account);
            }
        }
 public NetworkClient(AzureSubscription subscription, ICommandRuntime commandRuntime)
     : this(CreateClient <NetworkManagementClient>(subscription),
            CreateClient <ManagementClient>(subscription),
            commandRuntime)
 {
 }
 /// <summary>
 /// Constructs a database backup adapter
 /// </summary>
 /// <param name="profile">The current azure profile</param>
 /// <param name="subscription">The current azure subscription</param>
 public AzureSqlDatabaseBackupAdapter(AzureProfile Profile, AzureSubscription subscription)
 {
     this.Profile       = Profile;
     this._subscription = subscription;
     Communicator       = new AzureSqlDatabaseBackupCommunicator(Profile, subscription);
 }
 public SqlDataMaskingAdapter(AzureProfile profile, AzureSubscription subscription)
 {
     Profile      = profile;
     Subscription = subscription;
     Communicator = new DataMaskingEndpointsCommunicator(profile, subscription);
 }
Пример #36
0
        public async Task BindArmResources(AzureContext azureContext, AzureSubscription azureSubscription, TargetSettings targetSettings)
        {
            treeAzureARM.Nodes.Clear();

            try
            {
                if (azureSubscription != null)
                {
                    await azureSubscription.BindArmResources(targetSettings);

                    if (azureSubscription != null)
                    {
                        TreeNode subscriptionNodeARM = new TreeNode(azureSubscription.Name);
                        subscriptionNodeARM.ImageKey         = "Subscription";
                        subscriptionNodeARM.SelectedImageKey = "Subscription";
                        treeAzureARM.Nodes.Add(subscriptionNodeARM);
                        subscriptionNodeARM.Expand();

                        foreach (MigrationTarget.NetworkSecurityGroup targetNetworkSecurityGroup in azureSubscription.ArmTargetNetworkSecurityGroups)
                        {
                            TreeNode networkSecurityGroupParentNode = GetResourceGroupTreeNode(subscriptionNodeARM, ((Azure.Arm.NetworkSecurityGroup)targetNetworkSecurityGroup.SourceNetworkSecurityGroup).ResourceGroup);

                            TreeNode tnNetworkSecurityGroup = new TreeNode(targetNetworkSecurityGroup.SourceName);
                            tnNetworkSecurityGroup.Name             = targetNetworkSecurityGroup.SourceName;
                            tnNetworkSecurityGroup.Tag              = targetNetworkSecurityGroup;
                            tnNetworkSecurityGroup.ImageKey         = targetNetworkSecurityGroup.ImageKey;
                            tnNetworkSecurityGroup.SelectedImageKey = targetNetworkSecurityGroup.ImageKey;
                            networkSecurityGroupParentNode.Nodes.Add(tnNetworkSecurityGroup);
                        }

                        foreach (MigrationTarget.PublicIp targetPublicIP in azureSubscription.ArmTargetPublicIPs)
                        {
                            TreeNode publicIpParentNode = GetResourceGroupTreeNode(subscriptionNodeARM, ((Azure.Arm.PublicIP)targetPublicIP.Source).ResourceGroup);;

                            TreeNode tnPublicIP = new TreeNode(targetPublicIP.SourceName);
                            tnPublicIP.Name             = targetPublicIP.SourceName;
                            tnPublicIP.Tag              = targetPublicIP;
                            tnPublicIP.ImageKey         = targetPublicIP.ImageKey;
                            tnPublicIP.SelectedImageKey = targetPublicIP.ImageKey;
                            publicIpParentNode.Nodes.Add(tnPublicIP);
                        }

                        foreach (MigrationTarget.RouteTable targetRouteTable in azureSubscription.ArmTargetRouteTables)
                        {
                            TreeNode routeTableParentNode = GetResourceGroupTreeNode(subscriptionNodeARM, ((Azure.Arm.RouteTable)targetRouteTable.Source).ResourceGroup);

                            TreeNode tnRouteTable = new TreeNode(targetRouteTable.SourceName);
                            tnRouteTable.Name             = targetRouteTable.SourceName;
                            tnRouteTable.Tag              = targetRouteTable;
                            tnRouteTable.ImageKey         = targetRouteTable.ImageKey;
                            tnRouteTable.SelectedImageKey = targetRouteTable.ImageKey;
                            routeTableParentNode.Nodes.Add(tnRouteTable);
                        }

                        foreach (MigrationTarget.VirtualNetwork targetVirtualNetwork in azureSubscription.ArmTargetVirtualNetworks)
                        {
                            TreeNode virtualNetworkParentNode = GetResourceGroupTreeNode(subscriptionNodeARM, ((Azure.Arm.VirtualNetwork)targetVirtualNetwork.SourceVirtualNetwork).ResourceGroup);

                            TreeNode tnVirtualNetwork = new TreeNode(targetVirtualNetwork.SourceName);
                            tnVirtualNetwork.Name             = targetVirtualNetwork.SourceName;
                            tnVirtualNetwork.Tag              = targetVirtualNetwork;
                            tnVirtualNetwork.ImageKey         = targetVirtualNetwork.ImageKey;
                            tnVirtualNetwork.SelectedImageKey = targetVirtualNetwork.ImageKey;
                            virtualNetworkParentNode.Nodes.Add(tnVirtualNetwork);
                        }

                        foreach (MigrationTarget.VirtualNetworkGateway targetVirtualNetworkGateway in azureSubscription.ArmTargetVirtualNetworkGateways)
                        {
                            TreeNode virtualNetworkGatewayParentNode = GetResourceGroupTreeNode(subscriptionNodeARM, ((Azure.Arm.VirtualNetworkGateway)targetVirtualNetworkGateway.SourceVirtualNetworkGateway).ResourceGroup);

                            TreeNode tnVirtualNetworkGateway = new TreeNode(targetVirtualNetworkGateway.SourceName);
                            tnVirtualNetworkGateway.Name             = targetVirtualNetworkGateway.SourceName;
                            tnVirtualNetworkGateway.Tag              = targetVirtualNetworkGateway;
                            tnVirtualNetworkGateway.ImageKey         = targetVirtualNetworkGateway.ImageKey;
                            tnVirtualNetworkGateway.SelectedImageKey = targetVirtualNetworkGateway.ImageKey;
                            virtualNetworkGatewayParentNode.Nodes.Add(tnVirtualNetworkGateway);
                        }

                        foreach (MigrationTarget.LocalNetworkGateway targetLocalNetworkGateway in azureSubscription.ArmTargetLocalNetworkGateways)
                        {
                            TreeNode localNetworkGatewayParentNode = GetResourceGroupTreeNode(subscriptionNodeARM, ((Azure.Arm.LocalNetworkGateway)targetLocalNetworkGateway.SourceLocalNetworkGateway).ResourceGroup);

                            TreeNode tnLocalNetworkGateway = new TreeNode(targetLocalNetworkGateway.SourceName);
                            tnLocalNetworkGateway.Name             = targetLocalNetworkGateway.SourceName;
                            tnLocalNetworkGateway.Tag              = targetLocalNetworkGateway;
                            tnLocalNetworkGateway.ImageKey         = targetLocalNetworkGateway.ImageKey;
                            tnLocalNetworkGateway.SelectedImageKey = targetLocalNetworkGateway.ImageKey;
                            localNetworkGatewayParentNode.Nodes.Add(tnLocalNetworkGateway);
                        }

                        foreach (MigrationTarget.VirtualNetworkGatewayConnection targetConnection in azureSubscription.ArmTargetConnections)
                        {
                            TreeNode connectionParentNode = GetResourceGroupTreeNode(subscriptionNodeARM, ((Azure.Arm.VirtualNetworkGatewayConnection)targetConnection.SourceConnection).ResourceGroup);

                            TreeNode tnConnection = new TreeNode(targetConnection.SourceName);
                            tnConnection.Name             = targetConnection.SourceName;
                            tnConnection.Tag              = targetConnection;
                            tnConnection.ImageKey         = targetConnection.ImageKey;
                            tnConnection.SelectedImageKey = targetConnection.ImageKey;
                            connectionParentNode.Nodes.Add(tnConnection);
                        }

                        foreach (MigrationTarget.StorageAccount targetStorageAccount in azureSubscription.ArmTargetStorageAccounts)
                        {
                            TreeNode storageAccountParentNode = GetResourceGroupTreeNode(subscriptionNodeARM, ((Azure.Arm.StorageAccount)targetStorageAccount.SourceAccount).ResourceGroup);

                            TreeNode tnStorageAccount = new TreeNode(targetStorageAccount.SourceName);
                            tnStorageAccount.Name             = targetStorageAccount.SourceName;
                            tnStorageAccount.Tag              = targetStorageAccount;
                            tnStorageAccount.ImageKey         = targetStorageAccount.ImageKey;
                            tnStorageAccount.SelectedImageKey = targetStorageAccount.ImageKey;
                            storageAccountParentNode.Nodes.Add(tnStorageAccount);
                        }

                        foreach (MigrationTarget.Disk targetManagedDisk in azureSubscription.ArmTargetManagedDisks)
                        {
                            Azure.Arm.ManagedDisk armManagedDisk = (Azure.Arm.ManagedDisk)targetManagedDisk.SourceDisk;
                            TreeNode managedDiskParentNode       = GetResourceGroupTreeNode(subscriptionNodeARM, armManagedDisk.ResourceGroup);

                            TreeNode tnDisk = new TreeNode(targetManagedDisk.SourceName);
                            tnDisk.Name             = targetManagedDisk.SourceName;
                            tnDisk.Tag              = targetManagedDisk;
                            tnDisk.ImageKey         = targetManagedDisk.ImageKey;
                            tnDisk.SelectedImageKey = targetManagedDisk.ImageKey;
                            managedDiskParentNode.Nodes.Add(tnDisk);
                        }

                        foreach (MigrationTarget.AvailabilitySet targetAvailabilitySet in azureSubscription.ArmTargetAvailabilitySets)
                        {
                            TreeNode availabilitySetParentNode = GetResourceGroupTreeNode(subscriptionNodeARM, ((Azure.Arm.AvailabilitySet)targetAvailabilitySet.SourceAvailabilitySet).ResourceGroup);

                            TreeNode tnAvailabilitySet = new TreeNode(targetAvailabilitySet.SourceName);
                            tnAvailabilitySet.Name             = targetAvailabilitySet.SourceName;
                            tnAvailabilitySet.Tag              = targetAvailabilitySet;
                            tnAvailabilitySet.ImageKey         = targetAvailabilitySet.ImageKey;
                            tnAvailabilitySet.SelectedImageKey = targetAvailabilitySet.ImageKey;
                            availabilitySetParentNode.Nodes.Add(tnAvailabilitySet);
                        }

                        foreach (MigrationTarget.NetworkInterface targetNetworkInterface in azureSubscription.ArmTargetNetworkInterfaces)
                        {
                            TreeNode tnResourceGroup = GetResourceGroupTreeNode(subscriptionNodeARM, ((Azure.Arm.NetworkInterface)targetNetworkInterface.SourceNetworkInterface).ResourceGroup);

                            TreeNode txNetworkInterface = new TreeNode(targetNetworkInterface.SourceName);
                            txNetworkInterface.Name             = targetNetworkInterface.SourceName;
                            txNetworkInterface.Tag              = targetNetworkInterface;
                            txNetworkInterface.ImageKey         = targetNetworkInterface.ImageKey;
                            txNetworkInterface.SelectedImageKey = targetNetworkInterface.ImageKey;
                            tnResourceGroup.Nodes.Add(txNetworkInterface);
                        }

                        foreach (MigrationTarget.VirtualMachine targetVirtualMachine in azureSubscription.ArmTargetVirtualMachines)
                        {
                            TreeNode tnResourceGroup = GetResourceGroupTreeNode(subscriptionNodeARM, ((Azure.Arm.VirtualMachine)targetVirtualMachine.Source).ResourceGroup);

                            TreeNode tnVirtualMachine = new TreeNode(targetVirtualMachine.SourceName);
                            tnVirtualMachine.Name             = targetVirtualMachine.SourceName;
                            tnVirtualMachine.Tag              = targetVirtualMachine;
                            tnVirtualMachine.ImageKey         = targetVirtualMachine.ImageKey;
                            tnVirtualMachine.SelectedImageKey = targetVirtualMachine.ImageKey;
                            tnResourceGroup.Nodes.Add(tnVirtualMachine);
                        }

                        foreach (MigrationTarget.LoadBalancer targetLoadBalancer in azureSubscription.ArmTargetLoadBalancers)
                        {
                            TreeNode networkSecurityGroupParentNode = GetResourceGroupTreeNode(subscriptionNodeARM, ((Azure.Arm.LoadBalancer)targetLoadBalancer.Source).ResourceGroup);

                            TreeNode tnNetworkSecurityGroup = new TreeNode(targetLoadBalancer.SourceName);
                            tnNetworkSecurityGroup.Name             = targetLoadBalancer.SourceName;
                            tnNetworkSecurityGroup.Tag              = targetLoadBalancer;
                            tnNetworkSecurityGroup.ImageKey         = targetLoadBalancer.ImageKey;
                            tnNetworkSecurityGroup.SelectedImageKey = targetLoadBalancer.ImageKey;
                            networkSecurityGroupParentNode.Nodes.Add(tnNetworkSecurityGroup);
                        }

                        //foreach (MigrationTarget.VirtualMachineImage targetVirtualMachineImage in _AzureContextSource.AzureSubscription.ArmTargetVirtualMachineImages)
                        //{
                        //    TreeNode virtualMachineImageParentNode = GetResourceGroupTreeNode(subscriptionNodeARM, ((Azure.Arm.VirtualMachineImage)targetVirtualMachineImage.Source).ResourceGroup);

                        //    TreeNode tnVirtualMachineImage = new TreeNode(targetVirtualMachineImage.SourceName);
                        //    tnVirtualMachineImage.Name = targetVirtualMachineImage.SourceName;
                        //    tnVirtualMachineImage.Tag = targetVirtualMachineImage;
                        //    tnVirtualMachineImage.ImageKey = "VirtualMachineImage";
                        //    tnVirtualMachineImage.SelectedImageKey = "VirtualMachineImage";
                        //    virtualMachineImageParentNode.Nodes.Add(tnVirtualMachineImage);
                        //}

                        subscriptionNodeARM.Expand();
                        treeAzureARM.Sort();
                        treeAzureARM.Enabled = true;
                    }
                }
            }
            catch (Exception exc)
            {
                UnhandledExceptionDialog exceptionDialog = new UnhandledExceptionDialog(_LogProvider, exc);
                exceptionDialog.ShowDialog();
            }

            _StatusProvider.UpdateStatus("Ready");
        }
 public CloudServicesApi(AzureSubscription Subscription)
     : base(Subscription)
 {
 }