internal async Task <string> StartVirtualMachineAsync(string name)
        {
            string          returnMessage;
            IVirtualMachine machine = await GetVmByNameAsync(name);

            if (machine == null)
            {
                returnMessage = $"No machine named {name} was found";
            }
            else if (machine.PowerState == PowerState.Deallocated || machine.PowerState == PowerState.Stopped)
            {
#pragma warning disable CS4014 //This will take a while, let it run async and continue no need to await it
                machine.StartAsync();
#pragma warning restore CS4014
                returnMessage = $"{name} is starting, original state was {VmHtmlMaker.FormatPowerState(machine.PowerState)}";
            }
            else if (machine.PowerState == PowerState.Running)
            {
                IPublicIPAddress ipAddress = machine.GetPrimaryPublicIPAddress();
                returnMessage = $"Machine is already running, IP address is {ipAddress.IPAddress}";
            }
            else
            {
                returnMessage = $"No action taken, machine state is: {VmHtmlMaker.FormatPowerState(machine.PowerState)}";
            }

            //_helper.LogMessage("Finished");

            return(returnMessage);
        }
        /**
         * It creates a new Azure virtual machine and it instantiate a Java Docker client.
         * @param azure - instance of Azure
         * @param rgName - name of the Azure resource group to be used when creating a virtual machine
         * @param region - region to be used when creating a virtual machine
         * @return an instance of DockerClient
         */
        public static DockerClient FromNewDockerVM(IAzure azure, String rgName, Region region)
        {
            string dockerVMName     = SdkContext.RandomResourceName("dockervm", 15);
            string publicIPDnsLabel = SdkContext.RandomResourceName("pip", 10);
            string vmUserName       = "******";
            string vmPassword       = Utilities.CreatePassword();

            // Could not find a Docker environment; presume that there is no local Docker engine running and
            //    attempt to configure a Docker engine running inside a new Azure virtual machine
            Utilities.Log("Creating an Azure virtual machine running Docker");

            IVirtualMachine dockerVM = azure.VirtualMachines.Define(dockerVMName)
                                       .WithRegion(region)
                                       .WithExistingResourceGroup(rgName)
                                       .WithNewPrimaryNetwork("10.0.0.0/28")
                                       .WithPrimaryPrivateIPAddressDynamic()
                                       .WithNewPrimaryPublicIPAddress(publicIPDnsLabel)
                                       .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                                       .WithRootUsername(vmUserName)
                                       .WithRootPassword(vmPassword)
                                       .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                       .Create();

            Utilities.Log("Created Azure Virtual Machine: " + dockerVM.Id);

            // Get the IP of the Docker host
            INicIPConfiguration nicIPConfiguration = dockerVM.GetPrimaryNetworkInterface().PrimaryIPConfiguration;
            IPublicIPAddress    publicIp           = nicIPConfiguration.GetPublicIPAddress();
            string dockerHostIP = publicIp.IPAddress;

            DockerClient dockerClient = InstallDocker(dockerHostIP, vmUserName, vmPassword);

            return(dockerClient);
        }
        public override ILoadBalancer UpdateResource(ILoadBalancer resource)
        {
            String backendName  = resource.Backends.Values.First().Name;
            String frontendName = resource.Frontends.Values.First().Name;

            var nics = new List <INetworkInterface>();

            foreach (string nicId in resource.Backends[backendName].BackendNicIPConfigurationNames.Keys)
            {
                nics.Add(networks.Manager.NetworkInterfaces.GetById(nicId));
            }
            INetworkInterface nic1 = nics[0];
            INetworkInterface nic2 = nics[1];

            // Remove the NIC associations
            nic1.Update()
            .WithoutLoadBalancerBackends()
            .WithoutLoadBalancerInboundNatRules()
            .Apply();
            Assert.Empty(nic1.PrimaryIPConfiguration.ListAssociatedLoadBalancerBackends());

            nic2.Update()
            .WithoutLoadBalancerBackends()
            .WithoutLoadBalancerInboundNatRules()
            .Apply();
            Assert.Empty(nic2.PrimaryIPConfiguration.ListAssociatedLoadBalancerBackends());

            // Update the load balancer
            var existingPips     = loadBalancerHelper.EnsurePIPs(pips);
            IPublicIPAddress pip = resource.Manager.PublicIPAddresses.GetByResourceGroup(
                loadBalancerHelper.GroupName,
                loadBalancerHelper.PipNames[1]);

            resource = resource.Update()
                       .UpdatePublicFrontend(frontendName)
                       .WithExistingPublicIPAddress(pip)
                       .Parent()
                       .WithoutLoadBalancingRule("rule1")
                       .WithoutInboundNatRule("natrule1")
                       .WithTag("tag1", "value1")
                       .WithTag("tag2", "value2")
                       .Apply();

            Assert.True(resource.Tags.ContainsKey("tag1"));
            Assert.Empty(resource.InboundNatRules.Values);

            // Verify frontends
            Assert.Single(resource.PublicFrontends.Values);
            Assert.Empty(resource.PrivateFrontends.Values);
            Assert.True(resource.Frontends.ContainsKey(frontendName));
            var frontend = resource.Frontends[frontendName];

            Assert.True(frontend.IsPublic);
            var publicFrontend = (ILoadBalancerPublicFrontend)frontend;

            Assert.Equal(pip.Id, publicFrontend.PublicIPAddressId, ignoreCase: true);

            return(resource);
        }
        public Task <INetworkInterface> CreateNetworkInterfaceAsync(string nicBase, Region location,
                                                                    string groupName, string subNet, INetwork network,
                                                                    IPublicIPAddress publicIPAddress, INetworkSecurityGroup nsg, int i = 0)
        {
            Console.WriteLine($"Creating {i}th network interface in resource group {groupName}");
            var j        = 0;
            var maxRetry = 5; // 5 times retry is enough

            while (j < maxRetry)
            {
                try
                {
                    if (publicIPAddress != null && nsg != null)
                    {
                        var newNic = _azure.NetworkInterfaces.Define(nicBase + Convert.ToString(i))
                                     .WithRegion(location)
                                     .WithExistingResourceGroup(groupName)
                                     .WithExistingPrimaryNetwork(network)
                                     .WithSubnet(subNet)
                                     .WithPrimaryPrivateIPAddressDynamic()
                                     .WithExistingPrimaryPublicIPAddress(publicIPAddress)
                                     .WithExistingNetworkSecurityGroup(nsg)
                                     .CreateAsync();
                        return(newNic);
                    }
                    else
                    {
                        var newNic = _azure.NetworkInterfaces.Define(nicBase + Convert.ToString(i))
                                     .WithRegion(location)
                                     .WithExistingResourceGroup(groupName)
                                     .WithExistingPrimaryNetwork(network)
                                     .WithSubnet(subNet)
                                     .WithPrimaryPrivateIPAddressDynamic()
                                     .CreateAsync();
                        return(newNic);
                    }
                }
                catch (Exception e)
                {
                    // clear the uncompleted data
                    var allNICs    = _azure.NetworkInterfaces.ListByResourceGroup(groupName);
                    var ids        = new List <string>();
                    var enumerator = allNICs.GetEnumerator();
                    while (enumerator.MoveNext())
                    {
                        ids.Add(enumerator.Current.Id);
                    }
                    _azure.NetworkInterfaces.DeleteByIds(ids);

                    Task.Delay(2000);
                    Util.Log($"error: {e.Message} retry create {i}th nic");
                }
                j++;
            }
            return(null);
        }
