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));
            }
        }
Beispiel #2
0
        /**
         * Azure traffic manager sample for managing profiles.
         *  - Create a domain
         *  - Create a self-signed certificate for the domain
         *  - Create 5 app service plans in 5 different regions
         *  - Create 5 web apps under the each plan, bound to the domain and the certificate
         *  - Create a traffic manager in front of the web apps
         *  - Disable an endpoint
         *  - Delete an endpoint
         *  - Enable an endpoint
         *  - Change/configure traffic manager routing method
         *  - Disable traffic manager profile
         *  - Enable traffic manager profile
         */
        public static void RunSample(IAzure azure)
        {
            string rgName     = SdkContext.RandomResourceName("rgNEMV_", 24);
            string domainName = SdkContext.RandomResourceName("jsdkdemo-", 20) + ".com";
            string appServicePlanNamePrefix = SdkContext.RandomResourceName("jplan1_", 15);
            string webAppNamePrefix         = SdkContext.RandomResourceName("webapp1-", 20) + "-";
            string tmName = SdkContext.RandomResourceName("jsdktm-", 20);

            // The regions in which web app needs to be created
            //
            regions.Add(Region.USWest2);
            regions.Add(Region.USEast2);
            regions.Add(Region.AsiaEast);
            regions.Add(Region.IndiaWest);
            regions.Add(Region.USCentral);

            try
            {
                azure.ResourceGroups.Define(rgName)
                .WithRegion(Region.USWest)
                .Create();

                // ============================================================
                // Purchase a domain (will be canceled for a full refund)

                Utilities.Log("Purchasing a domain " + domainName + "...");
                var domain = azure.AppServices.AppServiceDomains.Define(domainName)
                             .WithExistingResourceGroup(rgName)
                             .DefineRegistrantContact()
                             .WithFirstName("Jon")
                             .WithLastName("Doe")
                             .WithEmail("*****@*****.**")
                             .WithAddressLine1("123 4th Ave")
                             .WithCity("Redmond")
                             .WithStateOrProvince("WA")
                             .WithCountry(CountryISOCode.UnitedStates)
                             .WithPostalCode("98052")
                             .WithPhoneCountryCode(CountryPhoneCode.UnitedStates)
                             .WithPhoneNumber("4258828080")
                             .Attach()
                             .WithDomainPrivacyEnabled(true)
                             .WithAutoRenewEnabled(false)
                             .Create();
                Utilities.Log("Purchased domain " + domain.Name);
                Utilities.Print(domain);

                //============================================================
                // Create a self-singed SSL certificate

                var pfxPath = domainName + ".pfx";
                Utilities.Log("Creating a self-signed certificate " + pfxPath + "...");
                Utilities.CreateCertificate(domainName, pfxPath, certPassword);
                Utilities.Log("Created self-signed certificate " + pfxPath);

                //============================================================
                // Creates app service in 5 different region

                var appServicePlans = new List <IAppServicePlan>();
                int id = 0;
                foreach (var region in regions)
                {
                    var planName = appServicePlanNamePrefix + id;
                    Utilities.Log("Creating an app service plan " + planName + " in region " + region + "...");
                    var appServicePlan = azure.AppServices.AppServicePlans
                                         .Define(planName)
                                         .WithRegion(region)
                                         .WithExistingResourceGroup(rgName)
                                         .WithPricingTier(PricingTier.BasicB1)
                                         .WithOperatingSystem(Microsoft.Azure.Management.AppService.Fluent.OperatingSystem.Windows)
                                         .Create();
                    Utilities.Log("Created app service plan " + planName);
                    Utilities.Print(appServicePlan);
                    appServicePlans.Add(appServicePlan);
                    id++;
                }

                //============================================================
                // Creates websites using previously created plan
                var webApps = new List <IWebApp>();
                id = 0;
                foreach (var appServicePlan in appServicePlans)
                {
                    var webAppName = webAppNamePrefix + id;
                    Utilities.Log("Creating a web app " + webAppName + " using the plan " + appServicePlan.Name + "...");
                    var webApp = azure.WebApps.Define(webAppName)
                                 .WithExistingWindowsPlan(appServicePlan)
                                 .WithExistingResourceGroup(rgName)
                                 .WithManagedHostnameBindings(domain, webAppName)
                                 .DefineSslBinding()
                                 .ForHostname(webAppName + "." + domain.Name)
                                 .WithPfxCertificateToUpload(Path.Combine(Utilities.ProjectPath, "Asset", pfxPath), certPassword)
                                 .WithSniBasedSsl()
                                 .Attach()
                                 .DefineSourceControl()
                                 .WithPublicGitRepository("https://github.com/jianghaolu/azure-site-test")
                                 .WithBranch("master")
                                 .Attach()
                                 .Create();
                    Utilities.Log("Created web app " + webAppName);
                    Utilities.Print(webApp);
                    webApps.Add(webApp);
                    id++;
                }
                //============================================================
                // Creates a traffic manager profile

                Utilities.Log("Creating a traffic manager profile " + tmName + " for the web apps...");
                IWithEndpoint tmDefinition = azure.TrafficManagerProfiles
                                             .Define(tmName)
                                             .WithExistingResourceGroup(rgName)
                                             .WithLeafDomainLabel(tmName)
                                             .WithPriorityBasedRouting();
                ICreatable <ITrafficManagerProfile> tmCreatable = null;
                int priority = 1;
                foreach (var webApp in webApps)
                {
                    tmCreatable = tmDefinition.DefineAzureTargetEndpoint("endpoint-" + priority)
                                  .ToResourceId(webApp.Id)
                                  .WithRoutingPriority(priority)
                                  .Attach();
                    priority++;
                }

                var trafficManagerProfile = tmCreatable.Create();
                Utilities.Log("Created traffic manager " + trafficManagerProfile.Name);
                Utilities.Print(trafficManagerProfile);

                //============================================================
                // Disables one endpoint and removes another endpoint

                Utilities.Log("Disabling and removing endpoint...");
                trafficManagerProfile = trafficManagerProfile.Update()
                                        .UpdateAzureTargetEndpoint("endpoint-1")
                                        .WithTrafficDisabled()
                                        .Parent()
                                        .WithoutEndpoint("endpoint-2")
                                        .Apply();
                Utilities.Log("Endpoints updated");

                //============================================================
                // Enables an endpoint

                Utilities.Log("Enabling endpoint...");
                trafficManagerProfile = trafficManagerProfile.Update()
                                        .UpdateAzureTargetEndpoint("endpoint-1")
                                        .WithTrafficEnabled()
                                        .Parent()
                                        .Apply();
                Utilities.Log("Endpoint updated");
                Utilities.Print(trafficManagerProfile);

                //============================================================
                // Change/configure traffic manager routing method

                Utilities.Log("Changing traffic manager profile routing method...");
                trafficManagerProfile = trafficManagerProfile.Update()
                                        .WithPerformanceBasedRouting()
                                        .Apply();
                Utilities.Log("Changed traffic manager profile routing method");

                //============================================================
                // Disables the traffic manager profile

                Utilities.Log("Disabling traffic manager profile...");
                trafficManagerProfile.Update()
                .WithProfileStatusDisabled()
                .Apply();
                Utilities.Log("Traffic manager profile disabled");

                //============================================================
                // Enables the traffic manager profile

                Utilities.Log("Enabling traffic manager profile...");
                trafficManagerProfile.Update()
                .WithProfileStatusDisabled()
                .Apply();
                Utilities.Log("Traffic manager profile enabled");

                //============================================================
                // Deletes the traffic manager profile

                Utilities.Log("Deleting the traffic manger profile...");
                azure.TrafficManagerProfiles.DeleteById(trafficManagerProfile.Id);
                Utilities.Log("Traffic manager profile deleted");
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.BeginDeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
            }
        }