Ejemplo n.º 1
0
        public async Task MoveFileAsync()
        {
            var ct   = CancellationToken.None;
            var root = await FileSystem.Root.ConfigureAwait(false);

            var doc1 = await root.CreateDocumentAsync("text1.txt", ct).ConfigureAwait(false);

            await doc1.FillWithAsync("Dokument 1", ct).ConfigureAwait(false);

            Assert.Equal("Dokument 1", await doc1.ReadAllAsync(ct).ConfigureAwait(false));
            var props1 = await doc1.GetPropertyElementsAsync(Dispatcher, ct).ConfigureAwait(false);

            var response = await Client
                           .MoveAsync(
                new Uri(Client.BaseAddress, new Uri("text1.txt", UriKind.Relative)),
                new Uri(Client.BaseAddress, new Uri("text2.txt", UriKind.Relative)))
                           .ConfigureAwait(false);

            Assert.True(response.IsSuccessStatusCode);

            var child = await root.GetChildAsync("text2.txt", ct).ConfigureAwait(false);

            var doc2   = Assert.IsType <InMemoryFile>(child);
            var props2 = await doc2.GetPropertyElementsAsync(Dispatcher, ct).ConfigureAwait(false);

            var changes = PropertyComparer.FindChanges(props1, props2, _propsToIgnoreDocument);

            Assert.Empty(changes);
        }
Ejemplo n.º 2
0
        public static Dictionary <string, int> GetContragentDictionary(IEnumerable <string> list, bool code1C)
        {
            using (var ctx = new DBEntities(60 * 10))
            {
                var result = new Dictionary <string, int>();

                if (code1C)
                {
                    var comparer = new PropertyComparer <KeyValue>("Key");
                    return(ctx.T_Contragent
                           .Where(c => list.Contains(c.Code1C))
                           .Select(c => new KeyValue {
                        Key = c.Code1C, Value = c.ID
                    })
                           .ToList()
                           .Distinct(comparer)
                           .ToDictionary(x => x.Key, x => x.Value));
                }
                else
                {
                    var comparer = new PropertyComparer <KeyValue>("Key");
                    return(ctx.T_Contragent
                           .Where(c => list.Contains(c.PersonalNumber))
                           .Select(c => new KeyValue {
                        Key = c.PersonalNumber, Value = c.ID
                    })
                           .ToList()
                           .Distinct(comparer)
                           .ToDictionary(x => x.Key, x => x.Value));
                }
            }
        }
Ejemplo n.º 3
0
        public async Task MoveEmptyDirectoryAsync()
        {
            var ct   = CancellationToken.None;
            var root = await FileSystem.Root.ConfigureAwait(false);

            var coll1 = await root.CreateCollectionAsync("test1", ct).ConfigureAwait(false);

            Assert.NotNull(coll1);
            var props1 = await coll1.GetPropertyElementsAsync(Dispatcher, ct).ConfigureAwait(false);

            var response = await Client
                           .MoveAsync(
                new Uri(Client.BaseAddress, new Uri("test1", UriKind.Relative)),
                new Uri(Client.BaseAddress, new Uri("test2", UriKind.Relative)))
                           .ConfigureAwait(false);

            Assert.True(response.IsSuccessStatusCode);

            var child = await root.GetChildAsync("test2", ct).ConfigureAwait(false);

            var coll2  = Assert.IsType <InMemoryDirectory>(child);
            var props2 = await coll2.GetPropertyElementsAsync(Dispatcher, ct).ConfigureAwait(false);

            var changes = PropertyComparer.FindChanges(props1, props2, _propsToIgnoreCollection);

            Assert.Empty(changes);
        }
