コード例 #1
0
        public async ThreadTask GetsSyncedTasks()
        {
            App app = App.Create(myRealmAppId);
            // :code-block-start: anon-login
            var user = await app.LogInAsync(Credentials.Anonymous());

            // :code-block-end:
            // :code-block-start: config
            config = new PartitionSyncConfiguration("myPart", user);
            //:hide-start:
            config.Schema = new[]
            {
                typeof(Task),
                typeof(User)
            };
            //:hide-end:
            var realm = await Realm.GetInstanceAsync(config);

            // :code-block-end:
            // :code-block-start: read-all
            var tasks = realm.All <Task>();

            // :code-block-end:
            //Assert.AreEqual(1, tasks.Count(),"Get All");
            // :code-block-start: read-some
            tasks = realm.All <Task>().Where(t => t.Status == "Open");
            // :code-block-end:
            //Assert.AreEqual(1, tasks.Count(), "Get Some");
            return;
        }
コード例 #2
0
        //[Test]// Commented because git builder can't find/save/write the file
        public async Task ExtractAndLoadRealmFile()
        {
            // :code-block-start: extract_and_copy_realm
            // :replace-start: {
            //  "terms": {
            //   "Config.appid": "\"myRealmAppId\""}
            // }
            // If you are using a local realm
            var config = RealmConfiguration.DefaultConfiguration;

            // If the realm file is a synced realm
            var app  = App.Create(Config.appid);
            var user = await app.LogInAsync(Credentials.Anonymous());

            config = new PartitionSyncConfiguration("myPartition", user);
            // :hide-start:
            config.Schema = new[] { typeof(Examples.Models.User) };
            // :hide-end:
            // :replace-end:

            // Extract and copy the realm
            if (!File.Exists(config.DatabasePath))
            {
                using var bundledDbStream = Assembly.GetExecutingAssembly()
                                            .GetManifestResourceStream("bundled.realm");
                using var databaseFile = File.Create(config.DatabasePath);
                bundledDbStream.CopyTo(databaseFile);
            }

            // Open the Realm:
            var realm = Realm.GetInstance(config);
            // :code-block-end:
        }
コード例 #3
0
    private async void ReadCopy()
    {
        // :code-block-start: read_a_realm_unity
        // After copying the above created file to the project folder,
        // we can access it in Application.dataPath

        // If you are using a local realm
        var config = RealmConfiguration.DefaultConfiguration;

        // If the realm is synced realm
        var app  = App.Create("myRealmAppId");
        var user = await app.LogInAsync(Credentials.Anonymous());

        config = new PartitionSyncConfiguration("myPartition", user);

        if (!File.Exists(config.DatabasePath))
        {//:uncomment-start:
         //FileUtil.CopyFileOrDirectory(Path.Combine(Application.dataPath,
         //     "bundled.realm"), config.DatabasePath);
         //:uncomment-end:
        }

        var realm = Realm.GetInstance(config);
        // :code-block-end:
    }
コード例 #4
0
        public async Task TestWaitForChangesToDownloadAsync()
        {
            var appConfig = new AppConfiguration(myRealmAppId)
            {
                DefaultRequestTimeout = TimeSpan.FromMilliseconds(1500)
            };

            app    = App.Create(appConfig);
            user   = app.LogInAsync(Credentials.Anonymous()).Result;
            config = new PartitionSyncConfiguration("myPartition", user);
            try
            {
                // :code-block-start: wait-for-changes-to-download-async-progress-notification
                // :uncomment-start:
                // using Realms.Sync;

                // :uncomment-end:
                var realm = Realm.GetInstance(config);
                await realm.SyncSession.WaitForDownloadAsync();

                // :code-block-end:
                realm.Dispose();
            }
            catch (Exception ex)
            {
            }
        }
