예제 #1
0
        /// <inheritdoc/>
        public Task ResetAsync <TLog>(Version version) where TLog : LogBase
        {
            return(Task.Run(() =>
            {
                using (Realm realm = Realm.GetInstance(Configuration))
                    using (Transaction transaction = realm.BeginWrite())
                    {
                        string _version = version.ToString();
                        if (typeof(TLog) == typeof(Event))
                        {
                            realm.RemoveRange(realm.All <RealmEvent>().Where(entry => entry.AppVersion == _version));
                        }
                        else if (typeof(TLog) == typeof(ExceptionReport))
                        {
                            realm.RemoveRange(realm.All <RealmExceptionReport>().Where(entry => entry.AppVersion == _version));
                        }
                        else
                        {
                            throw new ArgumentException("The input type is not valid", nameof(TLog));
                        }

                        transaction.Commit();
                    }

                Realm.Compact(Configuration);
            }));
        }
예제 #2
0
        public void Compact_ShouldReduceSize(bool encrypt, bool populate)
        {
            var config = GetFakeConfig();

            if (encrypt)
            {
                config.EncryptionKey = TestHelpers.GetEncryptionKey(5);
            }

            using (var realm = GetRealm(config))
            {
                var session = GetSession(realm);
                session.Stop();
                if (populate)
                {
                    AddDummyData(realm, singleTransaction: false);
                }

                session.CloseHandle();
            }

            var initialSize = new FileInfo(config.DatabasePath).Length;

            Assert.That(Realm.Compact(config), Is.True);

            var finalSize = new FileInfo(config.DatabasePath).Length;

            Assert.That(initialSize, Is.GreaterThanOrEqualTo(finalSize));

            using (var realm = GetRealm(config))
            {
                Assert.That(realm.All <ObjectIdPrimaryKeyWithValueObject>().Count(), Is.EqualTo(populate ? DummyDataSize / 2 : 0));
            }
        }
예제 #3
0
        public void SaveToRealm(ItemData[] items)
        {
            int current = 0, total = items.Length;

            using (var trans = realm.BeginWrite())
            {
                //realm.RemoveAll()
                foreach (var itemData in items)
                {
                    realm.Add(itemData);

                    if (OnProgress == null)
                    {
                        continue;
                    }
                    if (++current % 10 == 0 || current == total)
                    {
                        OnProgress(current, total);
                    }
                }
                trans.Commit();
            }

            Realm.Compact();
            realm.Dispose();
            OnComplete?.Invoke();
        }
예제 #4
0
        public void Compact_ShouldReduceSize(bool encrypt, bool populate)
        {
            var config = new RealmConfiguration($"compactrealm_{encrypt}_{populate}.realm");

            if (encrypt)
            {
                config.EncryptionKey    = new byte[64];
                config.EncryptionKey[0] = 5;
            }

            Realm.DeleteRealm(config);

            using (var realm = Realm.GetInstance(config))
            {
                if (populate)
                {
                    AddDummyData(realm);
                }
            }

            var initialSize = new FileInfo(config.DatabasePath).Length;

            Assert.That(Realm.Compact(config));

            var finalSize = new FileInfo(config.DatabasePath).Length;

            Assert.That(initialSize >= finalSize);

            using (var realm = Realm.GetInstance(config))
            {
                Assert.That(realm.All <IntPrimaryKeyWithValueObject>().Count(), Is.EqualTo(populate ? 500 : 0));
            }
        }
예제 #5
0
        public void Compact_ShouldReduceSize(bool encrypt, bool populate)
        {
            var config = RealmConfiguration.DefaultConfiguration;

            if (encrypt)
            {
                config.EncryptionKey = TestHelpers.GetEncryptionKey(5);
            }

            using (var realm = Realm.GetInstance(config))
            {
                if (populate)
                {
                    AddDummyData(realm);
                }
            }

            var initialSize = new FileInfo(config.DatabasePath).Length;

            Assert.That(Realm.Compact(config));

            var finalSize = new FileInfo(config.DatabasePath).Length;

            Assert.That(initialSize >= finalSize);

            using (var realm = Realm.GetInstance(config))
            {
                Assert.That(realm.All <IntPrimaryKeyWithValueObject>().Count(), Is.EqualTo(populate ? 500 : 0));
            }
        }
