Esempio n. 1
0
        public async Task ServiceValidationAttribute_ServiceAvailable_ComplexityRequirementsNotMet()
        {
            var services = new ServiceCollection();

            services.Configure <PasswordOptions>(options =>
            {
                options.RequiredLength         = 6;
                options.RequireDigit           = true;
                options.RequireNonAlphanumeric = true;
                options.RequireLowercase       = true;
                options.RequiredUniqueChars    = 2;
            });

            services.AddSingleton <IStringLocalizerFactory>(NullStringLocalizerFactory.Instance);
            services.AddTransient(typeof(IStringLocalizer <>), typeof(StringLocalizer <>));
            services.AddSingleton <IValidator <PasswordAttribute>, PasswordValidator>();

            var command = new ChangePasswordCommand
            {
                UserName    = "******",
                NewPassword = "******",
            };

            await using var sp = services.BuildServiceProvider();

            var validationEx = Assert.Throws <ValidationException>(() => DataAnnotationsValidator.Validate(command, sp));

            Assert.IsType <ExtendedValidationResult>(validationEx.ValidationResult);
            Assert.IsType <PasswordAttribute>(validationEx.ValidationAttribute);
            Assert.Equal(new[] { nameof(command.NewPassword) }, validationEx.ValidationResult.MemberNames);
        }
Esempio n. 2
0
        public void ObjectWithTwoInvalidAndOneValidEntryCollectionsUsesIndexPositionInResult()
        {
            var dav     = new DataAnnotationsValidator(new DottedNumberCollectionPropertyNamingStrategy());
            var request = new TestPerson
            {
                Name         = "Test Person",
                PhoneNumbers = new[]
                {
                    new TestPhone {
                        Category = "home", Number = ""
                    },
                    new TestPhone {
                        Category = "mobile", Number = "5130000000"
                    },
                    new TestPhone {
                        Category = "work", Number = ""
                    },
                }
            };
            List <ValidationResult> results = new List <ValidationResult>();
            var isValid = dav.TryValidateObjectRecursive(request, results, new ValidationContext(request));

            Assert.IsFalse(isValid);
            Assert.AreEqual(2, results.Count);
            Assert.AreEqual("PhoneNumbers.0.Number", results[0].MemberNames.ToArray()[0]);
            Assert.AreEqual("PhoneNumbers.2.Number", results[1].MemberNames.ToArray()[0]);
        }
Esempio n. 3
0
        public async Task ServiceValidationAttribute_ServiceAvailable_ComplexityRequirementsMet()
        {
            var services = new ServiceCollection();

            services.Configure <PasswordOptions>(options =>
            {
                options.RequiredLength         = 6;
                options.RequireDigit           = true;
                options.RequireNonAlphanumeric = true;
                options.RequireLowercase       = true;
                options.RequiredUniqueChars    = 2;
            });

            services.AddSingleton <IValidator <PasswordAttribute>, PasswordValidator>();

            var command = new ChangePasswordCommand
            {
                UserName    = "******",
                NewPassword = "******",
            };

            await using var sp = services.BuildServiceProvider();

            DataAnnotationsValidator.Validate(command);
        }
        public DataAnnotationsValidatorFixture()
        {
            this.propertyValidator1 =
                A.Fake<IPropertyValidator>();

            this.propertyValidator2 =
                A.Fake<IPropertyValidator>();

            this.validatableObjectAdapter =
                A.Fake<IValidatableObjectAdapter>();

            this.validatorFactory =
                A.Fake<IPropertyValidatorFactory>();

            A.CallTo(() => this.validatorFactory.GetValidators(typeof(ModelUnderTest)))
               .Returns(new[] { this.propertyValidator1, this.propertyValidator2 });

            this.validator =
                new DataAnnotationsValidator(typeof(ModelUnderTest), this.validatorFactory, this.validatableObjectAdapter);

            var adapterFactory = new DefaultPropertyValidatorFactory(new IDataAnnotationsValidatorAdapter[]
            {
                new RangeValidatorAdapter(),
                new RegexValidatorAdapter(),
                new RequiredValidatorAdapter(),
                new StringLengthValidatorAdapter(),
                new OopsAdapter()
            });

            var adapter = A.Fake<IValidatableObjectAdapter>();

            this.factory = new DataAnnotationsValidatorFactory(adapterFactory, adapter);
        }