コード例 #5
0
        public async ThreadTask OpenIfUserExists()
        {
            app = App.Create(myRealmAppId);
            User user3;
            PartitionSyncConfiguration config3;
            Realm realm3;

            // :code-block-start: check-if-offline
            // :replace-start: {
            //  "terms": {
            //   "app3": "app",
            //   "user3": "user",
            //   "config3" : "config",
            //   "realm3": "realm" }
            // }
            if (app.CurrentUser == null)
            {
                // App must be online for user to authenticate
                user3 = await app.LogInAsync(
                    Credentials.EmailPassword("*****@*****.**", "shhhItsASektrit!"));

                config3 = new PartitionSyncConfiguration("_part", user3);
                realm3  = await Realm.GetInstanceAsync(config3);
            }
            else
            {
                // This works whether online or offline
                user3   = app.CurrentUser;
                config3 = new PartitionSyncConfiguration("_part", user3);
                realm3  = Realm.GetInstance(config3);
            }
            // :replace-end:
            // :code-block-end:
        }
コード例 #6
0
        public async ThreadTask ModifiesATask()
        {
            // App app = App.Create(myRealmAppId);
            config = new PartitionSyncConfiguration("myPart", user);
            //:hide-start:
            config.Schema = new[]
            {
                typeof(Task),
                typeof(User)
            };
            //:hide-end:
            var realm = await Realm.GetInstanceAsync(config);

            // :code-block-start: modify
            var t = realm.All <Task>()
                    .FirstOrDefault(t => t.Id == testTaskId);

            realm.Write(() =>
            {
                t.Status = TaskStatus.InProgress.ToString();
            });

            // :code-block-end:
            var ttest = realm.All <Task>().FirstOrDefault(x => x.Id == t.Id);

            //Assert.AreEqual(1, allTasks.Count);
            Assert.AreEqual(TaskStatus.InProgress.ToString(), ttest.Status);

            return;
        }
コード例 #7
0
        public async ThreadTask Setup()
        {
            app  = App.Create(myRealmAppId);
            user = await app.LogInAsync(
                Credentials.EmailPassword("*****@*****.**", "foobar"));

            config        = new PartitionSyncConfiguration("myPart", user);
            config.Schema = new[]
            {
                typeof(MyClass)
            };
            return;
        }
コード例 #8
0
        public async Task ResetsTheClient()
        {
            app = App.Create(myRealmAppId);

            user = app.LogInAsync(Credentials.EmailPassword("*****@*****.**", "foobar")).Result;

            config = new PartitionSyncConfiguration("myPart", user);
            //:hide-start:
            config.Schema = new[] { typeof(User) };
            //:hide-end:
            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.SyncSession,
                                            ErrorCode.DivergingHistories, "diverging histories!", false);
        }
コード例 #9
0
        public async ThreadTask Setup()
        {
            app = App.Create(myRealmAppId);
            // :code-block-start: open-synced-realm
            user = await app.LogInAsync(
                Credentials.EmailPassword("*****@*****.**", "foobar"));

            config = new PartitionSyncConfiguration("myPart", user);
            //:hide-start:
            // Internal Note: this is so we can have a more "global" instance
            // or the realm object but the code snippet can show
            // it being initialized
            config.Schema = new[]
            {
                typeof(Task),
                typeof(Examples.Models.User)
            };
            Realm realm = Realm.GetInstance(config);

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

            realm.Write(() =>
            {
                realm.RemoveAll <Task>();
            });

            // :code-block-start: open-synced-realm-synchronously
            // :uncomment-start:
            // var synchronousRealm = await Realm.GetInstanceAsync(config);
            // :uncomment-end:
            // :code-block-end:

            return;
        }
コード例 #10
0
        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 PartitionSyncConfiguration("myPartition", user);
            var realm = Realm.GetInstance(config);
            // :code-block-start: upload-download-progress-notification
            var session = realm.SyncSession;
            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);
        }