예제 #6
0
        public async Task Compacts()
        {
            // :code-block-start:config-compact
            config = new RealmConfiguration()
            {
                ShouldCompactOnLaunch = (totalBytes, usedBytes) =>
                {
                    /* totalBytes refers to the size of the file on disk in
                     * bytes (data + free space).
                     * usedBytes refers to the number of bytes used by
                     * the realm file
                     */

                    // Compact if the file is over 100MB in size or more
                    // than 50% 'used'

                    var oneHundredMB = 100 * 1024 * 1024;

                    return((totalBytes > (double)oneHundredMB) ||
                           ((double)usedBytes / totalBytes > 0.5));
                }
            };
            var realm = await Realm.GetInstanceAsync(config);

            // :code-block-end:

            // :code-block-start:manual-compact
            config = new RealmConfiguration("my.realm");
            Realm.Compact(config);
            // :code-block-end:
        }
        public void Compact_ShouldReduceSize(bool encrypt, bool populate)
        {
            AsyncContext.Run(async() =>
            {
                var user      = await SyncTestHelpers.GetFakeUserAsync();
                var serverUri = new Uri($"realm://localhost:9080/~/compactrealm_{encrypt}_{populate}.realm");

                var config = new FullSyncConfiguration(serverUri, user);
                if (encrypt)
                {
                    config.EncryptionKey = TestHelpers.GetEncryptionKey(5);
                }

                using (var realm = GetRealm(config))
                {
                    if (populate)
                    {
                        AddDummyData(realm, singleTransaction: false);
                    }
                }

                var initialSize = new FileInfo(config.DatabasePath).Length;

                Assert.That(Realm.Compact(config));

                var finalSize = new FileInfo(config.DatabasePath).Length;
                Assert.That(initialSize >= finalSize);

                using (var realm = GetRealm(config))
                {
                    Assert.That(realm.All <IntPrimaryKeyWithValueObject>().Count(), Is.EqualTo(populate ? 500 : 0));
                }
            });
        }
예제 #8
0
        static void Compactar()
        {
            Console.WriteLine("\nCompactando..");
            RealmConfiguration configuration = new(NOME_DATABASE + ".realm");

            Realm.Compact(configuration);
            Console.WriteLine("\nCompactação finalizada");
        }
예제 #9
0
        async public static Task <Realm> GetRealm1(bool async = false, bool compact = false)
        {
            if (AppConfig && Realm != null)
            {
                return(Realm);
            }

            if (SRealmUri == null)
            {
                //SRealmUri = await RealmURI();
                //SRealmPath = await RealmPath();
                SRealmUri  = Settings.RealmUri;
                SRealmPath = Settings.RealmPath;
            }

            if (User == null || async)
            {
                User = await User.LoginAsync(Credentials.UsernamePassword(Settings.RealmUser, Settings.RealmPassword, false), new Uri(SRealmUri));
            }
            var realmUrl = new Uri(SRealmPath);
            var config   = new FullSyncConfiguration(realmUrl, User);
            //config.SchemaVersion = 6;
            Realm realm = null;

            if (async)
            {
                if (compact)
                {
                    Realm.Compact(config);
                }
                realm = await Realm.GetInstanceAsync(config);
            }
            else
            {
                realm = Realm.GetInstance(config);
            }

            if (AppConfig)
            {
                Realm = realm;
            }

            return(realm);
        }
예제 #10
0
 public void Compact_WhenInTransaction_ShouldThrow()
 {
     using var realm = GetRealm();
     Assert.That(() =>
     {
         realm.Write(() =>
         {
             Realm.Compact();
         });
     }, Throws.TypeOf <RealmInvalidTransactionException>());
 }
예제 #11
0
        public void Compact_OnWindows_ThrowsRealmException()
        {
            if (!TestHelpers.IsWindows)
            {
                // This is a windows only test that asserts that compact will throw (as it's unsupported)
                // On other platforms, we simply ignore it.
                Assert.Ignore("Compact works on this platform");
            }

            Assert.That(() => Realm.Compact(RealmConfiguration.DefaultConfiguration), Throws.TypeOf <RealmException>());
        }
예제 #12
0
        public void Compact_WhenResultsAreOpen_ShouldReturnFalse()
        {
            using var realm = GetRealm();

            var token = realm.All <Person>().SubscribeForNotifications((sender, changes, error) =>
            {
                Console.WriteLine(changes?.InsertedIndices);
            });

            Assert.That(() => Realm.Compact(), Is.False);
            token.Dispose();
        }
