示例#1
0
        public static ValidationError NewConsolidatedError(ValidationErrorCode code, IssueLogger issues, string message, params object[] parameters)
        {
            var error = issues.Issues.All(err => err.IsWarning) ? new ValidationWarning(code, null, message, parameters) : new ValidationError(code, null, message, parameters);

            error.InnerErrors = issues.Issues.ToArray();
            return(error);
        }
        public async Task GivenTags_WhenDeleteTag_ThenAssociatedErrorsShouldBeRemoved()
        {
            string studyUid    = TestUidGenerator.Generate();
            string seriesUid   = TestUidGenerator.Generate();
            string instanceUid = TestUidGenerator.Generate();

            // add instances
            long watermark = await AddInstanceAsync(studyUid, seriesUid, instanceUid);

            // add tag
            DicomTag tag1    = DicomTag.DeviceSerialNumber;
            int      tagKey1 = await AddTagAsync(tag1);

            DicomTag tag2    = DicomTag.DeviceID;
            int      tagKey2 = await AddTagAsync(tag2);

            // add errors
            ValidationErrorCode errorCode = ValidationErrorCode.DateIsInvalid;
            // add error on instance for both tag
            await _extendedQueryTagErrorStore.AddExtendedQueryTagErrorAsync(tagKey1, errorCode, watermark);

            await _extendedQueryTagErrorStore.AddExtendedQueryTagErrorAsync(tagKey2, errorCode, watermark);

            // delete tag
            await _extendedQueryTagStore.DeleteExtendedQueryTagAsync(tag1.GetPath(), tag1.GetDefaultVR().Code);

            // check errors
            Assert.False(await _errorStoreTestHelper.DoesExtendedQueryTagErrorExistAsync(tagKey1));
            Assert.True(await _errorStoreTestHelper.DoesExtendedQueryTagErrorExistAsync(tagKey2));
        }
示例#3
0
        public static ValidationError NewConsolidatedError(ValidationErrorCode code, ValidationError[] errors, string message, params object[] parameters)
        {
            var error = errors.All(err => err.IsWarning) ? new ValidationWarning(code, null, message, parameters) : new ValidationError(code, null, message, parameters);

            error.InnerErrors = errors;
            return(error);
        }
        public async Task GivenExistingExtendedQueryTagandTagError_WhenDeleteExtendedQueryTag_ThenTagErrorShouldAlsoBeRemoved()
        {
            string studyInstanceUid  = TestUidGenerator.Generate();
            string seriesInstanceUid = TestUidGenerator.Generate();
            string sopInstanceUid    = TestUidGenerator.Generate();

            DicomTag tag       = DicomTag.DeviceSerialNumber;
            long     watermark = await AddInstanceAsync(studyInstanceUid, seriesInstanceUid, sopInstanceUid);

            int tagKey = await AddTagAsync(tag);

            ValidationErrorCode errorCode = ValidationErrorCode.InvalidCharacters;
            await _extendedQueryTagErrorStore.AddExtendedQueryTagErrorAsync(tagKey, errorCode, watermark);

            var extendedQueryTagErrorBeforeTagDeletion = await _extendedQueryTagErrorStore.GetExtendedQueryTagErrorsAsync(tag.GetPath(), int.MaxValue, 0);

            Assert.Equal(1, extendedQueryTagErrorBeforeTagDeletion.Count);

            var extendedQueryTagBeforeTagDeletion = await _extendedQueryTagStore.GetExtendedQueryTagAsync(tag.GetPath());

            await _extendedQueryTagStore.DeleteExtendedQueryTagAsync(tag.GetPath(), tag.GetDefaultVR().Code);

            await Assert.ThrowsAsync <ExtendedQueryTagNotFoundException>(
                () => _extendedQueryTagStore.GetExtendedQueryTagAsync(tag.GetPath()));

            await Assert.ThrowsAsync <ExtendedQueryTagNotFoundException>(
                () => _extendedQueryTagErrorStore.GetExtendedQueryTagErrorsAsync(tag.GetPath(), 1, 0));

            Assert.False(await _errorStoreTestHelper.DoesExtendedQueryTagErrorExistAsync(tagKey));
        }
        public async Task GivenExistingInstanceandExtendedQueryTagandTagError_WhenDeleteInstance_ThenTagErrorShouldAlsoBeRemoved()
        {
            string studyInstanceUid  = TestUidGenerator.Generate();
            string seriesInstanceUid = TestUidGenerator.Generate();
            string sopInstanceUid    = TestUidGenerator.Generate();

            DicomTag tag       = DicomTag.DeviceSerialNumber;
            long     watermark = await AddInstanceAsync(studyInstanceUid, seriesInstanceUid, sopInstanceUid);

            int tagKey = await AddTagAsync(tag);

            ValidationErrorCode errorCode = ValidationErrorCode.MultiValues;
            await _extendedQueryTagErrorStore.AddExtendedQueryTagErrorAsync(tagKey, errorCode, watermark);

            var extendedQueryTagErrorBeforeTagDeletion = await _extendedQueryTagErrorStore.GetExtendedQueryTagErrorsAsync(tag.GetPath(), int.MaxValue, 0);

            Assert.Equal(1, extendedQueryTagErrorBeforeTagDeletion.Count);

            IReadOnlyList <Instance> instanceBeforeDeletion = await _indexDataStoreTestHelper.GetInstancesAsync(studyInstanceUid, seriesInstanceUid, sopInstanceUid);

            Assert.Equal(1, instanceBeforeDeletion.Count);

            await _indexDataStore.DeleteInstanceIndexAsync(DefaultPartition.Key, studyInstanceUid, seriesInstanceUid, sopInstanceUid, Clock.UtcNow);

            Assert.Empty(await _extendedQueryTagErrorStore.GetExtendedQueryTagErrorsAsync(tag.GetPath(), 1, 0));
            Assert.False(await _errorStoreTestHelper.DoesExtendedQueryTagErrorExistAsync(tagKey));

            IReadOnlyList <Instance> instanceAfterDeletion = await _indexDataStoreTestHelper.GetInstancesAsync(studyInstanceUid, seriesInstanceUid, sopInstanceUid);

            Assert.Equal(0, instanceAfterDeletion.Count);
        }
        public async Task GivenValidExtendedQueryTagError_WhenAddExtendedQueryTagError_ThenTagErrorShouldBeAdded()
        {
            string studyInstanceUid  = TestUidGenerator.Generate();
            string seriesInstanceUid = TestUidGenerator.Generate();
            string sopInstanceUid    = TestUidGenerator.Generate();

            DicomTag tag       = DicomTag.DeviceSerialNumber;
            long     watermark = await AddInstanceAsync(studyInstanceUid, seriesInstanceUid, sopInstanceUid);

            int tagKey = await AddTagAsync(tag);

            ValidationErrorCode errorCode = ValidationErrorCode.ExceedMaxLength;

            await _extendedQueryTagErrorStore.AddExtendedQueryTagErrorAsync(
                tagKey,
                errorCode,
                watermark);

            var errors = await _extendedQueryTagErrorStore.GetExtendedQueryTagErrorsAsync(tag.GetPath(), 1, 0);

            Assert.Equal(errors[0].StudyInstanceUid, studyInstanceUid);
            Assert.Equal(errors[0].SeriesInstanceUid, seriesInstanceUid);
            Assert.Equal(errors[0].SopInstanceUid, sopInstanceUid);
            Assert.Equal(errors[0].ErrorMessage, errorCode.GetMessage());
        }
 public virtual Task AddExtendedQueryTagErrorAsync(
     int tagKey,
     ValidationErrorCode errorCode,
     long watermark,
     CancellationToken cancellationToken = default)
 {
     throw new BadRequestException(DicomSqlServerResource.SchemaVersionNeedsToBeUpgraded);
 }
