public static AzureEnvironment DetermineEnvironment()
        {
            if (_initialised)
            {
                return _environment;
            }

            if (HasLightBlueEnvironmentFlag())
            {
                SetAsLightBlue(
                    configurationPath: Environment.GetEnvironmentVariable("LightBlueConfigurationPath"),
                    serviceDefinitionPath: Environment.GetEnvironmentVariable("LightBlueServiceDefinitionPath"),
                    roleName: Environment.GetEnvironmentVariable("LightBlueRoleName"));

                return _environment;
            }

            _initialised = true;

            try
            {
                _environment = RoleEnvironment.IsEmulated
                    ? AzureEnvironment.Emulator
                    : AzureEnvironment.ActualAzure;
            }
            catch (InvalidOperationException)
            {
                _environment = AzureEnvironment.External;
            }

            return _environment;
        }
Exemplo n.º 2
0
 public EnvironmentDefinition(
     AzureEnvironment azureEnvironment,
     HostingType hostingType,
     StandaloneConfiguration standaloneConfiguration)
 {
     _azureEnvironment = azureEnvironment;
     _hostingType = hostingType;
     _standaloneConfiguration = standaloneConfiguration;
 }
        public static void SetAsLightBlue(
            string configurationPath,
            string serviceDefinitionPath,
            string roleName)
        {
            _initialised = true;
            _environment = AzureEnvironment.LightBlue;

            StandaloneConfiguration = new StandaloneConfiguration
            {
                ConfigurationPath = configurationPath,
                ServiceDefinitionPath = serviceDefinitionPath,
                RoleName = roleName
            };
        }
