Exemplo n.º 1
0
		public Zoo(Context context)
		{
			realmConfig = (new RealmConfiguration.Builder(context)).name("library.zoo.realm").setModules(new AllAnimalsModule()).build(); // Always use explicit modules in library projects -  So always use a unique name -  Beware this is the app context

			// Reset Realm
			Realm.deleteRealm(realmConfig);
		}
Exemplo n.º 2
0
        public void TestWriteCopy()
        {
            // :code-block-start: copy_a_realm
            // open an existing realm
            var realm = Realm.GetInstance("myRealm.realm");

            // Create a RealmConfiguration for the *copy*
            var config = new RealmConfiguration("bundled.realm");

            // Make sure the file doesn't already exist
            Realm.DeleteRealm(config);

            // Copy the realm
            realm.WriteCopy(config);

            // Want to know where the copy is?
            var locationOfCopy = config.DatabasePath;
            // :code-block-end:
        }
Exemplo n.º 3
0
        public void GetInstanceWithJustFilenameTest()
        {
            var filename = Path.GetTempFileName();

            try
            {
                Assert.That(() =>
                {
                    using (Realm.GetInstance(filename))
                    {
                    }
                }, Throws.Nothing);
            }
            finally
            {
                var config = new RealmConfiguration(filename);
                Realm.DeleteRealm(config);
            }
        }
Exemplo n.º 4
0
        public void RealmWithOneClassWritesDesiredClass()
        {
            // Arrange
            var config = new RealmConfiguration("RealmWithOneClass.realm");

            Realm.DeleteRealm(config);
            config.ObjectClasses = new Type[] { typeof(LoneClass) };

            // Act
            using (var lonelyRealm = Realm.GetInstance(config)) {
                lonelyRealm.Write(() => {
                    var p  = lonelyRealm.CreateObject <LoneClass>();
                    p.Name = "The Singular";
                });

                // Assert
                Assert.That(lonelyRealm.All <LoneClass>().Count(), Is.EqualTo(1));
            }
        }
Exemplo n.º 5
0
        public void GetInstance_WhenDynamicAndDoesntExist_ReturnsEmptySchema()
        {
            var config = new RealmConfiguration(Path.GetTempFileName())
            {
                IsDynamic = true
            };

            try
            {
                using (var realm = Realm.GetInstance(config))
                {
                    Assert.That(realm.Schema, Is.Empty);
                }
            }
            finally
            {
                Realm.DeleteRealm(config);
            }
        }
