public void ListReference_ResolveDeletedParentObject_ShouldReturnNull()
        {
            AsyncContext.Run(async () =>
            {
                var obj = new Owner();
                obj.Dogs.Add(new Dog { Name = "1" });
                obj.Dogs.Add(new Dog { Name = "2" });

                _realm.Write(() => _realm.Add(obj));

                var listReference = ThreadSafeReference.Create(obj.Dogs);

                _realm.Write(() => _realm.Remove(obj));

                await Task.Run(() =>
                {
                    using (var otherRealm = Realm.GetInstance(_realm.Config))
                    {
                        var otherList = otherRealm.ResolveReference(listReference);

                        Assert.That(otherList, Is.Null);
                    }
                });
            });
        }
示例#2
0
 /// <summary>
 /// Creates a new Dataset
 /// </summary>
 public BaseDataset()
 {
     this._activeGraph = new ThreadSafeReference<IGraph>();
     this._defaultGraph = new ThreadSafeReference<IGraph>(this.InitDefaultGraph);
     this._defaultGraphs = new ThreadSafeReference<Stack<IGraph>>(this.InitGraphStack);
     this._activeGraphs = new ThreadSafeReference<Stack<IGraph>>(this.InitGraphStack);
 }
        public void ListReference_ShouldWork()
        {
            AsyncContext.Run(async () =>
            {
                var obj = new Owner();
                obj.Dogs.Add(new Dog { Name = "1" });
                obj.Dogs.Add(new Dog { Name = "2" });

                _realm.Write(() => _realm.Add(obj));

                var listReference = ThreadSafeReference.Create(obj.Dogs);

                await Task.Run(() =>
                {
                    using (var otherRealm = Realm.GetInstance(_realm.Config))
                    {
                        var otherList = otherRealm.ResolveReference(listReference);

                        Assert.That(otherList, Is.InstanceOf(typeof(RealmList<Dog>)));
                        var dogNames = otherList.Select(d => d.Name);
                        Assert.That(dogNames, Is.EqualTo(new[] { "1", "2" }));
                    }
                });
            });
        }
示例#4
0
        public void QueryReference_WhenFilterApplied_ShouldWork()
        {
            TestHelpers.RunAsyncTest(async() =>
            {
                _realm.Write(() =>
                {
                    _realm.Add(new IntPropertyObject {
                        Int = 1
                    });
                    _realm.Add(new IntPropertyObject {
                        Int = 2
                    });
                    _realm.Add(new IntPropertyObject {
                        Int = 3
                    });
                    _realm.Add(new IntPropertyObject {
                        Int = 4
                    });
                });

                var query          = _realm.All <IntPropertyObject>().Where(o => o.Int != 2);
                var queryReference = ThreadSafeReference.Create(query);
                await AssertQueryReferenceAsync(queryReference, new[] { 1, 3, 4 });
            });
        }
示例#5
0
        public void ObjectReference_WhenSourceRealmInTransaction_ShouldSucceed()
        {
            TestHelpers.RunAsyncTest(async() =>
            {
                ThreadSafeReference.Object <IntPropertyObject> objRef = null;

                _realm.Write(() =>
                {
                    var obj = _realm.Add(new IntPropertyObject {
                        Int = 123
                    });
                    objRef = ThreadSafeReference.Create(obj);
                });

                await Task.Run(() =>
                {
                    using var otherRealm = GetRealm(_realm.Config);
                    var otherObj         = otherRealm.ResolveReference(objRef);

                    Assert.That(otherObj.IsManaged);
                    Assert.That(otherObj.IsValid);
                    Assert.That(otherObj.Int, Is.EqualTo(123));
                });
            });
        }