Ejemplo n.º 5
0
        public override ILoadBalancer UpdateResource(ILoadBalancer resource)
        {
            ILoadBalancerBackend        backend        = resource.Backends.Values.First();
            ILoadBalancerInboundNatRule natRule        = resource.InboundNatRules.Values.First();
            ILoadBalancerPublicFrontend publicFrontend = (ILoadBalancerPublicFrontend)natRule.Frontend;

            IPublicIPAddress pip = resource.Manager.PublicIPAddresses.Define(loadBalancerHelper.PipNames[1])
                                   .WithRegion(loadBalancerHelper.Region)
                                   .WithExistingResourceGroup(loadBalancerHelper.GroupName)
                                   .WithLeafDomainLabel(loadBalancerHelper.PipNames[1])
                                   .Create();

            resource = resource.Update()
                       .UpdatePublicFrontend(publicFrontend.Name)
                       .WithExistingPublicIPAddress(pip)
                       .Parent()
                       .DefineBackend("backend2")
                       .Attach()
                       .WithoutBackend(backend.Name)
                       .WithoutInboundNatRule("natrule1")
                       .WithTag("tag1", "value1")
                       .WithTag("tag2", "value2")
                       .Apply();

            Assert.True(resource.Tags.ContainsKey("tag1"));

            // Verify frontends
            Assert.Equal(1, resource.Frontends.Count);
            Assert.Equal(1, resource.PublicFrontends.Count);
            Assert.Equal(0, resource.PrivateFrontends.Count);
            Assert.True(resource.Frontends.ContainsKey(publicFrontend.Name));
            var frontend = resource.Frontends[publicFrontend.Name];

            Assert.True(frontend.IsPublic);
            publicFrontend = (ILoadBalancerPublicFrontend)frontend;
            Assert.Equal(pip.Id, publicFrontend.PublicIPAddressId, ignoreCase: true);
            Assert.Equal(0, publicFrontend.LoadBalancingRules.Count);

            // Verify probes
            Assert.Equal(0, resource.TcpProbes.Count);
            Assert.Equal(0, resource.HttpProbes.Count);

            // Verify backends
            Assert.True(resource.Backends.ContainsKey("backend2"));
            Assert.True(!resource.Backends.ContainsKey(backend.Name));

            // Verify NAT rules
            Assert.Equal(0, resource.InboundNatRules.Count);

            // Verify load balancing rules
            Assert.Equal(0, resource.LoadBalancingRules.Count);

            return(resource);
        }
 ///GENMHASH:DAC7C95BFBE152B599EE795AE6AFEF02:B63A71AAE81F86EEB4A9F4709EF1253D
 internal ILoadBalancerPublicFrontend FindFrontendByPublicIPAddress(IPublicIPAddress publicIPAddress)
 {
     if (publicIPAddress == null)
     {
         return(null);
     }
     else
     {
         return(FindFrontendByPublicIPAddress(publicIPAddress.Id));
     }
 }
        public override IApplicationGateway CreateResource(IApplicationGateways resources)
        {
            // Create an application gateway
            try
            {
                string           appPublicIp = TestUtilities.GenerateName("pip");
                IPublicIPAddress pip         = resources.Manager.PublicIPAddresses
                                               .Define(appPublicIp)
                                               .WithRegion(applicationGatewayHelper.Region)
                                               .WithNewResourceGroup(applicationGatewayHelper.GroupName)
                                               .WithSku(PublicIPSkuType.Standard)
                                               .WithStaticIP()
                                               .Create();

                Assert.NotNull(pip);

                resources.Define(applicationGatewayHelper.AppGatewayName)
                .WithRegion(applicationGatewayHelper.Region)
                .WithExistingResourceGroup(applicationGatewayHelper.GroupName)

                // Request routing rules
                // Request routing rules
                .DefineRequestRoutingRule("rule1")
                .FromPublicFrontend()
                .FromFrontendHttpsPort(443)
                .WithSslCertificateFromPfxFile(new FileInfo(Path.Combine("Assets", "myTest._pfx")))
                .WithSslCertificatePassword("Abc123")
                .ToBackendHttpPort(8080)
                .ToBackendIPAddress("11.1.1.1")
                .ToBackendIPAddress("11.1.1.2")
                .Attach()
                .WithExistingPublicIPAddress(pip)
                .WithTier(ApplicationGatewayTier.WAFV2)
                .WithSize(ApplicationGatewaySkuName.WAFV2)
                .WithAutoscale(2, 5)
                .WithWebApplicationFirewall(true, ApplicationGatewayFirewallMode.Prevention)
                .Create();
            }
            catch
            {
            }

            // Get the resource as created so far
            string resourceId = applicationGatewayHelper.CreateResourceId(resources.Manager.SubscriptionId);
            IApplicationGateway appGateway = resources.GetById(resourceId);

            Assert.NotNull(appGateway);
            Assert.Equal(ApplicationGatewayTier.WAFV2, appGateway.Tier);
            Assert.Equal(ApplicationGatewaySkuName.WAFV2, appGateway.Size);
            Assert.Equal <int>(2, appGateway.AutoscaleConfiguration.MinCapacity);
            Assert.Equal <int>(5, appGateway.AutoscaleConfiguration.MaxCapacity.Value);

            return(appGateway);
        }
Ejemplo n.º 8
0
        IPublicIPAddress GetOrCreatePublicIPAddress(IAzure azure, string name, Region location, string groupName)
        {
            IPublicIPAddress publicIPAddress = FindInCollectionOrNull(azure.PublicIPAddresses, "a public IP address", name);

            if (publicIPAddress == null)
            {
                Console.WriteLine("Creating a public IP address...");
                publicIPAddress = azure.PublicIPAddresses.Define(name)
                                  .WithRegion(location)
                                  .WithExistingResourceGroup(groupName)
                                  .WithDynamicIP()
                                  .Create();
            }
            return(publicIPAddress);
        }
