示例#1
0
        /// <inheritdoc/>
        public RequestValidationResult Validate()
        {
            RequestValidationResult result = new RequestValidationResult();

            // Must contain at least one of either BluetoothSeeds or AreaMatches
            if (this.AreaMatches.Count == 0 && this.BluetoothMatches.Count == 0)
            {
                result.Fail(
                    RequestValidationIssue.InputEmpty,
                    RequestValidationProperty.Multiple,
                    ValidationMessages.EmptyMessage
                    );
            }
            if (this.AreaMatches.Count > 0)
            {
                // Validate individual area matches
                foreach (AreaMatch areaMatch in this.AreaMatches)
                {
                    // Use AreaMatch.Validate()
                    result.Combine(areaMatch.Validate());
                }
            }
            if (this.BluetoothMatches.Count > 0)
            {
                // Validate individual Bluetooth matches
                foreach (BluetoothMatch btMatch in this.BluetoothMatches)
                {
                    // User BluetoothMatch.Validate()
                    result.Combine(btMatch.Validate());
                }
            }

            return(result);
        }
示例#2
0
        /// <inheritdoc/>
        public async Task PublishAreaAsync(NarrowcastMessage message, CancellationToken cancellationToken = default)
        {
            // Validate inputs
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            RequestValidationResult validationResult = message.Validate();

            if (validationResult.Passed)
            {
                // Build a MessageContainer for the submitted NarrowcastMessage
                MessageContainer container = new MessageContainer();
                container.Narrowcasts.Add(message);

                // Define regions for the published message
                IEnumerable <Region> messageRegions = RegionHelper.GetRegionsCoverage(message.Area, this.PrecisionMin, this.PrecisionMax);

                // Publish
                await this._reportRepo.InsertAsync(container, messageRegions, cancellationToken);
            }
            else
            {
                throw new RequestValidationFailedException(validationResult);
            }
        }
        /// <inheritdoc/>
        public async Task <string> PublishAsync(InfectionReport report, Region region, CancellationToken cancellationToken = default)
        {
            // Validate inputs
            if (report == null)
            {
                throw new ArgumentNullException(nameof(report));
            }
            if (region == null)
            {
                throw new ArgumentNullException(nameof(region));
            }

            RequestValidationResult validationResult = report.Validate();

            validationResult.Combine(region.Validate());

            if (validationResult.Passed)
            {
                // Push to upstream data repository
                return(await this._reportRepo.InsertAsync(report, region, cancellationToken));
            }
            else
            {
                throw new RequestValidationFailedException(validationResult);
            }
        }
示例#4
0
        /// <inheritdoc/>
        public async Task <IEnumerable <MessageContainerMetadata> > GetLatestInfoAsync(Region region, long lastTimestamp, CancellationToken cancellationToken = default)
        {
            if (region == null)
            {
                throw new ArgumentNullException(nameof(region));
            }
            else
            {
                // Validate region
                RequestValidationResult validationResult = region.Validate();

                // Validate timestamp
                validationResult.Combine(Validator.ValidateFromRange(
                                             lastTimestamp,
                                             0,
                                             DateTimeOffset.UtcNow.AddDays(1).ToUnixTimeMilliseconds(),
                                             Entities.Validation.Resources.ValidationMessages.InvalidTimestamp));

                lastTimestamp = Math.Max(lastTimestamp, DateTimeOffset.UtcNow.AddDays(-MAX_MESSAGE_AGE_DAYS).ToUnixTimeMilliseconds());

                if (validationResult.Passed)
                {
                    // Get message information from database
                    return(await this._reportRepo.GetLatestAsync(RegionHelper.AdjustToPrecision(region), lastTimestamp, cancellationToken));
                }
                else
                {
                    throw new RequestValidationFailedException(validationResult);
                }
            }
        }
示例#5
0
        /// <inheritdoc/>
        public async Task <string> PublishAsync(SelfReportRequest request, long timeAtRequest, CancellationToken cancellationToken = default)
        {
            // Validate inputs
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            RequestValidationResult validationResult = request.Validate();

            validationResult.Combine(Validator.ValidateTimestamp(timeAtRequest));

            if (validationResult.Passed)
            {
                // Build MatchMessage from submitted content
                MatchMessage   message = new MatchMessage();
                BluetoothMatch matches = new BluetoothMatch();
                matches.Seeds.AddRange(request.Seeds);

                // Store in data repository
                message.BluetoothMatches.Add(matches);
                return(await this._messageRepo.InsertAsync(message, request.Region, cancellationToken));
            }
            else
            {
                throw new RequestValidationFailedException(validationResult);
            }
        }