コード例 #11
0
        public async ThreadTask Setup()
        {
            // :code-block-start: initialize-realm
            app = App.Create(myRealmAppId);
            // :code-block-end:

            user = await app.LogInAsync(
                Credentials.EmailPassword("*****@*****.**", "foobar"));

            config        = new PartitionSyncConfiguration("myPart", user);
            config.Schema = new[]
            {
                typeof(Task),
                typeof(User)
            };

            Realm realm = Realm.GetInstance(config);

            realm.Write(() =>
            {
                realm.RemoveAll <Task>();
            });

            // :code-block-start: open-synced-realm-sync
            // :uncomment-start:
            // var synchronousRealm = await Realm.GetInstanceAsync(config);
            // :uncomment-end:
            // :code-block-end:
            // :code-block-start: create
            var testTask = new Task
            {
                Name      = "Do this thing",
                Status    = TaskStatus.Open.ToString(),
                Partition = "myPart"
            };

            realm.Write(() =>
            {
                realm.Add(testTask);
            });
            // :code-block-end:
            testTaskId = testTask.Id;

            return;
        }
コード例 #12
0
ファイル: MongoDBExamples.cs プロジェクト: nlarew/docs-realm
        public async Task Setup()
        {
            app  = App.Create(myRealmAppId);
            user = await app.LogInAsync(Credentials.EmailPassword("*****@*****.**", "foobar"));

            config = new PartitionSyncConfiguration("myPart", user);

            // :code-block-start: mongo-setup
            mongoClient      = user.GetMongoClient("mongodb-atlas");
            dbPlantInventory = mongoClient.GetDatabase("inventory");
            plantsCollection = dbPlantInventory.GetCollection <Plant>("plants");
            // :code-block-end:

            await InsertsOne();
            await InsertsMany();

            return;
        }
コード例 #13
0
 public async ThreadTask ScopesARealm()
 {
     // :code-block-start: scope
     config = new PartitionSyncConfiguration("myPart", user);
     //:hide-start:
     config.Schema = new Type[]
     {
         typeof(Task),
         typeof(Examples.Models.User),
         typeof(AClassWorthStoring),
         typeof(AnotherClassWorthStoring)
     };
     //:hide-end:
     using (var realm = Realm.GetInstance(config))
     {
         var allTasks = realm.All <Task>();
     }
     // :code-block-end:
 }
コード例 #14
0
        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:
        }
コード例 #15
0
        public void DoDecimalStuff()
        {
            // :hide-start:
            var app    = App.Create(Config.appid);
            var user   = app.LogInAsync(Credentials.EmailPassword("*****@*****.**", "foobar")).Result;
            var config = new PartitionSyncConfiguration("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);
            });
        }
コード例 #16
0
        public async System.Threading.Tasks.Task Setup()
        {
            app    = App.Create(myRealmAppId);
            user   = app.LogInAsync(Credentials.EmailPassword("*****@*****.**", "foobar")).Result;
            config = new PartitionSyncConfiguration("foo", user);
            //:hide-start:
            config.Schema = new[]
            {
                typeof(UserTask),
                typeof(UserProject)
            };
            //:hide-end:
            var realm = await Realm.GetInstanceAsync(config);

            var synchronousRealm = await Realm.GetInstanceAsync(config);

            var t = new UserTask()
            {
                Priority = 100, ProgressMinutes = 5, Assignee = "Jamie"
            };
            var t2 = new UserTask()
            {
                Priority = 1, ProgressMinutes = 500, Assignee = "Elvis"
            };
            var up = new UserProject()
            {
                Name = "A Big Project"
            };

            up.Tasks.Add(t);
            up.Tasks.Add(t2);
            realm.Write(() =>
            {
                realm.Add(t);
                realm.Add(t2);
                realm.Add(up);
            });
            return;
        }
コード例 #17
0
        private static async Task MainAsync(string[] args)
        {
            var app  = App.Create(myRealmAppId);
            var user = await app.LogInAsync(Credentials.Anonymous());

            var config = new PartitionSyncConfiguration("partition", user);

            using var realm = await Realm.GetInstanceAsync();

            var foos = realm.All <TestClass>().Where(f => f.Bar > 5);

            foreach (var foo in foos)
            {
                await Task.Delay(10); // Simulates some background work

                Console.WriteLine(foo.Bar);
            }
            //:hide-start:
            await Task.Delay(10);

            //:hide-end:
        }