Ejemplo n.º 9
0
        public IPublicIPAddress createPublicIpAddress()
        {
            Microsoft.Azure.Management.Fluent.IAzure azureCredentials =
                new AzureCredentialProvider().LoginAzure();

            Console.WriteLine("Creating public IP address...");

            IPublicIPAddress publicIpAddress = azureCredentials.PublicIPAddresses.Define("myPublicIP")
                                               .WithRegion(Region.EuropeNorth)
                                               .WithExistingResourceGroup("sdk-netcore-practices")
                                               .WithDynamicIP()
                                               .Create();

            return(publicIpAddress);
        }
 internal void Print(IPublicIPAddress resource)
 {
     TestHelper.WriteLine(new StringBuilder().Append("Public IP Address: ").Append(resource.Id)
                          .Append("Name: ").Append(resource.Name)
                          .Append("\n\tResource group: ").Append(resource.ResourceGroupName)
                          .Append("\n\tRegion: ").Append(resource.Region)
                          .Append("\n\tTags: ").Append(resource.Tags)
                          .Append("\n\tIP Address: ").Append(resource.IPAddress)
                          .Append("\n\tLeaf domain label: ").Append(resource.LeafDomainLabel)
                          .Append("\n\tFQDN: ").Append(resource.Fqdn)
                          .Append("\n\tReverse FQDN: ").Append(resource.ReverseFqdn)
                          .Append("\n\tIdle timeout (minutes): ").Append(resource.IdleTimeoutInMinutes)
                          .Append("\n\tIP allocation method: ").Append(resource.IPAllocationMethod.ToString())
                          .ToString());
 }
        public static void PrintPIP(IPublicIPAddress resource)
        {
            var info = new StringBuilder().Append("Public IP Address: ").Append(resource.Id)
                       .Append("\n\tName: ").Append(resource.Name)
                       .Append("\n\tResource group: ").Append(resource.ResourceGroupName)
                       .Append("\n\tRegion: ").Append(resource.Region)
                       .Append("\n\tTags: ").Append(resource.Tags)
                       .Append("\n\tIP Address: ").Append(resource.IPAddress)
                       .Append("\n\tLeaf domain label: ").Append(resource.LeafDomainLabel)
                       .Append("\n\tFQDN: ").Append(resource.Fqdn)
                       .Append("\n\tReverse FQDN: ").Append(resource.ReverseFqdn)
                       .Append("\n\tIdle timeout (minutes): ").Append(resource.IdleTimeoutInMinutes)
                       .Append("\n\tIP allocation method: ").Append(resource.IPAllocationMethod)
                       .Append("\n\tIP version: ").Append(resource.Version);

            // Show the associated load balancer if any
            info.Append("\n\tLoad balancer association: ");
            if (resource.HasAssignedLoadBalancer)
            {
                var frontend = resource.GetAssignedLoadBalancerFrontend();
                var lb       = frontend.Parent;
                info.Append("\n\t\tLoad balancer ID: ").Append(lb.Id)
                .Append("\n\t\tFrontend name: ").Append(frontend.Name);
            }
            else
            {
                info.Append("(None)");
            }

            // Show the associated NIC if any
            info.Append("\n\tNetwork interface association: ");
            if (resource.HasAssignedNetworkInterface)
            {
                var nicIP = resource.GetAssignedNetworkInterfaceIPConfiguration();
                var nic   = nicIP.Parent;
                info.Append("\n\t\tNetwork interface ID: ").Append(nic.Id)
                .Append("\n\t\tIP config name: ").Append(nicIP.Name);
            }
            else
            {
                info.Append("(None)");
            }

            TestHelper.WriteLine(info.ToString());
        }
Ejemplo n.º 12
0
        public INetworkInterface createNetworkInterface(INetwork newNetwork, IPublicIPAddress publicIPAddress)
        {
            Microsoft.Azure.Management.Fluent.IAzure azureCredentials =
                new AzureCredentialProvider().LoginAzure();

            Console.WriteLine("Creating Network Interface...");

            INetworkInterface networkInterface = azureCredentials.NetworkInterfaces.Define("myNIC")
                                                 .WithRegion(Region.EuropeNorth)
                                                 .WithExistingResourceGroup("sdk-netcore-practices")
                                                 .WithExistingPrimaryNetwork(newNetwork)
                                                 .WithSubnet("mySubnet")
                                                 .WithPrimaryPrivateIPAddressDynamic()
                                                 .WithExistingPrimaryPublicIPAddress(publicIPAddress)
                                                 .Create();

            return(networkInterface);
        }
Ejemplo n.º 13
0
        INetworkInterface GetOrCreateNetworkInterface(IAzure azure, string name, Region location, string groupName,
                                                      IPublicIPAddress publicIPAddress, INetwork network)
        {
            INetworkInterface networkInterface = FindInCollectionOrNull(azure.NetworkInterfaces, "a network interface", name);

            if (networkInterface == null)
            {
                Console.WriteLine("Creating a network interface...");
                networkInterface = azure.NetworkInterfaces.Define(name)
                                   .WithRegion(location)
                                   .WithExistingResourceGroup(groupName)
                                   .WithExistingPrimaryNetwork(network)
                                   .WithSubnet("mySubnet")
                                   .WithPrimaryPrivateIPAddressDynamic()
                                   .WithExistingPrimaryPublicIPAddress(publicIPAddress)
                                   .Create();
            }
            return(networkInterface);
        }
Ejemplo n.º 14
0
        public async Task GetVmVn()
        {
            var allvms = await azure.VirtualMachines.ListAsync();

            IVirtualMachine targetvm = allvms
                                       .Where(vm => vm.Name == "Annvm")
                                       .SingleOrDefault();

            Console.WriteLine(targetvm?.Id);

            INetworkInterface targetnic = targetvm.GetPrimaryNetworkInterface();

            INicIPConfiguration targetipconfig = targetnic.PrimaryIPConfiguration;

            IPublicIPAddress targetipaddress = targetipconfig.GetPublicIPAddress();

            Console.WriteLine($"IP Address:\t{targetipaddress.IPAddress}");
            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
        }
        string GetVmControlContent(IVirtualMachine machine)
        {
            string           contents   = GetWebContentFile(ChangeStateFormFile);
            string           powerState = FormatPowerState(machine.PowerState);
            IPublicIPAddress ipAddress  = machine.GetPrimaryPublicIPAddress();
            string           action;
            string           buttonText;
            string           formVisibility      = "visible";
            string           qualifiedDnsName    = string.Empty;
            string           displayIp           = string.Empty;
            string           dnsCopyDisplayClass = "hidden";
            string           ipCopyDisplayClass  = "hidden";

            if (machine.PowerState == PowerState.Running)
            {
                action              = nameof(StopVm);
                buttonText          = "Deallocate";
                qualifiedDnsName    = ipAddress.Inner.DnsSettings != null ? ipAddress.Inner.DnsSettings.Fqdn : string.Empty;
                dnsCopyDisplayClass = !string.IsNullOrEmpty(qualifiedDnsName) ? "visible" : dnsCopyDisplayClass;
                displayIp           = ipAddress.IPAddress;
                ipCopyDisplayClass  = !string.IsNullOrEmpty(displayIp) ? "visible" : ipCopyDisplayClass;
            }
            else if (machine.PowerState == PowerState.Stopped || machine.PowerState == PowerState.Deallocated)
            {
                action     = nameof(StartVm);
                buttonText = "Start";
            }
            else
            {
                action         = string.Empty;
                buttonText     = string.Empty;
                formVisibility = "collapse";
            }
            if (!string.IsNullOrEmpty(_functionAccessCode))
            {
                action = $"{action}?code={_functionAccessCode}";
            }
            string finalForm = string.Format(contents, machine.Name, powerState, qualifiedDnsName, displayIp, action, formVisibility, buttonText, dnsCopyDisplayClass, ipCopyDisplayClass);

            return(finalForm);
        }