Exemplo n.º 4
0
        public static void SetAsExternal(AzureEnvironment azureEnvironment)
        {
            if (IsInitialised)
            {
                if (_context.AzureEnvironment == azureEnvironment)
                {
                    return;
                }

                var msg = string.Format(CultureInfo.InvariantCulture, "LightBlue has already been initialised for '{0}'. You cannot change the environment it is configured for.", _context.AzureEnvironment);
                throw new InvalidOperationException(msg);
            }

            _context = azureEnvironment == AzureEnvironment.LightBlue
                ? new ExternalLightBlueContext()
                : (ILightBlueContext)new ExternalAzureContext(azureEnvironment);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Returns a SharePoint ClientContext using Azure Active Directory App Only Authentication. This requires that you have a certificated created, and updated the key credentials key in the application manifest in the azure AD accordingly.
        /// </summary>
        /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param>
        /// <param name="clientId">The Azure AD Application Client ID</param>
        /// <param name="tenant">The Azure AD Tenant, e.g. mycompany.onmicrosoft.com</param>
        /// <param name="certificatePath">The path to the certificate (*.pfx) file on the file system</param>
        /// <param name="certificatePassword">Password to the certificate</param>
        /// <param name="environment">SharePoint environment being used</param>
        /// <returns>Client context object</returns>
        public ClientContext GetAzureADAppOnlyAuthenticatedContext(string siteUrl, string clientId, string tenant, string certificatePath, string certificatePassword, AzureEnvironment environment = AzureEnvironment.Production)
        {
            var certPassword = Utilities.EncryptionUtility.ToSecureString(certificatePassword);

            return(GetAzureADAppOnlyAuthenticatedContext(siteUrl, clientId, tenant, certificatePath, certPassword, environment));
        }
        private 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);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Returns a SharePoint ClientContext using Azure Active Directory authentication. This requires that you have a Azure AD Native Application registered. The user will be prompted for authentication.
        /// </summary>
        /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param>
        /// <param name="clientId">The Azure AD Native Application Client ID</param>
        /// <param name="redirectUri">The Azure AD Native Application Redirect Uri</param>
        /// <param name="tokenCache">Optional token cache. If not specified an in-memory token cache will be used</param>
        /// <param name="environment">SharePoint environment being used</param>
        /// <returns>Client context object</returns>
        public ClientContext GetAzureADNativeApplicationAuthenticatedContext(string siteUrl, string clientId, Uri redirectUri, TokenCache tokenCache = null, AzureEnvironment environment = AzureEnvironment.Production)
        {
            var clientContext = new ClientContext(siteUrl);

            _contextUrl      = siteUrl;
            _tokenCache      = tokenCache;
            _clientId        = clientId;
            _redirectUri     = redirectUri;
            _commonAuthority = String.Format("{0}/common", GetAzureADLoginEndPoint(environment));

            clientContext.ExecutingWebRequest += clientContext_NativeApplicationExecutingWebRequest;

            return(clientContext);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Creates a Dedicated Host Group.
        /// </summary>
        /// <param name="token">Auth token.</param>
        /// <param name="azureEnvironment">Azure cloud.</param>
        /// <param name="tenantId">Tenant ID.</param>
        /// <param name="subscriptionId">Subscription ID.</param>
        /// <param name="resourceGroup">Resource group.</param>
        /// <param name="dhgName">Dedicated Host group name.</param>
        /// <param name="azName">Availability zone.</param>
        /// <param name="platformFaultDomainCount">Fault domain count.</param>
        /// <param name="location">Location/region.</param>
        public async Task <AzureOperationResponse <DedicatedHostGroup> > CreateDedicatedHostGroup(
            string token,
            AzureEnvironment azureEnvironment,
            string tenantId,
            string subscriptionId,
            string resourceGroup,
            string dhgName,
            string azName,
            int platformFaultDomainCount,
            string location)
        {
            if (string.IsNullOrEmpty(token))
            {
                throw new ArgumentNullException(nameof(token));
            }

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

            if (string.IsNullOrEmpty(tenantId))
            {
                throw new ArgumentNullException(nameof(tenantId));
            }

            if (string.IsNullOrEmpty(subscriptionId))
            {
                throw new ArgumentException(nameof(subscriptionId));
            }

            if (string.IsNullOrEmpty(resourceGroup))
            {
                throw new ArgumentException(nameof(resourceGroup));
            }

            if (string.IsNullOrEmpty(dhgName))
            {
                throw new ArgumentException(nameof(dhgName));
            }

            if (string.IsNullOrEmpty(location))
            {
                throw new ArgumentException(nameof(location));
            }

            var azureCredentials = new AzureCredentials(
                new TokenCredentials(token),
                new TokenCredentials(token),
                tenantId,
                azureEnvironment);

            var newDedicatedHostGroup = new DedicatedHostGroup()
            {
                Location = location,
                PlatformFaultDomainCount = platformFaultDomainCount
            };

            if (!string.IsNullOrEmpty(azName))
            {
                newDedicatedHostGroup.Zones = new List <string> {
                    azName
                };
            }

            var dhgCreateRetryCount     = _config.DhgCreateRetryCount;
            var computeManagementClient = await _dhmComputeClient.GetComputeManagementClient(
                subscriptionId,
                azureCredentials,
                azureEnvironment);

            var response = new AzureOperationResponse <DedicatedHostGroup>();
            await Policy
            .Handle <CloudException>()
            .WaitAndRetryAsync(
                dhgCreateRetryCount,
                r => TimeSpan.FromSeconds(2 * r),
                (ex, ts, r) =>
                _logger.LogInformation(
                    $"Create host group {dhgName} failed. Attempt #{r}/{dhgCreateRetryCount}. Will try again in {ts.TotalSeconds} seconds. Exception={ex}"))
            .ExecuteAsync(async() =>
            {
                response = await computeManagementClient.DedicatedHostGroups.CreateOrUpdateWithHttpMessagesAsync(
                    resourceGroup,
                    dhgName,
                    newDedicatedHostGroup,
                    null,
                    default(CancellationToken));
            });

            return(response);
        }
Exemplo n.º 9
0
        private static readonly string APIVERSION = "2016-08-31-preview"; // "2015-06-01-preview";

        /// <summary>
        /// Creates the client to read data from the ratecard REST API. Uses user authentication for
        /// authentication. Opens a popup to enter user and password
        /// </summary>
        /// <param name="azureIdentity">the service credentials</param>
        /// <param name="environment">the azure environment</param>
        /// <param name="subscription">the subscription details</param>
        public RateCardClient(AzureIdentity azureIdentity, AzureEnvironment environment, Subscription subscription)
            : base(azureIdentity, environment, subscription)
        {
        }
Exemplo n.º 10
0
        /// <summary>
        /// Creates a Dedicated Host.
        /// </summary>
        /// <param name="token">Auth token.</param>
        /// <param name="azureEnvironment">Azure cloud.</param>
        /// <param name="tenantId">Tenant ID.</param>
        /// <param name="subscriptionId">Subscription ID.</param>
        /// <param name="resourceGroup">Resource group.</param>
        /// <param name="dhgName">Dedicated Host group name.</param>
        /// <param name="dhName">Dedicated Host name.</param>
        /// <param name="dhSku">Dedicated Host SKU</param>
        /// <param name="location">Azure region.</param>
        public async Task <AzureOperationResponse <DedicatedHost> > CreateDedicatedHost(
            string token,
            AzureEnvironment azureEnvironment,
            string tenantId,
            string subscriptionId,
            string resourceGroup,
            string dhgName,
            string dhName,
            string dhSku,
            string location)
        {
            if (string.IsNullOrEmpty(token))
            {
                throw new ArgumentNullException(nameof(token));
            }

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

            if (string.IsNullOrEmpty(tenantId))
            {
                throw new ArgumentNullException(nameof(tenantId));
            }

            if (string.IsNullOrEmpty(subscriptionId))
            {
                throw new ArgumentException(nameof(subscriptionId));
            }

            if (string.IsNullOrEmpty(resourceGroup))
            {
                throw new ArgumentException(nameof(resourceGroup));
            }

            if (string.IsNullOrEmpty(dhgName))
            {
                throw new ArgumentException(nameof(dhgName));
            }

            if (string.IsNullOrEmpty(dhName))
            {
                throw new ArgumentException(nameof(dhName));
            }

            if (string.IsNullOrEmpty(dhSku))
            {
                throw new ArgumentException(nameof(dhSku));
            }

            if (string.IsNullOrEmpty(location))
            {
                throw new ArgumentException(nameof(location));
            }

            var azureCredentials = new AzureCredentials(
                new TokenCredentials(token),
                new TokenCredentials(token),
                tenantId,
                azureEnvironment);

            var computeManagementClient = await _dhmComputeClient.GetComputeManagementClient(
                subscriptionId,
                azureCredentials,
                azureEnvironment);

            if (await computeManagementClient.DedicatedHostGroups.GetAsync(resourceGroup, dhgName) == null)
            {
                await computeManagementClient.DedicatedHostGroups.CreateOrUpdateAsync(
                    resourceGroup,
                    dhgName,
                    new DedicatedHostGroup()
                {
                    Location = location,
                    PlatformFaultDomainCount = 1
                });
            }

            return(await computeManagementClient.DedicatedHosts.CreateOrUpdateWithHttpMessagesAsync(
                       resourceGroup,
                       dhgName,
                       dhName,
                       new DedicatedHost
            {
                Location = location,
                Sku = new Sku()
                {
                    Name = dhSku
                }
            },
                       null));
        }
Exemplo n.º 11
0
        /// <summary>
        /// Finds a Dedicated Host to host a VM.
        /// </summary>
        /// <param name="token">Auth token.</param>
        /// <param name="azureEnvironment">Azure cloud.</param>
        /// <param name="tenantId">Tenant ID.</param>
        /// <param name="subscriptionId">Subscription ID.</param>
        /// <param name="resourceGroup">Resource group.</param>
        /// <param name="hostGroupName">Dedicated Host group name.</param>
        /// /// <param name="requiredVmSize">VM SKU.</param>
        /// <param name="vmName">VM name.</param>
        /// <param name="location">VM region.</param>
        public async Task <string> GetDedicatedHostForVmPlacement(
            string token,
            AzureEnvironment azureEnvironment,
            string tenantId,
            string subscriptionId,
            string resourceGroup,
            string hostGroupName,
            string requiredVmSize,
            string vmName,
            string location)
        {
            if (string.IsNullOrEmpty(token))
            {
                throw new ArgumentNullException(nameof(token));
            }

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

            if (string.IsNullOrEmpty(tenantId))
            {
                throw new ArgumentNullException(nameof(tenantId));
            }

            if (string.IsNullOrEmpty(subscriptionId))
            {
                throw new ArgumentException(nameof(subscriptionId));
            }

            if (string.IsNullOrEmpty(resourceGroup))
            {
                throw new ArgumentException(nameof(resourceGroup));
            }

            if (string.IsNullOrEmpty(hostGroupName))
            {
                throw new ArgumentException(nameof(hostGroupName));
            }

            if (string.IsNullOrEmpty(requiredVmSize))
            {
                throw new ArgumentException(nameof(requiredVmSize));
            }

            if (string.IsNullOrEmpty(vmName))
            {
                throw new ArgumentException(nameof(vmName));
            }

            if (string.IsNullOrEmpty(location))
            {
                throw new ArgumentException(nameof(location));
            }

            var matchingHostId     = string.Empty;
            var innerLoopStopwatch = Stopwatch.StartNew();

            while (string.IsNullOrEmpty(matchingHostId))
            {
                matchingHostId = await _dedicatedHostSelector.SelectDedicatedHost(
                    token,
                    azureEnvironment,
                    tenantId,
                    subscriptionId,
                    resourceGroup,
                    hostGroupName,
                    requiredVmSize);

                if (string.IsNullOrEmpty(matchingHostId))
                {
                    var lockRetryCount = _config.LockRetryCount;
                    var hostGroupId    = await GetDedicatedHostGroupId(
                        token,
                        azureEnvironment,
                        tenantId,
                        subscriptionId,
                        resourceGroup,
                        hostGroupName);

                    await Policy
                    .Handle <StorageException>()
                    .WaitAndRetryAsync(
                        lockRetryCount,
                        r => TimeSpan.FromSeconds(2 * r),
                        (ex, ts, r) => _logger.LogInformation($"Attempt #{r.Count}/{lockRetryCount}. Will try again in {ts.TotalSeconds} seconds. Exception={ex}"))
                    .ExecuteAsync(async() =>
                    {
                        try
                        {
                            _logger.LogInformation($"About to lock");
                            await _syncProvider.StartSerialRequests(hostGroupId);

                            matchingHostId = await _dedicatedHostSelector.SelectDedicatedHost(
                                token,
                                azureEnvironment,
                                tenantId,
                                subscriptionId,
                                resourceGroup,
                                hostGroupName,
                                requiredVmSize);

                            if (string.IsNullOrEmpty(matchingHostId))
                            {
                                _logger.LogInformation($"Creating a new host.");
                                var hostSku = GetVmToHostMapping(requiredVmSize);

                                var newDedicatedHostResponse = await CreateDedicatedHost(
                                    token,
                                    azureEnvironment,
                                    tenantId,
                                    subscriptionId,
                                    resourceGroup,
                                    hostGroupName,
                                    "host-" + (new Random().Next(100, 999)),
                                    hostSku,
                                    location);

                                matchingHostId = newDedicatedHostResponse.Body.Id;
                                _logger.LogMetric("DedicatedHostCreationCountMetric", 1);
                            }
                        }
                        catch (Exception exception)
                        {
                            _logger.LogError($"Error while finding a DH: {exception}");
                        }
                        finally
                        {
                            _logger.LogInformation($"Releasing the lock");
                            await _syncProvider.EndSerialRequests(hostGroupId);
                        }
                    });
                }

                _logger.LogInformation($"Retry to find a host for {vmName} of SKU {requiredVmSize}");
            }

            if (string.IsNullOrEmpty(matchingHostId))
            {
                _logger.LogError($"Something went really wrong! Could not find a " +
                                 $"matching host for {requiredVmSize} within {innerLoopStopwatch.Elapsed.TotalSeconds} seconds. ");
            }

            _logger.LogMetric("GetDedicatedHostTimeSecondsMetric", innerLoopStopwatch.Elapsed.TotalSeconds);
            _logger.LogInformation($"GetDedicatedHost: Took {innerLoopStopwatch.Elapsed.TotalSeconds} seconds to find a matching host {matchingHostId} for {vmName} of {requiredVmSize} SKU.");
            return(matchingHostId);
        }
Exemplo n.º 12
0
        private IEnumerable <AzureSubscription> ListServiceManagementSubscriptions(ref AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
        {
            List <AzureSubscription> result = new List <AzureSubscription>();

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

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

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

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

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

            return(result);
        }
Exemplo n.º 13
0
        private async void buttonPickupAccount_Click(object sender, EventArgs e)
        {
            AddAMSAccount1 addaccount1 = new AddAMSAccount1();

            if (addaccount1.ShowDialog() == DialogResult.OK)
            {
                if (addaccount1.SelectedMode == AddAccountMode.BrowseSubscriptions)
                {
                    Cursor = Cursors.WaitCursor;

                    environment = addaccount1.GetEnvironment();

                    AuthenticationContext authContext = new AuthenticationContext(
                        // authority:  environment.Authority,
                        authority: environment.AADSettings.AuthenticationEndpoint.ToString() + "common",
                        validateAuthority: true
                        );

                    AuthenticationResult accessToken;
                    try
                    {
                        accessToken = await authContext.AcquireTokenAsync(
                            resource : environment.AADSettings.TokenAudience.ToString(),
                            clientId : environment.ClientApplicationId,
                            redirectUri : new Uri("urn:ietf:wg:oauth:2.0:oob"),
                            parameters : new PlatformParameters(addaccount1.SelectUser ? PromptBehavior.SelectAccount : PromptBehavior.Auto)
                            );
                    }
                    catch (Exception ex)
                    {
                        Cursor = Cursors.Default;
                        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    TokenCredentials credentials = new TokenCredentials(accessToken.AccessToken, "Bearer");

                    SubscriptionClient subscriptionClient = new SubscriptionClient(environment.ArmEndpoint, credentials);

                    // Subcriptions listing
                    List <Subscription>  subscriptions     = new List <Subscription>();
                    IPage <Subscription> subscriptionsPage = subscriptionClient.Subscriptions.List();
                    while (subscriptionsPage != null)
                    {
                        subscriptions.AddRange(subscriptionsPage);
                        if (subscriptionsPage.NextPageLink != null)
                        {
                            subscriptionsPage = subscriptionClient.Subscriptions.ListNext(subscriptionsPage.NextPageLink);
                        }
                        else
                        {
                            subscriptionsPage = null;
                        }
                    }

                    // Tenants listing
                    List <TenantIdDescription>  tenants     = new List <TenantIdDescription>();
                    IPage <TenantIdDescription> tenantsPage = subscriptionClient.Tenants.List();
                    while (tenantsPage != null)
                    {
                        tenants.AddRange(tenantsPage);
                        if (tenantsPage.NextPageLink != null)
                        {
                            tenantsPage = subscriptionClient.Tenants.ListNext(tenantsPage.NextPageLink);
                        }
                        else
                        {
                            tenantsPage = null;
                        }
                    }

                    /*
                     * // Tenants browsing
                     * myTenants tenants = new myTenants();
                     * string URL = environment.ArmEndpoint + "tenants?api-version=2020-01-01";
                     *
                     * HttpClient client = new HttpClient();
                     * client.DefaultRequestHeaders.Remove("Authorization");
                     * client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken.AccessToken);
                     * HttpResponseMessage response = await client.GetAsync(URL);
                     * if (response.IsSuccessStatusCode)
                     * {
                     *  string str = await response.Content.ReadAsStringAsync();
                     *  tenants = (myTenants)JsonConvert.DeserializeObject(str, typeof(myTenants));
                     * }
                     */
                    Cursor = Cursors.Default;

                    AddAMSAccount2Browse addaccount2 = new AddAMSAccount2Browse(credentials, subscriptions, environment, tenants, new PlatformParameters(addaccount1.SelectUser ? PromptBehavior.SelectAccount : PromptBehavior.Auto));

                    if (addaccount2.ShowDialog() == DialogResult.OK)
                    {
                        // Getting Media Services accounts...
                        AzureMediaServicesClient mediaServicesClient = new AzureMediaServicesClient(environment.ArmEndpoint, credentials);

                        CredentialsEntryV3 entry = new CredentialsEntryV3(addaccount2.selectedAccount,
                                                                          environment,
                                                                          addaccount1.SelectUser ? PromptBehavior.SelectAccount : PromptBehavior.Auto,
                                                                          false,
                                                                          addaccount2.selectedTenantId,
                                                                          false
                                                                          );
                        CredentialList.MediaServicesAccounts.Add(entry);
                        AddItemToListviewAccounts(entry);

                        SaveCredentialsToSettings();
                    }
                    else
                    {
                        return;
                    }
                }


                // Get info from the Portal or Azure CLI JSON
                else if (addaccount1.SelectedMode == AddAccountMode.FromAzureCliOrPortalJson)
                {
                    string        example = @"{
  ""AadClientId"": ""00000000-0000-0000-0000-000000000000"",
  ""AadEndpoint"": ""https://login.microsoftonline.com"",
  ""AadSecret"": ""00000000-0000-0000-0000-000000000000"",
  ""AadTenantId"": ""00000000-0000-0000-0000-000000000000"",
  ""AccountName"": ""amsaccount"",
  ""ArmAadAudience"": ""https://management.core.windows.net/"",
  ""ArmEndpoint"": ""https://management.azure.com/"",
  ""Region"": ""West Europe"",
  ""ResourceGroup"": ""amsResourceGroup"",
  ""SubscriptionId"": ""00000000-0000-0000-0000-000000000000""
}";
                    EditorXMLJSON form    = new EditorXMLJSON("Enter the JSON output of the Azure Portal or Azure Cli Service Principal creation", example, true, ShowSampleMode.None, true, "The Service Principal secret is stored encrypted in the application settings.");

                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        JsonFromAzureCliOrPortal json;
                        try
                        {
                            json = (JsonFromAzureCliOrPortal)JsonConvert.DeserializeObject(form.TextData, typeof(JsonFromAzureCliOrPortal));
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Error reading the json", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        string resourceId  = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Media/mediaservices/{2}", json.SubscriptionId, json.ResourceGroup, json.AccountName);
                        string AADtenantId = json.AadTenantId;

                        // environment
                        ActiveDirectoryServiceSettings aadSettings = new ActiveDirectoryServiceSettings()
                        {
                            AuthenticationEndpoint = json.AadEndpoint ?? addaccount1.GetEnvironment().AADSettings.AuthenticationEndpoint,
                            TokenAudience          = json.ArmAadAudience,
                            ValidateAuthority      = true
                        };

                        AzureEnvironment env = new AzureEnvironment(AzureEnvType.Custom)
                        {
                            AADSettings = aadSettings, ArmEndpoint = json.ArmEndpoint
                        };

                        CredentialsEntryV3 entry = new CredentialsEntryV3(
                            // new MediaService(resourceId, json.AccountName, null, null, json.Location ?? json.Region),
                            new MediaService(json.Location ?? json.Region, resourceId, json.AccountName),

                            env,
                            PromptBehavior.Auto,
                            true,
                            AADtenantId,
                            false,
                            json.AadClientId,
                            json.AadSecret
                            );

                        CredentialList.MediaServicesAccounts.Add(entry);
                        AddItemToListviewAccounts(entry);

                        SaveCredentialsToSettings();
                    }
                    else
                    {
                        return;
                    }
                }
                else if (addaccount1.SelectedMode == AddAccountMode.ManualEntry)
                {
                    AddAMSAccount2Manual form = new AddAMSAccount2Manual();
                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        string accountnamecc = form.textBoxAMSResourceId.Text.Split('/').Last();

                        CredentialsEntryV3 entry = new CredentialsEntryV3(
                            new MediaService(form.textBoxLocation.Text, form.textBoxAMSResourceId.Text, accountnamecc),
                            addaccount1.GetEnvironment(),
                            PromptBehavior.Auto,
                            form.radioButtonAADServicePrincipal.Checked,
                            form.textBoxAADtenantId.Text,
                            true
                            );

                        CredentialList.MediaServicesAccounts.Add(entry);
                        AddItemToListviewAccounts(entry);

                        SaveCredentialsToSettings();
                    }
                    else
                    {
                        return;
                    }
                }
            }
        }