コード例 #18
0
        public async Task Setup()
        {
            app    = App.Create(myRealmAppId);
            user   = app.LogInAsync(Credentials.EmailPassword("*****@*****.**", "foobar")).Result;
            config = new PartitionSyncConfiguration("myPart", user);
            //:hide-start:
            config.Schema = new[] { typeof(Plant) };
            //:hide-end:
            SetupPlantCollection();

            await plantsCollection.DeleteManyAsync();

            venus = new Plant
            {
                Name      = "Venus Flytrap",
                Sunlight  = Sunlight.Full.ToString(),
                Color     = PlantColor.White.ToString(),
                Type      = PlantType.Perennial.ToString(),
                Partition = "Store 42"
            };
            sweetBasil = new Plant
            {
                Name      = "Sweet Basil",
                Sunlight  = Sunlight.Partial.ToString(),
                Color     = PlantColor.Green.ToString(),
                Type      = PlantType.Annual.ToString(),
                Partition = "Store 42"
            };
            thaiBasil = new Plant
            {
                Name      = "Thai Basil",
                Sunlight  = Sunlight.Partial.ToString(),
                Color     = PlantColor.Green.ToString(),
                Type      = PlantType.Perennial.ToString(),
                Partition = "Store 42"
            };
            helianthus = new Plant
            {
                Name      = "Helianthus",
                Sunlight  = Sunlight.Full.ToString(),
                Color     = PlantColor.Yellow.ToString(),
                Type      = PlantType.Annual.ToString(),
                Partition = "Store 42"
            };
            petunia = new Plant
            {
                Name      = "Petunia",
                Sunlight  = Sunlight.Full.ToString(),
                Color     = PlantColor.Purple.ToString(),
                Type      = PlantType.Annual.ToString(),
                Partition = "Store 47"
            };

            var listofPlants = new List <Plant>
            {
                venus,
                sweetBasil,
                thaiBasil,
                helianthus,
                petunia
            };

            var insertResult = await plantsCollection.InsertManyAsync(listofPlants);



            return;
        }
コード例 #19
0
        public async Task HandleErrors()
        {
            // :code-block-start: set-log-level
            Logger.LogLevel = LogLevel.Debug;
            // :code-block-end:


            // :code-block-start: customize-logging-function
            // :uncomment-start:
            //using Realms.Logging;
            //Logger.LogLevel = LogLevel.All;
            // :uncomment-end:
            // customize the logging function:
            Logger.Default = Logger.Function(message =>
            {
                // Do something with the message
            });
            // :code-block-end:
            var appConfig = new AppConfiguration(myRealmAppId)
            {
                DefaultRequestTimeout = TimeSpan.FromMilliseconds(1500)
            };

            app  = App.Create(appConfig);
            user = await app.LogInAsync(Credentials.Anonymous());

            config = new PartitionSyncConfiguration("myPartition", user);
            //:hide-start:
            config.Schema = new[] { typeof(Examples.Models.User) };
            //:hide-end:
            var realm = await Realm.GetInstanceAsync(config);

            // :code-block-start: handle-errors
            Session.Error += (session, errorArgs) =>
            {
                var sessionException = (SessionException)errorArgs.Exception;
                switch (sessionException.ErrorCode)
                {
                case ErrorCode.AccessTokenExpired:
                case ErrorCode.BadUserAuthentication:
                    // Ask user for credentials
                    break;

                case ErrorCode.PermissionDenied:
                    // Tell the user they don't have permissions to work with that Realm
                    // :hide-start:
                    didTriggerErrorHandler = true;
                    // :hide-end:
                    break;

                case ErrorCode.Unknown:
                    // Likely the app version is too old, prompt for update
                    break;
                    // ...
                }
            };
            // :code-block-end:
            TestingExtensions.SimulateError(realm.SyncSession,
                                            ErrorCode.PermissionDenied, "No permission to work with the Realm", false);

            // 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();

            Assert.IsTrue(didTriggerErrorHandler);
        }