Exemplo n.º 1
0
        public void TestDeleteChildren()
        {
            // Arrange - setup some hierarchies
            realm.Write(() =>
            {
                for (var pid = 1; pid <= 4; ++pid)
                {
                    var p = realm.CreateObject <Product>();
                    p.Id  = pid; p.Name = $"Product {pid}";
                    for (var rid = 1; rid <= 5; ++rid)
                    {
                        var r = realm.CreateObject <Report>();
                        r.Id  = rid + (pid * 1000);
                        r.Ref = $"Report {pid}:{rid}";
                        p.Reports.Add(r);
                    }
                }
            });

            var delId = 1;
            var delP  = realm.All <Product>().First(p => p.Id == delId);

            Assert.IsNotNull(delP);
            Assert.That(delP.Reports.Count, Is.EqualTo(5));

            realm.Write(() =>
            {
                foreach (var r in delP.Reports.ToList()) // use ToList to get static list so can remove items
                {
                    realm.Remove(r);                     // removes from the realm, and updates delP.Reports so can't just iterate that
                }
            });

            Assert.That(delP.Reports.Count, Is.EqualTo(0));
        }
Exemplo n.º 2
0
        public void BindingPerformanceTest(int totalRecs, int recsPerTrans)
        {
            Console.WriteLine($"Binding-based performance check for {totalRecs:n} entries at {recsPerTrans} ops per transaction -------------");

            var s = "String value";

            var sw      = Stopwatch.StartNew();
            var numRecs = totalRecs / recsPerTrans;

            for (var rowIndex = 0; rowIndex < numRecs; rowIndex++)
            {
                using (var trans = _realm.BeginWrite())
                {
                    var hangOntoObjectsUntilCommit = new List <RealmObject>();
                    for (var iTrans = 0; iTrans < recsPerTrans; ++iTrans)
                    {
                        var p = _realm.CreateObject <Person>();
                        p.FirstName     = s;
                        p.IsInteresting = true;
                        hangOntoObjectsUntilCommit.Add(p);
                    }

                    trans.Commit();
                }
            }

            sw.Stop();

            Console.WriteLine("Time spent: " + sw.Elapsed);
            Console.WriteLine("Kilo-iterations per second: {0:0.00}", (numRecs / 1000) / sw.Elapsed.TotalSeconds);
        }
Exemplo n.º 3
0
        public void PopulateData()
        {
            using (var transaction = realm.BeginWrite())
            {
                realm.RemoveAll();

                //Cliente
                Cliente cliente = realm.CreateObject <Cliente>();
                cliente.ID       = 1;
                cliente.Nombre   = "Jose Perez";
                cliente.Telefono = "885456114";

                //Pedido
                Pedido pedido = realm.CreateObject <Pedido>();
                pedido.ID      = 1;
                pedido.Cliente = cliente;
                pedido.Fecha   = DateTime.Now;
                pedido.Total   = 100;

                //Lineas de pedido
                for (int i = 0; i < 10; i++)
                {
                    LineaPedido linea = realm.CreateObject <LineaPedido>();

                    linea.Descripcion = "Linea pedido " + i;
                    linea.Unidades    = 1;
                    linea.Importe     = 10 * i;

                    pedido.Lineas.Add(linea);
                }

                transaction.Commit();
            }
        }
Exemplo n.º 4
0
        public void CommittingAWriteTransactionShouldRefreshQueries()
        {
            Person p1 = null, p2, p3;

            _realm.Write(() =>
            {
                p1          = _realm.CreateObject <Person>();
                p1.FullName = "Person 1";

                p2          = _realm.CreateObject <Person>();
                p2.FullName = "Person 2";
            });

            var q   = _realm.All <Person>();
            var ql1 = q.ToList().Select(p => p.FullName);

            Assert.That(ql1, Is.EquivalentTo(new[] { "Person 1", "Person 2" }));

            _realm.Write(() =>
            {
                p1.FullName = "Modified Person";

                p3          = _realm.CreateObject <Person>();
                p3.FullName = "Person 3";
            });

            var ql2 = q.ToList().Select(p => p.FullName);

            Assert.That(ql2, Is.EquivalentTo(new[] { "Modified Person", "Person 2", "Person 3" }));
        }
