Example #1
0
        public IDisposable BlockAllOperations()
        {
            if (isDisposed)
            {
                throw new ObjectDisposedException(nameof(RealmContextFactory));
            }

            if (!ThreadSafety.IsUpdateThread)
            {
                throw new InvalidOperationException($"{nameof(BlockAllOperations)} must be called from the update thread.");
            }

            Logger.Log(@"Blocking realm operations.", LoggingTarget.Database);

            try
            {
                contextCreationLock.Wait();

                lock (contextLock)
                {
                    context?.Dispose();
                    context = null;
                }

                const int sleep_length = 200;
                int       timeout      = 5000;

                // see https://github.com/realm/realm-dotnet/discussions/2657
                while (!Compact())
                {
                    Thread.Sleep(sleep_length);
                    timeout -= sleep_length;

                    if (timeout < 0)
                    {
                        throw new TimeoutException("Took too long to acquire lock");
                    }
                }
            }
            catch
            {
                contextCreationLock.Release();
                throw;
            }

            return(new InvokeOnDisposal <RealmContextFactory>(this, factory =>
            {
                factory.contextCreationLock.Release();
                Logger.Log(@"Restoring realm operations.", LoggingTarget.Database);
            }));
        }
Example #2
0
        public void Close()
        {
            if (!IsOpen)
            {
                return;
            }

            Realm.Dispose();
            IsOpen = false;

            // Clean up management files for in memory realms (unit tests were filling desktop documents folder when unit testing)
            if (RealmConfiguration is InMemoryConfiguration)
            {
                string        path      = RealmConfiguration.DatabasePath;
                DirectoryInfo directory = Directory.GetParent(path);
                string        fileName  = Path.GetFileNameWithoutExtension(path);

                foreach (DirectoryInfo info in directory.GetDirectories())
                {
                    if (info.Name.Contains(fileName))
                    {
                        info.Delete(true);
                    }
                }

                foreach (FileInfo info in directory.GetFiles())
                {
                    if (info.Name.Contains(fileName))
                    {
                        info.Delete();
                    }
                }
            }
        }
Example #3
0
        public void GetUniqueInstancesDifferentThreads()
        {
            TestHelpers.RunAsyncTest(async() =>
            {
                Realm realm1 = null;
                Realm realm2 = null;
                try
                {
                    // Arrange
                    realm1 = GetRealm();

                    // Act
                    await Task.Run(() =>
                    {
                        realm2 = GetRealm();
                    });

                    // Assert
                    Assert.That(ReferenceEquals(realm1, realm2), Is.False, "ReferenceEquals");
                    Assert.That(realm1.IsSameInstance(realm2), Is.False, "IsSameInstance");
                    Assert.That(realm1, Is.EqualTo(realm2), "IsEqualTo");  // equal and same Realm but not same instance
                }
                finally
                {
                    realm1.Dispose();
                    realm2.Dispose();
                }
            });
        }
Example #4
0
        public void PermissionResponse_WhenOfferIsValid_ShouldSetRealmUrl()
        {
            AsyncContext.Run(async() =>
            {
                var alice = await SyncTestHelpers.GetUser();
                var bob   = await SyncTestHelpers.GetUser();

                // Opening a synced realm with just read permission fails.
                // OS issue: https://github.com/realm/realm-object-store/issues/312
                var realmUrl   = await GrantPermissions(alice, bob);
                var syncConfig = new SyncConfiguration(bob, new Uri(realmUrl));

                Realm realm             = null;
                Assert.That(() => realm = Realm.GetInstance(syncConfig), Throws.Nothing);
                var handler             = new EventHandler <ErrorEventArgs>((sender, e) =>
                {
                    Assert.Fail("Opening the realm should not cause an error.", e.Exception);
                });

                Session.Error += handler;

                await Task.Delay(2000);
                realm.Dispose();

                Session.Error -= handler;
            });
        }
