public IActionResult Get() { if (!_isEnabled) { return(NotFound()); } try { var groupedLoadOrder = GetGroupedLoadOrder(_resourceLoadGraphFactory.CreateResourceLoadGraph()).ToList(); ModifyLoadOrderForAuthorizationConcerns(groupedLoadOrder); return(Request.GetTypedHeaders().Accept != null && Request.GetTypedHeaders().Accept.Any(a => a.MediaType.Value.EqualsIgnoreCase(CustomMediaContentTypes.GraphML)) ? Ok(CreateGraphML(_resourceLoadGraphFactory.CreateResourceLoadGraph())) : Ok(groupedLoadOrder)); } catch (NonAcyclicGraphException e) { // return a bad request if a circular reference occurs, with the path information of the reference. string message = e.Message.Replace($"{Environment.NewLine} is used by ", " -> ") .Replace(Environment.NewLine, " "); return(BadRequest(ErrorTranslator.GetErrorMessage(message))); } }
public RequestResult <IEnumerable <AdminEmail> > GetEmails() { int pageIndex = 0; DBResult <List <Email> > dbEmail = this.emailDelegate.GetEmails(pageIndex, this.maxEmails); IEnumerable <MessagingVerification> emailInvites = this.emailInviteDelegate.GetAllEmail(); RequestResult <IEnumerable <AdminEmail> > result = new RequestResult <IEnumerable <AdminEmail> >() { ResourcePayload = dbEmail.Payload.Select(e => { MessagingVerification emailInvite = emailInvites.First(ei => e.To !.Equals(ei.Email?.To, System.StringComparison.CurrentCultureIgnoreCase)); string inviteStatus = GetEmailInviteStatus(emailInvite); return(AdminEmail.CreateFromDbModel(e, inviteStatus)); }), PageIndex = pageIndex, PageSize = this.maxEmails, TotalResultCount = dbEmail.Payload.Count, ResultStatus = dbEmail.Status == DBStatusCode.Read ? ResultType.Success : ResultType.Error, ResultError = dbEmail.Status == DBStatusCode.Read ? null : new RequestResultError() { ResultMessage = dbEmail.Message, ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationInternal, ServiceType.Database) }, }; return(result); }
/// <inheritdoc /> public RequestResult <Communication> GetActiveBanner() { RequestResult <Communication> cacheEntry; if (!this.memoryCache.TryGetValue(BannerCacheKey, out cacheEntry)) { this.logger.LogInformation("Active Banner not found in cache, getting from DB..."); DBResult <Communication> dbComm = this.communicationDelegate.GetActiveBanner(); cacheEntry = new RequestResult <Communication>() { ResourcePayload = dbComm.Payload, ResultStatus = dbComm.Status == DBStatusCode.Read ? Common.Constants.ResultType.Success : ResultType.Error, ResultError = dbComm.Status == DBStatusCode.Read ? null : new RequestResultError() { ResultMessage = dbComm.Message, ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationInternal, ServiceType.Database), }, }; this.SetActiveBannerCache(cacheEntry); } else { this.logger.LogDebug("Active Banner was found in cache, returning..."); } return(cacheEntry); }
/// <inheritdoc /> public RequestResult <Communication> Add(Communication communication) { this.logger.LogTrace($"Communication recieved: {JsonConvert.SerializeObject(communication)}"); if (communication.CommunicationTypeCode == "Email") { if (communication.Text.Length == 0 || communication.Subject.Length == 0) { throw new ArgumentException("One of: Email Subject, Email Content is invalid."); } communication.EffectiveDateTime = DateTime.Now; communication.ExpiryDateTime = DateTime.Now; } this.logger.LogTrace($"Adding communication... {JsonConvert.SerializeObject(communication)}"); DBResult <Communication> dbResult = this.communicationDelegate.Add(communication); RequestResult <Communication> requestResult = new RequestResult <Communication>() { ResourcePayload = dbResult.Payload, ResultStatus = dbResult.Status == DBStatusCode.Created ? ResultType.Success : ResultType.Error, ResultError = dbResult.Status == DBStatusCode.Created ? null : new RequestResultError() { ResultMessage = dbResult.Message, ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationInternal, ServiceType.Database) }, }; return(requestResult); }
public override Task <IActionResult> Get(Guid id) { return(Task.FromResult <IActionResult>( StatusCode(StatusCodes.Status405MethodNotAllowed, ErrorTranslator .GetErrorMessage("The allowed methods for this resource with the 'Test-Profile-Resource-WriteOnly' profile are PUT, POST, DELETE and OPTIONS.")))); }
/// <inheritdoc/> public RequestResult <string> GetPatientPHN(string hdid, string authorization) { RequestResult <string> retVal = new RequestResult <string>() { ResultError = new RequestResultError() { ResultMessage = "Error during PHN retrieval", ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationExternal, ServiceType.ClientRegistries) }, ResultStatus = Constants.ResultType.Error, }; string retrievedPhn = string.Empty; RequestResult <Patient> patientResult = this.GetPatient(hdid, authorization); if (patientResult != null) { retVal.ResultError = patientResult.ResultError; retVal.ResultStatus = patientResult.ResultStatus; if (patientResult.ResultStatus == Constants.ResultType.Success && patientResult.ResourcePayload != null) { retVal.ResourcePayload = patientResult.ResourcePayload.PersonalHealthNumber; } } return(retVal); }
public void ShouldUpdateUserPreferenceWithDBError() { RequestResult <UserPreferenceModel> actualResult = ExecuteUpdateUserPreference(Database.Constants.DBStatusCode.Error); Assert.Equal(Common.Constants.ResultType.Error, actualResult.ResultStatus); Assert.Equal(ErrorTranslator.ServiceError(ErrorType.CommunicationInternal, ServiceType.Database), actualResult.ResultError.ErrorCode); }
public void CanTranslateErrors() { ErrorTranslator errorTranslator = new ErrorTranslator(); var actual = new[] { "Passwords must have at least one digit ('0'-'9').", "Passwords must have at least one non letter or digit character.", "Invalid token.", "Passwords must have at least one uppercase ('A'-'Z').", "Name is already taken.", "E-mail is already taken.", "Pawl is taken?!", "Passwords must have at least one digit ('0'-'9'). Name is already taken." }; for (int i = 0; i < actual.Length; i++) { errorTranslator.TranslateText(ref actual[i]); } var expected = new[] { "Hasło musi zawierać co najmniej jedną cyfrę.", "Hasło musi zawierać co najmniej jeden znak specjalny.", "Niepoprawny token.", "Hasło musi zawierać co najmniej jedną wielką literę.", "E-mail jest już zajęty.", "E-mail jest już zajęty.", "Pawl jest zajęty?!", "Hasło musi zawierać co najmniej jedną cyfrę. E-mail jest już zajęty." }; Assert.IsTrue(expected.SequenceEqual(actual)); }
/// <inheritdoc /> public RequestResult <UserComment> Add(UserComment userComment) { UserProfile profile = this.profileDelegate.GetUserProfile(userComment.UserProfileId).Payload; string? key = profile.EncryptionKey; if (key == null) { this.logger.LogError($"User does not have a key: ${userComment.UserProfileId}"); return(new RequestResult <UserComment>() { ResultStatus = ResultType.Error, ResultError = new RequestResultError() { ResultMessage = "Profile Key not set", ErrorCode = ErrorTranslator.InternalError(ErrorType.InvalidState) }, }); } Comment comment = userComment.ToDbModel(this.cryptoDelegate, key); DBResult <Comment> dbComment = this.commentDelegate.Add(comment); RequestResult <UserComment> result = new RequestResult <UserComment>() { ResourcePayload = UserComment.CreateFromDbModel(dbComment.Payload, this.cryptoDelegate, key), ResultStatus = dbComment.Status == DBStatusCode.Created ? ResultType.Success : ResultType.Error, ResultError = new RequestResultError() { ResultMessage = dbComment.Message, ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationInternal, ServiceType.Database) }, }; return(result); }
/// <inheritdoc /> public RequestResult <IEnumerable <UserComment> > GetEntryComments(string hdId, string parentEntryId) { UserProfile profile = this.profileDelegate.GetUserProfile(hdId).Payload; string? key = profile.EncryptionKey; // Check that the key has been set if (key == null) { this.logger.LogError($"User does not have a key: ${hdId}"); return(new RequestResult <IEnumerable <UserComment> >() { ResultStatus = ResultType.Error, ResultError = new RequestResultError() { ResultMessage = "Profile Key not set", ErrorCode = ErrorTranslator.InternalError(ErrorType.InvalidState) }, }); } DBResult <IEnumerable <Comment> > dbComments = this.commentDelegate.GetByParentEntry(hdId, parentEntryId); RequestResult <IEnumerable <UserComment> > result = new RequestResult <IEnumerable <UserComment> >() { ResourcePayload = UserComment.CreateListFromDbModel(dbComments.Payload, this.cryptoDelegate, key), TotalResultCount = dbComments.Payload.Count(), PageIndex = 0, PageSize = dbComments.Payload.Count(), ResultStatus = dbComments.Status == DBStatusCode.Read ? ResultType.Success : ResultType.Error, ResultError = dbComments.Status != DBStatusCode.Read ? new RequestResultError() { ResultMessage = dbComments.Message, ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationInternal, ServiceType.Database) } : null, }; return(result); }
/// <inheritdoc /> public RequestResult <Communication> Update(Communication communication) { if (communication.EffectiveDateTime < communication.ExpiryDateTime) { this.logger.LogTrace($"Updating communication... {JsonSerializer.Serialize(communication)}"); DBResult <HealthGateway.Database.Models.Communication> dbResult = this.communicationDelegate.Update(communication.ToDbModel()); return(new RequestResult <Communication>() { ResourcePayload = new Communication(dbResult.Payload), ResultStatus = dbResult.Status == DBStatusCode.Updated ? ResultType.Success : ResultType.Error, ResultError = dbResult.Status == DBStatusCode.Updated ? null : new RequestResultError() { ResultMessage = dbResult.Message, ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationInternal, ServiceType.Database) }, }); } else { return(new RequestResult <Communication>() { ResourcePayload = null, ResultStatus = ResultType.Error, ResultError = new RequestResultError() { ResultMessage = "Effective Date should be before Expiry Date.", ErrorCode = ErrorTranslator.InternalError(ErrorType.InvalidState) }, }); } }
public override Task <IActionResult> Put(SchoolsNullWriteRequest request, Guid id) { return(Task.FromResult <IActionResult>( StatusCode(StatusCodes.Status405MethodNotAllowed, ErrorTranslator .GetErrorMessage("The allowed methods for this resource with the 'Test-Profile-Resource-ReadOnly' profile are GET, DELETE and OPTIONS.")))); }
/// <inheritdoc /> public RequestResult <Communication> Delete(Communication communication) { if (communication.CommunicationStatusCode == CommunicationStatus.Processed) { this.logger.LogError($"Processed communication can't be deleted."); return(new RequestResult <Communication>() { ResultStatus = ResultType.Error, ResultError = new RequestResultError() { ResultMessage = "Processed communication can't be deleted.", ErrorCode = ErrorTranslator.InternalError(ErrorType.InvalidState) }, }); } DBResult <HealthGateway.Database.Models.Communication> dbResult = this.communicationDelegate.Delete(communication.ToDbModel()); RequestResult <Communication> result = new RequestResult <Communication>() { ResourcePayload = new Communication(dbResult.Payload), ResultStatus = dbResult.Status == DBStatusCode.Deleted ? ResultType.Success : ResultType.Error, ResultError = dbResult.Status == DBStatusCode.Deleted ? null : new RequestResultError() { ResultMessage = dbResult.Message, ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationInternal, ServiceType.Database) }, }; return(result); }
public virtual async Task <IActionResult> Post([FromBody] TPostRequest request) { var validationState = new ValidationState(); PutResult result; // Make sure Id is not already set (no client-assigned Ids) if (request.Id != default(Guid)) { return(BadRequest(ErrorTranslator.GetErrorMessage("Resource identifiers cannot be assigned by the client."))); } else { result = await PutPipeline.Value.ProcessAsync( new PutContext <TResourceWriteModel, TAggregateRoot>(request, validationState), CancellationToken.None); } // Throw an exceptions that occurred for global exception handling if (result.Exception != null) { Logger.Error("Post", result.Exception); return(CreateActionResultFromException(result.Exception)); } Response.GetTypedHeaders().ETag = GetEtag(result.ETag); Response.GetTypedHeaders().Location = new Uri(GetResourceUrl(result.ResourceId.GetValueOrDefault())); return(result.ResourceWasCreated ? (IActionResult)Created(new Uri(GetResourceUrl(result.ResourceId.GetValueOrDefault())), null) : Ok()); }
public override Task <IActionResult> GetAll(UrlQueryParametersRequest urlQueryParametersRequest, SchoolsNullReadRequest specification = null) { return(Task.FromResult <IActionResult>( StatusCode(StatusCodes.Status405MethodNotAllowed, ErrorTranslator .GetErrorMessage("The allowed methods for this resource with the 'Test-Profile-Resource-WriteOnly' profile are PUT, POST, DELETE and OPTIONS.")))); }
/// <inheritdoc/> public async System.Threading.Tasks.Task <RequestResult <string> > GetPatientPHN(string hdid) { using Activity? activity = Source.StartActivity("GetPatientPHN"); RequestResult <string> retVal = new RequestResult <string>() { ResultError = new RequestResultError() { ResultMessage = "Error during PHN retrieval", ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationExternal, ServiceType.ClientRegistries) }, ResultStatus = Constants.ResultType.Error, }; string retrievedPhn = string.Empty; RequestResult <PatientModel> patientResult = await this.GetPatient(hdid).ConfigureAwait(true); if (patientResult != null) { retVal.ResultError = patientResult.ResultError; retVal.ResultStatus = patientResult.ResultStatus; if (patientResult.ResultStatus == Constants.ResultType.Success && patientResult.ResourcePayload != null) { retVal.ResourcePayload = patientResult.ResourcePayload.PersonalHealthNumber; } } activity?.Stop(); return(retVal); }
public void ShouldGetUserPreferenceWithDBError() { Tuple <RequestResult <Dictionary <string, UserPreferenceModel> >, List <UserPreferenceModel> > result = ExecuteGetUserPreference(Database.Constants.DBStatusCode.Error); var actualResult = result.Item1; Assert.Equal(Common.Constants.ResultType.Error, actualResult.ResultStatus); Assert.Equal(ErrorTranslator.ServiceError(ErrorType.CommunicationInternal, ServiceType.Database), actualResult.ResultError.ErrorCode); }
public void ShouldUpdateNoteWithDBError() { Tuple <RequestResult <UserNote>, UserNote> getNotesResult = ExecuteUpdateNote(Database.Constants.DBStatusCode.Error); var actualResult = getNotesResult.Item1; Assert.Equal(Common.Constants.ResultType.Error, actualResult.ResultStatus); Assert.Equal(ErrorTranslator.ServiceError(ErrorType.CommunicationInternal, ServiceType.Database), actualResult.ResultError.ErrorCode); }
public RequestResult <BetaRequest> PutBetaRequest(BetaRequest betaRequest, string hostUrl) { this.logger.LogTrace($"Creating a beta request... {JsonConvert.SerializeObject(betaRequest)}"); // If there is a previous request, update it isntead of creating a new one BetaRequest previousRequest = this.betaRequestDelegate.GetBetaRequest(betaRequest.HdId).Payload; if (previousRequest != null) { RequestResult <BetaRequest> requestResult = new RequestResult <BetaRequest>(); DBResult <BetaRequest> insertResult = this.betaRequestDelegate.UpdateBetaRequest(betaRequest); if (insertResult.Status == DBStatusCode.Updated) { Dictionary <string, string> keyValues = new Dictionary <string, string>(); keyValues.Add(HostTemplateVariable, hostUrl); this.emailQueueService.QueueNewEmail(betaRequest.EmailAddress, EmailTemplateName.BetaConfirmationTemplate, keyValues); requestResult.ResourcePayload = insertResult.Payload; requestResult.ResultStatus = ResultType.Success; this.logger.LogDebug($"Finished updating beta request. {JsonConvert.SerializeObject(insertResult)}"); } else { requestResult.ResultError = new RequestResultError() { ResultMessage = insertResult.Message, ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationInternal, ServiceType.Database) }; requestResult.ResultStatus = ResultType.Error; } return(requestResult); } else { betaRequest.CreatedBy = betaRequest.HdId; betaRequest.UpdatedBy = betaRequest.HdId; DBResult <BetaRequest> insertResult = this.betaRequestDelegate.InsertBetaRequest(betaRequest); RequestResult <BetaRequest> requestResult = new RequestResult <BetaRequest>(); if (insertResult.Status == DBStatusCode.Created) { Dictionary <string, string> keyValues = new Dictionary <string, string>(); keyValues.Add(HostTemplateVariable, hostUrl); this.emailQueueService.QueueNewEmail(betaRequest.EmailAddress, EmailTemplateName.BetaConfirmationTemplate, keyValues); requestResult.ResourcePayload = insertResult.Payload; requestResult.ResultStatus = ResultType.Success; this.logger.LogDebug($"Finished creating beta request. {JsonConvert.SerializeObject(insertResult)}"); } else { requestResult.ResultError = new RequestResultError() { ResultMessage = insertResult.Message, ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationInternal, ServiceType.Database) }; requestResult.ResultStatus = ResultType.Error; } return(requestResult); } }
/// <inheritdoc /> public RequestResult <UserProfileModel> GetUserProfile(string hdid, DateTime jwtAuthTime) { this.logger.LogTrace($"Getting user profile... {hdid}"); DBResult <UserProfile> retVal = this.userProfileDelegate.GetUserProfile(hdid); this.logger.LogDebug($"Finished getting user profile. {JsonSerializer.Serialize(retVal)}"); if (retVal.Status == DBStatusCode.NotFound) { return(new RequestResult <UserProfileModel>() { ResultStatus = ResultType.Success, ResourcePayload = new UserProfileModel(), }); } DateTime previousLastLogin = retVal.Payload.LastLoginDateTime; if (DateTime.Compare(previousLastLogin, jwtAuthTime) != 0) { this.logger.LogTrace($"Updating user last login... {hdid}"); retVal.Payload.LastLoginDateTime = jwtAuthTime; DBResult <UserProfile> updateResult = this.userProfileDelegate.Update(retVal.Payload); this.logger.LogDebug($"Finished updating user last login. {JsonSerializer.Serialize(updateResult)}"); } RequestResult <TermsOfServiceModel> termsOfServiceResult = this.GetActiveTermsOfService(); UserProfileModel userProfile = UserProfileModel.CreateFromDbModel(retVal.Payload); userProfile.HasTermsOfServiceUpdated = termsOfServiceResult.ResourcePayload?.EffectiveDate > previousLastLogin; if (!userProfile.IsEmailVerified) { this.logger.LogTrace($"Retrieving last email invite... {hdid}"); MessagingVerification?emailInvite = this.messageVerificationDelegate.GetLastForUser(hdid, MessagingVerificationType.Email); this.logger.LogDebug($"Finished retrieving email: {JsonSerializer.Serialize(emailInvite)}"); userProfile.Email = emailInvite?.Email?.To; } if (!userProfile.IsSMSNumberVerified) { this.logger.LogTrace($"Retrieving last email invite... {hdid}"); MessagingVerification?smsInvite = this.messageVerificationDelegate.GetLastForUser(hdid, MessagingVerificationType.SMS); this.logger.LogDebug($"Finished retrieving email: {JsonSerializer.Serialize(smsInvite)}"); userProfile.SMSNumber = smsInvite?.SMSNumber; } return(new RequestResult <UserProfileModel>() { ResultStatus = retVal.Status != DBStatusCode.Error ? ResultType.Success : ResultType.Error, ResultError = retVal.Status != DBStatusCode.Error ? null : new RequestResultError() { ResultMessage = retVal.Message, ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationInternal, ServiceType.Database) }, ResourcePayload = userProfile, }); }
/// <summary> /// Formats the error from the given error type. /// </summary> /// <param name="message">The user friendly message.</param> /// <param name="actionType">Action type that caused the issue.</param> /// <returns>A RequestResultError encapsulating the action required.</returns> public static HealthGateway.Common.Models.RequestResultError ActionRequired(string message, ActionType actionType) { return(new Models.RequestResultError() { ResultMessage = message, ErrorCode = ErrorTranslator.InternalError(ErrorType.InvalidState), ActionCode = actionType, }); }
static ErrorMarshal() { try { Translate = new ErrorTranslator(strerror_r); Translate(Native.Errno.ERANGE); } catch (EntryPointNotFoundException) { Translate = new ErrorTranslator(strerror); } }
static ErrorMarshal () { try { Translate = new ErrorTranslator (strerror_r); Translate (Native.Errno.ERANGE); } catch (EntryPointNotFoundException) { Translate = new ErrorTranslator (strerror); } }
public async void ShouldInsertUserProfileWithClosedRegistration() { Tuple <RequestResult <UserProfileModel>, UserProfileModel> result = await ExecuteInsertUserProfile(DBStatusCode.Error, RegistrationStatus.Closed, null); var actualResult = result.Item1; Assert.Equal(ResultType.Error, actualResult.ResultStatus); Assert.Equal(ErrorTranslator.InternalError(ErrorType.InvalidState), actualResult.ResultError.ErrorCode); Assert.Equal("Registration is closed", actualResult.ResultError.ResultMessage); }
/// <inheritdoc /> public PrimitiveRequestResult <bool> ValidateEmail(string hdid, Guid inviteKey) { this.logger.LogTrace($"Validating email... {inviteKey}"); PrimitiveRequestResult <bool> retVal = new (); MessagingVerification?emailVerification = this.messageVerificationDelegate.GetLastByInviteKey(inviteKey); if (emailVerification == null || emailVerification.HdId != hdid || emailVerification.Validated == true || emailVerification.Deleted == true) { // Invalid Verification Attempt emailVerification = this.messageVerificationDelegate.GetLastForUser(hdid, MessagingVerificationType.Email); if (emailVerification != null && !emailVerification.Validated) { emailVerification.VerificationAttempts++; this.messageVerificationDelegate.Update(emailVerification); } return(new PrimitiveRequestResult <bool>() { ResultStatus = ResultType.Error, ResultError = new RequestResultError() { ResultMessage = "Invalid Email Verification", ErrorCode = ErrorTranslator.InternalError(ErrorType.InvalidState), }, }); } else if (emailVerification.VerificationAttempts >= this.maxVerificationAttempts || emailVerification.ExpireDate < DateTime.UtcNow) { // Verification Expired retVal.ResultStatus = ResultType.ActionRequired; retVal.ResultError = ErrorTranslator.ActionRequired("Email Verification Expired", ActionType.Expired); } else { emailVerification.Validated = true; this.messageVerificationDelegate.Update(emailVerification); UserProfile userProfile = this.profileDelegate.GetUserProfile(hdid).Payload; userProfile.Email = emailVerification.Email !.To; // Gets the user email from the email sent. this.profileDelegate.Update(userProfile); // Update the notification settings this.notificationSettingsService.QueueNotificationSettings(new NotificationSettingsRequest(userProfile, userProfile.Email, userProfile.SMSNumber)); retVal.ResultStatus = ResultType.Success; } this.logger.LogDebug($"Finished validating email: {JsonConvert.SerializeObject(retVal)}"); return(retVal); }
private void CheckPreviousError(bool safemode) { if (safemode) { Document err = this.Db.GetPreviousError(); if (ErrorTranslator.IsError(err)) { throw ErrorTranslator.Translate(err); } } }
/// <inheritdoc /> public RequestResult <IEnumerable <DependentModel> > GetDependents(string hdId, int page, int pageSize) { // Get Dependents from database int offset = page * pageSize; DBResult <IEnumerable <ResourceDelegate> > dbResourceDelegates = this.resourceDelegateDelegate.Get(hdId, offset, pageSize); // Get Dependents Details from Patient service List <DependentModel> dependentModels = new List <DependentModel>(); RequestResult <IEnumerable <DependentModel> > result = new RequestResult <IEnumerable <DependentModel> >() { ResultStatus = ResultType.Success, }; StringBuilder resultErrorMessage = new StringBuilder(); foreach (ResourceDelegate resourceDelegate in dbResourceDelegates.Payload) { this.logger.LogDebug($"Getting dependent details for Dependent hdid: {resourceDelegate.ResourceOwnerHdid} ..."); RequestResult <PatientModel> patientResult = Task.Run(async() => await this.patientService.GetPatient(resourceDelegate.ResourceOwnerHdid, PatientIdentifierType.HDID).ConfigureAwait(true)).Result; if (patientResult.ResourcePayload != null) { dependentModels.Add(DependentModel.CreateFromModels(resourceDelegate, patientResult.ResourcePayload)); } else { if (result.ResultStatus != ResultType.Error) { result.ResultStatus = ResultType.Error; resultErrorMessage.Append($"Communication Exception when trying to retrieve Dependent(s) - HdId: {resourceDelegate.ResourceOwnerHdid};"); } else { resultErrorMessage.Append($" HdId: {resourceDelegate.ResourceOwnerHdid};"); } } } result.ResourcePayload = dependentModels; if (result.ResultStatus != ResultType.Error) { result.ResultStatus = ResultType.Success; result.ResultError = null; result.TotalResultCount = dependentModels.Count; } else { result.ResultError = new RequestResultError() { ResultMessage = resultErrorMessage.ToString(), ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationExternal, ServiceType.Patient) }; } return(result); }
public void ValidateDependentWithWrongDateOfBirth() { AddDependentRequest addDependentRequest = SetupMockInput(); addDependentRequest.DateOfBirth = DateTime.Now; IDependentService service = SetupMockDependentService(addDependentRequest); RequestResult <DependentModel> actualResult = service.AddDependent(mockParentHdId, addDependentRequest); var userError = ErrorTranslator.ActionRequired(ErrorMessages.DataMismatch, ActionType.DataMismatch); Assert.Equal(Common.Constants.ResultType.ActionRequired, actualResult.ResultStatus); Assert.Equal(userError.ErrorCode, actualResult.ResultError.ErrorCode); Assert.Equal(mismatchedError, actualResult.ResultError.ResultMessage); }
/// <summary> /// Checks the error. /// </summary> /// <param name="safemode">if set to <c>true</c> [safemode].</param> private void CheckError(bool safemode) { if (!safemode) { return; } var lastError = Database.GetLastError(); if (ErrorTranslator.IsError(lastError)) { throw ErrorTranslator.Translate(lastError); } }
public virtual async Task <IActionResult> GetAll( [FromQuery] UrlQueryParametersRequest urlQueryParametersRequest, [FromQuery] TGetByExampleRequest request = default(TGetByExampleRequest)) { //respond quickly to DOS style requests (should we catch these earlier? e.g. attribute filter?) if (urlQueryParametersRequest.Limit != null && (urlQueryParametersRequest.Limit < 0 || urlQueryParametersRequest.Limit > _defaultPageLimitSize)) { return(BadRequest( ErrorTranslator.GetErrorMessage( "Limit must be omitted or set to a value between 1 and max value defined in configuration file (defaultPageSizeLimit)."))); } var internalRequestAsResource = new TResourceReadModel(); var internalRequest = internalRequestAsResource as TEntityInterface; if (request != null) { MapAll(request, internalRequest); } //TODO: Add support for If-None-Match; current implementation cannot verify value without going to the db // Read the incoming ETag header, if present Request.TryGetRequestHeader(HeaderConstants.IfNoneMatch, out string etagValue); var queryParameters = new QueryParameters(urlQueryParametersRequest); // Execute the pipeline (synchronously) var result = await GetManyPipeline.Value .ProcessAsync( new GetManyContext <TResourceReadModel, TAggregateRoot>(internalRequestAsResource, queryParameters), new CancellationToken()); // Handle exception result if (result.Exception != null) { Logger.Error(GetAllRequest, result.Exception); return(CreateActionResultFromException(result.Exception)); } // Return multiple results if (queryParameters.TotalCount) { Response.Headers.Add(HeaderConstants.TotalCount, result.ResultMetadata.TotalCount.ToString()); } Response.GetTypedHeaders().ContentType = new MediaTypeHeaderValue(GetReadContentType()); return(Ok(result.Resources)); }
/// <summary> /// Checks the previous error. /// </summary> /// <param name="safemode">if set to <c>true</c> [safemode].</param> private void CheckPreviousError(bool safemode) { if (!safemode) { return; } var previousError = Database.GetPreviousError(); if (ErrorTranslator.IsError(previousError)) { throw ErrorTranslator.Translate(previousError); } }