示例#8
0
        /// <summary>
        /// Updates a dashboard option using a <see cref="Delta"/> object.
        /// </summary>
        /// <param name="id">ID of the entity to be updated.</param>
        /// <param name="delta">
        /// Delta containing a list of entity properties.  Web Api does the magic of converting the JSON to
        /// a delta.
        /// </param>
        /// <returns>
        /// An asynchronous task result containing information needed to create an API response message.
        /// </returns>
        public override async Task <CommandResult <DashboardOptionBaseDto, Guid> > Update(Guid id, Delta <DashboardOptionBaseDto> delta)
        {
            var userId = Thread.CurrentPrincipal == null ? null : Thread.CurrentPrincipal.GetUserIdFromPrincipal();

            if (userId == null)
            {
                return(Command.Error <DashboardOptionBaseDto>(GeneralErrorCodes.TokenInvalid("UserId")));
            }

            if (delta == null)
            {
                return(Command.Error <DashboardOptionBaseDto>(EntityErrorCode.EntityFormatIsInvalid));
            }

            var userDashboardOptions = _context.GetDashboardOptionsForUser(Guid.Parse(userId));
            var entity = userDashboardOptions.SingleOrDefault(x => x.Id == id);

            if (entity == null)
            {
                return(Command.Error <DashboardOptionBaseDto>(EntityErrorCode.EntityNotFound));
            }

            var dto = _mapper.Map(entity, new DashboardOptionBaseDto());

            delta.Patch(dto);

            var validationResponse = ValidatorUpdate.Validate(dto);

            var userTenants = _context.GetTenantsForUser(Guid.Parse(userId));

            if (dto.TenantId != Guid.Empty && !userTenants.Any(x => x.Id == dto.TenantId))
            {
                validationResponse.FFErrors.Add(ValidationErrorCode.ForeignKeyValueDoesNotExist("TenantId"));
            }
            else if (_context.DashboardOptions.Any(x => x.Id != id && x.TenantId == dto.TenantId))
            {
                validationResponse.FFErrors.Add(EntityErrorCode.EntityAlreadyExists);
            }

            // Including the original Id in the Patch request will not return an error but attempting to change the Id is not allowed.
            if (dto.Id != id)
            {
                validationResponse.FFErrors.Add(ValidationErrorCode.EntityIDUpdateNotAllowed("Id"));
            }

            if (validationResponse.IsInvalid)
            {
                return(Command.Error <DashboardOptionBaseDto>(validationResponse));
            }

            _context.DashboardOptions.Attach(entity);
            _mapper.Map(dto, entity);
            entity.SetAuditFieldsOnUpdate(userId);

            await _context.SaveChangesAsync().ConfigureAwait(false);

            return(Command.NoContent <DashboardOptionBaseDto>());
        }
