Ejemplo n.º 1
0
        public void StartBuilding()
        {
            var dataExamples = InitialConfig.GetInstance().InitialExamples;

            // First update of Inf Gain
            foreach (var node in InitialConfig.GetInstance().NodesToBeInserted)
            {
                node.UpdateEntropy(this.CalculateNegativeAndPositiveAmountOfExamples(dataExamples), dataExamples.Length);

                // calculate the examples which contain specific value
                int[]   storeAmountOfOutcomeValueHits = new int[node.PossibleOutcomes.Length];
                int[][] positiveAndNegativeExamplesAfterSpecificValue = new int[node.PossibleOutcomes.Length][];
                for (int i = 0; i < node.PossibleOutcomes.Length; i++)
                {
                    storeAmountOfOutcomeValueHits[i] = node.calculateAmountOfExmplesWithSpecificProperties(node.Name, node.PossibleOutcomes[i]);
                    var examplesAfterOutcomeValue = node.ReturnAllExamplesAfterValueCondition(node.Name, node.PossibleOutcomes[i]);
                    positiveAndNegativeExamplesAfterSpecificValue[i] = CalculateNegativeAndPositiveAmountOfExamples(examplesAfterOutcomeValue);
                }

                node.UpdateInfGain(node.Entropy, storeAmountOfOutcomeValueHits, node.UsedExamplesSoFar.Length, positiveAndNegativeExamplesAfterSpecificValue);
                Console.WriteLine();
            }

            // Initially all nodes are ready to be inserted
            InsertRootNode(InitialConfig.GetInstance().NodesToBeInserted);
            ContinueFillingTheTreeRecursivly(this.RootNode);
        }
    // Use this for initializati1on
    void Start()
    {
        instance = this;

        InitialConfig.RestoreConfiguration();

        smartphone        = GameObject.Find("SmartPhone");
        wrapperSmartphone = GameObject.Find("WrapperSmartphone");
        firstMenu         = GameObject.Find("Principal");

        animatorSmartphone = wrapperSmartphone.GetComponent <Animator>();
        switch (context)
        {
        case MenuContext.InGame:
        case MenuContext.Menu:
            BindMenu();
            FillMenu();
            break;

        case MenuContext.Intro:
            firstMenu.SetActive(false);
            callWait   = GameObject.Find("ChamadaRecebida");
            callDialog = GameObject.Find("LigacaoEmAndamento");

            //InitDialog();
            Invoke("InitDialog", callInit);
            break;
        }

        wrapperSmartphone.SetActive(false);
        SetBlur(false);
    }
Ejemplo n.º 3
0
        public string GenerarOTP(string cedula, string celular, out string mensajeRetorno)
        {
            string resp = null;

            mensajeRetorno = "";
            try
            {
                resp = _ContratacionProducto.GeneraOtp(cedula, celular, _settings.EnvioOTP.opidUsuario, _settings.ProductoSG.NombreProducto, out mensajeRetorno);
            }
            catch (Exception e)
            {
                resp           = "503";
                mensajeRetorno = InitialConfig.getNotiMessage("503", _settings).paragraph;
            }
            if (resp == "0000")
            {
                resp = "200";
            }
            else
            {
                resp = "400";
            }

            return(resp);
        }
Ejemplo n.º 4
0
 public InitialForm()
 {
     InitializeComponent();
     MakeSureMmfTextFileExist();
     initialConfig   = new InitialConfig();
     mainFlowHandler = new MainFlowHandler();
     mainFlowHandler.OnComponentIntialDoneEvent += MainFlowHandler_OnComponentIntialDoneEvent;
 }