示例#6
0
        public void TestUpdateViaQueriedReference()
        {
            KeyBindingContainer testContainer = new TestKeyBindingContainer();

            keyBindingStore.Register(testContainer);

            var backBinding = query().Single(k => k.ActionInt == (int)GlobalAction.Back);

            Assert.That(backBinding.KeyCombination.Keys, Is.EquivalentTo(new[] { InputKey.Escape }));

            var tsr = ThreadSafeReference.Create(backBinding);

            using (var usage = realmContextFactory.GetForWrite())
            {
                var binding = usage.Realm.ResolveReference(tsr);
                binding.KeyCombination = new KeyCombination(InputKey.BackSpace);

                usage.Commit();
            }

            Assert.That(backBinding.KeyCombination.Keys, Is.EquivalentTo(new[] { InputKey.BackSpace }));

            // check still correct after re-query.
            backBinding = query().Single(k => k.ActionInt == (int)GlobalAction.Back);
            Assert.That(backBinding.KeyCombination.Keys, Is.EquivalentTo(new[] { InputKey.BackSpace }));
        }
        public void TestUpdateViaQueriedReference()
        {
            KeyBindingContainer testContainer = new TestKeyBindingContainer();

            keyBindingStore.Register(testContainer, Enumerable.Empty <RulesetInfo>());

            realm.Run(outerRealm =>
            {
                var backBinding = outerRealm.All <RealmKeyBinding>().Single(k => k.ActionInt == (int)GlobalAction.Back);

                Assert.That(backBinding.KeyCombination.Keys, Is.EquivalentTo(new[] { InputKey.Escape }));

                var tsr = ThreadSafeReference.Create(backBinding);

                realm.Run(innerRealm =>
                {
                    var binding = innerRealm.ResolveReference(tsr);
                    innerRealm.Write(() => binding.KeyCombination = new KeyCombination(InputKey.BackSpace));
                });

                Assert.That(backBinding.KeyCombination.Keys, Is.EquivalentTo(new[] { InputKey.BackSpace }));

                // check still correct after re-query.
                backBinding = outerRealm.All <RealmKeyBinding>().Single(k => k.ActionInt == (int)GlobalAction.Back);
                Assert.That(backBinding.KeyCombination.Keys, Is.EquivalentTo(new[] { InputKey.BackSpace }));
            });
        }