Exemplo n.º 6
0
        public void OpensLocalRealm()
        {
            var pathToDb = Directory.GetCurrentDirectory() + "/db";

            if (!File.Exists(pathToDb))
            {
                Directory.CreateDirectory(pathToDb);
            }

            // :code-block-start: local-realm
            var config = new RealmConfiguration(pathToDb + "/my.realm")
            {
                IsReadOnly = true,
            };

            // :hide-start:
            config.Schema = new[]
            {
                typeof(Task),
                typeof(Examples.Models.User)
            };
            // :hide-end:
            Realm localRealm;

            try
            {
                localRealm = Realm.GetInstance(config);
            }
            catch (RealmFileAccessErrorException ex)
            {
                Console.WriteLine($@"Error creating or opening the
                    realm file. {ex.Message}");
            }
            // :code-block-end:

            try
            {
                Directory.Delete(pathToDb, true);
            }
            catch (Exception)
            {
            }
        }
Exemplo n.º 7
0
        public void UnableToOpenWithDifferentKey()
        {
            ReliesOnEncryption();

            // Arrange
            var config = new RealmConfiguration("UnableToOpenWithDifferentKey.realm");

            Realm.DeleteRealm(config);  // ensure guarded from prev tests
            var emptyKey = new byte[64];

            config.EncryptionKey = emptyKey;
            var openedWithKey = Realm.GetInstance(config);

            openedWithKey.Close();
            config.EncryptionKey[0] = 42;

            // Assert
            Assert.Throws <RealmFileAccessErrorException>(() => { using (Realm.GetInstance(config)) {} });
        }
        protected internal override void onCreate(Bundle savedInstanceState)
        {
            base.onCreate(savedInstanceState);
            ContentView = R.layout.activity_realm_basic_example;

            rootLayout = ((LinearLayout)findViewById(R.id.container));
            rootLayout.removeAllViews();

            // 3 versions of the databases for testing. Normally you would only have one.
            copyBundledRealmFile(this.Resources.openRawResource(R.raw.default0), "default0");
            copyBundledRealmFile(this.Resources.openRawResource(R.raw.default1), "default1");
            copyBundledRealmFile(this.Resources.openRawResource(R.raw.default2), "default2");

            // When you create a RealmConfiguration you can specify the version of the schema.
            // If the schema does not have that version a RealmMigrationNeededException will be thrown.
            RealmConfiguration config0 = (new RealmConfiguration.Builder(this)).name("default0").schemaVersion(3).build();

            // You can then manually call Realm.migrateRealm().
            Realm.migrateRealm(config0, new Migration());
            realm = Realm.getInstance(config0);
            showStatus("Default0");
            showStatus(realm);
            realm.close();

            // Or you can add the migration code to the configuration. This will run the migration code without throwing
            // a RealmMigrationNeededException.
            RealmConfiguration config1 = (new RealmConfiguration.Builder(this)).name("default1").schemaVersion(3).migration(new Migration()).build();

            realm = Realm.getInstance(config1);             // Automatically run migration if needed
            showStatus("Default1");
            showStatus(realm);
            realm.close();

            // or you can set .deleteRealmIfMigrationNeeded() if you don't want to bother with migrations.
            // WARNING: This will delete all data in the Realm though.
            RealmConfiguration config2 = (new RealmConfiguration.Builder(this)).name("default2").schemaVersion(3).deleteRealmIfMigrationNeeded().build();

            realm = Realm.getInstance(config2);
            showStatus("default2");
            showStatus(realm);
            realm.close();
        }
Exemplo n.º 9
0
        protected Realm GetRealmInstance()
        {
            var config = new RealmConfiguration {
                SchemaVersion = SchemaVersion
            };

            #region Migration
            /***** Se houver alguma alteração de classes, deverá ser efetuado o Migration *****/
            //config.MigrationCallback = (migration, oldSchemaVersion) =>
            //{
            //    if (oldSchemaVersion < SchemaVersion)
            //    {
            //        if (oldSchemaVersion < 1)
            //        {
            //            var newObj = migration.NewRealm.All<Class>();
            //            // Use the dynamic api for oldPeople so we can access
            //            // .FirstName and .LastName even though they no longer
            //            // exist in the class definition.
            //            var oldObj = migration.OldRealm.All("className");
            //            for (var i = 0; i < newObj.Count(); i++)
            //            {
            //                var old = oldObj.ElementAt(i);
            //                var new = newObj.ElementAt(i);
            //            }
            //        }
            //    }
            //};
            #endregion

            config.ObjectClasses = new[]
            {
                typeof(Agenda),
                typeof(Apoio),
                typeof(Informacao),
                typeof(KeyValueStorage),
                typeof(Nota),
                typeof(Pessoa),
                typeof(TimeLine)
            };

            return(Realm.GetInstance(config));
        }
Exemplo n.º 10
0
        static void Demo2CustomConfig()
        {
            // Specifica le classi da persistere e la configurazione
            var config = new RealmConfiguration("Demo2CustomConfig.realm")
            {
                SchemaVersion = 1
            };

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

            People man = new People()
            {
                FirstName = "Stefano", Age = 52
            };

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

            People woman = new People()
            {
                FirstName = "Vale", Age = 43
            };

            using (var trans = realm.BeginWrite())
            {
                realm.Add(woman);
                trans.Commit();
            }

            using (var trans = realm.BeginWrite())
            {
                woman.FirstName = "Valentina";
                trans.Commit();
            }

            using (var trans = realm.BeginWrite())
            {
                realm.Remove(man);
                trans.Commit();
            }
        }
Exemplo n.º 11
0
        public void TriggerMigrationBySchemaEditing()
        {
            // NOTE to regnerate the bundled database go edit the schema in Person.cs and comment/uncomment ExtraToTriggerMigration
            // running in between and saving a copy with the added field
            // this should never be needed as this test just needs the Realm to need migrating

            // Because Realms opened during migration are not immediately disposed of, they can't be deleted.
            // To circumvent that, we're leaking realm files.
            // See https://github.com/realm/realm-dotnet/issues/1357
            var path = TestHelpers.CopyBundledDatabaseToDocuments(FileToMigrate, Path.GetTempFileName());

            var triggersSchemaFieldValue = string.Empty;

            var configuration = new RealmConfiguration(path)
            {
                SchemaVersion     = 100,
                MigrationCallback = (migration, oldSchemaVersion) =>
                {
                    Assert.That(oldSchemaVersion, Is.EqualTo(99));

                    var oldPeople = migration.OldRealm.All("Person");
                    var newPeople = migration.NewRealm.All <Person>();

                    Assert.That(newPeople.Count(), Is.EqualTo(oldPeople.Count()));

                    for (var i = 0; i < newPeople.Count(); i++)
                    {
                        var oldPerson = oldPeople.ElementAt(i);
                        var newPerson = newPeople.ElementAt(i);

                        Assert.That(newPerson.LastName, Is.Not.EqualTo(oldPerson.TriggersSchema));
                        newPerson.LastName = triggersSchemaFieldValue = oldPerson.TriggersSchema;
                    }
                }
            };

            using (var realm = Realm.GetInstance(configuration))
            {
                var person = realm.All <Person>().Single();
                Assert.That(person.LastName, Is.EqualTo(triggersSchemaFieldValue));
            }
        }
Exemplo n.º 12
0
        public RealmControler()
        {
            string DBDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "BitsoRealm");

            if (!Directory.Exists(DBDir))
            {
                Directory.CreateDirectory(DBDir);
            }

            RealmConfiguration config = new RealmConfiguration(Path.Combine(DBDir, "AppDB.realm"));

            byte[] answerKey = new byte[64]; // key MUST be exactly this size to avoid a FormatException
            answerKey[0]         = 0x2a;     // first byte is 42
            answerKey[1]         = 0x70;     // second byte 112 followed by 62 zeroes
            config.EncryptionKey = answerKey;

            context = Realm.GetInstance(config);

            Console.WriteLine($"Realm Database Inicializada, path: {DBDir}");
        }