示例#6
0
        /// <inheritdoc/>
        public RequestValidationResult Validate()
        {
            RequestValidationResult result = new RequestValidationResult();

            // Validate location
            if (this.Location == null)
            {
                result.Fail(
                    RequestValidationIssue.InputNull,
                    nameof(this.Location),
                    ValidationMessages.NullLocation
                    );
            }
            else
            {
                // Validate using Coordinates.Validate()
                result.Combine(this.Location.Validate());
            }

            // Validate timestamps
            result.Combine(Validator.ValidateTimestamp(this.BeginTimestamp, parameterName: nameof(this.BeginTimestamp)));
            result.Combine(Validator.ValidateTimestamp(this.EndTimestamp, parameterName: nameof(this.EndTimestamp)));
            result.Combine(Validator.ValidateTimeRange(this.BeginTimestamp, this.EndTimestamp));

            return(result);
        }
示例#7
0
        /// <inheritdoc/>
        public RequestValidationResult Validate()
        {
            RequestValidationResult result = new RequestValidationResult();

            // Validate provided NarrowcastArea
            if (this.Area != null)
            {
                // Use NarrowcastArea.Validate()
                result.Combine(this.Area.Validate());
            }
            else
            {
                result.Fail(
                    RequestValidationIssue.InputEmpty,
                    nameof(this.Area),
                    ValidationMessages.EmptyAreas
                    );
            }

            // Validate message
            if (String.IsNullOrEmpty(this.UserMessage))
            {
                result.Fail(
                    RequestValidationIssue.InputEmpty,
                    nameof(this.UserMessage),
                    ValidationMessages.EmptyMessage
                    );
            }

            return(result);
        }
        /// <inheritdoc/>
        public async Task <IEnumerable <InfectionReportMetadata> > GetLatestInfoAsync(Region region, long lastTimestamp, CancellationToken cancellationToken = default)
        {
            if (region == null)
            {
                throw new ArgumentNullException(nameof(region));
            }
            else
            {
                // Validate region
                RequestValidationResult validationResult = region.Validate();

                // Validate timestamp
                validationResult.Combine(Validator.ValidateTimestamp(lastTimestamp));

                if (validationResult.Passed)
                {
                    // Get message information from database
                    return(await this._reportRepo.GetLatestAsync(region, lastTimestamp, cancellationToken));
                }
                else
                {
                    throw new RequestValidationFailedException(validationResult);
                }
            }
        }
示例#9
0
        /// <inheritdoc/>
        public RequestValidationResult Validate()
        {
            RequestValidationResult result = new RequestValidationResult();

            // Validate location
            if (this.Location == null)
            {
                result.Fail(
                    RequestValidationIssue.InputNull,
                    nameof(this.Location),
                    ValidationMessages.NullLocation
                    );
            }
            else
            {
                // Validate using Coordinates.Validate()
                result.Combine(this.Location.Validate());
            }

            // Validate timestamps
            result.Combine(Validator.ValidateTimestamp(this.BeginTimestamp,
                                                       asOf: DateTimeOffset.UtcNow.AddDays(FUTURE_TIME_WINDOW_DAYS).ToUnixTimeMilliseconds(),
                                                       maxAgeDays: FUTURE_TIME_WINDOW_DAYS + PAST_TIME_WINDOW_DAYS,
                                                       parameterName: nameof(this.BeginTimestamp)));
            result.Combine(Validator.ValidateTimestamp(this.EndTimestamp,
                                                       asOf: DateTimeOffset.UtcNow.AddDays(FUTURE_TIME_WINDOW_DAYS).ToUnixTimeMilliseconds(),
                                                       maxAgeDays: FUTURE_TIME_WINDOW_DAYS + PAST_TIME_WINDOW_DAYS,
                                                       parameterName: nameof(this.EndTimestamp)));
            result.Combine(Validator.ValidateTimeRange(this.BeginTimestamp, this.EndTimestamp));

            return(result);
        }