Ejemplo n.º 5
0
        public JsonResult Calcular(string dataJson)    //mejorar esto
        {
            if (string.IsNullOrEmpty(dataJson))
            {
                return(Json(new { codError = "400", mensaje = "Olvidaste ingresar algún campo" }));
            }
            FromFormSolicitudCreditoDto data = null;

            try
            {
                data = JsonConvert.DeserializeObject <FromFormSolicitudCreditoDto>(dataJson);
            }
            catch (System.Exception)
            {
                return(Json(new { codError = "400", mensaje = "Petición erronea" }));
            }

            string mensaje;
            var    infoCliente = Session["datosClienteCP"] as DatosClientePy;

            var infoCatalogo = Session["datosCatSimulacion"] as DatosForSimuladorViewDto;

            if (infoCatalogo == null)
            {
                return(Json(new { codError = "405" }));
            }

            if (!data.IsValidModelSimulador(_settings, out mensaje))
            {
                return(Json(new { codError = "400", mensaje }));
            }

            //aqui va servicio calcula    ******** MEJORAR ESTO
            string codError = "", resp = null;

            if (data.modoDePago.idCodigo == 12167)
            {
                resp = _repoCreditoPyme.CalcularCuotaAlVencimiento(data);
            }
            else
            {
                resp = _repoCreditoPyme.CalculaCuotaMensual(data, infoCliente.Cedula, ref codError);
            }
            if (resp == null)
            {
                return(Json(new { codError = "503", mensaje = InitialConfig.getNotiMessage("503", _settings).paragraph }));
            }

            data.tasaEfectiva              = infoCatalogo.TasaEfectiva;
            data.tasaNominal               = infoCatalogo.TasaNominal;
            data.cuota                     = resp;
            infoCliente.infoSolicitud      = data;
            infoCatalogo.SeleccionAnterior = data;
            Session["datosCatSimulacion"]  = infoCatalogo;
            Session["datosClienteCP"]      = infoCliente;

            return(Json(new { codError = "200", cuota = resp }));
        }
Ejemplo n.º 6
0
    private InitialConfig saveInitialTransformation()
    {
        InitialConfig config = new InitialConfig();

        config.initialPos      = transform.position;
        config.initialRotation = transform.rotation;
        config.finalPos        = finalPos;
        return(config);
    }
Ejemplo n.º 7
0
 protected void init()
 {
     startPos = transform.position;
     calculateDirection();
     effector = GetComponentInChildren <AreaEffector2D>();
     startForce();
     clock         = new Clock(waitingTime);
     initialConfig = saveInitialTransformation();
 }
Ejemplo n.º 8
0
        public JsonResult ConsultaHostResumenFinal(object obj)
        {
            string CodError     = "";
            string MensajeError = "";

            var dataCliente = Session["datosClienteCP"] as DatosClientePy;
            var resp        = _repoCreditoPyme.ConsultarHostRiesgosGarantias(dataCliente.idProceso, dataCliente.Cedula, ref CodError, ref MensajeError);

            return(Json(new { codError = "200", mensaje = InitialConfig.getNotiMessage("we", _settings).paragraph }));
        }
Ejemplo n.º 9
0
        // GET: ErrorHandler
        public ActionResult Notificacion(string id)
        {
            var mensaje = InitialConfig.getNotiMessage(id, _settings);

            if (id == "000" || id == "099" || id == "001")
            {
                Session.Clear();
            }

            return(View(mensaje));
        }
Ejemplo n.º 10
0
        protected override async void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            // Initialize configurations
            InitialConfig.InitConfig();

            // Set up Aria2
            var ariaRunner = new AriaRunner();
            await ariaRunner.Start();
        }
Ejemplo n.º 11
0
        public JsonResult SendVentas(FromFormVentas data)
        {
            var dataCliente = Session["datosClienteCP"] as DatosClientePy;

            dataCliente.infoVentas    = data;
            Session["datosClienteCP"] = dataCliente;

            var resp = _repoCreditoPyme.RegistrarProductos(dataCliente.Cedula, data);

            return(Json(new { codError = resp, mensaje = InitialConfig.getNotiMessage(resp, _settings).paragraph }));
        }
Ejemplo n.º 12
0
        public JsonResult GetComboForArea(FromFormComboArea data)
        {
            var catalogo = _repoCatalogo.GetDataCboxDireccionBy(data.AreaType, data.IdSeleccionPadre);

            if (catalogo == null)
            {
                return(Json(new { codError = "503", mensaje = InitialConfig.getNotiMessage("503", _settings) }));
            }

            return(Json(new { catalogo, codError = "200" }));
        }