Exemplo n.º 13
0
        public void RealmWithOneClassThrowsIfUseOther()
        {
            // Arrange
            var config = new RealmConfiguration("RealmWithOneClass.realm");

            Realm.DeleteRealm(config);
            config.ObjectClasses = new Type[] { typeof(LoneClass) };

            // Act and assert
            using (var lonelyRealm = Realm.GetInstance(config)) {
                using (var trans = lonelyRealm.BeginWrite())
                {
                    Assert.Throws <ArgumentException>(() =>
                    {
                        lonelyRealm.CreateObject <Person>();
                    },
                                                      "Can't create an object with a class not included in this Realm");
                } // transaction
            }     // realm
        }
Exemplo n.º 14
0
        public void AddAnObjectFromAnotherRealmShouldFail()
        {
            Person p = null;

            _realm.Write(() => p = _realm.Add(new Person()));

            var secondaryConfig = new RealmConfiguration(Path.GetTempFileName());

            try
            {
                using (var otherRealm = Realm.GetInstance(secondaryConfig))
                {
                    Assert.That(() => otherRealm.Add(p), Throws.TypeOf <RealmObjectManagedByAnotherRealmException>());
                }
            }
            finally
            {
                Realm.DeleteRealm(secondaryConfig);
            }
        }
Exemplo n.º 15
0
        public void MigrationTriggersDelete()
        {
            // Arrange
            var config = new RealmConfiguration("MigrateWWillRecreate.realm")
            {
                ShouldDeleteIfMigrationNeeded = true
            };

            Realm.DeleteRealm(config);
            Assert.False(File.Exists(config.DatabasePath));

            TestHelpers.CopyBundledDatabaseToDocuments(
                "ForMigrationsToCopyAndMigrate.realm", "MigrateWWillRecreate.realm");

            // Act - should cope by deleting and silently recreating
            var realm = Realm.GetInstance(config);

            // Assert
            Assert.That(File.Exists(config.DatabasePath));
        }
Exemplo n.º 16
0
        public DataBaseHelper(Logger logger)
        {
            _logger = logger;
            string path = $"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\\RealmDesktop";
            bool   isDatabaseInitialized = Directory.Exists(path);

            if (!isDatabaseInitialized)
            {
                Directory.CreateDirectory(path);
            }

            string file = $"{path}\\default.realm";

            RealmConfiguration config = new RealmConfiguration(file)
            {
                SchemaVersion = 0
            };

            _realm = Realm.GetInstance(config);
        }
