コード例 #1
0
        public async Task Invoke(HttpContext context)
        {
            try
            {
                _timer.Start();
                await _next(context);

                _timer.Stop();
            }
            finally
            {
                if (_timer.ElapsedMilliseconds > 500)
                {
                    _logger.LogWarning($"Long Running {MessageTemplate}",
                                       context.Request?.Method,
                                       context.Request?.Path,
                                       context.Response?.StatusCode,
                                       _timer.Elapsed.TotalMilliseconds);
                }

                _logger.LogInformation(MessageTemplate,
                                       context.Request?.Method,
                                       context.Request?.Path,
                                       context.Response?.StatusCode,
                                       _timer.Elapsed.TotalMilliseconds);
            }
        }
コード例 #2
0
        public async Task <IActionResult> OnPost(IEnumerable <BasketItemViewModel> items)
        {
            try
            {
                await SetBasketModelAsync();

                if (!ModelState.IsValid)
                {
                    return(BadRequest());
                }

                var updateModel = items.ToDictionary(b => b.Id.ToString(), b => b.Quantity);
                await _basketService.SetQuantities(BasketModel.Id, updateModel);

                await _orderService.CreateOrderAsync(BasketModel.Id, new Address("123 Main St.", "Kent", "OH", "United States", "44240"));

                await _basketService.DeleteBasketAsync(BasketModel.Id);
            }
            catch (EmptyBasketOnCheckoutException emptyBasketOnCheckoutException)
            {
                //Redirect to Empty Basket page
                _logger.LogWarning(emptyBasketOnCheckoutException.Message);
                return(RedirectToPage("/Basket/Index"));
            }

            return(RedirectToPage("Success"));
        }
コード例 #3
0
        public IActionResult Get(double leftInput, double rightInput, int logicCode)
        {
            string result = string.Empty;

            try
            {
                result = _probabilityCalculationService.GetCalculationResult(
                    leftInput,
                    rightInput,
                    logicCode
                    ).Result.ToString();
            }
            catch (Exception ex)
            {
                _logger.LogWarning(
                    ex.StackTrace.ToString(),
                    leftInput,
                    rightInput,
                    logicCode
                    );

                return(StatusCode(StatusCodes.Status500InternalServerError));
            }

            return(Ok(new { calculationResult = result }));
        }
コード例 #4
0
        public Guid?Post(CustomerVm customerVm)
        {
            try
            {
                var customer = new Customer()
                {
                    Will            = _willService.Get(customerVm.WillId),
                    FirstName       = customerVm.FirstName,
                    LastName        = customerVm.LastName,
                    DateOfBirth     = new DateTime(customerVm.DateOfBirth.Year, customerVm.DateOfBirth.Month, customerVm.DateOfBirth.Day),
                    Address         = customerVm.Address.ToAddress(),
                    Telephone       = customerVm.Telephone,
                    MaritalStatusId = customerVm.MaritalStatusId,
                    //MaritalStatus = _maritalStatusVmService.Get(customerVm.MaritalStatusId),
                    UpdatedUtc = DateTime.UtcNow
                };

                return(_customerService.AddOrUpdate(customer));
            }
            catch (Exception e)
            {
                _logger.LogWarning("CustomerVmService Post exception", e.Message);
                return(null);
            }
        }
コード例 #5
0
        public async Task <IActionResult> OnGetAsync(int?negocioId, string searchString, int?currentPage, int?sizePage)
        {
            try
            {
                if (!negocioId.HasValue)
                {
                    _notifyService.Warning($"Debe seleccionar una zona para ver sus productos");
                    return(RedirectToPage("Index", new { area = "Negocios" }));
                }

                Negocio = await _negocioRepository.GetByIdAsync(negocioId.Value);

                if (Negocio == null)
                {
                    _notifyService.Warning($"No se ha encontrado la zona con el id {negocioId.Value}");
                    return(RedirectToPage("Index", new { area = "Negocios" }));
                }

                var totalItems = await _repository.CountAsync(new ProductoSpec(
                                                                  new ProductoFilter
                {
                    NegocioId = negocioId.Value,
                    Nombre = searchString, LoadChildren = false,
                    IsPagingEnabled = true
                }));

                UIPagination = new UIPaginationModel(currentPage, searchString, sizePage, totalItems);

                Productos = await _repository.ListAsync(new ProductoSpec(
                                                            new ProductoFilter
                {
                    IsPagingEnabled = true,
                    Nombre = UIPagination.SearchString,
                    NegocioId = negocioId.Value,
                    PageSize = UIPagination.GetPageSize,
                    Page = UIPagination.GetCurrentPage
                })
                                                        );

                return(Page());
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex.Message);
                return(RedirectToPage("Index", new { area = "Negocios" }));
            }
        }