Esempio n. 5
0
        public void ReturnTrueGivenNameEnAndLessThan10()
        {
            _todo.Name = "Teera Nai";
            var result = DataAnnotationsValidator.TryValidate(_todo);

            Assert.True(result, "Name should be English and less than 10");
        }
Esempio n. 6
0
        public override void Validate()
        {
            base.Validate();
            // Validation rules might be placed in here...
            // throw new NotImplementedException();
            var validator = new DataAnnotationsValidator();

            validator.TryValidate(this, out var results);
            if (results.Any())
            {
                throw new ServiceException(HttpStatusCode.BadRequest, new ContractExecutionResult(ContractExecutionStatesEnum.ValidationError, results.FirstOrDefault().ErrorMessage));
            }

            if (ExcludedSurveyedSurfaceIds != null && ExcludedSurveyedSurfaceIds.Length > 0)
            {
                foreach (var id in ExcludedSurveyedSurfaceIds)
                {
                    if (id == 0)
                    {
                        throw new ServiceException(HttpStatusCode.BadRequest,
                                                   new ContractExecutionResult(ContractExecutionStatesEnum.ValidationError,
                                                                               string.Format(
                                                                                   "Excluded Surface Id is invalid")));
                    }
                }
            }
        }
Esempio n. 7
0
        public void CanCreateCMVRequestTest()
        {
            //******************* isCustomCMVTargets = false **************************
            var        validator = new DataAnnotationsValidator();
            CMVRequest request   = new CMVRequest(projectId, null, callId, cmvSettings, liftSettings, null, 0, null, null, null);
            ICollection <ValidationResult> results;

            Assert.IsTrue(validator.TryValidate(request, out results));

            //missing project id
            request = new CMVRequest(-1, null, callId, cmvSettings, liftSettings, null, 0, null, null, null);
            Assert.IsFalse(validator.TryValidate(request, out results));

            //missing CMV settings
            request = new CMVRequest(projectId, null, callId, null, liftSettings, null, 0, null, null, null);
            Assert.IsFalse(validator.TryValidate(request, out results));

            //******************* isCustomCMVTargets = true ***************************
            request = new CMVRequest(projectId, null, callId, cmvSettingsEx, liftSettings, null, 0, null, null, null, true);
            Assert.IsTrue(validator.TryValidate(request, out results));

            //missing project id
            request = new CMVRequest(-1, null, callId, cmvSettingsEx, liftSettings, null, 0, null, null, null, true);
            Assert.IsFalse(validator.TryValidate(request, out results));

            //missing CMV settings
            request = new CMVRequest(projectId, null, callId, null, liftSettings, null, 0, null, null, null, true);
            Assert.IsFalse(validator.TryValidate(request, out results));
        }
Esempio n. 8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TcpServer"/> class.
        /// </summary>
        /// <param name="options">The options to intialize the instance with.</param>
        /// <param name="loggerFactory">A reference to the factory of loggers to use.</param>
        /// <param name="handlerSelector">A refrence to the selector of handlers for TCP messages.</param>
        /// <param name="clientsManager">A reference to a manager for clients.</param>
        /// <param name="listeners">A reference to the listeners to bind to the server.</param>
        /// <param name="gameworldAdapter">A reference to an adapter that will act as a client to the game world.</param>
        public TcpServer(
            IOptions <TcpServerOptions> options,
            ILoggerFactory loggerFactory,
            IHandlerSelector handlerSelector,
            IClientsManager clientsManager,
            IEnumerable <IListener> listeners,
            ITcpServerToGameworldAdapter gameworldAdapter)
        {
            options.ThrowIfNull(nameof(options));
            loggerFactory.ThrowIfNull(nameof(loggerFactory));
            handlerSelector.ThrowIfNull(nameof(handlerSelector));
            listeners.ThrowIfNull(nameof(listeners));
            gameworldAdapter.ThrowIfNull(nameof(gameworldAdapter));

            if (!listeners.Any())
            {
                throw new ArgumentException("No listeners found after composition.", nameof(listeners));
            }

            DataAnnotationsValidator.ValidateObjectRecursive(options.Value);

            this.id     = Guid.NewGuid().ToString();
            this.logger = loggerFactory.CreateLogger <TcpServer>();
            this.gameworldClientAdapter = gameworldAdapter;
            this.connectionToClientMap  = new Dictionary <IConnection, IClient>();
            this.clientsManager         = clientsManager;

            this.Options = options.Value;

            this.BindListeners(loggerFactory, handlerSelector, listeners);
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            var model = new CustomModel();

            model.Text   = "abcdefghijklmnopqrstuvwxyz";
            model.Text2  = "1";
            model.Number = -5;


            var validator = new DataAnnotationsValidator();

            var results = new List <ValidationResult>();

            //var context = new ValidationContext(model, serviceProvider: null, items: null);
            //var isValid = Validator.TryValidateObject(model, context, results, true);

            var isValid = validator.TryValidate(model, out results);

            var errors = model.Validate(null);

            if (!isValid)
            {
                foreach (var r in results)
                {
                    Console.WriteLine($"member: {r.MemberNames.ToList()[0]} error: {r.ErrorMessage}");
                }
            }

            Console.ReadKey();
        }