Exemplo n.º 14
0
 public ExternalAzureContext(AzureEnvironment azureEnvironment)
     : base(azureEnvironment)
 {
 }
Exemplo n.º 15
0
        /// <summary>
        /// Returns a SharePoint ClientContext using Azure Active Directory App Only Authentication. This requires that you have a certificated created, and updated the key credentials key in the application manifest in the azure AD accordingly.
        /// </summary>
        /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param>
        /// <param name="clientId">The Azure AD Application Client ID</param>
        /// <param name="tenant">The Azure AD Tenant, e.g. mycompany.onmicrosoft.com</param>
        /// <param name="certificate">Certificate used to authenticate</param>
        /// <param name="environment">SharePoint environment being used</param>
        /// <returns></returns>
        public ClientContext GetAzureADAppOnlyAuthenticatedContext(string siteUrl, string clientId, string tenant, X509Certificate2 certificate, AzureEnvironment environment = AzureEnvironment.Production)
        {
            var clientContext = new ClientContext(siteUrl);

            string authority = string.Format(CultureInfo.InvariantCulture, "{0}/{1}/", GetAzureADLoginEndPoint(environment), tenant);

            var authContext = new AuthenticationContext(authority);

            var clientAssertionCertificate = new ClientAssertionCertificate(clientId, certificate);

            var host = new Uri(siteUrl);

            clientContext.ExecutingWebRequest += (sender, args) =>
            {
                var ar = authContext.AcquireToken(host.Scheme + "://" + host.Host + "/", clientAssertionCertificate);
                args.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + ar.AccessToken;
            };

            return(clientContext);
        }
        /// <summary>
        /// Returns a SharePoint ClientContext using Azure Active Directory App Only Authentication. This requires that you have a certificated created, and updated the key credentials key in the application manifest in the azure AD accordingly.
        /// </summary>
        /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param>
        /// <param name="clientId">The Azure AD Application Client ID</param>
        /// <param name="tenant">The Azure AD Tenant, e.g. mycompany.onmicrosoft.com</param>
        /// <param name="certificate"></param>
        /// <param name="environment"></param>
        /// <returns></returns>
        public ClientContext GetAzureADAppOnlyAuthenticatedContext(string siteUrl, string clientId, string tenant, X509Certificate2 certificate, AzureEnvironment environment = AzureEnvironment.Production)
        {

            var clientContext = new ClientContext(siteUrl);

            var authority = string.Format(CultureInfo.InvariantCulture, "https://login.windows.net/{0}/", tenant);

            if (environment == AzureEnvironment.PPE)
            {
                //windows-ppe.net
                authority = string.Format(CultureInfo.InvariantCulture, "https://login.windows-ppe.net/{0}/", tenant);
            }

            var authContext = new AuthenticationContext(authority);

            var clientAssertionCertificate = new ClientAssertionCertificate(clientId, certificate);

            var host = new Uri(siteUrl);

            clientContext.ExecutingWebRequest += (sender, args) =>
            {
                var ar = authContext.AcquireToken(host.Scheme + "://" + host.Host + "/", clientAssertionCertificate);
                args.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + ar.AccessToken;
            };

            return clientContext;
        }
        /// <summary>
        /// Returns a SharePoint ClientContext using Azure Active Directory App Only Authentication. This requires that you have a certificated created, and updated the key credentials key in the application manifest in the azure AD accordingly.
        /// </summary>
        /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param>
        /// <param name="clientId">The Azure AD Application Client ID</param>
        /// <param name="tenant">The Azure AD Tenant, e.g. mycompany.onmicrosoft.com</param>
        /// <param name="certificatePath">The path to the certificate (*.pfx) file on the file system</param>
        /// <param name="certificatePassword">Password to the certificate</param>
        /// <param name="environment">Indicates which Azure AD environment is being used</param>
        /// <returns></returns>
        public ClientContext GetAzureADAppOnlyAuthenticatedContext(string siteUrl, string clientId, string tenant, string certificatePath, SecureString certificatePassword, AzureEnvironment environment = AzureEnvironment.Production)
        {
            var certfile = System.IO.File.OpenRead(certificatePath);
            var certificateBytes = new byte[certfile.Length];
            certfile.Read(certificateBytes, 0, (int)certfile.Length);
            var cert = new X509Certificate2(
                certificateBytes,
                certificatePassword,
                X509KeyStorageFlags.Exportable |
                X509KeyStorageFlags.MachineKeySet |
                X509KeyStorageFlags.PersistKeySet);

            return GetAzureADAppOnlyAuthenticatedContext(siteUrl, clientId, tenant, cert, environment);
        }
        /// <summary>
        /// Returns a SharePoint ClientContext using Azure Active Directory App Only Authentication. This requires that you have a certificated created, and updated the key credentials key in the application manifest in the azure AD accordingly.
        /// </summary>
        /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param>
        /// <param name="clientId">The Azure AD Application Client ID</param>
        /// <param name="tenant">The Azure AD Tenant, e.g. mycompany.onmicrosoft.com</param>
        /// <param name="certificatePath">The path to the certificate (*.pfx) file on the file system</param>
        /// <param name="certificatePassword">Password to the certificate</param>
        /// <param name="environment">Indicates which Azure AD environment is being used</param>
        /// <returns></returns>
        public ClientContext GetAzureADAppOnlyAuthenticatedContext(string siteUrl, string clientId, string tenant, string certificatePath, string certificatePassword, AzureEnvironment environment = AzureEnvironment.Production)
        {
            var certPassword = Utilities.EncryptionUtility.ToSecureString(certificatePassword);

            return GetAzureADAppOnlyAuthenticatedContext(siteUrl, clientId, tenant, certificatePath, certPassword, environment);
        }
        /// <summary>
        /// Returns a SharePoint ClientContext using Azure Active Directory App Only Authentication. This requires that you have a certificated created, and updated the key credentials key in the application manifest in the azure AD accordingly.
        /// </summary>
        /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param>
        /// <param name="clientId">The Azure AD Application Client ID</param>
        /// <param name="tenant">The Azure AD Tenant, e.g. mycompany.onmicrosoft.com</param>
        /// <param name="storeName">The name of the store for the certificate</param>
        /// <param name="storeLocation">The location of the store for the certificate</param>
        /// <param name="thumbPrint">The thumbprint of the certificate to locate in the store</param>
        /// <param name="environment">Indicates which Azure AD environment is being used</param>
        /// <returns></returns>
        public ClientContext GetAzureADAppOnlyAuthenticatedContext(string siteUrl, string clientId, string tenant, StoreName storeName, StoreLocation storeLocation, string thumbPrint, AzureEnvironment environment = AzureEnvironment.Production)
        {
            var cert = Utilities.X509CertificateUtility.LoadCertificate(storeName, storeLocation, thumbPrint);

            return GetAzureADAppOnlyAuthenticatedContext(siteUrl, clientId, tenant, cert, environment);
        }
 public AzureContext(AzureSubscription subscription, AzureAccount account, AzureEnvironment environment)
 {
     Subscription = subscription;
     Account = account;
     Environment = environment;
 }
Exemplo n.º 21
0
 protected AzureContextBase(AzureEnvironment azureEnvironment)
 {
     _azureEnvironment = azureEnvironment;
 }
Exemplo n.º 22
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            // Add Options
            var context = builder.GetContext();

            var section = context.Configuration.GetSection("Acmebot");

            builder.Services.AddOptions <AcmebotOptions>()
            .Bind(section.Exists() ? section : context.Configuration.GetSection("LetsEncrypt"))
            .ValidateDataAnnotations()
            .PostConfigure(options =>
            {
                // Backward compatibility
                if (options.Endpoint == "https://acme-v02.api.letsencrypt.org/")
                {
                    options.PreferredChain ??= "DST Root CA X3";
                }
            });

            // Add Services
            builder.Services.Replace(ServiceDescriptor.Transient(typeof(IOptionsFactory <>), typeof(OptionsFactory <>)));

            builder.Services.AddHttpClient();
            builder.Services.AddHttpClient("InSecure")
            .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
            });

            builder.Services.AddSingleton(new LookupClient(new LookupClientOptions(NameServer.GooglePublicDns, NameServer.GooglePublicDns2)
            {
                UseCache            = false,
                UseRandomNameServer = true
            }));

            builder.Services.AddSingleton <ITokenProvider, AppAuthenticationTokenProvider>();

            builder.Services.AddSingleton <IAzureEnvironment>(provider =>
            {
                var options = provider.GetRequiredService <IOptions <AcmebotOptions> >();

                return(AzureEnvironment.Get(options.Value.Environment));
            });

            builder.Services.AddSingleton(provider =>
            {
                var options     = provider.GetRequiredService <IOptions <AcmebotOptions> >();
                var environment = provider.GetRequiredService <IAzureEnvironment>();

                return(new WebSiteManagementClient(new Uri(environment.ResourceManager), new TokenCredentials(provider.GetRequiredService <ITokenProvider>()))
                {
                    SubscriptionId = options.Value.SubscriptionId
                });
            });

            builder.Services.AddSingleton(provider =>
            {
                var options     = provider.GetRequiredService <IOptions <AcmebotOptions> >();
                var environment = provider.GetRequiredService <IAzureEnvironment>();

                return(new DnsManagementClient(new Uri(environment.ResourceManager), new TokenCredentials(provider.GetRequiredService <ITokenProvider>()))
                {
                    SubscriptionId = options.Value.SubscriptionId
                });
            });

            builder.Services.AddSingleton(provider =>
            {
                var options     = provider.GetRequiredService <IOptions <AcmebotOptions> >();
                var environment = provider.GetRequiredService <IAzureEnvironment>();

                return(new ResourceManagementClient(new Uri(environment.ResourceManager), new TokenCredentials(provider.GetRequiredService <ITokenProvider>()))
                {
                    SubscriptionId = options.Value.SubscriptionId
                });
            });

            builder.Services.AddSingleton <IAcmeProtocolClientFactory, AcmeProtocolClientFactory>();
            builder.Services.AddSingleton <IKuduClientFactory, KuduClientFactory>();

            builder.Services.AddSingleton <WebhookClient>();
            builder.Services.AddSingleton <ILifeCycleNotificationHelper, WebhookLifeCycleNotification>();
        }