コード例 #6
0
 private void GetWillInfo(Guid id)
 {
     try
     {
         WillInfo = _willVmService.Get(id);
     }
     catch (ArgumentNullException e)
     {
         _logger.LogWarning("Partner GetWillInfo exception", e.Message);
         ErrorMessage = _errorNotFound;
     }
     catch (Exception e)
     {
         _logger.LogWarning("Partner GetWillInfo exception", e.Message);
         ErrorMessage = _errorDefaultMessage;
     }
 }
コード例 #7
0
        public async Task <Battery> UpdateBatteryAsync(int accountId, Battery battery)
        {
            Guard.AgainstNull(battery, "battery");
            Guard.AgainstAccountNumberMismatch(accountId, battery.AccountId, "accountId", "battery.AccountId");

            var result = await _batteryRepository.UpdateAsync(battery); // Use batteryex

            if (result != null)
            {
                _logger.LogInformation($"Updated battery, Id = {battery.Id}");
            }
            else
            {
                _logger.LogWarning($"Could not update battery, Id = {battery.Id}");
            }
            return(result);
        }
コード例 #8
0
ファイル: UserService.cs プロジェクト: ngnam/Test.Novaon.NET
        public async Task <IResponse> SignUp(UserModel model)
        {
            IResponse response = null;

            try
            {
                if (model == null)
                {
                    response.HasError = true;
                    response.Result   = null;
                    response.Errors.Add(new IdentityError {
                        Code = "BussinessError000", Description = "The model not found."
                    });
                }
                else
                {
                    // Check emailExist
                    var emailExist = _userRepository.Table.Any(u => u.Email == model.Email);
                    if (emailExist)
                    {
                        response.HasError = true;
                        response.Result   = null;
                        response.Errors.Add(new IdentityError {
                            Code = "BussinessError001", Description = $"The Email {model.Email} is already in use."
                        });
                    }
                    else
                    {
                        // insert
                        User user = new User();
                        user.Email        = model.Email;
                        user.Id           = Guid.NewGuid().ToString("N");
                        user.PasswordHash = Helpers.Encryptor.MD5Hash(model.Password);
                        var userSaved = await _userRepository.AddAsync(user);

                        response.Result.data = true;
                        response.HasError    = false;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning("Error when sign In", ex);
            }
            return(await Task.FromResult(response));
        }
コード例 #9
0
        public List <string> GetBillOfMaterials(BuilderType builderType)
        {
            string bill;
            var    bills = new List <string>();

            // Note : Use of Factory pattern prefered to inheritance/interface implementation
            IBillGenerator billGenerator = _billFactoryService.Create(builderType);

            try
            {
                foreach (var spec in _repository.ListAll())
                {
                    switch (spec.ShapeType)
                    {
                    case ShapeType.Rectangle:
                        bill = billGenerator.ProcessRectangle(new Rectangle(spec.PositionX, spec.PositionY, spec.Width, spec.Height));
                        bills.Add(bill);
                        break;

                    case ShapeType.Square:
                        bill = billGenerator.ProcessSquare(new Square(spec.PositionX, spec.PositionY, spec.Width));
                        bills.Add(bill);
                        break;

                    case ShapeType.Ellipse:
                        bill = billGenerator.ProcessEllipse(new Ellipse(spec.PositionX, spec.PositionY, spec.VerticalDiameter, spec.HorizontalDiameter));
                        bills.Add(bill);
                        break;

                    case ShapeType.Circle:
                        bill = billGenerator.ProcessCircle(new Circle(spec.PositionX, spec.PositionY, spec.Diameter));
                        bills.Add(bill);
                        break;

                    case ShapeType.Textbox:
                        bill = billGenerator.ProcessTextbox(new Textbox(spec.PositionX, spec.PositionY, spec.Width, spec.Height, spec.Text));
                        bills.Add(bill);
                        break;

                    default:
                        throw new UnknownShapeException();
                    }
                }
            }
            catch (InvalidMeasurementException ex)
            {
                bills.Add(Messages.Abort);
                _logger.LogWarning($"Error in GetBillOfMaterials : {ex.Message}");
            }
            catch (Exception)
            {
                throw;
            }

            return(bills);
        }
コード例 #10
0
        //TODO: Create a new object Report and insert it into DB
        public void ScrapeNewReleasedMovie()
        {
            _logger?.LogInformation("************** Start Scraping New Released Movies Job - {Date} **************", DateTime.Now.ToString("u", DateTimeFormatInfo.InvariantInfo));
            UrlInfo urlInfo = new UrlInfo()
            {
                EntryType = JavlibEntryType.NewRelease
            };
            int pageCount = GetPageCount(urlInfo);

            if (pageCount > 0)
            {
                _logger?.LogInformation($"Found {pageCount} pages. Now scanning movies on each page");
                for (int currentPage = 1; currentPage <= pageCount; currentPage++)
                {
                    List <Movie> lstMovieCurrentPage = ScanPageList(new UrlInfo {
                        EntryType = JavlibEntryType.NewRelease, Page = currentPage
                    }).GroupBy(x => x.Url).Select(x => x.First()).ToList();
                    if (lstMovieCurrentPage.Count > 0)
                    {
                        _logger?.LogInformation("Treating {pageCount} movies in page {currentPage}", lstMovieCurrentPage.Count, currentPage);
                        foreach (Movie movie in lstMovieCurrentPage.GroupBy(x => x.Number.ToUpper()).Select(x => x.First()))
                        {
                            ScanMovieDetails(new UrlInfo()
                            {
                                EntryType = JavlibEntryType.Movie, ExactUrl = movie.Url
                            }, movie);
                            _movieService.UpdateStatus(movie, MovieStatus.Scanned);
                            if (lstMovieCurrentPage.FindAll(c => c.Number == movie.Number).Count > 1)
                            {
                                movie.FavLevel = JavlibFavLevel.DlChineseSub;
                            }
                            _movieService.SaveMovie(movie, true);
                        }
                    }
                }
            }
            else
            {
                _logger?.LogWarning("Nothing found when scraping new released movie. UrlInfo: {0}", urlInfo.ToString());
            }

            _logger?.LogInformation("************** Scraping New Released Movies Job End - {Date} **************", DateTime.Now.ToString("u", DateTimeFormatInfo.InvariantInfo));
        }
コード例 #11
0
        public async Task <string> SaveFileOnAWSS3(IFormFile file, string fileName, string bucketName)
        {
            try
            {
                var urlFotografia = string.Empty;
                using (var memoryStream = new MemoryStream())
                {
                    await file.CopyToAsync(memoryStream);

                    urlFotografia = await _fileSystem.SaveImage(memoryStream, fileName, bucketName);
                }
                return(string.IsNullOrEmpty(urlFotografia) ? null : urlFotografia);
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex.Message);
                return(null);
            }
        }
コード例 #12
0
        public async Task <IActionResult> OnGet(int id)
        {
            try
            {
                var tipoNegocio = await _repository.GetByIdAsync(id);

                if (tipoNegocio == null)
                {
                    _notifyService.Warning($"No se ha encontrado el registro con el id {id}");
                    return(RedirectToPage("Index"));
                }
                TipoNegocio = tipoNegocio;
                return(Page());
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex.Message);
                throw;
            }
        }