Ejemplo n.º 16
0
        public void CreateVM()
        {
            String region        = AzureConnectionUtility.Region;
            String resourceGroup = AzureConnectionUtility.ResourceGroup;

            IAvailabilitySet  availabilitySet  = CreateAvailabilitySetIfNotExists();
            IPublicIPAddress  publicIPAddress  = CreateIPIfNotExists();
            INetwork          network          = CreateNetworkIfNotExists();
            INetworkInterface networkInterface = CreateNetworkInterfaceIfNotExists(network, publicIPAddress);

            messageContainer.AddInformationMessage("Configuring virtual machine...");
            String machineName = "azureAutoEngine_VM";

            virtualMachine = azureConnection.AzureLink.VirtualMachines.GetByResourceGroup(AzureConnectionUtility.ResourceGroup, machineName);

            if (virtualMachine == null)
            {
                messageContainer.AddInformationMessage("Creating virtual machine...");
                virtualMachine = azureConnection.AzureLink.VirtualMachines.Define(machineName)
                                 .WithRegion(AzureConnectionUtility.Region)
                                 .WithExistingResourceGroup(AzureConnectionUtility.ResourceGroup)
                                 .WithExistingPrimaryNetworkInterface(networkInterface)
                                 .WithLatestLinuxImage("credativ", "Debian", "8")
                                 .WithRootUsername("azureUser")
                                 .WithRootPassword("Azure12345678")
                                 .WithComputerName("azureAutoEngineVM")
                                 .WithExistingAvailabilitySet(availabilitySet)
                                 .WithSize(VirtualMachineSizeTypes.BasicA1)
                                 .Create();
                messageContainer.AddInformationMessage("Virtual machine created...");
            }

            if (virtualMachine.PowerState != PowerState.Running)
            {
                SwitchOnVM();
            }

            messageContainer.AddInformationMessage("Virtual machine configured... feel free to inspect it on the portal...");
        }
