public new IDeployment Create()
 {
     if (creatableResourceGroup != null)
     {
         creatableResourceGroup.Create();
     }
     CreateResource();
     return(this);
 }
 public IDeployment BeginCreate()
 {
     if (creatableResourceGroup != null)
     {
         creatableResourceGroup.Create();
     }
     Models.Deployment inner = new Models.Deployment()
     {
         Properties = new DeploymentPropertiesInner
         {
             Mode           = Mode.Value,
             Template       = Template,
             TemplateLink   = TemplateLink,
             Parameters     = Parameters,
             ParametersLink = ParametersLink
         }
     };
     SetInner(Extensions.Synchronize(() => Manager.Inner.Deployments.BeginCreateOrUpdateAsync(resourceGroupName, Name, inner.Properties)));
     return(this);
 }
示例#3
0
        public static Object Construct(Type type, CelestialBody body)
        {
            // Get all methods of the object
            ConstructorInfo[] methods =
                type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

            Object value = null;

            for (Int32 i = 0; i < methods.Length; i++)
            {
                // Is the method a KittopiaDestructor?
                if (!HasAttribute <KittopiaConstructor>(methods[i]))
                {
                    continue;
                }
                KittopiaConstructor attr = GetAttributes <KittopiaConstructor>(methods[i])[0];
                switch (attr.Parameter)
                {
                case KittopiaConstructor.ParameterType.Empty:
                    value = methods[i].Invoke(null);
                    break;

                case KittopiaConstructor.ParameterType.CelestialBody:
                    value = methods[i].Invoke(new Object[] { body });
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }

            if (value == null)
            {
                value = Activator.CreateInstance(type);
            }

            // Check if the object implements other constructors
            if (typeof(ICreatable <CelestialBody>).IsAssignableFrom(type))
            {
                ICreatable <CelestialBody> creatable = (ICreatable <CelestialBody>)value;
                creatable.Create(body);
            }
            else if (typeof(ICreatable).IsAssignableFrom(type))
            {
                ICreatable creatable = (ICreatable)value;
                creatable.Create();
            }

            return(value);
        }
示例#4
0
            /// <summary>
            /// Calls the methods declared as KittopiaDestructor
            /// </summary>
            public static Object Construct(Type type, CelestialBody body)
            {
                // Get all methods of the object
                ConstructorInfo[] methods =
                    type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

                Object value = null;

                for (Int32 i = 0; i < methods.Length; i++)
                {
                    // Is the method a KittopiaDestructor?
                    if (HasAttribute <KittopiaConstructor>(methods[i]))
                    {
                        KittopiaConstructor attr = GetAttributes <KittopiaConstructor>(methods[i])[0];
                        if (attr.parameter == KittopiaConstructor.Parameter.Empty)
                        {
                            value = methods[i].Invoke(null);
                        }

                        if (attr.parameter == KittopiaConstructor.Parameter.CelestialBody)
                        {
                            value = methods[i].Invoke(new Object[] { body });
                        }
                    }
                }

                if (value == null)
                {
                    value = Activator.CreateInstance(type);
                }

                // Check if the object implements other constructors
                if (typeof(ICreatable <CelestialBody>).IsAssignableFrom(type))
                {
                    ICreatable <CelestialBody> creatable = (ICreatable <CelestialBody>)value;
                    creatable.Create(body);
                }
                else if (typeof(ICreatable).IsAssignableFrom(type))
                {
                    ICreatable creatable = (ICreatable)value;
                    creatable.Create();
                }

                return(value);
            }
        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));
            }
        }
示例#6
0
 public IActionResult Todo(string taskName)
 {
     TodoList.Create(taskName);
     return(View(TodoList));
 }
示例#7
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");
                }
            }
        }