コード例 #13
0
        public async Task <IActionResult> OnGet(int id)
        {
            try
            {
                var categoria = await _repository.GetByIdAsync(id);

                if (categoria == null)
                {
                    _notifyService.Warning($"No se ha encontrado la categoria con el id {id}");
                    return(RedirectToPage("Index"));
                }
                Categoria = categoria;
                return(Page());
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex.Message);
                throw;
            }
        }
コード例 #14
0
        public async Task <IActionResult> OnGet(int Id)
        {
            try
            {
                var paquete = await _repository.GetByIdAsync(Id);

                if (paquete == null)
                {
                    _notyfService.Warning($"El paquete, con id {Id}, no ha sido encontrado.");
                    return(RedirectToPage("Index"));
                }
                Paquete = paquete;
                return(Page());
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex.Message);
                throw;
            }
        }
コード例 #15
0
        public async Task <Result <LivroModel> > AddLivroAsync(LivroModel livro)
        {
            var novoLivro = _mapper.Map <Livro>(livro);
            var validator = new LivroValidator();

            var resultValidation = validator.Validate(novoLivro);

            if (!resultValidation.IsValid)
            {
                _logger.LogWarning("Novo livro não passou na validação. Erros: {0}", resultValidation.Errors.ToJson());
                return(Result <LivroModel> .Invalid(resultValidation.AsErrors()));
            }

            var livroAdicionado = await _repositorio.AddAsync(novoLivro);

            Guard.Against.Null(livroAdicionado, "Novo livro");

            _logger.LogInformation("Novo livro foi inserido com sucesso");
            return(Result <LivroModel> .Success(
                       _mapper.Map <LivroModel>(livroAdicionado)));
        }