Example #5
0
        private static void CreateWorkOuts()
        {
            Realm realm = Realm.GetInstance(GetConfigurationBase());

            using (Transaction transaction = realm.BeginWrite())
            {
                try
                {
                    foreach (int code in WorkOuts.Keys)
                    {
                        WorkOut workOut = realm.Find <WorkOut>(code);

                        if (workOut == null)
                        {
                            workOut = CreateWorkOut(realm, code);
                        }
                    }

                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("=== PROBLEM: {0}", ex.Message);
                    transaction.Rollback();
                }
                finally
                {
                    realm.Dispose();
                }
            }
        }
Example #6
0
        public void TriggerMigrationBySchemaVersion()
        {
            var config = RealmConfiguration.DefaultConfiguration;

            // Arrange
            using (var realm = Realm.GetInstance())
            {
                // new database doesn't push back a version number
                Assert.That(realm.Config.SchemaVersion, Is.EqualTo(0));
            }

            // Act
            var config2 = config.ConfigWithPath(config.DatabasePath);

            config2.SchemaVersion = 99;
            Realm realm2 = null;  // should be updated by DoesNotThrow

            try
            {
                // Assert
                Assert.That(() => realm2 = Realm.GetInstance(config2), Throws.Nothing); // same path, different version, should auto-migrate quietly
                Assert.That(realm2.Config.SchemaVersion, Is.EqualTo(99));
            }
            finally
            {
                realm2.Dispose();
            }
        }
Example #7
0
        public void GetInstanceAsync_ExecutesMigrationsInBackground()
        {
            AsyncContext.Run(async() =>
            {
                Realm realm          = null;
                var config           = RealmConfiguration.DefaultConfiguration;
                config.SchemaVersion = 1;

                using (var firstRealm = Realm.GetInstance(config))
                {
                    Assert.That(firstRealm.All <IntPrimaryKeyWithValueObject>().Count(), Is.Zero);
                }

                var threadId = Environment.CurrentManagedThreadId;
                var hasCompletedMigration = false;
                config.SchemaVersion      = 2;
                config.MigrationCallback  = (migration, oldSchemaVersion) =>
                {
                    Assert.That(Environment.CurrentManagedThreadId, Is.Not.EqualTo(threadId));
                    Task.Delay(300).Wait();
                    migration.NewRealm.Add(new IntPrimaryKeyWithValueObject
                    {
                        Id = 123
                    });
                    hasCompletedMigration = true;
                };

                Exception ex = null;
                Realm.GetInstanceAsync(config)
                .ContinueWith(t =>
                {
                    if (t.IsFaulted)
                    {
                        ex = t.Exception;
                    }
                    else
                    {
                        realm = t.Result;
                    }
                }, TaskScheduler.FromCurrentSynchronizationContext());

                var ticks = 0;
                while (realm == null)
                {
                    await Task.Delay(100);
                    ticks++;

                    if (ticks > 10)
                    {
                        Assert.Fail("Migration should have completed by now.");
                    }
                }

                Assert.That(ex, Is.Null);
                Assert.That(hasCompletedMigration);
                Assert.That(ticks, Is.GreaterThanOrEqualTo(3));
                Assert.That(realm.All <IntPrimaryKeyWithValueObject>().Count(), Is.EqualTo(1));
                realm.Dispose();
            });
        }
Example #8
0
        public void DisposeCodeSnippet()
        {
            Realm realm = Realm.GetInstance();

            // :code-block-start: dispose
            realm.Dispose();
            // :code-block-end:
        }
        public override void OnDisabled(Context context)
        {
            base.OnDisabled(context);
            Realm realm = Realm.GetInstance(DB.RealmConfiguration);

            realm.Write(() => realm.RemoveAll <WidgetLargeAltParams>());
            realm.Dispose();
        }