Exemplo n.º 23
0
        public AzureSubscription ToAzureSubscription(List <AzureEnvironment> envs)
        {
            AzureSubscription subscription = new AzureSubscription();

            try
            {
                subscription.Id = new Guid(this.SubscriptionId);
            }
            catch (Exception ex)
            {
                throw new ArgumentException("Subscription ID is not a valid GUID.", ex);
            }
            subscription.Name = Name;

            // Logic to detect what is the subscription environment rely's on having ManagementEndpoint (i.e. RDFE endpoint) set already on the subscription
            List <AzureEnvironment> allEnvs = envs.Union(AzureEnvironment.PublicEnvironments.Values).ToList();
            AzureEnvironment        env     = allEnvs.FirstOrDefault(e => e.IsEndpointSetToValue(AzureEnvironment.Endpoint.ServiceManagement, this.ManagementEndpoint));

            if (env != null)
            {
                subscription.Environment = env.Name;
            }
            else
            {
                subscription.Environment = EnvironmentName.AzureCloud;
            }

            if (!string.IsNullOrEmpty(this.ManagementCertificate))
            {
                subscription.Account = this.ManagementCertificate;
                subscription.SetProperty(AzureSubscription.Property.SupportedModes,
                                         AzureModule.AzureServiceManagement.ToString());
            }

            if (!string.IsNullOrEmpty(this.ActiveDirectoryUserId))
            {
                subscription.Account = this.ActiveDirectoryUserId;
            }

            if (!string.IsNullOrEmpty(this.ActiveDirectoryTenantId))
            {
                subscription.SetProperty(AzureSubscription.Property.Tenants, ActiveDirectoryTenantId);
            }

            if (this.IsDefault)
            {
                subscription.SetProperty(AzureSubscription.Property.Default, "True");
            }

            if (!string.IsNullOrEmpty(this.CloudStorageAccount))
            {
                subscription.Properties.Add(AzureSubscription.Property.StorageAccount, this.CloudStorageAccount);
            }

            if (this.RegisteredResourceProviders.Count() > 0)
            {
                StringBuilder providers = new StringBuilder();
                subscription.Properties.Add(AzureSubscription.Property.RegisteredResourceProviders,
                                            string.Join(",", RegisteredResourceProviders));
            }

            return(subscription);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Tries to acquire an application Office 365 Management API Access Token
        /// </summary>
        /// <param name="tenant">Name or id of the tenant to acquire the token for (i.e. contoso.onmicrosoft.com). Required.</param>
        /// <param name="clientId">ClientId to use to acquire the token. Required.</param>
        /// <param name="clientSecret">Client Secret to use to acquire the token. Required.</param>
        /// <returns><see cref="OfficeManagementApiToken"/> instance with the token</returns>
        public static GenericToken AcquireApplicationToken(string tenant, string clientId, string clientSecret, AzureEnvironment azureEnvironment)
        {
            var endPoint = GenericToken.GetAzureADLoginEndPoint(azureEnvironment);

            return(new OfficeManagementApiToken(GenericToken.AcquireApplicationToken(tenant, clientId, $"{endPoint}/{tenant}", new[] { $"{ResourceIdentifier}/{DefaultScope}" }, clientSecret).AccessToken));
        }
Exemplo n.º 25
0
        public override void ExecuteCmdlet()
        {
            ConfirmAction("updating environment", Name,
                          () =>
            {
                if (AzureEnvironment.PublicEnvironments.Keys.Any((k) => string.Equals(k, Name, StringComparison.CurrentCultureIgnoreCase)))
                {
                    throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture,
                                                                      "Cannot change built-in or discovered environment {0}.", Name));
                }

                if (this.ParameterSetName.Equals(MetadataParameterSet, StringComparison.Ordinal))
                {
                    // Simply use built-in environments if the ARM endpoint matches the ARM endpoint for a built-in environment
                    var publicEnvironment = AzureEnvironment.PublicEnvironments.FirstOrDefault(
                        env => !string.IsNullOrWhiteSpace(ARMEndpoint) &&
                        string.Equals(
                            env.Value?.GetEndpoint(AzureEnvironment.Endpoint.ResourceManager)?.ToLowerInvariant(),
                            GeneralUtilities.EnsureTrailingSlash(ARMEndpoint)?.ToLowerInvariant(), StringComparison.CurrentCultureIgnoreCase));

                    var defProfile = GetDefaultProfile();
                    IAzureEnvironment newEnvironment;
                    if (!defProfile.TryGetEnvironment(this.Name, out newEnvironment))
                    {
                        newEnvironment = new AzureEnvironment
                        {
                            Name = this.Name,
                            Type = AzureEnvironment.TypeUserDefined
                        };
                    }

                    if (publicEnvironment.Key == null)
                    {
                        SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.ResourceManager, ARMEndpoint);
                        try
                        {
                            EnvHelper = (EnvHelper == null ? new EnvironmentHelper() : EnvHelper);
                            MetadataResponse metadataEndpoints = EnvHelper.RetrieveMetaDataEndpoints(newEnvironment.ResourceManagerUrl).Result;
                            string domain = EnvHelper.RetrieveDomain(ARMEndpoint);

                            SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.ActiveDirectory,
                                                  metadataEndpoints.authentication.LoginEndpoint.TrimEnd('/') + '/');
                            SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId,
                                                  metadataEndpoints.authentication.Audiences[0]);
                            SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.Gallery, metadataEndpoints.GalleryEndpoint);
                            SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.Graph, metadataEndpoints.GraphEndpoint);
                            SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.GraphEndpointResourceId,
                                                  metadataEndpoints.GraphEndpoint);
                            SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix,
                                                  AzureKeyVaultDnsSuffix ?? string.Format("vault.{0}", domain).ToLowerInvariant());
                            SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId,
                                                  AzureKeyVaultServiceEndpointResourceId ?? string.Format("https://vault.{0}", domain).ToLowerInvariant());
                            SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.StorageEndpointSuffix, StorageEndpoint ?? domain);
                            newEnvironment.OnPremise = metadataEndpoints.authentication.LoginEndpoint.TrimEnd('/').EndsWith("/adfs", System.StringComparison.OrdinalIgnoreCase);
                        }
                        catch (AggregateException ae)
                        {
                            if (ae.Flatten().InnerExceptions.Count > 1)
                            {
                                throw;
                            }

                            if (ae.InnerException != null)
                            {
                                throw ae.InnerException;
                            }
                        }
                    }
                    else
                    {
                        newEnvironment      = new AzureEnvironment(publicEnvironment.Value);
                        newEnvironment.Name = Name;
                        SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix,
                                              AzureKeyVaultDnsSuffix);
                        SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId,
                                              AzureKeyVaultServiceEndpointResourceId);
                    }

                    ModifyContext((profile, client) =>
                    {
                        WriteObject(new PSAzureEnvironment(client.AddOrSetEnvironment(newEnvironment)));
                    });
                }
                else
                {
                    ModifyContext((profile, profileClient) =>
                    {
                        IAzureEnvironment newEnvironment = new AzureEnvironment {
                            Name = Name
                        };
                        if (profile.EnvironmentTable.ContainsKey(Name))
                        {
                            newEnvironment = profile.EnvironmentTable[Name];
                        }

                        if (MyInvocation != null && MyInvocation.BoundParameters != null)
                        {
                            if (MyInvocation.BoundParameters.ContainsKey(nameof(EnableAdfsAuthentication)))
                            {
                                newEnvironment.OnPremise = EnableAdfsAuthentication;
                            }

                            SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.PublishSettingsFileUrl,
                                               nameof(PublishSettingsFileUrl));
                            SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.ServiceManagement, nameof(ServiceEndpoint));
                            SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.ResourceManager,
                                               nameof(ResourceManagerEndpoint));
                            SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.ManagementPortalUrl,
                                               nameof(ManagementPortalUrl));
                            SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.StorageEndpointSuffix,
                                               nameof(StorageEndpoint));
                            SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.ActiveDirectory,
                                               nameof(ActiveDirectoryEndpoint));
                            SetEndpointIfBound(newEnvironment,
                                               AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId,
                                               nameof(ActiveDirectoryServiceEndpointResourceId));
                            SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.Gallery, nameof(GalleryEndpoint));
                            SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.Graph, nameof(GraphEndpoint));
                            SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix,
                                               nameof(AzureKeyVaultDnsSuffix));
                            SetEndpointIfBound(newEnvironment,
                                               AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId,
                                               nameof(AzureKeyVaultServiceEndpointResourceId));
                            SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.TrafficManagerDnsSuffix,
                                               nameof(TrafficManagerDnsSuffix));
                            SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.SqlDatabaseDnsSuffix,
                                               nameof(SqlDatabaseDnsSuffix));
                            SetEndpointIfBound(newEnvironment,
                                               AzureEnvironment.Endpoint.AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix,
                                               nameof(AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix));
                            SetEndpointIfBound(newEnvironment,
                                               AzureEnvironment.Endpoint.AzureDataLakeStoreFileSystemEndpointSuffix,
                                               nameof(AzureDataLakeStoreFileSystemEndpointSuffix));
                            SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.AdTenant, nameof(AdTenant));
                            SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.GraphEndpointResourceId,
                                               nameof(GraphAudience));
                            SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.DataLakeEndpointResourceId,
                                               nameof(DataLakeAudience));
                            SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.BatchEndpointResourceId,
                                               nameof(BatchEndpointResourceId));
                            SetEndpointIfBound(newEnvironment, AzureEnvironment.ExtendedEndpoint.OperationalInsightsEndpointResourceId,
                                               nameof(AzureOperationalInsightsEndpointResourceId));
                            SetEndpointIfBound(newEnvironment, AzureEnvironment.ExtendedEndpoint.OperationalInsightsEndpoint,
                                               nameof(AzureOperationalInsightsEndpoint));
                            SetEndpointIfBound(newEnvironment, AzureEnvironment.ExtendedEndpoint.AnalysisServicesEndpointSuffix,
                                               nameof(AzureAnalysisServicesEndpointSuffix));
                            SetEndpointIfBound(newEnvironment, AzureEnvironment.ExtendedEndpoint.AnalysisServicesEndpointResourceId,
                                               nameof(AzureAnalysisServicesEndpointResourceId));
                            SetEndpointIfBound(newEnvironment, AzureEnvironment.ExtendedEndpoint.AzureAttestationServiceEndpointSuffix,
                                               nameof(AzureAttestationServiceEndpointSuffix));
                            SetEndpointIfBound(newEnvironment, AzureEnvironment.ExtendedEndpoint.AzureAttestationServiceEndpointResourceId,
                                               nameof(AzureAttestationServiceEndpointResourceId));
                            SetEndpointIfBound(newEnvironment, AzureEnvironment.ExtendedEndpoint.AzureSynapseAnalyticsEndpointSuffix,
                                               nameof(AzureSynapseAnalyticsEndpointSuffix));
                            SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.ContainerRegistryEndpointSuffix,
                                               nameof(ContainerRegistryEndpointSuffix));
                            SetEndpointIfBound(newEnvironment, AzureEnvironment.ExtendedEndpoint.AzureSynapseAnalyticsEndpointResourceId,
                                               nameof(AzureSynapseAnalyticsEndpointResourceId));
                            WriteObject(new PSAzureEnvironment(profileClient.AddOrSetEnvironment(newEnvironment)));
                        }
                    });
                }
            });
        }
