Пример #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
        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)
            {
            }
        }
Пример #3
0
        //[Test]
        public async System.Threading.Tasks.Task LinksAUser()
        {
            {
                // :code-block-start: link
                // 1) A user logs on anonymously:
                var anonUser = await app.LogInAsync(Credentials.Anonymous());

                // 2) They create some data, and then decide they want to save
                //    it, which requires creating an Email/Password account.
                // 3) We prompt the user to log in, and then use that info to
                //    register the new EmailPassword user, and then generate an
                //    EmailPassword credential to link the existing anonymous
                //    account:
                var email    = "*****@*****.**";
                var password = "******";
                await app.EmailPasswordAuth.RegisterUserAsync(
                    email, password);

                var officialUser = await anonUser.LinkCredentialsAsync(
                    Credentials.EmailPassword(email, password));

                // :code-block-end:
            }
            {
                // :code-block-start: link2
                var anonUser = await app.LogInAsync(Credentials.Anonymous());

                var officialUser = await anonUser.LinkCredentialsAsync(
                    Credentials.Google("<google-token>", GoogleCredentialType.AuthCode));

                // :code-block-end:
            }
            return;
        }
Пример #4
0
        public async System.Threading.Tasks.Task TearDown()
        {
            using (var realm = await Realm.GetInstanceAsync(config))
            {
                var myTask = new Task();
                // :code-block-start: delete
                realm.Write(() =>
                {
                    realm.Remove(myTask);
                });
                // :code-block-end:
                realm.Write(() =>
                {
                    realm.RemoveAll <Task>();
                    realm.RemoveAll <CustomGetterSetter>();
                });
                var user = await app.LogInAsync(Credentials.Anonymous());

                // :code-block-start: logout
                await user.LogOutAsync();

                // :code-block-end:
            }
            return;
        }
Пример #5
0
        public async ThreadTask TearDown()
        {
            App app = App.Create(myRealmAppId);

            using (var realm = Realm.GetInstance(config))
            {
                var myTask = new Task()
                {
                    Partition = "foo", Name = "foo2", Status = TaskStatus.Complete.ToString()
                };
                realm.Write(() =>
                {
                    realm.Add(myTask);
                });
                // :code-block-start: delete
                realm.Write(() =>
                {
                    realm.Remove(myTask);
                });
                // :code-block-end:
                realm.Write(() =>
                {
                    realm.RemoveAll <Task>();
                });
                var user = await app.LogInAsync(Credentials.Anonymous());

                // :code-block-start: logout
                await user.LogOutAsync();

                // :code-block-end:
            }
            return;
        }
Пример #6
0
        public async System.Threading.Tasks.Task GetsSyncedTasks()
        {
            // :code-block-start: anon-login
            var user = await app.LogInAsync(Credentials.Anonymous());

            // :code-block-end:
            // :code-block-start: config
            config = new SyncConfiguration("myPart", user);
            //:hide-start:
            config.ObjectClasses = new[]
            {
                typeof(Task),
                typeof(dotnet.User),
                typeof(CustomGetterSetter)
            };
            //: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;
        }
Пример #7
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:
        }
Пример #8
0
        public async Task handleErrors()
        {
            // :code-block-start: set-log-level
            var appConfig = new AppConfiguration(myRealmAppId)
            {
                //LogLevel = LogLevel.Debug,
                // :hide-start:
                DefaultRequestTimeout = TimeSpan.FromMilliseconds(1500)
                                        // :hide-end:
            };

            // :code-block-end:
            app  = App.Create(appConfig);
            user = await app.LogInAsync(Credentials.Anonymous());

            config = new SyncConfiguration("myPartition", user);
            //:hide-start:
            config.ObjectClasses = new[]
            {
                typeof(dotnet.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.GetSession(),
                                            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);
        }
Пример #9
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 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);
        }
Пример #10
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:
        }
Пример #11
0
        public async Task Creates()
        {
            // :code-block-start: create
            app  = App.Create(myRealmAppId);
            user = await app.LogInAsync(Credentials.Anonymous());

            mongoClient   = user.GetMongoClient("mongodb-atlas");
            dbTracker     = mongoClient.GetDatabase("tracker");
            cudCollection = dbTracker.GetCollection <CustomUserData>("user_data");

            var cud = new CustomUserData(user.Id)
            {
                FavoriteColor = "pink",
                LocalTimeZone = "+8",
                IsCool        = true
            };

            var insertResult = await cudCollection.InsertOneAsync(cud);

            // :code-block-end:
            Assert.AreEqual(user.Id, insertResult.InsertedId);
        }