예제 #13
0
        public RealmDatabase(string databaseName, bool persist = true)
        {
            string folder = Path.Combine(Directory.GetCurrentDirectory(), "Databases");
            string path   = Path.Combine(folder, databaseName);

            Directory.CreateDirectory(folder);
            _configuration = persist ? new RealmConfiguration(path) : new InMemoryConfiguration(databaseName);
            if (!isCompactado && persist)
            {
                isCompactado = Realm.Compact(_configuration);
            }
        }
예제 #14
0
        public void Compact_WhenOpenOnDifferentThread_ShouldReturnFalse()
        {
            using (var realm = Realm.GetInstance())
            {
                AddDummyData(realm);

                var initialSize = new FileInfo(realm.Config.DatabasePath).Length;
                Assert.That(() => Task.Run(() => Realm.Compact(realm.Config)).Result, Is.False);
                var finalSize = new FileInfo(realm.Config.DatabasePath).Length;

                Assert.That(finalSize, Is.EqualTo(initialSize));
            }
        }
예제 #15
0
 public void Compact_WhenInTransaction_ShouldThrow()
 {
     TestHelpers.IgnoreOnWindows("Compact doesn't work on Windows");
     using (var realm = Realm.GetInstance())
     {
         Assert.That(() =>
         {
             realm.Write(() =>
             {
                 Realm.Compact();
             });
         }, Throws.TypeOf <RealmInvalidTransactionException>());
     }
 }
예제 #16
0
        public void Compact_WhenResultsAreOpen_ShouldReturnFalse()
        {
            TestHelpers.IgnoreOnWindows("Compact doesn't work on Windows");
            using (var realm = Realm.GetInstance())
            {
                var token = realm.All <Person>().SubscribeForNotifications((sender, changes, error) =>
                {
                    Console.WriteLine(changes?.InsertedIndices);
                });

                Assert.That(() => Realm.Compact(), Is.False);
                token.Dispose();
            }
        }
예제 #17
0
        /// <inheritdoc/>
        public Task ResetAsync()
        {
            return(Task.Run(() =>
            {
                using (Realm realm = Realm.GetInstance(Configuration))
                    using (Transaction transaction = realm.BeginWrite())
                    {
                        realm.RemoveAll <RealmEvent>();
                        realm.RemoveAll <RealmExceptionReport>();
                        transaction.Commit();
                    }

                Realm.Compact(Configuration);
            }));
        }
예제 #18
0
 public void Compact_WhenOpenOnSameThread_ShouldReturnFalse()
 {
     // TODO: enable when we implement instance caching (#947)
     // This works because of caching of native instances in ObjectStore.
     // Technically, we get the same native instance, so Compact goes through.
     // However, this invalidates the opened realm, but we have no way of communicating that.
     // That is why, things seem fine until we try to run queries on the opened realm.
     // Once we handle caching in managed, we should reenable the test.
     using (var realm = Realm.GetInstance())
     {
         var initialSize = new FileInfo(realm.Config.DatabasePath).Length;
         Assert.That(() => Realm.Compact(), Is.False);
         var finalSize = new FileInfo(realm.Config.DatabasePath).Length;
         Assert.That(finalSize, Is.EqualTo(initialSize));
     }
 }
예제 #19
0
        /// <inheritdoc/>
        public Task ResetAsync(Version version)
        {
            return(Task.Run(() =>
            {
                using (Realm realm = Realm.GetInstance(Configuration))
                    using (Transaction transaction = realm.BeginWrite())
                    {
                        string _version = version.ToString();
                        realm.RemoveRange(realm.All <RealmEvent>().Where(entry => entry.AppVersion == _version));
                        realm.RemoveRange(realm.All <RealmExceptionReport>().Where(entry => entry.AppVersion == _version));
                        transaction.Commit();
                    }

                Realm.Compact(Configuration);
            }));
        }