Ejemplo n.º 4
0
        public async Task CopyDirectoryWithSubDirectoryAndFileDepthInfinityAsync()
        {
            var ct   = CancellationToken.None;
            var root = await FileSystem.Root.ConfigureAwait(false);

            var coll1 = await root.CreateCollectionAsync("test1", ct).ConfigureAwait(false);

            Assert.NotNull(coll1);

            var sub1 = await coll1.CreateCollectionAsync("subcoll", ct).ConfigureAwait(false);

            var doc1 = await sub1.CreateDocumentAsync("text.txt", ct).ConfigureAwait(false);

            await doc1.FillWithAsync("Dokument 1", ct).ConfigureAwait(false);

            Assert.Equal("Dokument 1", await doc1.ReadAllAsync(ct).ConfigureAwait(false));

            var props1 = await coll1.GetPropertyElementsAsync(Dispatcher, ct).ConfigureAwait(false);

            var subProps1 = await sub1.GetPropertyElementsAsync(Dispatcher, ct).ConfigureAwait(false);

            var docProps1 = await doc1.GetPropertyElementsAsync(Dispatcher, ct).ConfigureAwait(false);

            var response = await Client
                           .CopyAsync(
                new Uri(Client.BaseAddress, new Uri("test1", UriKind.Relative)),
                new Uri(Client.BaseAddress, new Uri("test2", UriKind.Relative)),
                true,
                WebDavDepthHeaderValue.Infinity)
                           .ConfigureAwait(false);

            Assert.True(response.IsSuccessStatusCode);

            var child = await root.GetChildAsync("test2", ct).ConfigureAwait(false);

            var coll2  = Assert.IsType <InMemoryDirectory>(child);
            var props2 = await coll2.GetPropertyElementsAsync(Dispatcher, ct).ConfigureAwait(false);

            var changes = PropertyComparer.FindChanges(props1, props2, _propsToIgnoreCollection);

            Assert.Empty(changes);

            var subChild = await coll2.GetChildAsync("subcoll", ct).ConfigureAwait(false);

            var sub2      = Assert.IsType <InMemoryDirectory>(subChild);
            var subProps2 = await sub2.GetPropertyElementsAsync(Dispatcher, ct).ConfigureAwait(false);

            var subChanges = PropertyComparer.FindChanges(subProps1, subProps2, _propsToIgnoreCollection);

            Assert.Empty(subChanges);

            var docChild = await sub2.GetChildAsync("text.txt", ct).ConfigureAwait(false);

            var doc2      = Assert.IsType <InMemoryFile>(docChild);
            var docProps2 = await doc2.GetPropertyElementsAsync(Dispatcher, ct).ConfigureAwait(false);

            var docChanges = PropertyComparer.FindChanges(docProps1, docProps2, _propsToIgnoreDocument);

            Assert.Empty(docChanges);
        }
    static PropertyCompare()
    {
        PropertyInfo[] properties   = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);
        var            firstObject  = Expression.Parameter(typeof(T), "a");
        var            secondObject = Expression.Parameter(typeof(T), "b");

        PropertyComparer <T>[] propertyComparers = new PropertyComparer <T> [properties.Length];
        for (int i = 0; i < properties.Length; i++)
        {
            PropertyInfo thisProperty       = properties[i];
            Expression   arePropertiesEqual = Expression.Equal(Expression.Property(firstObject, thisProperty), Expression.Property(secondObject, thisProperty));
            Expression <Func <T, T, bool> > equalityFunc = Expression.Lambda <Func <T, T, bool> >(arePropertiesEqual, firstObject, secondObject);
            PropertyComparer <T>            comparer     = new PropertyComparer <T>()
            {
                Compare      = equalityFunc.Compile(),
                PropertyName = properties[i].Name
            };
            propertyComparers[i] = comparer;
        }
        ChangedProps = new Func <T, T, List <string> >((a, b) =>
        {
            List <string> changedFields = new List <string>();
            foreach (PropertyComparer <T> comparer in propertyComparers)
            {
                if (comparer.Compare(a, b))
                {
                    continue;
                }
                changedFields.Add(comparer.PropertyName);
            }
            return(changedFields);
        });
    }
Ejemplo n.º 6
0
        public async Task CopyDirectoryWithSubDirectoryDepthZeroAsync()
        {
            var ct    = CancellationToken.None;
            var root  = await FileSystem.Root;
            var coll1 = await root.CreateCollectionAsync("test1", ct);

            Assert.NotNull(coll1);

            await coll1.CreateCollectionAsync("subcoll", ct);

            var props1 = await coll1.GetPropertyElementsAsync(Dispatcher, ct);

            var response = await Client
                           .CopyAsync(
                new Uri(Client.BaseAddress, new Uri("test1", UriKind.Relative)),
                new Uri(Client.BaseAddress, new Uri("test2", UriKind.Relative)),
                true,
                WebDavDepthHeaderValue.Zero)
            ;

            Assert.True(response.IsSuccessStatusCode);

            var child = await root.GetChildAsync("test2", ct);

            var coll2  = Assert.IsType <InMemoryDirectory>(child);
            var props2 = await coll2.GetPropertyElementsAsync(Dispatcher, ct);

            var changes = PropertyComparer.FindChanges(props1, props2, _propsToIgnoreCollection);

            Assert.Empty(changes);

            var subChild = await coll2.GetChildAsync("subcoll", ct);

            Assert.Null(subChild);
        }