示例#8
0
        public void RefreshAsync_Tests()
        {
            TestHelpers.RunAsyncTest(async() =>
            {
                Assert.That(SynchronizationContext.Current != null);

                IntPrimaryKeyWithValueObject obj = null;
                _realm.Write(() =>
                {
                    obj = _realm.Add(new IntPrimaryKeyWithValueObject());
                });

                var reference = ThreadSafeReference.Create(obj);

                Task.Run(() =>
                {
                    using var realm = GetRealm(_realm.Config);
                    var bgObj       = realm.ResolveReference(reference);
                    realm.Write(() =>
                    {
                        bgObj.StringValue = "123";
                    });
                }).Wait(); // <- wait to avoid the main thread autoupdating while idle

                Assert.That(obj.StringValue, Is.Null);

                var changeTiming = await MeasureTiming(_realm.RefreshAsync);

                Assert.That(obj.StringValue, Is.EqualTo("123"));

                // Make sure when there are no changes RefreshAsync completes quickly
                var idleTiming = await MeasureTiming(_realm.RefreshAsync);

                Assert.That(changeTiming, Is.GreaterThan(idleTiming));
        private ThreadSafeReference.Object<IntPropertyObject> SetupObjectReference()
        {
            var obj = new IntPropertyObject { Int = 12 };

            _realm.Write(() => _realm.Add(obj));

            return ThreadSafeReference.Create(obj);
        }
示例#10
0
        public void ThreadSafeReference_WhenObjectIsDeleted_ShouldFail()
        {
            var obj = new IntPropertyObject();
            _realm.Write(() => _realm.Add(obj));
            _realm.Write(() => _realm.Remove(obj));

            Assert.That(() => ThreadSafeReference.Create(obj), Throws.InstanceOf<RealmException>().And.Message.Contains("invalidated object"));
        }
示例#11
0
        public void ObjectReference_WhenSourceRealmInTransaction_ShouldFail()
        {
            _realm.Write(() =>
            {
                var obj = _realm.Add(new IntPropertyObject());

                Assert.That(() => ThreadSafeReference.Create(obj), Throws.InstanceOf<RealmInvalidTransactionException>());
            });
        }
示例#12
0
        public void QueryReference_WhenQueryIsNotRealmResults_ShouldFail()
        {
            var unmanagedDogs = new[] { new Dog() };
            Assert.That(() => ThreadSafeReference.Create(unmanagedDogs.AsQueryable()), Throws.InstanceOf<InvalidCastException>());

            _realm.Write(() => _realm.Add(new Dog()));

            var managedDogs = _realm.All<Dog>().ToArray().AsQueryable();
            Assert.That(() => ThreadSafeReference.Create(managedDogs), Throws.InstanceOf<InvalidCastException>());
        }
        public override Task HandleChangeAsync(IChangeDetails details)
        {
            try
            {
                if (details.Changes.TryGetValue("Task", out var changeSetDetails))
                {
                    //if (changeSetDetails.Insertions.Any())
                    //{
                    //    var newTasks = (from m in changeSetDetails.Insertions
                    //        let obj = m.CurrentObject
                    //        let text = (string)obj.Title
                    //        select new TaskItem {
                    //            Id = (string)obj.Id,
                    //            Reference = ThreadSafeReference.Create(obj),
                    //            Text = text,
                    //            Realm = details.GetRealmForWriting()
                    //        })
                    //        .ToList();

                    //    newTasks.ForEach(t => newTaskSubject.OnNext(t));
                    //}

                    if (changeSetDetails.Modifications.Any())
                    {
                        var modifiedTasks = (from m in changeSetDetails.Modifications
                                             //where m.CurrentObject != null && m.PreviousObject != null
                                             //group m by m.CurrentObject.Id into g
                                             //let obj = g.Last().CurrentObject
                                             //let text = (string)obj.Title
                                             let obj = m.CurrentObject
                                                       let text = (string)obj.Title
                                                                  select new TaskItem
                        {
                            Id = (string)obj.Id,
                            Reference = ThreadSafeReference.Create(obj),
                            Text = text,
                            Realm = details.GetRealmForWriting()
                        })
                                            .ToList();

                        modifiedTasks.ForEach(t => modifiedTaskSubject.OnNext(t));
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            return(Task.CompletedTask);
        }
示例#14
0
        private ThreadSafeReference.Query<IntPropertyObject> SetupQueryReference(Func<IQueryable<IntPropertyObject>, IQueryable<IntPropertyObject>> queryFunc)
        {
            _realm.Write(() =>
            {
                _realm.Add(new IntPropertyObject { Int = 1 });
                _realm.Add(new IntPropertyObject { Int = 2 });
                _realm.Add(new IntPropertyObject { Int = 3 });
                _realm.Add(new IntPropertyObject { Int = 4 });
            });

            var query = queryFunc(_realm.All<IntPropertyObject>());
            return ThreadSafeReference.Create(query);
        }
示例#15
0
        public void TestSongSelectLoadFilterFlowReferenceResolve()
        {
            var game = new Game();

            const int beatmap_count = 1_000_000;

            game.ScheduleRealmWrite(r => performBulkWrite(r, beatmap_count));

            logTime("bulk write completed");

            int foundCount = game.ScheduleRealm(r => r.All <BeatmapInfo>().Count());

            Assert.AreEqual(beatmap_count, foundCount);

            logTime("count lookup completed");

            var threadSafeFiltered = game.ScheduleRealm(r =>
            {
                // BeatmapCarousel currently does this on BDL.
                // as long as we are retrieving the IQueryable/IEnumerable this is a free query, so unnecessary to async it.
                var usableBeatmaps = r.All <BeatmapInfo>().Where(b => !b.DeletePending);

                // current filter logic is run synchronously
                var filteredBeatmaps = usableBeatmaps;

                return(ThreadSafeReference.Create(filteredBeatmaps));
            });

            game.ExitAndWait();

            logTime("filter completed");

            var localThreadRealm = game.GetGameRealm();
            var filtered         = localThreadRealm.ResolveReference(threadSafeFiltered).AsEnumerable().Where(b => isInRange(b.Difficulty)).ToList();

            logTime("filter resolved to list");

            Console.WriteLine($"post filter results: {filtered.Count()}");

            logTime("filter count completed");

            logTime($"sum filtered difficulties (backed): {filtered.Sum(f => f.Difficulty)}");
            logTime($"sum filtered difficulties (unbacked): {filtered.Sum(f => f.DifficultyUnbacked)}");

            filtered = filtered.ToList();
            logTime("convert to list");

            logTime($"sum filtered difficulties (backed): {filtered.Sum(f => f.Difficulty)}");
            logTime($"sum filtered difficulties (unbacked): {filtered.Sum(f => f.DifficultyUnbacked)}");
        }
示例#16
0
        public void ListReference_WhenListIsNotRealmList_ShouldFail()
        {
            IList <Dog> unmanagedDogs = new List <Dog>();

            unmanagedDogs.Add(new Dog());

            Assert.That(() => ThreadSafeReference.Create(unmanagedDogs), Throws.InstanceOf <InvalidCastException>());

            _realm.Write(() => _realm.Add(new Dog()));

            IList <Dog> managedDogs = _realm.All <Dog>().ToList();

            Assert.That(() => ThreadSafeReference.Create(managedDogs), Throws.InstanceOf <InvalidCastException>());
        }
示例#17
0
        public void RefreshAsync_Tests()
        {
            AsyncContext.Run(async() =>
            {
                Assert.That(SynchronizationContext.Current != null);

                IntPrimaryKeyWithValueObject obj = null;
                _realm.Write(() =>
                {
                    obj = _realm.Add(new IntPrimaryKeyWithValueObject());
                });

                var reference = ThreadSafeReference.Create(obj);

                Task.Run(() =>
                {
                    using (var realm = Realm.GetInstance(_realm.Config))
                    {
                        var bgObj = realm.ResolveReference(reference);
                        realm.Write(() =>
                        {
                            bgObj.StringValue = "123";
                        });
                    }
                }).Wait(); // <- wait to avoid the main thread autoupdating while idle

                Assert.That(obj.StringValue, Is.Null);

                var changeTiming = await measureTiming(_realm.RefreshAsync);

                Assert.That(obj.StringValue, Is.EqualTo("123"));

                // Make sure when there are no changes RefreshAsync completes quickly
                var idleTiming = await measureTiming(_realm.RefreshAsync);

                Assert.That(changeTiming, Is.GreaterThan(idleTiming));

                async Task <long> measureTiming(Func <Task> func)
                {
                    var sw = new Stopwatch();
                    sw.Start();
                    await func();
                    sw.Stop();
                    return(sw.ElapsedTicks);
                }
            });
        }
示例#18
0
        public async Task UpdateAttachment()
        {
            var unmanagedComment = await Device.InvokeOnMainThreadAsync(() => this.Clone());

            System.Diagnostics.Debug.WriteLine("Update: " + unmanagedComment.AttachmentUrl);

            if (unmanagedComment.AttachmentUrl == null)
            {
                System.Diagnostics.Debug.WriteLine("Skipped uncontained url: " + unmanagedComment.AttachmentUrl);
                return;
            }

            if (unmanagedComment.IsDownloaded())
            {
                System.Diagnostics.Debug.WriteLine("Skipped donwloaded attachment: " + unmanagedComment.AttachmentUrl);
                return;
            }

            System.Diagnostics.Debug.WriteLine("Before GetAsync(): " + unmanagedComment.AttachmentUrl);
            var response = await httpClient.GetAsync(unmanagedComment.AttachmentUrl);

            if (!response.IsSuccessStatusCode)
            {
                System.Diagnostics.Debug.WriteLine("Bad success code: " + unmanagedComment.AttachmentUrl);
                return;
            }

            System.Diagnostics.Debug.WriteLine("Before update realm: " + unmanagedComment.AttachmentUrl);
            var file = await response.Content.ReadAsByteArrayAsync();

            var commentReference = await Device.InvokeOnMainThreadAsync(() => ThreadSafeReference.Create(this));

            var resolvedComment = Realm.GetInstance().ResolveReference(commentReference);

            Realm.GetInstance().Write(() =>
            {
                resolvedComment.AttachmentFile         = file;
                resolvedComment.AttachmentFileByteSize = resolvedComment.AttachmentFile.Length;
            });
            System.Diagnostics.Debug.WriteLine("After update realm: " + unmanagedComment.AttachmentUrl);
        }
示例#19
0
        public void ObjectReference_ResolveDeletedObject_ShouldReturnNull()
        {
            TestHelpers.RunAsyncTest(async() =>
            {
                var obj = new IntPropertyObject {
                    Int = 12
                };
                _realm.Write(() => _realm.Add(obj));

                var objReference = ThreadSafeReference.Create(obj);

                _realm.Write(() => _realm.Remove(obj));

                await Task.Run(() =>
                {
                    using var otherRealm = GetRealm(_realm.Config);
                    var otherObj         = otherRealm.ResolveReference(objReference);
                    Assert.That(otherObj, Is.Null);
                });
            });
        }
示例#20
0
        public void ObjectReference_ResolveDeletedObject_ShouldReturnNull()
        {
            AsyncContext.Run(async () =>
            {
                var obj = new IntPropertyObject { Int = 12 };
                _realm.Write(() => _realm.Add(obj));

                var objReference = ThreadSafeReference.Create(obj);

                _realm.Write(() => _realm.Remove(obj));

                await Task.Run(() =>
                {
                    using (var otherRealm = Realm.GetInstance(_realm.Config))
                    {
                        var otherObj = otherRealm.ResolveReference(objReference);
                        Assert.That(otherObj, Is.Null);
                    }
                });
            });
        }
示例#21
0
        static void Demo8MultiThread()
        {
            var config = new RealmConfiguration("Demo8MultiThread.realm");

            config.ObjectClasses = new[] { typeof(People) };
            Realm.DeleteRealm(config);
            var realm = Realm.GetInstance(config);


            var persona = new People()
            {
                FirstName = "Riccardo"
            };

            realm.Write(() => realm.Add(persona));

            var referencePersona = ThreadSafeReference.Create(persona);

            Task.Run(() =>
            {
                // Da errore !!!
                //realm.Write(() =>
                //{
                //    persona.FirstName = "Marco";
                //});


                var altroRealm   = Realm.GetInstance(realm.Config);
                var altraPersona = altroRealm.ResolveReference(referencePersona);
                if (altraPersona == null)
                {
                    return; // person was deleted
                }

                altroRealm.Write(() =>
                {
                    altraPersona.FirstName = "Marco";
                });
            });
        }
            public async Task AssertThreadSafeReference(IList <T> list)
            {
                Assert.That(list, Is.TypeOf <RealmList <T> >());

                var tsr = ThreadSafeReference.Create(list);
                var originalThreadId = Environment.CurrentManagedThreadId;

                await Task.Run(() =>
                {
                    Assert.That(Environment.CurrentManagedThreadId, Is.Not.EqualTo(originalThreadId));

                    using (var bgRealm = Realm.GetInstance(list.AsRealmCollection().Realm.Config))
                    {
                        var backgroundList = bgRealm.ResolveReference(tsr);

                        for (var i = 0; i < backgroundList.Count; i++)
                        {
                            Assert.That(backgroundList[i], Is.EqualTo(referenceList[i]));
                        }
                    }
                });
            }
示例#23
0
        public override async Task HandleChangeAsync(IChangeDetails details)
        {
            if (details.Changes.TryGetValue("Ticket", out var changeSetDetails) &&
                changeSetDetails.Insertions.Length > 0)
            {
                // A new thread has been started - run sentiment analysis.

                try
                {
                    var tickets = changeSetDetails.Insertions
                                  .Select(i => i.CurrentObject)
                                  .Select(o => (string)(o.Title + Environment.NewLine + o.Description))
                                  .ToArray();

                    if (tickets.Length == 0)
                    {
                        return;
                    }

                    Console.WriteLine($"Requesting sentiment score for {tickets.Length} objects...");

                    var sentimentRequest = tickets.Select((text, index) => new SentimentDocument
                    {
                        Id       = index.ToString(),
                        Text     = text,
                        Language = "en"
                    })
                                           .Cast <IDocument>()
                                           .ToList();

                    var sentimentResponse = await _sentimentClient.GetSentimentAsync(new SentimentRequest
                    {
                        Documents = sentimentRequest
                    });

                    foreach (var error in sentimentResponse.Errors)
                    {
                        Console.WriteLine("Error from sentiment API: " + error.Message);
                    }

                    Console.WriteLine($"Requesting key phrases for {tickets.Length} objects...");

                    var keyPhraseRequest = tickets.Select((text, index) => new KeyPhraseDocument
                    {
                        Id       = index.ToString(),
                        Text     = text,
                        Language = "en"
                    })
                                           .Cast <IDocument>()
                                           .ToList();

                    var keyPhraseResponse = await _keyPhraseClient.GetKeyPhrasesAsync(new KeyPhraseRequest
                    {
                        Documents = keyPhraseRequest
                    });

                    foreach (var error in keyPhraseResponse.Errors)
                    {
                        Console.WriteLine("Error from KeyPhrase API: " + error.Message);
                    }

                    var keyPhraseDictionary = keyPhraseResponse.Documents.ToDictionary(d => d.Id, d => d.KeyPhrases);

                    var toUpdate = sentimentResponse.Documents
                                   .Select(doc =>
                    {
                        var obj = changeSetDetails.Insertions[int.Parse(doc.Id)].CurrentObject;

                        if (!keyPhraseDictionary.TryGetValue(doc.Id, out var keyPhrases) ||
                            keyPhrases == null)
                        {
                            keyPhrases = new List <string> {
                                "Unknown"
                            };
                        }

                        Console.WriteLine("------------------");
                        Console.WriteLine($"Analyzed: {obj.Title}");
                        Console.WriteLine($"Score: {doc.Score}");
                        Console.WriteLine($"KeyPhrases: {string.Join(", ", keyPhrases)}");
                        Console.WriteLine("------------------");

                        return(new
                        {
                            Score = doc.Score,
                            Reference = ThreadSafeReference.Create(obj),
                            KeyPhrases = keyPhrases
                        });
                    })
                                   .ToArray();

                    using (var realm = details.GetRealmForWriting())
                    {
                        var resolved = toUpdate.Select(t => new
                        {
                            Score      = t.Score,
                            Object     = realm.ResolveReference(t.Reference),
                            KeyPhrases = t.KeyPhrases
                        })
                                       .ToArray();

                        realm.Write(() =>
                        {
                            foreach (var item in resolved)
                            {
                                item.Object.Score = item.Score;
                                item.Object.Tags  = string.Join(" ", item.KeyPhrases);
                            }
                        });
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.StackTrace);
                }
            }
        }
        private async Task RunManagedTestsCore <T>(IList <T> items, T[] toAdd)
        {
            var realm = (items as RealmList <T>).Realm;

            if (toAdd == null)
            {
                toAdd = Array.Empty <T>();
            }

            var notifications = new List <ChangeSet>();

            using var token = items.SubscribeForNotifications((sender, changes, error) =>
            {
                if (changes != null)
                {
                    notifications.Add(changes);
                }
            });

            // Test add
            realm.Write(() =>
            {
                foreach (var item in toAdd)
                {
                    items.Add(item);
                }
            });

            // Test notifications
            if (toAdd.Any())
            {
                VerifyNotifications(realm, notifications, () =>
                {
                    Assert.That(notifications[0].InsertedIndices, Is.EquivalentTo(Enumerable.Range(0, toAdd.Length)));
                });
            }

            // Test iterating
            var iterator = 0;

            foreach (var item in items)
            {
                Assert.That(item, Is.EqualTo(toAdd[iterator++]));
            }

            // Test access by index
            for (var i = 0; i < items.Count; i++)
            {
                Assert.That(items[i], Is.EqualTo(toAdd[i]));
            }

            Assert.That(() => items[-1], Throws.TypeOf <ArgumentOutOfRangeException>());
            Assert.That(() => items[items.Count], Throws.TypeOf <ArgumentOutOfRangeException>());

            // Test indexOf
            foreach (var item in toAdd)
            {
                Assert.That(items.IndexOf(item), Is.EqualTo(Array.IndexOf(toAdd, item)));
            }

            // Test threadsafe reference
            var reference = ThreadSafeReference.Create(items);
            await Task.Run(() =>
            {
                using var bgRealm  = GetRealm(realm.Config);
                var backgroundList = bgRealm.ResolveReference(reference);
                for (var i = 0; i < backgroundList.Count; i++)
                {
                    Assert.That(backgroundList[i], Is.EqualTo(toAdd[i]));
                }
            });

            if (toAdd.Any())
            {
                // Test insert
                var toInsert = toAdd[_random.Next(0, toAdd.Length)];
                realm.Write(() =>
                {
                    items.Insert(0, toInsert);
                    items.Insert(items.Count, toInsert);

                    Assert.That(() => items.Insert(-1, toInsert), Throws.TypeOf <ArgumentOutOfRangeException>());
                    Assert.That(() => items.Insert(items.Count + 1, toInsert), Throws.TypeOf <ArgumentOutOfRangeException>());
                });

                Assert.That(items.First(), Is.EqualTo(toInsert));
                Assert.That(items.Last(), Is.EqualTo(toInsert));

                // Test notifications
                VerifyNotifications(realm, notifications, () =>
                {
                    Assert.That(notifications[0].InsertedIndices, Is.EquivalentTo(new[] { 0, items.Count - 1 }));
                });

                // Test remove
                realm.Write(() =>
                {
                    items.Remove(toInsert);
                    items.RemoveAt(items.Count - 1);

                    Assert.That(() => items.RemoveAt(-1), Throws.TypeOf <ArgumentOutOfRangeException>());
                    Assert.That(() => items.RemoveAt(items.Count + 1), Throws.TypeOf <ArgumentOutOfRangeException>());
                });

                CollectionAssert.AreEqual(items, toAdd);

                // Test notifications
                VerifyNotifications(realm, notifications, () =>
                {
                    Assert.That(notifications[0].DeletedIndices, Is.EquivalentTo(new[] { 0, items.Count + 1 }));
                });

                // Test set
                var indexToSet    = TestHelpers.Random.Next(0, items.Count);
                var previousValue = items[indexToSet];
                var valueToSet    = toAdd[TestHelpers.Random.Next(0, toAdd.Length)];
                realm.Write(() =>
                {
                    items[indexToSet] = valueToSet;

                    Assert.That(() => items[-1]          = valueToSet, Throws.TypeOf <ArgumentOutOfRangeException>());
                    Assert.That(() => items[items.Count] = valueToSet, Throws.TypeOf <ArgumentOutOfRangeException>());
                });

                VerifyNotifications(realm, notifications, () =>
                {
                    Assert.That(notifications[0].ModifiedIndices, Is.EquivalentTo(new[] { indexToSet }));
                });

                realm.Write(() => items[indexToSet] = previousValue);

                VerifyNotifications(realm, notifications, () =>
                {
                    Assert.That(notifications[0].ModifiedIndices, Is.EquivalentTo(new[] { indexToSet }));
                });

                // Test move
                var from = TestHelpers.Random.Next(0, items.Count);
                var to   = TestHelpers.Random.Next(0, items.Count);

                realm.Write(() =>
                {
                    items.Move(from, to);

                    Assert.That(() => items.Move(-1, to), Throws.TypeOf <ArgumentOutOfRangeException>());
                    Assert.That(() => items.Move(from, -1), Throws.TypeOf <ArgumentOutOfRangeException>());
                    Assert.That(() => items.Move(items.Count + 1, to), Throws.TypeOf <ArgumentOutOfRangeException>());
                    Assert.That(() => items.Move(from, items.Count + 1), Throws.TypeOf <ArgumentOutOfRangeException>());
                });

                Assert.That(items[to], Is.EqualTo(toAdd[from]));

                // Test notifications
                if (from != to)
                {
                    VerifyNotifications(realm, notifications, () =>
                    {
                        Assert.That(notifications[0].Moves.Length, Is.EqualTo(1));
                        var move = notifications[0].Moves[0];

                        // Moves may be reported with swapped from/to arguments if the elements are adjacent
                        if (move.From == to)
                        {
                            Assert.That(move.From, Is.EqualTo(to));
                            Assert.That(move.To, Is.EqualTo(from));
                        }
                        else
                        {
                            Assert.That(move.From, Is.EqualTo(from));
                            Assert.That(move.To, Is.EqualTo(to));
                        }
                    });
                }
            }

            // Test Clear
            realm.Write(() =>
            {
                items.Clear();
            });

            Assert.That(items, Is.Empty);

            // Test notifications
            if (toAdd.Any())
            {
                VerifyNotifications(realm, notifications, () =>
                {
                    // TODO: verify notifications contains the expected Deletions collection
                });
            }
        }
示例#25
0
        public void ThreadSafeReference_WhenAnObjectIsUnmanaged_ShouldFail()
        {
            var obj = new IntPropertyObject();

            Assert.That(() => ThreadSafeReference.Create(obj), Throws.InstanceOf<RealmException>().And.Message.Contains("unmanaged object"));
        }