Пример #12
0
        public async System.Threading.Tasks.Task LogsOnManyWays()
        {
            {
                // :code-block-start: logon_anon
                var user = await app.LogInAsync(Credentials.Anonymous());

                // :code-block-end:
                Assert.AreEqual(UserState.LoggedIn, user.State);
                await user.LogOutAsync();
            }
            {
                // :code-block-start: logon_EP
                var user = await app.LogInAsync(
                    Credentials.EmailPassword("*****@*****.**", "shhhItsASektrit!"));

                // :code-block-end:
                Assert.AreEqual(UserState.LoggedIn, user.State);
                await user.LogOutAsync();
            }
            {
                var apiKey = "F5ONly653MyQEq781wR4LT3nu3eGmIf0uDhHnkpsAkXyvsbPee8RqJyv6HVzM9dU";
                // :code-block-start: logon_API
                var user = await app.LogInAsync(Credentials.ApiKey(apiKey));

                // :code-block-end:
                Assert.AreEqual(UserState.LoggedIn, user.State);
                await user.LogOutAsync();
            }
            {
                // :code-block-start: logon_Function
                var functionParameters = new
                {
                    username = "******",
                    password = "******",
                    IQ       = 42,
                    isCool   = false
                };

                var user =
                    await app.LogInAsync(Credentials.Function(functionParameters));

                // :code-block-end:
                Assert.AreEqual(UserState.LoggedIn, user.State);
                await user.LogOutAsync();
            }
            {
                var jwt_token =
                    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9." +
                    "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6ImNhbGViQGV4YW1wbGUuY29tIiwiaWF0IjoxNjAxNjc4ODcyLCJleHAiOjI1MTYyMzkwMjIsImF1ZCI6InNuaXBwZXRzZG9ub3RkZWxldGUtcXJvdXEifQ." +
                    "Qp-sRcKAyuS5ONeBDvZuSg6-YAzohCdU3yKLnz7MXbI";
                // :code-block-start: logon_JWT
                var user =
                    await app.LogInAsync(Credentials.JWT(jwt_token));

                // :code-block-end:
                Assert.AreEqual(UserState.LoggedIn, user.State);
                await user.LogOutAsync();
            }
            try
            {
                var facebookToken = "";
                // :code-block-start: logon_fb
                var user =
                    await app.LogInAsync(Credentials.Facebook(facebookToken));

                // :code-block-end:
            }
            catch (Exception e)
            {
                Assert.AreEqual("InvalidSession: authentication via 'oauth2-facebook' is unsupported", e.Message);
            }
            try
            {
                var googleAuthCode = "";
                // :code-block-start: logon_google
                var user =
                    await app.LogInAsync(Credentials.Google(googleAuthCode, GoogleCredentialType.AuthCode));

                // :code-block-end:
            }
            catch (Exception e)
            {
                Assert.AreEqual("InvalidSession: authentication via 'oauth2-google' is unsupported", e.Message);
            }
            try
            {
                var appleToken = "";
                // :code-block-start: logon_apple
                var user =
                    await app.LogInAsync(Credentials.Apple(appleToken));

                // :code-block-end:
            }

            catch (Exception e)
            {
                Assert.AreEqual("InvalidSession: authentication via 'oauth2-apple' is unsupported", e.Message);
            }
        }
Пример #13
0
        public async Task TestUseFlexibleSync()
        {
            var app  = App.Create("dotnet-flexible-wtzwc");
            var user = await app.LogInAsync(Credentials.Anonymous());

            // :code-block-start: open-a-flexible-synced-realm
            var config = new FlexibleSyncConfiguration(app.CurrentUser);
            var realm  = Realm.GetInstance(config);
            // :code-block-end:


            // :code-block-start: get-subscriptions
            var subscriptions = realm.Subscriptions;

            // :code-block-end:

            // :code-block-start: update-subscriptions
            realm.Subscriptions.Update(() =>
            {
                // subscribe to all long running tasks, and give the subscription the name 'longRunningTasksSubscription'
                var longRunningTasksQuery = realm.All <MyTask>().Where(t => t.Status == "completed" && t.ProgressMinutes > 120);
                realm.Subscriptions.Add(longRunningTasksQuery, new SubscriptionOptions()
                {
                    Name = "longRunningTasks"
                });

                // subscribe to all of Ben's Task objects
                realm.Subscriptions.Add(realm.All <MyTask>().Where(t => t.Owner == "Ben"));

                // subscribe to all Teams, and give the subscription the name 'teamsSubscription' and throw an error if a new query is added to the team subscription
                realm.Subscriptions.Add(realm.All <Team>(), new SubscriptionOptions()
                {
                    Name = "teams", UpdateExisting = false
                });
            });
            // :code-block-end:


            // :code-block-start: wait-for-synchronization
            // Wait for the server to acknowledge the subscription change and return all objects
            // matching the query
            try
            {
                await realm.Subscriptions.WaitForSynchronizationAsync();
            }
            catch (SubscriptionException ex)
            {
                // do something in response to the exception or log it
                Console.WriteLine($@"The subscription set's state is Error and synchronization is paused:  {ex.Message}");
            }
            // :code-block-end:

            // :code-block-start: update-a-subscription
            realm.Subscriptions.Update(() =>
            {
                var updatedLongRunningTasksQuery = realm.All <MyTask>().Where(t => t.Status == "completed" && t.ProgressMinutes > 130);
                realm.Subscriptions.Add(updatedLongRunningTasksQuery, new SubscriptionOptions()
                {
                    Name = "longRunningTasks"
                });
            });
            // :code-block-end:

            // :code-block-start: remove-subscription-by-query
            realm.Subscriptions.Update(() =>
            {
                // remove a subscription by it's query
                var query = realm.All <MyTask>().Where(t => t.Owner == "Ben");
                realm.Subscriptions.Remove(query);
            });
            // :code-block-end:

            // :code-block-start: remove-subscription-by-name
            realm.Subscriptions.Update(() =>
            {
                // remove a named subscription
                var subscriptionName = "longRunningTasksSubscription";
                realm.Subscriptions.Remove(subscriptionName);
            });
            // :code-block-end:

            // :code-block-start: remove-all-subscriptions-of-object-type
            realm.Subscriptions.Update(() =>
            {
                // remove all subscriptions of the "Team" Class Name
                realm.Subscriptions.RemoveAll("Team");

                // Alernatively, remove all subscriptions of the "Team" object type
                realm.Subscriptions.RemoveAll <Team>();
            });
            // :code-block-end:

            // :code-block-start: remove-all-subscriptions
            realm.Subscriptions.Update(() =>
            {
                // remove all subscriptions, including named subscriptions
                realm.Subscriptions.RemoveAll(true);
            });
            // :code-block-end:
        }