Example #10
0
 private void OnSessionStateChanged(SessionStateChangedMessage message)
 {
     if (message.State != SessionState.LoggedIn)
     {
         _realm?.Dispose();
         _realm = null;
     }
 }
        protected override void OnDisappearing()
        {
            base.OnDisappearing();

            LocalRealmInstance.Dispose();

            ShouldContinue = false;
        }
        public override void OnReceive(Context context, Intent intent)
        {
            base.OnReceive(context, intent);

            string action = intent.Action;

            if (action == null)
            {
                return;
            }

            int appWidgetId = intent.GetIntExtra(AppWidgetManager.ExtraAppwidgetId, AppWidgetManager.InvalidAppwidgetId);

            if (appWidgetId == AppWidgetManager.InvalidAppwidgetId)
            {
                return;
            }

            Realm             realm             = Realm.GetInstance(DB.RealmConfiguration);
            WidgetLargeParams widgetLargeParams = realm.Find <WidgetLargeParams>(appWidgetId);

            if (action.Equals(NextClick))
            {
                // Next
                int bookId    = widgetLargeParams.Book;
                int bookCount = realm.All <Book>().Count();
                realm.Write(() => widgetLargeParams.Book = bookId + 1 >= bookCount ? 0 : bookId + 1);
                Redraw(context, appWidgetId);
            }
            if (action.Equals(PreviousClick))
            {
                // Previous
                int bookId    = widgetLargeParams.Book;
                int bookCount = realm.All <Book>().Count();
                realm.Write(() => widgetLargeParams.Book = bookId - 1 < 0 ? bookCount - 1 : bookId - 1);
                Redraw(context, appWidgetId);
            }
            if (action.Equals(ReverseClick))
            {
                // Reverse order
                realm.Write(() => widgetLargeParams.Descending = !widgetLargeParams.Descending);
                Redraw(context, appWidgetId);
            }
            if (action.Equals(RefreshClick))
            {
                // Refresh
                Update(context, appWidgetId);
            }
            if (action.Equals(BookClick))
            {
                // Open Book Url
                string url     = Realm.GetInstance(DB.RealmConfiguration).Find <Book>(widgetLargeParams.Book).URL;
                Uri    uri     = Uri.Parse(url);
                Intent browser = new Intent(Intent.ActionView, uri);
                context.StartActivity(browser);
            }
            realm.Dispose();
        }
        public override void OnReceive(Context context, Intent intent)
        {
            base.OnReceive(context, intent);

            string action = intent.Action;

            if (action == null)
            {
                return;
            }

            int appWidgetId = intent.GetIntExtra(AppWidgetManager.ExtraAppwidgetId, AppWidgetManager.InvalidAppwidgetId);

            if (appWidgetId == AppWidgetManager.InvalidAppwidgetId)
            {
                return;
            }

            Realm realm = Realm.GetInstance(DB.RealmConfiguration);
            WidgetLargeAltParams widgetLargeAltParams = realm.Find <WidgetLargeAltParams>(appWidgetId);

            if (action.Equals(MenuClick))
            {
                // Show Book list
                realm.Write(() => widgetLargeAltParams.OpenMenu = !widgetLargeAltParams.OpenMenu);
                Redraw(context, appWidgetId);
            }
            if (action.Equals(MenuOutsideClick))
            {
                // Hide Book list
                realm.Write(() => widgetLargeAltParams.OpenMenu = false);
                Redraw(context, appWidgetId);
            }
            if (action.Equals(ReverseClick))
            {
                // Reverse order
                realm.Write(() => widgetLargeAltParams.Descending = !widgetLargeAltParams.Descending);
                Redraw(context, appWidgetId);
            }
            if (action.Equals(RefreshClick))
            {
                // Refresh
                Update(context, appWidgetId);
            }
            if (action.Equals(RemoteBookAdapter.SelectBook))
            {
                int bookId = intent.GetIntExtra(RemoteBookAdapter.ExtraBookId, 0);
                realm.Write(() =>
                {
                    widgetLargeAltParams.Book     = bookId;
                    widgetLargeAltParams.OpenMenu = false;
                });
                Redraw(context, appWidgetId);
            }
            realm.Dispose();
        }
Example #14
0
        /// <summary>
        /// updates a quiz in the roster
        /// </summary>
        /// <param name="editedQuizInfo">quiz to update</param>
        public static void EditQuizInfo(QuizInfo editedQuizInfo)
        {
            RealmConfiguration threadConfig = App.realmConfiguration(RosterPath);
            Realm realmDB = Realm.GetInstance(threadConfig);

            realmDB.Write(() =>
            {
                realmDB.Add(editedQuizInfo, update: true);
            });
            realmDB.Dispose();
        }