Exemplo n.º 26
0
 /// <summary>
 /// Tries to acquire an application Office 365 Management API Access Token for the provided scopes interactively by allowing the user to log in
 /// </summary>
 /// <param name="clientId">ClientId to use to acquire the token. Required.</param>
 /// <param name="scopes">Array with scopes that should be requested access to. Required.</param>
 /// <returns><see cref="OfficeManagementApiToken"/> instance with the token</returns>
 public static new GenericToken AcquireApplicationTokenInteractive(string clientId, string[] scopes, AzureEnvironment azureEnvironment)
 {
     return(new OfficeManagementApiToken(GenericToken.AcquireApplicationTokenInteractive(clientId, scopes.Select(s => $"{ResourceIdentifier}/{s}").ToArray(), azureEnvironment).AccessToken));
 }
Exemplo n.º 27
0
        /// <summary>
        /// Creates a VM on a Dedicated Host
        /// </summary>
        /// <param name="token">Auth token.</param>
        /// <param name="azureEnvironment">Azure cloud.</param>
        /// <param name="tenantId">Tenant ID.</param>
        /// <param name="subscriptionId">Subscription ID.</param>
        /// <param name="resourceGroup">Resource group.</param>
        /// <param name="dhgName">Dedicated Host group name.</param>
        /// <param name="vmSku">VM SKU.</param>
        /// <param name="vmName">VM name.</param>
        /// <param name="region">Azure region for VM.</param>
        /// <param name="virtualMachine">VirtualMachine object (serialized).</param>
        public async Task <VirtualMachine> CreateVmOnDedicatedHost(
            string token,
            AzureEnvironment azureEnvironment,
            string tenantId,
            string subscriptionId,
            string resourceGroup,
            string dhgName,
            string vmSku,
            string vmName,
            Region region,
            VirtualMachine virtualMachine)
        {
            if (string.IsNullOrEmpty(token))
            {
                throw new ArgumentNullException(nameof(token));
            }

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

            if (string.IsNullOrEmpty(tenantId))
            {
                throw new ArgumentNullException(nameof(tenantId));
            }

            if (string.IsNullOrEmpty(subscriptionId))
            {
                throw new ArgumentException(nameof(subscriptionId));
            }

            if (string.IsNullOrEmpty(resourceGroup))
            {
                throw new ArgumentException(nameof(resourceGroup));
            }

            if (string.IsNullOrEmpty(dhgName))
            {
                throw new ArgumentException(nameof(dhgName));
            }

            if (string.IsNullOrEmpty(vmSku))
            {
                throw new ArgumentException(nameof(vmSku));
            }

            if (string.IsNullOrEmpty(vmName))
            {
                throw new ArgumentException(nameof(vmName));
            }

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

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

            var azureCredentials = new AzureCredentials(
                new TokenCredentials(token),
                new TokenCredentials(token),
                tenantId,
                azureEnvironment);

            var computeManagementClient = await _dhmComputeClient.GetComputeManagementClient(
                subscriptionId,
                azureCredentials,
                azureEnvironment);

            VirtualMachine response            = null;
            var            vmProvisioningState = virtualMachine.ProvisioningState;
            var            minIntervalToCheckForVmInSeconds = _config.MinIntervalToCheckForVmInSeconds;
            var            maxIntervalToCheckForVmInSeconds = _config.MaxIntervalToCheckForVmInSeconds;
            var            retryCountToCheckVmState         = _config.RetryCountToCheckVmState;
            var            maxRetriesToCreateVm             = _config.MaxRetriesToCreateVm;
            var            dedicatedHostCacheTtlMin         = _config.DedicatedHostCacheTtlMin;
            var            vmCreationRetryCount             = 0;

            while ((string.IsNullOrEmpty(vmProvisioningState) ||
                    !string.Equals(vmProvisioningState, "Succeeded", StringComparison.InvariantCultureIgnoreCase)) &&
                   vmCreationRetryCount < maxRetriesToCreateVm)
            {
                if (string.IsNullOrEmpty(vmProvisioningState))
                {
                    var dedicatedHostId = await GetDedicatedHostForVmPlacement(
                        token,
                        azureEnvironment,
                        tenantId,
                        subscriptionId,
                        resourceGroup,
                        dhgName,
                        vmSku,
                        vmName,
                        region.Name);

                    _dedicatedHostStateManager.MarkHostUsage(dedicatedHostId.ToLower(), DateTimeOffset.Now.ToString(), TimeSpan.FromMinutes(dedicatedHostCacheTtlMin));
                    virtualMachine.Host = new SubResource(dedicatedHostId);
                    try
                    {
                        response = await computeManagementClient.VirtualMachines
                                   .CreateOrUpdateAsync(
                            resourceGroup,
                            vmName,
                            virtualMachine);
                    }
                    catch (CloudException cloudException)
                    {
                        if (!string.IsNullOrEmpty(cloudException.Body?.Code) && string.Equals(cloudException.Body?.Code, "AllocationFailed"))
                        {
                            // do nothing, retry when we hit a allocation issue related to capacity
                        }
                        else
                        {
                            throw;
                        }
                    }
                }

                // TODO: Remove below 'if block' once the Compute DH stops provisioning VMs in F state when capacity bound.
                // TODO: Intentional code duplication below to keep logic related to this bug separate.
                if (string.Equals(vmProvisioningState, "Failed", StringComparison.InvariantCultureIgnoreCase))
                {
                    _logger.LogMetric("VmProvisioningFailureCountMetric", 1);
                    _dedicatedHostStateManager.MarkHostAtCapacity(virtualMachine.Host.Id.ToLower(), DateTimeOffset.Now.ToString(), TimeSpan.FromMinutes(dedicatedHostCacheTtlMin));
                    var dedicatedHostId = await GetDedicatedHostForVmPlacement(
                        token,
                        azureEnvironment,
                        tenantId,
                        subscriptionId,
                        resourceGroup,
                        dhgName,
                        vmSku,
                        vmName,
                        region.Name);

                    await computeManagementClient.VirtualMachines.DeallocateAsync(resourceGroup, virtualMachine.Name);

                    virtualMachine.Host = new SubResource(dedicatedHostId);
                    response            = await computeManagementClient.VirtualMachines
                                          .CreateOrUpdateAsync(
                        resourceGroup,
                        vmName,
                        virtualMachine);

                    try
                    {
                        await computeManagementClient.VirtualMachines.StartAsync(resourceGroup, virtualMachine.Name);
                    }
                    catch (CloudException cloudException)
                    {
                        if (!string.IsNullOrEmpty(cloudException.Body?.Code) && string.Equals(cloudException.Body?.Code, "AllocationFailed"))
                        {
                            // do nothing, retry when we hit a allocation issue related to capacity
                        }
                        else
                        {
                            throw;
                        }
                    }
                }

                // Wait for VM provisioning state to update
                await Task.Delay(TimeSpan.FromSeconds(new Random().Next(minIntervalToCheckForVmInSeconds, maxIntervalToCheckForVmInSeconds)));

                await Policy
                .Handle <CloudException>()
                .WaitAndRetryAsync(
                    retryCountToCheckVmState,
                    r => TimeSpan.FromSeconds(2 * r),
                    onRetry: (ex, ts, r) =>
                    _logger.LogInformation(
                        $"Could not get provisioning state for {virtualMachine.Name}. Attempt #{r}/{retryCountToCheckVmState}. Will try again in {ts.TotalSeconds} seconds. Exception={ex}"))
                .ExecuteAsync(async() =>
                {
                    vmProvisioningState =
                        (await computeManagementClient.VirtualMachines.GetAsync(resourceGroup, virtualMachine.Name))
                        .ProvisioningState;
                });

                _logger.LogInformation($"Provisioning state for {virtualMachine.Name} is {vmProvisioningState}");
                vmCreationRetryCount++;
            }

            return(response);
        }
Exemplo n.º 28
0
        public static GraphToken AcquireApplicationTokenDeviceLogin(string clientId, string[] scopes, Action <DeviceCodeResult> callBackAction, AzureEnvironment azureEnvironment)
        {
            var endPoint = GenericToken.GetAzureADLoginEndPoint(azureEnvironment);

            return(new GraphToken(AcquireApplicationTokenDeviceLogin(clientId, scopes.Select(s => $"{ResourceIdentifier}/{s}").ToArray(), $"{endPoint}/organizations", callBackAction).AccessToken));
        }
