Navigation

Sync Changes Between Devices - .NET SDK

Before you can access a synced realm from the client, you must:

To open a synced realm, call the GetInstanceAsync() method, passing in a SyncConfiguration object that includes the partition name and the user. The following code demonstrates this:

config = new SyncConfiguration("myPart", user);
var realm = await Realm.GetInstanceAsync(config);

In the above example, the code shows how to open the realm asynchronously by calling GetInstanceAsync(). You can also open a realm synchronously by calling the GetInstance() method, which is necessary if the device is offline.

var synchronousRealm = Realm.GetInstance(config);
Note

The first time a user logs on to your realm app, you should open the realm asynchronously to sync data from the server to the device. After that initial connection, you can open a realm synchronously to ensure the app works in an offline state.

The partition value specifies which subset of your data to sync. This is typically a user ID, project ID, store ID, or some other category identifier in your app that has particular relevance to the current user.

Tip
See also:

The syntax to read and write on a synced realm is identical to the syntax for non-synced realms. While you work with local data, a background thread efficiently integrates, uploads, and downloads changesets.

Important
When Using Sync, Avoid Writes on the Main Thread

The fact that Realm performs sync integrations on a background thread means that if you write to your realm on the main thread, there's a small chance your UI could appear to hang as it waits for the background sync thread to finish a write transaction. Therefore, it's a best practice never to write on the main thread when using Realm Sync.

The following code creates a new Task object and writes it to the realm:

var testTask = new Task
{
Name = "Do this thing",
Status = TaskStatus.Open.ToString()
};
realm.Write(() =>
{
realm.Add(testTask);
});
Tip
See also:

Realm Sync represents errors via SessionExceptions. In addition to the standard exception properties, you have access to an ErrorCode that contains information about the type of the error and allows you to have strongly typed handling logic.

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
break;
case ErrorCode.Unknown:
// Likely the app version is too old, prompt for update
break;
// ...
}
};

To control which messages are logged by the sync client logger, set the LogLevel property of the AppConfiguration object:

var appConfig = new AppConfiguration(myRealmAppId)
{
LogLevel = LogLevel.Debug,
};
Give Feedback