Example #15
0
 protected virtual void Dispose(bool disposing)
 {
     if (!this.disposed)
     {
         if (disposing)
         {
             realm.Dispose();
         }
     }
     this.disposed = true;
 }
Example #16
0
 public static void Using(this Realm realm, Action <Realm> action)
 {
     try
     {
         action(realm);
     }
     finally
     {
         realm.Dispose();
     }
 }
Example #17
0
 public static T Using <T>(this Realm realm, Func <Realm, T> action)
 {
     try
     {
         return(action(realm));
     }
     finally
     {
         realm.Dispose();
     }
 }
        public void Redraw(Context context, params int[] appWidgetIds)
        {
            Realm            realm            = Realm.GetInstance(DB.RealmConfiguration);
            AppWidgetManager appWidgetManager = AppWidgetManager.GetInstance(context);

            foreach (int appWidgetId in appWidgetIds)
            {
                appWidgetManager.UpdateAppWidget(appWidgetId, BuildRemoteView(context, appWidgetId, realm.Find <WidgetLargeAltParams>(appWidgetId)));
            }

            realm.Dispose();
        }
        /// <summary>
        /// Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    _realm.Dispose();
                }

                _disposed = true;
            }
        }
Example #20
0
 public async Task <bool> DisposeInstance()
 {
     try
     {
         realm.Dispose();
         return(await Task.FromResult(true));
     }
     catch (Exception ex)
     {
         Debug.WriteLine(ex.Message);
         return(await Task.FromResult(false));
     }
 }
        async void Save_Button_Clicked(object sender, EventArgs e)
        {
            realm.Write(() =>
            {
                TaskToEdit.Name   = newName;
                TaskToEdit.Status = newStatus;
            });
            OperationCompeleted(this, EventArgs.Empty);
            await Navigation.PopAsync();

            realm.Dispose();
            return;
        }
Example #22
0
            public RemoteViews GetViewAt(int position)
            {
                Realm other = Realm.GetInstance(DB.RealmConfiguration);

                if (!RealmInstance.IsSameInstance(other))
                {
                    RealmInstance.Dispose();
                    RealmInstance = other;
                }

                RemoteViews page = new RemoteViews(context.PackageName, ItemLayout);

                Book book = RealmInstance.Find <Book>(position);

                if (book == null)
                {
                    return(page);
                }

                page.SetTextViewText(Resource.Id.book_title, book.Title);

                Intent bookClick = new Intent();

                bookClick.SetAction(SelectBook);
                bookClick.PutExtra(AppWidgetManager.ExtraAppwidgetId, WidgetId);
                bookClick.PutExtra(ExtraBookId, book.ID);
                page.SetOnClickFillInIntent(Resource.Id.root, bookClick);

                if (book.ID == BookId)
                {
                    page.SetInt(Resource.Id.root, "setBackgroundColor", Color.ParseColor("#d0d0d0"));
                }
                else
                {
                    page.SetInt(Resource.Id.root, "setBackgroundColor", Color.ParseColor("#f0f0f0"));
                }

                return(page);
            }
        public void RedrawAll(Context context)
        {
            Realm            realm                  = Realm.GetInstance(DB.RealmConfiguration);
            AppWidgetManager appWidgetManager       = AppWidgetManager.GetInstance(context);
            ComponentName    appWidgetComponentName = new ComponentName(context, Java.Lang.Class.FromType(typeof(WidgetLargeAlt)).Name);

            int[] appWidgetIds = appWidgetManager.GetAppWidgetIds(appWidgetComponentName);
            foreach (int appWidgetId in appWidgetIds)
            {
                appWidgetManager.UpdateAppWidget(appWidgetId, BuildRemoteView(context, appWidgetId, realm.Find <WidgetLargeAltParams>(appWidgetId)));
            }

            realm.Dispose();
        }