Exemplo n.º 29
0
        /// <summary>
        /// Deletes a VM running on a Dedicated Host, and the Host too if it does not have
        /// any more VMs running.
        /// </summary>
        /// <param name="token">Auth token.</param>
        /// <param name="azureEnvironment">Azure cloud.</param>
        /// <param name="tenantId">Tenant ID.</param>
        /// <param name="subscriptionId">Subscription ID.</param>
        /// <param name="resourceGroup">Resource group.</param>
        /// <param name="dedicatedHostGroup">Dedicated Host group name.</param>
        /// <param name="vmName">VM name.</param>
        /// <returns></returns>
        public async Task DeleteVmOnDedicatedHost(
            string token,
            AzureEnvironment azureEnvironment,
            string tenantId,
            string subscriptionId,
            string resourceGroup,
            string dedicatedHostGroup,
            string vmName)
        {
            if (string.IsNullOrEmpty(token))
            {
                throw new ArgumentNullException(nameof(token));
            }

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

            if (string.IsNullOrEmpty(tenantId))
            {
                throw new ArgumentNullException(nameof(tenantId));
            }

            if (string.IsNullOrEmpty(subscriptionId))
            {
                throw new ArgumentNullException(nameof(subscriptionId));
            }

            if (string.IsNullOrEmpty(resourceGroup))
            {
                throw new ArgumentNullException(nameof(resourceGroup));
            }

            if (string.IsNullOrEmpty(dedicatedHostGroup))
            {
                throw new ArgumentNullException(nameof(dedicatedHostGroup));
            }

            if (string.IsNullOrEmpty(vmName))
            {
                throw new ArgumentNullException(nameof(vmName));
            }

            var azureCredentials = new AzureCredentials(
                new TokenCredentials(token),
                new TokenCredentials(token),
                tenantId,
                azureEnvironment);

            var computeManagementClient = await _dhmComputeClient.GetComputeManagementClient(
                subscriptionId,
                azureCredentials,
                azureEnvironment);

            var            retryCountToCheckVm      = _config.RetryCountToCheckVmState;
            var            dedicatedHostCacheTtlMin = _config.DedicatedHostCacheTtlMin;
            VirtualMachine virtualMachine           = null;
            DedicatedHost  dedicatedHost            = null;
            string         hostId = null;
            await Policy
            .Handle <CloudException>()
            .WaitAndRetryAsync(
                retryCountToCheckVm,
                r => TimeSpan.FromSeconds(2 * r),
                onRetry: (ex, ts, r) =>
                _logger.LogInformation(
                    $"Could not get VM details for {vmName}. Attempt #{r}/{retryCountToCheckVm}. Will try again in {ts.TotalSeconds} seconds. Exception={ex}"))
            .ExecuteAsync(async() =>
            {
                virtualMachine = await computeManagementClient.VirtualMachines.GetAsync(resourceGroup, vmName);
                hostId         = virtualMachine?.Host?.Id;
                var hostName   = hostId?.Split(new[] { '/' }).Last();
                await computeManagementClient.VirtualMachines.DeleteAsync(resourceGroup, vmName);
                dedicatedHost = await computeManagementClient.DedicatedHosts.GetAsync(resourceGroup, dedicatedHostGroup, hostName, InstanceViewTypes.InstanceView);
            });

            if (string.IsNullOrEmpty(hostId))
            {
                _logger.LogInformation($"Could not find Host for {vmName}.");
                return;
            }

            if (dedicatedHost?.VirtualMachines.Count == 0)
            {
                // Avoid locking for now; revisit if needed
                _dedicatedHostStateManager.MarkHostForDeletion(hostId.ToLower(), DateTimeOffset.Now.ToString(), TimeSpan.FromMinutes(dedicatedHostCacheTtlMin));
                if (!_dedicatedHostStateManager.IsHostInUsage(hostId.ToLower()))
                {
                    await computeManagementClient.DedicatedHosts.DeleteAsync(resourceGroup, dedicatedHostGroup, dedicatedHost.Name);

                    _dedicatedHostStateManager.UnmarkHostForDeletion(hostId.ToLower());
                }
            }
        }
Exemplo n.º 30
0
        /// <summary>
        /// Tries to acquire a delegated Office 365 Management API Access Token for the provided scopes using the provided credentials
        /// </summary>
        /// <param name="clientId">ClientId to use to acquire the token. Required.</param>
        /// <param name="scopes">Array with scopes that should be requested access to. Required.</param>
        /// <param name="username">The username to authenticate with. Required.</param>
        /// <param name="securePassword">The password to authenticate with. Required.</param>
        /// <returns><see cref="OfficeManagementApiToken"/> instance with the token</returns>
        public static GenericToken AcquireDelegatedTokenWithCredentials(string clientId, string[] scopes, string username, SecureString securePassword, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            var endPoint = GenericToken.GetAzureADLoginEndPoint(azureEnvironment);

            return(new OfficeManagementApiToken(GenericToken.AcquireDelegatedTokenWithCredentials(clientId, scopes.Select(s => $"{ResourceIdentifier}/{s}").ToArray(), $"{endPoint}/organizations/", username, securePassword).AccessToken));
        }
Exemplo n.º 31
0
        public async Task <IList <DedicatedHost> > PrepareDedicatedHostGroup(
            string token,
            AzureEnvironment azureEnvironment,
            string tenantId, string subscriptionId,
            string resourceGroup,
            string dhGroupName,
            string vmSku,
            int vmInstances,
            int?platformFaultDomain)
        {
            List <DedicatedHost> dedicatedHosts = default;

            if (string.IsNullOrEmpty(token))
            {
                throw new ArgumentNullException(nameof(token));
            }

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

            if (string.IsNullOrEmpty(tenantId))
            {
                throw new ArgumentNullException(nameof(tenantId));
            }

            if (string.IsNullOrEmpty(subscriptionId))
            {
                throw new ArgumentException(nameof(subscriptionId));
            }

            if (string.IsNullOrEmpty(resourceGroup))
            {
                throw new ArgumentException(nameof(resourceGroup));
            }

            if (string.IsNullOrEmpty(dhGroupName))
            {
                throw new ArgumentException(nameof(dhGroupName));
            }

            if (string.IsNullOrEmpty(vmSku))
            {
                throw new ArgumentException(nameof(vmSku));
            }

            var azureCredentials = new AzureCredentials(
                new TokenCredentials(token),
                new TokenCredentials(token),
                tenantId,
                azureEnvironment);

            var computeManagementClient = await _dhmComputeClient.GetComputeManagementClient(
                subscriptionId,
                azureCredentials,
                azureEnvironment);

            var dhgCreateRetryCount = _config.DhgCreateRetryCount;
            var hostGroup           = await GetDedicatedHostGroup();

            var location = hostGroup.Location; // Location of DH canot be different from Host Group.
            var existingHostsOnDHGroup = await GetExistingHostsOnDHGroup();

            var(dhSku, vmCapacityPerHost) = GetVmCapacityPerHost(location, vmSku);

            var numOfDedicatedHostsByFaultDomain = this.CalculatePlatformFaultDomainToHost(
                hostGroup,
                existingHostsOnDHGroup,
                vmSku,
                vmInstances,
                vmCapacityPerHost,
                platformFaultDomain);

            await CreateDedicatedHosts();

            return(dedicatedHosts ?? new List <DedicatedHost>());

            async Task <DedicatedHostGroup> GetDedicatedHostGroup()
            {
                var response = await Helper.ExecuteAsyncWithRetry <CloudException, AzureOperationResponse <DedicatedHostGroup> >(
                    funcToexecute : () => computeManagementClient.DedicatedHostGroups.GetWithHttpMessagesAsync(resourceGroup, dhGroupName),
                    logHandler : (retryMsg) => _logger.LogInformation($"Get Dedicated Host Group '{dhGroupName} failed.' {retryMsg}"),
                    exceptionFilter : ce => !ce.Message.Contains("not found"));

                return(response.Body);
            }

            async Task <List <DedicatedHost> > GetExistingHostsOnDHGroup()
            {
                var hostsInHostGroup = await this._dedicatedHostSelector.ListDedicatedHosts(
                    token,
                    azureEnvironment,
                    tenantId,
                    subscriptionId,
                    resourceGroup,
                    dhGroupName);

                var taskList = hostsInHostGroup.Select(
                    dedicatedHost => Helper.ExecuteAsyncWithRetry <CloudException, AzureOperationResponse <DedicatedHost> >(
                        () => computeManagementClient.DedicatedHosts.GetWithHttpMessagesAsync(
                            resourceGroup,
                            dhGroupName,
                            dedicatedHost.Name,
                            InstanceViewTypes.InstanceView),
                        (retryMsg) => _logger.LogInformation($"Get details for Dedicated Host '{dedicatedHost.Name} failed.' {retryMsg}")));

                var response = await Task.WhenAll(taskList);

                return(response.Select(r => r.Body).ToList());
            }

            async Task CreateDedicatedHosts()
            {
                if (numOfDedicatedHostsByFaultDomain.Any())
                {
                    var createDhHostTasks = numOfDedicatedHostsByFaultDomain
                                            .SelectMany(c => Enumerable.Repeat(c.fd, c.numberOfHosts))
                                            .Select(pfd => Helper.ExecuteAsyncWithRetry <CloudException, AzureOperationResponse <DedicatedHost> >(
                                                        funcToexecute: () => computeManagementClient.DedicatedHosts.CreateOrUpdateWithHttpMessagesAsync(
                                                            resourceGroup,
                                                            dhGroupName,
                                                            "host-" + (new Random().Next(100, 999)),
                                                            new DedicatedHost
                    {
                        Location = location,
                        Sku      = new Sku()
                        {
                            Name = dhSku
                        },
                        PlatformFaultDomain = pfd
                    }),
                                                        logHandler: (retryMsg) => _logger.LogInformation($"Create host on  Dedicated Host Group Fault Domain {pfd} failed.' {retryMsg}"),
                                                        retryCount: _config.DhgCreateRetryCount));

                    var bulkTask = Task.WhenAll(createDhHostTasks);
                    try
                    {
                        var response = await bulkTask;
                        dedicatedHosts = response.Select(c => c.Body).ToList();
                        _logger.LogInformation(@$ "Following dedicated hosts created created successfully : {string.Join(", ", dedicatedHosts.Select(d => d.Name))}");
                    }
                    catch (Exception ex)
                    {
                        if (bulkTask?.Exception?.InnerExceptions != null && bulkTask.Exception.InnerExceptions.Any())
                        {
                            throw new Exception($"Creation of Dedicated Host failed with exceptions : \n {string.Join(",\n", bulkTask.Exception.InnerExceptions.Select(c => c?.Message + "\n"))}");
                        }
                        else
                        {
                            throw new Exception($"Unexpected exception thrown {ex?.Message}");
                        }
                    }
                }
            }
        }