Exemplo n.º 5
0
        public void Setup()
        {
            Realm.DeleteRealm(_configuration);
            _realm = Realm.GetInstance(_configuration);

            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.º 6
0
        public void SetUp()
        {
            Realm.DeleteRealm(RealmConfiguration.DefaultConfiguration);
            realm = Realm.GetInstance();

            // we don't keep any variables pointing to these as they are all added to Realm
            using (var trans = realm.BeginWrite())
            {
                /* syntax we want back needs ability for constructor to auto-bind to active write transaction
                 * new Owner {Name = "Tim", Dogs = new IList<Dog> {
                 *  new Dog {Name = "Bilbo Fleabaggins"},
                 *  new Dog {Name = "Earl Yippington III" }
                 *  } };
                 */
                Owner o1 = realm.CreateObject <Owner>();
                o1.Name = "Tim";

                Dog d1 = realm.CreateObject <Dog>();
                d1.Name   = "Bilbo Fleabaggins";
                d1.Color  = "Black";
                o1.TopDog = d1;  // set a one-one relationship
                o1.Dogs.Add(d1);

                Dog d2 = realm.CreateObject <Dog>();
                d2.Name  = "Earl Yippington III";
                d2.Color = "White";
                o1.Dogs.Add(d2);

                // lonely people and dogs
                Owner o2 = realm.CreateObject <Owner>();
                o2.Name = "Dani";                    // the dog-less

                Dog d3 = realm.CreateObject <Dog>(); // will remain unassigned
                d3.Name  = "Maggie Mongrel";
                d3.Color = "Grey";

                /*
                 * These would work if we can preserve init through weaving, like:
                 * public IList<Dog> Dogs { get; set; } = new IList<Dog>();
                 *
                 * new Owner {Name = "JP", Dogs = { new Dog { Name = "Deputy Dawg", Vaccinated=false } } };
                 * new Owner {Name = "Arwa", Dogs = { new Dog { Name = "Hairy Pawter", Color = "Black" } } };
                 * new Owner {Name = "Joe", Dogs = { new Dog { Name = "Jabba the Mutt", Vaccinated = false } } };
                 * new Owner {Name = "Alex", Dogs = { new Dog { Name = "Hairy Pawter", Color = "Black" } } };
                 * new Owner {Name = "Michael", Dogs = { new Dog { Name = "Nerf Herder", Color="Red" } } };
                 * new Owner {Name = "Adam", Dogs = { new Dog { Name = "Defense Secretary Waggles" } } };
                 * new Owner {Name = "Samuel", Dogs = { new Dog { Name = "Salacious B. Crumb", Color="Tan" } } };
                 * new Owner {Name = "Kristen"}; // Kristen's dog was abducted by Tim so she doesn't have any
                 * new Owner {Name = "Emily", Dogs = { new Dog { Name = "Pickles McPorkchop" } } };
                 * new Owner {Name = "Katsumi", Dogs = { new Dog { Name = "Sir Yaps-a-lot", Vaccinated = false } } };
                 * new Owner {Name = "Morgan", Dogs = { new Dog { Name = "Rudy Loosebooty" } } };
                 */

                trans.Commit();
            }
        }
Exemplo n.º 7
0
        protected void MakeThreePeople()
        {
            Person p1, p2, p3;

            using (var transaction = _realm.BeginWrite())
            {
                p1                        = _realm.CreateObject <Person>();
                p1.FirstName              = "John";
                p1.LastName               = "Smith";
                p1.IsInteresting          = true;
                p1.Email                  = "*****@*****.**";
                p1.Salary                 = 30000;
                p1.Score                  = -0.9907f;
                p1.Latitude               = 51.508530;
                p1.Longitude              = 0.076132;
                p1.Birthday               = new DateTimeOffset(1959, 3, 13, 0, 0, 0, TimeSpan.Zero);
                p1.PublicCertificateBytes = new byte[] { 0xca, 0xfe, 0xba, 0xbe };
                p1.OptionalAddress        = "12 Cosgrove St.";
                p1.IsAmbivalent           = true;
                transaction.Commit();
            }

            using (var transaction = _realm.BeginWrite())
            {
                p2                        = _realm.CreateObject <Person>();
                p2.FullName               = "John Doe"; // uses our setter whcih splits and maps to First/Lastname
                p2.IsInteresting          = false;
                p2.Email                  = "*****@*****.**";
                p2.Salary                 = 60000;
                p2.Score                  = 100;
                p2.Latitude               = 40.7637286;
                p2.Longitude              = -73.9748113;
                p2.Birthday               = new DateTimeOffset(1963, 4, 14, 0, 0, 0, TimeSpan.Zero);
                p2.PublicCertificateBytes = new byte[] { 0xde, 0xad, 0xbe, 0xef };
                p2.OptionalAddress        = string.Empty;
                p2.IsAmbivalent           = false;
                transaction.Commit();
            }

            using (var transaction = _realm.BeginWrite())
            {
                p3               = _realm.CreateObject <Person>();
                p3.FullName      = "Peter Jameson";
                p3.Email         = "*****@*****.**";
                p3.Salary        = 87000;
                p3.IsInteresting = true;
                p3.Score         = 42.42f;
                p3.Latitude      = 37.7798657;
                p3.Longitude     = -122.394179;
                p3.Birthday      = new DateTimeOffset(1989, 2, 25, 0, 0, 0, TimeSpan.Zero);
                transaction.Commit();
            }
        }
Exemplo n.º 8
0
        public void ShouldTriggerRealmChangedEvent()
        {
            // Arrange
            var wasNotified = false;

            _realm.RealmChanged += (sender, e) => { wasNotified = true; };

            // Act
            _realm.Write(() => _realm.CreateObject <Person>());

            // Assert
            Assert.That(wasNotified, "RealmChanged notification was not triggered");
        }
Exemplo n.º 9
0
        public void SetAndGetValue(string propertyName, object propertyValue)
        {
            AllTypesObject ato;

            using (var transaction = _realm.BeginWrite())
            {
                ato = _realm.CreateObject <AllTypesObject>();

                TestHelpers.SetPropertyValue(ato, propertyName, propertyValue);
                transaction.Commit();
            }

            Assert.That(TestHelpers.GetPropertyValue(ato, propertyName), Is.EqualTo(propertyValue));
        }
Exemplo n.º 10
0
        private void AddEntry()
        {
            var transaction = _realm.BeginWrite();
            var entry       = _realm.CreateObject <JournalEntry>();
            var metadata    = _realm.CreateObject <EntryMetadata>();

            metadata.Date   = DateTimeOffset.Now;
            metadata.Author = AuthorName;
            entry.Metadata  = metadata;

            var page = new JournalEntryDetailsPage(new JournalEntryDetailsViewModel(entry, transaction));

            Navigation.PushAsync(page);
        }
        public bool SavePerson(string id, string firstName, string lastName)
        {
            try {
                RealmInstance.Write(() => {
                    var person       = RealmInstance.CreateObject <Person> ();
                    person.ID        = id;
                    person.FirstName = firstName;
                    person.LastName  = lastName;
                });

                return(true);
            } catch {
                return(false);
            }
        }
Exemplo n.º 12
0
        public ScannerPage(INavigation nav)
        {
            _realm    = Realm.GetInstance();
            _currUser = App.pubUser;
            _nav      = nav;
            Title     = "Scan";
            zxing     = new ZXingScannerView()
            {
                HorizontalOptions = LayoutOptions.FillAndExpand,
                VerticalOptions   = LayoutOptions.FillAndExpand
            };

            zxing.OnScanResult += (result) =>
                                  Device.BeginInvokeOnMainThread(async() =>
            {
                // Stop analysis until we navigate away so we don't keep reading barcodes
                zxing.IsAnalyzing = false;
                zxing.IsScanning  = false;
                        #if __ANDROID__
                // Initialize the scanner first so it can track the current context
                MobileBarcodeScanner.Initialize(Application);
                        #endif

                if (result != null)
                {
                    var answer = await UserDialogs.Instance.ConfirmAsync("Would you like to track this barcode?", "Barcode found!", "Yes", "No");
                    if (answer == true)
                    {
                        string[] timeArray = DateTime.Now.ToString().Split(null);
                        _realm.Write(() =>
                        {
                            var newScan     = _realm.CreateObject <RealmDB.ScanResult>();
                            newScan.Date    = timeArray[0];
                            newScan.Time    = timeArray[1] + " " + timeArray[2];
                            newScan.Format  = result.BarcodeFormat.ToString();
                            newScan.Owner   = _currUser;
                            newScan.Content = result.Text;
                        });
                    }
                }
                await _nav.PopAsync();
            });

            overlay = new ZXingDefaultOverlay
            {
                TopText    = "Hold your phone up to the barcode",
                BottomText = "Scanning will happen automatically",
            };

            var grid = new Grid
            {
                VerticalOptions   = LayoutOptions.FillAndExpand,
                HorizontalOptions = LayoutOptions.FillAndExpand,
            };
            grid.Children.Add(zxing);
            grid.Children.Add(overlay);

            // The root page of your application
            Content = grid;
        }
Exemplo n.º 13
0
        public TodoItem CreateTodoItem()
        {
            var result = realm.CreateObject <TodoItem>();

            result.ID = Guid.NewGuid().ToString();
            return(result);
        }
Exemplo n.º 14
0
 public void Insert(List <InspectorsModel> inspectorsModel)
 {
     try
     {
         //using (var trans = _realm.BeginWrite())
         {
             _realm.Write(() =>
             {
                 for (int i = 0; i < inspectorsModel.Count; i++)
                 {
                     var inspector                      = _realm.CreateObject <InspectorsRealmModel>();
                     inspector.a_Cid                    = inspectorsModel[i].a_Cid;
                     inspector.a_CodVer                 = inspectorsModel[i].a_CodVer;
                     inspector.a_descrizione            = inspectorsModel[i].a_descrizione;
                     inspector.CodiceConsorzioID        = inspectorsModel[i].CodiceConsorzioID;
                     inspector.CodiceConsorzioVerbaleID = inspectorsModel[i].CodiceConsorzioVerbaleID;
                 }
             });
             //trans.Commit();
         };
     }
     catch (Exception pException)
     {
         System.Diagnostics.Debug.WriteLine("Error In Selecting InspectionsBusiness " + pException.Message);
     }
 }
Exemplo n.º 15
0
        protected void MakeThreePeople()
        {
            Person p1, p2, p3;

            using (var transaction = _realm.BeginWrite())
            {
                p1               = _realm.CreateObject <Person>();
                p1.FirstName     = "John";
                p1.LastName      = "Smith";
                p1.IsInteresting = true;
                p1.Email         = "*****@*****.**";
                p1.Score         = -0.9907f;
                p1.Latitude      = 51.508530;
                p1.Longitude     = 0.076132;
                p1.Birthday      = new DateTimeOffset(1959, 3, 13, 0, 0, 0, TimeSpan.Zero);
                transaction.Commit();
            }
            Debug.WriteLine("p1 is named " + p1.FullName);

            using (var transaction = _realm.BeginWrite())
            {
                p2               = _realm.CreateObject <Person>();
                p2.FullName      = "John Doe"; // uses our setter whcih splits and maps to First/Lastname
                p2.IsInteresting = false;
                p2.Email         = "*****@*****.**";
                p2.Score         = 100;
                p2.Latitude      = 40.7637286;
                p2.Longitude     = -73.9748113;
                p2.Birthday      = new DateTimeOffset(1963, 4, 14, 0, 0, 0, TimeSpan.Zero);
                transaction.Commit();
            }
            Debug.WriteLine("p2 is named " + p2.FullName);

            using (var transaction = _realm.BeginWrite())
            {
                p3               = _realm.CreateObject <Person>();
                p3.FullName      = "Peter Jameson";
                p3.Email         = "*****@*****.**";
                p3.IsInteresting = true;
                p3.Score         = 42.42f;
                p3.Latitude      = 37.7798657;
                p3.Longitude     = -122.394179;
                p3.Birthday      = new DateTimeOffset(1989, 2, 25, 0, 0, 0, TimeSpan.Zero);
                transaction.Commit();
            }
            Debug.WriteLine("p3 is named " + p3.FullName);
        }
        public long InsertThousandItems()
        {
            var watch = Stopwatch.StartNew();

            _realm.Write(() =>
            {
                for (int i = 0; i < 1000; i++)
                {
                    var person  = _realm.CreateObject("Person");
                    person.Name = $"Dog {i}";
                    person.Age  = 18;
                    _realm.Add(person);
                }
            });
            watch.Stop();
            return(watch.ElapsedMilliseconds);
        }
Exemplo n.º 17
0
        public void SimpleTest()
        {
            dynamic allTypesObject;

            using (var transaction = _realm.BeginWrite())
            {
                allTypesObject = _realm.CreateObject("AllTypesObject");
                Assert.That(allTypesObject, Is.InstanceOf <Realms.Dynamic.DynamicRealmObject>());

                allTypesObject.CharProperty         = 'F';
                allTypesObject.NullableCharProperty = 'o';
                allTypesObject.StringProperty       = "o";

                transaction.Commit();
            }

            Assert.That((char)(allTypesObject.CharProperty), Is.EqualTo('F'));
            Assert.That((char)(allTypesObject.NullableCharProperty), Is.EqualTo('o'));
            Assert.That(allTypesObject.StringProperty, Is.EqualTo("o"));
        }
Exemplo n.º 18
0
        public bool Save(string personId, string firstName, string lastName, string email)
        {
            try
            {
                RealmInstance.Write(() =>
                {
                    var person       = RealmInstance.CreateObject <Person>();
                    person.Id        = personId;
                    person.FirstName = firstName;
                    person.LastName  = lastName;
                    person.Email     = email;
                });

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Exemplo n.º 19
0
 private void AddEntry()
 {
     _realm.Write(() =>
     {
         var person  = _realm.CreateObject("Person");
         person.Id   = 9999999;
         person.Name = "New";
         person.Age  = 18;
         _realm.Add(person);
     });
 }
        private void AddEntry()
        {
            var transaction = _realm.BeginWrite();
            var entry       = _realm.CreateObject <JournalEntry>();

            entry.Date = DateTimeOffset.Now;

            var page = new JournalEntryDetailsPage(new JournalEntryDetailsViewModel(entry, transaction));

            Navigation.PushAsync(page);
        }
Exemplo n.º 21
0
        public void SetAndGetPropertyTest(
            [Values(0, 11, 23)] int hour,
            [Values(0, 6, 30, 59)] int mins,
            [Values(0, 6, 30, 59)] int secs,
            [Values(0, 1, 999)] int ms)
        {
            var turingsBirthday = new DateTimeOffset(1912, 6, 23, hour, mins, secs, ms, TimeSpan.Zero);

            Person turing;

            using (var transaction = _realm.BeginWrite())
            {
                turing           = _realm.CreateObject <Person>();
                turing.FirstName = "Alan";
                turing.LastName  = "Turing";
                turing.Birthday  = turingsBirthday;
                transaction.Commit();
            }

            // perform a db fetch
            var turingAgain = _realm.All <Person>().First();

            Assert.That(turingAgain.Birthday, Is.EqualTo(turingsBirthday));
        }
Exemplo n.º 22
0
        public bool Create <T>(T obj) where T : RealmObject, new()
        {
            try
            {
                realm.Write(() =>
                {
                    var newObj = realm.CreateObject <T>();
                    newObj     = obj;
                });
            }
            catch
            {
                return(false);
            }

            return(true);
        }
Exemplo n.º 23
0
        public void CreateObject_WhenPKExists_ShouldFail(Type type, object primaryKeyValue)
        {
            var pkProperty = type.GetProperties().Single(p => p.GetCustomAttribute <PrimaryKeyAttribute>() != null);

            _realm.Write(() =>
            {
                var first = _realm.CreateObject(type.Name);
                pkProperty.SetValue(first, primaryKeyValue);
            });

            Assert.That(() =>
            {
                _realm.Write(() =>
                {
                    var second = _realm.CreateObject(type.Name);
                    pkProperty.SetValue(second, primaryKeyValue);
                });
            }, Throws.InnerException.TypeOf <RealmDuplicatePrimaryKeyValueException>());
        }
Exemplo n.º 24
0
        public void SetAndGetPropertyTest()
        {
            var turingsBirthday = new DateTimeOffset(1912, 6, 23, 0, 0, 0, TimeSpan.Zero);

            Person turing;

            using (var transaction = _realm.BeginWrite())
            {
                turing           = _realm.CreateObject <Person>();
                turing.FirstName = "Alan";
                turing.LastName  = "Turing";
                turing.Birthday  = turingsBirthday;
                transaction.Commit();
            }

            // perform a db fetch
            var turingAgain = _realm.All <Person>().First();

            Assert.That(turingAgain.Birthday, Is.EqualTo(turingsBirthday));
        }
Exemplo n.º 25
0
        private void bt_Salvar_Clicked(object obj)
        {
            string msg;

            _realm = Realm.GetInstance();

            using (var transaction = _realm.BeginWrite())
            {
                var cliente = _realm.CreateObject <Cliente>();
                cliente.Nome   = TxtNome;
                cliente.Cidade = TxtCidade;

                transaction.Commit();
            }

            msg = "Temos : " + _realm.All <Cliente>().Count() + " Clientes";

            _realm.Close();

            _controle.Message(msg);
        }
Exemplo n.º 26
0
        public async void AsyncWrite_UpdateViaObjectId()
        {
            var          path = "/path/to/some/item";
            MyDataObject obj  = null;

            _realm.Write(() =>
            {
                obj      = _realm.CreateObject <MyDataObject>();
                obj.Path = path;
            });

            await _realm.WriteAsync(realm =>
            {
                var dataObj = realm.All <MyDataObject>().Single(d => d.Path == path);
                dataObj.ExpensiveToComputeValue = 123; // imagine this was a very CPU-intensive operation
            });

            // see #564
            TestHelpers.RunEventLoop(TimeSpan.FromMilliseconds(100));

            Assert.That(obj.ExpensiveToComputeValue, Is.Not.Null);
        }
Exemplo n.º 27
0
        public StaffListPageViewModel(INavigationService navigationService, Realm realm, TNaviParams naviparams) : base(navigationService)
        {
            _realm = realm;

            AddCommand = new DelegateCommand(async() =>
            {
                naviparams.Set(_realm.BeginWrite());
                naviparams.Set(_realm.CreateObject("TStaff", null));
                await NavigationService.NavigateAsync("StaffEditPage");
            });

            EditCommand = new Command <TStaff>(async(staff) =>
            {
                naviparams.Set(_realm.BeginWrite());
                naviparams.Set(staff);
                await NavigationService.NavigateAsync("StaffEditPage");
            });

            DeleteCommand = new Command <TStaff>(DeleteStaff);

            Staffs = _realm.All <TStaff>() as IEnumerable <TStaff>;
        }
        public string SaveItem(TodoItem item)
        {
            var newItem = realm.All <TodoItem>()
                          .ToList()
                          .FirstOrDefault(x => x.ID == item.ID);

            using (var trans = realm.BeginWrite()) {
                if (newItem == null)
                {
                    newItem    = realm.CreateObject <TodoItem>();
                    newItem.ID = Guid.NewGuid().ToString();
                }

                newItem.Name  = item.Name;
                newItem.Notes = item.Notes;
                newItem.Done  = item.Done;

                trans.Commit();
            }

            return(newItem?.ID);
        }
Exemplo n.º 29
0
        public async void AsyncWrite_UpdateViaPrimaryKey()
        {
            var          path = "/path/to/some/item";
            MyDataObject obj  = null;

            _realm.Write(() =>
            {
                obj      = _realm.CreateObject <MyDataObject>();
                obj.Path = path;
            });

            await _realm.WriteAsync(realm =>
            {
                var dataObj = realm.Find <MyDataObject>(path);
                dataObj.ExpensiveToComputeValue = 123; // imagine this was a very CPU-intensive operation
            });

            // see #564
            TestHelpers.RunEventLoop();

            Assert.That(obj.ExpensiveToComputeValue, Is.Not.Null);
        }
Exemplo n.º 30
0
        // Method to login the user
        public async void Login(string userParam, string passParam)
        {
            _realm = Realm.GetInstance();
            var currentUser = _realm.All <RealmDB.User>().Where(d => (d.username == userParam)).ToList().FirstOrDefault();

            if (currentUser == null)
            {
                // Give the user opportunity to create a new user
                var answer = await UserDialogs.Instance.ConfirmAsync("User not found, create user " + userParam + "?", "Cancel", "Create");

                if (answer == true)
                {
                    _realm.Write(() =>
                    {
                        var newUser      = _realm.CreateObject <RealmDB.User>();
                        newUser.username = userParam;
                        newUser.password = passParam;
                    });
                    RealmDB.User loginUser = new RealmDB.User();
                    loginUser.username = userParam;
                    loginUser.password = passParam;
                    // Show successful login
                    UserDialogs.Instance.SuccessToast("User created", null, 3000);
                    PostLogin(loginUser);
                }
            }
            else
            {
                // Check if the username & password match
                RealmDB.User loginUser = _realm.All <RealmDB.User>().Where(u => u.username == userParam && u.password == passParam).ToList().FirstOrDefault();
                if (loginUser == null)
                {
                    // Show login failure
                    UserDialogs.Instance.ErrorToast("Login failed", "Username or password incorrect", 3000);
                }
                PostLogin(loginUser);
            }
        }