public async System.Threading.Tasks.Task GetsSyncedTasks() { var user = await app.LogInAsync(Credentials.Anonymous()); config = new SyncConfiguration("myPart", user); var realm = await Realm.GetInstanceAsync(config); var tasks = realm.All <Task>(); Assert.AreEqual(1, tasks.Count(), "Get All"); tasks = realm.All <Task>().Where(t => t.Status == "Open"); Assert.AreEqual(1, tasks.Count(), "Get Some"); return; }
public async Task GetsSyncedTasks() { var user = app.LogInAsync(Credentials.Anonymous()).Result; config = new SyncConfiguration("My Project", user); var realm = await Realm.GetInstanceAsync(config); var tasks = realm.All <RealmTask>(); Assert.AreEqual(1, tasks.Count(), "Get All"); tasks = realm.All <RealmTask>().Where(t => t.Status == "Open"); Assert.AreEqual(1, tasks.Count(), "Get Some"); return; }
public async System.Threading.Tasks.Task InverseQuery() { var realm = await Realm.GetInstanceAsync(); realm.Write(() => { realm.RemoveAll <Task>(); realm.RemoveAll <UserTwo>(); }); UserTwo user = new UserTwo() { Name = "Katie" }; realm.Write(() => { realm.Add(user); }); var task1 = new Task() { Text = "Defribillate the master oscillator", Assignee = user }; var task2 = new Task() { Text = "Subvert the paradigm", Assignee = user }; realm.Write(() => { realm.Add(task1); realm.Add(task2); }); // :code-block-start: inverse-query var oscillatorAssignees = realm.All <UserTwo>() .Filter("Tasks.Text CONTAINS 'oscillator'").ToList(); foreach (UserTwo u in oscillatorAssignees) { Console.WriteLine(u.Name); } // :code-block-end: Assert.AreEqual(1, oscillatorAssignees.Count()); Assert.AreEqual("Katie", oscillatorAssignees[0].Name); return; }
public async Task resetsTheClient() { app = App.Create(myRealmAppId); user = app.LogInAsync(Credentials.EmailPassword("*****@*****.**", "foobar")).Result; config = new SyncConfiguration("myPartition", user); var realm = await Realm.GetInstanceAsync(config); // :code-block-start: handle Session.Error += (sender, err) => { if (err.Exception is ClientResetException clientResetEx) { var session = (Session)sender; Console.WriteLine("Client Reset requested for " + session.Path + "due to " + clientResetEx.Message); // Prompt user to perform client reset immediately. If they don't do it, // they won't receive any data from the server until they restart the app // and all changes they make will be discarded when the app restarts. var didUserConfirmReset = true; if (didUserConfirmReset) { // Close the Realm before doing the reset as it'll need // to be deleted and all objects obtained from it will be // invalidated. realm.Dispose(); var didReset = clientResetEx.InitiateClientReset(); if (didReset) { // Navigate the user back to the main page or reopen the // the Realm and reinitialize the current page. } else { // Reset failed - notify user that they'll need to restart the app. } // :hide-start: Assert.IsTrue(didReset); // :hide-end: } } }; // :code-block-end: TestingExtensions.SimulateError(realm.GetSession(), ErrorCode.DivergingHistories, "diverging histories!", false); }
public async System.Threading.Tasks.Task TearDown() { config = new SyncConfiguration("myPartition", user); using (var realm = await Realm.GetInstanceAsync(config)) { realm.Write(() => { realm.RemoveAll <Task>(); }); var realmUser = await app.LogInAsync(Credentials.Anonymous()); await realmUser.LogOutAsync(); } return; }
public async Task QueryEmbeddedObject() { var realm = await Realm.GetInstanceAsync(config); var losAngelesContacts = realm.All <Contact>().Filter("Address.City == 'Los Angeles'"); // Find All Contacts with an Address of "Los Angeles" foreach (Contact losAngelesContact in losAngelesContacts) { Console.WriteLine("Los Angeles Contact:"); Console.WriteLine(losAngelesContact.Name); Console.WriteLine(losAngelesContact.Address.Street); } // Test that the query worked and that the Contacts returned actually are from 'Los Angeles' Assert.AreEqual(losAngelesContacts.FirstOrDefault().Address.City, "Los Angeles"); }
public static async Task <Realm> GetInstanceAsync(SyncConfiguration config, bool openAsync, bool waitForRemote = true) { if (openAsync) { return(await Realm.GetInstanceAsync(config)); } var realm = Realm.GetInstance(config); if (waitForRemote) { await realm.GetSession().WaitForDownloadAsync(); } return(realm); }
private async Task OpenRealm() { await Task.Yield(); var dialog = new ProgressDialog(new ProgressDialogConfig { IsDeterministic = true, Title = "Downloading Realm...", AutoShow = true, MaskType = MaskType.Black, }); try { dialog.Show(); var user = await User.LoginAsync(Constants.Credentials, Constants.AuthUri); var config = new FullSyncConfiguration(Constants.RealmUri, user) { OnProgress = (progress) => { dialog.PercentComplete = (int)(progress.TransferredBytes * 100 / progress.TransferableBytes); } }; _realm = await Realm.GetInstanceAsync(config); var feedItems = _realm.All <FeedItem>().OrderByDescending(f => f.Date); var tvSource = FeedTableView.Source as FeedDataSource; tvSource.SetSource(feedItems); dialog.Hide(); FeedTableView.ReloadData(); } catch (Exception ex) { Console.WriteLine(ex); dialog.Hide(); await UserDialogs.Instance.AlertAsync("An error occurred", ex.ToString()); } finally { await Task.Delay(10); dialog.Hide(); } }
public void GetInstanceAsync_OpensReadonlyRealm(bool singleTransaction) { AsyncContext.Run(async() => { var alice = await SyncTestHelpers.GetUser(); var bob = await SyncTestHelpers.GetUser(); var realmUrl = SyncTestHelpers.GetRealmUrl(userId: alice.Identity); var aliceConfig = new SyncConfiguration(alice, new Uri(realmUrl)); var aliceRealm = Realm.GetInstance(aliceConfig); // TODO: replace with wrapper API await GrantPermissions(alice, bob, realmUrl); AddDummyData(aliceRealm, singleTransaction); var bobConfig = new SyncConfiguration(bob, new Uri(realmUrl)); var bobRealm = await Realm.GetInstanceAsync(bobConfig); var bobsObjects = bobRealm.All <IntPrimaryKeyWithValueObject>(); var alicesObjects = aliceRealm.All <IntPrimaryKeyWithValueObject>(); Assert.That(bobsObjects.Count(), Is.EqualTo(alicesObjects.Count())); var bobTcs = new TaskCompletionSource <object>(); bobsObjects.AsRealmCollection().CollectionChanged += (sender, e) => { bobTcs.TrySetResult(null); }; aliceRealm.Write(() => { aliceRealm.Add(new IntPrimaryKeyWithValueObject { Id = 9999, StringValue = "Some value" }); }); await bobTcs.Task.Timeout(1000); Assert.That(bobsObjects.Count(), Is.EqualTo(alicesObjects.Count())); var bobObject = bobRealm.Find <IntPrimaryKeyWithValueObject>(9999); Assert.That(bobObject, Is.Not.Null); Assert.That(bobObject.StringValue, Is.EqualTo("Some value")); }); }
public async Task TestUploadDownloadProgressNotification() { var progressNotificationTriggered = false; var appConfig = new AppConfiguration(myRealmAppId) { DefaultRequestTimeout = TimeSpan.FromMilliseconds(1500) }; app = App.Create(appConfig); user = app.LogInAsync(Credentials.Anonymous()).Result; config = new SyncConfiguration("myPartition", user); var realm = await Realm.GetInstanceAsync(config); // :code-block-start: upload-download-progress-notification var session = realm.GetSession(); var token = session.GetProgressObservable(ProgressDirection.Upload, ProgressMode.ReportIndefinitely) .Subscribe(progress => { // :hide-start: progressNotificationTriggered = true; // :hide-end: Console.WriteLine($"transferred bytes: {progress.TransferredBytes}"); Console.WriteLine($"transferable bytes: {progress.TransferableBytes}"); }); // :code-block-end: upload-download-progress-notification var id = 2; var myObj = new ProgressObj { Id = id }; realm.Write(() => { realm.Add(myObj); }); realm.Write(() => { realm.RemoveAll <ProgressObj>(); }); // :code-block-start: remove-progress-notification token.Dispose(); // :code-block-end: remove-progress-notification Assert.IsTrue(progressNotificationTriggered); }
public async Task TearDown() { config = new SyncConfiguration("myPartition", user); using var realm = await Realm.GetInstanceAsync(config); { var filter = new BsonDocument("name", "Thai Basil"); var deleteResult = await plantsCollection.DeleteOneAsync(filter); } { var filter = new BsonDocument("type", PlantType.Annual); var deleteResult = await plantsCollection.DeleteManyAsync(filter); } await plantsCollection.DeleteManyAsync(); return; }
public async System.Threading.Tasks.Task TearDown() { config = new SyncConfiguration("My Project", user); Realm realm = await Realm.GetInstanceAsync(config); // :code-block-start: delete realm.Write(() => { realm.RemoveAll <RealmTask>(); }); // :code-block-end: // :code-block-start: logout await user.LogOutAsync(); // :code-block-end: return; }
public async System.Threading.Tasks.Task OneToManyQuery() { var realm = await Realm.GetInstanceAsync(); realm.Write(() => { realm.RemoveAll <Dog>(); realm.RemoveAll <Person>(); }); var dog1 = new Dog() { Id = ObjectId.GenerateNewId(), Name = "Fido", Age = 1 }; var dog2 = new Dog() { Id = ObjectId.GenerateNewId(), Name = "Spot", Age = 1 }; var dog3 = new Dog() { Id = ObjectId.GenerateNewId(), Name = "Lucky", Age = 2 }; var person = new Person() { Name = "Katie" }; realm.Write(() => { person.Dogs.Add(dog1); person.Dogs.Add(dog2); person.Dogs.Add(dog3); realm.Add(person); }); // :code-block-start: one-to-many-query var youngDogs = realm.All <Dog>().Where(d => d.Age == 1).OrderBy(dog => dog.Name).ToList(); // :code-block-end: var younglist = new List <Dog>(); younglist.Add(dog1); younglist.Add(dog2); Assert.AreEqual(youngDogs[0].Name, younglist[0].Name); }
protected async Task <Realm> GetRealmAsync(RealmConfigurationBase config, bool openAsync = true, CancellationToken cancellationToken = default(CancellationToken)) { Realm result; if (openAsync) { result = await Realm.GetInstanceAsync(config, cancellationToken); } else { result = Realm.GetInstance(config); await SyncTestHelpers.WaitForDownloadAsync(result); } CleanupOnTearDown(result); return(result); }
private static async Task MainAsync(string[] args) { var app = App.Create(myRealmAppId); var user = await app.LogInAsync(Credentials.Anonymous()); var config = new SyncConfiguration("partition", user); using var realm = await Realm.GetInstanceAsync(); var foos = realm.All <Foo>().Where(f => f.Bar > 5); foreach (var foo in foos) { await Task.Delay(10); // Simulates some background work Console.WriteLine(foo.Bar); } }
public async System.Threading.Tasks.Task ScopesARealm() { // :code-block-start: scope config = new SyncConfiguration("myPart", user); //:hide-start: config.ObjectClasses = new[] { typeof(Task), typeof(dotnet.User), typeof(CustomGetterSetter) }; //:hide-end: using (var realm = await Realm.GetInstanceAsync(config)) { var allTasks = realm.All <Task>(); } // :code-block-end: }
public async Task <bool> DeleteItemAsync(string id) { using (var realm = await Realm.GetInstanceAsync()) { var item = realm.All <RealmCurrency>().First(f => f.Code == id); if (item == null) { return(false); } using (var transition = realm.BeginWrite()) { realm.Remove(item); transition.Commit(); return(true); } } }
protected override async void OnAppearing() { projectPartition = $"project={App.RealmApp.CurrentUser.Id}"; WaitingLayout.IsVisible = true; try { var syncConfig = new SyncConfiguration(projectPartition, App.RealmApp.CurrentUser); taskRealm = await Realm.GetInstanceAsync(syncConfig); SetUpTaskList(); } catch (Exception ex) { await DisplayAlert("Error Fetching Tasks", ex.Message, "OK"); } base.OnAppearing(); }
private async Task <bool> LogIn() { try { var user = User.Current; if (user == null) { // Not already logged in. var loginResult = await UserDialogs.Instance.LoginAsync("Log in", "Enter a username and password"); if (!loginResult.Ok) { return(false); } // Create credentials with the given username and password. // Leaving the third parameter null allows a user to be registered // if one does not already exist for this username. var credentials = Realms.Sync.Credentials.UsernamePassword(loginResult.LoginText, loginResult.Password); // Log in as the user. user = await User.LoginAsync(credentials, new Uri(Constants.AuthUrl)); } Debug.Assert(user != null); var configuration = new FullSyncConfiguration(new Uri(Constants.RealmPath, UriKind.Relative), user); _realm = await Realm.GetInstanceAsync(configuration); // Get the list of items. Entries = _realm.All <Item>().OrderBy(i => i.Timestamp); Console.WriteLine("Login successful."); return(true); } catch (Exception ex) { // Display the error message. await Application.Current.MainPage.DisplayAlert("Error", ex.Message, "OK"); return(false); } }
public async Task WorkWithSets() { if (realm == null) { realm = await Realm.GetInstanceAsync(); } //:code-block-start:query-sets //:replace-start: { // "terms": { // "PlantInventory": "Inventory"} // } var inventory = new PlantInventory(); inventory.PlantSet.Add(new Plant() { Name = "Prickly Pear" }); inventory.DoubleSet.Add(123.45); realm.Write(() => { realm.Add <PlantInventory>(inventory); }); // convert the Plant Set to an IQueryable and apply a filter var pricklyPear = inventory.PlantSet.AsRealmQueryable() .Where(p => p.Name == "Prickly Pear"); // Alternatively, apply a filter directly on the Plant Set var pricklyPearPlants = inventory.PlantSet .Filter("Name == 'Prickly Pear'"); // Find all Inventory items that have at least one value in their // IntDict that is larger than 5 var moreThan100 = realm.All <PlantInventory>() .Filter("DoubleSet.@values > 100"); // :replace-end: //:code-block-end: Assert.IsNotNull(pricklyPear); Assert.IsNotNull(pricklyPearPlants); Assert.IsNotNull(moreThan100); }
public async System.Threading.Tasks.Task Comparisons() { var realm = await Realm.GetInstanceAsync(config); var tasks = realm.All <UserTask>(); // :code-block-start: comparisons var highPri = tasks.Where(t => t.Priority > 5); var quickTasks = tasks.Where(t => 1 <= t.ProgressMinutes && t.ProgressMinutes < 15); var unassignedTasks = tasks.Where(t => t.Assignee == null); var AliOrJamieTasks = tasks.Where(t => new List <string> { "Ali", "Jamie" } .Contains(t.Assignee)); // :code-block-end: // :code-block-start: logical var completedTasksForAli = tasks.Where(t => t.Assignee == "Ali" && t.IsComplete); // :code-block-end: // :code-block-start: strings bool ignoreCase = true; var tasksThatStartWithE = tasks.Where(t => t.Name.StartsWith("E", ignoreCase, CultureInfo.CurrentCulture)); var tasksNamesWithIe = tasks.Where(t => t.Name.Contains("ie", StringComparison.OrdinalIgnoreCase)); // :code-block-end: var projects = realm.All <UserProject>(); // :code-block-start: aggregate var highPriProjects = projects.Where(p => p.Tasks.Average(task => task.Priority) > 5); var longRunningProjects = projects.Where(p => p.Tasks.Sum(t => t.ProgressMinutes) > 120); // :code-block-end: return; }
public async Task UpdateEmbeddedObject() { var realm = await Realm.GetInstanceAsync(config); var resultContact = realm.All <Contact>() // Find the First Contact (Sorted By Name) .OrderBy(c => c.Name) .FirstOrDefault(); // Update the Result Contact's Embedded Address Object's Properties realm.Write(() => { resultContact.Address.Street = "Hollywood Upstairs Medical College"; resultContact.Address.City = "Los Angeles"; resultContact.Address.PostalCode = "90210"; }); // Test that the Contact embedded Address's Street has been updated Assert.AreEqual(resultContact.Address.Street, "Hollywood Upstairs Medical College"); }
public async Task WorkWithLists() { if (realm == null) { realm = await Realm.GetInstanceAsync(); } var listInventory = new ListInventory() { Id = ObjectId.GenerateNewId().ToString() }; listInventory.Plants.Add(new Plant() { Name = "Prickly Pear", Color = PlantColor.Green.ToString() }); realm.Write(() => { realm.Add <ListInventory>(listInventory); }); //:code-block-start:query-lists //:replace-start: { // "terms": { // "ListInventory": "Inventory"} // } var firstPlants = realm.All <ListInventory>().ElementAt(0).Plants; // convert the Plant List to an IQueryable and apply a filter // to find plants with a name of "Prickly Pear" var pricklyPearCacti = firstPlants.AsQueryable().Where(plant => plant.Name == "Prickly Pear"); // Alternatively, apply a filter directly on the plant list var pricklyPearCactiCactiPlants = firstPlants.Filter("Name == 'Prickly Pear'"); // Find all Inventory items that have a green colored plant var greenPlants = realm.All <ListInventory>().Filter("Plants.Color CONTAINS[c] 'Green'"); // :replace-end: //:code-block-end: Assert.IsNotNull(pricklyPearCacti); Assert.IsNotNull(pricklyPearCactiCactiPlants); Assert.AreEqual(1, greenPlants.Count()); }
public async Task QueryEmbeddedObject() { using (var realm = await Realm.GetInstanceAsync(config)) { var address = new Address() // Create an Address { Street = "123 Fake St.", City = "Los Angeles", Country = "USA", PostalCode = "90710" }; var newContact = new Contact() // Create a Contact { Name = "Foo Barbaz", Partition = "myPart", Address = address // Embed the Address Object }; realm.Write(() => { realm.Add(newContact); }); // :code-block-start:query // Find All Contacts with an Address of "Los Angeles" var losAngelesContacts = realm.All <Contact>() .Filter("address.city == 'Los Angeles'"); foreach (var contact in losAngelesContacts) { Console.WriteLine("Los Angeles Contact:"); Console.WriteLine(contact.Name); Console.WriteLine(contact.Address.Street); } //:code-block-end: // Test that the query worked and that the Contacts returned // actually are from 'Los Angeles'. Assert.AreEqual(losAngelesContacts.FirstOrDefault() .Address.City, "Los Angeles"); } }
public static async Task DoSomeThingAsync() { var config = new RealmConfiguration(Environment.CurrentDirectory + "\\database.realm") { EncryptionKey = Encoding.ASCII.GetBytes("OIUygsRx8bTuFTSuie5dEFCpV5mIaHXWXu3ru3i5eYFtqwe6FQpUmkXXqp7qUgQy".ToCharArray(), 0, 64), // Pass HEX(128bit) for Realm Studio: 4f495579677352783862547546545375696535644546437056356d496148585758753372753369356559467471776536465170556d6b58587170377155675179 IsDynamic = false, IsReadOnly = false, SchemaVersion = 2, MigrationCallback = (migration, oldSchemaVersion) => { // potentially lengthy data migration }, // ObjectClasses = new[] { typeof(EntryMetadata), typeof(JournalEntry) }, // if is dynamic ShouldDeleteIfMigrationNeeded = false }; try { var realm = await Realm.GetInstanceAsync(config); // Realm successfully opened, with migration applied on background thread Console.Clear(); var jur = new JournalEntriesViewModel(realm); foreach (var e in jur.Entries) { Console.WriteLine(e.Title); } while (true) { var addedEntry = await jur.AddEntryAsync(); Console.WriteLine(addedEntry.Title); Console.ReadKey(); } } catch (Exception ex) { // Handle exception that occurred while opening the Realm Console.Error.WriteLine(ex.Message); } }
public async Task TestWriteCopySynced() { var appConfig = new AppConfiguration(Config.appid); var app = App.Create(appConfig); var user = await app.LogInAsync(Credentials.Anonymous()); // :code-block-start: copy_a_synced_realm // open an existing realm // :uncomment-start: // var existingConfig = new PartitionSyncConfiguration("myPartition", user); // :uncomment-end: // :hide-start: var existingConfig = new PartitionSyncConfiguration("myPartition", user) { Schema = new[] { typeof(Models.User) } }; // :hide-end: var realm = await Realm.GetInstanceAsync(existingConfig); // Create a RealmConfiguration for the *copy* // Be sure the partition name matches the original var bundledConfig = new PartitionSyncConfiguration("myPartition", user, "bundled.realm"); // Make sure the file doesn't already exist Realm.DeleteRealm(bundledConfig); // IMPORTANT: When copying a Synced realm, you must ensure // that there are no pending Sync operations. You do this // by calling WaitForUploadAsync() and WaitForDownloadAsync(): var session = realm.SyncSession; await session.WaitForUploadAsync(); await session.WaitForDownloadAsync(); // Copy the realm realm.WriteCopy(bundledConfig); // Want to know where the copy is? var locationOfCopy = existingConfig.DatabasePath; // :code-block-end: }
public void PlayWithDecimals() { // :hide-start: var app = App.Create("tuts-tijya"); var user = app.LogInAsync(Credentials.EmailPassword("*****@*****.**", "foobar")).Result; var config = new SyncConfiguration("myPart", user); var realm = Realm.GetInstanceAsync().Result; // :hide-end: var myInstance = new MyClassWithDecimals(); // To store decimal values: realm.Write(() => { myInstance.VeryPreciseNumber = 1.234567890123456789M; myInstance.EvenMorePreciseNumber = Decimal128.Parse("987654321.123456789"); // Decimal128 has explicit constructors that take a float or a double myInstance.EvenMorePreciseNumber = new Decimal128(9.99999); }); }
public async System.Threading.Tasks.Task TestsCustomSetter() { var foo = new CustomGetterSetter() { Email = "*****@*****.**" }; using (var realm = await Realm.GetInstanceAsync(config)) { realm.Write(() => { realm.Add(foo); }); Assert.IsNotNull(foo.Email); var bar = realm.All <CustomGetterSetter>().Where(f => f._id == foo._id).FirstOrDefault(); Assert.AreEqual("*****@*****.**", bar.Email); } }
public async System.Threading.Tasks.Task ModifiesATask() { config = new SyncConfiguration("myPart", user); var realm = await Realm.GetInstanceAsync(config); var t = realm.All <Task>() .FirstOrDefault(t => t.Id == testTaskId); realm.Write(() => { t.Status = TaskStatus.InProgress.ToString(); }); var allTasks = realm.All <Task>().ToList(); Assert.AreEqual(1, allTasks.Count); Assert.AreEqual(TaskStatus.InProgress.ToString(), allTasks.First().Status); return; }
private async AsyncTask LoadProjects() { try { var syncConfig = new SyncConfiguration( $"user={ App.RealmApp.CurrentUser.Id }", App.RealmApp.CurrentUser); userRealm = await Realm.GetInstanceAsync(syncConfig); user = userRealm.Find <User>(App.RealmApp.CurrentUser.Id); if (user == null && !Constants.AlreadyWarnedAboutBackendSetup) { // Either the trigger hasn't completed yet, has failed, // or was never created on the backend // So let's wait a few seconds and check again... await System.Threading.Tasks.Task.Delay(5000); user = userRealm.Find <User>(App.RealmApp.CurrentUser.Id); if (user == null) { Console.WriteLine("NO USER OBJECT: This error occurs if " + "you do not have the trigger configured on the backend " + "or when there is a network connectivity issue. See " + "https://www.mongodb.com/docs/realm/tutorial/realm-app/#triggers"); await DisplayAlert("No User object", "The User object for this user was not found on the server. " + "If this is a new user acocunt, the backend trigger may not have completed, " + "or the tirgger doesn't exist. Check your backend set up and logs.", "OK"); Constants.AlreadyWarnedAboutBackendSetup = true; } } SetUpProjectList(); } catch (Exception ex) { await DisplayAlert("Error Loading Projects", ex.Message, "OK"); } }