示例#10
0
        /// <inheritdoc/>
        public RequestValidationResult Validate()
        {
            RequestValidationResult result = new RequestValidationResult();

            // Validate areas
            if (this.Areas.Count > 0)
            {
                // Validate individual areas
                foreach (Area area in this.Areas)
                {
                    // Use Area.Validate()
                    result.Combine(area.Validate());
                }
            }
            else
            {
                result.Fail(
                    RequestValidationIssue.InputEmpty,
                    nameof(this.Areas),
                    ValidationMessages.EmptyAreas
                    );
            }

            // Validate message
            if (String.IsNullOrEmpty(this.UserMessage))
            {
                result.Fail(
                    RequestValidationIssue.InputEmpty,
                    nameof(this.UserMessage),
                    ValidationMessages.EmptyMessage
                    );
            }

            return(result);
        }
        /// <inheritdoc/>
        public async Task <IEnumerable <InfectionReport> > GetByIdsAsync(IEnumerable <string> ids, CancellationToken cancellationToken = default)
        {
            if (ids == null || ids.Count() == 0)
            {
                throw new ArgumentNullException(nameof(ids));
            }

            // Confirm IDs are valid
            RequestValidationResult result = new RequestValidationResult();

            foreach (string messageId in ids)
            {
                result.Combine(Validator.ValidateGuid(messageId, nameof(messageId)));
            }

            // Verify results were validated
            if (result.Passed)
            {
                return(await this._reportRepo.GetRangeAsync(ids, cancellationToken));
            }
            else
            {
                throw new RequestValidationFailedException(result);
            }
        }
        /// <inheritdoc/>
        public async Task PublishAreaAsync(AreaReport areaReport, CancellationToken cancellationToken = default)
        {
            // Validate inputs
            if (areaReport == null)
            {
                throw new ArgumentNullException(nameof(areaReport));
            }

            RequestValidationResult validationResult = areaReport.Validate();

            if (validationResult.Passed)
            {
                // Build an InfectionReport containing the submitted areas
                InfectionReport message = new InfectionReport();
                message.AreaReports.Add(areaReport);

                // Define a regions for the published message
                IEnumerable <Region> messageRegions = RegionHelper.GetRegionsCoverage(areaReport.Areas, this.RegionPrecision);

                // Publish
                await this._reportRepo.InsertAsync(message, messageRegions, cancellationToken);
            }
            else
            {
                throw new RequestValidationFailedException(validationResult);
            }
        }
示例#13
0
        /// <inheritdoc/>
        public RequestValidationResult Validate()
        {
            RequestValidationResult result = new RequestValidationResult();

            // Ensure lat/lng are within range
            result.Combine(Validator.ValidateLatitude(this.Latitude, nameof(this.Latitude)));
            result.Combine(Validator.ValidateLongitude(this.Longitude, nameof(this.Longitude)));

            return(result);
        }
        public void ShouldReturnsErrorWhenCreationIsFail()
        {
            RequestValidationResult <UserSignUpRequest, Error> result = UserSignUpRequest.Create(
                email: "*****@*****.**",
                password: string.Empty
                );

            Assert.IsFalse(result.IsValid);
            Assert.AreEqual(result.Errors.First().FieldId, "Password");
            Assert.AreEqual(result.Errors.First().Error, Error.Required);
        }
示例#15
0
        public void ShouldCreateValidRequestResult()
        {
            var requestForTest = new RequestForTest(value: "test");

            var result = RequestValidationResult <RequestForTest, Error> .CreateValidResult(
                result : requestForTest
                );

            Assert.IsTrue(result.IsValid);
            Assert.AreEqual(result.Result.Value, requestForTest.Value);
            Assert.AreEqual(result.Errors.Count, 0);
        }
示例#16
0
        /// <inheritdoc/>
        public RequestValidationResult Validate()
        {
            RequestValidationResult result = new RequestValidationResult();

            // MessageId validation
            result.Combine(Validator.ValidateGuid(this.MessageId, nameof(this.MessageId)));

            // Timestamp validation
            result.Combine(Validator.ValidateTimestamp(this.MessageTimestamp, nameof(this.MessageTimestamp)));

            return(result);
        }