Ejemplo n.º 7
0
        public void TestCompareThroughRelationship()
        {
            //---------------Set up test pack-------------------
            Car car1 = new Car();
            car1.CarRegNo = "5";
            Car car2 = new Car();
            car2.CarRegNo = "2";

            Engine engine1 = new Engine();
            engine1.CarID = car1.CarID;
            engine1.EngineNo = "20";

            Engine engine2 = new Engine();
            engine2.CarID = car2.CarID;
            engine2.EngineNo = "50";

            ITransactionCommitter committer = BORegistry.DataAccessor.CreateTransactionCommitter();
            committer.AddBusinessObject(car1);
            committer.AddBusinessObject(car2);
            committer.AddBusinessObject(engine1);
            committer.AddBusinessObject(engine2);
            committer.CommitTransaction();

            //---------------Assert PreConditions---------------            
            //---------------Execute Test ----------------------
            PropertyComparer<Engine, string> comparer = new PropertyComparer<Engine, string>("CarRegNo");
            comparer.Source = new Source("Car");
            int comparisonResult = comparer.Compare(engine1, engine2);
            //---------------Test Result -----------------------
            Assert.Greater(comparisonResult, 0, "engine1 should be greater as its car's regno is greater");
            //---------------Tear Down -------------------------     
        }
Ejemplo n.º 8
0
        protected override void ApplySortCore(PropertyDescriptor property, ListSortDirection direction)
#endif
        {
#if !_CPT
            List <T> items = this.Items as List <T>;

            if ((null != items) && (null != property))
            {
                PropertyComparer <T> pc = new PropertyComparer <T>(property, direction);
                items.Sort(pc);

                /* Set sorted */
                m_IsSorted = true;
                if (Sorted != null)
                {
                    Sorted(direction, property.Name);
                }
            }
            else
            {
                /* Set sorted */
                m_IsSorted = false;
            }
#endif
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Sorts the items on the list.
        /// </summary>
        /// <param name="prop"><see cref="PropertyDescriptor"/> that specifies the property to sort on.</param>
        /// <param name="direction"><see cref="ListSortDirection"/> that specifies whether to sort the list in ascending or descending order.</param>
        protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction)
        {
            // get list to sort
            var items = this.Items as List <T>;

            // apply the sort
            if (items != null && prop != null)
            {
                // if this property is an EntityObject, get map to sort by display value
                ListDictionary map = null;
                if (DataSource != null && !prop.PropertyType.IsPrimitive) //typeof(EntityObject).IsAssignableFrom(prop.PropertyType))
                {
                    map = DataSource.GetLookupDictionary(prop.PropertyType);
                }

                // go sort the list
                var pc = new PropertyComparer <T>(prop, direction, map);
                items.Sort(pc);
            }

            // save new settings and notify listeners
            _sortProp = prop;
            _sortDir  = direction;
            this.OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
        }
