public async Task <IActionResult> Enable(long id)
        {
            var result = new ResultDto <bool>();

            try
            {
                var modelExists = await _enteDocumentoTipoService.GetByIdAsync(id);

                if (modelExists == null)
                {
                    throw new AwayException("No existe el registro que desea activar.");
                }

                result.Data = await _enteDocumentoTipoService.EnableAsync(id);
            }
            catch (AwayException ex)
            {
                _logger.Error(KOriginApp, ex.Message, ex);
                result.AddError(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.Error(KOriginApp, ex.Message, ex);
                result.AddError("Ocurrió un error al intentar activar el registro.");
            }
            return(Ok(result));
        }
        public async Task <IActionResult> Delete(long id)
        {
            var result = new ResultDto <bool>();

            try
            {
                var modelExists = await _articuloUnidadMedidaService.GetByIdAsync(id);

                if (modelExists == null)
                {
                    throw new AwayException("No existe el registro que desea eliminar.");
                }

                result.Data = await _articuloUnidadMedidaService.DeleteAsync(id);
            }
            catch (AwayException ex)
            {
                _logger.Error(KOriginApp, ex.Message, ex);
                result.AddError(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.Error(KOriginApp, ex.Message, ex);
                result.AddError("Ocurrió un error al intentar eliminar el registro.");
            }
            return(Ok(result));
        }
        public async Task <IActionResult> Put(long id, [FromBody] EnteDocumentoTipoDto valueDto)
        {
            var result = new ResultDto <bool>();

            try
            {
                var modelExists = await _enteDocumentoTipoService.GetByIdAsync(id);

                if (modelExists == null)
                {
                    throw new AwayException("No existe el registro que desea editar.");
                }

                valueDto.Id = modelExists.Id;
                result.Data = await _enteDocumentoTipoService.UpdateAsync(valueDto);
            }
            catch (AwayException ex)
            {
                _logger.Error(KOriginApp, ex.Message, ex);
                result.AddError(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.Error(KOriginApp, ex.Message, ex);
                result.AddError("Ocurrió un error al intentar editar los datos del registro.");
            }
            return(Ok(result));
        }
Пример #4
0
        public async Task <IActionResult> Authenticate([FromBody] LoginDto loginDto)
        {
            var result = new ResultDto <UsuarioAutenticadoDto>();

            try
            {
                if (loginDto == null)
                {
                    throw new AwayException("Datos inválidos.");
                }

                var usuarioDto = await _usuarioService.GetByCredentialsAsync(loginDto.User, loginDto.Pass);

                if ((usuarioDto == null) || (usuarioDto.Id <= 0))
                {
                    throw new AwayException("Usuario/Password inválidos.");
                }

                result.Data = new UsuarioAutenticadoDto()
                {
                    Id       = usuarioDto.Id,
                    Nombre   = usuarioDto.Nombre,
                    Apellido = usuarioDto.Apellido,
                    Rol      = usuarioDto.Rol,
                    Token    = AwayTokenGenerator.GenerateTokenJwt(_appSettings, _jwtIssuerOptions, usuarioDto)
                };
            }
            catch (AwayException ex)
            {
                _logger.Error(KOriginApp, ex.Message, ex);
                result.AddError(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.Error(KOriginApp, ex.Message, ex);
                result.AddError("Ocurrió un error al intentar logearse en el sistema.");
            }
            return(Ok(result));
        }
Пример #5
0
        public async Task <ResultDto <Domain.Contact.Contact> > GetAsync(int contactId)
        {
            var contact = await _contactRepository.GetAsync(contactId);

            var result = new ResultDto <Domain.Contact.Contact>(contact);

            if (result.Data == null)
            {
                result.AddError(ErrorCodeDto.GeneralNotFound);
                return(result);
            }

            return(result);
        }
Пример #6
0
        public async Task <ActionResult> Login([FromBody] LoginDto model, CancellationToken cancellationToken = default)
        {
            var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.IsPersistente, false);

            if (result.Succeeded)
            {
                var user = _userManager.Users.SingleOrDefault(r => r.Email == model.Email);
                return(Ok(await GenerateJwtToken(model.Email, user, Request.Headers["Origin"])));
            }
            var errorResult = new ResultDto();

            errorResult.AddError("Credenziali Errate");
            return(BadRequest(errorResult));
        }
        public async Task <IActionResult> Post([FromBody] EnteDocumentoTipoDto valueDto)
        {
            var result = new ResultDto <EnteDocumentoTipoDto>();

            try
            {
                result.Data = await _enteDocumentoTipoService.CreateAsync(valueDto);
            }
            catch (Exception ex)
            {
                _logger.Error(KOriginApp, ex.Message, ex);
                result.AddError("Ocurrió un error al intentar agregar el registro.");
            }
            return(Ok(result));
        }
        public async Task <IActionResult> Get(long id)
        {
            var result = new ResultDto <EnteDocumentoTipoDto>();

            try
            {
                result.Data = await _enteDocumentoTipoService.GetByIdAsync(id);
            }
            catch (Exception ex)
            {
                _logger.Error(KOriginApp, ex.Message, ex);
                result.AddError("Ocurrió un error al obtener los datos del registro.");
            }
            return(Ok(result));
        }
Пример #9
0
        public async Task <ResultDto <ICollection <Domain.Contact.Contact> > > GetAllAsync()
        {
            //SQLLite does not support this sort on query (decimal not native)
            //System.NotSupportedException: SQLite cannot order by expressions of type 'decimal'.
            var contacts = (await _contactRepository.GetAllAsync()).OrderBy(c => c.Sequence).ToList();
            var result   = new ResultDto <ICollection <Domain.Contact.Contact> >();

            if (!contacts.Any())
            {
                result.AddError(ErrorCodeDto.GeneralNotFound);
                return(result);
            }

            result.AddData(contacts);
            return(result);
        }
        public async Task <IActionResult> GetAll()
        {
            var result = new ResultDto <List <EnteDocumentoTipoDto> >();

            try
            {
                var listDataDto = await _enteDocumentoTipoService.GetAsync();

                result.Data = listDataDto.Items;
            }
            catch (Exception ex)
            {
                _logger.Error(KOriginApp, ex.Message, ex);
                result.AddError("Ocurrió un error al obtener el listado de tipos de documento.");
            }
            return(Ok(result));
        }
Пример #11
0
        public async Task <IActionResult> GetActives()
        {
            var result = new ResultDto <List <SucursalDto> >();

            try
            {
                var listDataDto = await _sucursalService.GetActivesAsync();

                result.Data = listDataDto.Items;
            }
            catch (Exception ex)
            {
                _logger.Error(KOriginApp, ex.Message, ex);
                result.AddError("Ocurrió un error al obtener el listado de sucursales.");
            }
            return(Ok(result));
        }
Пример #12
0
        public async Task <IActionResult> GetAll()
        {
            var result = new ResultDto <List <ArticuloLineaDto> >();

            try
            {
                var listDataDto = await _articuloLineaService.GetAsync();

                result.Data = listDataDto.Items;
            }
            catch (Exception ex)
            {
                _logger.Error(KOriginApp, ex.Message, ex);
                result.AddError("Ocurrió un error al obtener el listado de líneas de artículo.");
            }
            return(Ok(result));
        }
Пример #13
0
        public async Task <IActionResult> GetAll()
        {
            var result = new ResultDto <List <ClienteCategoriaDto> >();

            try
            {
                var listDataDto = await _clienteCategoriaService.GetAsync();

                result.Data = listDataDto.Items;
            }
            catch (Exception ex)
            {
                _logger.Error(KOriginApp, ex.Message, ex);
                result.AddError("Ocurrió un error al obtener el listado de categorías de cliente.");
            }
            return(Ok(result));
        }
Пример #14
0
        public async Task <IActionResult> Get()
        {
            var result = new ResultDto <List <LogDto> >();

            try
            {
                var rolesDto = await _logService.GetAsync();

                result.Data = rolesDto.Items;
            }
            catch (Exception ex)
            {
                _logger.Error(KOriginApp, ex.Message, ex);
                result.AddError("Ocurrió un error al obtener el listado de logs.");
            }
            return(Ok(result));
        }
Пример #15
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseAuthentication();

            app.UseCors("AllowSpecificOrigin");

            app.UseStatusCodePages(async context =>
            {
                context.HttpContext.Response.ContentType = "application/json";
                var result = new ResultDto();
                result.AddError(string.Format("status code: {0}", context.HttpContext.Response.StatusCode));
                await context.HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(result));
            });

            app.UseExceptionHandler(appBuilder =>
            {
                appBuilder.Use(async(context, next) =>
                {
                    var error = context.Features[typeof(IExceptionHandlerFeature)] as IExceptionHandlerFeature;

                    //when authorization has failed, should retrun a json message to client
                    if (error?.Error is SecurityTokenExpiredException)
                    {
                        context.Response.StatusCode  = 401;
                        context.Response.ContentType = "application/json";

                        var result = new ResultDto();
                        result.AddError("El token expiró");
                        await context.Response.WriteAsync(JsonConvert.SerializeObject(result));
                    }
                    else if (error?.Error is SecurityTokenValidationException)
                    {
                        context.Response.StatusCode  = 401;
                        context.Response.ContentType = "application/json";

                        var result = new ResultDto();
                        result.AddError("El token no es válido!!");
                        await context.Response.WriteAsync(JsonConvert.SerializeObject(result));
                    }
                    else if (error?.Error != null)
                    {
                        context.Response.StatusCode  = 500;
                        context.Response.ContentType = "application/json";

                        var result = new ResultDto();
                        result.AddError(error.Error.Message);
                        await context.Response.WriteAsync(JsonConvert.SerializeObject(result));
                    }
                    //when no error, do next.
                    else
                    {
                        await next();
                    }
                });
            });

            app.UseMvc();

            using (var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope())
            {
                var context = serviceScope.ServiceProvider.GetRequiredService <DataContext>();
                if (context.Database.GetPendingMigrations().ToList().Count > 0)
                {
                    context.Database.Migrate();
                }
            }

            CurrentContextResolver.Configure(app.ApplicationServices.GetRequiredService <IHttpContextAccessor>());
            AwayAppContext.Configure(app.ApplicationServices.GetRequiredService <IHttpContextAccessor>());
        }