public void ReturnFailureForNotWellFormedUri()
		{
			LocationValidator validator = new LocationValidator(".foo");
			ValidationResults validationResults = validator.Validate("http: //host/foo");

			Assert.IsFalse(validationResults.IsValid);
		}
		public void ReturnFailureForNullFile()
		{
			LocationValidator validator = new LocationValidator(".foo");
			ValidationResults validationResults = validator.Validate(null);

			Assert.IsFalse(validationResults.IsValid);
		}
		public void ReturnFailureForInvalidFile()
		{
			LocationValidator validator = new LocationValidator(".foo");
			ValidationResults validationResults = validator.Validate(@"C:\SomeFile>");

			Assert.IsFalse(validationResults.IsValid);
		}
		public void ReturnSuccessForValidFile()
		{
			LocationValidator validator = new LocationValidator(".dll");
			ValidationResults validationResults = validator.Validate(Assembly.GetExecutingAssembly().Location);

			Assert.IsTrue(validationResults.IsValid);
		}
Exemplo n.º 5
0
        public void ValidateLocationShouldNotThrowExceptionWithCorrectLocationBuilder()
        {
            var actionResultWithLocation = new CreatedNegotiatedContentResult <int>(
                TestObjectFactory.GetUri(), 5, MyWebApi.Controller <WebApiController>().Controller);

            LocationValidator.ValidateLocation(
                actionResultWithLocation,
                location =>
                location
                .WithHost("somehost.com")
                .AndAlso()
                .WithAbsolutePath("/someuri/1")
                .AndAlso()
                .WithPort(80)
                .AndAlso()
                .WithScheme("http")
                .AndAlso()
                .WithFragment(string.Empty)
                .AndAlso()
                .WithQuery("?query=Test"),
                TestObjectFactory.GetFailingValidationAction());
        }
