public static Response Handle(NancyContext ctx, Exception exception) { var returnCode = HttpStatusCode.BadRequest; var respModel = new DtoResponse(exception.Message) { Data = null, StatusCode = 0, Stack = exception.StackTrace }; if (exception.GetType() == typeof(ResponseException)) { var responseEx = ((ResponseException)exception); returnCode = HttpStatusCode.OK; respModel.StatusCode = (int)responseEx.StatusCode; // Por padrão pega a mensagem via StatusCode Description, do contrário usa a customizada if (exception.Message == "") { respModel.Message = responseEx.StatusCode.GetDescription(); } } if (exception.GetType() == typeof(AcademicoException)) { returnCode = HttpStatusCode.OK; respModel.StatusCode = 100; } var resp = new JsonResponse <DtoResponse>(respModel, new DefaultJsonSerializer()) { StatusCode = returnCode }; // Todas as rotas que retornam - Tentando mapear todas as transações que não possuem status de erro if (returnCode == HttpStatusCode.OK) { var routeDescription = ctx.ResolvedRoute.Description; NewRelicAgent.SetTransactionName("Custom", $"Trilhas Exception {routeDescription.Method} {routeDescription.Path}"); } // Faz com que o new relic mostre mais informações sobre a pessoa que causou o erro if (ctx.CurrentUser != null) { var currentUser = (UserIdentity)ctx.CurrentUser; NewRelicAgent.AddCustomParameter("JWT_TOKEN", currentUser.JwtToken); NewRelicAgent.AddCustomParameter("CPF", currentUser.UserName); NewRelicAgent.AddCustomParameter("Nome", currentUser.Usuario.Nome); NewRelicAgent.AddCustomParameter("Trilha ID", $"{currentUser.Nivel.ID}"); NewRelicAgent.AddCustomParameter("Trilha Nome", $"{currentUser.Nivel.Nome}"); } NewRelicAgent.AddCustomParameter("Stack Trace", exception.StackTrace); resp.Headers.Add("Access-Control-Allow-Origin", "*"); resp.Headers.Add("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE"); resp.Headers.Add("Access-Control-Allow-Headers", "Accept, Origin, Content-type, Authorization"); return(resp); }
/// <summary> /// Handles the specified request. /// </summary> /// <param name="request">The request.</param> /// <param name="response">The response.</param> protected override void Handle(CreateSystemAdminRequest request, DtoResponse <SystemAccountDto> response) { var systemAccount = _systemAccountRepository.GetByIdentifier(request.Email); var roleKey = _roleRepository.GetInternalRoleKeyByName("System Admin"); if (roleKey.HasValue) { if (systemAccount == null) { var result = _systemAccountIdentityServiceManager.Create(request.Email); if (result.Sucess) { var systemAccountFactory = new SystemAccountFactory(); systemAccount = systemAccountFactory.Create(Guid.Empty, request.Email, new Email(request.Email)); systemAccount.AddRole(roleKey.Value); var systemAccountDto = Mapper.Map <SystemAccount, SystemAccountDto> (systemAccount); response.DataTransferObject = systemAccountDto; } else { var dataErrorInfo = new DataErrorInfo(result.ErrorMessage, ErrorLevel.Error); response.DataTransferObject = new SystemAccountDto(); response.DataTransferObject.AddDataErrorInfo(dataErrorInfo); } } else { var dataErrorInfo = new DataErrorInfo("System Admin already exists.", ErrorLevel.Error); response.DataTransferObject = new SystemAccountDto(); response.DataTransferObject.AddDataErrorInfo(dataErrorInfo); } } }
/// <summary> /// Handles the specified request. /// </summary> /// <param name="request">The request.</param> /// <param name="response">The response.</param> protected override void Handle(RemoveStaffFromTeamRequest request, DtoResponse <TeamSummaryDto> response) { var team = _teamRepository.GetByKey(request.TeamKey); team.RemoveStaff(request.StaffKey); response.DataTransferObject = Mapper.Map <Team, TeamSummaryDto> (team); }
protected override void Handle(CreateSystemAdminRequest request, DtoResponse <SystemAccountDto> response) { var systemAccount = _systemAccountRepository.GetByIdentifier(request.Email); var role = _roleRepository.GetInternalRoleKeyByName("System Admin"); if (role != null) { if (systemAccount == null) { var identityServiceResponse = _systemAccountIdentityServiceManager.Create(request.Username, request.Email); if (identityServiceResponse.Sucess) { systemAccount = _systemAccountFactory.CreateSystemAdmin(request.Email, new Email(request.Email)); var systemAccountDto = Mapper.Map <SystemAccount, SystemAccountDto>(systemAccount); response.DataTransferObject = systemAccountDto; systemAccount.AddRole(role); } else { var result = identityServiceResponse.ErrorMessage; var dataErrorInfo = new DataErrorInfo(result, ErrorLevel.Error); response.DataTransferObject = new SystemAccountDto(); response.DataTransferObject.AddDataErrorInfo(dataErrorInfo); } } else { var result = "System account already in use."; var dataErrorInfo = new DataErrorInfo(result, ErrorLevel.Error); response.DataTransferObject = new SystemAccountDto(); response.DataTransferObject.AddDataErrorInfo(dataErrorInfo); } } }
/// <summary> /// Handles the specified request. /// </summary> /// <param name="request">The request.</param> /// <param name="response">The response.</param> protected override void Handle(UpdateTeamNameRequest request, DtoResponse <TeamSummaryDto> response) { var team = _teamRepository.GetByKey(request.Key); team.ReviseName(request.Name); response.DataTransferObject = Mapper.Map <Team, TeamSummaryDto> (team); }
/// <summary> /// Handles the specified request. /// </summary> /// <param name="request">The request.</param> /// <param name="response">The response.</param> protected override void Handle(UpdateOrganizationNameRequest request, DtoResponse <OrganizationDto> response) { var organization = _organizationRepository.GetByKey(request.Key); organization.ReviseName(request.Name); response.DataTransferObject = Mapper.Map <Organization, OrganizationDto> (organization); }
/// <summary> /// Handles the specified request. /// </summary> /// <param name="request">The request.</param> /// <param name="response">The response.</param> protected override void Handle(AddDtoRequest <TeamStaffDto> request, DtoResponse <TeamStaffDto> response) { var team = _teamRepository.GetByKey(request.AggregateKey); team.AddStaff(request.DataTransferObject.Key); response.DataTransferObject = request.DataTransferObject; }
/// <summary> /// Handles the specified request. /// </summary> /// <param name="request">The request.</param> /// <param name="response">The response.</param> protected override void Handle(RemoveOrganizationPhoneRequest request, DtoResponse <OrganizationPhoneDto> response) { var organization = _organizationRepository.GetByKey(request.OrganizationKey); var organizationPhone = organization.OrganizationPhones.FirstOrDefault(a => a.GetHashCode() == request.OriginalHash); organization.RemovePhone(organizationPhone); response.DataTransferObject = Mapper.Map <OrganizationPhone, OrganizationPhoneDto>(organizationPhone); }
/// <summary> /// Handles the specified request. /// </summary> /// <param name="request">The request.</param> /// <param name="response">The response.</param> protected override void Handle(CreateTeamRequest request, DtoResponse <TeamSummaryDto> response) { var team = _teamFactory.Create(request.OrganizationKey, request.Name); if (team != null) { response.DataTransferObject = Mapper.Map <Team, TeamSummaryDto> (team); } }
/// <summary> /// Handles the specified request. /// </summary> /// <param name="request">The request.</param> /// <param name="response">The response.</param> protected override void Handle(CreateTeamRequest request, DtoResponse <TeamSummaryDto> response) { var organization = _organizationRepository.GetByKey(UserContext.OrganizationKey); var team = _teamFactory.Create(organization, request.Name); if (team != null) { response.DataTransferObject = Mapper.Map <Team, TeamSummaryDto> (team); } }
protected override void Handle(CancelAssessmentReminderRequest request, DtoResponse <AssessmentReminderDto> response) { var assessmentReminder = _assessmentReminderRepository.GetByKey(request.AssessmentReminderKey); if (assessmentReminder != null) { assessmentReminder.Cancel(); var dto = Mapper.Map <AssessmentReminder, AssessmentReminderDto>(assessmentReminder); response.DataTransferObject = dto; } }
/// <summary> /// Handles the specified request. /// </summary> /// <param name="request">The request.</param> /// <param name="response">The response.</param> protected override void Handle(RemoveStaffFromTeamRequest request, DtoResponse <TeamSummaryDto> response) { var team = _teamRepository.GetByKey(request.TeamKey); var staff = team.Staff.FirstOrDefault(s => s.Key == request.StaffKey); if (staff != null) { team.RemoveStaff(staff); } response.DataTransferObject = Mapper.Map <Team, TeamSummaryDto> (team); }
protected override void Handle(SaveDtoRequest <StaffDto> request, DtoResponse <StaffDto> response) { var staff = _staffRepository.GetByKey(request.DataTransferObject.Key); staff.ReviseName(request.DataTransferObject.Name); staff.ReviseEmail(string.IsNullOrWhiteSpace(request.DataTransferObject.Email) ? null : new Email(request.DataTransferObject.Email)); staff.ReviseLocation(request.DataTransferObject.Location); staff.ReviseNpi(request.DataTransferObject.NPI); response.DataTransferObject = Mapper.Map <Staff, StaffDto>(staff); }
protected override void Handle(AcknowledgeAssessmentReminderRequest request, DtoResponse <AssessmentReminderDto> response) { var assessmentReminder = _assessmentReminderRepository.GetByKey(request.Key); if (assessmentReminder != null) { assessmentReminder.Acknowledge(); var dto2 = Mapper.Map <AssessmentReminder, AssessmentReminderDto>(assessmentReminder); response.DataTransferObject = dto2; } }
protected override void Handle(GetRoleDtoByKeyRequest request, DtoResponse <RoleDto> response) { var role = _roleRepository.GetByKey(request.Key); if (role != null) { var roleDto = Mapper.Map <Role, RoleDto>(role); roleDto.Permissions = roleDto.Permissions.OrderBy(p => p); response.DataTransferObject = roleDto; } }
/// <summary> /// Handles the specified request. /// </summary> /// <param name="request">The request.</param> /// <param name="response">The response.</param> protected override void Handle(RemovePatientFromTeamRequest request, DtoResponse <TeamSummaryDto> response) { var team = _teamRepository.GetByKey(request.TeamKey); var patient = team.Patients.FirstOrDefault(p => p.Key == request.PatientKey); if (patient != null) { team.RemovePatient(patient); } response.DataTransferObject = Mapper.Map <Team, TeamSummaryDto> (team); }
/// <summary> /// Handles the specified request. /// </summary> /// <param name="request">The request.</param> /// <param name="response">The response.</param> protected override void Handle(GetDtoByKeyRequest <OrganizationDto> request, DtoResponse <OrganizationDto> response) { var organizationKey = UserContext.OrganizationKey; if (UserContext.IsSystemAdmin) { organizationKey = request.Key; } var organization = _organizationRepository.GetByKey(organizationKey); response.DataTransferObject = Mapper.Map <Organization, OrganizationDto> (organization); }
protected override void Handle(UpdateRoleRequest request, DtoResponse <RoleDto> response) { var role = _roleRepository.GetByKey(request.Key); if (role != null) { role.ReviseName(request.Name); var roleDto = Mapper.Map <Role, RoleDto>(role); response.DataTransferObject = roleDto; } }
protected override void Handle(UpdateAssessmentReminderRequest request, DtoResponse <AssessmentReminderDto> response) { if (request.AssessmentReminderKey == Guid.Empty) { var dto = request.AssessmentReminderDto; var assessmentReminder = _assessmentReminderRepository.GetByKey(dto.Key); if (assessmentReminder != null) { if (dto.PatientKey.HasValue && assessmentReminder.PatientKey != dto.PatientKey.Value) { assessmentReminder.RevisePatientKey(dto.PatientKey.Value); } if (dto.CreatedByStaffKey.HasValue && assessmentReminder.CreatedByStaffKey != dto.CreatedByStaffKey.Value) { assessmentReminder.ReviseCreatedbyStaffKey(dto.CreatedByStaffKey.Value); } if (assessmentReminder.Title != dto.Title) { assessmentReminder.ReviseTitle(dto.Title); } if (assessmentReminder.Start.Date != dto.Start.Date) { assessmentReminder.ReviseStart(dto.Start); } if (dto.AssessmentDefinitionKey.HasValue && assessmentReminder.AssessmentDefinitionKey != dto.AssessmentDefinitionKey.Value) { assessmentReminder.ReviseAssessmentDefinitionKey(dto.AssessmentDefinitionKey.Value); } if (dto.ReminderTime > 0) { assessmentReminder.ReviseReminder(dto.ReminderTime, dto.ReminderUnit, string.IsNullOrWhiteSpace(dto.SendToEmail) ? null : new Email(dto.SendToEmail)); } if (dto.ForSelfAdministration) { assessmentReminder.AllowSelfAdministration(); } var dto2 = Mapper.Map <AssessmentReminder, AssessmentReminderDto>(assessmentReminder); response.DataTransferObject = dto2; } } else { var assessmentReminder = _assessmentReminderRepository.GetByKey(request.AssessmentReminderKey); if (assessmentReminder != null) { assessmentReminder.ReviseStart(assessmentReminder.Start.AddDays(request.DayDelta)); var dto2 = Mapper.Map <AssessmentReminder, AssessmentReminderDto>(assessmentReminder); response.DataTransferObject = dto2; } } }
/// <summary> /// Delete message of given id. /// </summary> /// <param name="id"> Message id. </param> /// <returns> Success/failure message. </returns> public async Task <DtoResponse> Delete(int id) { var entity = await _unitOfWork.GroupMessageRepository.FindAsync(g => g.Id == id); if (entity == null) { return(DtoResponse.Failed("Group Message not found - task failed successfully")); } _unitOfWork.GroupMessageRepository.Delete(entity); await _unitOfWork.SaveChangesAsync(); return(DtoResponse.Success()); }
/// <summary> /// Delete the poll of given Id. /// </summary> /// <param name="pollId">Id of a poll to be deleted.</param> /// <returns>Success/failure message.</returns> public async Task <DtoResponse> Delete(int pollId) { var entity = await _unitOfWork.PollRepository.FindAsync(p => p.Id == pollId); if (entity == null) { return(DtoResponse.Failed("Poll not found")); } _unitOfWork.PollRepository.Delete(entity); await _unitOfWork.SaveChangesAsync(); return(DtoResponse.Success()); }
protected override void Handle(GetAssessmentReminderByKeyRequest request, DtoResponse <AssessmentReminderDto> response) { var assessmentReminder = _assessmentReminderRepository.GetByKey(request.AssessmentReminderKey); if (assessmentReminder != null) { var patient = _patientRepository.GetByKey(assessmentReminder.PatientKey); var assessmentDefinition = _assessmentDefinitionRepository.GetByKey(assessmentReminder.AssessmentDefinitionKey); var assessmentReminderDto = Mapper.Map <AssessmentReminder, AssessmentReminderDto> (assessmentReminder); assessmentReminderDto.AssessmentName = _resourcesManager.GetResourceManagerByName(assessmentDefinition.CodedConcept.Name).GetString("_" + assessmentDefinition.CodedConcept.Code); assessmentReminderDto.PatientFirstName = patient.Name.FirstName; assessmentReminderDto.PatientLastName = patient.Name.LastName; response.DataTransferObject = assessmentReminderDto; } }
/// <summary> /// Handles the specified request. /// </summary> /// <param name="request">The request.</param> /// <param name="response">The response.</param> protected override void Handle(AddDtoRequest <TeamPatientDto> request, DtoResponse <TeamPatientDto> response) { var team = _teamRepository.GetByKey(request.AggregateKey); var patient = _patientRepository.GetByKey(request.DataTransferObject.Key); response.DataTransferObject = request.DataTransferObject; if (patient != null) { team.AddPatient(patient); } else { Logger.Error(string.Format("Tried adding invalid patient {0} to team {1}", request.DataTransferObject.Key, team.Key)); response.DataTransferObject.AddDataErrorInfo(new DataErrorInfo("Invalid patient key.", ErrorLevel.Error)); } }
/// <summary> /// Handles the specified request. /// </summary> /// <param name="request">The request.</param> /// <param name="response">The response.</param> protected override void Handle(AddDtoRequest <TeamStaffDto> request, DtoResponse <TeamStaffDto> response) { var team = _teamRepository.GetByKey(request.AggregateKey); var staff = _staffRepository.GetByKey(request.DataTransferObject.Key); if (staff != null) { team.AddStaff(staff); } else { Logger.Error(string.Format("Tried adding invalid staff {0} to team {1}", request.DataTransferObject.Key, team.Key)); response.DataTransferObject.AddDataErrorInfo(new DataErrorInfo("Invalid staff key.", ErrorLevel.Error)); } response.DataTransferObject = request.DataTransferObject; }
/// <summary> /// Handles the specified request. /// </summary> /// <param name="request">The request.</param> /// <param name="response">The response.</param> protected override void Handle(UpdateStaffRequest request, DtoResponse <StaffDto> response) { var staff = _staffRepository.GetByKey(request.StaffKey); DataErrorInfo dataErrorInfo = null; switch (request.UpdateType) { case UpdateStaffRequest.StaffUpdateType.Name: staff.ReviseName((PersonName)request.Value); break; case UpdateStaffRequest.StaffUpdateType.Email: Email newEmail = null; try { if (!string.IsNullOrWhiteSpace((string)request.Value)) { newEmail = new Email((string)request.Value); } } catch (ArgumentException ae) { if (!ae.Message.Contains("email address", StringComparison.OrdinalIgnoreCase)) { throw; } dataErrorInfo = new DataErrorInfo(ae.Message, ErrorLevel.Error, PropertyUtil.ExtractPropertyName <StaffDto, string> (s => s.Email)); } staff.ReviseEmail(string.IsNullOrWhiteSpace((string)request.Value) ? null : newEmail); break; case UpdateStaffRequest.StaffUpdateType.Location: staff.ReviseLocation((string)request.Value); break; case UpdateStaffRequest.StaffUpdateType.NPI: staff.ReviseNpi((string)request.Value); break; } response.DataTransferObject = Mapper.Map <Staff, StaffDto> (staff); if (dataErrorInfo != null) { response.DataTransferObject.AddDataErrorInfo(dataErrorInfo); } }
/// <summary> /// 触发异常时调用的方法 /// </summary> /// <param name="filterContext"></param> public override void OnException(ExceptionContext filterContext) { string message = string.Format("消息类型:{0}<br>消息内容:{1}<br>引发异常的方法:{2}<br>引发异常的对象:{3}<br>异常目录:{4}<br>异常文件:{5}<br>堆栈: {6}" , filterContext.Exception.GetType().Name , filterContext.Exception.Message , filterContext.Exception.TargetSite , filterContext.Exception.Source , filterContext.RouteData.GetRequiredString("controller") , filterContext.RouteData.GetRequiredString("action") , filterContext.Exception.StackTrace); //LogHelper.Error(message);//TODO:将 ex 错误对象记录到系统日志模块 DtoResponse<BaseEntity> response = new DtoResponse<BaseEntity>(); response.Code = Codes.Error; response.Message = filterContext.Exception.Message; JsonResult errorJson = new JsonResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet }; errorJson.Data = response; filterContext.Result = errorJson; base.OnException(filterContext); }
/// <summary> /// Delete the question of given Id. /// </summary> /// <param name="pollQuestionId">Id of question to be deleted.</param> /// <returns>Success/failure message.</returns> public async Task <DtoResponse> Delete(int pollQuestionId) { var entity = await _unitOfWork.PollQuestionRepository.FindAsync(p => p.Id == pollQuestionId); if (entity == null) { return(DtoResponse.Failed("Poll question not found")); } if (entity.Points != 0) { var poll = _unitOfWork.PollRepository.Get(entity.PollId); poll.Points -= entity.Points; _unitOfWork.PollRepository.Update(poll, entity.PollId); } _unitOfWork.PollQuestionRepository.Delete(entity); await _unitOfWork.SaveChangesAsync(); return(DtoResponse.Success()); }
public LojaModule() : base("Loja") { this.RequiresAuthentication(); // Obter dados da loja. Tem que passar o Id do nível (Mapa) e o Id da loja (Tópico Temático) Get["/{lojaId:int}"] = p => { var trilhaServices = new TrilhaServices(); // Objeto da loja obtido no método de dados da loja. É usado pra obter as mensagens da guia. PontoSebrae pontoSebrae; trilhaServices.VerificarConclusaoMissao(AcessoAtual); // Retornar os dados da loja. var response = new DtoResponse( trilhaServices.ObterDadosLoja(AcessoAtual, p.lojaId, out pontoSebrae), trilhaServices.ObterMensagensGuiaLoja(AcessoAtual.Matricula, pontoSebrae) ); return(response); }; Get["/cambio/mensagemguia"] = p => { return(new DtoResponse(new TrilhaServices().ObterMensagensGuiaCambio(AcessoAtual.Matricula))); }; Post["/Cambio"] = p => { VerificarBloqueio(); // Retornar a quantidade de moedas de ouro. return(new DtoResponse(new TrilhaServices().ConverterMoedasOuro(AcessoAtual))); }; }
protected override void Handle(UpdateStaffRequest request, DtoResponse <StaffDto> response) { var staff = _staffRepository.GetByKey(request.StaffKey); switch (request.UpdateType) { case UpdateStaffRequest.StaffUpdateType.Name: staff.ReviseName((PersonName)request.Value); break; case UpdateStaffRequest.StaffUpdateType.Email: staff.ReviseEmail(string.IsNullOrWhiteSpace((string)request.Value) ? null : new Email((string)request.Value)); break; case UpdateStaffRequest.StaffUpdateType.Location: staff.ReviseLocation((string)request.Value); break; case UpdateStaffRequest.StaffUpdateType.NPI: staff.ReviseNpi((string)request.Value); break; } response.DataTransferObject = Mapper.Map <Staff, StaffDto>(staff); }
/// <summary> /// Handles the specified request. /// </summary> /// <param name="request">The request.</param> /// <param name="response">The response.</param> protected override void Handle(CreateOrganizationRequest request, DtoResponse <OrganizationSummaryDto> response) { var organization = _organizationFactory.Create(request.Name); response.DataTransferObject = Mapper.Map <Organization, OrganizationSummaryDto>(organization); }
/// <summary> /// Handles the specified request. /// </summary> /// <param name="request">The request.</param> /// <param name="response">The response.</param> protected override void Handle(GetDtoByKeyRequest <OrganizationSummaryDto> request, DtoResponse <OrganizationSummaryDto> response) { var organization = _organizationRepository.GetByKey(request.Key); response.DataTransferObject = Mapper.Map <Organization, OrganizationSummaryDto>(organization); }