public void ShouldNotThrowStackOverflowExceptionOnCircullarReference()
        {
            var objectToValidate = new ObjectWithCircularReference {Name = "object1"};
            objectToValidate.RelatedObject = objectToValidate;

            var validator = new ObjectValidator();

            var result = validator.Validate(new[] { objectToValidate }, null).ToArray();
        }
        public void ShouldValidateIEnumerable()
        {
            var objectToValidate = GetEnumerator();
            var validator = new ObjectValidator();

            var result = validator.Validate(new[] { objectToValidate }, null).ToArray();
            Assert.IsTrue(result.Any());
            Assert.AreEqual(2, result.Length);
        }
        public void ShouldValidateObjectWithIEnumerable()
        {
            var objectToValidate = new ObjectWithIEnumerable()
            {
                Collection = new InnerObject []{new InnerObject(), new InnerObject{Value1 = "element"}, new InnerObject(), }
            };
            var validator = new ObjectValidator();

            var result = validator.Validate(new[] {objectToValidate}, null).ToArray();
            Assert.IsTrue(result.Any());
            Assert.AreEqual(2, result.Length);
        }
        public void PropertyShouldNotAllowNullExpression()
        {
            // arrange
            var validator = new ObjectValidator<IComponent>();
            Expression<Func<IComponent, ISite>> propertyExpression = null;

            // act
            var ex = Assert.Throws<ArgumentNullException>( () => validator.Property( propertyExpression ) );

            // assert
            Assert.Equal( "propertyExpression", ex.ParamName );
        }
        public void PropertyShouldReturnSameBuilderForExpression()
        {
            // arrange
            var validator = new ObjectValidator<IComponent>();

            // act
            var expected = validator.Property( c => c.Site );
            var actual = validator.Property( c => c.Site );

            // assert
            Assert.Same( expected, actual );
        }
        public void ShouldValidateLargeArrays()
        {
            const int length = 1000000;
            var objectToValidate = new InnerObject[length];
            for (int i = 0; i < length; i++)
            {
                objectToValidate[i]=new InnerObject();
            }
            var validator = new ObjectValidator();

            var result = validator.Validate(new[] { objectToValidate }, null).ToArray();
            Assert.IsTrue(result.Any());
            Assert.AreEqual(length, result.Length);
        }
        public void ValidateObjectShouldNotAllowNullInstance()
        {
            // arrange
            IComponent instance = null;
            var objectValidator = new ObjectValidator<IComponent>();
            IObjectValidator<IComponent> validatorOfT = objectValidator;
            IObjectValidator validator = objectValidator;

            // act
            var ex1 = Assert.Throws<ArgumentNullException>( () => validatorOfT.ValidateObject( instance ) );
            var ex2 = Assert.Throws<ArgumentNullException>( () => validator.ValidateObject( instance ) );

            // assert
            Assert.Equal( "instance", ex1.ParamName );
            Assert.Equal( "instance", ex2.ParamName );
        }