Exemplo n.º 6
0
        public void ParentShouldNotBeSameAsEntity()
        {
            // Arrange
            var parentId = 999;
            var location = NewLocation("SameName", parentId);

            var repository = new Mock <IRepository>();

            repository.Setup(x => x.FindOne <MDM.Location>(parentId))
            .Returns(new MDM.Location {
                Name = "SameName"
            });

            // Act
            var violations = new List <IRule>();
            var validator  = new LocationValidator(new Mock <IValidatorEngine>().Object, repository.Object);
            var result     = validator.IsValid(location, violations);

            // Assert
            Assert.IsFalse(result, "Validation should not have succeeded");
            Assert.AreEqual(1, violations.Count);
            Assert.AreEqual("Parent must not be same as entity", violations[0].Message);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Validates geolocation candidates by streets geocoder.
        /// </summary>
        /// <param name="addresses">Address to geocode.</param>
        /// <param name="candidates">Geocded candidates.</param>
        private void _ValidateLocation(Address[] addresses, AddressCandidate[] candidates)
        {
            Debug.Assert(null != addresses);                     // created
            Debug.Assert(null != candidates);                    // created
            Debug.Assert(candidates.Length == addresses.Length); // valid stated
            Debug.Assert(null != _checker);                      // inited

            // init location validator
            var streetsGeocoder   = App.Current.StreetsGeocoder;
            var locationValidator = new LocationValidator(streetsGeocoder);

            // do validation
            var incorrectCandidates = locationValidator
                                      .FindIncorrectLocations(candidates)
                                      .GroupBy(index => addresses[index])
                                      .ToArray();

            // get incorrect candidate indexes
            var addressesForGeocoding = incorrectCandidates
                                        .Select(item => item.Key)
                                        .ToArray();

            _checker.ThrowIfCancellationRequested();

            // regeocoding by streets geocoder
            var fixedCandidates = streetsGeocoder.BatchGeocode(addressesForGeocoding);

            // update regeocoded candidates
            for (var index = 0; index < fixedCandidates.Length; ++index)
            {
                _checker.ThrowIfCancellationRequested();
                foreach (var j in incorrectCandidates[index])
                {
                    candidates[j] = fixedCandidates[index];
                }
            }
        }
        public void BadSystemFails()
        {
            // Assert
            var start = new DateTime(1999, 1, 1);
            var finish = new DateTime(2020, 12, 31);
            var validity = new DateRange(start, finish);
            var system = new MDM.SourceSystem { Name = "Test" };
            var locationMapping = new LocationMapping { System = system, MappingValue = "1", Validity = validity };

            var list = new List<LocationMapping> { locationMapping };
            var repository = new Mock<IRepository>();
            repository.Setup(x => x.Queryable<LocationMapping>()).Returns(list.AsQueryable());

            var badSystemIdentifier = new EnergyTrading.Mdm.Contracts.MdmId
            {
                SystemName = "Jim",
                Identifier = "1",
                StartDate = start.AddHours(-10),
                EndDate = start.AddHours(-5)
            };

            var identifierValidator = new NexusIdValidator<LocationMapping>(repository.Object);
            var validatorEngine = new Mock<IValidatorEngine>();
            validatorEngine.Setup(x => x.IsValid(It.IsAny<EnergyTrading.Mdm.Contracts.MdmId>(), It.IsAny<IList<IRule>>()))
                           .Returns((EnergyTrading.Mdm.Contracts.MdmId x, IList<IRule> y) => identifierValidator.IsValid(x, y));
            var validator = new LocationValidator(validatorEngine.Object, repository.Object);

            var location = new Location { Identifiers = new EnergyTrading.Mdm.Contracts.MdmIdList { badSystemIdentifier } };

            // Act
            var violations = new List<IRule>();
            var result = validator.IsValid(location, violations);

            // Assert
            Assert.IsFalse(result, "Validator succeeded");
        }
Exemplo n.º 9
0
        /// <summary>
        /// Tests whether created result has specific location provided by string.
        /// </summary>
        /// <param name="location">Expected location as string.</param>
        /// <returns>The same created test builder.</returns>
        public IAndCreatedTestBuilder AtLocation(string location)
        {
            var uri = LocationValidator.ValidateAndGetWellFormedUriString(location, this.ThrowNewCreatedResultAssertionException);

            return(this.AtLocation(uri));
        }
        public void ParentShouldNotBeSameAsEntity()
        {
            // Arrange
            var parentId = 999;
            var location = NewLocation("SameName", parentId);

            var repository = new Mock<IRepository>();
            repository.Setup(x => x.FindOne<MDM.Location>(parentId))
                .Returns(new MDM.Location { Name = "SameName"});

            // Act
            var violations = new List<IRule>();
            var validator = new LocationValidator(new Mock<IValidatorEngine>().Object, repository.Object);
            var result = validator.IsValid(location, violations);

            // Assert
            Assert.IsFalse(result, "Validation should not have succeeded");
            Assert.AreEqual(1, violations.Count);
            Assert.AreEqual("Parent must not be same as entity", violations[0].Message);
        }
        public void GivenLocation_ValidateShouldReturnExpected(int xCoordinate, int yCoordinate, bool expected, [Frozen] Mock <IPlateu> plateu, LocationValidator sut)
        {
            plateu.SetupGet(p => p.Size).Returns(new Size(5, 5));

            var actual = sut.Validate(new Location(xCoordinate, yCoordinate), plateu.Object);

            actual.Should().Be(expected);
        }
Exemplo n.º 12
0
 public EditLocationCommand(MFGContext context, IMapper mapper, LocationValidator validator)
 {
     _context   = context;
     _mapper    = mapper;
     _validator = validator;
 }
Exemplo n.º 13
0
        /// <summary>
        /// Validates geolocation candidates by streets geocoder.
        /// </summary>
        /// <param name="addresses">Address to geocode.</param>
        /// <param name="candidates">Geocded candidates.</param>
        private void _ValidateLocation(Address[] addresses, AddressCandidate[] candidates)
        {
            Debug.Assert(null != addresses); // created
            Debug.Assert(null != candidates); // created
            Debug.Assert(candidates.Length == addresses.Length); // valid stated
            Debug.Assert(null != _checker); // inited

            // init location validator
            var streetsGeocoder = App.Current.StreetsGeocoder;
            var locationValidator = new LocationValidator(streetsGeocoder);

            // do validation
            var incorrectCandidates = locationValidator
                .FindIncorrectLocations(candidates)
                .GroupBy(index => addresses[index])
                .ToArray();

            // get incorrect candidate indexes
            var addressesForGeocoding = incorrectCandidates
                .Select(item => item.Key)
                .ToArray();

            _checker.ThrowIfCancellationRequested();

            // regeocoding by streets geocoder
            var fixedCandidates = streetsGeocoder.BatchGeocode(addressesForGeocoding);

            // update regeocoded candidates
            for (var index = 0; index < fixedCandidates.Length; ++index)
            {
                _checker.ThrowIfCancellationRequested();
                foreach (var j in incorrectCandidates[index])
                {
                    candidates[j] = fixedCandidates[index];
                }
            }
        }
Exemplo n.º 14
0
 public MeetupAppService(IDocumentStore eventStore, LocationValidator validateLocation)
 {
     _validateLocation = validateLocation;
     _eventStore       = eventStore;
 }
 public override IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
 {
   var validator = new LocationValidator();
   var result = validator.Validate(this);
   return result.Errors.Select(item => new ValidationResult(item.ErrorMessage, new[] { item.PropertyName }));
 }
Exemplo n.º 16
0
 public EFAddLocation(OzposloviContext context, LocationValidator validations)
 {
     _context         = context;
     this.validations = validations;
 }
		public void ReturnSuccessForValidUri()
		{
			LocationValidator validator = new LocationValidator(".foo");
			ValidationResults validationResults = validator.Validate("http://foo");

			Assert.IsTrue(validationResults.IsValid);
		}
Exemplo n.º 18
0
 public LocationService(IKeyedRepository<int, Location> locationRepo)
 {
     _repo = locationRepo;
     _validation = new LocationValidator();
 }
        public void ValidLocationPasses()
        {
            // Assert
            var start = new DateTime(1999, 1, 1);
            var system = new MDM.SourceSystem { Name = "Test" };

            var systemList = new List<MDM.SourceSystem> { system };
            var systemRepository = new Mock<IRepository>();
            var repository = new StubValidatorRepository();

            systemRepository.Setup(x => x.Queryable<MDM.SourceSystem>()).Returns(systemList.AsQueryable());

            var identifier = new EnergyTrading.Mdm.Contracts.MdmId
            {
                SystemName = "Test",
                Identifier = "1",
                StartDate = start.AddHours(-10),
                EndDate = start.AddHours(-5)
            };

            var validatorEngine = new Mock<IValidatorEngine>();
            var validator = new LocationValidator(validatorEngine.Object, repository);

            var location = new Location { Details = new EnergyTrading.MDM.Contracts.Sample.LocationDetails{Name = "Test"}, Identifiers = new EnergyTrading.Mdm.Contracts.MdmIdList { identifier } };
            this.AddRelatedEntities(location);

            // Act
            var violations = new List<IRule>();
            var result = validator.IsValid(location, violations);

            // Assert
            Assert.IsTrue(result, "Validator failed");
            Assert.AreEqual(0, violations.Count, "Violation count differs");
        }
Exemplo n.º 20
0
        /// <summary>
        /// Validates and fixes candidates with incorrect locations.
        /// </summary>
        /// <param name="candidates">The reference to the collection of address candidates to
        /// be validated and fixed.</param>
        /// <param name="geocodable">The reference to the geocodable object used for retrieving
        /// candidates collection.</param>
        /// <returns>A reference to the collection of address candidates with fixed
        /// locations.</returns>
        private IEnumerable<AddressCandidate> _GetValidLocations(
            IEnumerable<AddressCandidate> candidates,
            IGeocodable geocodable)
        {
            Debug.Assert(candidates != null);
            Debug.Assert(candidates.All(candidate => candidate != null));
            Debug.Assert(geocodable != null);

            List<int> incorrectCandidates = new List<int>();

            try
            {
                var streetsGeocoder = App.Current.StreetsGeocoder;
                var locationValidator = new LocationValidator(streetsGeocoder);

                incorrectCandidates = locationValidator
                    .FindIncorrectLocations(candidates)
                    .ToList();
            }
            catch (Exception ex)
            {
                if (GeocodeHelpers.MustThrowException(ex))
                {
                    throw;
                }
            }

            if (!incorrectCandidates.Any())
            {
                return candidates;
            }

            // Get incorrect address candidates.
            List<AddressCandidate> allCandidates = candidates.ToList();
            var invalidAddressCandidates = incorrectCandidates
                .Select(index => allCandidates[index])
                .ToList();

            // Get all candidates which is not invalid.
            var result = candidates
                .Except(invalidAddressCandidates)
                .ToList();

            return result;
        }
        /// <inheritdoc />
        public IAndRedirectTestBuilder ToUrl(string location)
        {
            var uri = LocationValidator.ValidateAndGetWellFormedUriString(location, this.ThrowNewRedirectResultAssertionException);

            return(this.ToUrl(uri));
        }
Exemplo n.º 22
0
        /// <summary>
        /// Tests whether redirect result has specific location provided by string.
        /// </summary>
        /// <param name="location">Expected location as string.</param>
        /// <returns>Base test builder.</returns>
        public IBaseTestBuilderWithCaughtException AtLocation(string location)
        {
            var uri = LocationValidator.ValidateAndGetWellFormedUriString(location, this.ThrowNewRedirectResultAssertionException);

            return(this.AtLocation(uri));
        }
Exemplo n.º 23
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>());
        }
Exemplo n.º 24
0
 public MeetupAppService(MeetupRepository repo, AttendantsRepository attendantsRepo, IBus bus, LocationValidator validateLocation)
 {
     _repo             = repo;
     _attendantsRepo   = attendantsRepo;
     _validateLocation = validateLocation;
     _bus = bus;
 }