Ejemplo n.º 10
0
        private void UpdateForm_Shown(object sender, EventArgs e)
        {
            Application.DoEvents();

            _tmpDir = Path.Combine(AppConfig.ExecutableDir, "Tmp");
            if (!Directory.Exists(_tmpDir))
            {
                Directory.CreateDirectory(_tmpDir);
            }


            _fileDownloadList = new List <FileDownload>();
            if (_xmlUpdate.DeleteBin)
            {
                _doNotDeleteFileList = new List <string>();
                var executablePath = Application.ExecutablePath.ToLowerInvariant();
                _doNotDeleteFileList.Add(executablePath);
                _doNotDeleteFileList.Add(executablePath.Remove(executablePath.Length - ".exe".Length) + ".config");
                _doNotDeleteFileList.Add(executablePath + ".config");
            }

            //todo aq unda gavaketo + is magivrad Combine rom gaketdes
            var urlDir = _selfUpdate
                        ? AppConfig.UpdaterUrlDir + AppConfig.UpdaterDirSeperator + (!string.IsNullOrWhiteSpace(_xmlUpdate.CompressFolderName) ? _xmlUpdate.CompressFolderName + AppConfig.UpdaterDirSeperator : string.Empty)
                        : AppConfig.UpdateUrlDir + AppConfig.UpdateDirSeperator + (!string.IsNullOrWhiteSpace(_xmlUpdate.CompressFolderName) ? _xmlUpdate.CompressFolderName + AppConfig.UpdateDirSeperator : string.Empty);

            foreach (var file in _xmlUpdate.Files)
            {
                var tmplocalFile = _selfUpdate
                        ? Path.Combine(AppConfig.ExecutableDir, file.File)
                        : Path.Combine(AppConfig.AppExeFolder, file.File);
                if (_xmlUpdate.DeleteBin)
                {
                    _doNotDeleteFileList.Add(tmplocalFile.ToLowerInvariant());
                }
                if (!File.Exists(tmplocalFile) || file.Hash != Ext.MD5HexFile(tmplocalFile))
                {
                    _fileDownloadList.Add(new FileDownload
                    {
                        Name   = tmplocalFile.Substring(tmplocalFile.LastIndexOf(_selfUpdate ? AppConfig.UpdaterDirSeperator : AppConfig.UpdateDirSeperator) + 1),
                        Local  = tmplocalFile,
                        Server = urlDir + file.Hash + _xmlUpdate.Extension,
                        Tmp    = Path.Combine(_tmpDir, file.Hash + _xmlUpdate.Extension)
                    });
                }
            }

            if (_fileDownloadList.Count == 0)
            {
                return;
            }

            var comparer = new PropertyComparer <FileDownload>("Server");
            var tmpList  = _fileDownloadList.Distinct(comparer).ToList();

            progressDownload.Maximum       = tmpList.Count;
            progressDownload.Value         = 0;
            progressDownload.UseWaitCursor = true;
            bwDownload.RunWorkerAsync(tmpList);
        }
Ejemplo n.º 11
0
        public void CharacterRepository_Save()
        {
            //seed a character
            var character = _repoHelper.SeedCharacters().First();

            //keep a local copy of the character name
            var characterInitName = character.Name;

            //modify the character
            character.Name = Guid.NewGuid().ToString();

            //keep a local copy of the new character name
            var characterModName = character.Name;

            //save the character with the new name
            _characterRepo.Save(character);

            //get the character from the db
            var characterDb = _characterRepo.Get(character.Id);

            //ensure the init name isn't the same as the db name
            Assert.AreNotEqual(characterInitName, characterDb.Name);

            //ensure the mod name is the same as the db name
            Assert.AreEqual(characterModName, characterDb.Name);

            //ensure the db returns what we gave it
            var comparer = new PropertyComparer <Character>();

            Assert.IsTrue(comparer.Equals(character, characterDb));
        }
Ejemplo n.º 12
0
        private void dgvPersons_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            PropertyComparer comparer = new PropertyComparer(this.dgvPersons.Columns[e.ColumnIndex].DataPropertyName, this.dgvPersons.Columns[e.ColumnIndex].DefaultCellStyle.Alignment == DataGridViewContentAlignment.MiddleRight, this.smalltobig);

            this.Persons.Sort(comparer);
            this.RebindDataSource();
            this.smalltobig = !this.smalltobig;
        }
Ejemplo n.º 13
0
        public void compare_two_string_by_length_using_get_hash_code()
        {
            const string string1 = "lorem";
            const string string2 = "ipsum";
            var comparer = new PropertyComparer<string>(x => x.Length);

            Assert.Equal(comparer.GetHashCode(string1), comparer.GetHashCode(string2));
        }
Ejemplo n.º 14
0
        public void compare_two_string_by_length_using_equals()
        {
            const string string1 = "lorem";
            const string string2 = "ipsum";
            var comparer = new PropertyComparer<string>(x => x.Length);

            Assert.True(comparer.Equals(string1, string2));
        }