Ejemplo n.º 13
0
        public JsonResult SaveCuentaToDebDep(FromFormCuentaParaCredito data)
        {
            var dataCliente = Session["datosClienteCP"] as DatosClientePy;

            FromFormCuentaParaCredito info = null;

            info = data;
            dataCliente.infoCuentas   = info;
            Session["datosClienteCP"] = dataCliente;
            var resp = _repoCreditoPyme.SaveCtasParaCredito(dataCliente.Cedula, data);

            return(Json(new { codError = resp, mensaje = InitialConfig.getNotiMessage(resp, _settings).paragraph }));
        }
Ejemplo n.º 14
0
        public JsonResult PostBalances()
        {
            var dataCliente = Session["datosClienteCP"] as DatosClientePy;

            string mensaje = "", codigoError = "";

            var resp = _repoCreditoPyme.ProcesarPdfSRI(dataCliente, Request, out codigoError, out mensaje);

            if (string.IsNullOrEmpty(mensaje))
            {
                mensaje = InitialConfig.getNotiMessage(codigoError, _settings).paragraph;
            }

            return(Json(new { codError = codigoError, mensaje }));
        }
Ejemplo n.º 15
0
 public FinalConfig Run(InitialConfig c)
 {
     // The Busy Beaver Turing Machine with 4 states and 2 letters takes 107 steps to halt.
     return(c.Step().Step().Step().Step().Step().Step().Step().Step().Step().Step()
            .Step().Step().Step().Step().Step().Step().Step().Step().Step().Step()
            .Step().Step().Step().Step().Step().Step().Step().Step().Step().Step()
            .Step().Step().Step().Step().Step().Step().Step().Step().Step().Step()
            .Step().Step().Step().Step().Step().Step().Step().Step().Step().Step()
            .Step().Step().Step().Step().Step().Step().Step().Step().Step().Step()
            .Step().Step().Step().Step().Step().Step().Step().Step().Step().Step()
            .Step().Step().Step().Step().Step().Step().Step().Step().Step().Step()
            .Step().Step().Step().Step().Step().Step().Step().Step().Step().Step()
            .Step().Step().Step().Step().Step().Step().Step().Step().Step().Step()
            .Step().Step().Step().Step().Step().Step().Step());
 }
Ejemplo n.º 16
0
        public JsonResult SaveReferenciaBancaria(ReferenciasBancariasPyme[] data)
        {
            var dataCliente = Session["datosClienteCP"] as DatosClientePy;
            var resp        = _repoCreditoPyme.RegistrarReferenciasBancariasSolicitud(dataCliente.Cedula, data);

            if (resp != "200")
            {
                return(Json(new { codError = resp, mensaje = InitialConfig.getNotiMessage(resp, _settings).paragraph }));
            }

            var resp2 = _repoCreditoPyme.ConsultarCuentasCliente(dataCliente.Cedula);


            return(Json(new { codError = resp2.errorCode, mensaje = InitialConfig.getNotiMessage(resp2.errorCode, _settings).paragraph, numCtas = resp2.NumCuentas }));
        }
Ejemplo n.º 17
0
        public JsonResult validarEstadoCivil(FromFormEstadoCivilDto data)
        {
            var dataCliente = Session["datosClienteCP"] as DatosClientePy;

            if (dataCliente.estadoCivilFormRC == null)
            {
                var resp = _repoCreditoPyme.ConsultaEstadoCivilCliente(dataCliente.Cedula);
                if (resp.codError != "200")
                {
                    return(Json(new { resp.codError, mensaje = InitialConfig.getNotiMessage(resp.codError, _settings).paragraph }));
                }
                //return Json("Notificacion", "ErrorHandler", new { id = resp.codError });
            }

            //if()

            return(null);
        }