コード例 #16
0
        //public async Task GetRoles()
        //{
        //    await Task.Run(() =>
        //    {
        //        RolesDictionary =  (_dbContext.Roles.ToList().Select(r => new { r.RoleName, r.RoleId }).ToDictionary(r => r.RoleName, r => r.RoleId));
        //    });
        //}

        //public async Task GetAreas()
        //{
        //    await Task.Run(() =>
        //    {
        //        AreasDictionary = (_dbContext.Areas.ToList().Select(r => new { r.AreaName, r.AreaId }).ToDictionary(r => r.AreaName, r => r.AreaId));
        //    });
        //}

        private Task WhenAllTasks(List <Task> tasks)
        {
            Task allTasks = Task.WhenAll(tasks);

            try
            {
                allTasks.Wait();
            }
            catch (Exception ex)
            {
                _appLogger.LogWarning($"WhenAllTasks Exception: {ex.ToString()}");
            }

            _appLogger.LogWarning($"WhenAllTasks status: {allTasks.Status}");

            if (allTasks.Exception != null)
            {
                throw allTasks.Exception;
            }
            return(allTasks);
        }
コード例 #17
0
        public async Task <Response <string> > InsertAsync(UserDTO model)
        {
            var response = new Response <string>();

            try
            {
                var resp = _mapper.Map <User>(model);
                response.Data = await _Domain.InsertAsync(resp);

                if (response.Data == "Success")
                {
                    response.IsSuccess = true;
                    response.Message   = "Se ha registrado el User exitosamente.";
                }
                else
                {
                    response.IsSuccess = false;
                    response.Message   = "Ha ocurrido un error inesperado, por favor intente nuevamente";
                    _logger.LogWarning("Ha ocurrido un error inesperado registrando el usuario " + model.Username + ", (" + response.Data + ")");
                }
            }
            catch (Exception ex)
            {
                response.IsSuccess = false;
                response.Message   = ex.Message;
                _logger.LogError(ex.Message);
            }

            return(response);
        }
コード例 #18
0
        public async Task <Response <string> > InsertAsync(CorrespondenceDTO model)
        {
            var response = new Response <string>();

            try
            {
                var resp = _mapper.Map <Correspondence>(model);
                response.Data = await _CorrespondencesDomain.InsertAsync(resp);

                if (response.Data == "Success")
                {
                    response.IsSuccess = true;
                    response.Message   = "Se ha registrado la Correspondencia exitosamente.";
                }
                else
                {
                    response.IsSuccess = false;
                    response.Message   = "Ha ocurrido un error inesperado, por favor intente nuevamente";
                    _logger.LogWarning("Ha ocurrido un error inesperado, por favor intente nuevamente " + response.Data);
                }
            }
            catch (Exception ex)
            {
                response.IsSuccess = false;
                response.Message   = ex.Message;
                _logger.LogError(ex.Message);
            }

            return(response);
        }
コード例 #19
0
ファイル: MachineService.cs プロジェクト: Karmil/Machine
        /// <summary>
        ///
        /// </summary>
        /// <param name="custumMachine"></param>
        /// <returns></returns>
        public async Task <Commande> ConstructionCafe(CustumMachine custumMachine)
        {
            // Vérifier la quantite du boisson choisi
            var boissonType = await asyncTypeRepository.GetByIdAsync(custumMachine.IdType);

            if (boissonType is null)
            {
                _logger.LogWarning("boisson n'esxiste pas");
                throw new ArgumentNullException("Idtype", "Votre choix.... ");
            }
            else
            {
                if (boissonType.Quantite > 0)
                {
                    // Reduire la quatite de la quantite consomme
                    boissonType.Quantite--;
                    await asyncTypeRepository.UpdateAsync(boissonType);

                    // Construction commande
                    var command = new Commande
                    {
                        Id            = Guid.NewGuid().ToString(),
                        DateComande   = DateTime.Now,
                        IdTypeBoisson = custumMachine.IdType,
                        Login         = custumMachine.Login,
                        Mug           = custumMachine.Mug
                    };

                    // Sauvgarder la commande
                    return(await asyncCommandeRepository.AddAsync(command));
                }
                else
                {
                    _logger.LogWarning("Boisson " + boissonType.DescriptionType + " terminé");
                    throw new Exception("Il n'a plus de" + boissonType.DescriptionType);
                }
            }
        }
