public void EqualsArray()
        {
            var now    = DateTime.Now;
            var array1 = new object[]
            {
                "string",
                123,
                123.5d,
                45.67m,
                now
            };
            var array2 = new object[]
            {
                "string",
                123,
                123.5d,
                45.67m,
                now
            };
            var array3 = new object[]
            {
                "string",
                444,
                123.5d,
                45.67m,
                now
            };

            Assert.AreEqual(true, DefaultComparer.Equals(array1, array1));
            Assert.AreEqual(true, DefaultComparer.Equals(array1, array2));
            Assert.AreEqual(false, DefaultComparer.Equals(array1, array3));
        }
Ejemplo n.º 2
0
        public override bool Equals(object obj)
        {
            if (!(obj is TestStructClean))
            {
                return(false);
            }
            var other = (TestStructClean)obj;

            return
                (DefaultComparer.Equals(this.Arr, other.Arr) &&
                 Equals(this.B, other.B) &&
                 Equals(this.C, other.C) &&
                 Equals(this.ConStr, other.ConStr) &&
                 Equals(this.D, other.D) &&
                 Equals(this.Date, other.Date) &&
                 Equals(this.Dec, other.Dec) &&
                 Equals(this.F, other.F) &&
                 Equals(this.I, other.I) &&
                 Equals(this.S, other.S) &&
                 Equals(this.SB, other.SB) &&
                 Equals(this.Text, other.Text) &&
                 Equals(this.Time, other.Time) &&
                 Equals(this.UI, other.UI) &&
                 Equals(this.Uri, other.Uri) &&
                 Equals(this.US, other.US));
        }
Ejemplo n.º 3
0
        public void Equals_Check(int?testValue1, int?testValue2, bool expected)
        {
            var comparer = new DefaultComparer();
            var result   = comparer.Equals(testValue1, testValue2);

            Assert.Equal(expected, result);
        }
        public async Task LicensesEqual()
        {
            const string MIT = @"MIT License

Copyright (c) [year] [fullname]

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the ""Software""), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/ or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.";

            string license = await new GitHubLicenseUrlReader()
                             .GetLicenseTextAsync("https://raw.githubusercontent.com/lvermeulen/Flurl.Http.Xml/master/LICENSE");

            var  comparer = new DefaultComparer(MIT);
            bool equal    = comparer.Equals(license);

            Assert.True(equal);
        }
Ejemplo n.º 5
0
        public RecordCollection Records()
        {
            XElement documentElement = XDocument.FirstElement();

            if (documentElement == null ||
                !DefaultComparer.NameEquals(documentElement, ElementNames.Document))
            {
                ThrowInvalidOperation(ErrorMessages.MissingElement(ElementNames.Document));
            }

            string versionText = documentElement.AttributeValueOrDefault(AttributeNames.Version);

            if (versionText != null)
            {
                if (!Version.TryParse(versionText, out Version version))
                {
                    ThrowInvalidOperation(ErrorMessages.InvalidDocumentVersion());
                }
                else if (version > SchemaVersion)
                {
                    ThrowInvalidOperation(ErrorMessages.DocumentVersionIsNotSupported(version, SchemaVersion));
                }
            }

            XElement entitiesElement = EntitiesElement(documentElement);

            if (entitiesElement != null)
            {
                return(ReadRecords(entitiesElement.Elements()));
            }
            else
            {
                return(Empty.RecordCollection);
            }
        }
Ejemplo n.º 6
0
        internal PropertyDefinition(
            string name,
            string type,
            string defaultValue = null,
            bool isCollection   = false,
            XElement element    = null)
        {
            if (!object.ReferenceEquals(name, IdName))
            {
                if (DefaultComparer.NameEquals(name, Id.Name))
                {
                    ThrowHelper.ThrowInvalidOperation(ExceptionMessages.PropertyNameIsReserved(Id.Name), element);
                }

                if (DefaultComparer.NameEquals(name, AttributeNames.Tag))
                {
                    ThrowHelper.ThrowInvalidOperation(ExceptionMessages.PropertyNameIsReserved(AttributeNames.Tag), element);
                }
            }

            Name         = name;
            Type         = type;
            DefaultValue = defaultValue;
            IsCollection = isCollection;
        }