Ejemplo n.º 18
0
        public string ValidarOTP(SobreGiroDetalleSolicitudDto requisition, string cedula, string posibleOtp, out long idExpediente, out string codigoRetorno, out string mensajeRetorno)
        {
            mensajeRetorno = "";
            string resp;

            idExpediente  = 0;
            codigoRetorno = "0000";
            try
            {
                ServicioContratacionProductos.Solicitud solicitud = new ServicioContratacionProductos.Solicitud();

                Mapper.Map(requisition, solicitud);
                Mapper.Map(_settings, solicitud);
                solicitud.IdentificacionCliente = cedula;

                var resp1 = _ContratacionProducto.ValidarOtpSobregiro(cedula, posibleOtp, _settings.ProductoSG.IdProductoNeo,
                                                                      solicitud, out idExpediente, out codigoRetorno, out mensajeRetorno);
            }
            catch (Exception e)
            {
                codigoRetorno  = "503";
                mensajeRetorno = InitialConfig.getNotiMessage("503", _settings).paragraph;
                return("0");
            }

            if (codigoRetorno == "099")
            {
                codigoRetorno = "200";
                return("099");
            }
            if (codigoRetorno == "000")
            {
                codigoRetorno = "200";
                return("000");
            }
            if (codigoRetorno == "0001" || codigoRetorno == "9999")
            {
                codigoRetorno  = "400";
                mensajeRetorno = "El código ingresado está incorrecto. Por favor ingrésalo nuevamente";
                return("");
            }

            return("");
        }
Ejemplo n.º 19
0
        public JsonResult PostDireccionDomYneg(FromFormInfoDirecNeg data /*FromFormInfoDomicilio data*/)
        {
            string mensaje;
            var    dataCliente = Session["datosClienteCP"] as DatosClientePy;

            if (!data.isValidInfoDomicilio(out mensaje))
            {
                return(Json(new { codError = "400", mensaje }));
            }

            if (data.tipoDomicilio == "B")
            {
                dataCliente.DireccionNegocio = dataCliente.DireccionDomicilio;
            }
            if (data.tipoDomicilio == "T")
            {
                if (!(string.IsNullOrEmpty(dataCliente.DireccionNegocio)))
                {
                    var tempDireccion = dataCliente.DireccionDomicilio;
                    dataCliente.DireccionDomicilio = dataCliente.DireccionNegocio;
                    dataCliente.DireccionNegocio   = tempDireccion;
                }
            }

            if (data.tipoDomicilio != "Negocio")
            {
                dataCliente.infoDomicilio     = AutoMapper.Mapper.Map <FromFormInfoDomicilio>(data);
                dataCliente.TelefonoDomicilio = data.telefonoDomNeg;
            }
            else
            {
                dataCliente.infoNegocio = data;
            }

            Session["datosClienteCP"] = dataCliente;

            //aqui se deben enviar a servicio
            var codError = _repoCreditoPyme.RegistrarDireccionDomOrNeg(dataCliente.Cedula, data);

            return(Json(new { codError, mensaje = InitialConfig.getNotiMessage(codError, _settings) }));
        }
Ejemplo n.º 20
0
        public JsonResult SaveCertificaciones(string data)
        {
            if (string.IsNullOrEmpty(data))
            {
                return(Json(new { codError = "400", mensaje = "Petición incorrecta" }));
            }
            FromFormNegocioCertf info = null;

            try { info = JsonConvert.DeserializeObject <FromFormNegocioCertf>(data); }
            catch (System.Exception) {
                return(Json(new { codError = "500", mensaje = "Petición incorrecta" }));
            }

            var dataCliente = Session["datosClienteCP"] as DatosClientePy;

            dataCliente.infoCertificaciones = info;
            Session["datosClienteCP"]       = dataCliente;
            //aqui va metodo registrar cert
            var resp = _repoCreditoPyme.RegistrarCertificaciones(dataCliente.Cedula, info);

            return(Json(new { codError = resp, mensaje = InitialConfig.getNotiMessage(resp, _settings).paragraph }));
        }