Esempio n. 10
0
        public void CanCreateFileDescriptorTest()
        {
            string bigString = new string('A', 10000);

            var            validator = new DataAnnotationsValidator();
            FileDescriptor file      = FileDescriptor.CreateFileDescriptor("u72003136-d859-4be8-86de-c559c841bf10",
                                                                           "BC Data/Sites/Integration10/Designs", "Cycleway.ttm");
            ICollection <ValidationResult> results;

            Assert.IsTrue(validator.TryValidate(file, out results));

            //Note: file name is string.Empty due to the ValidFilename attribute otherwise get a null reference exception
            file = FileDescriptor.CreateFileDescriptor(null, null, string.Empty);
            Assert.IsFalse(validator.TryValidate(file, out results), "empty file descriptor failed");

            //too big path
            file = FileDescriptor.CreateFileDescriptor("u72003136-d859-4be8-86de-c559c841bf10",
                                                       bigString, "Cycleway.ttm");
            Assert.IsFalse(validator.TryValidate(file, out results), " too big path failed");

            //too big file name
            file = FileDescriptor.CreateFileDescriptor("u72003136-d859-4be8-86de-c559c841bf10",
                                                       "BC Data/Sites/Integration10/Designs", bigString);
            Assert.IsFalse(validator.TryValidate(file, out results), "too big file name failed");
        }
Esempio n. 11
0
        public void Validate_DetectionTemplates_HasValidTemplateStructure(string detectionsYamlFileName)
        {
            var yaml = GetYamlFileAsString(detectionsYamlFileName);

            //we ignore known issues (in progress)
            foreach (var templateToSkip in TemplatesSchemaValidationsReader.WhiteListStructureTestsTemplateIds)
            {
                if (yaml.Contains(templateToSkip))
                {
                    return;
                }
            }

            var exception = Record.Exception(() =>
            {
                var templateObject    = JsonConvert.DeserializeObject <AnalyticsTemplateInternalModelBase>(ConvertYamlToJson(yaml));
                var validationResults = DataAnnotationsValidator.ValidateObjectRecursive(templateObject);
                DataAnnotationsValidator.ThrowExceptionIfResultsInvalid(validationResults);
            });
            string exceptionToDisplay = string.Empty;

            if (exception != null)
            {
                exceptionToDisplay = $"In template {detectionsYamlFileName} there was an error while parsing: {exception.Message}";
            }
            exception.Should().BeNull(exceptionToDisplay);
        }
    public void ValidatesCollections()
    {
        var model = new TestObjectWithList()
        {
            Test = new List <TestItem>()
            {
                new TestItem(),
                new TestItem()
                {
                    Test = "valid"
                },
                new TestItem()
            }
        };

        var result = DataAnnotationsValidator.Validate(model);

        Assert.False(result.IsValid);
        Assert.Collection(result.Errors,
                          e =>
        {
            Assert.Equal("Test[0].Test", e.Key);
            Assert.Collection(e.Value, er => Assert.Equal("The Test field is required.", er));
        },
                          e =>
        {
            Assert.Equal("Test[2].Test", e.Key);
            Assert.Collection(e.Value, er => Assert.Equal("The Test field is required.", er));
        });
    }