Exemplo n.º 32
0
        public async Task LoadARMObjectsFromSampleOfflineFile2()
        {
            string           restResponseFile         = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestDocs\\NewTest1\\temp.json");
            TargetSettings   targetSettings           = new FakeSettingsProvider().GetTargetSettings();
            AzureEnvironment azureEnvironment         = AzureEnvironment.GetAzureEnvironments()[0];
            AzureContext     azureContextUSCommercial = await TestHelper.SetupAzureContext(azureEnvironment, restResponseFile);

            await azureContextUSCommercial.AzureSubscription.InitializeChildrenAsync(true);

            await azureContextUSCommercial.AzureSubscription.BindArmResources(targetSettings);

            AzureGenerator templateGenerator = await TestHelper.SetupTemplateGenerator(azureContextUSCommercial);

            var artifacts = new ExportArtifacts(azureContextUSCommercial.AzureSubscription);

            artifacts.ResourceGroup = await TestHelper.GetTargetResourceGroup(azureContextUSCommercial);


            artifacts.VirtualMachines.Add(azureContextUSCommercial.AzureSubscription.ArmTargetVirtualMachines[0]);
            artifacts.VirtualMachines[0].OSVirtualHardDisk.DiskSizeInGB = 128;

            await artifacts.ValidateAzureResources();

            Assert.IsNotNull(artifacts.SeekAlert("Network Interface Card (NIC) 'manageddisk01549-nic' utilizes Network Security Group (NSG) 'ManagedDisk01-nsg-nsg', but the NSG resource is not added into the migration template."));
            artifacts.NetworkSecurityGroups.Add(azureContextUSCommercial.AzureSubscription.ArmTargetNetworkSecurityGroups[0]);
            await artifacts.ValidateAzureResources();

            Assert.IsNull(artifacts.SeekAlert("Network Interface Card (NIC) 'manageddisk01549-nic' utilizes Network Security Group (NSG) 'ManagedDisk01-nsg-nsg', but the NSG resource is not added into the migration template."));

            Assert.IsNotNull(artifacts.SeekAlert("Target Virtual Network 'ManagedDiskvnet-vnet' for Virtual Machine 'ManagedDisk01-vm' Network Interface 'manageddisk01549-nic' is invalid, as it is not included in the migration / template."));
            artifacts.VirtualNetworks.Add(azureContextUSCommercial.AzureSubscription.ArmTargetVirtualNetworks[0]);
            await artifacts.ValidateAzureResources();

            Assert.IsNull(artifacts.SeekAlert("Target Virtual Network 'ManagedDiskvnet-vnet' for Virtual Machine 'ManagedDisk01-vm' Network Interface 'manageddisk01549-nic' is invalid, as it is not included in the migration / template."));

            Assert.IsNotNull(artifacts.SeekAlert("Network Interface Card (NIC) 'manageddisk01549-nic' IP Configuration 'ipconfig1' utilizes Public IP 'ManagedDisk01-ip', but the Public IP resource is not added into the migration template."));
            artifacts.PublicIPs.Add(azureContextUSCommercial.AzureSubscription.ArmTargetPublicIPs[0]);
            await artifacts.ValidateAzureResources();

            Assert.IsNull(artifacts.SeekAlert("Network Interface Card (NIC) 'manageddisk01549-nic' IP Configuration 'ipconfig1' utilizes Public IP 'ManagedDisk01-ip', but the Public IP resource is not added into the migration template."));

            Assert.IsNotNull(artifacts.SeekAlert("Virtual Machine 'ManagedDisk01' references Managed Disk 'ManagedDisk01_OsDisk_1_e901d155e5404b6a912afb22e7a804a6' which has not been added as an export resource."));
            artifacts.Disks.Add(azureContextUSCommercial.AzureSubscription.ArmTargetManagedDisks[1]);
            await artifacts.ValidateAzureResources();

            Assert.IsNull(artifacts.SeekAlert("Virtual Machine 'ManagedDisk01' references Managed Disk 'ManagedDisk01_OsDisk_1_e901d155e5404b6a912afb22e7a804a6' which has not been added as an export resource."));

            Assert.IsNotNull(artifacts.SeekAlert("Virtual Machine 'ManagedDisk01' references Managed Disk 'ManagedDataDisk01' which has not been added as an export resource."));
            artifacts.Disks.Add(azureContextUSCommercial.AzureSubscription.ArmTargetManagedDisks[0]);
            await artifacts.ValidateAzureResources();

            Assert.IsNull(artifacts.SeekAlert("Virtual Machine 'ManagedDisk01' references Managed Disk 'ManagedDataDisk01' which has not been added as an export resource."));

            Assert.IsNotNull(artifacts.SeekAlert("Network Interface Card (NIC) 'manageddisk01549-nic' is used by Virtual Machine 'ManagedDisk01-vm', but is not included in the exported resources."));
            artifacts.NetworkInterfaces.Add(azureContextUSCommercial.AzureSubscription.ArmTargetNetworkInterfaces[0]);
            await artifacts.ValidateAzureResources();

            Assert.IsNull(artifacts.SeekAlert("Network Interface Card (NIC) 'manageddisk01549-nic' is used by Virtual Machine 'ManagedDisk01-vm', but is not included in the exported resources."));

            Assert.IsTrue(artifacts.VirtualMachines[0].TargetSize.ToString() == "Standard_A1");
            await artifacts.ValidateAzureResources();

            Assert.IsFalse(artifacts.HasErrors, "Template Generation cannot occur as the are error(s).");

            ManagedDiskStorage managedDiskStorage = new ManagedDiskStorage(artifacts.VirtualMachines[0].OSVirtualHardDisk.SourceDisk);

            managedDiskStorage.StorageAccountType = Azure.Core.Interface.StorageAccountType.Premium_LRS;
            artifacts.VirtualMachines[0].OSVirtualHardDisk.TargetStorage = managedDiskStorage;
            await artifacts.ValidateAzureResources();

            Assert.IsNotNull(artifacts.SeekAlert("Premium Disk based Virtual Machines must be of VM Series 'B', 'DS', 'DS v2', 'DS v3', 'GS', 'GS v2', 'Ls' or 'Fs'."));

            artifacts.VirtualMachines[0].TargetSize = artifacts.ResourceGroup.TargetLocation.SeekVmSize("Standard_DS2_v2");
            await artifacts.ValidateAzureResources();

            Assert.IsNull(artifacts.SeekAlert("Premium Disk based Virtual Machines must be of VM Series 'B', 'DS', 'DS v2', 'DS v3', 'GS', 'GS v2', 'Ls' or 'Fs'."));

            Assert.IsFalse(artifacts.HasErrors, "Template Generation cannot occur as the are error(s).");

            templateGenerator.ExportArtifacts = artifacts;
            await templateGenerator.GenerateStreams();

            JObject templateJson = JObject.Parse(await templateGenerator.GetTemplateString());

            Assert.AreEqual(7, templateJson["resources"].Children().Count());

            var resource = templateJson["resources"].First();

            Assert.AreEqual("Microsoft.Network/networkSecurityGroups", resource["type"].Value <string>());
            Assert.AreEqual("ManagedDisk01-nsg-nsg", resource["name"].Value <string>());
            Assert.AreEqual("[resourceGroup().location]", resource["location"].Value <string>());
        }
Exemplo n.º 33
0
        internal async Task ExportAuthFileAsync(ServicePrincipalImpl servicePrincipal, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (authFile == null)
            {
                return;
            }
            RestClient       restClient  = servicePrincipal.Manager().restClient;
            AzureEnvironment environment = null;

            if (restClient.Credentials is AzureCredentials)
            {
                environment = ((AzureCredentials)restClient.Credentials).Environment;
            }
            else
            {
                string baseUrl = restClient.BaseUri;
                if (AzureEnvironment.AzureGlobalCloud.ResourceManagerEndpoint.ToLower().Contains(baseUrl.ToLower()))
                {
                    environment = AzureEnvironment.AzureGlobalCloud;
                }
                else if (AzureEnvironment.AzureChinaCloud.ResourceManagerEndpoint.ToLower().Contains(baseUrl.ToLower()))
                {
                    environment = AzureEnvironment.AzureChinaCloud;
                }
                else if (AzureEnvironment.AzureGermanCloud.ResourceManagerEndpoint.ToLower().Contains(baseUrl.ToLower()))
                {
                    environment = AzureEnvironment.AzureGermanCloud;
                }
                else if (AzureEnvironment.AzureUSGovernment.ResourceManagerEndpoint.ToLower().Contains(baseUrl.ToLower()))
                {
                    environment = AzureEnvironment.AzureUSGovernment;
                }
                if (environment == null)
                {
                    throw new NotSupportedException("Unknown resource manager endpoint " + baseUrl);
                }
            }

            try
            {
                await authFile.WriteLineAsync("{");

                await authFile.WriteLineAsync(string.Format("  \"clientId\": \"{0}\",", servicePrincipal.ApplicationId()));

                await authFile.WriteLineAsync(string.Format("  \"clientSecret\": \"{0}\",", Value()));

                await authFile.WriteLineAsync(string.Format("  \"tenantId\": \"{0}\",", servicePrincipal.Manager().tenantId));

                await authFile.WriteLineAsync(string.Format("  \"subscriptionId\": \"{0}\",", servicePrincipal.assignedSubscription));

                await authFile.WriteLineAsync(string.Format("  \"activeDirectoryEndpointUrl\": \"{0}\",", environment.AuthenticationEndpoint));

                await authFile.WriteLineAsync(string.Format("  \"resourceManagerEndpointUrl\": \"{0}\",", environment.ResourceManagerEndpoint));

                await authFile.WriteLineAsync(string.Format("  \"activeDirectoryGraphResourceId\": \"{0}\",", environment.GraphEndpoint));

                await authFile.WriteLineAsync(string.Format("  \"managementEndpointUrl\": \"{0}\"", environment.ManagementEndpoint));

                await authFile.WriteLineAsync("}");
            }
            finally
            {
                authFile.Dispose();
            }
        }
