Example #1
0
        public void NullsAreEqual()
        {
            var falseComparer = new DelegateEqualityComparer <ExampleClass>((c1, c2) => false);

            var result = falseComparer.Equals(null, null);

            Assert.That(result, Is.True);
        }
        public void IndexOf_WithoutCountParam()
        {
            var builder     = ImmutableArray.Create(2, 5, 8).ToBuilder();
            var absComparer = new DelegateEqualityComparer <int>(equals: (x, y) => Math.Abs(x) == Math.Abs(y));

            Assert.Equal(1, builder.IndexOf(-5, 0, absComparer));
            Assert.Equal(-1, builder.IndexOf(-5, 2, absComparer));
        }
Example #3
0
        public void NullsHaveHashOfZero()
        {
            var comparer = new DelegateEqualityComparer <ExampleClass>((c1, c2) => false, c => 1);

            var result = comparer.GetHashCode(null);

            Assert.That(result, Is.EqualTo(0));
        }
Example #4
0
        public void CanComputeHashOfClass()
        {
            var first    = new ExampleClass();
            var comparer = new DelegateEqualityComparer <ExampleClass>((c1, c2) => false, c => 1);

            var result = comparer.GetHashCode(first);

            Assert.That(result, Is.EqualTo(1));
        }
 public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(
     this IEnumerable<TSource> source,
     Func<TSource, TKey> keySelector,
     Func<TKey, TKey, bool> equalityComparison)
 {
     return source.GroupBy(
         keySelector,
         DelegateEqualityComparer<TKey>.Create(equalityComparison);
 }
        public void DistinctString()
        {
            var comparer = new DelegateEqualityComparer <string>((x, y) => x == y, x => x.GetHashCode());

            string[] source = new[] { "1", "2", "32", "3", "2", "1", "4", "4", "5", "6", "7", "8", "9", "9", };
            string[] expect = new[] { "1", "2", "32", "3", "4", "5", "6", "7", "8", "9", };

            source.Distinct(comparer).ToArray().Is(expect);
        }
        public void DistinctInt()
        {
            var comparer = new DelegateEqualityComparer <int>((x, y) => x == y, x => x.GetHashCode());

            int[] source = new[] { 1, 2, 32, 3, 2, 1, 4, 4, 5, 6, 7, 8, 9, 9, };
            int[] expect = new[] { 1, 2, 32, 3, 4, 5, 6, 7, 8, 9, };

            source.Distinct(comparer).ToArray().Is(expect);
        }
        public void RemoveRange_EqualityComparer()
        {
            var builder     = ImmutableArray.Create(1.5, 2.5, 3.5, 4.5, 5.6).ToBuilder();
            var absComparer = new DelegateEqualityComparer <double>(equals: (x, y) => Math.Abs(x) == Math.Abs(y));

            builder.RemoveRange(new[] { -2.5, -4.5, 6.2 }, absComparer);
            Assert.Equal(new[] { 1.5, 3.5, 5.6 }, builder);
            AssertExtensions.Throws <ArgumentNullException>("items", () => builder.RemoveRange(null, absComparer));
        }
Example #9
0
        public void SelfIsAlwaysEqualWithSelf()
        {
            var self          = new ExampleClass();
            var falseComparer = new DelegateEqualityComparer <ExampleClass>((c1, c2) => false);

            var result = falseComparer.Equals(self, self);

            Assert.That(result, Is.True);
        }
Example #10
0
        public void NullWithNonNullIsAlwaysUnequal()
        {
            var otherClass   = new ExampleClass();
            var trueComparer = new DelegateEqualityComparer <ExampleClass>((c1, c2) => true);

            var result = trueComparer.Equals(null, otherClass);

            Assert.That(result, Is.False);
        }
Example #11
0
        public AttributesIndex(MemoryMap map, AttributesIndexMode mode = AttributesIndexMode.ReverseAll)
        {
            if (mode == AttributesIndexMode.None)
            {
                throw new ArgumentException("Cannot create a new index without a valid operating mode.");
            }
            this._stringIndex            = new Index <string>(map);
            this._collectionIndex        = new Index <int[]>(map);
            this._isReadonly             = false;
            this._mode                   = mode;
            this._stringReverseIndex     = (IDictionary <string, int>)null;
            this._collectionReverseIndex = (IDictionary <int[], uint>)null;
            if ((this._mode & AttributesIndexMode.IncreaseOne) == AttributesIndexMode.IncreaseOne)
            {
                this._index  = (ArrayBase <uint>) new Array <uint>(map, 1024L);
                this._nextId = 0U;
            }
            if ((this._mode & AttributesIndexMode.ReverseStringIndex) == AttributesIndexMode.ReverseStringIndex || (this._mode & AttributesIndexMode.ReverseStringIndexKeysOnly) == AttributesIndexMode.ReverseStringIndexKeysOnly)
            {
                this._stringReverseIndex = (IDictionary <string, int>) new Reminiscence.Collections.Dictionary <string, int>(map, 16384);
            }
            if ((this._mode & AttributesIndexMode.ReverseCollectionIndex) != AttributesIndexMode.ReverseCollectionIndex)
            {
                return;
            }
            MemoryMap memoryMap = map;
            int       num       = 16384;

            DelegateEqualityComparer <int[]> .GetHashCodeDelegate hashCodeDelegate1 = (DelegateEqualityComparer <int[]> .GetHashCodeDelegate)(obj =>
            {
                int hashCode = obj.Length.GetHashCode();
                for (int index = 0; index < obj.Length; ++index)
                {
                    hashCode ^= obj[index].GetHashCode();
                }
                return(hashCode);
            });
            DelegateEqualityComparer <int[]> equalityComparer = new DelegateEqualityComparer <int[]>(hashCodeDelegate1, (DelegateEqualityComparer <int[]> .EqualsDelegate)((x, y) =>
            {
                if (x.Length != y.Length)
                {
                    return(false);
                }
                for (int index = 0; index < x.Length; ++index)
                {
                    if (x[index] != y[index])
                    {
                        return(false);
                    }
                }
                return(true);
            }));

            this._collectionReverseIndex = (IDictionary <int[], uint>) new Reminiscence.Collections.Dictionary <int[], uint>(memoryMap, num, (IEqualityComparer <int[]>)equalityComparer);
        }
        public void Remove_EqualityComparer()
        {
            var builder     = ImmutableArray.Create(1.5, 2.5, 3.5).ToBuilder();
            var absComparer = new DelegateEqualityComparer <double>(equals: (x, y) => Math.Abs(x) == Math.Abs(y));

            Assert.True(builder.Remove(-1.5, absComparer));
            Assert.Equal(new[] { 2.5, 3.5 }, builder);

            Assert.False(builder.Remove(5, absComparer));
            Assert.False(builder.Remove(4, null));
        }
        public void Replace()
        {
            var builder = ImmutableArray.Create(1.5, 2.5, 3.5).ToBuilder();

            builder.Replace(1.5, 1.6);

            Assert.Equal(new[] { 1.6, 2.5, 3.5 }, builder);

            var absComparer = new DelegateEqualityComparer <double>(equals: (x, y) => Math.Abs(x) == Math.Abs(y));

            builder.Replace(-3.5, 4.2, absComparer);

            Assert.Equal(new[] { 1.6, 2.5, 4.2 }, builder);
        }
        public void GetHashCodeCallsTheProvidedDelegate()
        {
            var hashWasCalled = false;

            Func<string, int> hash = (string obj) =>
            {
                hashWasCalled = true;
                return 1;
            };

            var sut = new DelegateEqualityComparer<string>(this.defaultComparer, hash);

            sut.GetHashCode("test");

            Assert.True(hashWasCalled);
        }
        public void EqualsCallsTheProvidedDelegate()
        {
            var comparerWasCalled = false;

            Func<string, string, bool> comparer = (string x, string y) =>
            {
                comparerWasCalled = true;
                return true;
            };

            var sut = new DelegateEqualityComparer<string>(comparer, this.defaultHash);

            sut.Equals("test", "test");

            Assert.True(comparerWasCalled);
        }
Example #16
0
        public void Replace()
        {
            var mutable = ImmutableList <double> .Empty.ToBuilder();

            mutable.Add(1.5);
            mutable.Add(2.4);
            mutable.Add(3.6);

            mutable.Replace(3.6, 3.8);
            Assert.Equal(new[] { 1.5, 2.4, 3.8 }, mutable);

            var absComparer = new DelegateEqualityComparer <double>(equals: (x, y) => Math.Abs(x) == Math.Abs(y));

            mutable.Replace(-1.5, 1.2, absComparer);
            Assert.Equal(new[] { 1.2, 2.4, 3.8 }, mutable);
        }
Example #17
0
        public void CanMakeEqualityTest()
        {
            var first = new ExampleClass {
                Number = 1, Word = "Hat"
            };
            var second = new ExampleClass {
                Number = 1, Word = "Sock"
            };
            var comparer = new DelegateEqualityComparer <ExampleClass>((c1, c2) => c1.Number == c2.Number);

            var defaultEquals = first == second;
            var result        = comparer.Equals(first, second);

            Assume.That(defaultEquals, Is.False);
            Assert.That(result, Is.True);
        }
Example #18
0
 public AttributesIndex(AttributesIndexMode mode = AttributesIndexMode.ReverseAll)
 {
     this._stringIndex            = new Index <string>();
     this._collectionIndex        = new Index <int[]>();
     this._isReadonly             = false;
     this._mode                   = mode;
     this._stringReverseIndex     = (IDictionary <string, int>)null;
     this._collectionReverseIndex = (IDictionary <int[], uint>)null;
     if ((this._mode & AttributesIndexMode.IncreaseOne) == AttributesIndexMode.IncreaseOne)
     {
         this._index  = (ArrayBase <uint>) new MemoryArray <uint>(1024L);
         this._nextId = 0U;
     }
     if ((this._mode & AttributesIndexMode.ReverseStringIndex) == AttributesIndexMode.ReverseStringIndex || (this._mode & AttributesIndexMode.ReverseStringIndexKeysOnly) == AttributesIndexMode.ReverseStringIndexKeysOnly)
     {
         this._stringReverseIndex = (IDictionary <string, int>) new Reminiscence.Collections.Dictionary <string, int>();
     }
     if ((this._mode & AttributesIndexMode.ReverseCollectionIndex) != AttributesIndexMode.ReverseCollectionIndex)
     {
         return;
     }
     DelegateEqualityComparer <int[]> .GetHashCodeDelegate hashCodeDelegate1 = (DelegateEqualityComparer <int[]> .GetHashCodeDelegate)(obj =>
     {
         int hashCode = obj.Length.GetHashCode();
         for (int index = 0; index < obj.Length; ++index)
         {
             hashCode ^= obj[index].GetHashCode();
         }
         return(hashCode);
     });
     this._collectionReverseIndex = (IDictionary <int[], uint>) new Reminiscence.Collections.Dictionary <int[], uint>((IEqualityComparer <int[]>) new DelegateEqualityComparer <int[]>(hashCodeDelegate1, (DelegateEqualityComparer <int[]> .EqualsDelegate)((x, y) =>
     {
         if (x.Length != y.Length)
         {
             return(false);
         }
         for (int index = 0; index < x.Length; ++index)
         {
             if (x[index] != y[index])
             {
                 return(false);
             }
         }
         return(true);
     })));
 }
        static Tuple <Employee, Employee, EmployeeRelationship>[] GenerateRelationships(IEnumerable <Employee> employees)
        {
            Random rand     = new Random();
            var    comparer = new DelegateEqualityComparer <Tuple <Employee, Employee> >(
                (a, b) => (a.Item1.Equals(b.Item1) && a.Item2.Equals(b.Item2)) || (a.Item1.Equals(b.Item2) && a.Item2.Equals(b.Item1)),
                (item) => item.Item1.GetHashCode() ^ item.Item2.GetHashCode());
            var pairs = employees.SelectMany(employee1 => employees.Select(employee2 => new Tuple <Employee, Employee>(employee1, employee2)))
                        .Where(pair => !pair.Item1.Equals(pair.Item2)).Distinct(comparer).ToArray();
            var relations = new List <Tuple <Employee, Employee, EmployeeRelationship> >();

            pairs.ForEach((pair, index) => {
                if ((index % 4) <= 1)
                {
                    relations.Add(new Tuple <Employee, Employee, EmployeeRelationship>(pair.Item1, pair.Item2, (EmployeeRelationship)(index % 4)));
                }
            });
            return(relations.ToArray());
        }
        public void TryParseOrderByExpressionsWithValidSourceReturnsExpressions(
            string orderBy, OrderByExpression[] expectedExpressions)
        {
            OrderByExpression[] expressions = null;

            var result = orderBy.TryParseOrderByExpressions(out expressions);

            Assert.True(result);

            var comparer = new DelegateEqualityComparer <OrderByExpression>(
                (OrderByExpression x, OrderByExpression y) =>
            {
                return(x.PropertyName == y.PropertyName && x.Direction == y.Direction);
            },
                (OrderByExpression obj) => { return(obj.GetHashCode()); });

            Assert.Equal(expectedExpressions, expressions, comparer);
        }
Example #21
0
        public void Remove_EqualityComparer()
        {
            var mutable = ImmutableList <double> .Empty.ToBuilder();

            mutable.Add(1.5);
            mutable.Add(2.4);
            mutable.Add(3.6);

            Assert.True(mutable.Remove(2.4, null));
            Assert.Equal(new[] { 1.5, 3.6 }, mutable);

            var absComparer = new DelegateEqualityComparer <double>(equals: (x, y) => Math.Abs(x) == Math.Abs(y));

            Assert.True(mutable.Remove(-1.5, absComparer));
            Assert.Equal(new[] { 3.6 }, mutable);

            Assert.False(mutable.Remove(5, absComparer));
            Assert.False(mutable.Remove(5, null));
        }
        private static MethodInfo DetermineMethodFromParams(IEnumerable <MethodInfo> methods, Type genericType, IEnumerable <object> args)
        {
            MethodInfo methodToExecute = null;

            //Given the args, lets get the types and compare the type sequence to try and find the correct overload
            var argTypes = args.Select(o =>
            {
                var oe = (o as Expression);
                return(oe != null ? oe.Type : o.GetType());
            });

            var methodsWithArgTypes = methods.Select(method => new
            {
                method,
                //skip the first arg because that is the extension method type ('this') that we are looking for
                types = method.GetParameters().Select(pi => pi.ParameterType).Skip(1)
            });

            //This type comparer will check
            var typeComparer = new DelegateEqualityComparer <Type>(
                //Checks if the argument type passed in can be assigned from the parameter type in the method. For
                // example, if the argument type is HtmlHelper<MyModel> but the method parameter type is HtmlHelper then
                // it will match because the argument is assignable to that parameter type and will be able to execute
                TypeHelper.IsTypeAssignableFrom,
                //This will not ever execute but if it does we need to get the hash code of the string because the hash
                // code of a type is random
                type => type.FullName.GetHashCode());

            var firstMatchingOverload = methodsWithArgTypes
                                        .FirstOrDefault(m => m.types.SequenceEqual(argTypes, typeComparer));

            if (firstMatchingOverload != null)
            {
                methodToExecute = firstMatchingOverload.method;
            }

            return(methodToExecute);
        }
Example #23
0
        public static void AddRange <T, TSort, TEquality>(
            this ObservableCollection <T> target,
            IEnumerable <T> collection,
            Func <T, TSort> sortSelector,
            Func <T, TEquality> equalitySelector)
            where TSort : IComparable
        {
            var sortComparer = new DelegateComparer <T>(
                (x, y) => sortSelector(x).CompareTo(sortSelector(y)));
            var equalityComparer = new DelegateEqualityComparer <T>(
                (x, y) => equalitySelector(x).Equals(equalitySelector(y)));
            var index = target.Count - 1;

            foreach (var addItem in collection.OrderBy(sortSelector))
            {
                if (index < 0)
                {
                    target.Insert(0, addItem);
                }
                else
                {
                    while (index >= 0)
                    {
                        var currentItem = target[index];
                        if (sortComparer.Compare(currentItem, addItem) >= 0)
                        {
                            if (equalityComparer.Equals(currentItem, addItem) != true)
                            {
                                target.Insert(index + 1, addItem);
                            }
                            break;
                        }
                        index -= 1;
                    }
                }
            }
        }
Example #24
0
        public void RemoveRange()
        {
            var mutable = ImmutableList <double> .Empty.ToBuilder();

            mutable.Add(1.5);
            mutable.Add(2.4);
            mutable.Add(3.6);
            mutable.Add(4.7);
            mutable.Add(5.8);
            mutable.Add(6.2);

            mutable.RemoveRange(4, 2);
            Assert.Equal(new[] { 1.5, 2.4, 3.6, 4.7 }, mutable);

            mutable.RemoveRange(new double[] { 2.4, 3.6 });
            Assert.Equal(new[] { 1.5, 4.7 }, mutable);

            var absComparer = new DelegateEqualityComparer <double>(equals: (x, y) => Math.Abs(x) == Math.Abs(y));

            mutable.RemoveRange(new double[] { -1.5 }, absComparer);
            Assert.Equal(new[] { 4.7 }, mutable);

            AssertExtensions.Throws <ArgumentOutOfRangeException>("index", () => mutable.RemoveRange(2, 3));
        }
        public void GetHashCode_()
        {
            var comparer = new DelegateEqualityComparer <int>((value1, value2) => value1 == value2, value => value);

            Assert.Equal(1234, comparer.GetHashCode(1234));
        }
    protected void ValidateLocked(TItem compositionContentType)
    {
        // performs business-level validation of the composition
        // should ensure that it is absolutely safe to save the composition

        // eg maybe a property has been added, with an alias that's OK (no conflict with ancestors)
        // but that cannot be used (conflict with descendants)

        IContentTypeComposition[] allContentTypes = Repository.GetMany(new int[0]).Cast <IContentTypeComposition>().ToArray();

        IEnumerable <string> compositionAliases            = compositionContentType.CompositionAliases();
        IEnumerable <IContentTypeComposition> compositions = allContentTypes.Where(x => compositionAliases.Any(y => x.Alias.Equals(y)));
        var propertyTypeAliases  = compositionContentType.PropertyTypes.Select(x => x.Alias).ToArray();
        var propertyGroupAliases = compositionContentType.PropertyGroups.ToDictionary(x => x.Alias, x => x.Type, StringComparer.InvariantCultureIgnoreCase);
        IEnumerable <IContentTypeComposition> indirectReferences = allContentTypes.Where(x => x.ContentTypeComposition.Any(y => y.Id == compositionContentType.Id));
        var comparer     = new DelegateEqualityComparer <IContentTypeComposition>((x, y) => x?.Id == y?.Id, x => x.Id);
        var dependencies = new HashSet <IContentTypeComposition>(compositions, comparer);

        var stack = new Stack <IContentTypeComposition>();

        foreach (IContentTypeComposition indirectReference in indirectReferences)
        {
            stack.Push(indirectReference); // push indirect references to a stack, so we can add recursively
        }

        while (stack.Count > 0)
        {
            IContentTypeComposition indirectReference = stack.Pop();
            dependencies.Add(indirectReference);

            // get all compositions for the current indirect reference
            IEnumerable <IContentTypeComposition> directReferences = indirectReference.ContentTypeComposition;
            foreach (IContentTypeComposition directReference in directReferences)
            {
                if (directReference.Id == compositionContentType.Id || directReference.Alias.Equals(compositionContentType.Alias))
                {
                    continue;
                }

                dependencies.Add(directReference);

                // a direct reference has compositions of its own - these also need to be taken into account
                IEnumerable <string> directReferenceGraph = directReference.CompositionAliases();
                foreach (IContentTypeComposition c in allContentTypes.Where(x => directReferenceGraph.Any(y => x.Alias.Equals(y, StringComparison.InvariantCultureIgnoreCase))))
                {
                    dependencies.Add(c);
                }
            }

            // recursive lookup of indirect references
            foreach (IContentTypeComposition c in allContentTypes.Where(x => x.ContentTypeComposition.Any(y => y.Id == indirectReference.Id)))
            {
                stack.Push(c);
            }
        }

        var duplicatePropertyTypeAliases = new List <string>();
        var invalidPropertyGroupAliases  = new List <string>();

        foreach (IContentTypeComposition dependency in dependencies)
        {
            if (dependency.Id == compositionContentType.Id)
            {
                continue;
            }

            IContentTypeComposition?contentTypeDependency = allContentTypes.FirstOrDefault(x => x.Alias.Equals(dependency.Alias, StringComparison.InvariantCultureIgnoreCase));
            if (contentTypeDependency == null)
            {
                continue;
            }

            duplicatePropertyTypeAliases.AddRange(contentTypeDependency.PropertyTypes.Select(x => x.Alias).Intersect(propertyTypeAliases, StringComparer.InvariantCultureIgnoreCase));
            invalidPropertyGroupAliases.AddRange(contentTypeDependency.PropertyGroups.Where(x => propertyGroupAliases.TryGetValue(x.Alias, out PropertyGroupType type) && type != x.Type).Select(x => x.Alias));
        }

        if (duplicatePropertyTypeAliases.Count > 0 || invalidPropertyGroupAliases.Count > 0)

        {
            throw new InvalidCompositionException(compositionContentType.Alias, null, duplicatePropertyTypeAliases.Distinct().ToArray(), invalidPropertyGroupAliases.Distinct().ToArray());
        }
    }
Example #27
0
 /// <summary>The legacy distinct by.</summary>
 /// <param name="source">The source.</param>
 /// <param name="keySelector">The key selector.</param>
 /// <typeparam name="TSource">Source type</typeparam>
 /// <typeparam name="TKey">Key type</typeparam>
 /// <returns>the unique list</returns>
 public static IEnumerable <TSource> LegacyDistinctBy <TSource, TKey>(this IEnumerable <TSource> source, Func <TSource, TKey> keySelector)
     where TKey : IEquatable <TKey>
 {
     return(source.Distinct(DelegateEqualityComparer <TSource> .CompareMember(keySelector)));
 }
Example #28
0
        /// <summary>
        /// Compares two directories with an <see cref="CompareDirectoryOptions" /> parameter specifying the properties to compare.
        /// </summary>
        /// <param name="directory">The <see cref="DirectoryInfo" /> to process.</param>
        /// <param name="other">The other <see cref="DirectoryInfo" /> to compare to <paramref name="directory" />.</param>
        /// <param name="options">The <see cref="CompareDirectoryOptions" /> flags specifying what properties to compare.</param>
        /// <returns>
        /// A value indicating whether the directories are equal.
        /// </returns>
        public static bool Compare(this DirectoryInfo directory, DirectoryInfo other, CompareDirectoryOptions options)
        {
            Check.ArgumentNull(directory, nameof(directory));
            Check.DirectoryNotFound(directory.FullName);
            Check.ArgumentNull(other, nameof(other));
            Check.DirectoryNotFound(other.FullName);

            if (!options.HasFlag(CompareDirectoryOptions.IgnoreDirectories))
            {
                DirectoryInfo[] directoriesA = directory.GetDirectories().OrderBy(d => d.Name).ToArray();
                DirectoryInfo[] directoriesB = other.GetDirectories().OrderBy(d => d.Name).ToArray();

                if (directoriesA.Length == directoriesB.Length)
                {
                    DelegateEqualityComparer <DirectoryInfo> comparer = new DelegateEqualityComparer <DirectoryInfo>((a, b) =>
                                                                                                                     CompareNames(a.Name, b.Name) &&
                                                                                                                     (!options.HasFlag(CompareDirectoryOptions.CompareDirectoryLastWriteTime) || a.LastWriteTime == b.LastWriteTime) &&
                                                                                                                     (!options.HasFlag(CompareDirectoryOptions.Recursive) || a.Compare(b, options))
                                                                                                                     );

                    if (!directoriesA.SequenceEqual(directoriesB, comparer))
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }

            if (!options.HasFlag(CompareDirectoryOptions.IgnoreFiles))
            {
                FileInfo[] filesA = directory.GetFiles().OrderBy(f => f.Name).ToArray();
                FileInfo[] filesB = other.GetFiles().OrderBy(f => f.Name).ToArray();

                if (filesA.Length == filesB.Length)
                {
                    DelegateEqualityComparer <FileInfo> comparer = new DelegateEqualityComparer <FileInfo>((a, b) =>
                                                                                                           CompareNames(a.Name, b.Name) &&
                                                                                                           (!options.HasFlag(CompareDirectoryOptions.CompareFileLastWriteTime) || a.LastWriteTime == b.LastWriteTime) &&
                                                                                                           (!options.HasFlag(CompareDirectoryOptions.CompareFileContents) || a.CompareContents(b)) &&
                                                                                                           (!options.HasFlag(CompareDirectoryOptions.CompareFileSize) || a.Length == b.Length)
                                                                                                           );

                    if (!filesA.SequenceEqual(filesB, comparer))
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }

            return(true);

            bool CompareNames(string nameA, string nameB)
            {
                return(nameA.Equals(nameB, options.HasFlag(CompareDirectoryOptions.IgnoreCase) ? SpecialStringComparisons.IgnoreCase : SpecialStringComparisons.None));
            }
        }
Example #29
0
        private void ValidateLocked(IContentTypeComposition compositionContentType)
        {
            // performs business-level validation of the composition
            // should ensure that it is absolutely safe to save the composition

            // eg maybe a property has been added, with an alias that's OK (no conflict with ancestors)
            // but that cannot be used (conflict with descendants)

            var contentType = compositionContentType as IContentType;
            var mediaType   = compositionContentType as IMediaType;

            IContentTypeComposition[] allContentTypes;
            if (contentType != null)
            {
                allContentTypes = GetAllContentTypes().Cast <IContentTypeComposition>().ToArray();
            }
            else if (mediaType != null)
            {
                allContentTypes = GetAllMediaTypes().Cast <IContentTypeComposition>().ToArray();
            }
            else
            {
                throw new Exception("Composition is neither IContentType nor IMediaType?");
            }

            var compositionAliases  = compositionContentType.CompositionAliases();
            var compositions        = allContentTypes.Where(x => compositionAliases.Any(y => x.Alias.Equals(y)));
            var propertyTypeAliases = compositionContentType.PropertyTypes.Select(x => x.Alias.ToLowerInvariant()).ToArray();
            var indirectReferences  = allContentTypes.Where(x => x.ContentTypeComposition.Any(y => y.Id == compositionContentType.Id));
            var comparer            = new DelegateEqualityComparer <IContentTypeComposition>((x, y) => x.Id == y.Id, x => x.Id);
            var dependencies        = new HashSet <IContentTypeComposition>(compositions, comparer);
            var stack = new Stack <IContentTypeComposition>();

            indirectReferences.ForEach(stack.Push);//Push indirect references to a stack, so we can add recursively
            while (stack.Count > 0)
            {
                var indirectReference = stack.Pop();
                dependencies.Add(indirectReference);
                //Get all compositions for the current indirect reference
                var directReferences = indirectReference.ContentTypeComposition;

                foreach (var directReference in directReferences)
                {
                    if (directReference.Id == compositionContentType.Id || directReference.Alias.Equals(compositionContentType.Alias))
                    {
                        continue;
                    }
                    dependencies.Add(directReference);
                    //A direct reference has compositions of its own - these also need to be taken into account
                    var directReferenceGraph = directReference.CompositionAliases();
                    allContentTypes.Where(x => directReferenceGraph.Any(y => x.Alias.Equals(y, StringComparison.InvariantCultureIgnoreCase))).ForEach(c => dependencies.Add(c));
                }
                //Recursive lookup of indirect references
                allContentTypes.Where(x => x.ContentTypeComposition.Any(y => y.Id == indirectReference.Id)).ForEach(stack.Push);
            }

            foreach (var dependency in dependencies)
            {
                if (dependency.Id == compositionContentType.Id)
                {
                    continue;
                }
                var contentTypeDependency = allContentTypes.FirstOrDefault(x => x.Alias.Equals(dependency.Alias, StringComparison.InvariantCultureIgnoreCase));
                if (contentTypeDependency == null)
                {
                    continue;
                }
                var intersect = contentTypeDependency.PropertyTypes.Select(x => x.Alias.ToLowerInvariant()).Intersect(propertyTypeAliases).ToArray();
                if (intersect.Length == 0)
                {
                    continue;
                }

                var message = string.Format("The following PropertyType aliases from the current ContentType conflict with existing PropertyType aliases: {0}.",
                                            string.Join(", ", intersect));
                throw new Exception(message);
            }
        }
        protected void ValidateLocked(TItem compositionContentType)
        {
            // performs business-level validation of the composition
            // should ensure that it is absolutely safe to save the composition

            // eg maybe a property has been added, with an alias that's OK (no conflict with ancestors)
            // but that cannot be used (conflict with descendants)

            var allContentTypes = Repository.GetMany(new int[0]).Cast <IContentTypeComposition>().ToArray();

            var compositionAliases  = compositionContentType.CompositionAliases();
            var compositions        = allContentTypes.Where(x => compositionAliases.Any(y => x.Alias.Equals(y)));
            var propertyTypeAliases = compositionContentType.PropertyTypes.Select(x => x.Alias.ToLowerInvariant()).ToArray();
            var indirectReferences  = allContentTypes.Where(x => x.ContentTypeComposition.Any(y => y.Id == compositionContentType.Id));
            var comparer            = new DelegateEqualityComparer <IContentTypeComposition>((x, y) => x.Id == y.Id, x => x.Id);
            var dependencies        = new HashSet <IContentTypeComposition>(compositions, comparer);
            var stack = new Stack <IContentTypeComposition>();

            foreach (var indirectReference in indirectReferences)
            {
                stack.Push(indirectReference); // push indirect references to a stack, so we can add recursively
            }
            while (stack.Count > 0)
            {
                var indirectReference = stack.Pop();
                dependencies.Add(indirectReference);

                // get all compositions for the current indirect reference
                var directReferences = indirectReference.ContentTypeComposition;
                foreach (var directReference in directReferences)
                {
                    if (directReference.Id == compositionContentType.Id || directReference.Alias.Equals(compositionContentType.Alias))
                    {
                        continue;
                    }
                    dependencies.Add(directReference);
                    // a direct reference has compositions of its own - these also need to be taken into account
                    var directReferenceGraph = directReference.CompositionAliases();
                    foreach (var c in allContentTypes.Where(x => directReferenceGraph.Any(y => x.Alias.Equals(y, StringComparison.InvariantCultureIgnoreCase))))
                    {
                        dependencies.Add(c);
                    }
                }

                // recursive lookup of indirect references
                foreach (var c in allContentTypes.Where(x => x.ContentTypeComposition.Any(y => y.Id == indirectReference.Id)))
                {
                    stack.Push(c);
                }
            }

            foreach (var dependency in dependencies)
            {
                if (dependency.Id == compositionContentType.Id)
                {
                    continue;
                }
                var contentTypeDependency = allContentTypes.FirstOrDefault(x => x.Alias.Equals(dependency.Alias, StringComparison.InvariantCultureIgnoreCase));
                if (contentTypeDependency == null)
                {
                    continue;
                }
                var intersect = contentTypeDependency.PropertyTypes.Select(x => x.Alias.ToLowerInvariant()).Intersect(propertyTypeAliases).ToArray();
                if (intersect.Length == 0)
                {
                    continue;
                }

                throw new InvalidCompositionException(compositionContentType.Alias, intersect.ToArray());
            }
        }
        public void TryParseOrderByExpressionsWithValidSourceReturnsExpressions(
            string orderBy, OrderByExpression[] expectedExpressions)
        {
            OrderByExpression[] expressions = null;

            var result = orderBy.TryParseOrderByExpressions(out expressions);

            Assert.True(result);

            var comparer = new DelegateEqualityComparer<OrderByExpression>(
                (OrderByExpression x, OrderByExpression y) =>
                {
                    return x.PropertyName == y.PropertyName && x.Direction == y.Direction;
                },
                (OrderByExpression obj) => { return obj.GetHashCode(); });

            Assert.Equal(expectedExpressions, expressions, comparer);
        }
        public void Equals_CompareEqualTwoIntegers_ReturnTrue()
        {
            var comparer = new DelegateEqualityComparer <int>((value1, value2) => value1 == value2);

            Assert.True(comparer.Equals(1234, 1234));
        }
Example #33
0
        /// <summary>
        /// Distinct by delegate.
        /// </summary>
        public static IEnumerable <T> DistinctBy <T>(this IEnumerable <T> source, Func <T, T, bool> equals)
        {
            var comparer = new DelegateEqualityComparer <T>(equals);

            return(source.Distinct(comparer));
        }