Example #24
0
        protected override void OnSleep()
        {
            // Handle when your app sleeps
            CrossConnectivity.Current.ConnectivityChanged -= ConnectivityChanged;

            MessagingService.Current.Unsubscribe(MessageKeys.NavigateLogin);
            MessagingService.Current.Unsubscribe <MessagingServiceAlert>(MessageKeys.Message);
            MessagingService.Current.Unsubscribe <MessagingServiceQuestion>(MessageKeys.Question);

            if (realm != null)
            {
                realm.Dispose();
            }
        }
        public override void OnDeleted(Context context, int[] appWidgetIds)
        {
            base.OnDeleted(context, appWidgetIds);
            Realm realm = Realm.GetInstance(DB.RealmConfiguration);

            realm.Write(() =>
            {
                foreach (int appWidgetId in appWidgetIds)
                {
                    WidgetLargeAltParams widgetParams = realm.Find <WidgetLargeAltParams>(appWidgetId);
                    realm.Remove(widgetParams);
                }
            });

            realm.Dispose();
        }
        public override void OnRestored(Context context, int[] oldWidgetIds, int[] newWidgetIds)
        {
            base.OnRestored(context, oldWidgetIds, newWidgetIds);
            Realm realm = Realm.GetInstance(DB.RealmConfiguration);

            realm.Write(() =>
            {
                for (int i = 0; i < oldWidgetIds.Length; i++)
                {
                    WidgetLargeAltParams widgetLargeAltParams = realm.Find <WidgetLargeAltParams>(oldWidgetIds[i]);
                    widgetLargeAltParams.ID = newWidgetIds[i];
                }
            });

            realm.Dispose();
        }
        private async void Logout_Clicked(object sender, EventArgs e)
        {
            // Ensure the realm is closed
            taskRealm.Dispose();
            await App.RealmApp.CurrentUser.LogOutAsync();

            var root = Navigation.NavigationStack.First();

            if (!(root is LoginPage))
            {
                // App started with user logged in, so skipped the login page.
                var loginPage = new LoginPage();
                NavigationPage.SetHasBackButton(loginPage, false);
                Navigation.InsertPageBefore(loginPage, root);
            }
            await Navigation.PopToRootAsync();
        }
Example #28
0
        public IDisposable BlockAllOperations()
        {
            if (IsDisposed)
            {
                throw new ObjectDisposedException(nameof(RealmContextFactory));
            }

            Logger.Log(@"Blocking realm operations.", LoggingTarget.Database);

            contextCreationLock.Wait();

            lock (contextLock)
            {
                context?.Dispose();
                context = null;
            }

            return(new InvokeOnDisposal <RealmContextFactory>(this, endBlockingSection));
Example #29
0
        public void Cleanup()
        {
            CleanupCore();

            _realm.Dispose();

            for (var i = 0; i < 10; i++)
            {
                try
                {
                    Realm.DeleteRealm(_realm.Config);
                    break;
                }
                catch
                {
                    Task.Delay(10).Wait();
                }
            }
        }
Example #30
0
 public async Task Run(CancellationToken token, bool isBoot)
 {
     try
     {
         await Task.Run(async() =>
         {
             //Realm realm = await MyRealm.GetInstanceAsync();
             Realm realm = null;
             for (iCounter = 1; true; iCounter++)
             {
                 if (!token.IsCancellationRequested)
                 {
                     Console.WriteLine($"{TAG} Message {iCounter}");
                     if (realm != null)
                     {
                         realm.Write(() => realm.Add(new CounterMessage {
                             Text = $"Message {iCounter}"
                         }));
                     }
                 }
                 if (token.IsCancellationRequested)
                 {
                     Console.WriteLine($"{TAG} Ok exit.");
                     if (realm != null)
                     {
                         realm.Write(() => realm.Add(new CounterMessage {
                             Text = "Last message"
                         }));
                         realm.Dispose();
                     }
                     break;
                 }
                 else
                 {
                     Task.Delay(5000).Wait();
                 }
             }
         }, token);
     }
     catch (Exception ex) { Console.WriteLine($"{TAG} Erreur {ex.Message}"); }
 }