Esempio n. 13
0
        public void CoordinateSystemFileValidationRequestTest()
        {
            var    validator = new DataAnnotationsValidator();
            string fileName  = "test.dc";

            byte[] fileContent = { 0, 1, 2, 3, 4, 5, 6, 7 };

            // Test the CreateCoordinateSystemFileValidationRequest() method with valid parameters...
            CoordinateSystemFileValidationRequest coordSystemFileValidation = new CoordinateSystemFileValidationRequest(fileContent, "test.dc");

            Assert.IsTrue(validator.TryValidate(coordSystemFileValidation, out ICollection <ValidationResult> results));

            // Test the CreateCoordinateSystemFileValidationRequest() method with a file name length exceeds 256 characters...
            string prefix = "overlimit";

            //int maxCount = (int)(CoordinateSystemFile.MAX_FILE_NAME_LENGTH / prefix.Length);

            for (int i = 1; prefix.Length <= CoordinateSystemFileValidationRequest.MAX_FILE_NAME_LENGTH; i++)
            {
                prefix += prefix;
            }

            coordSystemFileValidation = new CoordinateSystemFileValidationRequest(fileContent, prefix + fileName);
            Assert.IsFalse(validator.TryValidate(coordSystemFileValidation, out results));

            // Test the CreateCoordinateSystemFileValidationRequest() method with no file name provided...
            coordSystemFileValidation = new CoordinateSystemFileValidationRequest(fileContent, string.Empty);
            Assert.IsFalse(validator.TryValidate(coordSystemFileValidation, out results));

            // Test the CreateCoordinateSystemFileValidationRequest() method with no content provided...
            coordSystemFileValidation = new CoordinateSystemFileValidationRequest(null, fileName);
            Assert.IsFalse(validator.TryValidate(coordSystemFileValidation, out results));
        }
        public ActionConfirmation <SupportTicket> Open(SupportTicketFormDto supportTicketFormDto)
        {
            if (supportTicketFormDto == null)
            {
                throw new ArgumentNullException("supportTicketFormDto is null");
            }
            if (!DataAnnotationsValidator.TryValidate(supportTicketFormDto))
            {
                throw new InvalidOperationException("supportTicketFormDto is in an invalid state");
            }

            var supportTicketToSave = supportTicketFormDto.Id > 0
                ? _supportTicketRepository.Get(supportTicketFormDto.Id)
                : CreateNewSupportTicket(supportTicketFormDto);

            TransferFormValuesTo(supportTicketToSave, supportTicketFormDto);

            var customerConfirmationMessage = HandleNewCustomer(supportTicketFormDto.NewCustomer, supportTicketToSave);
            var issueConfirmationMessage    = HandleNewIssueType(supportTicketFormDto.NewIssueType, supportTicketToSave);

            _supportTicketRepository.SaveOrUpdate(supportTicketToSave);

            return(ActionConfirmation <SupportTicket>
                   .CreateSuccessConfirmation("Support ticket #" + supportTicketToSave.Id + " has been opened." +
                                              customerConfirmationMessage + issueConfirmationMessage, supportTicketToSave));
        }
Esempio n. 15
0
        public void CanCreatePatchRequestTest()
        {
            var          validator = new DataAnnotationsValidator();
            PatchRequest request   = new PatchRequest(
                projectId, null, callId, DisplayMode.Height, null, liftSettings, false, VolumesType.None, 0.0, null, null, null,
                FilterLayerMethod.None, 5, 50);
            ICollection <ValidationResult> results;

            Assert.IsTrue(validator.TryValidate(request, out results));

            //missing project id
            request = new PatchRequest(
                -1, null, callId, DisplayMode.Height, palettes, liftSettings, false, VolumesType.None, 0.0, null, null, null,
                FilterLayerMethod.None, 5, 50);
            Assert.IsFalse(validator.TryValidate(request, out results));

            //vol no change tolerance out of range
            request = new PatchRequest(
                projectId, null, callId, DisplayMode.Height, null, liftSettings, false, VolumesType.None, 10.1, null, null, null,
                FilterLayerMethod.None, 5, 50);
            Assert.IsFalse(validator.TryValidate(request, out results));

            //patch number out of range
            request = new PatchRequest(
                projectId, null, callId, DisplayMode.Height, null, liftSettings, false, VolumesType.None, 0.0, null, null, null,
                FilterLayerMethod.None, -1, 50);
            Assert.IsFalse(validator.TryValidate(request, out results));

            //patch size out of range
            request = new PatchRequest(
                projectId, null, callId, DisplayMode.Height, null, liftSettings, false, VolumesType.None, 0.0, null, null, null,
                FilterLayerMethod.None, 5, 9999);
            Assert.IsFalse(validator.TryValidate(request, out results));
        }
Esempio n. 16
0
        public void CanCreatePassCountSettingsTest()
        {
            var validator = new DataAnnotationsValidator();
            PassCountSettings settings = PassCountSettings.CreatePassCountSettings(new[] { 1, 3, 5, 10 });

            Assert.IsTrue(validator.TryValidate(settings, out ICollection <ValidationResult> results));
        }