예제 #20
0
        public void Compact_WhenOpenOnSameThread_ShouldReturnTrue()
        {
            using var realm = GetRealm();

            var initialSize = new FileInfo(realm.Config.DatabasePath).Length;

            Assert.That(() => Realm.Compact(), Is.True);
            var finalSize = new FileInfo(realm.Config.DatabasePath).Length;

            Assert.That(finalSize, Is.LessThanOrEqualTo(initialSize));

            // Test that the Realm instance is still valid and we can write to it
            realm.Write(() =>
            {
                realm.Add(new Person());
            });
        }
        public void Compact_ShouldReduceSize(bool encrypt, bool populate)
        {
            TestHelpers.RunAsyncTest(async() =>
            {
                var config = GetFakeConfig();
                if (encrypt)
                {
                    config.EncryptionKey = TestHelpers.GetEncryptionKey(5);
                }

                using (var realm = GetRealm(config))
                {
                    var session = GetSession(realm);
                    session.Stop();
                    if (populate)
                    {
                        AddDummyData(realm, singleTransaction: false);
                    }

                    session.CloseHandle();
                }

                var initialSize = new FileInfo(config.DatabasePath).Length;

                var attempts = 200;

                // Give core a chance to close the Realm
                while (!Realm.Compact(config) && (attempts-- > 0))
                {
                    await Task.Delay(50);
                }

                Assert.That(attempts, Is.GreaterThan(0));

                var finalSize = new FileInfo(config.DatabasePath).Length;
                Assert.That(initialSize, Is.GreaterThanOrEqualTo(finalSize));

                using (var realm = GetRealm(config))
                {
                    Assert.That(realm.All <ObjectIdPrimaryKeyWithValueObject>().Count(), Is.EqualTo(populate ? DummyDataSize / 2 : 0));
                }
            });
        }
예제 #22
0
        public void Compact_WhenOpenOnDifferentThread_ShouldReturnFalse()
        {
            TestHelpers.RunAsyncTest(async() =>
            {
                using var realm = GetRealm();
                AddDummyData(realm);

                var initialSize  = new FileInfo(realm.Config.DatabasePath).Length;
                bool?isCompacted = null;
                await Task.Run(() =>
                {
                    isCompacted = Realm.Compact(realm.Config);
                });

                Assert.That(isCompacted, Is.False);
                var finalSize = new FileInfo(realm.Config.DatabasePath).Length;

                Assert.That(finalSize, Is.EqualTo(initialSize));
            });
        }
예제 #23
0
        // Trims the logs according to the given predicate
        private Task TrimAsync([NotNull] Predicate <ILog> predicate)
        {
            return(Task.Run(() =>
            {
                using (Realm realm = Realm.GetInstance(Configuration))
                    using (Transaction transaction = realm.BeginWrite())
                    {
                        foreach (RealmObject old in new IEnumerable <RealmObject>[]
                        {
                            realm.All <RealmExceptionReport>().ToArray().Where(log => predicate(log)),
                            realm.All <RealmEvent>().ToArray().Where(log => predicate(log))
                        }.SelectMany(l => l))
                        {
                            realm.Remove(old);
                        }
                        transaction.Commit();
                    }

                Realm.Compact(Configuration);
            }));
        }
예제 #24
0
        // Trims the saved logs according to the input predicate
        private Task TrimAsync <TLog>([NotNull] Predicate <ILog> predicate) where TLog : LogBase
        {
            return(Task.Run(() =>
            {
                using (Realm realm = Realm.GetInstance(Configuration))
                    using (Transaction transaction = realm.BeginWrite())
                    {
                        // Execute the query
                        IEnumerable <RealmObject> query;
                        if (typeof(TLog) == typeof(Event))
                        {
                            query =
                                from entry in realm.All <RealmEvent>().ToArray()
                                where predicate(entry)
                                select entry;
                        }
                        else if (typeof(TLog) == typeof(ExceptionReport))
                        {
                            query =
                                from entry in realm.All <RealmExceptionReport>().ToArray()
                                where predicate(entry)
                                select entry;
                        }
                        else
                        {
                            throw new ArgumentException("The input type is not valid", nameof(TLog));
                        }

                        // Trim the database
                        foreach (RealmObject item in query)
                        {
                            realm.Remove(item);
                        }
                        transaction.Commit();
                    }

                Realm.Compact(Configuration);
            }));
        }