示例#17
0
        public void ValidateTimestamp_AcceptsValidInput()
        {
            // Arrange
            long timestamp1 = 0;
            long timestamp2 = Int64.MaxValue;

            // Act
            RequestValidationResult result1 = Validator.ValidateTimestamp(timestamp1);
            RequestValidationResult result2 = Validator.ValidateTimestamp(timestamp2);

            // Assert
            Assert.IsTrue(result1.Passed);
            Assert.IsTrue(result2.Passed);
        }
示例#18
0
        /// <inheritdoc/>
        public RequestValidationResult Validate()
        {
            RequestValidationResult result = new RequestValidationResult();

            // Seed validation
            result.Combine(Validator.ValidateSeed(this.Seed, nameof(this.Seed)));

            // Ensure times are valid
            result.Combine(Validator.ValidateTimestamp(this.SequenceStartTime, nameof(this.SequenceStartTime)));
            result.Combine(Validator.ValidateTimestamp(this.SequenceEndTime, nameof(this.SequenceEndTime)));
            result.Combine(Validator.ValidateTimeRange(this.SequenceStartTime, this.SequenceEndTime));

            return(result);
        }
        /// <inheritdoc/>
        public RequestValidationResult Validate()
        {
            RequestValidationResult result = new RequestValidationResult();

            // Seed validation
            result.Combine(Validator.ValidateSeed(this.Seed, nameof(this.Seed)));

            // Ensure times are valid
            result.Combine(Validator.ValidateTimestamp(this.BeginTimestamp, parameterName: nameof(this.BeginTimestamp)));
            result.Combine(Validator.ValidateTimestamp(this.EndTimestamp, parameterName: nameof(this.EndTimestamp)));
            result.Combine(Validator.ValidateTimeRange(this.BeginTimestamp, this.EndTimestamp));

            return(result);
        }
示例#20
0
        public void ValidateTimestamp_FailsOnNegativeTimestamp()
        {
            // Arrange
            long timestamp1 = -1;
            long timestamp2 = Int64.MinValue;

            // Act
            RequestValidationResult result1 = Validator.ValidateTimestamp(timestamp1);
            RequestValidationResult result2 = Validator.ValidateTimestamp(timestamp2);

            // Assert
            Assert.IsFalse(result1.Passed);
            Assert.IsFalse(result2.Passed);
        }
        public void ShouldCreatesValidSignUpRequest()
        {
            var email    = "*****@*****.**";
            var password = "******";

            RequestValidationResult <UserSignUpRequest, Error> result = UserSignUpRequest.Create(
                email: email,
                password: password
                );

            Assert.IsTrue(result.IsValid);
            Assert.AreEqual(result.Result.Email.Value, email);
            Assert.AreEqual(result.Result.Password.Value, password);
        }
示例#22
0
        public void ValidateLatitude_FailsOnInvalidInputs()
        {
            // Arrange
            long input1 = 91;  // Too high
            long input2 = -91; // Too low

            // Act
            RequestValidationResult result1 = Validator.ValidateLatitude(input1);
            RequestValidationResult result2 = Validator.ValidateLatitude(input2);

            // Assert
            Assert.IsFalse(result1.Passed);
            Assert.IsFalse(result2.Passed);
        }
示例#23
0
        public void ValidateTimestamp_AcceptsValidInput()
        {
            // Arrange
            long timestamp1 = DateTimeOffset.UtcNow.AddDays(-(Validator.MAX_TIMESTAMP_AGE_DAYS - 1)).ToUnixTimeMilliseconds();
            long timestamp2 = DateTimeOffset.UtcNow.AddDays(1).AddHours(-1).ToUnixTimeMilliseconds();

            // Act
            RequestValidationResult result1 = Validator.ValidateTimestamp(timestamp1);
            RequestValidationResult result2 = Validator.ValidateTimestamp(timestamp2);

            // Assert
            Assert.IsTrue(result1.Passed);
            Assert.IsTrue(result2.Passed);
        }
示例#24
0
        public void ValidateGuid_AcceptsValidInput()
        {
            // Arrange
            string input1 = "00000000-0000-0000-0000-000000000001";
            string input2 = "00000000000000000000000000000001";

            // Act
            RequestValidationResult result1 = Validator.ValidateGuid(input1);
            RequestValidationResult result2 = Validator.ValidateGuid(input2);

            // Assert
            Assert.IsTrue(result1.Passed);
            Assert.IsTrue(result2.Passed);
        }