Ejemplo n.º 15
0
        public void compare_two_string_by_length_using_get_hash_code()
        {
            const string string1  = "lorem";
            const string string2  = "ipsum";
            var          comparer = new PropertyComparer <string>(x => x.Length);

            Assert.Equal(comparer.GetHashCode(string1), comparer.GetHashCode(string2));
        }
Ejemplo n.º 16
0
        public void compare_two_string_by_length_using_equals()
        {
            const string string1  = "lorem";
            const string string2  = "ipsum";
            var          comparer = new PropertyComparer <string>(x => x.Length);

            Assert.True(comparer.Equals(string1, string2));
        }
Ejemplo n.º 17
0
		public ClassComparer ()
		{
			icomparer = new InterfaceComparer ();
			ccomparer = new ConstructorComparer ();
			fcomparer = new FieldComparer ();
			pcomparer = new PropertyComparer ();
			ecomparer = new EventComparer ();
			mcomparer = new MethodComparer ();
		}
Ejemplo n.º 18
0
        public async Task CopyDirectoryWithTwoSubDirectoriesDepthOneAsync()
        {
            var ct   = CancellationToken.None;
            var root = await FileSystem.Root.ConfigureAwait(false);

            var coll1 = await root.CreateCollectionAsync("test1", ct).ConfigureAwait(false);

            Assert.NotNull(coll1);

            var sub11 = await coll1.CreateCollectionAsync("subcoll1", ct).ConfigureAwait(false);

            var sub12 = await coll1.CreateCollectionAsync("subcoll2", ct).ConfigureAwait(false);

            var props1 = await coll1.GetPropertyElementsAsync(Dispatcher, ct).ConfigureAwait(false);

            var subProps11 = await sub11.GetPropertyElementsAsync(Dispatcher, ct).ConfigureAwait(false);

            var subProps12 = await sub12.GetPropertyElementsAsync(Dispatcher, ct).ConfigureAwait(false);

            var response = await Client
                           .CopyAsync(
                new Uri(Client.BaseAddress, new Uri("test1", UriKind.Relative)),
                new Uri(Client.BaseAddress, new Uri("test2", UriKind.Relative)),
                true,
                WebDavDepthHeaderValue.Infinity)
                           .ConfigureAwait(false);

            Assert.True(response.IsSuccessStatusCode);

            var child = await root.GetChildAsync("test2", ct).ConfigureAwait(false);

            var coll2  = Assert.IsType <InMemoryDirectory>(child);
            var props2 = await coll2.GetPropertyElementsAsync(Dispatcher, ct).ConfigureAwait(false);

            var changes = PropertyComparer.FindChanges(props1, props2, _propsToIgnoreCollection);

            Assert.Empty(changes);

            var subChild21 = await coll2.GetChildAsync("subcoll1", ct).ConfigureAwait(false);

            var sub21      = Assert.IsType <InMemoryDirectory>(subChild21);
            var subProps21 = await sub21.GetPropertyElementsAsync(Dispatcher, ct).ConfigureAwait(false);

            var subChanges1 = PropertyComparer.FindChanges(subProps11, subProps21, _propsToIgnoreCollection);

            Assert.Empty(subChanges1);

            var subChild22 = await coll2.GetChildAsync("subcoll2", ct).ConfigureAwait(false);

            var sub22      = Assert.IsType <InMemoryDirectory>(subChild22);
            var subProps22 = await sub22.GetPropertyElementsAsync(Dispatcher, ct).ConfigureAwait(false);

            var subChanges2 = PropertyComparer.FindChanges(subProps12, subProps22, _propsToIgnoreCollection);

            Assert.Empty(subChanges2);
        }