예제 #25
0
        public void Compact_ShouldReduceSize(bool encrypt, bool populate)
        {
            TestHelpers.IgnoreOnWindows("Compact doesn't work on Windows");

            if (encrypt)
            {
                TestHelpers.ReliesOnEncryption();
            }

            var config = RealmConfiguration.DefaultConfiguration;

            if (encrypt)
            {
                config.EncryptionKey    = new byte[64];
                config.EncryptionKey[0] = 5;
            }

            using (var realm = Realm.GetInstance(config))
            {
                if (populate)
                {
                    AddDummyData(realm);
                }
            }

            var initialSize = new FileInfo(config.DatabasePath).Length;

            Assert.That(Realm.Compact(config));

            var finalSize = new FileInfo(config.DatabasePath).Length;

            Assert.That(initialSize >= finalSize);

            using (var realm = Realm.GetInstance(config))
            {
                Assert.That(realm.All <IntPrimaryKeyWithValueObject>().Count(), Is.EqualTo(populate ? 500 : 0));
            }
        }
예제 #26
0
        public void Compact_WhenOpenOnDifferentThread_ShouldReturnFalse()
        {
            TestHelpers.IgnoreOnWindows("Compact doesn't work on Windows");
            AsyncContext.Run(async() =>
            {
                using (var realm = Realm.GetInstance())
                {
                    AddDummyData(realm);

                    var initialSize  = new FileInfo(realm.Config.DatabasePath).Length;
                    bool?isCompacted = null;
                    await Task.Run(() =>
                    {
                        isCompacted = Realm.Compact(realm.Config);
                    });

                    Assert.That(isCompacted, Is.False);
                    var finalSize = new FileInfo(realm.Config.DatabasePath).Length;

                    Assert.That(finalSize, Is.EqualTo(initialSize));
                }
            });
        }
예제 #27
0
        public void Compact_ShouldReduceSize(bool encrypt, bool populate)
        {
            AsyncContext.Run(async() =>
            {
                var user      = await User.LoginAsync(Credentials.AccessToken("foo:bar", Guid.NewGuid().ToString(), isAdmin: false), new Uri("http://localhost:9080"));
                var serverUri = new Uri($"realm://localhost:9080/~/compactrealm_{encrypt}_{populate}.realm");

                var config = new SyncConfiguration(user, serverUri);
                if (encrypt)
                {
                    config.EncryptionKey    = new byte[64];
                    config.EncryptionKey[0] = 5;
                }

                Realm.DeleteRealm(config);

                using (var realm = Realm.GetInstance(config))
                {
                    if (populate)
                    {
                        AddDummyData(realm, singleTransaction: false);
                    }
                }

                var initialSize = new FileInfo(config.DatabasePath).Length;

                Assert.That(Realm.Compact(config));

                var finalSize = new FileInfo(config.DatabasePath).Length;
                Assert.That(initialSize >= finalSize);

                using (var realm = Realm.GetInstance(config))
                {
                    Assert.That(realm.All <IntPrimaryKeyWithValueObject>().Count(), Is.EqualTo(populate ? 500 : 0));
                }
            });
        }
예제 #28
0
        static void DeleteCNAESVazios()
        {
            using (Realm realm = Realm.GetInstance(NOME_DATABASE + ".realm"))
            {
                List <CnaeSubclasse> lista = new();
                foreach (var cnae in realm.All <CnaeSubclasse>())
                {
                    if (!cnae.Empresas.Any())
                    {
                        lista.Add(cnae);
                    }
                }
                realm.Write(() =>
                {
                    foreach (var c in lista)
                    {
                        realm.Remove(c);
                    }
                });
            }
            RealmConfiguration configuration = new(NOME_DATABASE + ".realm");

            Realm.Compact(configuration);
        }
예제 #29
0
        private static void DeleteSemEmailTelefone()
        {
            using (Realm realm = Realm.GetInstance(NOME_DATABASE + ".realm"))
            {
                List <Empresa> lista = new();
                foreach (var e in realm.All <Empresa>())
                {
                    if (e.Contato == null || string.IsNullOrEmpty(e.Contato.Email) || e.Contato.Numeros.Count == 0)
                    {
                        lista.Add(e);
                    }
                }
                realm.Write(() =>
                {
                    foreach (var c in lista)
                    {
                        realm.Remove(c);
                    }
                });
            }
            RealmConfiguration configuration = new(NOME_DATABASE + ".realm");

            Realm.Compact(configuration);
        }
예제 #30
0
 public void Compact_OnWindows_ThrowsRealmException()
 {
     Assert.That(() => Realm.Compact(RealmConfiguration.DefaultConfiguration), Throws.TypeOf <RealmException>());
 }