示例#9
0
        /// <summary>
        /// Updates a Location Log Entry using a <see cref="Delta"/> object.
        /// </summary>
        /// <param name="id">ID of the Location Log Entry to be updated.</param>
        /// <param name="delta">
        /// Delta containing a list of Location Log Entry properties.  Web Api does the magic of converting the JSON to
        /// a delta.
        /// </param>
        /// <returns>
        /// An asynchronous task result containing information needed to create an API response message.
        /// </returns>
        public override async Task <CommandResult <LocationLogEntryBaseDto, Guid> > Update(Guid id, Delta <LocationLogEntryBaseDto> delta)
        {
            // User ID should always be available, but if not ...
            var userId = GetCurrentUser();

            if (!userId.HasValue)
            {
                return(Command.Error <LocationLogEntryBaseDto>(GeneralErrorCodes.TokenInvalid("UserId")));
            }

            if (delta == null)
            {
                return(Command.Error <LocationLogEntryBaseDto>(EntityErrorCode.EntityFormatIsInvalid));
            }

            var locationLogEntry = await _context.GetLocationLogEntriesForUser(userId.Value)
                                   .SingleOrDefaultAsync(l => l.Id == id)
                                   .ConfigureAwait(false);

            if (locationLogEntry == null)
            {
                return(Command.Error <LocationLogEntryBaseDto>(EntityErrorCode.EntityNotFound));
            }

            var dto = _mapper.Map(locationLogEntry, new LocationLogEntryQueryDto());

            delta.Patch(dto);

            var validationResponse = ValidatorUpdate.Validate(dto);

            // Including the original ID in the Patch request will not return an error but attempting to change the Id is not allowed.
            if (dto.Id != id)
            {
                validationResponse.FFErrors.Add(ValidationErrorCode.EntityIDUpdateNotAllowed("Id"));
            }

            var locationExists = await DoesLocationExist(dto.LocationId);

            if (!locationExists)
            {
                validationResponse.FFErrors.Add(ValidationErrorCode.ForeignKeyValueDoesNotExist(nameof(LocationLogEntry.LocationId)));
            }

            if (validationResponse.IsInvalid)
            {
                return(Command.Error <LocationLogEntryBaseDto>(validationResponse));
            }

            _context.LocationLogEntries.Attach(locationLogEntry);
            _mapper.Map(dto, locationLogEntry);

            locationLogEntry.SetAuditFieldsOnUpdate(userId.Value);

            await _context.SaveChangesAsync().ConfigureAwait(false);

            return(Command.NoContent <LocationLogEntryBaseDto>());
        }
 public Task AddExtendedQueryTagErrorAsync(int tagKey, ValidationErrorCode errorCode, long watermark, CancellationToken cancellationToken)
 {
     EnsureArg.EnumIsDefined(errorCode, nameof(errorCode));
     return(_extendedQueryTagErrorStore.AddExtendedQueryTagErrorAsync(
                tagKey,
                errorCode,
                watermark,
                cancellationToken));
 }
        public void Ctor_Should_Initialize_Code_And_Severity(string code, int severity)
        {
            // Arrange

            // Act
            var validationErrorCode = new ValidationErrorCode(code, severity);

            // Assert
            validationErrorCode.Code.Should().Be(code);
            validationErrorCode.Severity.Should().Be(severity);
        }
        public void Parse_Should_Return_Correctly_Initialized_ValidationErrorCode(string code, int severity)
        {
            // Arrange

            // Act
            var validationErrorCode = ValidationErrorCode.Parse(code);

            // Assert
            validationErrorCode.Code.Should().Be(code);
            validationErrorCode.Severity.Should().Be(severity);
        }