示例#25
0
        /// <inheritdoc/>
        public RequestValidationResult Validate()
        {
            RequestValidationResult result = new RequestValidationResult();

            // Only validate if collection contains message information
            if (this.RequestedQueries.Count > 0)
            {
                foreach (MessageInfo info in this.RequestedQueries)
                {
                    // Use Validate() method in MessageInfo
                    result.Combine(info.Validate());
                }
            }

            return(result);
        }
示例#26
0
        /// <inheritdoc/>
        public RequestValidationResult Validate()
        {
            RequestValidationResult result = new RequestValidationResult();

            // Only validate if collection contains seeds
            if (this.Seeds.Count > 0)
            {
                foreach (BlueToothSeed seed in this.Seeds)
                {
                    // Use Validate() from BlueToothSeed
                    result.Combine(seed.Validate());
                }
            }

            return(result);
        }
示例#27
0
        public void ShouldCreateInvalidRequestResult()
        {
            var errors = new List <ValidationError <ErrorForTest> >
            {
                new ValidationError <ErrorForTest>(fieldId: "FieldId", error: ErrorForTest.AnyError)
            }.AsReadOnly();

            var result = RequestValidationResult <RequestForTest, ErrorForTest> .CreateInvalidResult(
                errors : errors
                );

            Assert.IsFalse(result.IsValid);
            Assert.AreEqual(result.Errors[0].FieldId, errors[0].FieldId);
            Assert.AreEqual(result.Errors[0].Error, errors[0].Error);
            Assert.AreEqual(result.Errors.Count, 1);
        }
        public async Task VerifyComponentsHookUpCorrectly()
        {
            IServiceCollection services = new ServiceCollection();

            services.AddTransient <IRequestProcessor, RequestProcessor>();

            var serviceProvider = services.BuildServiceProvider();

            string logKey = "TestLog";
            // Request processing
            ProcessRequestDelegate <string> process =
                async(request, contextBag, cancellationToken) =>
            {
                var log = contextBag[logKey] as StringBuilder;
                log.Append("Processed");
                return(string.Empty);
            };

            ValidateRequestDelegate validator = async(request, contextBag, cancellationToken) =>
            {
                var log = contextBag[logKey] as StringBuilder;
                log.Append("Validated>>");
                return(RequestValidationResult.Instance());
            };

            AuthorizeRequestDelegate authorizer = async(request, contextBag, cancellationToken) =>
            {
                var log = contextBag[logKey] as StringBuilder;
                log.Append("Authorized>>");
                return(new RequestAuthorizationResult());
            };

            var contextBag = ApFrameworkHelper.GetEmptyBag();

            contextBag[logKey] = new StringBuilder();

            var expected = "Authorized>>Validated>>Processed";

            var request   = new Request <string>(process, validator, authorizer);
            var processor = serviceProvider.GetService <IRequestProcessor>();

            await processor.ProcessRequestAsync(request, contextBag);

            var log = contextBag[logKey] as StringBuilder;

            Assert.True(log.ToString() == expected);
        }
示例#29
0
        public void ValidateLatitude_AcceptsValidInput()
        {
            // Arrange
            long input1 = 0;
            long input2 = 90;
            long input3 = -90;

            // Act
            RequestValidationResult result1 = Validator.ValidateLatitude(input1);
            RequestValidationResult result2 = Validator.ValidateLatitude(input2);
            RequestValidationResult result3 = Validator.ValidateLatitude(input3);

            // Assert
            Assert.IsTrue(result1.Passed);
            Assert.IsTrue(result2.Passed);
            Assert.IsTrue(result3.Passed);
        }
示例#30
0
        public void ValidateGuid_FailsOnInvalidInputs()
        {
            // Arrange
            string input1 = "00000000-0000-0000-0000-00000000000"; // Too short
            string input2 = "0000000000000000000000000000000";     // Too short
            string input3 = "Not a guid!";                         // Invalid format

            // Act
            RequestValidationResult result1 = Validator.ValidateGuid(input1);
            RequestValidationResult result2 = Validator.ValidateGuid(input2);
            RequestValidationResult result3 = Validator.ValidateGuid(input3);

            // Assert
            Assert.IsFalse(result1.Passed);
            Assert.IsFalse(result2.Passed);
            Assert.IsFalse(result3.Passed);
        }