Exemplo n.º 17
0
        public void ShouldCompact_IsInvokedAfterOpening(bool shouldCompact)
        {
            var config = new RealmConfiguration($"shouldcompact.realm");

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

            var  oldSize          = new FileInfo(config.DatabasePath).Length;
            long projectedNewSize = 0;
            bool hasPrompted      = false;

            config.ShouldCompactOnLaunch = (totalBytes, bytesUsed) =>
            {
                Assert.That(totalBytes, Is.EqualTo(oldSize));
                hasPrompted      = true;
                projectedNewSize = (long)bytesUsed;
                return(shouldCompact);
            };

            using (var realm = Realm.GetInstance(config))
            {
                Assert.That(hasPrompted, Is.True);
                var newSize = new FileInfo(config.DatabasePath).Length;
                if (shouldCompact)
                {
                    Assert.That(newSize, Is.LessThan(oldSize));

                    // Less than 20% error in projections
                    Assert.That((newSize - projectedNewSize) / newSize, Is.LessThan(0.2));
                }
                else
                {
                    Assert.That(newSize, Is.EqualTo(oldSize));
                }

                Assert.That(realm.All <IntPrimaryKeyWithValueObject>().Count(), Is.EqualTo(500));
            }
        }
Exemplo n.º 18
0
        public void GetInstance_WhenDynamic_ReadsSchemaFromDisk()
        {
            var config = new RealmConfiguration(Path.GetTempFileName())
            {
                ObjectClasses = new[] { typeof(AllTypesObject) }
            };

            try
            {
                // Create the realm and add some objects
                using (var realm = Realm.GetInstance(config))
                {
                    realm.Write(() => realm.Add(new AllTypesObject
                    {
                        Int32Property          = 42,
                        RequiredStringProperty = "This is required!"
                    }));
                }

                config.IsDynamic = true;

                using (var dynamicRealm = Realm.GetInstance(config))
                {
                    Assert.That(dynamicRealm.Schema.Count == 1);

                    var objectSchema = dynamicRealm.Schema.Find(nameof(AllTypesObject));
                    Assert.That(objectSchema, Is.Not.Null);

                    var hasExpectedProp = objectSchema.TryFindProperty(nameof(AllTypesObject.RequiredStringProperty), out var requiredStringProp);
                    Assert.That(hasExpectedProp);
                    Assert.That(requiredStringProp.Type, Is.EqualTo(PropertyType.String));

                    var ato = dynamicRealm.All(nameof(AllTypesObject)).Single();
                    Assert.That(ato.RequiredStringProperty, Is.EqualTo("This is required!"));
                }
            }
            finally
            {
                Realm.DeleteRealm(config);
            }
        }
Exemplo n.º 19
0
        //readonly Realm _connection;

        public RealmConnection()
        {
            _config = new RealmConfiguration
            {
                //ShouldDeleteIfMigrationNeeded = true,
                SchemaVersion = 1,
                //https://www.realm.io/docs/dotnet/latest/#encryption
                //EncryptionKey = new byte[64] // key MUST be exactly this size
                //{
                //0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
                //0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
                //0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
                //0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,
                //0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
                //0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
                //0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
                //0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78
                //}
            };
            //_connection = Realm.GetInstance(_config);
        }
Exemplo n.º 20
0
        public DatabaseModel()
        {
            try
            {
                // need to do this if we change the schema
                RealmConfiguration config = new RealmConfiguration();
                Realm.DeleteRealm(config);
                _realm = Realm.GetInstance();
#if DEBUG
                DeleteAll();                                    // only for debugging
#endif
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"{_Tag}.{_Tag} error: {ex.Message}\n{ex.InnerException}");

                RealmConfiguration config = new RealmConfiguration();
                Realm.DeleteRealm(config);
                _realm = Realm.GetInstance();
            }
        }
Exemplo n.º 21
0
        public void GetInstance_WhenPathContainsNonASCIICharacters_ShouldWork(string path)
        {
            var folder = Path.Combine(Path.GetTempPath(), path);

            Directory.CreateDirectory(folder);
            var realmPath = Path.Combine(folder, "my.realm");
            var config    = new RealmConfiguration(realmPath);

            try
            {
                using (var realm = Realm.GetInstance(config))
                {
                    realm.Write(() => realm.Add(new Person()));
                    Assert.AreEqual(1, realm.All <Person>().Count());
                }
            }
            finally
            {
                Realm.DeleteRealm(config);
            }
        }
Exemplo n.º 22
0
        public void List_IndexOf_WhenObjectBelongsToADifferentRealm_ShouldThrow()
        {
            var owner = new Owner();

            _realm.Write(() =>
            {
                _realm.Add(owner);
            });

            var config = new RealmConfiguration(Guid.NewGuid().ToString());

            using var otherRealm = GetRealm(config);
            var otherRealmDog = new Dog();

            otherRealm.Write(() =>
            {
                otherRealm.Add(otherRealmDog);
            });

            Assert.That(() => owner.Dogs.IndexOf(otherRealmDog), Throws.InstanceOf <RealmObjectManagedByAnotherRealmException>());
        }