Esempio n. 17
0
        public void CanValidateModelTest()
        {
            // Arrange
            var taxonomyBranch           = TestFramework.TestTaxonomyBranch.Create();
            var viewModel                = new EditViewModel(taxonomyBranch);
            var nameOfTaxonomyBranchName = GeneralUtility.NameOf(() => viewModel.TaxonomyBranchName);

            ICollection <ValidationResult> validationResults;

            // Act
            DataAnnotationsValidator.TryValidate(viewModel, out validationResults);

            // Assert
            Assert.That(validationResults.Count, Is.EqualTo(1), "Expecting certain number of errors");
            TestFramework.AssertFieldRequired(validationResults, nameOfTaxonomyBranchName);

            // Act
            // Set string fields to string longer than their max lengths
            viewModel.TaxonomyBranchName = TestFramework.MakeTestNameLongerThan(nameOfTaxonomyBranchName, ProjectFirmaModels.Models.TaxonomyBranch.FieldLengths.TaxonomyBranchName);
            DataAnnotationsValidator.TryValidate(viewModel, out validationResults);

            // Assert
            Assert.That(validationResults.Count, Is.EqualTo(1), "Expecting certain number of errors");
            TestFramework.AssertFieldStringLength(validationResults, nameOfTaxonomyBranchName, ProjectFirmaModels.Models.TaxonomyBranch.FieldLengths.TaxonomyBranchName);

            // Act
            // Happy path
            viewModel.TaxonomyBranchName = TestFramework.MakeTestName(nameOfTaxonomyBranchName, ProjectFirmaModels.Models.TaxonomyBranch.FieldLengths.TaxonomyBranchName);
            var isValid = DataAnnotationsValidator.TryValidate(viewModel, out validationResults);

            // Assert
            Assert.That(isValid, Is.True, "Should pass validation");
        }
Esempio n. 18
0
        /// <summary>
        /// Validates all properties
        /// </summary>
        public void Validate(IServiceExceptionHandler serviceExceptionHandler)
        {
            var validator = new DataAnnotationsValidator();

            validator.TryValidate(this, out ICollection <ValidationResult> results);
            if (results.Any())
            {
                throw new ServiceException(HttpStatusCode.BadRequest, new ContractExecutionResult(ContractExecutionStatesEnum.ValidationError, results.FirstOrDefault().ErrorMessage));
            }

            ValidateRange(useMachineTargetPassCount, customTargetPassCountMinimum, customTargetPassCountMaximum, "pass count");
            ValidateRange(useMachineTargetTemperature, customTargetTemperatureMinimum, customTargetTemperatureMaximum, "temperature");
            ValidateRange(useDefaultTargetRangeCmvPercent, customTargetCmvPercentMinimum, customTargetCmvPercentMaximum, "CMV %");
            ValidateRange(useDefaultTargetRangeMdpPercent, customTargetMdpPercentMinimum, customTargetMdpPercentMaximum, "MDP %");
            ValidateRange(useDefaultTargetRangeSpeed, customTargetSpeedMinimum, customTargetSpeedMaximum, "Speed");

            ValidateValue(useMachineTargetCmv, customTargetCmv, "CMV");
            ValidateValue(useMachineTargetMdp, customTargetMdp, "MDP");
            ValidateValue(useDefaultVolumeShrinkageBulking, customBulkingPercent, "bulking %");
            ValidateValue(useDefaultVolumeShrinkageBulking, customShrinkagePercent, "shrinkage %");

            ValidateCutFill();
            ValidatePassCounts();
            ValidateCMVs();
            ValidateTemperatures();
        }
Esempio n. 19
0
        public void CanEnlistChildOjects_InResultSet_ToBeValidated()
        {
            var testObj = new ParentValidateType
            {
                PropWithAttribValidation = 50,
                EnlistChildObjectOne     = new ChildValidateType
                {
                    AddPredicateValidation   = true,
                    PropWithAttribValidation = 1013
                }
            };

            var validator = new DataAnnotationsValidator(testObj);
            var resultSet = validator.Validate();

            Assert.True(resultSet.IsInvalid);

            Assert.True(testObj.EnlistChildObjectOne.WasValidationMethodInvoked);

            var allValidations = resultSet.ObjectValidations
                                 .SelectMany(ov => ov.Validations)
                                 .ToArray();

            Assert.Single(allValidations);

            var valItem = allValidations.First();

            Assert.Equal("Value can't be 1013.", valItem.Message);
        }