示例#8
0
        /**
         * Azure CDN sample for managing CDN profiles:
         * - Create 8 web apps in 8 regions:
         *    * 2 in US
         *    * 2 in EU
         *    * 2 in Southeast
         *    * 1 in Brazil
         *    * 1 in Japan
         * - Create CDN profile using Standard Verizon SKU with endpoints in each region of Web apps.
         * - Load some content (referenced by Web Apps) to the CDN endpoints.
         */
        public static void RunSample(IAzure azure)
        {
            string cdnProfileName = Utilities.CreateRandomName("cdnStandardProfile");
            string rgName         = SdkContext.RandomResourceName("rgCDN_", 24);
            var    appNames       = new string[8];

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

                // ============================================================
                // Create 8 websites
                for (int i = 0; i < 8; i++)
                {
                    appNames[i] = SdkContext.RandomResourceName("webapp" + (i + 1) + "-", 20);
                }

                // 2 in US
                CreateWebApp(azure, rgName, appNames[0], Region.USWest);
                CreateWebApp(azure, rgName, appNames[1], Region.USEast);

                // 2 in EU
                CreateWebApp(azure, rgName, appNames[2], Region.EuropeWest);
                CreateWebApp(azure, rgName, appNames[3], Region.EuropeNorth);

                // 2 in Southeast
                CreateWebApp(azure, rgName, appNames[4], Region.AsiaSouthEast);
                CreateWebApp(azure, rgName, appNames[5], Region.AustraliaSouthEast);

                // 1 in Brazil
                CreateWebApp(azure, rgName, appNames[6], Region.BrazilSouth);

                // 1 in Japan
                CreateWebApp(azure, rgName, appNames[7], Region.JapanWest);

                // =======================================================================================
                // Create CDN profile using Standard Verizon SKU with endpoints in each region of Web apps.
                Utilities.Log("Creating a CDN Profile");

                // create Cdn Profile definition object that will let us do a for loop
                // to define all 8 endpoints and then parallelize their creation
                var profileDefinition = azure.CdnProfiles.Define(cdnProfileName)
                                        .WithRegion(Region.USCentral)
                                        .WithExistingResourceGroup(rgName)
                                        .WithStandardVerizonSku();

                // define all the endpoints. We need to keep track of the last creatable stage
                // to be able to call create on the entire Cdn profile deployment definition.
                ICreatable <ICdnProfile> cdnCreatable = null;
                foreach (var webSite in appNames)
                {
                    cdnCreatable = profileDefinition
                                   .DefineNewEndpoint()
                                   .WithOrigin(webSite + Suffix)
                                   .WithHostHeader(webSite + Suffix)
                                   .WithCompressionEnabled(true)
                                   .WithContentTypeToCompress("application/javascript")
                                   .WithQueryStringCachingBehavior(QueryStringCachingBehavior.IgnoreQueryString)
                                   .Attach();
                }

                // create profile and then all the defined endpoints in parallel
                ICdnProfile profile = cdnCreatable.Create();

                // =======================================================================================
                // Load some content (referenced by Web Apps) to the CDN endpoints.
                var contentToLoad = new List <string>();
                contentToLoad.Add("/server.js");
                contentToLoad.Add("/pictures/microsoft_logo.png");

                foreach (ICdnEndpoint endpoint in profile.Endpoints.Values)
                {
                    endpoint.LoadContent(contentToLoad);
                }
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.DeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
            }
        }
示例#9
0
 public Game Create(Game entity) =>
 _creatable.Create(entity);