示例#13
0
 public static ValidationError CreateError(bool isWarning, ValidationErrorCode code, string source, string messageFormat, params object[] formatParams)
 {
     if (isWarning)
     {
         return(new ValidationWarning(code, source, messageFormat, formatParams));
     }
     else
     {
         return(new ValidationError(code, source, messageFormat, formatParams));
     }
 }
 /// <summary>
 /// Get error message for error code.
 /// </summary>
 /// <param name="errorCode">The error code</param>
 /// <returns>The message</returns>
 public static string GetMessage(this ValidationErrorCode errorCode)
 {
     if (MessageMap.TryGetValue(errorCode, out string message))
     {
         return(message);
     }
     else
     {
         Debug.Fail($"Missing message for error code {errorCode}");
         return(string.Empty);
     }
 }
示例#15
0
        /// <summary>
        /// Updates a limit type using a <see cref="Delta"/> object.
        /// </summary>
        /// <param name="id">ID of the entity to be updated.</param>
        /// <param name="delta">
        /// Delta containing a list of entity properties.  Web Api does the magic of converting the JSON to
        /// a delta.
        /// </param>
        /// <returns>
        /// An asynchronous task result containing information needed to create an API response message.
        /// </returns>
        public override async Task <CommandResult <LimitTypeBaseDto, Guid> > Update(Guid id, Delta <LimitTypeBaseDto> delta)
        {
            var userId = Thread.CurrentPrincipal == null ? null : Thread.CurrentPrincipal.GetUserIdFromPrincipal();

            if (userId == null)
            {
                return(Command.Error <LimitTypeBaseDto>(GeneralErrorCodes.TokenInvalid("UserId")));
            }

            if (delta == null)
            {
                return(Command.Error <LimitTypeBaseDto>(EntityErrorCode.EntityFormatIsInvalid));
            }

            var entity = await _context.LimitTypes
                         .SingleOrDefaultAsync(x => x.Id == id)
                         .ConfigureAwait(false);

            if (entity == null)
            {
                return(Command.Error <LimitTypeBaseDto>(EntityErrorCode.EntityNotFound));
            }

            var dto = _mapper.Map(entity, new LimitTypeBaseDto());

            delta.Patch(dto);

            var validationResponse = ValidatorUpdate.Validate(dto);

            if (_context.LimitTypes.Any(x => x.Id != id && x.I18NKeyName == dto.I18NKeyName))
            {
                validationResponse.FFErrors.Add(ValidationErrorCode.EntityPropertyDuplicateNotAllowed(nameof(LocationType.I18NKeyName)));
            }

            // Including the original Id in the Patch request will not return an error but attempting to change the Id is not allowed.
            if (dto.Id != id)
            {
                validationResponse.FFErrors.Add(ValidationErrorCode.EntityIDUpdateNotAllowed("Id"));
            }

            if (validationResponse.IsInvalid)
            {
                return(Command.Error <LimitTypeBaseDto>(validationResponse));
            }

            _context.LimitTypes.Attach(entity);
            _mapper.Map(dto, entity);
            entity.SetAuditFieldsOnUpdate(userId);

            await _context.SaveChangesAsync().ConfigureAwait(false);

            return(Command.NoContent <LimitTypeBaseDto>());
        }
        public void AsGenericResultOf_DifferentCode_Values_Should_Return_Correct_Result(string code, Type resultType, Type underlyingType)
        {
            // Arrange
            var errors = _fixture.Create <Dictionary <string, string[]> >();
            var validationErrorCode = ValidationErrorCode.Parse(code);

            // Act
            var result = validationErrorCode.AsGenericResultOf(underlyingType, errors);

            // Assert
            result.Should().BeOfType(resultType);
            (result as GeneralFail <int>) !.Errors.Should().BeSameAs(errors);
        }
示例#17
0
 public ValidationError(ValidationErrorCode code, string source, string messageformat, params object[] formatParams)
 {
     this.Code   = code;
     this.Source = source;
     try
     {
         this.Message = string.Format(messageformat, formatParams);
     }
     catch
     {
         this.Message = messageformat;
     }
 }