Exemplo n.º 23
0
        public MainWindowViewModel()
        {
            Config = new RealmConfiguration(Path.Combine(
                                                Directory.GetCurrentDirectory(), "Notification.realm"));

            var realm = Realm.GetInstance(Config);

            Counter = realm.Find <Counter>(COUNTER_KEY);
            if (Counter == null)
            {
                Counter = new Counter {
                    CounterKey = COUNTER_KEY, Count = 0,
                };
                realm.Write(() =>
                {
                    realm.Add(Counter);
                });
            }

            CountUpCommand = new DelegateCommand(CountUp);
        }
Exemplo n.º 24
0
        public SettingsDB()
        {
            var imei = Encoding.UTF8.GetBytes(DependencyService.Get <IDevice>().GetIdentifier());

            key = new byte[64] {
                0x75, 0x02, 0x18, 0x75, 0x34, 0x06, 0x07, 0x08,
                0x11, 0x32, 0x13, imei[0], 0x15, 0x25, 0x17, 0x18,
                imei[imei.Length / 2], 0x02, 0x23, 0x24, 0x73, 0x26, 0x27, 0x28,
                0x25, 0x32, 0x32, 0x34, 0x12, imei[4], 0x08, 0x38,
                0x68, 0x54, 0x41, 0x18, 0x45, 0x46, 0x32, 0x48,
                0x51, imei[1], 0x53, 0x54, 0x55, 0x25, 0x57, 0x51,
                0x61, 0x62, 0x75, 0x64, 0x65, 0x66, 0x67, 0x63,
                0x68, 0x72, 0x73, 0x25, 0x25, 0x76, 0x11, imei[imei.Length - 1]
            };
            var config = new RealmConfiguration("Settings.realm")
            {
                EncryptionKey = key
            };

            SettingsDataBase = Realm.GetInstance(config);
        }
Exemplo n.º 25
0
        public void ExceptionInMigrationCallback()
        {
            TestHelpers.CopyBundledDatabaseToDocuments(
                "ForMigrationsToCopyAndMigrate.realm", "NeedsMigrating.realm");

            var dummyException = new Exception();

            var configuration = new RealmConfiguration("NeedsMigrating.realm")
            {
                SchemaVersion = 100
            };

            configuration.MigrationCallback = (migration, oldSchemaVersion) =>
            {
                throw dummyException;
            };

            var ex = Assert.Throws <AggregateException>(() => Realm.GetInstance(configuration).Dispose());

            Assert.That(ex.Flatten().InnerException, Is.SameAs(dummyException));
        }
Exemplo n.º 26
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";
                });
            });
        }
Exemplo n.º 27
0
        public void TriggerMigrationBySchemaEditing()
        {
            // NOTE to regnerate the bundled database go edit the schema in Person.cs and comment/uncomment ExtraToTriggerMigration
            // running in between and saving a copy with the added field
            // this should never be needed as this test just needs the Realm to need migrating
            TestHelpers.CopyBundledDatabaseToDocuments(
                "ForMigrationsToCopyAndMigrate.realm", "NeedsMigrating.realm");

            var triggersSchemaFieldValue = string.Empty;

            var configuration = new RealmConfiguration("NeedsMigrating.realm")
            {
                SchemaVersion     = 100,
                MigrationCallback = (migration, oldSchemaVersion) =>
                {
                    Assert.That(oldSchemaVersion, Is.EqualTo(99));

                    var oldPeople = migration.OldRealm.All("Person");
                    var newPeople = migration.NewRealm.All <Person>();

                    Assert.That(newPeople.Count(), Is.EqualTo(oldPeople.Count()));

                    for (var i = 0; i < newPeople.Count(); i++)
                    {
                        var oldPerson = oldPeople.ElementAt(i);
                        var newPerson = newPeople.ElementAt(i);

                        Assert.That(newPerson.LastName, Is.Not.EqualTo(oldPerson.TriggersSchema));
                        newPerson.LastName = triggersSchemaFieldValue = oldPerson.TriggersSchema;
                    }
                }
            };

            using (var realm = Realm.GetInstance(configuration))
            {
                var person = realm.All <Person>().Single();
                Assert.That(person.LastName, Is.EqualTo(triggersSchemaFieldValue));
            }
        }