Ejemplo n.º 21
0
        public ActionResult ValidaOTP(string data)
        {
            string codigoRetorno;
            string mensajeRetorno;

            var dataClient = Session["datosClienteCP"] as DatosClientePy;

            var resp = _OtpRepo.ValidarOTPCP(dataClient.Cedula, data, out codigoRetorno, out mensajeRetorno);


            if (codigoRetorno == "503")
            {
                return(Json(new { codError = "503", mensaje = InitialConfig.getNotiMessage(codigoRetorno, _settings).paragraph }));
            }

            if (codigoRetorno == "099")
            {
                Session.Clear();
            }

            return(Json(new { codError = resp, mensaje = mensajeRetorno }));
        }
Ejemplo n.º 22
0
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");


            if (InitialConfig.getEnvironment().mode.Equals("development", StringComparison.InvariantCultureIgnoreCase))
            {
                routes.MapRoute(
                    name: "Default",
                    url: "{controller}/{action}/{id}",
                    defaults: new { controller = "Test", action = "Index", id = UrlParameter.Optional }
                    );
            }
            else
            {
                routes.MapRoute(
                    name: "Default",
                    url: "{controller}/{action}/{id}",
                    defaults: new { controller = "TokenAccessValidation", action = "Index", id = UrlParameter.Optional }
                    );
            }
        }
Ejemplo n.º 23
0
        public void ContinueFillingTheTreeRecursivly(TreeNode currentNode)
        {
            // With more complex and bigger amount of possible Nodes it might be better
            // To optimize this by splitting used and unused nodes in order not to
            // iterate in big sized array every time
            // (for smaller sets it is not that necessary because of memory space optimization)
            var availableNodes = InitialConfig.GetInstance().NodesToBeInserted.Where(tmpNode => !tmpNode.IsUsed);

            foreach (var outcome in currentNode.PossibleOutcomes)
            {
                int[]  possitiveAndNegativeExamplesAfterOutcome = CalculateNegativeAndPositiveAmountOfExamples(currentNode.ReturnAllExamplesAfterValueCondition(currentNode.Name, outcome));
                string leafInf = currentNode.DeclareLeafInf(possitiveAndNegativeExamplesAfterOutcome);
                if (leafInf != "Node")
                {
                    currentNode.LeafInf.Add(outcome, leafInf);
                    continue;
                }
                if (availableNodes.ToArray().Length == 0)
                {
                    if (possitiveAndNegativeExamplesAfterOutcome[0] <= possitiveAndNegativeExamplesAfterOutcome[1])
                    {
                        currentNode.LeafInf.Add(outcome, "Yes");
                        continue;
                    }
                    else
                    {
                        currentNode.LeafInf.Add(outcome, "No");
                        continue;
                    }
                }

                var dataExamples = currentNode.UsedExamplesSoFar;

                foreach (var node in availableNodes)
                {
                    if (!node.IsUsed)
                    {
                        node.UsedExamplesSoFar = dataExamples;
                        node.UsedExamplesSoFar = node.ReturnAllExamplesAfterValueCondition(currentNode.Name, outcome);
                        node.UpdateEntropy(this.CalculateNegativeAndPositiveAmountOfExamples(node.UsedExamplesSoFar), node.UsedExamplesSoFar.Length);

                        // calculate the examples which contain specific value
                        int[]   storeAmountOfOutcomeValueHits = new int[node.PossibleOutcomes.Length];
                        int[][] positiveAndNegativeExamplesAfterSpecificValue = new int[node.PossibleOutcomes.Length][];
                        for (int i = 0; i < node.PossibleOutcomes.Length; i++)
                        {
                            storeAmountOfOutcomeValueHits[i] = node.calculateAmountOfExmplesWithSpecificProperties(node.Name, node.PossibleOutcomes[i]);
                            var examplesAfterOutcomeValue = node.ReturnAllExamplesAfterValueCondition(node.Name, node.PossibleOutcomes[i]);
                            positiveAndNegativeExamplesAfterSpecificValue[i] = CalculateNegativeAndPositiveAmountOfExamples(examplesAfterOutcomeValue);
                        }

                        node.UpdateInfGain(node.Entropy, storeAmountOfOutcomeValueHits, node.UsedExamplesSoFar.Length, positiveAndNegativeExamplesAfterSpecificValue);
                    }
                }

                TreeNode nextNode = availableNodes.OrderBy(tmpNode => tmpNode.InfGain).Last();
                nextNode.IsUsed           = true;
                nextNode.ParentTransition = outcome;
                currentNode.Children.Add(nextNode);
            }

            foreach (var child in currentNode.Children)
            {
                ContinueFillingTheTreeRecursivly(child);
            }
        }