示例#18
0
        /// <summary>
        /// Creates a dashboard option.
        /// </summary>
        /// <param name="dto">Data Transfer Object (DTO) used to create an entity.</param>
        /// <returns>
        /// An asynchronous task result containing information needed to create an API response message.
        /// If successful, the task result contains the DTO associated with the entity created.
        /// </returns>
        public override async Task <CommandResult <DashboardOptionQueryDto, Guid> > Create(DashboardOptionBaseDto dto)
        {
            var userId = Thread.CurrentPrincipal == null ? null : Thread.CurrentPrincipal.GetUserIdFromPrincipal();

            if (userId == null)
            {
                return(Command.Error <DashboardOptionQueryDto>(GeneralErrorCodes.TokenInvalid("UserId")));
            }

            var validationResponse = ValidatorCreate.Validate(dto);

            if (dto == null)
            {
                return(Command.Error <DashboardOptionQueryDto>(validationResponse));
            }

            if (dto.Id != Guid.Empty)
            {
                validationResponse.FFErrors.Add(ValidationErrorCode.PropertyIsInvalid("Id"));
            }

            var userTenants = _context.GetTenantsForUser(Guid.Parse(userId));

            if (dto.TenantId != Guid.Empty && !userTenants.Any(x => x.Id == dto.TenantId))
            {
                validationResponse.FFErrors.Add(ValidationErrorCode.ForeignKeyValueDoesNotExist("TenantId"));
            }
            else if (_context.DashboardOptions.Any(x => x.TenantId == dto.TenantId))
            {
                validationResponse.FFErrors.Add(EntityErrorCode.EntityAlreadyExists);
            }

            if (validationResponse.IsInvalid)
            {
                return(Command.Error <DashboardOptionQueryDto>(validationResponse));
            }

            var newEntity = new DashboardOption();

            _mapper.Map(dto, newEntity);

            newEntity.Id = Guid.NewGuid();
            newEntity.SetAuditFieldsOnCreate(userId);

            _context.DashboardOptions.Add(newEntity);
            await _context.SaveChangesAsync().ConfigureAwait(false);

            return(Command.Created(_mapper.Map(newEntity, new DashboardOptionQueryDto()), newEntity.Id));
        }
示例#19
0
        public async Task When_Create_NoLocationTypeId_Should_Fail()
        {
            var dto = new LocationBaseDto
            {
                Name = "New Location"
            };

            var commandResult = await _facade.Create(dto);

            Assert.That(commandResult.StatusCode, Is.EqualTo(FacadeStatusCode.BadRequest));
            Assert.That(commandResult.GeneratedId, Is.EqualTo(Guid.Empty));
            Assert.That(commandResult.ErrorCodes.Count, Is.EqualTo(1));
            Assert.That(commandResult.ErrorCodes[0].Code, Is.EqualTo(ValidationErrorCode.PropertyRequired("LocationTypeId").Code));
            Assert.That(commandResult.ErrorCodes[0].Description, Is.EqualTo(ValidationErrorCode.PropertyRequired("LocationTypeId").Description));
        }
示例#20
0
        /// <summary>
        /// Creates a Location Log Entry.
        /// </summary>
        /// <param name="dto">Data Transfer Object (DTO) used to create a Location Log Entry.</param>
        /// <returns>
        /// An asynchronous task result containing information needed to create an API response message.
        /// If successful, the task result contains the DTO associated with the Location Log Entry.
        /// </returns>
        public override async Task <CommandResult <LocationLogEntryQueryDto, Guid> > Create(LocationLogEntryBaseDto dto)
        {
            // User ID should always be available, but if not ...
            var userId = GetCurrentUser();

            if (!userId.HasValue)
            {
                return(Command.Error <LocationLogEntryQueryDto>(GeneralErrorCodes.TokenInvalid("UserId")));
            }

            var validationResponse = ValidatorCreate.Validate(dto);

            if (dto == null)
            {
                return(Command.Error <LocationLogEntryQueryDto>(validationResponse));
            }

            if (dto.Id != Guid.Empty)
            {
                validationResponse.FFErrors.Add(ValidationErrorCode.PropertyIsInvalid(nameof(LocationLogEntry.Id)));
            }

            var locationExists = await DoesLocationExist(dto.LocationId);

            if (!locationExists)
            {
                validationResponse.FFErrors.Add(ValidationErrorCode.ForeignKeyValueDoesNotExist(nameof(LocationLogEntry.LocationId)));
            }

            if (validationResponse.IsInvalid)
            {
                return(Command.Error <LocationLogEntryQueryDto>(validationResponse));
            }

            var locationLogEntry = new LocationLogEntry
            {
                Id = Guid.NewGuid()
            };

            _mapper.Map(dto, locationLogEntry);

            locationLogEntry.SetAuditFieldsOnCreate(userId.Value);

            _context.LocationLogEntries.Add(locationLogEntry);
            await _context.SaveChangesAsync().ConfigureAwait(false);

            return(Command.Created(_mapper.Map(locationLogEntry, new LocationLogEntryQueryDto()), locationLogEntry.Id));
        }
示例#21
0
        public async Task When_Create_LocationTypeIdNoExist_Should_Fail()
        {
            var dto = new LocationBaseDto
            {
                Name           = "New Location",
                LocationTypeId = Guid.NewGuid()
            };

            var commandResult = await _facade.Create(dto);

            Assert.That(commandResult.StatusCode, Is.EqualTo(FacadeStatusCode.BadRequest));
            Assert.That(commandResult.GeneratedId, Is.EqualTo(Guid.Empty));
            Assert.That(commandResult.ErrorCodes.Count, Is.EqualTo(1));
            Assert.That(commandResult.ErrorCodes[0].Code, Is.EqualTo(ValidationErrorCode.ForeignKeyValueDoesNotExist("LocationTypeId").Code));
            Assert.That(commandResult.ErrorCodes[0].Description, Is.EqualTo(ValidationErrorCode.ForeignKeyValueDoesNotExist("LocationTypeId").Description));
        }