Exemplo n.º 28
0
        // Чтение данных из БД
        private void ReadMyInfo(string Search, MyDate DateForSearch)
        {
            var config = new RealmConfiguration()
            {
                SchemaVersion = 1
            };
            Realm  _realm      = Realm.GetInstance(config);
            var    AllDay      = _realm.All <Day>();
            string SearchDate  = Search;
            var    AllNeedDays = _realm.All <Day>().Where(f => f.Date == SearchDate).ToList();

            if (AllNeedDays.Count == 0) // Вывод если в этот день не велась статистика
            {
                PrintException();
                return;
            }
            var NeedDay = AllNeedDays[0];

            GetInformation["Cnt_sigarets"]       = NeedDay.CntSigarets;
            GetInformation["Cnt_sigarets_today"] = NeedDay.CntSigaretsToday;
            LastSigarete          = new MyDate(NeedDay.LastSigaret);
            LastSigareteYesterday = new MyDate(NeedDay.LastSigaretYesterday);
            AverageSpan           = NeedDay.SigaretAverageSpan;
            AverageSpanYesterday  = NeedDay.SigaretAverageSpanYesterday;
            FirstSigaret          = new MyDate(NeedDay.FirstSigaret);
            CntEndSmoking         = NeedDay.CntEndSmoking;
            MaxTime             = NeedDay.MaxTimeWithoutSigaret;
            SpentOnSigaretAll   = NeedDay.SpentOnSigaretAll;
            SpentOnSigaretToday = NeedDay.SpentOnSigaretToday;

            // Если сбросили статистику или не использовали приложение
            if (NeedDay.CntSigarets == 0)
            {
                PrintException();
                return;
            }

            PrintInfo(Search, DateForSearch);
        }
Exemplo n.º 29
0
        public static void CopyBundledDatabaseToDocuments(string realmName, string destPath = null, bool overwrite = true)
        {
            destPath = RealmConfiguration.GetPathToRealm(destPath);  // any relative subdir or filename works

#if __ANDROID__
            using (var asset = Android.App.Application.Context.Assets.Open(realmName))
                using (var destination = File.OpenWrite(destPath))
                {
                    asset.CopyTo(destination);
                }

            return;
#endif

            string sourceDir = string.Empty;
#if __IOS__
            sourceDir = NSBundle.MainBundle.BundlePath;
#endif
            // TODO add cases for Windows setting sourcedir for bundled files

            File.Copy(Path.Combine(sourceDir, realmName), destPath, overwrite);
        }
Exemplo n.º 30
0
        public override void SetUp()
        {
            _configuration = new RealmConfiguration {
                ObjectClasses = new[] { typeof(DynamicOwner), typeof(DynamicDog) }
            };
            if (_mode == DynamicTestObjectType.DynamicRealmObject)
            {
                _configuration.Dynamic = true;
            }

            base.SetUp();

            using (var trans = _realm.BeginWrite())
            {
                var o1 = _realm.CreateObject("DynamicOwner");
                o1.Name = "Tim";

                var d1 = _realm.CreateObject("DynamicDog");
                d1.Name   = "Bilbo Fleabaggins";
                d1.Color  = "Black";
                o1.TopDog = d1;  // set a one-one relationship
                o1.Dogs.Add(d1);

                var d2 = _realm.CreateObject("DynamicDog");
                d2.Name  = "Earl Yippington III";
                d2.Color = "White";
                o1.Dogs.Add(d2);

                // lonely people and dogs
                var o2 = _realm.CreateObject("DynamicOwner");
                o2.Name = "Dani";                           // the dog-less

                var d3 = _realm.CreateObject("DynamicDog"); // will remain unassigned
                d3.Name  = "Maggie Mongrel";
                d3.Color = "Grey";

                trans.Commit();
            }
        }
Exemplo n.º 31
0
        public void GetInstance_WhenCacheEnabled_ReturnsSameStates(bool enableCache)
        {
            var config = new RealmConfiguration(Path.GetTempFileName());

            Assert.That(config.EnableCache, Is.True);

            config.EnableCache = enableCache;

            try
            {
                var stateAccessor = typeof(Realm).GetField("_state", BindingFlags.Instance | BindingFlags.NonPublic);
                using (var first = Realm.GetInstance(config))
                    using (var second = Realm.GetInstance(config))
                    {
                        Assert.That(enableCache == ReferenceEquals(stateAccessor.GetValue(first), stateAccessor.GetValue(second)));
                    }
            }
            finally
            {
                Realm.DeleteRealm(config);
            }
        }