示例#10
0
        /// <summary>
        /// Load data for ParserTarget field or property from a configuration node
        /// </summary>
        /// <param name="member">Member to load data for</param>
        /// <param name="o">Instance of the object which owns member</param>
        /// <param name="node">Configuration node from which to load data</param>
        /// <param name="configName">The name of the mod that corresponds to the entry in ParserOptions</param>
        /// <param name="getChildren">Whether getters on the object should get called</param>
        private static void LoadObjectMemberFromConfigurationNode(MemberInfo member, Object o, ConfigNode node,
                                                                  String configName = "Default", Boolean getChildren = true)
        {
            // Get the parser targets
            ParserTarget[] targets = (ParserTarget[])member.GetCustomAttributes(typeof(ParserTarget), true);

            // Process the targets
            foreach (ParserTarget target in targets)
            {
                // Figure out if this field exists and if we care
                Boolean isNode = node.GetNodes()
                                 .Any(n => n.name.StartsWith(target.FieldName + ":") || n.name == target.FieldName);
                Boolean isValue = node.HasValue(target.FieldName);

                // Obtain the type the member is (can only be field or property)
                Type   targetType;
                Object targetValue = null;
                if (member.MemberType == MemberTypes.Field)
                {
                    targetType  = ((FieldInfo)member).FieldType;
                    targetValue = getChildren ? ((FieldInfo)member).GetValue(o) : null;
                }
                else
                {
                    targetType = ((PropertyInfo)member).PropertyType;
                    try
                    {
                        if (((PropertyInfo)member).CanRead && getChildren)
                        {
                            targetValue = ((PropertyInfo)member).GetValue(o, null);
                        }
                    }
                    catch (Exception)
                    {
                        // ignored
                    }
                }

                // Get settings data
                ParserOptions.Data data = ParserOptions.Options[configName];

                // Log
                data.LogCallback("Parsing Target " + target.FieldName + " in (" + o.GetType() + ") as (" + targetType +
                                 ")");

                // If there was no data found for this node
                if (!isNode && !isValue)
                {
                    if (!target.Optional && !(target.AllowMerge && targetValue != null))
                    {
                        // Error - non optional field is missing
                        throw new ParserTargetMissingException(
                                  "Missing non-optional field: " + o.GetType() + "." + target.FieldName);
                    }

                    // Nothing to do, so DONT return!
                    continue;
                }

                // Does this node have a required config source type (and if so, check if valid)
                RequireConfigType[] attributes =
                    (RequireConfigType[])targetType.GetCustomAttributes(typeof(RequireConfigType), true);
                if (attributes.Length > 0)
                {
                    if (attributes[0].Type == ConfigType.Node && !isNode ||
                        attributes[0].Type == ConfigType.Value && !isValue)
                    {
                        throw new ParserTargetTypeMismatchException(
                                  target.FieldName + " requires config value of " + attributes[0].Type);
                    }
                }

                // If this object is a value (attempt no merge here)
                if (isValue)
                {
                    // Process the value
                    Object val = ProcessValue(targetType, node.GetValue(target.FieldName));

                    // Throw exception or print error
                    if (val == null)
                    {
                        data.LogCallback("[Kopernicus]: Configuration.Parser: ParserTarget \"" + target.FieldName +
                                         "\" is a non parsable type: " + targetType);
                        continue;
                    }

                    targetValue = val;
                }

                // If this object is a node (potentially merge)
                else
                {
                    // If the target type is a ConfigNode, this works natively
                    if (targetType == typeof(ConfigNode))
                    {
                        targetValue = node.GetNode(target.FieldName);
                    }

                    // We need to get an instance of the object we are trying to populate
                    // If we are not allowed to merge, or the object does not exist, make a new instance
                    // Otherwise we can merge this value
                    else if (targetValue == null || !target.AllowMerge)
                    {
                        if (!targetType.IsAbstract)
                        {
                            targetValue = Activator.CreateInstance(targetType);
                        }
                    }

                    // Check for the name significance
                    switch (target.NameSignificance)
                    {
                    case NameSignificance.None:

                        // Just processes the contents of the node
                        LoadObjectFromConfigurationNode(targetValue, node.GetNode(target.FieldName), configName,
                                                        target.GetChild);
                        break;

                    case NameSignificance.Type:

                        // Generate the type from the name
                        ConfigNode subnode     = node.GetNodes().First(n => n.name.StartsWith(target.FieldName + ":"));
                        String[]   split       = subnode.name.Split(':');
                        Type       elementType = ModTypes.FirstOrDefault(t =>
                                                                         t.Name == split[1] && !Equals(t.Assembly, typeof(HighLogic).Assembly) &&
                                                                         targetType.IsAssignableFrom(t));

                        // If no object was found, check if the type implements custom constructors
                        targetValue = Activator.CreateInstance(elementType);
                        if (typeof(ICreatable).IsAssignableFrom(elementType))
                        {
                            ICreatable creatable = (ICreatable)targetValue;
                            creatable.Create();
                        }

                        // Parse the config node into the object
                        LoadObjectFromConfigurationNode(targetValue, subnode, configName, target.GetChild);
                        break;

                    case NameSignificance.Key:
                        throw new Exception("NameSignificance.Key is not supported on ParserTargets");

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                }

                // If the member type is a field, set the value
                if (member.MemberType == MemberTypes.Field)
                {
                    ((FieldInfo)member).SetValue(o, targetValue);
                }

                // If the member wasn't a field, it must be a property.  If the property is writable, set it.
                else if (((PropertyInfo)member).CanWrite)
                {
                    ((PropertyInfo)member).SetValue(o, targetValue, null);
                }
            }
        }
示例#11
0
        /// <summary>
        /// Load collection for ParserTargetCollection
        /// </summary>
        /// <param name="member">Member to load data for</param>
        /// <param name="o">Instance of the object which owns member</param>
        /// <param name="node">Configuration node from which to load data</param>
        /// <param name="configName">The name of the mod that corresponds to the entry in ParserOptions</param>
        /// <param name="getChildren">Whether getters on the object should get called</param>
        private static void LoadCollectionMemberFromConfigurationNode(MemberInfo member, Object o, ConfigNode node,
                                                                      String configName = "Default", Boolean getChildren = true)
        {
            // Get the target attributes
            ParserTargetCollection[] targets =
                (ParserTargetCollection[])member.GetCustomAttributes(typeof(ParserTargetCollection), true);

            // Process the target attributes
            foreach (ParserTargetCollection target in targets)
            {
                // Figure out if this field exists and if we care
                Boolean isNode  = node.HasNode(target.FieldName) || target.FieldName == "self";
                Boolean isValue = node.HasValue(target.FieldName);

                // Obtain the type the member is (can only be field or property)
                Type   targetType;
                Object targetValue = null;
                if (member.MemberType == MemberTypes.Field)
                {
                    targetType  = ((FieldInfo)member).FieldType;
                    targetValue = getChildren ? ((FieldInfo)member).GetValue(o) : null;
                }
                else
                {
                    targetType = ((PropertyInfo)member).PropertyType;
                    try
                    {
                        if (((PropertyInfo)member).CanRead && getChildren)
                        {
                            targetValue = ((PropertyInfo)member).GetValue(o, null);
                        }
                    }
                    catch (Exception)
                    {
                        // ignored
                    }
                }

                // Get settings data
                ParserOptions.Data data = ParserOptions.Options[configName];

                // Log
                data.LogCallback("Parsing Target " + target.FieldName + " in (" + o.GetType() + ") as (" + targetType +
                                 ")");

                // If there was no data found for this node
                if (!isNode && !isValue)
                {
                    if (!target.Optional && !(target.AllowMerge && targetValue != null))
                    {
                        // Error - non optional field is missing
                        throw new ParserTargetMissingException(
                                  "Missing non-optional field: " + o.GetType() + "." + target.FieldName);
                    }

                    // Nothing to do, so return
                    continue;
                }

                // If we are dealing with a generic collection
                if (targetType.IsGenericType)
                {
                    // If the target is a generic dictionary
                    if (typeof(IDictionary).IsAssignableFrom(targetType))
                    {
                        // We need a node for this decoding
                        if (!isNode)
                        {
                            throw new Exception("Loading a generic dictionary requires sources to be nodes");
                        }

                        // Get the target value as a dictionary
                        IDictionary collection = targetValue as IDictionary;

                        // Get the internal type of this collection
                        Type genericTypeA = targetType.GetGenericArguments()[0];
                        Type genericTypeB = targetType.GetGenericArguments()[1];

                        // Create a new collection if merge is disallowed or if the collection is null
                        if (collection == null || !target.AllowMerge)
                        {
                            collection  = Activator.CreateInstance(targetType) as IDictionary;
                            targetValue = collection;
                        }

                        // Process the node
                        ConfigNode targetNode = target.FieldName == "self" ? node : node.GetNode(target.FieldName);

                        // Check the config type
                        RequireConfigType[] attributes =
                            (RequireConfigType[])genericTypeA.GetCustomAttributes(typeof(RequireConfigType), true);
                        if (attributes.Length > 0)
                        {
                            if (attributes[0].Type == ConfigType.Node)
                            {
                                throw new ParserTargetTypeMismatchException(
                                          "The key value of a generic dictionary must be a Value");
                            }
                        }

                        attributes =
                            (RequireConfigType[])genericTypeB.GetCustomAttributes(typeof(RequireConfigType), true);
                        if (attributes.Length > 0 || genericTypeB == typeof(String))
                        {
                            ConfigType type = genericTypeB == typeof(String) ? ConfigType.Value : attributes[0].Type;
                            if (type == ConfigType.Node)
                            {
                                // Iterate over all of the nodes in this node
                                foreach (ConfigNode subnode in targetNode.nodes)
                                {
                                    // Check for the name significance
                                    switch (target.NameSignificance)
                                    {
                                    case NameSignificance.None:
                                        // Just processes the contents of the node
                                        collection.Add(ProcessValue(genericTypeA, subnode.name),
                                                       CreateObjectFromConfigNode(genericTypeB, subnode, configName,
                                                                                  target.GetChild));
                                        break;

                                    case NameSignificance.Type:
                                        throw new Exception(
                                                  "NameSignificance.Type isn't supported on generic dictionaries.");

                                    case NameSignificance.Key:
                                        throw new Exception(
                                                  "NameSignificance.Key isn't supported on generic dictionaries");

                                    default:
                                        throw new ArgumentOutOfRangeException();
                                    }
                                }
                            }
                            else
                            {
                                // Iterate over all of the values in this node
                                foreach (ConfigNode.Value value in targetNode.values)
                                {
                                    // Check for the name significance
                                    switch (target.NameSignificance)
                                    {
                                    case NameSignificance.None:
                                        collection.Add(ProcessValue(genericTypeA, value.name),
                                                       ProcessValue(genericTypeB, value.value));
                                        break;

                                    case NameSignificance.Type:
                                        throw new Exception(
                                                  "NameSignificance.Type isn't supported on generic dictionaries.");

                                    case NameSignificance.Key:
                                        throw new Exception(
                                                  "NameSignificance.Key isn't supported on generic dictionaries");

                                    default:
                                        throw new ArgumentOutOfRangeException();
                                    }
                                }
                            }
                        }
                    }

                    // If the target is a generic collection
                    else if (typeof(IList).IsAssignableFrom(targetType))
                    {
                        // We need a node for this decoding
                        if (!isNode)
                        {
                            throw new Exception("Loading a generic list requires sources to be nodes");
                        }

                        // Get the target value as a collection
                        IList collection = targetValue as IList;

                        // Get the internal type of this collection
                        Type genericType = targetType.GetGenericArguments()[0];

                        // Create a new collection if merge is disallowed or if the collection is null
                        if (collection == null || !target.AllowMerge)
                        {
                            collection  = Activator.CreateInstance(targetType) as IList;
                            targetValue = collection;
                        }

                        // Store the objects that were already patched
                        List <Object> patched = new List <Object>();

                        // Process the node
                        ConfigNode targetNode = target.FieldName == "self" ? node : node.GetNode(target.FieldName);

                        // Check the config type
                        RequireConfigType[] attributes =
                            (RequireConfigType[])genericType.GetCustomAttributes(typeof(RequireConfigType), true);
                        if (attributes.Length > 0 || genericType == typeof(String))
                        {
                            ConfigType type = genericType == typeof(String) ? ConfigType.Value : attributes[0].Type;
                            if (type == ConfigType.Node)
                            {
                                // Iterate over all of the nodes in this node
                                foreach (ConfigNode subnode in targetNode.nodes)
                                {
                                    // Check for the name significance
                                    switch (target.NameSignificance)
                                    {
                                    case NameSignificance.None:
                                    case NameSignificance.Key when subnode.name == target.Key:

                                        // Check if the type represents patchable data
                                        Object current = null;
                                        if (typeof(IPatchable).IsAssignableFrom(genericType) &&
                                            collection.Count > 0)
                                        {
                                            for (Int32 i = 0; i < collection.Count; i++)
                                            {
                                                if (collection[i].GetType() != genericType)
                                                {
                                                    continue;
                                                }

                                                if (patched.Contains(collection[i]))
                                                {
                                                    continue;
                                                }

                                                IPatchable patchable = (IPatchable)collection[i];
                                                PatchData  patchData =
                                                    CreateObjectFromConfigNode <PatchData>(subnode, "Internal");
                                                if (patchData.name == patchable.name)
                                                {
                                                    // Name matches, check for an index
                                                    if (patchData.index == collection.IndexOf(collection[i]))
                                                    {
                                                        // Both values match
                                                        current = collection[i];
                                                        break;
                                                    }

                                                    if (patchData.index > -1)
                                                    {
                                                        // Index doesn't match, continue
                                                        continue;
                                                    }

                                                    // Name matches, and no index exists
                                                    current = collection[i];
                                                    break;
                                                }

                                                if (patchData.name != null)
                                                {
                                                    // The name doesn't match, continue the search
                                                    continue;
                                                }

                                                // We found the first object that wasn't patched yet
                                                current = collection[i];
                                                break;
                                            }
                                        }

                                        // If no object was found, check if the type implements custom constructors
                                        if (current == null)
                                        {
                                            current = Activator.CreateInstance(genericType);
                                            collection?.Add(current);
                                        }

                                        // Parse the config node into the object
                                        LoadObjectFromConfigurationNode(current, subnode, configName,
                                                                        target.GetChild);
                                        patched.Add(current);
                                        if (collection != null)
                                        {
                                            collection[collection.IndexOf(current)] = current;
                                        }

                                        break;

                                    case NameSignificance.Type:

                                        // Generate the type from the name
                                        Type elementType = ModTypes.FirstOrDefault(t =>
                                                                                   t.Name == subnode.name &&
                                                                                   !Equals(t.Assembly, typeof(HighLogic).Assembly) &&
                                                                                   genericType.IsAssignableFrom(t));

                                        // Check if the type represents patchable data
                                        current = null;
                                        if (typeof(IPatchable).IsAssignableFrom(elementType) &&
                                            collection.Count > 0)
                                        {
                                            for (Int32 i = 0; i < collection.Count; i++)
                                            {
                                                if (collection[i].GetType() != elementType)
                                                {
                                                    continue;
                                                }

                                                if (patched.Contains(collection[i]))
                                                {
                                                    continue;
                                                }

                                                IPatchable patchable = (IPatchable)collection[i];
                                                PatchData  patchData =
                                                    CreateObjectFromConfigNode <PatchData>(subnode, "Internal");
                                                if (patchData.name == patchable.name)
                                                {
                                                    // Name matches, check for an index
                                                    if (patchData.index == i)
                                                    {
                                                        // Both values match
                                                        current = collection[i];
                                                        break;
                                                    }

                                                    if (patchData.index > -1)
                                                    {
                                                        // Index doesn't match, continue
                                                        continue;
                                                    }

                                                    // Name matches, and no index exists
                                                    current = collection[i];
                                                    break;
                                                }

                                                if (patchData.name != null)
                                                {
                                                    // The name doesn't match, continue the search
                                                    continue;
                                                }

                                                // We found the first object that wasn't patched yet
                                                current = collection[i];
                                                break;
                                            }
                                        }

                                        // If no object was found, check if the type implements custom constructors
                                        if (current == null)
                                        {
                                            current = Activator.CreateInstance(elementType);
                                            collection?.Add(current);
                                            if (typeof(ICreatable).IsAssignableFrom(elementType))
                                            {
                                                ICreatable creatable = (ICreatable)current;
                                                creatable.Create();
                                            }
                                        }

                                        // Parse the config node into the object
                                        LoadObjectFromConfigurationNode(current, subnode, configName,
                                                                        target.GetChild);
                                        patched.Add(current);
                                        if (collection != null)
                                        {
                                            collection[collection.IndexOf(current)] = current;
                                        }

                                        break;

                                    default:
                                        continue;
                                    }
                                }
                            }
                            else
                            {
                                // Iterate over all of the nodes in this node
                                foreach (ConfigNode.Value value in targetNode.values)
                                {
                                    // Check for the name significance
                                    switch (target.NameSignificance)
                                    {
                                    case NameSignificance.None:

                                        // Just processes the contents of the node
                                        collection?.Add(ProcessValue(genericType, value.value));
                                        break;

                                    case NameSignificance.Type:

                                        // Generate the type from the name
                                        Type elementType = ModTypes.FirstOrDefault(t =>
                                                                                   t.Name == value.name &&
                                                                                   !Equals(t.Assembly, typeof(HighLogic).Assembly) &&
                                                                                   genericType.IsAssignableFrom(t));

                                        // Add the object to the collection
                                        collection?.Add(ProcessValue(elementType, value.value));
                                        break;

                                    case NameSignificance.Key when value.name == target.Key:

                                        // Just processes the contents of the node
                                        collection?.Add(ProcessValue(genericType, value.value));
                                        break;

                                    default:
                                        continue;
                                    }
                                }
                            }
                        }
                    }
                }

                // If we are dealing with a non generic collection
                else
                {
                    // Check for invalid scenarios
                    if (target.NameSignificance == NameSignificance.None)
                    {
                        throw new Exception(
                                  "Can not infer type from non generic target; can not infer type from zero name significance");
                    }
                }

                // If the member type is a field, set the value
                if (member.MemberType == MemberTypes.Field)
                {
                    ((FieldInfo)member).SetValue(o, targetValue);
                }

                // If the member wasn't a field, it must be a property.  If the property is writable, set it.
                else if (((PropertyInfo)member).CanWrite)
                {
                    ((PropertyInfo)member).SetValue(o, targetValue, null);
                }
            }
        }
示例#12
0
 public Friend Create(Friend entity) =>
 _creatable.Create(entity);
示例#13
0
 public Loan Create(Loan entity) =>
 _creatable.Create(entity);