示例#22
0
        public async Task When_Create_ParentIdNoExist_Should_Fail()
        {
            var distributionType = _mockContext.Object.LocationTypes.Single(x => x.I18NKeyName == "Distribution");
            var dto = new LocationBaseDto
            {
                Name           = "New Location",
                LocationTypeId = distributionType.Id,
                ParentId       = Guid.NewGuid()
            };

            var commandResult = await _facade.Create(dto);

            Assert.That(commandResult.StatusCode, Is.EqualTo(FacadeStatusCode.BadRequest));
            Assert.That(commandResult.GeneratedId, Is.EqualTo(Guid.Empty));
            Assert.That(commandResult.ErrorCodes.Count, Is.EqualTo(1));
            Assert.That(commandResult.ErrorCodes[0].Code, Is.EqualTo(ValidationErrorCode.ForeignKeyValueDoesNotExist("ParentId").Code));
            Assert.That(commandResult.ErrorCodes[0].Description, Is.EqualTo(ValidationErrorCode.ForeignKeyValueDoesNotExist("ParentId").Description));
        }
        public async Task GivenMultipleTagsOnSameInstance_WhenDeleteInstance_ThenAssociatedErrorsShouldBeRemoved()
        {
            string studyUid1    = TestUidGenerator.Generate();
            string seriesUid1   = TestUidGenerator.Generate();
            string instanceUid1 = TestUidGenerator.Generate();
            string studyUid2    = TestUidGenerator.Generate();
            string seriesUid2   = TestUidGenerator.Generate();
            string instanceUid2 = TestUidGenerator.Generate();

            // add instances
            long watermark1 = await AddInstanceAsync(studyUid1, seriesUid1, instanceUid1);

            long watermark2 = await AddInstanceAsync(studyUid2, seriesUid2, instanceUid2);

            // add tags
            DicomTag tag1    = DicomTag.DeviceSerialNumber;
            int      tagKey1 = await AddTagAsync(tag1);

            DicomTag tag2    = DicomTag.DeviceID;
            int      tagKey2 = await AddTagAsync(tag2);

            // add errors
            ValidationErrorCode errorCode = ValidationErrorCode.DateIsInvalid;

            // both tag has error on instance1
            await _extendedQueryTagErrorStore.AddExtendedQueryTagErrorAsync(tagKey1, errorCode, watermark1);

            await _extendedQueryTagErrorStore.AddExtendedQueryTagErrorAsync(tagKey2, errorCode, watermark1);

            // Only tag2 has error on instance2
            await _extendedQueryTagErrorStore.AddExtendedQueryTagErrorAsync(tagKey2, errorCode, watermark2);

            // delete instance1
            await _indexDataStore.DeleteInstanceIndexAsync(new InstanceIdentifier(studyUid1, seriesUid1, instanceUid1, DefaultPartition.Key));

            // check errors
            Assert.Empty(await _extendedQueryTagErrorStore.GetExtendedQueryTagErrorsAsync(tag1.GetPath(), 1, 0));
            var errors = await _extendedQueryTagErrorStore.GetExtendedQueryTagErrorsAsync(tag2.GetPath(), int.MaxValue, 0);

            Assert.Single(errors);
            Assert.Equal(studyUid2, errors[0].StudyInstanceUid);
            Assert.Equal(seriesUid2, errors[0].SeriesInstanceUid);
            Assert.Equal(instanceUid2, errors[0].SopInstanceUid);
        }
示例#24
0
        public async Task <IHttpActionResult> GetConfig([FromUri] Guid?tenantId, [FromUri] Guid?operationId = null)
        {
            var errors = new List <FFErrorCode>();

            if (!tenantId.HasValue)
            {
                errors.Add(ValidationErrorCode.PropertyRequired(nameof(tenantId)));
            }

            if (errors.Any())
            {
                return(Request.CreateApiResponse(NoDtoHelpers.CreateCommandResult(errors)));
            }

            var authHeader = Request.Headers.Authorization.ToString();
            var result     = await _facade.Get((Guid)tenantId, operationId, authHeader);

            return(Request.CreateApiResponse(result));
        }
