public static async Task <TModel> RunAsync <TModel>( Client client, IParameters <TModel> parameters, IAsyncCmdlet asyncCmdlet, CancellationToken cancellationToken) where TModel : class { // create a DAG of configs. var config = await parameters.CreateConfigAsync(); // reade current Azure state. var current = await config.GetStateAsync(client, cancellationToken); // update location. parameters.Location = current.UpdateLocation(parameters.Location, config); // update a DAG of configs. config = await parameters.CreateConfigAsync(); var engine = new SdkEngine(client.SubscriptionId); var target = config.GetTargetState(current, engine, parameters.Location); // apply target state var newState = await config.UpdateStateAsync( client, target, cancellationToken, new ShouldProcess(asyncCmdlet), asyncCmdlet.ReportTaskProgress); return(newState.Get(config) ?? current.Get(config)); }
/// <summary> /// Called, when scanner sends a beacon event. If the background task is registered, /// it will resolve the actions and we do nothing here. /// </summary> /// <param name="sender"></param> /// <param name="e">The beacon event.</param> private async void OnBeaconEventAsync(object sender, BeaconEventArgs e) { if (!IsBackgroundTaskRegistered) { await SdkEngine.ResolveBeaconAction(e); } }
public async Task ResolveMultipleAction() { LayoutManager layoutManager = (LayoutManager)ServiceManager.LayoutManager; await layoutManager.VerifyLayoutAsync(true); SdkEngine engine = new SdkEngine(false); await engine.InitializeAsync(); TaskCompletionSource <IList <BeaconAction> > action = new TaskCompletionSource <IList <BeaconAction> >(); IList <BeaconAction> list = new List <BeaconAction>(); engine.BeaconActionResolved += (sender, args) => { list.Add(args); if (list.Count >= 3) { action.TrySetResult(list); } }; await engine.ResolveBeaconAction(new BeaconEventArgs() { Beacon = new Beacon() { Id1 = "7367672374000000ffff0000ffff0003", Id2 = 48869, Id3 = 21321 }, EventType = BeaconEventType.Enter }); IList <BeaconAction> result = await action.Task; Assert.AreEqual(4, result.Count, "Not 4 action found"); }
/// <summary> /// Constructor. /// </summary> private SDKManager() { SdkEngine = new SdkEngine(true); Status = new SdkStatus(); _backgroundTaskManager = new BackgroundTaskManager(); _backgroundTaskManager.RegisterOnProgressEventHandler(); }
public async Task ResolveBackgroundBeaconsSingleAction() { LayoutManager layoutManager = (LayoutManager)ServiceManager.LayoutManager; await layoutManager.VerifyLayoutAsync(true); SdkEngine engine = new SdkEngine(false); await engine.InitializeAsync(); BeaconAction orgAction = layoutManager.Layout.ResolvedActions.FirstOrDefault(ra => ra.BeaconAction.Uuid == "9ded63644e424d758b0218f7c70f2473").BeaconAction; TaskCompletionSource <BeaconAction> action = new TaskCompletionSource <BeaconAction>(); engine.BeaconActionResolved += (sender, args) => { action.SetResult(args); }; await engine.ResolveBeaconAction(new BeaconEventArgs() { Beacon = new Beacon() { Id1 = "7367672374000000ffff0000ffff0004", Id2 = 39178, Id3 = 30929 }, EventType = BeaconEventType.Enter }); BeaconAction result = await action.Task; Assert.AreEqual(orgAction, result, "action not found"); }
/// <summary> /// Initializes the SDK using the given configuration. The scanner can be used separately, but /// the resolving beacon actions cannot be done unless the SDK is initialized. /// If background task is enabled, this method check if there are updates for the /// background task filters available and updates them if so. /// </summary> public async Task InitializeAsync(SdkConfiguration configuration) { Status.IsApiKeyValid = false; _logger.Debug("InitializeAsync"); Configuration = configuration; SdkEngine.Configuration = configuration; if (!IsInitialized) { await SdkEngine.InitializeAsync(); await InitializeSettingsAsync(); Status.IsApiKeyValid = ServiceManager.LayoutManager.IsLayoutValid; Scanner.StatusChanged += OnScannerStatusChanged; Scanner.BeaconEvent += OnBeaconEventAsync; } if (SdkData.BackgroundTaskEnabled) { _logger.Debug("InitializeAsync#InitializeBackgground"); await UpdateBackgroundTaskIfNeededAsync(); } if (configuration.AutoStartScanner) { StartScanner(); } }
/// <summary> /// Finishes background processing and releases all resources. /// </summary> public void Dispose() { try { SdkEngine.BeaconActionResolved -= OnBeaconActionResolvedAsync; } finally { SdkEngine.Dispose(); } }
/// <summary> /// Processes the delayed actions, executes them as necessary and sends history statistics. /// </summary> public async Task ProcessDelayedActionsAsync(bool flushHistory = true) { await SdkEngine.ProcessDelayedActionsAsync(); // if (flushHistory) // { await SdkEngine.FlushHistory(); // } Finished?.Invoke(this, BackgroundWorkerType.TimedWorker); }
/// <summary> /// Initializes BackgroundEngine. /// </summary> public async Task InitializeAsync() { await SdkEngine.InitializeAsync(); AppSettings = await ServiceManager.SettingsManager.GetSettings(); //TODO verfiy if (BackgroundTaskManager.CheckIfBackgroundFilterUpdateIsRequired()) { ToastNotification toastNotification = NotificationUtils.CreateToastNotification("New beacon signature available", "Launch the application to update"); NotificationUtils.ShowToastNotification(toastNotification); } }
/// <summary> /// De-initializes the SDK. /// </summary> /// <param name="stopScanner">If true, will stop scanner if running.</param> public void Deinitialize(bool stopScanner) { if (IsInitialized) { if (stopScanner) { StopScanner(); } SdkEngine.Dispose(); } AppSettings = null; Dispose(); }
public async Task UpdateExitTimeoutTest() { SdkEngine engine = new SdkEngine(true); await engine.InitializeAsync(); AppSettings appSettings = engine.AppSettings; Assert.AreEqual((ulong)123, appSettings.BeaconExitTimeout); Assert.AreEqual((ulong)123, engine.Resolver.BeaconExitTimeout); ((MockApiConnection)ServiceManager.ApiConnction).MockSettings = "{\"revision\":0,\"settings\":{\"scanner.backgroundWaitTime\":120000, \"scanner.exitTimeoutMillis\":123000, \"network.historyUploadInterval\":321}}"; ((SettingsManager)ServiceManager.SettingsManager).OnTimerTick(null); appSettings = engine.AppSettings; Assert.AreEqual((ulong)123000, appSettings.BeaconExitTimeout); Assert.AreEqual((ulong)123000, engine.Resolver.BeaconExitTimeout); }
/// <summary> /// Resolves beacons, which triggered the background task. /// </summary> public async Task ResolveBeaconActionsAsync(List <Beacon> beacons, int outOfRangeDb) { Logger.Trace("ResolveBeaconActionsAsync Count: " + beacons.Count); Beacons = beacons; if (Beacons.Count > 0) { await AddBeaconsToBeaconArgsAsync(outOfRangeDb); } if (_beaconArgs.Count > 0) { // Resolve new events foreach (var beaconArg in _beaconArgs) { await SdkEngine.ResolveBeaconAction(beaconArg); } } Finished?.Invoke(this, BackgroundWorkerType.AdvertisementWorker); }
public async Task TestSilentCampaign() { ((MockApiConnection)ServiceManager.ApiConnction).LayoutFile = "mock/mock_silent_layout.json"; ServiceManager.ReadOnlyForTests = false; MockStorage storage = new MockStorage(); ServiceManager.StorageService = new StorageService() { Storage = storage }; ServiceManager.ReadOnlyForTests = true; SdkEngine engine = new SdkEngine(false); await engine.InitializeAsync(); TaskCompletionSource <bool> action = new TaskCompletionSource <bool>(); engine.BeaconActionResolved += (sender, args) => { action.SetResult(true); }; await engine.ResolveBeaconAction(new BeaconEventArgs() { Beacon = new Beacon() { Id1 = "7367672374000000ffff0000ffff4321", Id2 = 39178, Id3 = 30929 }, EventType = BeaconEventType.Enter }); if (await Task.WhenAny(action.Task, Task.Delay(500)) == action.Task) { Assert.Fail("no action should fired"); } else { Assert.AreEqual(1, storage.UndeliveredActions.Count, "Not 1 undlivered action"); Assert.AreEqual(1, storage.UndeliveredEvents.Count, "Not 1 undlivered event"); } }
public async Task ResolveSingleActionNoResult() { LayoutManager layoutManager = (LayoutManager)ServiceManager.LayoutManager; await layoutManager.VerifyLayoutAsync(true); SdkEngine engine = new SdkEngine(false); await engine.InitializeAsync(); TaskCompletionSource <IList <BeaconAction> > action = new TaskCompletionSource <IList <BeaconAction> >(); IList <BeaconAction> list = new List <BeaconAction>(); engine.BeaconActionResolved += (sender, args) => { list.Add(args); if (list.Count >= 3) { action.SetResult(list); } }; await engine.ResolveBeaconAction(new BeaconEventArgs() { Beacon = new Beacon() { Id1 = "7367672374000000ffff0000ffff1234", Id2 = 39178, Id3 = 30929 }, EventType = BeaconEventType.Enter }); if (await Task.WhenAny(action.Task, Task.Delay(500)) == action.Task) { Assert.AreEqual(0, action.Task.Result, "Not 0 action found"); } else { //timeout is fine } }
async Task StrategyExecuteCmdletAsync(IAsyncCmdlet asyncCmdlet) { ResourceGroupName = ResourceGroupName ?? Name; VirtualNetworkName = VirtualNetworkName ?? Name; SubnetName = SubnetName ?? Name; PublicIpAddressName = PublicIpAddressName ?? Name; SecurityGroupName = SecurityGroupName ?? Name; var imageAndOsType = new ImageAndOsType(OperatingSystemTypes.Windows, null); var resourceGroup = ResourceGroupStrategy.CreateResourceGroupConfig(ResourceGroupName); var virtualNetwork = resourceGroup.CreateVirtualNetworkConfig( name: VirtualNetworkName, addressPrefix: AddressPrefix); var subnet = virtualNetwork.CreateSubnet(SubnetName, SubnetAddressPrefix); var publicIpAddress = resourceGroup.CreatePublicIPAddressConfig( name: PublicIpAddressName, getDomainNameLabel: () => DomainNameLabel, allocationMethod: AllocationMethod); var networkSecurityGroup = resourceGroup.CreateNetworkSecurityGroupConfig( name: SecurityGroupName, openPorts: OpenPorts, getOsType: () => imageAndOsType.OsType); var networkInterface = resourceGroup.CreateNetworkInterfaceConfig( Name, subnet, publicIpAddress, networkSecurityGroup); var availabilitySet = AvailabilitySetName == null ? null : resourceGroup.CreateAvailabilitySetConfig(name: AvailabilitySetName); ResourceConfig <VirtualMachine> virtualMachine = null; if (DiskFile == null) { virtualMachine = resourceGroup.CreateVirtualMachineConfig( name: Name, networkInterface: networkInterface, getImageAndOsType: () => imageAndOsType, adminUsername: Credential.UserName, adminPassword: new NetworkCredential(string.Empty, Credential.Password).Password, size: Size, availabilitySet: availabilitySet); } else { var resourceClient = AzureSession.Instance.ClientFactory.CreateArmClient <ResourceManagementClient>(DefaultProfile.DefaultContext, AzureEnvironment.Endpoint.ResourceManager); if (!resourceClient.ResourceGroups.CheckExistence(ResourceGroupName)) { var st0 = resourceClient.ResourceGroups.CreateOrUpdate(ResourceGroupName, new ResourceGroup { Location = Location, Name = ResourceGroupName }); } imageAndOsType = new ImageAndOsType( Linux ? OperatingSystemTypes.Linux : OperatingSystemTypes.Windows, null); var storageClient = AzureSession.Instance.ClientFactory.CreateArmClient <StorageManagementClient>(DefaultProfile.DefaultContext, AzureEnvironment.Endpoint.ResourceManager); var st1 = storageClient.StorageAccounts.Create( ResourceGroupName, Name, new StorageAccountCreateParameters { #if !NETSTANDARD AccountType = AccountType.PremiumLRS, #else Sku = new Microsoft.Azure.Management.Storage.Models.Sku { Name = SkuName.PremiumLRS }, #endif Location = Location }); var filePath = new FileInfo(SessionState.Path.GetUnresolvedProviderPathFromPSPath(DiskFile)); using (var vds = new VirtualDiskStream(filePath.FullName)) { if (vds.DiskType == DiskType.Fixed) { long divisor = Convert.ToInt64(Math.Pow(2, 9)); long rem = 0; Math.DivRem(filePath.Length, divisor, out rem); if (rem != 0) { throw new ArgumentOutOfRangeException( "filePath", string.Format("Given vhd file '{0}' is a corrupted fixed vhd", filePath)); } } } var storageAccount = storageClient.StorageAccounts.GetProperties(ResourceGroupName, Name); BlobUri destinationUri = null; BlobUri.TryParseUri( new Uri(string.Format( "{0}{1}/{2}{3}", storageAccount.PrimaryEndpoints.Blob, ResourceGroupName.ToLower(), Name.ToLower(), ".vhd")), out destinationUri); if (destinationUri == null || destinationUri.Uri == null) { throw new ArgumentNullException("destinationUri"); } var storageCredentialsFactory = new StorageCredentialsFactory( this.ResourceGroupName, storageClient, DefaultContext.Subscription); var parameters = new UploadParameters(destinationUri, null, filePath, true, 2) { Cmdlet = this, BlobObjectFactory = new CloudPageBlobObjectFactory(storageCredentialsFactory, TimeSpan.FromMinutes(1)) }; if (!string.Equals( Environment.GetEnvironmentVariable("AZURE_TEST_MODE"), "Playback", StringComparison.OrdinalIgnoreCase)) { var st2 = VhdUploaderModel.Upload(parameters); } var disk = resourceGroup.CreateManagedDiskConfig( name: Name, sourceUri: destinationUri.Uri.ToString() ); virtualMachine = resourceGroup.CreateVirtualMachineConfig( name: Name, networkInterface: networkInterface, osType: imageAndOsType.OsType, disk: disk, size: Size, availabilitySet: availabilitySet); } var client = new Client(DefaultProfile.DefaultContext); // get current Azure state var current = await virtualMachine.GetStateAsync(client, new CancellationToken()); Location = current.UpdateLocation(Location, virtualMachine); // generate a domain name label if it's not specified. DomainNameLabel = await PublicIPAddressStrategy.UpdateDomainNameLabelAsync( domainNameLabel : DomainNameLabel, name : Name, location : Location, client : client); var fqdn = PublicIPAddressStrategy.Fqdn(DomainNameLabel, Location); if (DiskFile == null) { imageAndOsType = await client.UpdateImageAndOsTypeAsync(ImageName, Location); } // create target state var engine = new SdkEngine(client.SubscriptionId); var target = virtualMachine.GetTargetState(current, engine, Location); if (target.Get(availabilitySet) != null) { throw new InvalidOperationException("Availability set doesn't exist."); } // apply target state var newState = await virtualMachine .UpdateStateAsync( client, target, new CancellationToken(), new ShouldProcess(asyncCmdlet), asyncCmdlet.ReportTaskProgress); var result = newState.Get(virtualMachine); if (result == null) { result = current.Get(virtualMachine); } if (result != null) { var psResult = ComputeAutoMapperProfile.Mapper.Map <PSVirtualMachine>(result); psResult.FullyQualifiedDomainName = fqdn; var connectionString = imageAndOsType.GetConnectionString( fqdn, Credential.UserName); asyncCmdlet.WriteVerbose( Resources.VirtualMachineUseConnectionString, connectionString); asyncCmdlet.WriteObject(psResult); } }
/// <summary> /// Sends all pending history elements. /// </summary> public async Task FlushHistory() { await SdkEngine.FlushHistory(); }
public async Task CreateWithSimpleParameters(ICmdletAdapter adapter) { ResourceGroupName = ResourceGroupName ?? Name; AppServicePlan = AppServicePlan ?? Name; string planResourceGroup = ResourceGroupName; string planName = AppServicePlan; var rgStrategy = ResourceGroupStrategy.CreateResourceGroupConfig(ResourceGroupName); ResourceConfig <ResourceGroup> planRG = rgStrategy; if (MyInvocation.BoundParameters.ContainsKey(nameof(AppServicePlan))) { if (!TryGetServerFarmFromResourceId(AppServicePlan, out planResourceGroup, out planName)) { planResourceGroup = ResourceGroupName; planName = AppServicePlan; } planRG = ResourceGroupStrategy.CreateResourceGroupConfig(planResourceGroup); } else { var farm = await GetDefaultServerFarm(Location); if (farm != null) { planResourceGroup = farm.ResourceGroup; planName = farm.Name; planRG = ResourceGroupStrategy.CreateResourceGroupConfig(planResourceGroup); } } var farmStrategy = planRG.CreateServerFarmConfig(planResourceGroup, planName); var siteStrategy = rgStrategy.CreateSiteConfig(farmStrategy, Name); var client = new WebClient(DefaultContext); var current = await siteStrategy.GetStateAsync(client, default(CancellationToken)); if (!MyInvocation.BoundParameters.ContainsKey(nameof(Location))) { Location = current.GetLocation(siteStrategy) ?? "East US"; } var engine = new SdkEngine(DefaultContext.Subscription.Id); var target = siteStrategy.GetTargetState(current, engine, Location); var endState = await siteStrategy.UpdateStateAsync(client, target, default(CancellationToken), adapter, adapter.ReportTaskProgress); var output = endState.Get(siteStrategy) ?? current.Get(siteStrategy); output.SiteConfig = WebsitesClient.WrappedWebsitesClient.WebApps().GetConfiguration(output.ResourceGroup, output.Name).ConvertToSiteConfig(); try { var appSettings = WebsitesClient.WrappedWebsitesClient.WebApps().ListApplicationSettings(output.ResourceGroup, output.Name); output.SiteConfig.AppSettings = appSettings.Properties.Select(s => new NameValuePair { Name = s.Key, Value = s.Value }).ToList(); var connectionStrings = WebsitesClient.WrappedWebsitesClient.WebApps().ListConnectionStrings(output.ResourceGroup, output.Name); output.SiteConfig.ConnectionStrings = connectionStrings .Properties .Select(s => new ConnStringInfo() { Name = s.Key, ConnectionString = s.Value.Value, Type = s.Value.Type }).ToList(); } catch { //ignore if this call fails as it will for reader RBAC } string userName = null, password = null; try { var scmHostName = output.EnabledHostNames.FirstOrDefault(s => s.Contains(".scm.")); if (!string.IsNullOrWhiteSpace(scmHostName)) { var profile = await WebsitesClient.WrappedWebsitesClient.WebApps.ListPublishingProfileXmlWithSecretsAsync(output.ResourceGroup, output.Name, new CsmPublishingProfileOptions { Format = "WebDeploy" }); var doc = new XmlDocument(); doc.Load(profile); userName = doc.SelectSingleNode("//publishProfile[@publishMethod=\"MSDeploy\"]/@userName").Value; password = doc.SelectSingleNode("//publishProfile[@publishMethod=\"MSDeploy\"]/@userPWD").Value; var newOutput = new PSSite(output) { GitRemoteUri = $"https://{scmHostName}", GitRemoteUsername = userName, GitRemotePassword = SecureStringExtensions.ConvertToSecureString(password) }; output = newOutput; var git = new GitCommand(adapter.SessionState.Path, GitRepositoryPath); var repository = await git.VerifyGitRepository(); if (repository != null) { if (!await git.CheckExistence()) { adapter.WriteWarningAsync(git.InstallationInstructions); } else if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password)) { await git.AddRemoteRepository("azure", $"https://{userName}:{password}@{scmHostName}"); adapter.WriteVerboseAsync(Microsoft.Azure.Commands.WebApps.Properties.Resources.GitRemoteMessage); newOutput.GitRemoteName = "azure"; } } } } catch (Exception exception) { // do not write errors for problems with adding git repository var repoPath = GitRepositoryPath ?? adapter?.SessionState?.Path?.CurrentFileSystemLocation?.Path; adapter.WriteWarningAsync(String.Format(Microsoft.Azure.Commands.WebApps.Properties.Resources.GitRemoteAddFailure, repoPath, exception.Message)); } adapter.WriteObjectAsync(output); }
public BackgroundEngine() { SdkEngine = new SdkEngine(false); _beaconArgs = new List <BeaconEventArgs>(); SdkEngine.BeaconActionResolved += OnBeaconActionResolvedAsync; }
public void TestDependencyGraph() { // resource group var rgStrategy = ResourceStrategy.Create <Model, Client, Client>( ResourceType.ResourceGroup, c => c, async(c, m) => null, async(c, m) => new Model(), m => m.Location, (m, location) => m.Location = location, m => 0, false); var rgConfig = rgStrategy.CreateResourceConfig(null, "rgname"); var rgConfig2 = rgStrategy.CreateResourceConfig(null, "rgname2"); // resource var resourceStrategy = ResourceStrategy.Create <Model, Client, Client>( new ResourceType("Company.Namespace", "resourceProvider"), c => c, async(c, m) => null, async(c, m) => new Model(), m => m.Location, (m, location) => m.Location = location, m => 0, false); var resource = resourceStrategy.CreateResourceConfig(rgConfig, "res"); // nested resource var rgNestedStrategy = NestedResourceStrategy.Create <NestedModel, Model>( "rgnested", m => m.Nested, (m, list) => m.Nested = list, nm => nm.Name, (nm, name) => nm.Name = name); // add the nested resource to the resource group. var rgNestedConfig = rgConfig.CreateNested(rgNestedStrategy, "rgnestedname"); // nested resource var nestedStrategy = NestedResourceStrategy.Create <NestedModel, Model>( "nested", m => m.Nested, (m, list) => m.Nested = list, nm => nm.Name, (nm, name) => nm.Name = name); // add the nested resource to a resource. var nestedConfig = resource.CreateNested( nestedStrategy, "nestedname", e => new NestedModel { Id = e.GetId(rgConfig2) }); // var engine = new SdkEngine("s"); // empty state. var current = new StateOperationContext(new Client(), new CancellationToken()) .Result; var state = resource.GetTargetState(current, engine, "eastus"); var rgModel = state.Get(rgConfig); Assert.Equal("eastus", rgModel.Location); var rgNestedModel = rgModel.Nested.First() as NestedModel; Assert.Equal("rgnestedname", rgNestedModel.Name); var rgModel2 = state.Get(rgConfig2); Assert.NotNull(rgModel2); }
async Task SimpleParameterSetExecuteCmdlet(IAsyncCmdlet asyncCmdlet) { ResourceGroupName = ResourceGroupName ?? VMScaleSetName; VirtualNetworkName = VirtualNetworkName ?? VMScaleSetName; SubnetName = SubnetName ?? VMScaleSetName; PublicIpAddressName = PublicIpAddressName ?? VMScaleSetName; SecurityGroupName = SecurityGroupName ?? VMScaleSetName; LoadBalancerName = LoadBalancerName ?? VMScaleSetName; FrontendPoolName = FrontendPoolName ?? VMScaleSetName; BackendPoolName = BackendPoolName ?? VMScaleSetName; var imageAndOsType = new ImageAndOsType(OperatingSystemTypes.Windows, null); var resourceGroup = ResourceGroupStrategy.CreateResourceGroupConfig(ResourceGroupName); var publicIpAddress = resourceGroup.CreatePublicIPAddressConfig( name: PublicIpAddressName, getDomainNameLabel: () => DomainNameLabel, allocationMethod: AllocationMethod); var virtualNetwork = resourceGroup.CreateVirtualNetworkConfig( name: VirtualNetworkName, addressPrefix: VnetAddressPrefix); var subnet = virtualNetwork.CreateSubnet(SubnetName, SubnetAddressPrefix); var loadBalancer = resourceGroup.CreateLoadBalancerConfig( name: LoadBalancerName); var frontendIpConfiguration = loadBalancer.CreateFrontendIPConfiguration( name: FrontendPoolName, zones: Zone, publicIpAddress: publicIpAddress); var backendAddressPool = loadBalancer.CreateBackendAddressPool( name: BackendPoolName); if (BackendPort != null) { var LoadBalancingRuleName = LoadBalancerName; foreach (var backendPort in BackendPort) { loadBalancer.CreateLoadBalancingRule( name: LoadBalancingRuleName + backendPort.ToString(), fronendIpConfiguration: frontendIpConfiguration, backendAddressPool: backendAddressPool, frontendPort: backendPort, backendPort: backendPort); } } var inboundNatPools = new List <NestedResourceConfig <InboundNatPool, LoadBalancer> >(); var virtualMachineScaleSet = resourceGroup.CreateVirtualMachineScaleSetConfig( name: VMScaleSetName, subnet: subnet, frontendIpConfigurations: new[] { frontendIpConfiguration }, backendAdressPool: backendAddressPool, inboundNatPools: inboundNatPools, getImageAndOsType: () => imageAndOsType, adminUsername: Credential.UserName, adminPassword: new NetworkCredential(string.Empty, Credential.Password).Password, vmSize: VmSize, instanceCount: InstanceCount, upgradeMode: MyInvocation.BoundParameters.ContainsKey(nameof(UpgradePolicyMode)) ? UpgradePolicyMode : (UpgradeMode?)null); var client = new Client(DefaultProfile.DefaultContext); // get current Azure state var current = await virtualMachineScaleSet.GetStateAsync(client, new CancellationToken()); Location = current.UpdateLocation(Location, virtualMachineScaleSet); imageAndOsType = await client.UpdateImageAndOsTypeAsync(ImageName, Location); NatBackendPort = imageAndOsType.OsType.UpdatePorts(NatBackendPort); var inboundNatPoolName = VMScaleSetName; const int FirstPortRangeStart = 50000; var portRangeStart = FirstPortRangeStart; var PortRangeSize = InstanceCount * 2; foreach (var natBackendPort in NatBackendPort) { inboundNatPools.Add( loadBalancer.CreateInboundNatPool( name: inboundNatPoolName + natBackendPort.ToString(), frontendIpConfiguration: frontendIpConfiguration, frontendPortRangeStart: portRangeStart, frontendPortRangeEnd: portRangeStart + PortRangeSize, backendPort: natBackendPort)); portRangeStart += 2000; } // generate a domain name label if it's not specified. DomainNameLabel = await PublicIPAddressStrategy.UpdateDomainNameLabelAsync( domainNameLabel : DomainNameLabel, name : VMScaleSetName, location : Location, client : client); var fqdn = PublicIPAddressStrategy.Fqdn(DomainNameLabel, Location); var engine = new SdkEngine(client.SubscriptionId); var target = virtualMachineScaleSet.GetTargetState(current, engine, Location); var newState = await virtualMachineScaleSet .UpdateStateAsync( client, target, new CancellationToken(), new ShouldProcess(asyncCmdlet), asyncCmdlet.ReportTaskProgress); var result = newState.Get(virtualMachineScaleSet); if (result == null) { result = current.Get(virtualMachineScaleSet); } if (result != null) { var psObject = new PSVirtualMachineScaleSet(); ComputeAutomationAutoMapperProfile.Mapper.Map(result, psObject); psObject.FullyQualifiedDomainName = fqdn; var port = "<port>"; var connectionString = imageAndOsType.GetConnectionString( fqdn, Credential.UserName, port); var range = FirstPortRangeStart.ToString() + ".." + (FirstPortRangeStart + PortRangeSize).ToString(); asyncCmdlet.WriteVerbose( Resources.VmssUseConnectionString, connectionString); asyncCmdlet.WriteVerbose( Resources.VmssPortRange, port, range); asyncCmdlet.WriteObject(psObject); } }