Exemplo n.º 34
0
        public async Task OfflineUITargetTreeViewTest()
        {
            string           restResponseFile         = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestDocs\\NewTest1\\temp.json");
            TargetSettings   targetSettings           = new FakeSettingsProvider().GetTargetSettings();
            AzureEnvironment azureEnvironment         = AzureEnvironment.GetAzureEnvironments()[0];
            AzureContext     azureContextUSCommercial = await TestHelper.SetupAzureContext(azureEnvironment, restResponseFile);

            await azureContextUSCommercial.AzureSubscription.InitializeChildrenAsync(true);

            await azureContextUSCommercial.AzureSubscription.BindArmResources(targetSettings);

            AzureGenerator templateGenerator = await TestHelper.SetupTemplateGenerator(azureContextUSCommercial);

            var artifacts = new ExportArtifacts(azureContextUSCommercial.AzureSubscription);

            artifacts.ResourceGroup = await TestHelper.GetTargetResourceGroup(azureContextUSCommercial);

            TargetTreeView targetTreeView = new TargetTreeView();

            targetTreeView.TargetSettings = targetSettings;

            await targetTreeView.AddMigrationTarget(azureContextUSCommercial.AzureSubscription.ArmTargetRouteTables[0]);

            targetTreeView.SeekAlertSource(azureContextUSCommercial.AzureSubscription.ArmTargetRouteTables[0]);
            Assert.IsTrue(targetTreeView.SelectedNode != null, "Selected Node is null");
            Assert.IsTrue(targetTreeView.SelectedNode.Tag != null, "Selected Node Tag is null");
            Assert.IsTrue(targetTreeView.SelectedNode.Tag.GetType() == azureContextUSCommercial.AzureSubscription.ArmTargetRouteTables[0].GetType(), "Object type mismatch");
            Assert.IsTrue(targetTreeView.SelectedNode.Tag == azureContextUSCommercial.AzureSubscription.ArmTargetRouteTables[0], "Not the correct object");

            await targetTreeView.AddMigrationTarget(azureContextUSCommercial.AzureSubscription.ArmTargetVirtualNetworks[0]);

            targetTreeView.SeekAlertSource(azureContextUSCommercial.AzureSubscription.ArmTargetVirtualNetworks[0]);
            Assert.IsTrue(targetTreeView.SelectedNode != null, "Selected Node is null");
            Assert.IsTrue(targetTreeView.SelectedNode.Tag != null, "Selected Node Tag is null");
            Assert.IsTrue(targetTreeView.SelectedNode.Tag.GetType() == azureContextUSCommercial.AzureSubscription.ArmTargetVirtualNetworks[0].GetType(), "Object type mismatch");
            Assert.IsTrue(targetTreeView.SelectedNode.Tag == azureContextUSCommercial.AzureSubscription.ArmTargetVirtualNetworks[0], "Not the correct object");

            await targetTreeView.AddMigrationTarget(azureContextUSCommercial.AzureSubscription.ArmTargetNetworkInterfaces[0]);

            targetTreeView.SeekAlertSource(azureContextUSCommercial.AzureSubscription.ArmTargetNetworkInterfaces[0]);
            Assert.IsTrue(targetTreeView.SelectedNode != null, "Selected Node is null");
            Assert.IsTrue(targetTreeView.SelectedNode.Tag != null, "Selected Node Tag is null");
            Assert.IsTrue(targetTreeView.SelectedNode.Tag.GetType() == azureContextUSCommercial.AzureSubscription.ArmTargetNetworkInterfaces[0].GetType(), "Object type mismatch");
            Assert.IsTrue(targetTreeView.SelectedNode.Tag == azureContextUSCommercial.AzureSubscription.ArmTargetNetworkInterfaces[0], "Not the correct object");

            await targetTreeView.AddMigrationTarget(azureContextUSCommercial.AzureSubscription.ArmTargetManagedDisks[0]);

            targetTreeView.SeekAlertSource(azureContextUSCommercial.AzureSubscription.ArmTargetManagedDisks[0]);
            Assert.IsTrue(targetTreeView.SelectedNode != null, "Selected Node is null");
            Assert.IsTrue(targetTreeView.SelectedNode.Tag != null, "Selected Node Tag is null");
            Assert.IsTrue(targetTreeView.SelectedNode.Tag.GetType() == azureContextUSCommercial.AzureSubscription.ArmTargetManagedDisks[0].GetType(), "Object type mismatch");
            Assert.IsTrue(targetTreeView.SelectedNode.Tag == azureContextUSCommercial.AzureSubscription.ArmTargetManagedDisks[0], "Not the correct object");

            await targetTreeView.AddMigrationTarget(azureContextUSCommercial.AzureSubscription.ArmTargetNetworkSecurityGroups[0]);

            targetTreeView.SeekAlertSource(azureContextUSCommercial.AzureSubscription.ArmTargetNetworkSecurityGroups[0]);
            Assert.IsTrue(targetTreeView.SelectedNode != null, "Selected Node is null");
            Assert.IsTrue(targetTreeView.SelectedNode.Tag != null, "Selected Node Tag is null");
            Assert.IsTrue(targetTreeView.SelectedNode.Tag.GetType() == azureContextUSCommercial.AzureSubscription.ArmTargetNetworkSecurityGroups[0].GetType(), "Object type mismatch");
            Assert.IsTrue(targetTreeView.SelectedNode.Tag == azureContextUSCommercial.AzureSubscription.ArmTargetNetworkSecurityGroups[0], "Not the correct object");
        }
Exemplo n.º 35
0
 /// <summary>
 /// Returns a SharePoint ClientContext using Azure Active Directory authentication. This requires that you have a Azure AD Native Application registered. The user will be prompted for authentication.
 /// </summary>
 /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param>
 /// <param name="clientId">The Azure AD Native Application Client ID</param>
 /// <param name="redirectUrl">The Azure AD Native Application Redirect Uri as a string</param>
 /// <param name="tokenCache">Optional token cache. If not specified an in-memory token cache will be used</param>
 /// <param name="environment">SharePoint environment being used</param>
 /// <returns>Client context object</returns>
 public ClientContext GetAzureADNativeApplicationAuthenticatedContext(string siteUrl, string clientId, string redirectUrl, TokenCache tokenCache = null, AzureEnvironment environment = AzureEnvironment.Production)
 {
     return(GetAzureADNativeApplicationAuthenticatedContext(siteUrl, clientId, new Uri(redirectUrl), tokenCache, environment));
 }
Exemplo n.º 36
0
        private IEnumerable <AzureSubscription> ListSubscriptionsFromServerForAllAccounts(AzureEnvironment environment)
        {
            // Get all AD accounts and iterate
            var accountNames = Profile.Accounts.Keys;

            List <AzureSubscription> subscriptions = new List <AzureSubscription>();

            foreach (var accountName in accountNames.ToArray())
            {
                var account = Profile.Accounts[accountName];

                if (account.Type != AzureAccount.AccountType.Certificate)
                {
                    subscriptions.AddRange(ListSubscriptionsFromServer(ref account, environment, null, ShowDialog.Never));
                }

                AddOrSetAccount(account);
            }

            if (subscriptions.Any())
            {
                return(subscriptions);
            }
            else
            {
                return(new AzureSubscription[0]);
            }
        }
Exemplo n.º 37
0
        /// <summary>
        /// Returns a SharePoint ClientContext using Azure Active Directory App Only Authentication. This requires that you have a certificated created, and updated the key credentials key in the application manifest in the azure AD accordingly.
        /// </summary>
        /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param>
        /// <param name="clientId">The Azure AD Application Client ID</param>
        /// <param name="tenant">The Azure AD Tenant, e.g. mycompany.onmicrosoft.com</param>
        /// <param name="storeName">The name of the store for the certificate</param>
        /// <param name="storeLocation">The location of the store for the certificate</param>
        /// <param name="thumbPrint">The thumbprint of the certificate to locate in the store</param>
        /// <param name="environment">SharePoint environment being used</param>
        /// <returns>ClientContext being used</returns>
        public ClientContext GetAzureADAppOnlyAuthenticatedContext(string siteUrl, string clientId, string tenant, StoreName storeName, StoreLocation storeLocation, string thumbPrint, AzureEnvironment environment = AzureEnvironment.Production)
        {
            var cert = Utilities.X509CertificateUtility.LoadCertificate(storeName, storeLocation, thumbPrint);

            return(GetAzureADAppOnlyAuthenticatedContext(siteUrl, clientId, tenant, cert, environment));
        }
Exemplo n.º 38
0
        private IEnumerable <AzureSubscription> ListSubscriptionsFromServer(ref AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
        {
            try
            {
                if (!account.IsPropertySet(AzureAccount.Property.Tenants))
                {
                    LoadAccountTenants(ref account, environment, password, promptBehavior);
                }
            }
            catch (AadAuthenticationException aadEx)
            {
                WriteOrThrowAadExceptionMessage(aadEx);
                return(new AzureSubscription[0]);
            }

            try
            {
                List <AzureSubscription> mergedSubscriptions = MergeSubscriptions(
                    ListServiceManagementSubscriptions(ref account, environment, password, ShowDialog.Never).ToList(),
                    ListResourceManagerSubscriptions(ref account, environment, password, ShowDialog.Never).ToList());

                // Set user ID
                foreach (var subscription in mergedSubscriptions)
                {
                    subscription.Environment = environment.Name;
                    subscription.Account     = account.Id;
                    account.SetOrAppendProperty(AzureAccount.Property.Subscriptions, subscription.Id.ToString());
                }

                if (mergedSubscriptions.Any())
                {
                    return(mergedSubscriptions);
                }
                else
                {
                    return(new AzureSubscription[0]);
                }
            }
            catch (AadAuthenticationException aadEx)
            {
                WriteOrThrowAadExceptionMessage(aadEx);
                return(new AzureSubscription[0]);
            }
        }
Exemplo n.º 39
0
        /// <summary>
        /// Returns a SharePoint ClientContext using Azure Active Directory App Only Authentication. This requires that you have a certificated created, and updated the key credentials key in the application manifest in the azure AD accordingly.
        /// </summary>
        /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param>
        /// <param name="clientId">The Azure AD Application Client ID</param>
        /// <param name="tenant">The Azure AD Tenant, e.g. mycompany.onmicrosoft.com</param>
        /// <param name="certificatePath">The path to the certificate (*.pfx) file on the file system</param>
        /// <param name="certificatePassword">Password to the certificate</param>
        /// <param name="environment">SharePoint environment being used</param>
        /// <returns>Client context object</returns>
        public ClientContext GetAzureADAppOnlyAuthenticatedContext(string siteUrl, string clientId, string tenant, string certificatePath, SecureString certificatePassword, AzureEnvironment environment = AzureEnvironment.Production)
        {
            var certfile         = System.IO.File.OpenRead(certificatePath);
            var certificateBytes = new byte[certfile.Length];

            certfile.Read(certificateBytes, 0, (int)certfile.Length);
            var cert = new X509Certificate2(
                certificateBytes,
                certificatePassword,
                X509KeyStorageFlags.Exportable |
                X509KeyStorageFlags.MachineKeySet |
                X509KeyStorageFlags.PersistKeySet);

            return(GetAzureADAppOnlyAuthenticatedContext(siteUrl, clientId, tenant, cert, environment));
        }
Exemplo n.º 40
0
        private AzureEnvironment MergeEnvironmentProperties(AzureEnvironment environment1, AzureEnvironment environment2)
        {
            if (environment1 == null || environment2 == null)
            {
                throw new ArgumentNullException("environment1");
            }
            if (environment1.Name != environment2.Name)
            {
                throw new ArgumentException("Subscription Ids do not match.");
            }
            AzureEnvironment mergedEnvironment = new AzureEnvironment
            {
                Name = environment1.Name
            };

            // Merge all properties
            foreach (AzureEnvironment.Endpoint property in Enum.GetValues(typeof(AzureEnvironment.Endpoint)))
            {
                string propertyValue = environment1.GetEndpoint(property) ?? environment2.GetEndpoint(property);
                if (propertyValue != null)
                {
                    mergedEnvironment.Endpoints[property] = propertyValue;
                }
            }

            return(mergedEnvironment);
        }
Exemplo n.º 41
0
 /// <summary>
 /// Returns an app only ClientContext object
 /// </summary>
 /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param>
 /// <param name="appId">Application ID which is requesting the ClientContext object</param>
 /// <param name="appSecret">Application secret of the Application which is requesting the ClientContext object</param>
 /// <param name="environment">SharePoint environment being used</param>
 /// <returns>ClientContext to be used by CSOM code</returns>
 public ClientContext GetAppOnlyAuthenticatedContext(string siteUrl, string appId, string appSecret, AzureEnvironment environment = AzureEnvironment.Production)
 {
     return(GetAppOnlyAuthenticatedContext(siteUrl, TokenHelper.GetRealmFromTargetUrl(new Uri(siteUrl)), appId, appSecret, GetAzureADACSEndPoint(environment), GetAzureADACSEndPointPrefix(environment)));
 }
Exemplo n.º 42
0
 public AzureEnvironmentSource(AzureEnvironment currentEnvironment)
 {
     CurrentEnvironment = currentEnvironment;
 }