示例#25
0
        /// <summary>
        /// Creates a limit type.
        /// </summary>
        /// <param name="dto">Data Transfer Object (DTO) used to create an entity.</param>
        /// <returns>
        /// An asynchronous task result containing information needed to create an API response message.
        /// If successful, the task result contains the DTO associated with the entity created.
        /// </returns>
        public override async Task <CommandResult <LimitTypeQueryDto, Guid> > Create(LimitTypeBaseDto dto)
        {
            var userId = Thread.CurrentPrincipal == null ? null : Thread.CurrentPrincipal.GetUserIdFromPrincipal();

            if (userId == null)
            {
                return(Command.Error <LimitTypeQueryDto>(GeneralErrorCodes.TokenInvalid("UserId")));
            }

            var validationResponse = ValidatorCreate.Validate(dto);

            if (dto == null)
            {
                return(Command.Error <LimitTypeQueryDto>(validationResponse));
            }

            if (dto.Id != Guid.Empty)
            {
                validationResponse.FFErrors.Add(ValidationErrorCode.PropertyIsInvalid("Id"));
            }

            if (_context.LimitTypes.Any(x => x.I18NKeyName == dto.I18NKeyName))
            {
                validationResponse.FFErrors.Add(EntityErrorCode.EntityAlreadyExists);
            }

            if (validationResponse.IsInvalid)
            {
                return(Command.Error <LimitTypeQueryDto>(validationResponse));
            }

            var newEntity = new LimitType();

            _mapper.Map(dto, newEntity);

            newEntity.Id = Guid.NewGuid();
            newEntity.SetAuditFieldsOnCreate(userId);

            _context.LimitTypes.Add(newEntity);
            await _context.SaveChangesAsync().ConfigureAwait(false);

            return(Command.Created(_mapper.Map(newEntity, new LimitTypeQueryDto()), newEntity.Id));
        }
        public async Task GivenStudyWithMultileInstances_WhenDeleteStudy_ThenAssociatedErrorsShouldBeRemoved()
        {
            string studyUid1    = TestUidGenerator.Generate();
            string seriesUid1   = TestUidGenerator.Generate();
            string instanceUid1 = TestUidGenerator.Generate();
            string seriesUid2   = TestUidGenerator.Generate();
            string instanceUid2 = TestUidGenerator.Generate();
            string studyUid3    = TestUidGenerator.Generate();
            string seriesUid3   = TestUidGenerator.Generate();
            string instanceUid3 = TestUidGenerator.Generate();

            // add instances: instance1 and instance2 are in same study
            long watermark1 = await AddInstanceAsync(studyUid1, seriesUid1, instanceUid1);

            long watermark2 = await AddInstanceAsync(studyUid1, seriesUid2, instanceUid2);

            long watermark3 = await AddInstanceAsync(studyUid3, seriesUid3, instanceUid3);

            // add tag
            DicomTag tag    = DicomTag.DeviceSerialNumber;
            int      tagKey = await AddTagAsync(tag);


            // add errors
            ValidationErrorCode errorCode = ValidationErrorCode.DateIsInvalid;
            await _extendedQueryTagErrorStore.AddExtendedQueryTagErrorAsync(tagKey, errorCode, watermark1);

            await _extendedQueryTagErrorStore.AddExtendedQueryTagErrorAsync(tagKey, errorCode, watermark2);

            await _extendedQueryTagErrorStore.AddExtendedQueryTagErrorAsync(tagKey, errorCode, watermark3);

            // delete instance
            await _indexDataStore.DeleteStudyIndexAsync(DefaultPartition.Key, studyUid1, DateTime.UtcNow);

            // check errors
            var errors = await _extendedQueryTagErrorStore.GetExtendedQueryTagErrorsAsync(tag.GetPath(), int.MaxValue, 0);

            Assert.Single(errors);
            Assert.Equal(studyUid3, errors[0].StudyInstanceUid);
            Assert.Equal(seriesUid3, errors[0].SeriesInstanceUid);
            Assert.Equal(instanceUid3, errors[0].SopInstanceUid);
        }
示例#27
0
        public async Task GivenValidInput_WhenAddingExtendedQueryTag_ThenShouldSucceed()
        {
            const int  TagKey    = 7;
            const long Watermark = 30;
            const ValidationErrorCode ErrorCode = ValidationErrorCode.DateIsInvalid;

            await _extendedQueryTagErrorsService.AddExtendedQueryTagErrorAsync(
                TagKey,
                ErrorCode,
                Watermark,
                _tokenSource.Token);

            await _extendedQueryTagErrorStore
            .Received(1)
            .AddExtendedQueryTagErrorAsync(
                Arg.Is(TagKey),
                Arg.Is(ErrorCode),
                Arg.Is(Watermark),
                Arg.Is(_tokenSource.Token));
        }
示例#28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ValidationError"/> class.
        /// </summary>
        /// <param name="resource">The resource.</param>
        /// <param name="field">The field.</param>
        /// <param name="code">The code.</param>
        /// <param name="errorMessage">The error message.</param>
        public ValidationError(string resource, string field, ValidationErrorCode code, string errorMessage = null)
        {
            if (string.IsNullOrWhiteSpace(resource))
            {
                throw new ArgumentNullException(nameof(resource));
            }

            if (string.IsNullOrWhiteSpace(field))
            {
                throw new ArgumentNullException(nameof(field));
            }

            if (code == ValidationErrorCode.None)
            {
                throw new ArgumentNullException(nameof(code));
            }

            this.Resource = resource;
            this.Field    = field;
            this.Code     = code;
            this.Message  = errorMessage;
        }
 public static ValidationErrorCode OrGeneralErrorCodeIfNull(this ValidationErrorCode validationErrorCode)
 => validationErrorCode ?? ValidationErrorCode.GeneralError;