Ejemplo n.º 19
0
        public async Task SetNewProp()
        {
            var ct   = CancellationToken.None;
            var root = await FileSystem.Root.ConfigureAwait(false);

            const string resourceName = "text1.txt";

            var doc1 = await root.CreateDocumentAsync(resourceName, ct).ConfigureAwait(false);

            await doc1.FillWithAsync("Dokument 1", ct).ConfigureAwait(false);

            var propsBefore = await doc1.GetPropertyElementsAsync(Dispatcher, ct).ConfigureAwait(false);

            var requestUri    = new Uri(Client.BaseAddress, new Uri(resourceName, UriKind.Relative));
            var propertyValue = "<testProp>someValue</testProp>";
            var response      = await Client
                                .PropPatchAsync(
                requestUri,
                new PropertyUpdate
            {
                Items = new[]
                {
                    new Set
                    {
                        Prop = new Prop
                        {
                            AdditionalProperties = new[]
                            {
                                XElement.Parse(propertyValue),
                            },
                        },
                    },
                },
            },
                ct)
                                .ConfigureAwait(false);

            Assert.True(response.IsSuccessStatusCode);

            var child = await root.GetChildAsync(resourceName, ct).ConfigureAwait(false);

            var doc2   = Assert.IsType <InMemoryFile>(child);
            var props2 = await doc2.GetPropertyElementsAsync(Dispatcher, ct).ConfigureAwait(false);

            var changes       = PropertyComparer.FindChanges(propsBefore, props2, _propsToIgnoreDocument);
            var addedProperty = Assert.Single(changes);

            Assert.NotNull(addedProperty);

            var expectedAddedChangeItem = PropertyChangeItem.Added(XElement.Parse(propertyValue));

            Assert.Equal(expectedAddedChangeItem.Name, addedProperty.Name);
            Assert.Equal(expectedAddedChangeItem.Change, addedProperty.Change);
            Assert.Equal(expectedAddedChangeItem.Left, addedProperty.Left);
            Assert.True(XNode.DeepEquals(expectedAddedChangeItem.Right, addedProperty.Right));
        }
Ejemplo n.º 20
0
        public void Serialize_Desirialize()
        {
            // NOTE: Watch that all properties LogEntryData have non default values.
            var serialized = new LogEntryData("somedate", true, AccessType.REGISTRY, @"d:\my documents\pics", @"c:\win\malware.exe");

            var data         = LogEntryData.Serialize(serialized);
            var deserialized = LogEntryData.Deserialize(data);

            Assert.IsTrue(PropertyComparer.AreEqual(serialized, deserialized));
        }
 protected void AssertEqual(
     IEnumerable <IProperty> expectedProperties,
     IEnumerable <IProperty> actualProperties,
     PropertyComparer propertyComparer = null)
 {
     propertyComparer = propertyComparer ?? new PropertyComparer();
     Assert.Equal(
         new SortedSet <IProperty>(expectedProperties, propertyComparer),
         new SortedSet <IProperty>(actualProperties, propertyComparer),
         propertyComparer);
 }
Ejemplo n.º 22
0
 protected void AssertEqual(
     IEnumerable <IProperty> expectedProperties,
     IEnumerable <IProperty> actualProperties,
     PropertyComparer propertyComparer = null)
 {
     propertyComparer ??= new PropertyComparer(compareAnnotations: false);
     Assert.Equal(
         new SortedSet <IProperty>(expectedProperties, propertyComparer),
         new SortedSet <IProperty>(actualProperties, propertyComparer),
         propertyComparer);
 }
Ejemplo n.º 23
0
 /// <summary>
 ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
 ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
 ///     any release. You should only use it directly in your code with extreme caution and knowing that
 ///     doing so can result in application failures when updating to a new Entity Framework Core release.
 /// </summary>
 protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction)
 {
     if (PropertyComparer.CanSort(prop.PropertyType))
     {
         ((List <T>)Items).Sort(new PropertyComparer(prop, direction));
         _sortDirection = direction;
         _sortProperty  = prop;
         _isSorted      = true;
         OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
     }
 }
Ejemplo n.º 24
0
 protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction)
 {
     if (!PropertyComparer.IsAllowable(prop.PropertyType))
     {
         return;
     }
     ((List <T>)Items).Sort(new PropertyComparer(prop, direction));
     sortDirection = direction;
     sortProperty  = prop;
     isSorted      = true;
     OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
 }
Ejemplo n.º 25
0
 private void SortTheKeyColumn()
 {
     if (this.SortColumnID > 0)
     {
         Column columnByID = this.GetColumnByID(this.SortColumnID);
         if (columnByID != null)
         {
             PropertyComparer comparer = new PropertyComparer(columnByID.Name, columnByID.IsNumber, this.SmallToBig);
             this.tabList.gameObjectList.GameObjects.Sort(comparer);
         }
     }
 }