Esempio n. 20
0
        public void ReturnFalseGivenNameEmpty()
        {
            _todo.Name = "";
            var result = DataAnnotationsValidator.TryValidate(_todo);

            Assert.False(result, "Name should not be empty");
        }
Esempio n. 21
0
        public DataAnnotationsValidatorFixture()
        {
            this.propertyValidator1 =
                A.Fake <IPropertyValidator>();

            this.propertyValidator2 =
                A.Fake <IPropertyValidator>();

            this.validatableObjectAdapter =
                A.Fake <IValidatableObjectAdapter>();

            this.validatorFactory =
                A.Fake <IPropertyValidatorFactory>();

            A.CallTo(() => this.validatorFactory.GetValidators(typeof(ModelUnderTest)))
            .Returns(new[] { this.propertyValidator1, this.propertyValidator2 });

            this.validator =
                new DataAnnotationsValidator(typeof(ModelUnderTest), this.validatorFactory, this.validatableObjectAdapter);

            var adapterFactory = new DefaultPropertyValidatorFactory(new IDataAnnotationsValidatorAdapter[]
            {
                new RangeValidatorAdapter(),
                new RegexValidatorAdapter(),
                new RequiredValidatorAdapter(),
                new StringLengthValidatorAdapter(),
                new OopsAdapter()
            });

            var adapter = A.Fake <IValidatableObjectAdapter>();

            this.factory = new DataAnnotationsValidatorFactory(adapterFactory, adapter);
        }
Esempio n. 22
0
        public void ValidationSet_OnlyErrors_ConsideredInvalid()
        {
            var testObj = new ParentValidateType
            {
                PropWithAttribValidation = 50,
                EnlistChildObjectOne     = new ChildValidateType
                {
                    AddPredicateValidation   = true,
                    PropWithAttribValidation = 1013,
                    PredicateValidationType  = ValidationTypes.Info
                },
                EnlistChildObjectTwo = new ChildValidateType
                {
                    AddPredicateValidation   = true,
                    PropWithAttribValidation = 1013,
                    PredicateValidationType  = ValidationTypes.Warning
                }
            };

            var validator = new DataAnnotationsValidator(testObj);
            var resultSet = validator.Validate();

            Assert.True(resultSet.IsValid);
            Assert.False(resultSet.IsInvalid);
        }
Esempio n. 23
0
        public void ReturnFalseGivenNameLengthMoreThan10()
        {
            _todo.Name = ".Net Core Unit Test";
            var result = DataAnnotationsValidator.TryValidate(_todo);

            Assert.False(result, "Name should not be more than 10");
        }
Esempio n. 24
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SectorMapLoader"/> class.
        /// </summary>
        /// <param name="logger">A reference to the logger instance in use.</param>
        /// <param name="itemFactory">A reference to the item factory.</param>
        /// <param name="tileFactory">A reference to the tile factory.</param>
        /// <param name="sectorMapLoaderOptions">The options for this map loader.</param>
        public SectorMapLoader(
            ILogger <SectorMapLoader> logger,
            IItemFactory itemFactory,
            ITileFactory tileFactory,
            IOptions <SectorMapLoaderOptions> sectorMapLoaderOptions)
        {
            logger.ThrowIfNull(nameof(logger));
            itemFactory.ThrowIfNull(nameof(itemFactory));
            tileFactory.ThrowIfNull(nameof(tileFactory));
            sectorMapLoaderOptions.ThrowIfNull(nameof(sectorMapLoaderOptions));

            DataAnnotationsValidator.ValidateObjectRecursive(sectorMapLoaderOptions.Value);

            this.mapDirInfo = new DirectoryInfo(sectorMapLoaderOptions.Value.LiveMapDirectory);

            if (!this.mapDirInfo.Exists)
            {
                throw new ApplicationException($"The map directory '{sectorMapLoaderOptions.Value.LiveMapDirectory}' could not be found.");
            }

            this.logger      = logger;
            this.itemFactory = itemFactory;
            this.tileFactory = tileFactory;

            this.totalTileCount   = 1;
            this.totalLoadedCount = default;

            this.loadLock = new object();

            this.sectorsLengthX = 1 + SectorXMax - SectorXMin;
            this.sectorsLengthY = 1 + SectorYMax - SectorYMin;
            this.sectorsLengthZ = 1 + SectorZMax - SectorZMin;

            this.sectorsLoaded = new bool[this.sectorsLengthX, this.sectorsLengthY, this.sectorsLengthZ];
        }