示例#30
0
        /// <summary>
        /// Updates a location using a <see cref="Delta"/> object.
        /// </summary>
        /// <param name="id">ID of the location to be updated.</param>
        /// <param name="delta">
        /// Delta containing a list of location properties.  Web Api does the magic of converting the JSON to
        /// a delta.
        /// </param>
        /// <returns>
        /// An asynchronous task result containing information needed to create an API response message.
        /// </returns>
        public override async Task <CommandResult <LocationBaseDto, Guid> > Update(Guid id, Delta <LocationBaseDto> delta)
        {
            // Thread.CurrentPrincipal is not available in the constrtor.  Do not try and move this
            var uid = GetCurrentUser();

            // User ID should always be available, but if not ...
            if (!uid.HasValue)
            {
                return(Command.Error <LocationBaseDto>(GeneralErrorCodes.TokenInvalid("UserId")));
            }

            if (delta == null)
            {
                return(Command.Error <LocationBaseDto>(EntityErrorCode.EntityFormatIsInvalid));
            }

            var location = await _context.GetLocationsForUser(uid.Value)
                           .SingleOrDefaultAsync(l => l.Id == id)
                           .ConfigureAwait(false);

            if (location == null)
            {
                return(Command.Error <LocationBaseDto>(EntityErrorCode.EntityNotFound));
            }

            var locationDto = _mapper.Map(location, new LocationBaseDto());

            delta.Patch(locationDto);

            var validationResponse = ValidatorUpdate.Validate(locationDto);

            if (locationDto.ParentId.HasValue)
            {
                var existingTask = _context.Locations.AnyAsync(l => l.Id == locationDto.ParentId.Value);

                if (!existingTask.Result)
                {
                    validationResponse.FFErrors.Add(ValidationErrorCode.ForeignKeyValueDoesNotExist(nameof(Location.ParentId)));
                }
                else
                {
                    // Check for circular references
                    if (await LocationValidator.IsCircularReference(_context.Locations, locationDto, id))
                    {
                        validationResponse.FFErrors.Add(ValidationErrorCode.CircularReferenceNotAllowed(nameof(Location.ParentId)));
                    }
                }
            }

            // Check that Location Type exists
            if (locationDto.LocationTypeId != Guid.Empty && !_context.LocationTypes.Any(lt => lt.Id == locationDto.LocationTypeId))
            {
                validationResponse.FFErrors.Add(ValidationErrorCode.ForeignKeyValueDoesNotExist(nameof(Location.LocationTypeId)));
            }

            // Including the original Id in the Patch request will not return an error but attempting to change the Id is not allowed.
            if (locationDto.Id != id)
            {
                validationResponse.FFErrors.Add(ValidationErrorCode.EntityIDUpdateNotAllowed("Id"));
            }

            // Check that unique fields are still unique
            if (_context.Locations.Any(l => l.Id != id && l.Name == locationDto.Name))
            {
                validationResponse.FFErrors.Add(ValidationErrorCode.EntityPropertyDuplicateNotAllowed(nameof(Location.Name)));
            }

            if (validationResponse.IsInvalid)
            {
                return(Command.Error <LocationBaseDto>(validationResponse));
            }

            _context.Locations.Attach(location);
            _mapper.Map(locationDto, location);

            location.SetAuditFieldsOnUpdate(uid.Value);

            await _context.SaveChangesAsync().ConfigureAwait(false);

            return(Command.NoContent <LocationBaseDto>());
        }
示例#31
0
 public ValidationError(ValidationErrorCode code, string source, string messageformat, params object[] formatParams)
 {
     this.Code = code;
     this.Source = source;
     this.Message = string.Format(messageformat, formatParams);
 }
示例#32
0
        public static ValidationError NewConsolidatedError(ValidationErrorCode code, ValidationError[] errors, string message, params object[] parameters)
        {
            var error = errors.All(err => err.IsWarning) ? new ValidationWarning(code, null, message, parameters) : new ValidationError(code, null, message, parameters);

            error.InnerErrors = errors;
            return error;
        }
 public ValidationWarning(ValidationErrorCode code, string source, string format, params object[] formatParams)
     : base(code, source, format, formatParams)
 {
 }
 public ValidationError(ValidationErrorCode code, string message)
 {
     _code = code;
     _message = message;
 }
示例#35
0
 public static ValidationError CreateError(bool isWarning, ValidationErrorCode code, string source, string messageFormat, params object[] formatParams)
 {
     if (isWarning)
         return new ValidationWarning(code, source, messageFormat, formatParams);
     else
         return new ValidationError(code, source, messageFormat, formatParams);
 }