Ejemplo n.º 7
0
        public bool Contains(KeyValuePair <long, TValue> item)
        {
            TValue value;

            return(TryGetValue(item.Key, out value) &&
                   DefaultComparer.Compare(value, item.Value) == 0);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Writes all fields of the object to the specified section (replacing a present one).
        /// </summary>
        /// <param name="section">The section to write to.</param>
        /// <param name="type">Type of <paramref name="item"/></param>
        /// <param name="item">The instance to write.</param>
        public void WriteFields(string section, Type type, object item)
        {
            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }

            foreach (var field in item.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                if (field.HasAttribute <IniIgnoreAttribute>())
                {
                    continue;
                }

                var value = field.GetValue(item);

                if (field.HasAttribute <IniSectionAttribute>())
                {
                    var sectionAttribute = field.GetAttribute <IniSectionAttribute>();
                    if (value is null)
                    {
                        continue;
                    }

                    if (value is IEnumerable enumerable)
                    {
                        throw new NotSupportedException("Arrays are not (yet) supported!");
                    }

                    switch (sectionAttribute.SettingsType)
                    {
                    case IniSettingsType.Fields: WriteFields(sectionAttribute.Name ?? field.Name, field.FieldType, value); continue;

                    case IniSettingsType.Properties: WriteProperties(sectionAttribute.Name ?? field.Name, field.FieldType, value); continue;

                    default: throw new NotImplementedException($"IniSettingsType.{sectionAttribute.SettingsType} not implemented at {GetType()}!");
                    }
                }
                else if (!SkipRoundTripTests)
                {
                    //roundtrip test
                    try
                    {
                        var data      = StringExtensions.ToString(value, Properties.Culture);
                        var test      = TypeExtension.ConvertValue(field.FieldType, data, Properties.Culture);
                        var container = Activator.CreateInstance(type);
                        field.SetValue(container, test);
                        if (!DefaultComparer.Equals(test, value))
                        {
                            throw new InvalidDataException($"Equals test at field {field} failed! Value = {test}, expected = {value}");
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new InvalidDataException($"Roundtrip w/r test for field {field} failed!", ex);
                    }
                }
                WriteSetting(section, field.Name, value);
            }
        }
        public void Compare_ForLineWithoutStringButNumber_TakesNumberForZero2()
        {
            var comparer = new DefaultComparer();

            var difference = comparer.Compare(" Hello World", "3. Hello World");

            Assert.Equal(-1, difference);
        }
Ejemplo n.º 10
0
        public void GetHashCode_Int_ZeroCheck(int?testValue, bool expected)
        {
            var comparer = new DefaultComparer();
            var hasCode  = comparer.GetHashCode(testValue);
            var result   = hasCode == 0;

            Assert.Equal(expected, result);
        }
 /// <summary>
 /// Returns distinct elements from a sequence by using a specified <see cref="T:System.Collections.Generic.IEqualityComparer`1"/> to compare values.
 /// </summary>
 /// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam>
 /// <param name="source">The sequence to remove duplicate elements from.</param>
 /// <param name="comparer">An <see cref="T:System.Collections.Generic.IEqualityComparer`1"/> to compare values.</param>
 /// <returns>
 /// An <see cref="IBindableCollection{TElement}"/> that contains distinct elements from the source sequence.
 /// </returns>
 /// <exception cref="T:System.ArgumentNullException">
 ///     <paramref name="source"/> is null.</exception>
 public static IBindableCollection <TSource> Distinct <TSource>(this IBindableCollection <TSource> source, IEqualityComparer <TSource> comparer) where TSource : class
 {
     if (comparer == null)
     {
         comparer = new DefaultComparer <TSource>();
     }
     return(source.GroupBy(c => comparer.GetHashCode(c), DependencyDiscovery.Disabled).Select(group => group.First().Current, DependencyDiscovery.Disabled));
 }
        public void Compare_ForNullArguments_ThrowsNoExceptions()
        {
            var comparer = new DefaultComparer();

            var difference = comparer.Compare(null, null);

            Assert.Equal(0, difference);
        }
        public void Compare_ForLineWithoutNumber_ComparesStrings()
        {
            var comparer = new DefaultComparer();

            var difference = comparer.Compare("Beaver", "Chipmunk");

            Assert.Equal(-1, difference);
        }
        public void Compare_ForEmptyArguments_ThrowsNoExceptions()
        {
            var comparer = new DefaultComparer();

            var difference = comparer.Compare(string.Empty, string.Empty);

            Assert.Equal(0, difference);
        }
Ejemplo n.º 15
0
        private Record CreateRecord(XElement element)
        {
            string id = null;

            Collection <IPropertyOperation> operations = null;

            foreach (XAttribute attribute in element.Attributes())
            {
                if (DefaultComparer.NameEquals(attribute, AttributeNames.Id))
                {
                    id = GetValue(attribute);
                }
                else
                {
                    IPropertyOperation operation = CreateOperationFromAttribute(element, attribute);

                    (operations ?? (operations = new Collection <IPropertyOperation>())).Add(operation);
                }
            }

            Record record = CreateRecord(id);

            operations?.ExecuteAll(record);

            ExecuteChildOperations(element, record);

            ExecutePendingOperations(record);

            foreach (PropertyDefinition property in Entity.AllProperties())
            {
                if (property.DefaultValue != null)
                {
                    if (!record.ContainsProperty(property.Name))
                    {
                        if (property.IsCollection)
                        {
                            record[property.Name] = new List <object>()
                            {
                                property.DefaultValue
                            };
                        }
                        else
                        {
                            record[property.Name] = property.DefaultValue;
                        }
                    }
                }
                else if (ShouldCheckRequiredProperty &&
                         property.IsRequired &&
                         !record.ContainsProperty(property.Name))
                {
                    Throw(ErrorMessages.PropertyIsRequired(property.Name));
                }
            }

            return(record);
        }
Ejemplo n.º 16
0
 static EqualityComparer()
 {
     if (typeof(IEquatable <T>).IsAssignableFrom(typeof(T)))
     {
         _default = (EqualityComparer <T>)Activator.CreateInstance(typeof(IEquatableOfTEqualityComparer <>).MakeGenericType(typeof(T)));
     }
     else
     {
         _default = new DefaultComparer();
     }
 }
Ejemplo n.º 17
0
        public bool Contains(KeyValuePair <string, TValue> item)
        {
            KeyWalker kw    = StringToBytes(item.Key);
            TValue    value = default(TValue);

            if (base.Find(ref kw, ref value))
            {
                return(DefaultComparer.Compare(value, item.Value) == 0);
            }
            return(false);
        }
Ejemplo n.º 18
0
        public bool Contains(KeyValuePair <byte[], TValue> item)
        {
            KeyWalker kw    = new KeyWalker(item.Key, item.Key.Length);
            TValue    value = default(TValue);

            if (base.Find(ref kw, ref value))
            {
                return(DefaultComparer.Compare(value, item.Value) == 0);
            }
            return(false);
        }
Ejemplo n.º 19
0
        private XElement DocumentElement()
        {
            XElement element = XDocument.Elements().FirstOrDefault();

            if (element == null || !DefaultComparer.NameEquals(element, ElementNames.Document))
            {
                ThrowHelper.ThrowInvalidOperation(ExceptionMessages.MissingElement(ElementNames.Document));
            }

            return(element);
        }
Ejemplo n.º 20
0
        public static DefaultComparer <T> BindDefaultSearch <T>(RangeListView lv, string id, bool enableAlphaNum = false)
        {
            if (!_defaultSearches.ContainsKey(lv))
            {
                _defaultSearches[lv] = new DefaultComparer <T>(enableAlphaNum);
            }

            DefaultComparer <T> comparer = (DefaultComparer <T>)_defaultSearches[lv];

            lv.Dispatch(p => comparer.SetOrder(WpfUtils.GetLastGetSearchAccessor(lv) ?? id, WpfUtils.GetLastSortDirection(lv)));
            return(comparer);
        }
Ejemplo n.º 21
0
        public bool Remove(KeyValuePair <long, TValue> item)
        {
            KeyWalker kw    = Encode(item.Key);
            KeyWalker kw2   = kw;
            TValue    value = default(TValue);

            if (Find(ref kw, ref value) && DefaultComparer.Compare(value, item.Value) == 0)
            {
                return(Remove(ref kw2, ref value));
            }
            return(false);
        }
Ejemplo n.º 22
0
        public bool Remove(KeyValuePair <byte[], TValue> item)
        {
            KeyWalker kw    = new KeyWalker(item.Key, item.Key.Length);
            KeyWalker kw2   = kw;
            TValue    value = default(TValue);

            if (Find(ref kw, ref value) && DefaultComparer.Compare(value, item.Value) == 0)
            {
                return(Remove(ref kw2, ref value));
            }
            return(false);
        }
Ejemplo n.º 23
0
        private Operation CreateOperationFromAttribute(
            XElement element,
            ElementKind kind,
            XAttribute attribute,
            bool throwOnId = false)
        {
            string attributeName = attribute.LocalName();

            if (throwOnId &&
                DefaultComparer.NameEquals(attributeName, AttributeNames.Id))
            {
                Throw(ErrorMessages.CannotUseOperationOnProperty(element, attributeName));
            }

            PropertyDefinition property;

            string name = attribute.LocalName();

            if (name == PropertyDefinition.TagsName)
            {
                property = PropertyDefinition.Tags;
            }
            else
            {
                property = GetProperty(attribute);
            }

            switch (kind)
            {
            case ElementKind.With:
            {
                return(new Operation(property, GetValue(attribute), _depth, OperationKind.With));
            }

            case ElementKind.Without:
            {
                if (!property.IsCollection)
                {
                    Throw(ErrorMessages.CannotUseOperationOnNonCollectionProperty(element, property.Name));
                }

                return(new Operation(property, GetValue(attribute), _depth, OperationKind.Without));
            }

            default:
            {
                Debug.Assert(kind == ElementKind.New, kind.ToString());

                return(new Operation(property, GetValue(attribute), _depth, OperationKind.With));
            }
            }
        }
Ejemplo n.º 24
0
        public static int BinarySearchFromTo <T>(this List <T> list, T item, int from, int to)
        {
            var dc = new DefaultComparer <T>();

            if (from > to)
            {
                throw new IndexOutOfRangeException();
            }

            int count = to - from;

            return(list.BinarySearch(from, count, item, dc));
        }
Ejemplo n.º 25
0
        internal SortedBuffer(C comparerInstance)
        {
            this.size   = 0;
            this.buffer = null;

            if (Comparer == null)
            {
                Comparer = new DefaultComparer(comparerInstance);
            }
            else
            {
                Fx.Assert(object.ReferenceEquals(DefaultComparer.Comparer, comparerInstance), "The SortedBuffer type has already been initialized with a different comparer instance.");
            }
        }
Ejemplo n.º 26
0
        internal SortedBuffer(C comparerInstance)
        {
            Count   = 0;
            _buffer = null;

            if (s_comparer == null)
            {
                s_comparer = new DefaultComparer(comparerInstance);
            }
            else
            {
                Fx.Assert(ReferenceEquals(DefaultComparer.Comparer, comparerInstance), "The SortedBuffer type has already been initialized with a different comparer instance.");
            }
        }
Ejemplo n.º 27
0
        private Record CreateRecord(XElement element)
        {
            string id = null;

            Collection <Operation> operations = null;

            foreach (XAttribute attribute in element.Attributes())
            {
                if (DefaultComparer.NameEquals(attribute, AttributeNames.Id))
                {
                    id = GetValue(attribute);
                }
                else
                {
                    Operation operation = CreateOperationFromAttribute(element, ElementKind.New, attribute);

                    (operations ?? (operations = new Collection <Operation>())).Add(operation);
                }
            }

            Record record = CreateRecord(id);

            if (operations != null)
            {
                ExecuteAll(operations, record);
            }

            ExecuteChildOperations(element, record);

            ExecutePendingOperations(record);

            foreach (PropertyDefinition property in _entityDefinition.AllProperties())
            {
                if (property.DefaultValue != null)
                {
                    if (!record.ContainsProperty(property.Name))
                    {
                        record[property.Name] = property.DefaultValue;
                    }
                }
                else if (_state == State.Records &&
                         property.IsRequired &&
                         !record.ContainsProperty(property.Name))
                {
                    Throw(ErrorMessages.PropertyIsRequired(property.Name));
                }
            }

            return(record);
        }
Ejemplo n.º 28
0
        internal Variable FindVariable(string name)
        {
            if (_variables != null)
            {
                Variable variable = _variables.FirstOrDefault(f => DefaultComparer.NameEquals(name, f.Name));

                if (!variable.IsDefault)
                {
                    return(variable);
                }
            }

            return(_entityDefinition.FindVariable(name));
        }
Ejemplo n.º 29
0
        internal Variable FindVariable(string name)
        {
            if (Variables != null)
            {
                Variable variable = Variables.FirstOrDefault(f => DefaultComparer.NameEquals(name, f.Name));

                if (variable != null)
                {
                    return(variable);
                }
            }

            return(Entity.FindVariable(name));
        }
Ejemplo n.º 30
0
        public static void InsertIntoList <T>(RangeListView lv, T item, IList <T> allItems)
        {
            if (!_defaultSearches.ContainsKey(lv))
            {
                _defaultSearches[lv] = new DefaultComparer <T>();
            }

            DefaultComparer <T> comparer = (DefaultComparer <T>)_defaultSearches[lv];
            var index = allItems.ToList().BinarySearch(item, comparer);

            if (index < 0)
            {
                index = ~index;
            }
            allItems.Insert(index, item);
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Parses an individual comparer.
        /// </summary>
        /// <param name="lexer">the lexer to read the tokens from</param>
        /// <param name="defaultFormat">the default format</param>
        /// <returns>a single <see cref="IComparer{T}"/></returns>
        private IComparer<byte[]> ParseComparer(Lexer lexer, string defaultFormat)
        {
            var start = lexer.ParseInt() - 1;
            var length = lexer.ParseInt();
            string format;

            if (lexer.Current == AscendingOrder || lexer.Current == DescendingOrder)
            {
                // if we have the order token no format is specified, thus use the default one
                format = defaultFormat;
            }
            else
            {
                // otherwise the current token is the format
                format = lexer.Parse();
            }
            var ascending = lexer.Current == AscendingOrder;

            IComparer<byte[]> comparer;
            if (format == StringFormat)
            {
                comparer = new StringComparer
                {
                    Encoding = Encoding,
                    SortEncoding = SortEncoding,
                    Ascending = ascending,
                    Start = start,
                    Length = length
                };
            }
            else
            {
                var accessor = GetAccessor(start, length, format, Encoding) as IAccessor<decimal>;
                comparer = new DefaultComparer<decimal> { Ascending = ascending, Accessor = accessor };
            }

            return comparer;
        }
Ejemplo n.º 32
0
        protected virtual bool UpdateVariableValues(MultivariateTestVariableItem variableItem, out List<ID> modifiedVariations)
        {
            Assert.ArgumentNotNull(variableItem, "variableItem");
            modifiedVariations = new List<ID>();
            List<VariableValueItemStub> variableValues = VariableValues;
            var list2 = new List<MultivariateTestValueItem>(TestingUtil.MultiVariateTesting.GetVariableValues(variableItem));
            var comparer = new DefaultComparer();
            list2.Sort((lhs, rhs) => comparer.Compare(lhs, rhs));
            int num = (list2.Count > 0) ? (list2[0].InnerItem.Appearance.Sortorder - 1) : Settings.DefaultSortOrder;
            var templateID = new TemplateID(MultivariateTestValueItem.TemplateID);
            var list3 = new List<KeyValuePair<MultivariateTestValueItem, VariableValueItemStub>>();
            var list4 = new List<KeyValuePair<int, VariableValueItemStub>>();
            for (int i = variableValues.Count - 1; i >= 0; i--)
            {
                VariableValueItemStub stub = variableValues[i];
                ID currentId = stub.Id;
                int index = list2.FindIndex(item => item.ID == currentId);
                if (index < 0)
                {
                    var pair = new KeyValuePair<int, VariableValueItemStub>(num--, stub);
                    list4.Add(pair);
                }
                else
                {
                    MultivariateTestValueItem item = list2[index];
                    if (IsVariableValueChanged(item, stub))
                    {
                        list3.Add(new KeyValuePair<MultivariateTestValueItem, VariableValueItemStub>(item, stub));
                    }
                    list2.RemoveAt(index);
                }
            }
            if (list2.Count != 0)
            {
            }

                foreach (Item item2 in list2)
                {
                    modifiedVariations.Add(item2.ID);
                    item2.Delete();
                }
                foreach (var pair2 in list4)
                {
                    VariableValueItemStub variableStub = pair2.Value;
                    int key = pair2.Key;
                    string name = variableStub.Name;
                    if (ContainsNonASCIISymbols(name))
                    {
                        Item item3 = variableItem.Database.GetItem(templateID.ID);
                        name = (item3 != null) ? item3.Name : "Unnamed item";
                    }
                    if (!ItemUtil.IsItemNameValid(name))
                    {
                        try
                        {
                            name = ItemUtil.ProposeValidItemName(name);
                        }
                        catch (Exception)
                        {
                            return false;
                        }
                    }
                    name = ItemUtil.GetUniqueName(variableItem, name);
                    Item item4 = variableItem.InnerItem.Add(name, templateID);
                    Assert.IsNotNull(item4, "newVariableValue");
                    UpdateVariableValueItem((MultivariateTestValueItem) item4, variableStub, key);
                }
                foreach (var pair3 in list3)
                {
                    MultivariateTestValueItem variableValue = pair3.Key;
                    VariableValueItemStub stub3 = pair3.Value;
                    modifiedVariations.Add(variableValue.ID);
                    UpdateVariableValueItem(variableValue, stub3);
                }
            return true;
        }