internal static RouteRow[] GetByCountryId(Rbr_Db pDb, int pCountryId) { var _list = new List <RouteRow>(); var _routes = pDb.RouteCollection.GetByCountry_id(pCountryId); foreach (var _route in _routes) { if (_route.IsProper) { _list.Insert(0, _route); } else { _list.Add(_route); } } var _genericComparer = new GenericComparer(); _genericComparer.SortInfos.Add(new SortInfo(RouteRow.calling_plan_id_PropName, ListSortDirection.Ascending)); _genericComparer.SortInfos.Add(new SortInfo(RouteRow.IsProper_PropName, ListSortDirection.Descending)); _genericComparer.SortInfos.Add(new SortInfo(RouteRow.BreakoutName_PropName, ListSortDirection.Ascending)); _list.Sort((IComparer <RouteRow>)_genericComparer); return(_list.ToArray()); }
void sort(SortOrder order, bool Rebuild) { if (order != SortOrder.None) { GroupRow g = Rebuild ? Source.GetGroup(Source.Position) : null; if (comparer == null) { comparer = new GenericComparer(GroupValueType); } comparer.Descending = order == SortOrder.Descending; List.Sort(compare); if (Rebuild) { Rows.Clear(); RebuildRows(); Source.FireBaseReset(false); if (g != null) { Source.Position = g.Index; if (!g.Collapsed) { Source.Position++; } } } } }
public async void GetShouldReturnProducts() { // Arrange var products = new List<Product> { new Product {ProductId = 1, ProductName = "Product1"}, new Product {ProductId = 2, ProductName = "Product2"}, new Product {ProductId = 3, ProductName = "Product3"}, }; // Mock products repo var productsRepoMock = new Mock<IProductsRepository>(); productsRepoMock.Setup(m => m.GetProducts()).ReturnsAsync(products); // Mock unit of work var unitofWorkMock = new Mock<INorthwindUnitOfWork>(); unitofWorkMock.SetupGet(m => m.ProductsRepository).Returns(productsRepoMock.Object); // Create controller var productsController = new ProductsController(unitofWorkMock.Object); // Act IHttpActionResult response = await productsController.Get(); // Assert var actual = ((OkNegotiatedContentResult<IEnumerable<Product>>)response).Content; var comparer = new GenericComparer<Product>( (p1, p2) => p1.ProductId == p2.ProductId); Assert.Equal(products, actual, comparer); }
AreEnumerablesEqualComparer_ExpectedAndActualHaveSameObjectsInSameOrder_ShouldNotThrowAssertFailedExceptionIfEqualsOverride() { var comparer = new GenericComparer <EqualityTestObject, EqualityTestObject>( (expected, actual) => expected.Equals(actual)); var expected = new List <EqualityTestObject> { new EqualityTestObject(), new EqualityTestObject { BooleanPropertyTest = true } }; var actual = new List <EqualityTestObject> { new EqualityTestObject(), new EqualityTestObject { BooleanPropertyTest = true } }; ExceptionAsserter.DoesNotThrowException <AssertFailedException>( () => { CollectionAsserter.AreEnumerablesEqual <EqualityTestObject>(expected, actual, comparer); }); }
public void UsesProvidedGenericComparer() { var comparer = new GenericComparer <int>(); Assert.That(rangeConstraint.Using(comparer).ApplyTo(19).IsSuccess); Assert.That(comparer.WasCalled, "Comparer was not called"); }
static void Main(string[] args) { int mu = 10; int lambda = 70; int generations = 10; GenericComparer <Individual> comparer = new GenericComparer <Individual>(CompareFunctions.CompareRating); //create parent generation List <Individual> parents = new List <Individual>(); List <Individual> childs = null; for (int i = 0; i < mu / 2; i++) { parents.Add(new Individual(new[] { 2.0, 200.0 }, new[] { 2.0, 2.0 })); parents.Add(new Individual(new[] { 1.0, 2000.0 }, new[] { 2.0, 2.0 })); } //start evolving! for (int i = 0; i < generations; i++) { childs = EvolutionSteps.Recombine(ref parents, lambda, BasicEvolutionStrategyFunctions.IntermediateRecombination, BasicEvolutionStrategyFunctions.DiscreteRecombination); EvolutionSteps.Mutate(ref childs, 0.1f, 0.2f, BasicEvolutionStrategyFunctions.Mutate); EvolutionSteps.Evaluate(ref childs, BasicEvolutionStrategyFunctions.SimpleZeroRating); EvolutionSteps.Selection(ref childs, mu, comparer); parents = childs; } //show me foreach (Individual ind in childs) { Console.WriteLine(ind); } }
public static IComparer <TSource> ToComparer <TSource>(this IEnumerable <Sort <TSource> > sorts) { var comparer = new GenericComparer <TSource>((x, y) => { int result = 0; foreach (var sort in sorts) { var sortByFunc = sort.SortBy.Compile(); result = Comparer <object> .Default.Compare(sortByFunc(x), sortByFunc(y)); result *= sort.ListSortDirection == ListSortDirection.Descending ? -1 : 1; if (result != 0) { break; } } return(result); }); return(comparer); }
/// <summary> /// Determines if the property is valid /// </summary> /// <param name="value">Value to check</param> /// <param name="validationContext">Validation context</param> /// <returns>The validation result</returns> protected override ValidationResult IsValid(object value, ValidationContext validationContext) { GenericComparer <IComparable> Comparer = new GenericComparer <IComparable>(); IComparable Value2 = (IComparable)Value.To <object>(value.GetType()); IComparable TempValue = value as IComparable; if (Type == ComparisonType.Equal) { return(Comparer.Compare(TempValue, Value2) == 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName))); } else if (Type == ComparisonType.NotEqual) { return(Comparer.Compare(TempValue, Value2) != 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName))); } else if (Type == ComparisonType.GreaterThan) { return(Comparer.Compare(TempValue, Value2) > 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName))); } else if (Type == ComparisonType.GreaterThanOrEqual) { return(Comparer.Compare(TempValue, Value2) >= 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName))); } else if (Type == ComparisonType.LessThan) { return(Comparer.Compare(TempValue, Value2) < 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName))); } else if (Type == ComparisonType.LessThanOrEqual) { return(Comparer.Compare(TempValue, Value2) <= 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName))); } else { return(ValidationResult.Success); } }
public void AllItemsAreInRange_UsingGenericComparer() { var comparer = new GenericComparer<int>(); int[] c = new int[] { 12, 27, 19, 32, 45, 99, 26 }; Assert.That(c, Is.All.InRange(10, 100).Using(comparer)); Assert.That(comparer.WasCalled); }
/// <summary> /// Determines if the property is valid /// </summary> /// <param name="value">Value to check</param> /// <param name="validationContext">Validation context</param> /// <returns>The validation result</returns> protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var Comparer = new GenericComparer <IComparable>(); var Value2 = (IComparable)Value.To <object>(value.GetType()); var TempValue = value as IComparable; switch (Type) { case ComparisonType.Equal: return(Comparer.Compare(TempValue, Value2) == 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName))); case ComparisonType.NotEqual: return(Comparer.Compare(TempValue, Value2) != 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName))); case ComparisonType.GreaterThan: return(Comparer.Compare(TempValue, Value2) > 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName))); case ComparisonType.GreaterThanOrEqual: return(Comparer.Compare(TempValue, Value2) >= 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName))); case ComparisonType.LessThan: return(Comparer.Compare(TempValue, Value2) < 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName))); case ComparisonType.LessThanOrEqual: return(Comparer.Compare(TempValue, Value2) <= 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName))); default: return(ValidationResult.Success); } }
/// <exclude /> public static XhtmlDocument RenderDataList <T>(IVisualFunction function, XhtmlDocument xhtmlDocument, DataTypeDescriptor typeDescriptor, FunctionContextContainer functionContextContainer, Expression <Func <T, bool> > filter) where T : class, IData { if (function == null) { throw new ArgumentNullException("function"); } if (xhtmlDocument == null) { throw new ArgumentNullException("xhtmlDocument"); } if (typeDescriptor == null) { throw new ArgumentNullException("typeDescriptor"); } if (functionContextContainer == null) { throw new ArgumentNullException("functionContextContainer"); } Type dataType = typeDescriptor.GetInterfaceType(); if (dataType == null) { throw new InvalidOperationException(string.Format("'{0}' is not a known type manager type.", typeDescriptor.TypeManagerTypeName)); } List <T> allData = DataFacade.GetData <T>(filter).ToList(); List <T> itemsToList; if (function.OrderbyFieldName == "(random)") { int itemsInList = allData.Count(); int itemsToFetch = Math.Min(itemsInList, function.MaximumItemsToList); itemsToList = new List <T>(); while (itemsToFetch > 0) { int itemToGet = (Math.Abs(Guid.NewGuid().GetHashCode()) % itemsInList); // (new Random()).Next(0, itemsInList); itemsToList.Add(allData[itemToGet]); allData.RemoveAt(itemToGet); itemsToFetch--; itemsInList--; } } else { IComparer <T> comparer = GenericComparer <T> .Build(typeDescriptor.GetInterfaceType(), function.OrderbyFieldName, function.OrderbyAscending); allData.Sort(comparer); itemsToList = allData.Take(function.MaximumItemsToList).ToList(); } return(RenderDataListImpl <T>(xhtmlDocument, typeDescriptor, itemsToList, functionContextContainer)); }
public void UsesProvidedGenericComparer() { var comparer = new GenericComparer <int>(); Assert.That(new[] { 1, 2 }, Is.Ordered.Using(comparer)); Assert.That(comparer.WasCalled, "Comparer was not called"); }
/// <summary> /// Determines if the property is valid /// </summary> /// <param name="value">Value to check</param> /// <param name="validationContext">Validation context</param> /// <returns>The validation result</returns> protected override ValidationResult IsValid(object value, ValidationContext validationContext) { IComparable Tempvalue = value as IComparable; GenericComparer <IComparable> Comparer = new GenericComparer <IComparable>(); IComparable ComparisonValue = (IComparable)validationContext.ObjectType.GetProperty(PropertyName).GetValue(validationContext.ObjectInstance, null).To <object>(value.GetType()); if (Type == ComparisonType.Equal) { return(Comparer.Compare(Tempvalue, ComparisonValue) == 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName))); } else if (Type == ComparisonType.NotEqual) { return(Comparer.Compare(Tempvalue, ComparisonValue) != 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName))); } else if (Type == ComparisonType.GreaterThan) { return(Comparer.Compare(Tempvalue, ComparisonValue) > 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName))); } else if (Type == ComparisonType.GreaterThanOrEqual) { return(Comparer.Compare(Tempvalue, ComparisonValue) >= 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName))); } else if (Type == ComparisonType.LessThan) { return(Comparer.Compare(Tempvalue, ComparisonValue) < 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName))); } else if (Type == ComparisonType.LessThanOrEqual) { return(Comparer.Compare(Tempvalue, ComparisonValue) <= 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName))); } else { return(ValidationResult.Success); } }
public void GenericComparerTest2() { GenericComparer <IDjvuNode> nodeComparer = new GenericComparer <IDjvuNode>( x => (x.ChunkType.GetHashCode() + x.DataOffset.GetHashCode()), (x, y) => x.ChunkType == y.ChunkType && x.DataOffset == y.DataOffset); Mock <IDjvuNode> nodeMock1 = new Mock <IDjvuNode>(); nodeMock1.Setup(x => x.ChunkType).Returns(ChunkType.Anta); nodeMock1.Setup(x => x.DataOffset).Returns(2048); Mock <IDjvuNode> nodeMock2 = new Mock <IDjvuNode>(); nodeMock2.Setup(x => x.ChunkType).Returns(ChunkType.Anta); nodeMock2.Setup(x => x.DataOffset).Returns(2048); Mock <IDjvuNode> nodeMock3 = new Mock <IDjvuNode>(); nodeMock3.Setup(x => x.ChunkType).Returns(ChunkType.Antz); nodeMock3.Setup(x => x.DataOffset).Returns(2048); Assert.NotSame(nodeMock1.Object, nodeMock2.Object); Assert.True(nodeComparer.Equals(nodeMock1.Object, nodeMock2.Object)); Assert.Equal <int>(nodeComparer.GetHashCode(nodeMock1.Object), nodeComparer.GetHashCode(nodeMock2.Object)); Assert.NotSame(nodeMock1.Object, nodeMock3.Object); Assert.False(nodeComparer.Equals(nodeMock1.Object, nodeMock3.Object)); Assert.NotEqual <int>(nodeComparer.GetHashCode(nodeMock1.Object), nodeComparer.GetHashCode(nodeMock3.Object)); }
public void UsesProvidedGenericComparer() { var comparer = new GenericComparer <int>(); Assert.That(2 + 2, Is.EqualTo(4).Using(comparer)); Assert.That(comparer.WasCalled, "Comparer was not called"); }
static void BuildTables(IEnumerable <JumpEntry> jumps, LabelOperand defaultLabel, out List <JumpTable> tables, out List <JumpEntry> rest) { rest = new List <JumpEntry>(); var numbers = FilterJumps(jumps, rest); var comparer = new GenericComparer <JumpTableEntry <int> >((b1, b2) => b1.Value - b2.Value); numbers.Sort(comparer); tables = new List <JumpTable>(); for (var i = 0; i < numbers.Count; i++) { var table = TryBuildTable(numbers, i, defaultLabel); if (table != null) { tables.Add(table); i += table.Entries.Count - table.Holes - 1; } else { rest.Add(new JumpEntry(numbers[i].Condition, numbers[i].Label)); } } }
public void AllItemsAreInRange_UsingGenericComparer() { var comparer = new GenericComparer<int>(); int[] c = new int[] { 12, 27, 19, 32, 45, 99, 26 }; Assert.That(c, new AllItemsConstraint(new RangeConstraint(10, 100).Using(comparer))); Assert.That(comparer.WasCalled); }
public void UsesProvidedGenericComparer() { var comparer = new GenericComparer <int>(); ComparisonConstraint.Using(comparer).ApplyTo(0); Assert.That(comparer.WasCalled, "Comparer was not called"); }
public async void GetShouldReturnProducts() { // Arrange var products = new List <Product> { new Product { ProductId = 1, ProductName = "Product1" }, new Product { ProductId = 2, ProductName = "Product2" }, new Product { ProductId = 3, ProductName = "Product3" }, }; IProductsRepository productsRepo = new MockProductsRepository(products); INorthwindUnitOfWork unitOfWork = new MockNorthwindUnitOfWork(productsRepo); var productsController = new ProductsController(unitOfWork); // Act IHttpActionResult response = await productsController.Get(); // Assert var actual = ((OkNegotiatedContentResult <IEnumerable <Product> >)response).Content; var comparer = new GenericComparer <Product>( (p1, p2) => p1.ProductId == p2.ProductId); Assert.Equal(products, actual, comparer); }
public void CompareNullNonValueType() { var Comparer = new GenericComparer <string>(); Assert.Equal(0, Comparer.Compare(null, null)); Assert.Equal(-1, Comparer.Compare(null, "B")); Assert.Equal(-1, Comparer.Compare("B", null)); }
static TimeSpan() { if (MonoTouchAOTHelper.FalseFlag) { GenericComparer <TimeSpan> genericComparer = new GenericComparer <TimeSpan>(); GenericEqualityComparer <TimeSpan> genericEqualityComparer = new GenericEqualityComparer <TimeSpan>(); } }
static Guid() { if (MonoTouchAOTHelper.FalseFlag) { GenericComparer <Guid> genericComparer = new GenericComparer <Guid>(); GenericEqualityComparer <Guid> genericEqualityComparer = new GenericEqualityComparer <Guid>(); } }
public void CompareValueType() { var Comparer = new GenericComparer <int>(); Assert.Equal(0, Comparer.Compare(0, 0)); Assert.Equal(-1, Comparer.Compare(0, 1)); Assert.Equal(1, Comparer.Compare(1, 0)); }
public void Compare() { var Comparer = new GenericComparer <string>(); Assert.Equal(0, Comparer.Compare("A", "A")); Assert.Equal(-1, Comparer.Compare("A", "B")); Assert.Equal(1, Comparer.Compare("B", "A")); }
public static IList <Expression <Func <T, bool> > > ByQueryParams <T>(OptionsFilter queryParams) where T : IEntity { IList <Expression <Func <T, bool> > > predicate = new List <Expression <Func <T, bool> > >(); var classType = typeof(T); var propList = classType.GetProperties(); var props = new Dictionary <string, PropertyInfo>(propList.Select(x => new KeyValuePair <string, PropertyInfo>(x.Name, x)), StringComparer.OrdinalIgnoreCase); var filters = new List <QueryFilter>(); foreach (var param in queryParams._filter) { if (string.IsNullOrEmpty(param)) { return(predicate); } if (param.Contains("==")) { filters.Add(PrepareFilter(param, "==")); } if (param.Contains(">=")) { filters.Add(PrepareFilter(param, ">=")); } if (param.Contains("<=")) { filters.Add(PrepareFilter(param, "<=")); } } if (queryParams._filter.Count > 0 && filters.Count == 0) { throw new BadRequestException($"Todos os filtros devem conter um dos operadores ('>=','<=','==')"); } foreach (var param in filters) { if (props.ContainsKey(param.PropertyName)) { var prop = props[param.PropertyName.ToLower()]; if (prop.PropertyType == typeof(int) || prop.PropertyType == typeof(DateTime) || prop.PropertyType == typeof(string)) { predicate.Add(x => GenericComparer.GenericComparison(prop.GetValue(x, null), param.Value, param.Operator, prop.PropertyType)); } } else { throw new BadRequestException($"A propriedade {param.PropertyName} não exite neste objeto."); } } return(predicate); }
/// <summary> /// Validates an object /// </summary> /// <param name="Object">Object to validate</param> public override void Validate(ObjectType Object) { GenericComparer <DataType> Comparer = new GenericComparer <DataType>(); if (Comparer.Compare(ItemToValidate(Object), MinValue) <= 0) { throw new NotValid(ErrorMessage); } }
public void TestCompare(int x, int y) { Func <int, int, int> compare = DoCompare; GenericComparer <int> gc = new GenericComparer <int>(compare); m_bCompareCalled = false; Assert.AreEqual(x - y, gc.Compare(x, y)); Assert.IsTrue(m_bCompareCalled); }
/// <summary> /// sorts the grid based on sort expression and sort direction /// </summary> /// <typeparam name="T"> Type</typeparam> /// <param name="gvObject">Gridview</param> /// <param name="sDir">sortDirection</param> /// <param name="sortExpr">sortExpression</param> /// <param name="collection">List of Items</param> public static void GridSort <T>(GridView gvObject, SortDirection sDir, string sortExpr, List <T> collection) { GenericComparer <T> comparer = new GenericComparer <T>(sortExpr, sDir); //Initializes new comparer collection.Sort(comparer); //sorts //databinding gvObject.DataSource = collection; gvObject.DataBind(); }
public List<Media_Types> GetSortedListByStatus(string status, string sortBy) { List<Media_Types> objList = GetListByStatus(status); if (sortBy != "") { GenericComparer<Media_Types> cmp = new GenericComparer<Media_Types>(sortBy); objList.Sort(cmp); } return objList; }
/// <summary> /// Determines if a value is between two values /// </summary> /// <typeparam name="T">Data type</typeparam> /// <param name="Value">Value to check</param> /// <param name="Low">Low bound (inclusive)</param> /// <param name="High">High bound (inclusive)</param> /// <returns>True if it is between the low and high values</returns> public static bool Between <T>(this T Value, T Low, T High) where T : IComparable { GenericComparer <T> Comparer = new GenericComparer <T>(); if (Comparer.Compare(High, Value) >= 0 && Comparer.Compare(Value, Low) >= 0) { return(true); } return(false); }
/// <summary> /// Override SimpleKeyValue GetCollection to add support for IPersistent Value POCO (de)serialization. /// </summary> /// <param name="container"></param> /// <param name="comparer"></param> /// <param name="came"></param> /// <param name="isDataInKeySegment"></param> /// <returns></returns> protected override ISortedDictionaryOnDisk GetCollection( ISortedDictionaryOnDisk container, GenericComparer <TKey> comparer, string came, bool isDataInKeySegment) { var o = (OnDisk.Algorithm.SortedDictionary.ISortedDictionaryOnDisk) base.GetCollection(container, comparer, came, isDataInKeySegment); o.OnValuePack += new OnObjectPack(Collection_OnPack); o.OnValueUnpack += new OnObjectUnpack(Collection_OnValueUnpack); return(o); }
/// <summary> /// Returns the minimum value between the two /// </summary> /// <param name="InputA">Input A</param> /// <param name="InputB">Input B</param> /// <returns>The minimum value</returns> public static T Min <T>(this T InputA, T InputB) where T : IComparable { GenericComparer <T> Comparer = new GenericComparer <T>(); if (Comparer.Compare(InputA, InputB) > 0) { return(InputB); } return(InputA); }
public List <Media_Types> GetSortedListByStatus(string status, string sortBy) { List <Media_Types> objList = GetListByStatus(status); if (sortBy != "") { GenericComparer <Media_Types> cmp = new GenericComparer <Media_Types>(sortBy); objList.Sort(cmp); } return(objList); }
public async void GetShouldReturnProducts() { // Arrange var expected = new List<Product> { new Product {ProductId = 1, ProductName = "Product1"}, new Product {ProductId = 2, ProductName = "Product2"}, new Product {ProductId = 3, ProductName = "Product3"}, }; IProductsRepository productsRepo = new MockProductsRepository(expected); INorthwindUnitOfWork unitOfWork = new MockNorthwindUnitOfWork(productsRepo); var productsController = new ProductsController(unitOfWork); // Act IHttpActionResult response = await productsController.Get(); // Assert var actual = ((OkNegotiatedContentResult<IEnumerable<Product>>)response).Content; var comparer = new GenericComparer<Product>( (p1, p2) => p1.ProductId == p2.ProductId); Assert.Equal(expected, actual, comparer); }
/// <summary> /// Determines if the property is valid /// </summary> /// <param name="value">Value to check</param> /// <param name="validationContext">Validation context</param> /// <returns>The validation result</returns> protected override ValidationResult IsValid(object value, ValidationContext validationContext) { GenericComparer<IComparable> Comparer = new GenericComparer<IComparable>(); IComparable MaxValue = (IComparable)Max.To<object>(value.GetType()); IComparable MinValue = (IComparable)Min.To<object>(value.GetType()); IComparable TempValue = value as IComparable; return (Comparer.Compare(MaxValue, TempValue) >= 0 && Comparer.Compare(TempValue, MinValue) >= 0) ? new ValidationResult(FormatErrorMessage(validationContext.DisplayName)) : ValidationResult.Success; }
public void UsesProvidedGenericComparer() { var al = new List<int>(); al.Add(1); al.Add(2); var comparer = new GenericComparer<int>(); Assert.That(al, Is.Ordered.Using(comparer)); Assert.That(comparer.WasCalled, "Comparer was not called"); }
/// <summary> /// Determines if the property is valid /// </summary> /// <param name="value">Value to check</param> /// <param name="validationContext">Validation context</param> /// <returns>The validation result</returns> protected override ValidationResult IsValid(object value, ValidationContext validationContext) { IComparable Tempvalue = value as IComparable; GenericComparer<IComparable> Comparer = new GenericComparer<IComparable>(); IComparable ComparisonValue = (IComparable)validationContext.ObjectType.GetProperty(PropertyName).GetValue(validationContext.ObjectInstance, null).To<object>(value.GetType()); if (Type == ComparisonType.Equal) return Comparer.Compare(Tempvalue, ComparisonValue) == 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); else if (Type == ComparisonType.NotEqual) return Comparer.Compare(Tempvalue, ComparisonValue) != 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); else if (Type == ComparisonType.GreaterThan) return Comparer.Compare(Tempvalue, ComparisonValue) > 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); else if (Type == ComparisonType.GreaterThanOrEqual) return Comparer.Compare(Tempvalue, ComparisonValue) >= 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); else if (Type == ComparisonType.LessThan) return Comparer.Compare(Tempvalue, ComparisonValue) < 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); else if (Type == ComparisonType.LessThanOrEqual) return Comparer.Compare(Tempvalue, ComparisonValue) <= 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); else return ValidationResult.Success; }
public void Constructor_NullComparison_ThrowsException() { GenericComparer<string> c = new GenericComparer<string>(null); }
public void Constructor_NonNullComparison_DoesNotThrowException() { GenericComparer<string> c = new GenericComparer<string>((x,y) => { return 0; }); }
public void UsesProvidedGenericComparer() { var comparer = new GenericComparer<int>(); Assert.That(rangeConstraint.Using(comparer).ApplyTo(19).IsSuccess); Assert.That(comparer.WasCalled, "Comparer was not called"); }
public void ShouldThrowExceptionIfFromIsLessThanTo() { var comparer = new GenericComparer<int>(); Assert.Throws<ArgumentException>(() => new RangeConstraint( 42, 5 )); }
public void ShouldThrowExceptionIfFromIsLessThanTo() { var comparer = new GenericComparer<int>(); rangeConstraint = new RangeConstraint( 42, 5 ); rangeConstraint.Using(comparer).ApplyTo(19); }
/// <summary> /// Determines if the property is valid /// </summary> /// <param name="value">Value to check</param> /// <param name="validationContext">Validation context</param> /// <returns>The validation result</returns> protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var Comparer = new GenericComparer<IComparable>(); var Value2 = (IComparable)Value.To<object>(value.GetType()); var TempValue = value as IComparable; switch (Type) { case ComparisonType.Equal: return Comparer.Compare(TempValue, Value2) == 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); case ComparisonType.NotEqual: return Comparer.Compare(TempValue, Value2) != 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); case ComparisonType.GreaterThan: return Comparer.Compare(TempValue, Value2) > 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); case ComparisonType.GreaterThanOrEqual: return Comparer.Compare(TempValue, Value2) >= 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); case ComparisonType.LessThan: return Comparer.Compare(TempValue, Value2) < 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); case ComparisonType.LessThanOrEqual: return Comparer.Compare(TempValue, Value2) <= 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); default: return ValidationResult.Success; } }
public void UsesProvidedGenericComparer() { var comparer = new GenericComparer<int>(); Assert.That(new[] { 1, 2 }, Is.Ordered.Using(comparer)); Assert.That(comparer.WasCalled, "Comparer was not called"); }
/// <summary> /// Determines if the property is valid /// </summary> /// <param name="value">Value to check</param> /// <param name="validationContext">Validation context</param> /// <returns>The validation result</returns> protected override ValidationResult IsValid(object value, ValidationContext validationContext) { GenericComparer<IComparable> Comparer = new GenericComparer<IComparable>(); IComparable Value2 = (IComparable)Value.TryTo<object>(value.GetType()); IComparable TempValue = value as IComparable; if (Type == ComparisonType.Equal) return Comparer.Compare(TempValue, Value2) == 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); else if (Type == ComparisonType.NotEqual) return Comparer.Compare(TempValue, Value2) != 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); else if (Type == ComparisonType.GreaterThan) return Comparer.Compare(TempValue, Value2) > 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); else if (Type == ComparisonType.GreaterThanOrEqual) return Comparer.Compare(TempValue, Value2) >= 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); else if (Type == ComparisonType.LessThan) return Comparer.Compare(TempValue, Value2) < 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); else if (Type == ComparisonType.LessThanOrEqual) return Comparer.Compare(TempValue, Value2) <= 0 ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); else return ValidationResult.Success; }