Ejemplo n.º 26
0
        public List <FleetData> ChooseFleetsToLaunch(Guid userId, ReadOnlyMap map)
        {
            if (map == null)
            {
                throw new ArgumentNullException(nameof(map));
            }
            if (!map.Any())
            {
                return(new List <FleetData>());
            }
            var planetComparer = new PropertyComparer <ReadOnlyPlanetData, string>(x => x.Name);
            var myPlanets      = map
                                 .Where(x => x.OwnerId == userId)
                                 .ToHashSet(planetComparer);
            var allPlanets = map
                             .ToHashSet(planetComparer);

            if (myPlanets.Count == 0)
            {
                return(new List <FleetData>());
            }
            var topPlanet   = allPlanets.OrderByDescending(RankPlanet).First();
            var myTopPlanet = myPlanets.OrderByDescending(RankPlanet).First();
            var candidates  = myPlanets
                              .AsParallel()
                              .SelectMany(source =>
            {
                var otherPlanets = allPlanets
                                   .Except(new[] { source }, planetComparer);
                return(GetCandidates(map, source, otherPlanets, myTopPlanet, topPlanet));
            })
                              .OrderByDescending(Rank)
                              .ToList();
            var sentShips = new Dictionary <string, int>();
            var fleets    = new List <FleetData>();

            foreach (var candidate in candidates)
            {
                var sent = sentShips.GetOrCreateDefault(candidate.Source.Name);
                if (candidate.Ships + sent > candidate.Source.Ships)
                {
                    continue;
                }
                fleets.Add(new FleetData
                {
                    From  = candidate.Source.Position,
                    To    = candidate.Destination.Position,
                    Ships = candidate.Ships
                });
                sentShips[candidate.Source.Name] += candidate.Ships;
            }
            return(fleets);
        }
Ejemplo n.º 27
0
        public void TestHashCode()
        {
            var entity1 = new Comparable {
                Id = 1, Name = "Name", Description = "Description"
            };
            var entity2 = new Comparable {
                Id = 1, Name = "Name", Description = "Description"
            };
            var comparer = new PropertyComparer <Comparable>();

            Assert.Equal(comparer.GetHashCode(entity1), comparer.GetHashCode(entity2));
        }
Ejemplo n.º 28
0
     protected override void OnSetViewData(object data)
     {
         if (GroupComparer == null && !Compare.IsNullOrEmpty(GroupBy))
         {
             GroupComparer = new PropertyComparer {
                 PropertyName = GroupBy
             }
         }
         ;
         DataSource = data;
     }
 }
Ejemplo n.º 29
0
        public void FindCarsByLicensePlateTest_AllVehicles()
        {
            var expect = new List <Vehicle>
            {
                new Car
                {
                    Manufacturer   = "VW",
                    Model          = "Käfer",
                    LicensePlate   = "K-GS-01",
                    Year           = 1965,
                    NewPrice       = 9999m,
                    Capacity       = 1000,
                    Power          = 30,
                    PollutantClass = PollutantClasses.Normal
                },
                new Car
                {
                    Manufacturer   = "Opel",
                    Model          = "Kadett",
                    LicensePlate   = "K-GS-02",
                    Year           = 1964,
                    NewPrice       = 12000m,
                    Capacity       = 1600,
                    Power          = 60,
                    PollutantClass = PollutantClasses.Diesel
                },
                new Motorcycle
                {
                    Manufacturer = "BMW",
                    Model        = "R1200r",
                    LicensePlate = "K-GS-03",
                    Year         = 1999,
                    NewPrice     = 6000m,
                    Capacity     = 1170
                },
                new Truck
                {
                    Manufacturer = "Mercedes",
                    Model        = "LG 315",
                    LicensePlate = "K-GS-04",
                    Year         = 1960,
                    NewPrice     = 23000m,
                    Axis         = 2,
                    Payload      = 5.5
                }
            };
            var sut = VehicleManagerFactory.Create(null);

            var result = sut.FindCarsByLicensePlate("");

            Assert.IsTrue(PropertyComparer.AreEqual(expect, new List <Vehicle>(result.Keys)));
        }
Ejemplo n.º 30
0
        public void StoryRepository_Get()
        {
            //seed a story
            var story = _repoHelper.SeedStories().First();

            //get the story
            var storyDb = _storyRepo.Get(story.Id);

            //check to see if the db returns what we gave it
            var comparer = new PropertyComparer <Story>();

            Assert.IsTrue(comparer.Equals(story, storyDb));
        }