Ejemplo n.º 24
0
        public DatosClientePy GetInfoClientePy(string cedula, out string codError, out string mensajeError)
        {
            DataNamesMapper <DatosClientePy> mapperToclient = new DataNamesMapper <DatosClientePy>();
            DatosClientePy infoCliente = null;
            DataSet        data        = null;

            try
            {
                data = _ContratacionProducto.ConsultaDatosClienteCoreAll(cedula, "C", out codError, out mensajeError);
            }
            catch (System.Exception)
            {
                codError     = "503";
                mensajeError = InitialConfig.getNotiMessage(codError, _settings).paragraph;
                return(null);
            }
            int       paso        = 0;
            int       idSolicitud = 0;
            DataRow   row         = null;
            DataTable table       = null;

            if (data.Tables.Contains("DatosBasicosCliente") && codError == "000")
            {
                row         = data.Tables["DatosBasicosCliente"].Rows[0];
                infoCliente = mapperToclient.Map(row);
                var pagina = row.Field <string>("ID_PASO_SOLICITUD");
                var idSoli = row.Field <string>("ID_SOLICITUD");
                paso        = pagina.ToInt();
                idSolicitud = idSoli.ToInt();
                //EstadoCivilFromCore
                DataNamesMapper <EstadoCivilFromCore> mapperToEcFromCore = new DataNamesMapper <EstadoCivilFromCore>();
                infoCliente.estadoCivilFormCore = mapperToEcFromCore.Map(row);
            }
            if (paso == 0 && idSolicitud == 0)
            {
                return(infoCliente);
            }


            if (paso >= 1) // Simulador | datos cliente
            {
                infoCliente.infoSolicitud = Mapper.Map <FromFormSolicitudCreditoDto>(row);
                //DataNamesMapper<SolicitudSeleccion> mapperToSeleccion1 = new DataNamesMapper<SolicitudSeleccion>();
                //infoCliente.SolicitudSeleccionAnt = mapperToSeleccion1.Map(row);
            }
            if (paso >= 2)//no definido     (estado Civil)
            {
            }
            if (paso >= 3) //Direccion domicilio | Confirmacion Datos Cliente
            {
                DataNamesMapper <FromFormInfoDomicilio> mapperToSeleccion3 = new DataNamesMapper <FromFormInfoDomicilio>();
                infoCliente.infoDomicilio = mapperToSeleccion3.Map(row);
                infoCliente.ActionRoute   = "InfoDomicilio";
            }
            if (paso >= 4) //Carga Balances
            {
            }
            if (paso >= 5) //Carga IVA
            {
            }
            if (paso >= 6) //Ventas Cliente
            {
                DataNamesMapper <Models.Producto> mapperToSeleccion6 = new DataNamesMapper <Models.Producto>();
                var seleccionado = new FromFormVentas();
                seleccionado.productos       = mapperToSeleccion6.Map(data.Tables["Productos"]).ToList();
                seleccionado.numeroEmpleados = row["NUM_EMPLEADOS"].ToString().ToInt();
                infoCliente.infoVentas       = seleccionado;
                infoCliente.ActionRoute      = "TusVentas";
            }
            if (paso >= 7) //Clientes-Proveedores
            {
                List <ClientesProveedores>            clientesProveedores = new List <ClientesProveedores>();
                DataNamesMapper <ClientesProveedores> mapperToSeleccion7  = new DataNamesMapper <ClientesProveedores>();
                FromFormClientes forWiew = new FromFormClientes();

                if (data.Tables.Contains("Clientes") && codError == "000")
                {
                    var t = data.Tables["Clientes"].getWithAddedCol("C");
                    clientesProveedores = mapperToSeleccion7.Map(t).ToList();
                }
                if (data.Tables.Contains("Proveedores") && codError == "000")
                {
                    var t = data.Tables["Proveedores"].getWithAddedCol("P");
                    var r = mapperToSeleccion7.Map(t).ToList();
                    if (clientesProveedores != null)
                    {
                        clientesProveedores = clientesProveedores.Concat(r).ToList();
                    }
                    else
                    {
                        clientesProveedores = r;
                    }
                }
                forWiew.clientes = clientesProveedores;
                infoCliente.infoClientesProveedores = forWiew;
                infoCliente.ActionRoute             = "ClientesProveedores";
            }
            if (paso >= 8) //Direccion Negocio
            {
                DataNamesMapper <FromFormInfoDirecNeg> mapperToSeleccion8 = new DataNamesMapper <FromFormInfoDirecNeg>();
                infoCliente.infoNegocio = mapperToSeleccion8.Map(row);
                infoCliente.ActionRoute = "DireccionNegocio";
            }
            if (paso >= 9)  //Certificacion | Confirmacion Datos Negocio
            {
            }
            if (paso == 10) //Referencias Bancarias
            {
            }

            return(infoCliente);
        }