Esempio n. 25
0
        public void CanCreateTileRequestTest()
        {
            var         validator = new DataAnnotationsValidator();
            TileRequest request   = new TileRequest(
                projectId, null, callId, DisplayMode.Height, null, liftSettings, VolumesType.None, 0.0, null, null, 0, null, 0,
                FilterLayerMethod.None, boundingBox2DLatLon, null, 256, 256);
            ICollection <ValidationResult> results;

            Assert.IsTrue(validator.TryValidate(request, out results));

            //missing project id
            request = new TileRequest(-1, null, callId, DisplayMode.Height, null, liftSettings, VolumesType.None, 0.0, null, null, 0, null, 0,
                                      FilterLayerMethod.None, boundingBox2DLatLon, null, 256, 256);
            Assert.IsFalse(validator.TryValidate(request, out results));

            //vol no change tolerance out of range
            request = new TileRequest(projectId, null, callId, DisplayMode.Height, null, liftSettings, VolumesType.None, 10.1, null, null, 0, null, 0,
                                      FilterLayerMethod.None, boundingBox2DLatLon, null, 256, 256);
            Assert.IsFalse(validator.TryValidate(request, out results));

            //width out of range
            request = new TileRequest(projectId, null, callId, DisplayMode.Height, null, liftSettings, VolumesType.None, 0.0, null, null, 0, null, 0,
                                      FilterLayerMethod.None, boundingBox2DLatLon, null, 16, 256);
            Assert.IsFalse(validator.TryValidate(request, out results));

            //height out of range
            request = new TileRequest(projectId, null, callId, DisplayMode.Height, null, liftSettings, VolumesType.None, 0.0, null, null, 0, null, 0,
                                      FilterLayerMethod.None, boundingBox2DLatLon, null, 256, 16000);
            Assert.IsFalse(validator.TryValidate(request, out results));
        }
Esempio n. 26
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ApplicationContext"/> class.
        /// </summary>
        /// <param name="options">A reference to the application configuration.</param>
        /// <param name="rsaDecryptor">A reference to the RSA decryptor in use.</param>
        /// <param name="itemTypeLoader">A reference to the item type loader in use.</param>
        /// <param name="monsterTypeLoader">A reference to the monster type loader in use.</param>
        /// <param name="telemetryClient">A reference to the telemetry client.</param>
        /// <param name="cancellationTokenSource">A reference to the master cancellation token source.</param>
        /// <param name="dbContextGenerationFunc">A reference to a function to generate the database context.</param>
        public ApplicationContext(
            IOptions <ApplicationContextOptions> options,
            IRsaDecryptor rsaDecryptor,
            IItemTypeLoader itemTypeLoader,
            IMonsterTypeLoader monsterTypeLoader,
            TelemetryClient telemetryClient,
            CancellationTokenSource cancellationTokenSource,
            Func <IFibulaDbContext> dbContextGenerationFunc)
        {
            options.ThrowIfNull(nameof(options));
            rsaDecryptor.ThrowIfNull(nameof(rsaDecryptor));
            itemTypeLoader.ThrowIfNull(nameof(itemTypeLoader));
            monsterTypeLoader.ThrowIfNull(nameof(monsterTypeLoader));
            cancellationTokenSource.ThrowIfNull(nameof(cancellationTokenSource));
            dbContextGenerationFunc.ThrowIfNull(nameof(dbContextGenerationFunc));

            DataAnnotationsValidator.ValidateObjectRecursive(options.Value);

            this.Options                 = options.Value;
            this.RsaDecryptor            = rsaDecryptor;
            this.CancellationTokenSource = cancellationTokenSource;

            this.TelemetryClient = telemetryClient;

            this.itemTypeLoader            = itemTypeLoader;
            this.monsterTypeLoader         = monsterTypeLoader;
            this.contextGenerationFunction = dbContextGenerationFunc;
        }