Ejemplo n.º 31
0
        public void CharacterRepository_Get()
        {
            //seed a character
            var character = _repoHelper.SeedCharacters().First();

            //get the character
            var characterDb = _characterRepo.Get(character.Id);

            //check to see if the db returns what we gave it
            var comparer = new PropertyComparer <Character>();

            Assert.IsTrue(comparer.Equals(character, characterDb));
        }
Ejemplo n.º 32
0
        protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction)
        {
            //Only apply sort if the column is sortable, decision was made not to throw in this case.
            //Don't prevent nullable types from working.
            Type propertyType = prop.PropertyType;

            if (PropertyComparer.IsAllowable(propertyType))
            {
                ((List <T>) this.Items).Sort(new PropertyComparer(prop, direction));
                sortDirection = direction;
                sortProperty  = prop;
                isSorted      = true;
                OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
            }
        }
Ejemplo n.º 33
0
        public void TestSimpleCompare_String()
        {
            //---------------Set up test pack-------------------
            Car car1 = new Car();
            car1.CarRegNo = "5";
            Car car2 = new Car();
            car2.CarRegNo = "2";

            //---------------Execute Test ----------------------
            PropertyComparer<Car, string> comparer = new PropertyComparer<Car, string>("CarRegNo");
            int comparisonResult = comparer.Compare(car1, car2);
            //---------------Test Result -----------------------
            Assert.Greater(comparisonResult, 0, "car1 should be greater than car2 when compared on CarRegNo");
            //---------------Tear Down -------------------------
        }
Ejemplo n.º 34
0
        protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction)
        {
            if (null == prop)
            {
                throw new ArgumentNullException(nameof(prop));
            }

            if (PropertyComparer.IsAllowable(prop))
            {
                ((List <T>)Items).Sort(new PropertyComparer(prop, direction));
                sortDirection = direction;
                sortProperty  = prop;
                sorted        = true;
            }
        }
Ejemplo n.º 35
0
        private void Initialize()
        {
            comparer = new PropertyComparer();
            childrenOfObject1 = new StringCollection();
            childrenOfObject2 = new StringCollection();
            ignoreObject = new StringCollection();
            ignoreProperty = new StringCollection();
            ignoreType = new StringCollection();
            ignoreSchema = new StringCollection();
            ignorePropertyForObject = new ArrayList(3);
            ignorePropertyForType = new ArrayList(3);
            collectionCanBeNull = new ArrayList(3);
            DiffProps = new ArrayList(3);

            Configure();
        }
Ejemplo n.º 36
0
            protected override void ApplySortCore(PropertyDescriptor property, ListSortDirection direction)
            {
                if (property.PropertyType.GetInterface("IComparable") != null)
                {
                    List <T> items = this.Items as List <T>;

                    // Apply and set the sort, if items to sort
                    if (items != null)
                    {
                        PropertyComparer <T> pc = new PropertyComparer <T>(property, direction); //wywalic direction
                        items.Sort(pc);
                    }

                    // Let bound controls know they should refresh their views
                    this.OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
                }
            }
Ejemplo n.º 37
0
        public void SetUp()
        {
            _referencedInstance = new ClassWithProperties();

            _instance = new ClassWithProperties
            {
                IntegerValue = 2,
                StringValue = "string",
                ClassReference = _referencedInstance
            };

            _instanceWithSameValues = new ClassWithProperties
            {
                IntegerValue = 2,
                StringValue = "string",
                ClassReference = _referencedInstance
            };

            _comparer = new PropertyComparer();
        }
Ejemplo n.º 38
0
 /// <summary>
 /// Constructor for the class comparer
 /// </summary>
 /// <param name="rootComparer">The root comparer instantiated by the RootComparerFactory</param>
 public ClassComparer(RootComparer rootComparer) : base(rootComparer)
 {
     _propertyComparer = new PropertyComparer(rootComparer);
     _fieldComparer = new FieldComparer(rootComparer);
 }
Ejemplo n.º 39
0
 /// <summary>
 /// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
 /// </summary>
 /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
 /// <returns>
 /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
 /// </returns>    
 public override bool Equals(object obj)
 {
     var comparer = new PropertyComparer();
       return comparer.Equals(this, obj);
 }