コード例 #20
0
        public async Task SetQuantities(int basketId, Dictionary <string, int> quantities)
        {
            var basket = await _basketRepository.GetByIdAsync(basketId);

            foreach (var item in basket.Items)
            {
                if (quantities.TryGetValue(item.Id.ToString(), out var quantity))
                {
                    _logger.LogWarning($"Updating quantity of item ID:{item.Id} to {quantity}.");
                    item.Quantity = quantity;
                }
            }
            await _basketRepository.UpdateAsync(basket);
        }
コード例 #21
0
        public async Task <JsonResult> OnGetSelect(int Id)
        {
            try
            {
                var paquete = await _repository.GetByIdAsync(Id);

                if (paquete == null)
                {
                    _notyfService.Warning($"El paquete, con id {Id}, no ha sido encontrado.");
                    return(new JsonResult(new { selected = false }));
                }
                Paquete = paquete;
                return(new JsonResult(new
                {
                    info = Paquete
                }));
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex.Message);
                throw;
            }
        }
コード例 #22
0
        public async Task <JsonResult> OnGetMun(string DepName)
        {
            try
            {
                Departamento = await _repositoryDepSV.ListAsync();

                Departamento = Departamento.Where(x => x.DepName == DepName);

                Municipio = await _repositoryMunSV.ListAsync();

                Municipio = Municipio.Where(x => x.DEPSV_ID == Departamento.First().ID);
                if (Municipio == null)
                {
                    return(new JsonResult(new { selected = true }));
                }
                return(new JsonResult(new { Municipio }));
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex.Message);
                throw;
            }
        }
コード例 #23
0
ファイル: CatalogController.cs プロジェクト: safr0/eShopOnWeb
 public IActionResult GetImage(int id)
 {
     byte[] imageBytes;
     try
     {
         imageBytes = _imageService.GetImageBytesById(id);
     }
     catch (CatalogImageMissingException ex)
     {
         _logger.LogWarning($"No image found for id: {id}");
         return(NotFound());
     }
     return(File(imageBytes, "image/png"));
 }