Пример #14
0
        public async System.Threading.Tasks.Task LogsOnManyWays()
        {
            {
                // :code-block-start: logon_anon
                var user = await app.LogInAsync(Credentials.Anonymous());

                // :code-block-end:
                Assert.AreEqual(UserState.LoggedIn, user.State);
                await user.LogOutAsync();
            }
            {
                // :code-block-start: logon_EP
                var user = await app.LogInAsync(
                    Credentials.EmailPassword("*****@*****.**", "shhhItsASektrit!"));

                // :code-block-end:
                Assert.AreEqual(UserState.LoggedIn, user.State);
                await user.LogOutAsync();
            }
            {
                var apiKey = "eRECwv1e6gkLEse99XokWOgegzoguEkwmvYvXk08zAucG4kXmZu7TTgV832SwFCv";
                // :code-block-start: logon_API
                var user = await app.LogInAsync(Credentials.ApiKey(apiKey));

                // :code-block-end:
                Assert.AreEqual(UserState.LoggedIn, user.State);
                await user.LogOutAsync();
            }
            {
                // :code-block-start: logon_Function
                var functionParameters = new
                {
                    username = "******",
                    password = "******",
                    IQ       = 42,
                    isCool   = false
                };

                var user =
                    await app.LogInAsync(Credentials.Function(functionParameters));

                // :code-block-end:
                Assert.AreEqual(UserState.LoggedIn, user.State);
                await user.LogOutAsync();
            }
            {
                var jwt_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkNhbGViIiwiaWF0IjoxNjAxNjc4ODcyLCJleHAiOjI1MTYyMzkwMjIsImF1ZCI6InR1dHMtdGlqeWEifQ.LHbeSI2FDWrlUVOBxe-rasuFiW-etv2Gu5e3eAa6Y6k";
                // :code-block-start: logon_JWT
                var user =
                    await app.LogInAsync(Credentials.JWT(jwt_token));

                // :code-block-end:
                Assert.AreEqual(UserState.LoggedIn, user.State);
                await user.LogOutAsync();
            }
            try
            {
                var facebookToken = "";
                // :code-block-start: logon_fb
                var user =
                    await app.LogInAsync(Credentials.Facebook(facebookToken));

                // :code-block-end:
            }
            catch (Exception e)
            {
                Assert.AreEqual("InvalidSession: authentication via 'oauth2-facebook' is unsupported", e.Message);
            }
            try
            {
                var googleAuthCode = "";
                // :code-block-start: logon_google
                var user =
                    await app.LogInAsync(Credentials.Google(googleAuthCode, GoogleCredentialType.AuthCode));

                // :code-block-end:
            }
            catch (Exception e)
            {
                Assert.AreEqual("InvalidSession: authentication via 'oauth2-google' is unsupported", e.Message);
            }
            try
            {
                var appleToken = "";
                // :code-block-start: logon_apple
                var user =
                    await app.LogInAsync(Credentials.Apple(appleToken));

                // :code-block-end:
            }

            catch (Exception e)
            {
                Assert.AreEqual("InvalidSession: authentication via 'oauth2-apple' is unsupported", e.Message);
            }
        }