protected virtual void TryCatch(Action tryAction, BaseResponse response, Action finallyAction = null) { try { tryAction.Invoke(); } catch (ErrorCodeParameterException ex) { logger.LogError(ex, ex.Message); response.Fail(ex.ErrorCode, ex.Parameters); } catch (ErrorCodeException ex) { logger.LogError(ex, ex.Message); response.Fail(ex.ErrorCode); } catch (Exception ex) { logger.LogError(ex, ex.Message); response.Fail(ErrorCodeDefine.UNKNOW_ERROR); } finally { finallyAction?.Invoke(); } }
protected virtual TResult TryCatchAsync <TResult>(Func <TResult> tryFunction, BaseResponse response, Action finallyAction = null) { try { return(tryFunction.Invoke()); } catch (ErrorCodeParameterException ex) { logger.LogError(ex, ex.Message); response.Fail(ex.ErrorCode, ex.Parameters); } catch (ErrorCodeException ex) { logger.LogError(ex, ex.Message); response.Fail(ex.ErrorCode); } catch (Exception ex) { logger.LogError(ex, ex.Message); response.Fail(ErrorCodeDefine.UNKNOW_ERROR); } finally { finallyAction?.Invoke(); } return(default(TResult)); }
public BaseResponse <object> JoinTeam(int playerId, string teamJoinCode) { if (!_dbContext.Players.Any(x => x.Id == playerId)) { return(BaseResponse <object> .Fail(_errorMessageProvider.PlayerNotFound)); } var team = _dbContext.Teams.FirstOrDefault(x => x.TeamJoinInfo.Key == teamJoinCode); if (team == null) { return(BaseResponse <object> .Fail(_errorMessageProvider.JoinKeyIsInvalid)); } if (_dbContext.CompanyPlayers.Any(x => x.CompanyId == team.Id && x.PlayerId == playerId)) { return(BaseResponse <object> .Fail(_errorMessageProvider.PlayerAlreadyAddedToTeam)); } var playerTeam = new PlayerTeam { IsOwner = false, TeamId = team.Id, PlayerId = playerId, }; _dbContext.PlayerTeams.Add(playerTeam); _dbContext.SaveChanges(); return(BaseResponse <object> .Success()); }
public BaseResponse <object> JoinCompany(int playerId, string companyJoinCode) { if (!_dbContext.Players.Any(x => x.Id == playerId)) { return(BaseResponse <object> .Fail(_errorMessageProvider.PlayerNotFound)); } var company = _dbContext.Companies.FirstOrDefault(x => x.CompanyJoinInfo.Key == companyJoinCode); if (company == null) { return(BaseResponse <object> .Fail(_errorMessageProvider.JoinKeyIsInvalid)); } if (_dbContext.CompanyPlayers.Any(x => x.CompanyId == company.Id && x.PlayerId == playerId)) { return(BaseResponse <object> .Fail(_errorMessageProvider.PlayerAlreadyAddedToCompany)); } var companyPlayer = new CompanyPlayer { IsOwner = false, CompanyId = company.Id, PlayerId = playerId, }; _dbContext.CompanyPlayers.Add(companyPlayer); _dbContext.SaveChanges(); return(BaseResponse <object> .Success()); }
public BaseResponse <object> SetAnswer(int playerId, int taskId, string answer) { if (!_dbContext.Players.Any(x => x.Id == playerId)) { return(BaseResponse <object> .Fail(_errorMessageProvider.PlayerNotFound)); } var task = _dbContext.Tasks.FirstOrDefault(x => x.Id == taskId); if (task == null) { return(BaseResponse <object> .Fail(_errorMessageProvider.TaskNotFound)); } if (task.Answer != answer) { return(BaseResponse <object> .Fail(_errorMessageProvider.AnswerIsWrong)); } var playerTask = new PlayerTask { PlayerId = playerId, TaskId = taskId, }; _dbContext.PlayerTasks.Add(playerTask); _dbContext.SaveChanges(); return(BaseResponse <object> .Success()); }
public BaseResponse <object> Create(int playerId, int companyId, ChallangeRequest request) { var validationResult = Validate <object>(request); if (!validationResult.Ok) { return(validationResult); } if (!_dbContext.Companies.Any(x => x.Id == companyId && x.Players.Any(q => q.IsOwner && q.PlayerId == playerId))) { return(BaseResponse <object> .Fail(_errorMessageProvider.CompanyNotFound)); } var challange = new Challange { CompanyId = companyId, Desciprion = request.Description, Name = request.Name, PlayerOwnerId = playerId, }; _dbContext.Challanges.Add(challange); _dbContext.SaveChanges(); return(BaseResponse <object> .Success()); }
public async Task <BaseResponse> SubscribeAsync(SubscriptionModel subscriptionModel) { try { string requestUrl = $"{_configuration["WebService:url"]}" + $"?date={subscriptionModel.ShortDate.ToString("yyyy-MM-dd")}" + $"&callback={subscriptionModel.CallbackUrl}"; var responseObject = await _httpClient.SendGetAsync <AlaricMonitorResponseModel>(requestUrl); var domainModel = _mapper.Map <SubscirptionDataModel>(responseObject); var entityModel = _mapper.Map <Entities.SubscriptionData>(domainModel); await _repository.AddAsync(entityModel); await _unitOfWork.SaveChangesAsync(); _connectionStore.Add(domainModel.Token, subscriptionModel.SignalRConnectionId); return(BaseResponse.Ok()); } catch (HttpRequestException httpEx) { _logger.LogError(httpEx, "When making http request"); return(BaseResponse.Fail("Error when making http request", System.Net.HttpStatusCode.BadGateway)); } catch (Exception ex) { _logger.LogError(ex, "SubscriptionService"); return(BaseResponse.Fail("Error in internal service", System.Net.HttpStatusCode.InternalServerError)); } }
public BaseResponse <object> Upate(int playerId, int challangeId, ChallangeRequest request) { var validationResult = Validate <object>(request); if (!validationResult.Ok) { return(validationResult); } var challange = _dbContext.Challanges.FirstOrDefault(x => x.Id == challangeId && x.Company.Players.Any(q => q.IsOwner && q.PlayerId == playerId)); if (challange == null) { return(BaseResponse <object> .Fail(_errorMessageProvider.ChallangeNotFound)); } challange.Name = request.Name; challange.Desciprion = request.Description; _dbContext.SaveChanges(); return(BaseResponse <object> .Success()); }
public void OnException(ExceptionContext context) { if (context.Exception is RequestNotValidatedException requestNotValidatedException) { var hasAnyFailures = requestNotValidatedException.Failures != null && requestNotValidatedException.Failures.Any(); var response = BaseResponse.Fail("Not Validated", hasAnyFailures ? requestNotValidatedException.Failures : new string[] { requestNotValidatedException.Message }); context.Result = new ObjectResult(response) { StatusCode = (int)HttpStatusCode.BadRequest }; } else if (context.Exception is EntityNotFoundException entityNotFoundException) { var response = BaseResponse.Fail("Not Found", new string[] { entityNotFoundException.Message }); context.Result = new ObjectResult(response) { StatusCode = (int)HttpStatusCode.NotFound }; } else { var response = BaseResponse.Fail("Unhandled Exception", new string[] { context.Exception.Message }); context.Result = new ObjectResult(response) { StatusCode = (int)HttpStatusCode.InternalServerError }; } context.ExceptionHandled = true; }
public BaseResponse <object> AcceptChallange(int playerId, int teamId, int challangeId) { var challange = _dbContext.Challanges.FirstOrDefault(x => x.Id == challangeId); if (challange == null) { return(BaseResponse <object> .Fail(_errorMessageProvider.ChallangeNotFound)); } if (!_dbContext.Teams.Any(x => x.Id == teamId && x.Players.Any(q => q.IsOwner && q.PlayerId == playerId) && x.CompanyId == challange.CompanyId)) { return(BaseResponse <object> .Fail(_errorMessageProvider.TeamNotFound)); } if (_dbContext.ChallangeTeams.Any(x => x.ChallangeId == challangeId && x.TeamId == teamId)) { return(BaseResponse <object> .Fail(_errorMessageProvider.ChallangeAlreadyAccepted)); } var challangeTeam = new ChallangeTeam { ChallangeId = challangeId, TeamId = teamId }; _dbContext.ChallangeTeams.Add(challangeTeam); _dbContext.SaveChanges(); return(BaseResponse <object> .Success()); }
public async Task <BaseResponse <CommentViewModel> > Handle(CreateSubCommentCommand command, CancellationToken cancellationToken) { if (IsNullOrEmpty(command.Message)) { return(BaseResponse.Fail <CommentViewModel>(await _translator.GetTranslation("Comment", "NeedMessage"))); } var comment = await _ctx.Comments .Include(x => x.Match) .ThenInclude(x => x.MatchUsers) .FirstAsync(x => x.Id == command.CommentId, cancellationToken: cancellationToken); if (comment == null) { return(BaseResponse.Fail <CommentViewModel>(await _translator.GetTranslation("Comment", "NotFound"))); } var user = await _ctx.UserInformation .FirstAsync(x => x.Id == command.UserId, cancellationToken : cancellationToken); if (user == null) { return(BaseResponse.Fail <CommentViewModel>(await _translator.GetTranslation("User", "NotFound"))); } var subComment = new SubComment { Picture = user.Picture, DisplayName = user.DisplayName, Message = command.Message, TaggedUser = command.TaggedUser }; comment.SubComments.Add(subComment); await _ctx.SaveChangesAsync(cancellationToken); if (!IsNullOrEmpty(command.TaggedUser)) { var taggedUser = await _ctx.UserInformation.FirstAsync(x => x.DisplayName == command.TaggedUser, cancellationToken); _notification.QueueNotification( await _translator.GetTranslation("Notification", "CommentReply", user.DisplayName), new[] { comment.MatchId.ToString(), comment.Id.ToString(), subComment.Id.ToString() }.DefaultJoin(), NotificationMessageType.SubComment, new[] { taggedUser.Id }); } _notification.QueueNotification( await _translator.GetTranslation("Notification", "CommentCreated", user.DisplayName), new[] { comment.MatchId.ToString(), comment.Id.ToString(), subComment.Id.ToString() }.DefaultJoin(), NotificationMessageType.SubComment, comment.Match.GetOtherUserIds(user.Id)); return(BaseResponse.Ok(await _translator.GetTranslation("Comment", "Created"), CommentViewModel.CommentProjection.Compile().Invoke(comment))); }
public BaseResponse <object> Create(int playerId, int companyId, TeamRequest request) { var validationResult = Validate <object>(request); if (!validationResult.Ok) { return(validationResult); } if (!_dbContext.Companies.Any(x => x.Id == companyId)) { return(BaseResponse <object> .Fail(_errorMessageProvider.ChallangeNotFound)); } var player = _dbContext.Players .Include(x => x.Teams) .ThenInclude(x => x.Team) .FirstOrDefault(x => x.Id == playerId); if (player == null) { return(BaseResponse <object> .Fail(_errorMessageProvider.PlayerNotFound)); } if (player.Teams.Where(x => x.IsOwner).Any(x => x.Team.CompanyId == companyId)) { return(BaseResponse <object> .Fail(_errorMessageProvider.PlayerAlreadyHasTeamInThisCompany)); } var team = new Team { Name = request.Name, //TODO do I need make name unique? CompanyId = companyId, }; var teamJoinInfo = new TeamJoinInfo { Team = team, Key = Guid.NewGuid().ToString() //TODO move it to invite generator }; var playerTeam = new PlayerTeam { IsOwner = true, PlayerId = player.Id, Team = team, }; team.Players.Add(playerTeam); _dbContext.Teams.Add(team); _dbContext.PlayerTeams.Add(playerTeam); _dbContext.TeamJoinInfos.Add(teamJoinInfo); _dbContext.SaveChanges(); return(BaseResponse <object> .Success()); }
protected BaseResponse <T> Validate <T>(object obj) { var resultList = new List <ValidationResult>(); if (!Validator.TryValidateObject(obj, new ValidationContext(obj), resultList)) { return(BaseResponse <T> .Fail(string.Join(", ", resultList.Select(x => x.ErrorMessage)))); } return(BaseResponse <T> .Success()); }
public BaseResponse <CompanyResponse> Info(int companyId) { var companyResponse = _dbContext.Companies.FirstOrDefault(x => x.Id == companyId); if (companyResponse == null) { return(BaseResponse <CompanyResponse> .Fail(_errorMessageProvider.CompanyNotFound)); } return(BaseResponse <CompanyResponse> .Success(_mefMapper.Map <Company, CompanyResponse>(companyResponse))); }
public BaseResponse <TeamResponse> Info(int teamId) { var team = _dbContext.Teams.FirstOrDefault(x => x.Id == teamId); if (team == null) { return(BaseResponse <TeamResponse> .Fail(_errorMessageProvider.TaskNotFound)); } return(BaseResponse <TeamResponse> .Success(_mefMapper.Map <Team, TeamResponse>(team))); }
public BaseResponse <TaskResponse> Info(int taskId) { var task = _dbContext.Tasks.FirstOrDefault(x => x.Id == taskId); if (task == null) { return(BaseResponse <TaskResponse> .Fail(_errorMessageProvider.TaskNotFound)); } return(BaseResponse <TaskResponse> .Success(_mefMapper.Map <Entities.Task, TaskResponse>(task))); }
public BaseResponse <ChallangeResponse> Info(int challangeId) { var challange = _dbContext.Challanges.FirstOrDefault(x => x.Id == challangeId); if (challange == null) { return(BaseResponse <ChallangeResponse> .Fail(_errorMessageProvider.ChallangeNotFound)); } return(BaseResponse <ChallangeResponse> .Success(_mefMapper.Map <Challange, ChallangeResponse>(challange))); }
public BaseResponse <string> GetCompanyJoinCode(int playerId, int companyId) { var company = _dbContext.Companies.Include(x => x.CompanyJoinInfo) .FirstOrDefault(x => x.Id == companyId && x.Players.Any( q => q.IsOwner && q.PlayerId == playerId)); if (company == null) { return(BaseResponse <string> .Fail(_errorMessageProvider.CompanyNotFound)); } return(BaseResponse <string> .Success(company.CompanyJoinInfo.Key)); }
//TODO check cascade task remove! public BaseResponse <object> Delete(int playerId, int teamId) { var team = _dbContext.Teams.FirstOrDefault(x => x.Id == teamId && x.Players.Any(q => q.IsOwner && q.PlayerId == playerId)); if (team == null) { return(BaseResponse <object> .Fail(_errorMessageProvider.TeamNotFound)); } _dbContext.Teams.Remove(team); _dbContext.SaveChanges(); return(BaseResponse <object> .Success()); }
public BaseResponse <object> LeaveTeam(int playerId, int teamId) { var playerTeam = _dbContext.PlayerTeams.FirstOrDefault(x => x.TeamId == teamId && x.PlayerId == playerId); if (playerTeam == null) { return(BaseResponse <object> .Fail(_errorMessageProvider.PlayerDoesNotExistInThisTeam)); } _dbContext.PlayerTeams.Remove(playerTeam); _dbContext.SaveChanges(); return(BaseResponse <object> .Success()); }
public BaseResponse <object> LeaveCompany(int playerId, int companyId) { var companyPlayer = _dbContext.CompanyPlayers.FirstOrDefault(x => x.CompanyId == companyId && x.PlayerId == playerId); if (companyPlayer == null) { return(BaseResponse <object> .Fail(_errorMessageProvider.PlayerDoesNotExistInThisCompany)); } _dbContext.CompanyPlayers.Remove(companyPlayer); _dbContext.SaveChanges(); return(BaseResponse <object> .Success()); }
public BaseResponse <object> Delete(int playerId, int companyId) { var company = _dbContext.Companies.FirstOrDefault(x => x.Id == companyId && x.Players.Any(q => q.IsOwner && q.PlayerId == playerId)); if (company == null) { return(BaseResponse <object> .Fail(_errorMessageProvider.CompanyNotFound)); } _dbContext.Companies.Remove(company); _dbContext.SaveChanges(); return(BaseResponse <object> .Success()); }
public BaseResponse <object> Delete(int playerId, int taskId) { var task = _dbContext.Tasks.FirstOrDefault(x => x.Id == taskId && x.Challange.Company.Players.Any(q => q.IsOwner && q.CompanyId == playerId)); if (task == null) { return(BaseResponse <object> .Fail(_errorMessageProvider.TaskNotFound)); } _dbContext.Tasks.Remove(task); _dbContext.SaveChanges(); return(BaseResponse <object> .Success()); }
public async Task <BaseResponse> InsertMobile(InsertMobileModel model) { BaseResponse response = null; try { var repo = (_mobilieRepository as MobileRepository); response = BaseResponse.Ok(); var mobile = new Mobile { Brand = model.Brand, CPU = model.CPU, InternalMemory = model.InternalMemory, Name = model.Name, OS = model.OS, Price = model.Price, RAM = model.RAM, ScreenResolution = model.ScreenResolution, ScreenSize = model.ScreenSize, Size = model.Size, VideoUrl = model.VideoUrl, Weight = model.Weight }; foreach (var item in model.Photos) { var photo = new Domain.DAO.Entities.Photo() { Value = item.Base64 }; mobile.Photos.Add(photo); } repo.Add(mobile); repo.Save(); } catch (Exception ex) { _logger.LogError(ex.Message); response = BaseResponse.Fail($"Could not add item"); } return(response); }
public async Task <BaseResponse <CommentViewModel> > Handle( CreateCommentCommand request, CancellationToken cancellationToken) { if (IsNullOrEmpty(request.Message)) { return(BaseResponse.Fail <CommentViewModel>(await _translator.GetTranslation("Comment", "NeedMessage"))); } var match = await _ctx.Matches.AsNoTracking() .Include(x => x.MatchUsers) .FirstAsync(x => x.Id == request.MatchId, cancellationToken); if (match == null) { return(BaseResponse.Fail <CommentViewModel>(await _translator.GetTranslation("Match", "NotFound"))); } var user = _ctx.UserInformation.AsNoTracking().FirstOrDefault(x => x.Id == request.UserId); if (user == null) { return(BaseResponse.Fail <CommentViewModel>(await _translator.GetTranslation("User", "NotFound"))); } var comment = new Comment { MatchId = match.Id, Picture = user.Picture, DisplayName = user.DisplayName, Message = request.Message }; _ctx.Comments.Add(comment); await _ctx.SaveChangesAsync(cancellationToken); var message = await _translator.GetTranslation("Notification", "CommentCreated", user.DisplayName); _notification.QueueNotification(message, new[] { match.Id.ToString(), comment.Id.ToString() }.DefaultJoin(), NotificationMessageType.Comment, match.GetOtherUserIds(user.Id)); return(BaseResponse.Ok(await _translator.GetTranslation("Comment", "Created"), CommentViewModel.CommentProjection.Compile().Invoke(comment))); }
public async Task <BaseResponse> GetMobilelist(GetMobileListRequest request) { BaseResponse <List <MobileListItem> > response = null; try { var result = await(_mobilieRepository as MobileRepository) .FindBy(x => (x.FilterProductByQueryString(request.QueryString)) && (x.FilterProductByPriceRange(request.PriceFrom, request.PriceTo))) .Include(x => x.Photos).ToListAsync(); response = BaseResponse.Ok(new List <MobileListItem>()); foreach (var item in result) { response.Data.Add(new MobileListItem() { Brand = item.Brand, CPU = item.CPU, InternalMemory = item.InternalMemory, MobileId = item.Id, Name = item.Name, OS = item.OS, Price = item.Price, RAM = item.RAM, ScreenResolution = item.ScreenResolution, ScreenSize = item.ScreenSize, Size = item.Size, VideoUrl = item.VideoUrl, Weight = item.Weight, Photos = (item.Photos as List <Domain.DAO.Entities.Photo>).Select(x => new Domain.DTO.ServiceModels.Photo() { Base64 = x.Value, PhotoId = x.Id }).ToList() }); } } catch (Exception e) { _logger.LogError(e.Message); response = BaseResponse.Fail <List <MobileListItem> >(new Error() { Code = ErrorCode.Internal, ErrorMessage = "Could not find products." }); } return(response); }
public BaseResponse <LoginResponse> Login(string email, string password) { var player = _dbContext.Players .Include(x => x.Roles) .ThenInclude(x => x.Role) .FirstOrDefault(x => x.Email == email); if (player == null || !HashPassword(player.PasswordSalt, password).SequenceEqual(player.PasswordHash)) { return(BaseResponse <LoginResponse> .Fail(_errorMessageProvider.EmailOrPasswordIsIncorrect)); } return(BaseResponse <LoginResponse> .Success(new LoginResponse { Roles = player.Roles.Select(x => x.Role.Name), PlayerId = player.Id.ToString() })); }
public async Task <BaseResponse> GetMobile(int id) { BaseResponse <MobileListItem> response = null; try { var item = await(_mobilieRepository as MobileRepository).FindBy(m => m.Id == id) .Include(m => m.Photos).SingleOrDefaultAsync(); var responseItem = new MobileListItem { Brand = item.Brand, CPU = item.CPU, InternalMemory = item.InternalMemory, MobileId = item.Id, Name = item.Name, OS = item.OS, Price = item.Price, RAM = item.RAM, ScreenResolution = item.ScreenResolution, ScreenSize = item.ScreenSize, Size = item.Size, VideoUrl = item.VideoUrl, Weight = item.Weight, Photos = (item.Photos as List <Domain.DAO.Entities.Photo>).Select(x => new Domain.DTO.ServiceModels.Photo() { Base64 = x.Value, PhotoId = x.Id }).ToList() }; response = BaseResponse.Ok(responseItem); } catch (Exception e) { _logger.LogError(e.Message); response = BaseResponse.Fail <MobileListItem>(new Error() { Code = ErrorCode.Internal, ErrorMessage = "Could not find product" }); } return(response); }
public BaseResponse <object> Upate(int playerId, int taskId, TaskRequest request) { var task = _dbContext.Tasks.FirstOrDefault(x => x.Id == taskId && x.Challange.Company.Players.Any(q => q.IsOwner && q.CompanyId == playerId)); if (task == null) { return(BaseResponse <object> .Fail(_errorMessageProvider.TaskNotFound)); } task.Answer = request.Answer; task.Description = request.Description; task.Name = request.Name; task.Score = request.Score; _dbContext.SaveChanges(); return(BaseResponse <object> .Success()); }
public BaseResponse <object> Create(int playerId, int challangeId, TaskRequest request) { if (!_dbContext.Challanges.Any(x => x.Id == challangeId && x.Company.Players.Any(q => q.IsOwner && q.PlayerId == playerId))) { return(BaseResponse <object> .Fail(_errorMessageProvider.ChallangeNotFound)); } var task = new Entities.Task { Answer = request.Answer, Description = request.Description, Name = request.Name, Score = request.Score }; _dbContext.Tasks.Add(task); _dbContext.SaveChanges(); return(BaseResponse <object> .Success()); }