Ejemplo n.º 17
0
        private IPublicIPAddress CreateIPIfNotExists()
        {
            messageContainer.AddInformationMessage("Configuring IP...");

            String           ipName          = "azureAutoEngine_IPAddress";
            IPublicIPAddress publicIPAddress = azureConnection.AzureLink.PublicIPAddresses.GetByResourceGroup(AzureConnectionUtility.ResourceGroup, ipName);

            if (publicIPAddress == null)
            {
                messageContainer.AddInformationMessage("Creating public IP...");
                publicIPAddress = azureConnection.AzureLink.PublicIPAddresses.Define(ipName)
                                  .WithRegion(AzureConnectionUtility.Region)
                                  .WithExistingResourceGroup(AzureConnectionUtility.ResourceGroup)
                                  .WithDynamicIP()
                                  .Create();

                messageContainer.AddInformationMessage("Public IP created...");
            }

            messageContainer.AddInformationMessage("IP configured...");

            return(publicIPAddress);
        }
        internal async Task <string> GetVmStatusAsync(string name)
        {
            _helper.LogMessage($"Starting");

            string          returnMessage;
            IVirtualMachine machine = await GetVmByNameAsync(name);

            PowerState powerState = machine.PowerState;

            if (powerState == PowerState.Running)
            {
                IPublicIPAddress ipAddress = machine.GetPrimaryPublicIPAddress();
                returnMessage = $"{powerState}, IP Address: {ipAddress.IPAddress}";
            }
            else
            {
                returnMessage = $"Machine status: {powerState}";
            }

            _helper.LogMessage($"Finished");

            return(returnMessage);
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Associates an existing public IP address with the network interface's primary IP configuration.
 /// </summary>
 /// <param name="publicIPAddress">An existing public IP address.</param>
 /// <return>The next stage of the definition.</return>
 NetworkInterface.Definition.IWithCreate NetworkInterface.Definition.IWithPrimaryPublicIPAddress.WithExistingPrimaryPublicIPAddress(IPublicIPAddress publicIPAddress)
 {
     return this.WithExistingPrimaryPublicIPAddress(publicIPAddress) as NetworkInterface.Definition.IWithCreate;
 }
 ///GENMHASH:BE684C4F4845D0C09A9399569DFB7A42:05B694DF2AF4DFEC5D2DC7534C0AD459
 public VirtualNetworkGatewayImpl WithExistingPublicIPAddress(IPublicIPAddress publicIPAddress)
 {
     EnsureDefaultIPConfig().WithExistingPublicIPAddress(publicIPAddress);
     return(this);
 }
        ///GENMHASH:AC21A10EE2E745A89E94E447800452C1:5EB77CF275BEAA2D6C9B6E198BAA8385
        override protected void BeforeCreating()
        {
            // Account for the newly created public IPs
            if (creatablePIPKeys != null)
            {
                foreach (var pipFrontendAssociation in creatablePIPKeys)
                {
                    IPublicIPAddress pip = (IPublicIPAddress)CreatedResource(pipFrontendAssociation.Key);
                    if (pip != null)
                    {
                        WithExistingPublicIPAddress(pip.Id, pipFrontendAssociation.Value);
                    }
                }

                creatablePIPKeys.Clear();
            }

            // Reset and update probes
            var innerProbes = InnersFromWrappers <ProbeInner, ILoadBalancerHttpProbe>(httpProbes.Values);

            innerProbes  = InnersFromWrappers(httpsProbes.Values, innerProbes);
            Inner.Probes = InnersFromWrappers(tcpProbes.Values, innerProbes) ?? new List <ProbeInner>();

            // Reset and update backends
            Inner.BackendAddressPools = InnersFromWrappers <BackendAddressPoolInner, ILoadBalancerBackend>(backends.Values) ?? new List <BackendAddressPoolInner>();

            // Reset and update frontends
            Inner.FrontendIPConfigurations = InnersFromWrappers <FrontendIPConfigurationInner, ILoadBalancerFrontend>(frontends.Values) ?? new List <FrontendIPConfigurationInner>();

            // Reset and update inbound NAT rules
            Inner.InboundNatRules = InnersFromWrappers <InboundNatRuleInner, ILoadBalancerInboundNatRule>(inboundNatRules.Values) ?? new List <InboundNatRuleInner>();
            foreach (var natRule in inboundNatRules.Values)
            {
                // Clear deleted frontend references
                var frontendRef = natRule.Inner.FrontendIPConfiguration;
                if (frontendRef != null && !Frontends().ContainsKey(ResourceUtils.NameFromResourceId(frontendRef.Id)))
                {
                    natRule.Inner.FrontendIPConfiguration = null;
                }
            }

            // Reset and update inbound NAT pools
            Inner.InboundNatPools = InnersFromWrappers <InboundNatPoolInner, ILoadBalancerInboundNatPool>(inboundNatPools.Values) ?? new List <InboundNatPoolInner>();
            foreach (var natPool in inboundNatPools.Values)
            {
                // Clear deleted frontend references
                var frontendRef = natPool.Inner.FrontendIPConfiguration;
                if (frontendRef != null && !Frontends().ContainsKey(ResourceUtils.NameFromResourceId(frontendRef.Id)))
                {
                    natPool.Inner.FrontendIPConfiguration = null;
                }
            }

            // Reset and update load balancing rules
            Inner.LoadBalancingRules = InnersFromWrappers <LoadBalancingRuleInner, ILoadBalancingRule>(loadBalancingRules.Values) ?? new List <LoadBalancingRuleInner>();
            foreach (var lbRule in loadBalancingRules.Values)
            {
                // Clear deleted frontend references
                var frontendRef = lbRule.Inner.FrontendIPConfiguration;
                if (frontendRef != null && !Frontends().ContainsKey(ResourceUtils.NameFromResourceId(frontendRef.Id)))
                {
                    lbRule.Inner.FrontendIPConfiguration = null;
                }

                // Clear deleted backend references
                var backendRef = lbRule.Inner.BackendAddressPool;
                if (backendRef != null && !Backends().ContainsKey(ResourceUtils.NameFromResourceId(backendRef.Id)))
                {
                    lbRule.Inner.BackendAddressPool = null;
                }

                // Clear deleted probe references
                var probeRef = lbRule.Inner.Probe;
                if (probeRef != null &&
                    !HttpProbes().ContainsKey(ResourceUtils.NameFromResourceId(probeRef.Id)) &&
                    !HttpsProbes().ContainsKey(ResourceUtils.NameFromResourceId(probeRef.Id)) &&
                    !TcpProbes().ContainsKey(ResourceUtils.NameFromResourceId(probeRef.Id)))
                {
                    lbRule.Inner.Probe = null;
                }
            }
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Associates an existing public IP address with the resource.
 /// </summary>
 /// <param name="publicIPAddress">An existing public IP address.</param>
 /// <return>The next stage of the update.</return>
 ApplicationGatewayFrontend.Update.IUpdate HasPublicIPAddress.Update.IWithExistingPublicIPAddress <ApplicationGatewayFrontend.Update.IUpdate> .WithExistingPublicIPAddress(IPublicIPAddress publicIPAddress)
 {
     return(this.WithExistingPublicIPAddress(publicIPAddress) as ApplicationGatewayFrontend.Update.IUpdate);
 }
Ejemplo n.º 23
0
 /// <summary>
 /// Associates an existing public IP address with the resource.
 /// </summary>
 /// <param name="publicIPAddress">An existing public IP address.</param>
 /// <return>The next stage of the definition.</return>
 ApplicationGatewayFrontend.Definition.IWithAttach <ApplicationGateway.Definition.IWithListener> HasPublicIPAddress.Definition.IWithExistingPublicIPAddress <ApplicationGatewayFrontend.Definition.IWithAttach <ApplicationGateway.Definition.IWithListener> > .WithExistingPublicIPAddress(IPublicIPAddress publicIPAddress)
 {
     return(this.WithExistingPublicIPAddress(publicIPAddress) as ApplicationGatewayFrontend.Definition.IWithAttach <ApplicationGateway.Definition.IWithListener>);
 }
Ejemplo n.º 24
0
 /// <summary>
 /// Associates an existing public IP address with the resource.
 /// </summary>
 /// <param name="publicIPAddress">An existing public IP address.</param>
 /// <return>The next stage of the definition.</return>
 ApplicationGatewayFrontend.UpdateDefinition.IWithAttach <ApplicationGateway.Update.IUpdate> HasPublicIPAddress.UpdateDefinition.IWithExistingPublicIPAddress <ApplicationGatewayFrontend.UpdateDefinition.IWithAttach <ApplicationGateway.Update.IUpdate> > .WithExistingPublicIPAddress(IPublicIPAddress publicIPAddress)
 {
     return(this.WithExistingPublicIPAddress(publicIPAddress) as ApplicationGatewayFrontend.UpdateDefinition.IWithAttach <ApplicationGateway.Update.IUpdate>);
 }
Ejemplo n.º 25
0
 ///GENMHASH:8FC05031058012246BAA83A815D4D8FB:37FCC8D93CF67DD30C6ADCDA2115A8F2
 internal NetworkInterfaceImpl WithExistingPrimaryPublicIPAddress(IPublicIPAddress publicIPAddress)
 {
     PrimaryIPConfiguration().WithExistingPublicIPAddress(publicIPAddress);
     return(this);
 }
Ejemplo n.º 26
0
 static async Task <INetworkInterface> CreateNIC(IResourceGroup resourceGroup, INetwork network, string subnetName, IPublicIPAddress publicIPAddress, string name = "CSNIC")
 {
     Console.WriteLine("Creating network interface...");
     return(await Subscription.NetworkInterfaces.Define("myNIC")
            .WithRegion(resourceGroup.Region)
            .WithExistingResourceGroup(resourceGroup)
            .WithExistingPrimaryNetwork(network)
            .WithSubnet(subnetName)
            .WithPrimaryPrivateIPAddressDynamic()
            .WithExistingPrimaryPublicIPAddress(publicIPAddress)
            .CreateAsync());
 }
Ejemplo n.º 27
0
 /// <summary>
 /// Associates an existing public IP address with the network interface's primary IP configuration.
 /// if there is an existing public IP association then that will be removed in favour of this.
 /// </summary>
 /// <param name="publicIPAddress">An existing public IP address.</param>
 /// <return>The next stage of the network interface update.</return>
 NetworkInterface.Update.IUpdate NetworkInterface.Update.IWithPrimaryPublicIPAddress.WithExistingPrimaryPublicIPAddress(IPublicIPAddress publicIPAddress)
 {
     return this.WithExistingPrimaryPublicIPAddress(publicIPAddress) as NetworkInterface.Update.IUpdate;
 }
Ejemplo n.º 28
0
 /// <summary>
 /// Associates an existing public IP address with the resource.
 /// </summary>
 /// <param name="publicIPAddress">An existing public IP address.</param>
 /// <return>The next stage of the update.</return>
 LoadBalancerPublicFrontend.Update.IUpdate HasPublicIPAddress.Update.IWithExistingPublicIPAddress <LoadBalancerPublicFrontend.Update.IUpdate> .WithExistingPublicIPAddress(IPublicIPAddress publicIPAddress)
 {
     return(this.WithExistingPublicIPAddress(publicIPAddress));
 }
Ejemplo n.º 29
0
 /// <summary>
 /// Associates an existing public IP address with the resource.
 /// </summary>
 /// <param name="publicIPAddress">An existing public IP address.</param>
 /// <return>The next stage of the definition.</return>
 LoadBalancerPublicFrontend.UpdateDefinition.IWithAttach <LoadBalancer.Update.IUpdate> HasPublicIPAddress.UpdateDefinition.IWithExistingPublicIPAddress <LoadBalancerPublicFrontend.UpdateDefinition.IWithAttach <LoadBalancer.Update.IUpdate> > .WithExistingPublicIPAddress(IPublicIPAddress publicIPAddress)
 {
     return(this.WithExistingPublicIPAddress(publicIPAddress));
 }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation($"{DateAndTime()} | C# HTTP trigger function processed a request.");

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            ProvisioningModel provisioningModel = JsonConvert.DeserializeObject <ProvisioningModel>(requestBody);


            if (string.IsNullOrEmpty(provisioningModel.ClientId) ||
                string.IsNullOrEmpty(provisioningModel.ClientSecret) ||
                string.IsNullOrEmpty(provisioningModel.TenantId) ||
                string.IsNullOrEmpty(provisioningModel.SubscriptionId) ||
                string.IsNullOrEmpty(provisioningModel.ClustrerName) ||
                string.IsNullOrEmpty(provisioningModel.ResourceGroupName) ||
                string.IsNullOrEmpty(provisioningModel.MainVhdURL) ||
                string.IsNullOrEmpty(provisioningModel.SmtpServer) ||
                string.IsNullOrEmpty(provisioningModel.SmtpPort.ToString()) ||
                string.IsNullOrEmpty(provisioningModel.SmtpEmail) ||
                string.IsNullOrEmpty(provisioningModel.SmtpPassword))
            {
                log.LogInformation($"{DateAndTime()} | Error |  Missing parameter | \n{requestBody}");
                return(new BadRequestObjectResult(false));
            }
            else
            {
                bool isSingleInstance;

                switch (provisioningModel.InstanceCount)
                {
                case "1": { isSingleInstance = true; break; }

                case "3": {
                    isSingleInstance = false;
                    if (
                        string.IsNullOrEmpty(provisioningModel.MysqlVhdURL) ||
                        string.IsNullOrEmpty(provisioningModel.MongoVhdURL))
                    {
                        log.LogInformation($"{DateAndTime()} | Error | Missing parameter for 3 instance (MysqlVhdURL/MongoVhdURL) | \n{requestBody}");
                        return(new BadRequestObjectResult(false));
                    }
                    break;
                }

                default:
                {
                    log.LogInformation($"{DateAndTime()} | Error | Please set valid instance count (1 or 3) | \n{requestBody}");
                    return(new BadRequestObjectResult(false));
                }
                }

                SmtpClient smtpClient = new SmtpClient()
                {
                    Host                  = provisioningModel.SmtpServer,
                    Port                  = provisioningModel.SmtpPort,
                    EnableSsl             = true,
                    UseDefaultCredentials = false,
                    Credentials           = new NetworkCredential(provisioningModel.SmtpEmail, provisioningModel.SmtpPassword)
                };

                MailMessage mailMessage = new MailMessage();

                mailMessage.From = new MailAddress(provisioningModel.SmtpEmail);
                mailMessage.To.Add(new MailAddress(provisioningModel.SmtpEmail));
                mailMessage.Subject = "Branch Academy Installation";

                try
                {
                    string resourceGroupName = provisioningModel.ResourceGroupName;
                    string clusterName       = provisioningModel.ClustrerName;
                    string MainVhdURL        = provisioningModel.MainVhdURL;
                    string MysqlVhdURL       = provisioningModel.MysqlVhdURL;
                    string MongoVhdURL       = provisioningModel.MongoVhdURL;
                    string subnet            = "default";
                    string username          = provisioningModel.Username;
                    string password          = provisioningModel.Password;

                    string contactPerson = provisioningModel.SmtpEmail;

                    log.LogInformation("deploying Main instance");
                    Utils.Email(smtpClient, "Main Instance Deployed Successfully", log, mailMessage);

                    ServicePrincipalLoginInformation principalLogIn = new ServicePrincipalLoginInformation();
                    principalLogIn.ClientId     = provisioningModel.ClientId;
                    principalLogIn.ClientSecret = provisioningModel.ClientSecret;

                    AzureEnvironment environment = AzureEnvironment.AzureGlobalCloud;
                    AzureCredentials credentials = new AzureCredentials(principalLogIn, provisioningModel.TenantId, environment);

                    IAzure _azureProd = Azure.Configure()
                                        .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                                        .Authenticate(credentials)
                                        .WithSubscription(provisioningModel.SubscriptionId);


                    IResourceGroup resourceGroup = _azureProd.ResourceGroups.GetByName(resourceGroupName);
                    Region         region        = resourceGroup.Region;

                    #region comment

                    #region Create Virtual Network
                    INetwork virtualNetwork = _azureProd.Networks.Define($"{clusterName}-vnet")
                                              .WithRegion(region)
                                              .WithExistingResourceGroup(resourceGroupName)
                                              .WithAddressSpace("10.0.0.0/16")
                                              .DefineSubnet(subnet)
                                              .WithAddressPrefix("10.0.0.0/24")
                                              .Attach()
                                              .WithTag("_contact_person", contactPerson)
                                              .Create();

                    #endregion

                    log.LogInformation($"{DateAndTime()} | Created | VNET");

                    #region Create VM IP
                    IPublicIPAddress publicIpAddress = _azureProd.PublicIPAddresses.Define($"{clusterName}-vm-ip")
                                                       .WithRegion(region)
                                                       .WithExistingResourceGroup(resourceGroupName)
                                                       .WithDynamicIP()
                                                       .WithLeafDomainLabel(clusterName)
                                                       .WithTag("_contact_person", contactPerson)
                                                       .Create();
                    #endregion

                    log.LogInformation($"{DateAndTime()} | Created | VM IP Address");

                    #region NSG
                    INetworkSecurityGroup networkSecurityGroup = _azureProd.NetworkSecurityGroups.Define($"{clusterName}-nsg")
                                                                 .WithRegion(region)
                                                                 .WithExistingResourceGroup(resourceGroupName)
                                                                 .DefineRule("ALLOW-SSH")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(22)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(100)
                                                                 .WithDescription("Allow SSH")
                                                                 .Attach()
                                                                 .DefineRule("LMS")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(80)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(101)
                                                                 .WithDescription("LMS")
                                                                 .Attach()
                                                                 .DefineRule("CMS")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(18010)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(102)
                                                                 .WithDescription("CMS")
                                                                 .Attach()
                                                                 .DefineRule("CMSSSLPort")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(48010)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(112)
                                                                 .WithDescription("CMSSSLPort")
                                                                 .Attach()
                                                                 .DefineRule("LMSSSLPort")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(443)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(122)
                                                                 .WithDescription("LMSSSLPort")
                                                                 .Attach()
                                                                 .DefineRule("Certs")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(18090)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(132)
                                                                 .WithDescription("Certs")
                                                                 .Attach()
                                                                 .DefineRule("Discovery")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(18381)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(142)
                                                                 .WithDescription("Discovery")
                                                                 .Attach()
                                                                 .DefineRule("Ecommerce")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(18130)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(152)
                                                                 .WithDescription("Ecommerce")
                                                                 .Attach()
                                                                 .DefineRule("edx-release")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(8099)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(162)
                                                                 .WithDescription("edx-release")
                                                                 .Attach()
                                                                 .DefineRule("Forum")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(18080)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(172)
                                                                 .WithDescription("Forum")
                                                                 .Attach()
                                                                 .WithTag("_contact_person", contactPerson)
                                                                 .DefineRule("Xqueue")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(18040)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(182)
                                                                 .WithDescription("Xqueue")
                                                                 .Attach()
                                                                 .WithTag("_contact_person", contactPerson)
                                                                 .Create();
                    #endregion

                    log.LogInformation($"{DateAndTime()} | Created | Network Security Group");

                    #region nic
                    INetworkInterface networkInterface = _azureProd.NetworkInterfaces.Define($"{clusterName}-nic")
                                                         .WithRegion(region)
                                                         .WithExistingResourceGroup(resourceGroupName)
                                                         .WithExistingPrimaryNetwork(virtualNetwork)
                                                         .WithSubnet(subnet)
                                                         .WithPrimaryPrivateIPAddressDynamic()
                                                         .WithExistingPrimaryPublicIPAddress(publicIpAddress)
                                                         .WithExistingNetworkSecurityGroup(networkSecurityGroup)
                                                         .WithTag("_contact_person", contactPerson)
                                                         .Create();
                    #endregion

                    log.LogInformation($"{DateAndTime()} | Created | Network Interface");

                    IStorageAccount storageAccount = _azureProd.StorageAccounts.GetByResourceGroup(resourceGroupName, $"{clusterName}vhdsa");

                    #region vm
                    IVirtualMachine createVm = _azureProd.VirtualMachines.Define($"{clusterName}-jb")
                                               .WithRegion(region)
                                               .WithExistingResourceGroup(resourceGroupName)
                                               .WithExistingPrimaryNetworkInterface(networkInterface)
                                               .WithStoredLinuxImage(MainVhdURL)
                                               .WithRootUsername(username)
                                               .WithRootPassword(password)
                                               .WithComputerName(username)
                                               .WithBootDiagnostics(storageAccount)
                                               .WithSize(VirtualMachineSizeTypes.StandardD2sV3)
                                               .WithTag("_contact_person", contactPerson)
                                               .Create();
                    #endregion

                    log.LogInformation($"{DateAndTime()} | Created | Main Virtual Machine");

                    #region LMS IP
                    IPublicIPAddress publicIPAddressLMS = _azureProd.PublicIPAddresses.Define($"{clusterName}-lms-ip")
                                                          .WithRegion(region)
                                                          .WithExistingResourceGroup(resourceGroupName)
                                                          .WithDynamicIP()
                                                          .WithLeafDomainLabel($"{clusterName}-lms-ip")
                                                          .WithTag("_contact_person", contactPerson)
                                                          .Create();
                    #endregion

                    log.LogInformation($"{DateAndTime()} | Created | LMS Public IP Address");

                    #region CMS IP
                    IPublicIPAddress publicIPAddressCMS = _azureProd.PublicIPAddresses.Define($"{clusterName}-cms-ip")
                                                          .WithRegion(region)
                                                          .WithExistingResourceGroup(resourceGroupName)
                                                          .WithDynamicIP()
                                                          .WithLeafDomainLabel($"{clusterName}-cms-ip")
                                                          .WithTag("_contact_person", contactPerson)
                                                          .Create();
                    #endregion

                    log.LogInformation($"{DateAndTime()} | Created | CMS Public IP Address");

                    #region LoadBalancer
                    ILoadBalancer loadBalancer = _azureProd.LoadBalancers.Define($"{clusterName}-lb")
                                                 .WithRegion(region)
                                                 .WithExistingResourceGroup(resourceGroupName)

                                                 .DefineLoadBalancingRule("LBRuleCMS")
                                                 .WithProtocol(TransportProtocol.Tcp)
                                                 .FromFrontend("CMS")
                                                 .FromFrontendPort(80)
                                                 .ToBackend($"{clusterName}-bepool")
                                                 .ToBackendPort(18010)
                                                 .WithProbe("tcpProbeCMS")
                                                 .WithFloatingIPDisabled()
                                                 .Attach()

                                                 .DefineLoadBalancingRule("LBRuleCMS_SSL")
                                                 .WithProtocol(TransportProtocol.Tcp)
                                                 .FromFrontend("CMS")
                                                 .FromFrontendPort(443)
                                                 .ToBackend($"{clusterName}-bepool")
                                                 .ToBackendPort(48010)
                                                 .WithProbe("tcpProbeCMSSSL")
                                                 .WithFloatingIPDisabled()
                                                 .Attach()

                                                 .DefineLoadBalancingRule("LBRuleLMS")
                                                 .WithProtocol(TransportProtocol.Tcp)
                                                 .FromFrontend("LMS")
                                                 .FromFrontendPort(80)
                                                 .ToBackend($"{clusterName}-bepool")
                                                 .ToBackendPort(80)
                                                 .WithProbe("tcpProbeLMS")
                                                 .WithFloatingIPDisabled()
                                                 .Attach()

                                                 .DefineLoadBalancingRule("LBRuleLMS_SSL")
                                                 .WithProtocol(TransportProtocol.Tcp)
                                                 .FromFrontend("LMS")
                                                 .FromFrontendPort(443)
                                                 .ToBackend($"{clusterName}-bepool")
                                                 .ToBackendPort(443)
                                                 .WithProbe("tcpProbeLMSSSL")
                                                 .WithFloatingIPDisabled()
                                                 .Attach()

                                                 .DefineBackend($"{clusterName}-bepool")
                                                 .WithExistingVirtualMachines(createVm)
                                                 .Attach()

                                                 .DefinePublicFrontend("LMS")
                                                 .WithExistingPublicIPAddress(publicIPAddressLMS)
                                                 .Attach()

                                                 .DefinePublicFrontend("CMS")
                                                 .WithExistingPublicIPAddress(publicIPAddressCMS)
                                                 .Attach()

                                                 .DefineHttpProbe("tcpProbeCMS")
                                                 .WithRequestPath("/heartbeat")
                                                 .WithPort(18010)
                                                 .WithIntervalInSeconds(5)
                                                 .WithNumberOfProbes(6)
                                                 .Attach()

                                                 .DefineTcpProbe("tcpProbeCMSSSL")
                                                 .WithPort(48010)
                                                 .WithIntervalInSeconds(5)
                                                 .WithNumberOfProbes(6)
                                                 .Attach()

                                                 .DefineHttpProbe("tcpProbeLMS")
                                                 .WithRequestPath("/heartbeat")
                                                 .WithPort(80)
                                                 .WithIntervalInSeconds(5)
                                                 .WithNumberOfProbes(6)
                                                 .Attach()

                                                 .DefineTcpProbe("tcpProbeLMSSSL")
                                                 .WithPort(443)
                                                 .WithIntervalInSeconds(5)
                                                 .WithNumberOfProbes(6)
                                                 .Attach()
                                                 .WithTag("_contact_person", contactPerson)
                                                 .Create();
                    #endregion

                    log.LogInformation($"{DateAndTime()} | Created | Load Balancer");

                    #region tm
                    IWithEndpoint tmDefinitionLMS = _azureProd.TrafficManagerProfiles
                                                    .Define($"{clusterName}-lms-tm")
                                                    .WithExistingResourceGroup(resourceGroupName)
                                                    .WithLeafDomainLabel($"{clusterName}-lms-tm")
                                                    .WithPriorityBasedRouting();
                    ICreatable <ITrafficManagerProfile> tmCreatableLMS = null;

                    tmCreatableLMS = tmDefinitionLMS
                                     .DefineExternalTargetEndpoint($"{clusterName}-lms-tm")
                                     .ToFqdn(publicIPAddressLMS.Fqdn)
                                     .FromRegion(region)
                                     .WithRoutingPriority(1)
                                     .Attach()
                                     .WithTag("_contact_person", contactPerson);

                    ITrafficManagerProfile trafficManagerProfileLMS = tmCreatableLMS.Create();

                    log.LogInformation($"{DateAndTime()} | Created | LMS Traffic Manager");

                    IWithEndpoint tmDefinitionCMS = _azureProd.TrafficManagerProfiles
                                                    .Define($"{clusterName}-cms-tm")
                                                    .WithExistingResourceGroup(resourceGroupName)
                                                    .WithLeafDomainLabel($"{clusterName}-cms-tm")
                                                    .WithPriorityBasedRouting();
                    ICreatable <ITrafficManagerProfile> tmCreatableCMS = null;

                    tmCreatableCMS = tmDefinitionCMS
                                     .DefineExternalTargetEndpoint($"{clusterName}-cms-tm")
                                     .ToFqdn(publicIPAddressCMS.Fqdn)
                                     .FromRegion(region)
                                     .WithRoutingPriority(1)
                                     .Attach()
                                     .WithTag("_contact_person", contactPerson);

                    ITrafficManagerProfile trafficManagerProfileCMS = tmCreatableCMS.Create();

                    log.LogInformation($"{DateAndTime()} | Created | CMS Traffic Manager");

                    #endregion

                    #endregion

                    if (!isSingleInstance)
                    {
                        #region mysql
                        INetworkSecurityGroup networkSecurityGroupmysql = _azureProd.NetworkSecurityGroups.Define($"{clusterName}-mysql-nsg")
                                                                          .WithRegion(region)
                                                                          .WithExistingResourceGroup(resourceGroup)
                                                                          .DefineRule("ALLOW-SSH")
                                                                          .AllowInbound()
                                                                          .FromAnyAddress()
                                                                          .FromAnyPort()
                                                                          .ToAnyAddress()
                                                                          .ToPort(22)
                                                                          .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                          .WithPriority(100)
                                                                          .WithDescription("Allow SSH")
                                                                          .Attach()
                                                                          .DefineRule("mysql")
                                                                          .AllowInbound()
                                                                          .FromAnyAddress()
                                                                          .FromAnyPort()
                                                                          .ToAnyAddress()
                                                                          .ToPort(3306)
                                                                          .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                          .WithPriority(101)
                                                                          .WithDescription("mysql")
                                                                          .Attach()
                                                                          .WithTag("_contact_person", contactPerson)
                                                                          .Create();

                        log.LogInformation($"{DateAndTime()} | Created | MySQL Network Security Group");

                        INetworkInterface networkInterfacemysql = _azureProd.NetworkInterfaces.Define($"{clusterName}-mysql-nic")
                                                                  .WithRegion(region)
                                                                  .WithExistingResourceGroup(resourceGroup)
                                                                  .WithExistingPrimaryNetwork(virtualNetwork)
                                                                  .WithSubnet(subnet)
                                                                  .WithPrimaryPrivateIPAddressDynamic()
                                                                  .WithExistingNetworkSecurityGroup(networkSecurityGroupmysql)
                                                                  .WithTag("_contact_person", contactPerson)
                                                                  .Create();

                        log.LogInformation($"{DateAndTime()} | Created | MySQL Network Interface");

                        IVirtualMachine createVmmysql = _azureProd.VirtualMachines.Define($"{clusterName}-mysql")
                                                        .WithRegion(region)
                                                        .WithExistingResourceGroup(resourceGroup)
                                                        .WithExistingPrimaryNetworkInterface(networkInterfacemysql)
                                                        .WithStoredLinuxImage(MysqlVhdURL)
                                                        .WithRootUsername(username)
                                                        .WithRootPassword(password)
                                                        .WithComputerName("mysql")
                                                        .WithBootDiagnostics(storageAccount)
                                                        .WithSize(VirtualMachineSizeTypes.StandardD2V2)
                                                        .WithTag("_contact_person", contactPerson)
                                                        .Create();

                        log.LogInformation($"{DateAndTime()} | Created | MySQL Virtual Machine");

                        #endregion

                        #region mongodb
                        INetworkSecurityGroup networkSecurityGroupmongo = _azureProd.NetworkSecurityGroups.Define($"{clusterName}-mongo-nsg")
                                                                          .WithRegion(region)
                                                                          .WithExistingResourceGroup(resourceGroup)
                                                                          .DefineRule("ALLOW-SSH")
                                                                          .AllowInbound()
                                                                          .FromAnyAddress()
                                                                          .FromAnyPort()
                                                                          .ToAnyAddress()
                                                                          .ToPort(22)
                                                                          .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                          .WithPriority(100)
                                                                          .WithDescription("Allow SSH")
                                                                          .Attach()
                                                                          .DefineRule("mongodb")
                                                                          .AllowInbound()
                                                                          .FromAnyAddress()
                                                                          .FromAnyPort()
                                                                          .ToAnyAddress()
                                                                          .ToPort(27017)
                                                                          .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                          .WithPriority(101)
                                                                          .WithDescription("mongodb")
                                                                          .Attach()
                                                                          .WithTag("_contact_person", contactPerson)
                                                                          .Create();

                        log.LogInformation($"{DateAndTime()} | Created | MongoDB Network Security Group");

                        INetworkInterface networkInterfacemongo = _azureProd.NetworkInterfaces.Define($"{clusterName}-mongo-nic")
                                                                  .WithRegion(region)
                                                                  .WithExistingResourceGroup(resourceGroup)
                                                                  .WithExistingPrimaryNetwork(virtualNetwork)
                                                                  .WithSubnet(subnet)
                                                                  .WithPrimaryPrivateIPAddressDynamic()
                                                                  .WithExistingNetworkSecurityGroup(networkSecurityGroupmongo)
                                                                  .WithTag("_contact_person", contactPerson)
                                                                  .Create();

                        log.LogInformation($"{DateAndTime()} | Created | MongoDB Network Interface");

                        IVirtualMachine createVmmongo = _azureProd.VirtualMachines.Define($"{clusterName}-mongo")
                                                        .WithRegion(region)
                                                        .WithExistingResourceGroup(resourceGroup)
                                                        .WithExistingPrimaryNetworkInterface(networkInterfacemongo)
                                                        .WithStoredLinuxImage(MongoVhdURL)
                                                        .WithRootUsername(username)
                                                        .WithRootPassword(password)
                                                        .WithComputerName("mongo")
                                                        .WithBootDiagnostics(storageAccount)
                                                        .WithSize(VirtualMachineSizeTypes.StandardD2V2)
                                                        .WithTag("_contact_person", contactPerson)
                                                        .Create();

                        log.LogInformation($"{DateAndTime()} | Created | MongoDB Virtual Machine");

                        #endregion

                        log.LogInformation("deploying 3 instance");

                        Utils.Email(smtpClient, "MySQL Instance Deployed Successfully", log, mailMessage);
                    }


                    string cmsUrl = trafficManagerProfileCMS.DnsLabel;
                    string lmsUrl = trafficManagerProfileLMS.DnsLabel;

                    Utils.Email(smtpClient, "Your Learning Platform is Ready to use." +
                                "<br/>"
                                + $"<a href=\"{lmsUrl}\">LMS</a>" +
                                "<br/>" +
                                $"<a href=\"{cmsUrl}\">CMS</a>"
                                , log, mailMessage);
                    log.LogInformation($"Done");
                }
                catch (Exception e)
                {
                    log.LogInformation($"{DateAndTime()} | Error | {e.Message}");

                    return(new BadRequestObjectResult(false));
                }

                log.LogInformation($"{DateAndTime()} | Done");
                return(new OkObjectResult(true));
            }
        }