Esempio n. 27
0
        private static Contact GetDeliveryContactFromViewData(CheckoutViewData checkoutViewData, ModelStateDictionary modelState)
        {
            if (checkoutViewData.UseCardholderContact)
            {
                return(null);
            }

            var deliveryContact = new Contact
            {
                Address1  = checkoutViewData.DeliveryContactAddress1,
                Address2  = checkoutViewData.DeliveryContactAddress2,
                Address3  = checkoutViewData.DeliveryContactAddress3,
                Country   = checkoutViewData.DeliveryContactCountry,
                County    = checkoutViewData.DeliveryContactCounty,
                Firstname = checkoutViewData.DeliveryContactFirstName,
                Lastname  = checkoutViewData.DeliveryContactLastName,
                Town      = checkoutViewData.DeliveryContactTown,
                Telephone = checkoutViewData.DeliveryContactTelephone,
                Postcode  = checkoutViewData.DeliveryContactPostcode
            };

            DataAnnotationsValidator
            .Validate(deliveryContact)
            .WithPropertyPrefix("DeliveryContact")
            .AndUpdate(modelState);

            return(deliveryContact);
        }
Esempio n. 28
0
        public void ReturnFalseGivenNameNotEn()
        {
            _todo.Name = ".เนต คอ";
            var result = DataAnnotationsValidator.TryValidate(_todo);

            Assert.False(result, "Name should be English");
        }
Esempio n. 29
0
        public void ReturnFalseGivenNameWhitSpace()
        {
            _todo.Name = "    ";
            var result = DataAnnotationsValidator.TryValidate(_todo);

            Assert.False(result, "Name should not be whit space");
        }
Esempio n. 30
0
        public void ValidationSet_CanBeQueried_ForValidationsOfType()
        {
            var testObj = new ParentValidateType
            {
                PropWithAttribValidation = 50,
                EnlistChildObjectOne     = new ChildValidateType
                {
                    AddPredicateValidation   = true,
                    PropWithAttribValidation = 1013,
                    PredicateValidationType  = ValidationTypes.Info
                },
                EnlistChildObjectTwo = new ChildValidateType
                {
                    AddPredicateValidation   = true,
                    PropWithAttribValidation = 1013,
                    PredicateValidationType  = ValidationTypes.Warning
                }
            };

            var validator = new DataAnnotationsValidator(testObj);
            var resultSet = validator.Validate();

            Assert.Single(resultSet.GetValidationsOfType(ValidationTypes.Info));
            Assert.Single(resultSet.GetValidationsOfType(ValidationTypes.Warning));
        }
Esempio n. 31
0
        public void CanCreateColorPaletteTest()
        {
            var          validator = new DataAnnotationsValidator();
            ColorPalette palette   = new ColorPalette(0xA5BC4E, 0.2);
            ICollection <ValidationResult> results;

            Assert.IsTrue(validator.TryValidate(palette, out results));
        }
        public void should_return_false_and_have_collection()
        {
            var instance = new ValidationTestClass();
            var validator = new DataAnnotationsValidator();

            Assert.IsFalse(validator.TryValidate(instance));
            Assert.That(validator.ErrorCollection.Count > 0);
        }
        public void should_return_true_and_error_collection_should_be_null()
        {
            var instance = new ValidationTestClass
                           	{
                           		RequiredField = "Has Value"
                           	};
            var validator = new DataAnnotationsValidator();

            Assert.IsTrue(validator.TryValidate(instance));
            Assert.That(validator.ErrorCollection.Count == 0);
        }
        public void ValidateAge()
        {
            // Arrange
            var employee = new Employee()
                               {
                                   FirstName = "Fred",
                                   LastName = "Flintstone",
                                   Age = 0,
                               };

            // Act
            var results = new DataAnnotationsValidator<Employee>()
                .Validate(employee);

            // Assert
            results.AssertInvalidFor("Age", typeof(ValidationAttribute));
            var result = results.Single(r => r.PropertyName == "Age");
            Assert.That(result.Context, Is.SameAs(employee));
        }
        public DataAnnotationsValidatorFixture()
        {
            this.propertyValidator1 =
                A.Fake<IPropertyValidator>();

            this.propertyValidator2 =
                A.Fake<IPropertyValidator>();

            this.validatableObjectAdapter =
                A.Fake<IValidatableObjectAdapter>();

            this.validatorFactory =
                A.Fake<IPropertyValidatorFactory>();

            A.CallTo(() => this.validatorFactory.GetValidators(typeof(ModelUnderTest)))
               .Returns(new[] { this.propertyValidator1, this.propertyValidator2 });

            this.validator =
                new DataAnnotationsValidator(typeof(ModelUnderTest), this.validatorFactory, this.validatableObjectAdapter);
        }