コード例 #24
0
        public async Task <IActionResult> LinkLoginCallback()
        {
            _logger.LogInformation("External login inicialized");
            var infoExternelLogin = await _signInManager.GetExternalLoginInfoAsync();

            if (infoExternelLogin == null)
            {
                _logger.LogWarning("External login failed");
                throw new ApplicationException("Unexpected error occurred loading external login.");
            }

            string email        = infoExternelLogin.Principal.FindFirstValue(ClaimTypes.Email);
            var    providerUser = _userManager.Users.Where(x => x.Email == email && x.ProviderName == infoExternelLogin.ProviderDisplayName).ToList().FirstOrDefault();

            if (providerUser == null)
            {
                // redirecting to a new user's page
                return(LocalRedirect("/Identity/Account/RegisterSocial"));
            }
            else
            {
                var numberDaysActive = Int32.Parse(_configuration.GetValue <string>("SocialLogin:NumberDaysActive"));
                var registrationDate = providerUser.RegistrationDate;
                var diffDates        = DateTime.Now.Subtract(registrationDate);
                if (diffDates.Days > numberDaysActive)
                {
                    // send e-mail for comfirmation
                    providerUser.EmailConfirmed = false;
                    await _userManager.UpdateAsync(providerUser);

                    _logger.LogInformation("User is registered, email confirmation is missing.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(providerUser);

                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { userId = providerUser.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(providerUser.Email, "Confirm your email", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
                }
            }
            // Sign In
            _logger.LogInformation($"External login accepted for {email} by {infoExternelLogin.ProviderDisplayName}");
            await _signInManager.SignInAsync(providerUser, isPersistent : false);

            return(RedirectToAction(nameof(Index)));
        }
コード例 #25
0
        public async Task <CreateUserResponse> Create(string firstName, string lastName, string email, string password)
        {
            _logger.LogInformation("Create new User");

            try
            {
                ApplicationUser appUser = new ApplicationUser {
                    Email = email, UserName = email, FirstName = firstName, LastName = lastName, JwtRole = JwtRole.User
                };

                IdentityResult identityResult = await _userManager.CreateAsync(appUser, password);

                CreateUserResponse result = _mapper.Map <CreateUserResponse>(identityResult);

                return(result);
            }
            catch (Exception ex)
            {
                _logger.LogWarning("Failed to Create new User");
                return(null);

                throw ex;
            }
        }
コード例 #26
0
        public GCPStorageManager(IAppLogger appLogger, GCPSettings gcpSettings)
        {
            _gcpSettings = gcpSettings;
            _appLogger   = appLogger;

            _localRetryPolicy = Policy
                                .Handle <Exception>()
                                .WaitAndRetryAsync(3,
                                                   retryAttempt => TimeSpan.FromMilliseconds(200),
                                                   (exception, timeSpan, retryCount, context) =>
            {
                var msg = $"GCPStorageManager Retry - Count:{retryCount}, Exception:{exception.Message}";
                _appLogger.LogWarning(msg);
            });
        }
コード例 #27
0
 public async Task EnsureLoggedInAsync()
 {
     try
     {
         await _client.GetApiVersionAsync();
     }
     catch (QBittorrentClientRequestException e)
     {
         if (e.StatusCode == HttpStatusCode.Forbidden)
         {
             _logger.LogWarning("Qbittorrent logged out, logging in Now");
             await _client.LoginAsync(_qbittorrentSetting.Username, _qbittorrentSetting.Password);
         }
     }
 }
コード例 #28
0
    public string GetAssociatedProductName(string subscriptionId)
    {
        var subscription = _subscriptionService.Get(subscriptionId); // direct call to Stripe

        var item            = subscription.Items.Data[0];
        var productNickname = item.Price.Nickname; // what if this is null?

        if (String.IsNullOrEmpty(productNickname))
        {
            _logger.LogWarning($"Product Nickname from Stripe for subscription Id {subscriptionId} was null or empty!");
            productNickname = "Default";
        }

        return(productNickname);
    }
コード例 #29
0
        public async Task <IActionResult> OnPost()
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var User = await _User.ListAsync();

                    Console.WriteLine();

                    var result = User.Where(x => x.Email == LoginUser.email).SingleOrDefault();

                    if (result != null && HashHelper.CheckHash(LoginUser.password, result.Contraseña, result.salt))
                    {
                        var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role);
                        identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, result.ID.ToString()));
                        identity.AddClaim(new Claim(ClaimTypes.Name, result.NombreCompleto()));
                        identity.AddClaim(new Claim(ClaimTypes.Email, result.Email));
                        identity.AddClaim(new Claim(ClaimTypes.Webpage, result.Fotografia));
                        identity.AddClaim(new Claim(ClaimTypes.Role, result.Rol));
                        var principal = new ClaimsPrincipal(identity);

                        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal,
                                                      new AuthenticationProperties { ExpiresUtc = DateTime.Now.AddDays(1), IsPersistent = true }
                                                      );

                        _notyfService.Success("Bienvenido, " + result.NombreCompleto());
                        return(RedirectToPage("/Index"));
                    }
                    else
                    {
                        _notyfService.Warning("El usuario o la contraseña son incorrectos");
                        ModelState.AddModelError(nameof(LoginUser.email), "El correo electronico y/o la contraseña son incorrectos");
                        return(Page());
                    }
                }
                else
                {
                    _notyfService.Warning("Por favor complete todos los campos");
                    return(Page());
                }
            }
            catch (Exception ex) {
                _notyfService.Error("Ocurrio un error en el servidor: ");
                _logger.LogWarning(ex.Message);
                return(Page());
            }
        }
コード例 #30
0
        public AWSGameStateStore(IAppLogger appLogger, AWSSettings awsSettings)
        {
            _awsSettings = awsSettings;
            _appLogger   = appLogger;

            _retryPolicy = Policy
                           .Handle <Exception>()
                           .WaitAndRetryAsync(3,
                                              retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
                                              (exception, timeSpan, retryCount, context) =>
            {
                var msg = $"AWSGameStateStore Retry - Count:{retryCount}, Exception:{exception.Message}";
                _appLogger?.LogWarning(msg);
            }
                                              );
        }