Beispiel #8
0
        private bool Validate(IValidatableObject movie)
        {
            // for lab 2 below
            // var validatior = new ObjectValidator ();
            var results = ObjectValidator.TryValidateObject(movie);

            if (results.Count() > 0)
            {
                //if (!String.IsNullOrEmpty (message))
                foreach (var result in results)
                {
                    MessageBox.Show(this, result.ErrorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                ;
                return(false);
            }
            ;

            return(true);
        }
Beispiel #9
0
        public void Validate_ValidatorIsRegisteredAndInstanceIsNotValid_ReturnProperlyErrorMesssage()
        {
            var instance         = new object();
            var validationResult = new ValidationResult(new List <ValidationFailure> {
                new ValidationFailure("prop", "error")
            });
            var objectValidator = new ObjectValidator(validationResult);
            var validators      = new List <IValidator> {
                new StringValidator(), objectValidator
            };
            var validationProcessor = new ValidationProcessor(validators);

            var validationError = validationProcessor.Validate(instance).ValidationErrors.SingleOrDefault(e => true);

            Assert.AreEqual(string.Format("[ValidationError][Property='{0}'][AttemptedValue='{1}'][Message='{2}']",
                                          validationResult.Errors[0].PropertyName,
                                          validationResult.Errors[0].AttemptedValue,
                                          validationResult.Errors[0].ErrorMessage),
                            validationError.Message);
        }
        public ActionResult Add(CharacterModel character)
        {
            character.uniqueName = NameCheck(character.Name);
            ObjectValidator.TryValidateFullObject(character).ForEach(x => ModelState.AddModelError("", x.ErrorMessage));

            if (ModelState.IsValid)
            {
                try
                {
                    character.Id = s_characters.Add(character.Convert()).Id;
                    return(RedirectToAction(nameof(CharacterSheet), new { id = character.Id }));
                } catch (Exception e)
                {
                    ModelState.AddModelError("", e.Message);
                };
            }
            ;

            return(View(character));
        }
Beispiel #11
0
        /// <summary>Adds a movie.</summary>
        /// <param name="movie">The movie to add.</param>
        /// <returns>The added movie.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="movie"/> is <see langword="null"/>.</exception>
        /// <exception cref="ValidationException"><paramref name="movie"/> is invalid.</exception>
        /// <exception cref="ArgumentException">A movie with the same title already exists.</exception>
        public Movie Add(Movie movie)
        {
            //Validate
            if (movie == null)
            {
                throw new ArgumentNullException(nameof(movie));
            }
            ObjectValidator.ValidateObject(movie);

            //Movie cannot already exist
            var existing = FindByTitleCore(movie.Title);

            if (existing != null)
            {
                throw new ArgumentException("Movie with same title already exists.", nameof(movie));
            }

            //Create the new movie
            return(AddCore(movie));
        }
Beispiel #12
0
        private void DequeueInvalidTargets()
        {
            object target = null;

            while (this.targetQueue.Count > 0 && target == null)
            {
                target = this.targetQueue[QueueHeadIndex];

                var unityObject = target as UnityEngine.Object;

                if (unityObject != null && ObjectValidator.Validate(unityObject))
                {
                    // We're reached a non-disposed and active target.
                    return;
                }

                // Discard the target.
                this.targetQueue.RemoveAt(QueueHeadIndex);
            }
        }
        public static async Task <TelimenaPackageInfo> GetToolkitUpdateInfo(IProgramsUnitOfWork unitOfWork, Program program, UpdateRequest request, string maximumSupportedToolkitVersion)
        {
            ObjectValidator.Validate(() => Version.TryParse(request.ToolkitVersion, out _)
                                     , new ArgumentException($"[{request.ToolkitVersion}] is not a valid version string"));

            List <TelimenaPackageInfo> packages = (await unitOfWork.ToolkitData.GetPackagesNewerThan(request.ToolkitVersion).ConfigureAwait(false))
                                                  .OrderByDescending(x => x.Version, new TelimenaVersionStringComparer()).ToList();

            if (!request.AcceptBeta)
            {
                packages.RemoveAll(x => x.IsBeta);
            }

            if (packages.Any(x => x.IntroducesBreakingChanges))
            {
                packages.Reverse();
                List <TelimenaPackageInfo> listOfCompatiblePackages = new List <TelimenaPackageInfo>();
                foreach (TelimenaPackageInfo package in packages)
                {
                    if (!package.IntroducesBreakingChanges)
                    {
                        listOfCompatiblePackages.Add(package);
                    }
                    else
                    {
                        if (maximumSupportedToolkitVersion.IsNewerOrEqualVersion(package.Version))
                        {
                            listOfCompatiblePackages.Add(package);
                        }
                        else //at this point a breaking package is not supported by the program, so time to break the loop - no point checking even newer ones
                        {
                            break;
                        }
                    }
                }

                return(listOfCompatiblePackages.LastOrDefault());
            }

            return(packages.FirstOrDefault());
        }
        public void Save()
        {
            var validator = new ObjectValidator(typeof(SupplementCycleDefinitionDTO));

            if (definition.Profile == null)
            {
                definition.Profile = UserContext.Current.CurrentProfile;
            }
            var result = validator.Validate(definition);

            if (!result.IsValid)
            {
                BAMessageBox.ShowValidationError(result.ToBAResults());
                return;
            }
            parentView.RunAsynchronousOperation(delegate
            {
                try
                {
                    context.CycleDefinition = ServiceManager.SaveSupplementsCycleDefinition(definition);
                    //todo:add here clone of saved definition to the cache
                    SupplementsCycleDefinitionsReposidory.Instance.Update(context.CycleDefinition.StandardClone());
                    parentView.SynchronizationContext.Send(delegate
                    {
                        Fill(parentView, context);
                        IsModified = false;
                    }, null);
                }
                catch (ValidationException ex)
                {
                    parentView.SynchronizationContext.Send(state => BAMessageBox.ShowValidationError(ex.Results), null);
                }
                catch (Exception ex)
                {
                    parentView.SynchronizationContext.Send(state => ExceptionHandler.Default.Process(ex, SuplementsEntryStrings.Exception_SupplementsCycleDefinitionEditorViewModel_Save, ErrorWindow.EMailReport), null);
                }
            }, v =>
            {
                updateButtons(v.State == OperationState.Started);
            });
        }
Beispiel #15
0
        private void OnSave(object sender, EventArgs e)
        {
            if (!ValidateChildren())
            {
                return;
            }

            //var movie = new Movie();
            //movie.Name = _txtName.Text;
            //movie.Description = _txtDescription.Text;
            //movie.ReleaseYear = GetInt32(_txtReleaseYear);
            //movie.RunLength = GetInt32(_txtRunLength);
            //movie.IsOwned = _chkOwned.Checked;

            //Initializer syntax
            var movie = new Movie()
            {
                Name        = _txtName.Text,
                Description = _txtDescription.Text,
                ReleaseYear = GetInt32(_txtReleaseYear),
                RunLength   = GetInt32(_txtRunLength),
                IsOwned     = _chkOwned.Checked,
            };

            var results = ObjectValidator.TryValidate(movie);

            foreach (var result in results)

            //if (results.Count > 0)
            {
                // var firstMessage = results[0];
                MessageBox.Show(this, result.ErrorMessage, "Validation Failed", MessageBoxButtons.OK);

                return;
            }
            ;

            Movie        = movie;
            DialogResult = DialogResult.OK;
            Close();
        }
Beispiel #16
0
        public Product Update(Product product, out string message)
        {
            message = "";

            if (product == null)
            {
                message = "Product cannot be null.";
                return(null);
            }
            ;

            //Validate product
            var errors = ObjectValidator.Validate(product);

            if (errors.Count() > 0)
            {
                message = errors.ElementAt(0).ErrorMessage;
                return(null);
            }
            ;

            //Verify Unique product
            var existing = GetProductByNameCore(product.Name);

            if (existing != null && existing.Id != product.Id)
            {
                message = "Product already exists.";
                return(null);
            }
            ;

            //Find Existing
            existing = existing ?? GetCore(product.Id);
            if (existing == null)
            {
                message = "Product not found";
                return(null);
            }

            return(UpdateCore(product));
        }
        /// <summary>Updates a product.</summary>
        /// <param name="product">The product to update.</param>
        /// <returns>The updated product.</returns>
        public Product Update(Product product)
        {
            if (product == null)
            {
                throw new ArgumentNullException(nameof(product));
            }


            var results = ObjectValidator.TryValidateObject(product);

            if (results.Count() > 0)
            {
                throw new ValidationException(results.FirstOrDefault().ErrorMessage);
            }

            //Get existing product
            var existing = GetCore(product.Id);


            return(UpdateCore(existing, product));
        }
Beispiel #18
0
        public async Task <List <TelimenaPackageInfo> > GetPackagesNewerThan(string version)
        {
            ObjectValidator.Validate(() => Version.TryParse(version, out _), new ArgumentException($"[{version}] is not a valid version string"));

            TelimenaPackageInfo current = await this.TelimenaPortalContext.ToolkitPackages.Where(x => x.Version == version).OrderByDescending(x => x.Id).FirstOrDefaultAsync().ConfigureAwait(false);

            List <TelimenaPackageInfo> packages;

            if (current != null)
            {
                packages = (await this.TelimenaPortalContext.ToolkitPackages.Where(x => x.UploadedDate > current.UploadedDate).ToListAsync().ConfigureAwait(false))
                           .OrderByDescending(x => x.Version, new TelimenaVersionStringComparer()).ThenByDescending(x => x.Id).ToList();
            }
            else
            {
                packages = (await this.TelimenaPortalContext.ToolkitPackages.ToListAsync().ConfigureAwait(false)).Where(x => Utils.VersionComparison.Extensions.IsNewerVersionThan(x.Version, version))
                           .OrderByDescending(x => x.Version, new TelimenaVersionStringComparer()).ThenByDescending(x => x.Id).ToList();
            }

            return(this.GetUniquePackages(packages));
        }
Beispiel #19
0
        /// <summary>Updates a product.</summary>
        /// <param name="product">The product to update.</param>
        /// <returns>The updated product.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="product"/> is null.</exception>
        /// <exception cref="ValidationException"><paramref name="product"/> is invalid.</exception>
        /// <exception cref="Exception">Product not found.</exception>
        public Product Update(Product product)
        {
            // Validate
            if (product == null)
            {
                throw new ArgumentNullException(nameof(product));
            }

            //if (!ObjectValidator.TryValidate(product, out var errors))
            //  throw new ArgumentException("Product is invalid.", nameof(product));
            ObjectValidator.Validate(product);

            //Use throw expression
            //Get existing product
            var existing = GetCore(product.Id) ?? throw new Exception("Product not found.");

            //if (existing == null)
            //    throw new Exception("Product not found.");

            return(UpdateCore(existing, product));
        }
        private void LoadConfiguration(IActivatingEventArgs <object> handler)
        {
            var settings    = handler.Instance;
            var sectionName = GetSectionName(settings);

            if (sectionName != null)
            {
                // Lookup settings with the specified section name.
                var configuration = handler.Context.Resolve <IConfiguration>();
                var section       = configuration.GetSection(sectionName);

                // Bind the configuration to the settings instance.
                section.Bind(settings);
            }

            // Determine if the settings object can be validated.
            var validator        = new ObjectValidator(settings);
            var validationResult = new ValidationResult(settings, validator);

            validationResult.ThrowIfInvalid();
        }
Beispiel #21
0
        private bool Validate(IValidatableObject movie)
        {
            //var message = movie.Validate();
            //var context = new ValidationContext (movie);
            //var results = movie.Validate (context);

            var results = ObjectValidator.TryValidateObject(movie);

            if (results.Count() > 0)
            //if (results.Count () > 0)
            {
                foreach (var result in results)
                {
                    MessageBox.Show(this, result.ErrorMessage, "Error", MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                }
                ;
                return(false);
            }
            return(true);
        }
Beispiel #22
0
        /// <summary>Adds a product.</summary>
        /// <param name="product">The product to add.</param>
        /// <returns>The added product.</returns>
        public Product Add(Product product)
        {
            // Check arguments
            if (product == null)
            {
                throw new ArgumentException(nameof(product));
            }

            //Validate product
            ObjectValidator.Validate(product);

            var existing = FindByName(product.Name);

            if (existing != null)
            {
                throw new Exception("Game must be unique.");
            }

            //Emulate database by storing copy
            return(AddCore(product));
        }
Beispiel #23
0
        /// <summary>Adds a product.</summary>
        /// <param name="product">The product to add.</param>
        /// <returns>The added product.</returns>
        public Product Add(Product product)
        {
            if (product == null)
            {
                throw new ArgumentNullException(nameof(product));
            }


            ObjectValidator.Validate(product);

            //products must be unique
            var existing = FindByName(product.Name);

            if (existing != null)
            {
                throw new Exception("Product must be unique.");
            }

            //Emulate database by storing copy
            return(AddCore(product));
        }
Beispiel #24
0
        //OnSave Event Handler, validates at business and UI level
        private void OnSave(object sender, EventArgs e)
        {
            if (!ValidateChildren())
            {
                return;
            }

            var contact = Savedata();

            try
            {
                ObjectValidator.Validate(contact);
            } catch (ValidationException)
            {
                MessageBox.Show(this, "Contact not valid.", "Error", MessageBoxButtons.OK);
                return;
            }
            CurrentContact = contact;
            DialogResult   = DialogResult.OK;
            Close();
        }
Beispiel #25
0
        /// <summary>
        /// Updates an already existing movie
        /// </summary>
        /// <param name="movie">movie to update</param>
        /// <param name="message">error message</param>
        /// <returns>updated movie</returns>
        public Movie Update(Movie movie, out string message)
        {
            message = "";

            //check for null
            if (movie == null)
            {
                message = "Movie cannot be null.";
                return(null);
            }

            //validate movie with IValidatableObject
            var errors = ObjectValidator.Validate(movie);

            if (errors.Count() > 0)
            {
                //get first error (element at 0)
                message = errors.ElementAt(0).ErrorMessage;
                return(null);
            }

            //verify movie is unique
            var existing = GetMovieByTitleCore(movie.Title);

            if (existing != null && existing.Id != movie.Id)
            {
                message = "Movie already exists.";
                return(null);
            }

            //find existing
            existing = existing ?? GetCore(movie.Id);
            if (existing == null)
            {
                message = "Product not found.";
                return(null);
            }

            return(UpdateCore(movie));
        }
Beispiel #26
0
        /// <summary>Adds a product.</summary>
        /// <param name="product">The product to add.</param>
        /// <returns>The added product.</returns>
        public Product Add(Product product)
        {
            //TODO: Check arguments
            //Check null
            if (product == null)
            {
                throw new ArgumentNullException("product");
            }
            //Check invalid

            if (product.Name == null)
            {
                throw new ArgumentNullException("name");
            }
            else if (product.Name == "")
            {
                throw new ArgumentException("Name cannot be empty");
            }

            //Throw exception when adding a product with same name

            //var existing = GetCore(product.Id);
            //if (!(String.IsNullOrEmpty(existing.Name)))
            //{
            //    if (String.Compare(product.Name, existing.Name, true) == 0)
            //        throw new ArgumentNullException("This product already added.");
            //}

            if (product.Price < 0)
            {
                throw new ArgumentOutOfRangeException("Price must be greater or equal to 0");
            }

            //TODO: Validate product
            ObjectValidator.Validate(product);


            //Emulate database by storing copy
            return(AddCore(product));
        }
Beispiel #27
0
        /// <summary>Updates the movie.</summary>
        /// <param name="movie">The movie to update</param>
        /// <returns>The updated movie</returns>
        public Movie Update(Movie movie)
        {
            if (movie == null)
            {
                return(null);
            }

            //Validate using IValidatable Object
            if (!ObjectValidator.TryValidate(movie, out var errors))
            {
                return(null);
            }

            var existing = GetCore(movie.Id);

            if (existing == null)
            {
                return(null);
            }

            return(UpdateCore(existing, movie));
        }
        public Release(DateTime ReleasedAt, String Sha1String, ReleaseDownloadUrl ReleaseDownloadUrl, ReleaseFileName ReleaseFileName, ModVersion ModVersion, FactorioVersion FactorioVersion, List <Dependency> Dependencies)
        {
            DateTimeValidator.ValidateRequiredDateTimeBeforePresent(ReleasedAt, nameof(ReleasedAt));
            ObjectValidator.ValidateRequiredObject(Sha1String, nameof(Sha1String));
            ObjectValidator.ValidateRequiredObject(ReleaseDownloadUrl, nameof(ReleaseDownloadUrl));
            ObjectValidator.ValidateRequiredObject(ReleaseFileName, nameof(ReleaseFileName));
            ObjectValidator.ValidateRequiredObject(ModVersion, nameof(ModVersion));
            ObjectValidator.ValidateRequiredObject(FactorioVersion, nameof(FactorioVersion));
            ListValidator.ValidateRequiredListNotEmpty(Dependencies, nameof(Dependencies));

            Regex sha1CaptureRegex = new Regex(Release.Sha1CapturePattern);
            Match match            = sha1CaptureRegex.Match(Sha1String);

            if (!match.Success)
            {
                throw new ArgumentException($"Unable to parse \"{Sha1String}\" to a valid SHA-1 hash due to formatting.", "Sha1String");
            }

            String sha1 = match.Groups[1].Value;

            if (sha1.Length != Sha1Length)
            {
                throw new ArgumentException($"Unable to parse \"{Sha1String}\" to a valid SHA-1 hash due to length. The SHA-1 hash must have a length of exactly {Release.Sha1Length} characters.", "Sha1String");
            }
            if (ModVersion != ReleaseFileName.ModVersion)
            {
                throw new ArgumentException("The specified release file name version does not match the specified release version.", "ReleaseFileName");
            }

            this.ReleasedAt         = ReleasedAt;
            this.ReleaseDownloadUrl = new ReleaseDownloadUrl(ReleaseDownloadUrl);
            this.ReleaseFileName    = new ReleaseFileName(ReleaseFileName);
            this.Sha1            = sha1;
            this.ModVersion      = new ModVersion(ModVersion);
            this.FactorioVersion = new FactorioVersion(FactorioVersion);
            // TODO: We may want to write an .AddDependency() method that validates that the dependency we're adding isn't for the release/mod itself. That would generate a circular dependency.
            this.Dependencies = Dependencies.ConvertAll(dependency => new Dependency(dependency));
        }
Beispiel #29
0
        public async Task <ProgramUpdatePackageInfo> StorePackageAsync(Program program, string packageName, Stream fileStream, string supportedToolkitVersion, bool isBeta, string releaseNotes, IFileSaver fileSaver)
        {
            var versions = await
                           this.streamVersionReader.GetVersionsFromStream(packageName, fileStream
                                                                          , program.PrimaryAssembly.GetFileName()).ConfigureAwait(false);



            fileStream = await Utilities.ZipTheStreamIfNeeded(packageName, fileStream).ConfigureAwait(false);

            if (versions.toolkitVersion != null)
            {
                supportedToolkitVersion = versions.toolkitVersion;
            }

            ObjectValidator.Validate(() => Version.TryParse(supportedToolkitVersion, out Version _)
                                     , new InvalidOperationException($"[{supportedToolkitVersion}] is not a valid version string"));
            ObjectValidator.Validate(() => this.TelimenaPortalContext.ToolkitPackages.Any(x => x.Version == supportedToolkitVersion)
                                     , new ArgumentException($"There is no toolkit package with version [{supportedToolkitVersion}]"));

            ProgramUpdatePackageInfo pkg = await this.TelimenaPortalContext.UpdatePackages.Where(x => x.ProgramId == program.Id &&
                                                                                                 x.Version == versions.appVersion
#pragma warning disable 618
                                                                                                 && x.SupportedToolkitVersion == supportedToolkitVersion).OrderByDescending(x => x.Id).FirstOrDefaultAsync().ConfigureAwait(false);

#pragma warning restore 618
            if (pkg == null)
            {
                pkg = new ProgramUpdatePackageInfo(packageName, program.Id, versions.appVersion, fileStream.Length, supportedToolkitVersion);
                this.TelimenaPortalContext.UpdatePackages.Add(pkg);
            }

            pkg.UpdateContentAndMetadata(isBeta, releaseNotes);

            await fileSaver.SaveFile(pkg, fileStream, this.containerName).ConfigureAwait(false);

            return(pkg);
        }
Beispiel #30
0
        public static IList <Company> ReadCsvFile1()
        {
            Console.WriteLine("Running ReadCsvFile1");
            var parser     = new CsvFileParser(Common.CsvDataPath);
            var fileErrors = new Dictionary <int, IList <string> >();
            var validator  = new ObjectValidator();

            //parser.Delimiters // can adjust the delimiters
            //parser.FixedWidths // can parse fixed widths

            var rowIndex  = parser.RowStart;
            var companies = new List <Company>();

            foreach (dynamic row in parser.ParseFile())
            {
                var errors = new List <string>();

                var rowObj = FileIOUtilities.MapObject <Company>(row, rowIndex, validator, null, ref errors);
                validator.TryValidate(rowObj, ref errors);
                companies.Add(rowObj);

                if (errors.Count > 0)
                {
                    fileErrors.Add(rowIndex, errors);
                }
                rowIndex++;
            }

            foreach (var errs in fileErrors)
            {
                foreach (var err in errs.Value)
                {
                    Console.WriteLine("Line:{0}, Error: {1}", errs.Key, err);
                }
            }

            return(companies);
        }
        /// <summary>Adds a product.</summary>
        /// <param name="product">The product to add.</param>
        /// <returns>The added product.</returns>
        public Product Add(Product product)
        {
            if (product == null)
            {
                throw new ArgumentException(nameof(product));
            }

            var results = ObjectValidator.TryValidateObject(product);

            if (results.Count() > 0)
            {
                throw new ValidationException(results.FirstOrDefault().ErrorMessage);
            }

            var existing = GetCore(product.Id);

            if (existing != null)
            {
                throw new InvalidOperationException("Id must be unique.");
            }

            return(AddCore(product));
        }
        public void ValidatorTests_Error()
        {
            string input     = "THEVALUE";
            string nullInput = null;

            Assert.That(() =>
                        ObjectValidator.Validate(() => int.TryParse(input, out int _), () => throw new InvalidOperationException($"Error to throw: [{input}]")),
                        Throws.InvalidOperationException.With.Message.EqualTo("Error to throw: [THEVALUE]"));
            Assert.That(() =>
                        ObjectValidator.Validate(() => int.TryParse(nullInput, out int _), () => throw new InvalidOperationException($"Error to throw: [{nullInput}]")),
                        Throws.InvalidOperationException.With.Message.EqualTo("Error to throw: []"));

            Assert.That(() =>
                        ObjectValidator.Validate(() => int.TryParse(input, out int _), new InvalidOperationException("Error to throw")),
                        Throws.InvalidOperationException.With.Message.EqualTo("Error to throw"));
            Assert.That(() =>
                        ObjectValidator.Validate(() => int.TryParse(nullInput, out int _), new InvalidOperationException($"Error to throw: [{nullInput}]")),
                        Throws.InvalidOperationException.With.Message.EqualTo("Error to throw: []"));

            Assert.That(() =>
                        ObjectValidator.Validate(() => this.MyOwnValidation("asd", 3, 2M, null), () => throw new InvalidOperationException($"Error to throw: [{input}]")),
                        Throws.InvalidOperationException.With.Message.EqualTo("Error to throw: [THEVALUE]"));
        }
Beispiel #33
0
        public Language(Language original)
        {
            ObjectValidator.ValidateRequiredObject(original, nameof(original));

            if (original.Id != null)
            {
                this.Id = original.Id;
            }
            if (original.EnglishName != null)
            {
                this.EnglishName = original.EnglishName;
            }
            if (original.LanguageTag != null)
            {
                this.LanguageTag = original.LanguageTag;
            }
            if (original.Culture != null)
            {
                this.Culture = original.Culture;
            }
            this.IsDefault = original.IsDefault;
            this.ModTitles = original.ModTitles != null?original.ModTitles.ConvertAll(title => new ModTitle(title)) : null;
        }
Beispiel #34
0
        /// <summary>Adds a product.</summary>
        /// <param name="product">The product to add.</param>
        /// <returns>The added product.</returns>
        public Product Add(Product product)
        {
            //TODO: Check arguments
            if (product == null)
            {
                throw new ArgumentNullException("product");
            }
            ObjectValidator.TryValidate(product);

            //TODO: Validate product
            try
            {
                //_database.Add(
                AddCore(product);
            }
            catch (Exception e)
            {
                throw new Exception("Add failed", e);
            };

            //Emulate database by storing copy
            return(AddCore(product));
        }
Beispiel #35
0
        /// <summary>Adds a product.</summary>
        /// <param name="product">The product to add.</param>
        /// <returns>The added product.</returns>
        public Product Add(Product product)
        {
            //TODO: Check arguments
            if (product.Name == null)
            {
                throw new ArgumentNullException(nameof(product));
            }
            else if (product.Name == "")
            {
                throw new ArgumentException(nameof(product));
            }

            if (product == null)
            {
                throw new ArgumentNullException(nameof(product));
            }

            //TODO: Validate product
            ObjectValidator.Validate(product);

            //Emulate database by storing copy
            return(AddCore(product));
        }
Beispiel #36
0
        /// <summary>Updates a product.</summary>
        /// <param name="product">The product to update.</param>
        /// <returns>The updated product.</returns>
        public Product Update(Product product)
        {
            // Validate
            if (product == null)
            {
                return(null);
            }

            if (!ObjectValidator.TryValidate(product, out var errors))
            {
                return(null);
            }

            //Get existing product
            var existing = GetCore(product.Id);

            if (existing == null)
            {
                return(null);
            }

            return(UpdateCore(existing, product));
        }
Beispiel #37
0
        public APIReturn Create(Marca toCreate)
        {
            try
            {
                result = new APIReturn
                {
                    Content      = JsonConvert.SerializeObject(rep.Create(toCreate)),
                    Message      = string.IsNullOrEmpty(ObjectValidator.MarcaValidator(toCreate)) ? "Adicionado com sucesso" : "Dados incorretos",
                    ErrorMessage = ObjectValidator.MarcaValidator(toCreate)
                };
            }
            catch (Exception ex)
            {
                result = new APIReturn
                {
                    StatusCode   = 500,
                    Message      = "Ocorreu um erro inesperado ao tendar criar o registro",
                    ErrorMessage = ex.Message
                };
            }

            return(result);
        }
        public void ValidateObjectShouldValidateSpecifiedProperties()
        {
            // arrange
            var instance = new Mock<IComponent>().Object;
            var validator = new ObjectValidator<IComponent>();
            var propertyNames = new[] { "Site" };

            validator.Property( c => c.Site ).Required();

            // act
            var actual = validator.ValidateObject( instance, propertyNames );

            // assert
            Assert.Equal( 1, actual.Count );
            Assert.Equal( "Site", actual[0].MemberNames.Single() );
        }
        public void ValidatePropertyShouldNotAllowNullOrEmptyPropertyName( string propertyName )
        {
            // arrange
            var validator = new ObjectValidator<IComponent>();
            object value = null;

            // act
            var ex = Assert.Throws<ArgumentNullException>( () => validator.ValidateProperty( propertyName, value ) );

            // assert
            Assert.Equal( "propertyName", ex.ParamName );
        }
        public void ValidatePropertyShouldReturnExpectedResult()
        {
            // arrange
            var validator = new ObjectValidator<IComponent>();

            validator.Property( c => c.Site ).Required();

            // act
            var actual = validator.ValidateProperty( "Site", null );

            // assert
            Assert.Equal( 1, actual.Count );
            Assert.Equal( "Site", actual[0].MemberNames.Single() );
        }
        public void ValidateObjectShouldNotAllowNullPropertyNames()
        {
            // arrange
            var instance = new Mock<IComponent>().Object;
            IEnumerable<string> propertyNames = null;
            var objectValidator = new ObjectValidator<IComponent>();
            IObjectValidator<IComponent> validatorOfT = objectValidator;
            IObjectValidator validator = objectValidator;

            // act
            var ex1 = Assert.Throws<ArgumentNullException>( () => validatorOfT.ValidateObject( instance, propertyNames ) );
            var ex2 = Assert.Throws<ArgumentNullException>( () => validator.ValidateObject( instance, propertyNames ) );

            // assert
            Assert.Equal( "propertyNames", ex1.ParamName );
            Assert.Equal( "propertyNames", ex2.ParamName );
        }