Ejemplo n.º 25
0
 void app_Startup(object sender, StartupEventArgs e)
 {
     InitialConfig.InitialFile();
     InitialConfig.GetConfig();
 }
Ejemplo n.º 26
0
 static void Main()
 {
     var         c = new InitialConfig();
     FinalConfig f = new Program().Run(c);
 }
Ejemplo n.º 27
0
        private async void InitializeDatabase(IApplicationBuilder app, UserManager <ApplicationUser> userManager, RoleManager <IdentityRole> roleManager)
        {
            using (var scope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope())
            {
                scope.ServiceProvider.GetRequiredService <PersistedGrantDbContext>().Database.Migrate();

                var configurationContext = scope.ServiceProvider.GetRequiredService <ConfigurationDbContext>();



                configurationContext.Database.Migrate();
                //This will populate records based on config file for Identity Server
                if (!configurationContext.Clients.Any())
                {
                    foreach (var client in InitialConfig.GetClients())
                    {
                        configurationContext.Clients.Add(client.ToEntity());
                    }
                    configurationContext.SaveChanges();
                }

                if (!configurationContext.IdentityResources.Any())
                {
                    foreach (var resource in InitialConfig.GetIdentityResources())
                    {
                        configurationContext.IdentityResources.Add(resource.ToEntity());
                    }
                    configurationContext.SaveChanges();
                }

                if (!configurationContext.ApiResources.Any())
                {
                    foreach (var resource in InitialConfig.GetApiResources())
                    {
                        configurationContext.ApiResources.Add(resource.ToEntity());
                    }
                    configurationContext.SaveChanges();
                }
                var authenticationContext = scope.ServiceProvider.GetRequiredService <ApplicationDbContext>();
                authenticationContext.Database.Migrate();

                //this will populate default superadmin user.
                if (!authenticationContext.Users.Any())
                {
                    //TODO Add this to a message broker or separate service with retry policies so if error occurs while creating initila use application can still continue
                    UserDto superAdmin = InitialConfig.GetUsers().First();

                    await userManager.CreateAsync(
                        new ApplicationUser { UserName = superAdmin.Username, IsSuperAdmin = true },
                        superAdmin.Password);
                }
                if (!authenticationContext.Roles.Any())
                {
                    IEnumerable <RoleDto> roles = InitialConfig.GetRoles();
                    foreach (RoleDto roleDto in roles)
                    {
                        await roleManager.CreateAsync(
                            new IdentityRole { Name = roleDto.Name, NormalizedName = roleDto.Name.ToUpper() });
                    }
                }
            }
        }