Couchbase Lite for .NET Documentation

repository·master·Indexed 19 days ago

https://github.com/couchbase/couchbase-lite-net

A lightweight, embedded NoSQL database for mobile and desktop applications. It provides capabilities for managing documents, querying data via QueryBuilder and SQL++, and synchronizing with backend structures like Couchbase Server through replication. Supported platforms include .NET 6 Desktop (Linux, CentOS, Ubuntu), .NET 7 iOS, Android, Mac Catalyst, UWP, and Xamarin.

Tokens
2.9K
Snippets
3
Records
12
Agent score
66%

What's inside Couchbase Lite for .NET

  1. Understand Couchbase Lite versioning formats

    master

    Couchbase Lite uses a specific versioning structure to distinguish between stable releases and developer builds.

    Standard Version Format: Major.Minor.Patch[.Hotfix][.BuildNum] (e.g., X.Y.Z.A or X.Y.Z.A-b####)

    • Major/Minor/Patch: Standard semantic versioning components.
    • Hotfix: An optional component for rapid fixes.
    • BuildNum: An increasing count of builds generated by the CI server. If a build fails, the number is skipped.

    Developer Build Format: X.Y.Z-db###

    • Used for packages on the developer NuGet feed. db stands for developer build, followed by an increasing sequence number.

    Note on Binary Integrity: When builds are promoted from internal feeds to public feeds, the binaries remain identical. Consequently, the version reported in logs or Windows file properties may show the internal build number (e.g., X.Y.Z-b####) rather than the public developer build number. This is intentional to ensure bit-for-bit consistency between validation and shipping.

  2. Manage Documents in Couchbase Lite

    master

    Documents are managed via a Collection within a Database.

    • Creation: Use MutableDocument to define new records. Use methods like .SetString() or .SetFloat() to populate fields. Save the document using collection.Save(mutableDoc).
    • Retrieval: Use collection.GetDocument(id) to retrieve a document. This returns a read-only Document.
    • Updating: To modify a document, call .ToMutable() on the retrieved Document to get a MutableDocument. After making changes, call collection.Save(mutableDoc) to persist them.
  3. Query data using QueryBuilder or SQL++

    master

    Couchbase Lite provides two ways to query data within a collection:

    1. QueryBuilder: A type-safe, fluent API for constructing queries.

      using var query = QueryBuilder.Select(SelectResult.All())
          .From(DataSource.Collection(collection))
          .Where(Expression.Property("type").EqualTo(Expression.String("SDK")));
      var result = query.Execute();
    2. SQL++: A standard SQL-like syntax. When querying a collection directly, use the underscore _ to refer to the database.

      using var sqlppQuery = collection.CreateQuery("SELECT * FROM _ WHERE type = 'SDK'");
  4. Understand the Couchbase Lite NuGet package structure

    master

    Couchbase Lite for .NET uses a split package architecture to keep the main package size small.

    • Couchbase.Lite: This is the managed-only package. It contains the C# API surface but does not contain the native LiteCore binaries.
    • Couchbase.Lite.Support.*: These are platform-specific support packages that contain the actual native LiteCore binaries (Android ABIs, Apple xcframework, Windows x64/arm64, Linux, macOS).

    When you add the Couchbase.Lite package to your project, NuGet's per-TFM (Target Framework Moniker) dependency resolution automatically pulls in the correct Couchbase.Lite.Support package for your target platform. This ensures you only download the native binaries required for the platform you are building for.

  5. Getting Started with Couchbase Lite .NET

    master

    Couchbase Lite is an embedded NoSQL database for .NET. This starter code demonstrates the core lifecycle: initializing a database, managing documents (create, update, read), querying data using both the QueryBuilder and SQL++, and setting up replication to sync with a remote endpoint.

    Supported Platforms:

    • .NET 6 Desktop (Linux, CentOS, Ubuntu)
    • .NET 7 iOS, Android, and Mac Catalyst
    • UWP
    • Xamarin iOS and Xamarin Android
    using System;
    using Couchbase.Lite;
    using Couchbase.Lite.Query;
    using Couchbase.Lite.Sync;
    
    // 1. Initialize Database and Collection
    var database = new Database("mydb");
    var collection = database.GetDefaultCollection();
    
    // 2. Create and Save a Document
    using var createdDoc = new MutableDocument();
    createdDoc.SetFloat("version", 2.0f)
        .SetString("type", "SDK");
    collection.Save(createdDoc);
    var id = createdDoc.Id;
    
    // 3. Update a Document
    using var doc = collection.GetDocument(id);
    using var mutableDoc = doc.ToMutable();
    mutableDoc.SetString("language", "C#");
    collection.Save(mutableDoc);
    
    // 4. Querying Data
    // Using QueryBuilder
    using var query = QueryBuilder.Select(SelectResult.All())
        .From(DataSource.Collection(collection))
        .Where(Expression.Property("type").EqualTo(Expression.String("SDK")));
    
    // Using SQL++
    using var sqlppQuery = collection.CreateQuery("SELECT * FROM _ WHERE type = 'SDK'");
    
    var result = query.Execute();
    
    // 5. Replication (Syncing to Cloud)
    var targetEndpoint = new URLEndpoint(new Uri("ws://localhost:4984/getting-started-db"));
    var replConfig = new ReplicatorConfiguration(targetEndpoint);
    replConfig.AddCollection(database.GetDefaultCollection());
    replConfig.Authenticator = new BasicAuthenticator("john", "pass");
    
    var replicator = new Replicator(replConfig);
    replicator.AddChangeListener((sender, args) =>
    {
        if (args.Status.Error != null) {
            Console.WriteLine($"Error :: {args.Status.Error}");
        }
    });
    
    replicator.Start();
    
    // Note: Stop and dispose the replicator before closing/disposing the database.
  6. Configure Replication with ReplicatorConfiguration

    master

    Replication allows pushing and pulling changes between a local database and a remote endpoint (e.g., Couchbase Server).

    To set up replication:

    1. Define a URLEndpoint for the target.
    2. Create a ReplicatorConfiguration using that endpoint.
    3. Add the collections you wish to sync using replConfig.AddCollection(collection).
    4. (Optional) Provide authentication via replConfig.Authenticator = new BasicAuthenticator("user", "pass").
    5. Instantiate a Replicator with the configuration and call .Start().

    Important: Always stop and dispose of the Replicator before closing or disposing of the Database to ensure data integrity.

    var targetEndpoint = new URLEndpoint(new Uri("ws://localhost:4984/getting-started-db"));
    var replConfig = new ReplicatorConfiguration(targetEndpoint);
    replConfig.AddCollection(database.GetDefaultCollection());
    replConfig.Authenticator = new BasicAuthenticator("john", "pass");
    
    var replicator = new Replicator(replConfig);
    replicator.Start();
  7. How to obtain LiteCore native libraries

    master

    To build the native components required by Couchbase Lite, you must check out the LiteCore repository.

    1. Identify Version: Check the core_version.ini file in the root of the couchbase-lite-net repository for the ce hash to find the matching LiteCore version.
    2. Automated Download: You can use the script src/build/get_litecore_source.py provided in this repository to automate the process.
    3. Build Process: LiteCore uses CMake. Build scripts are located in the build_cmake/scripts folder of the LiteCore repository.

    Important Constraints:

    • Building for Android on Windows is not supported.
    • CMake must be installed on your system.
    • Platform-specific prerequisites may be required.
  8. Install Couchbase Lite via NuGet

    master

    To use Couchbase Lite in your .NET project, install the appropriate NuGet packages based on your target platform. The core library is Couchbase.Lite, and platform-specific support packages are required for specialized environments like UWP, Android, iOS, or WinUI.

    Core Package:

    • Couchbase.Lite

    Platform Support Packages:

    • Couchbase.Lite.Support.UWP
    • Couchbase.Lite.Support.Android
    • Couchbase.Lite.Support.iOS
    • Couchbase.Lite.Support.WinUI (available from version 3.1 onwards)
  9. Build Couchbase Lite from source

    master

    You can build the Couchbase Lite solution using Visual Studio 2022 or later. The solution contains multiple projects:

    • Couchbase.Lite: The .NET Standard base library.
    • Couchbase.Lite.Support.*: Support classes for specific platforms.

    Build Tips:

    • Selective Building: By default, building the solution builds all projects. To build only specific platforms, use the Configuration Manager in Visual Studio or build individual projects directly.
    • Reducing Build Complexity: If you only need a specific platform, you can modify the TargetFrameworks in Couchbase.Lite.csproj to remove other targets. This reduces the number of native libraries required for the build.
  10. Native Components Requirements for Couchbase Lite

    master

    Couchbase Lite for .NET relies on native libraries from LiteCore. If you are building the library from source, you must provide these native components in the vendor/prebuilt_core directory.

    Required Directory Structure:

    • Windows: windows/x86_64/bin/LiteCore.{dll,pdb}
    • macOS: macos/lib/libLiteCore.dylib (fat mach-o)
    • Linux: linux/x86_64/lib/libLiteCore.so (along with icu and stdc++ libraries)
    • iOS: prebuilt_core\ios\LiteCore.xcframework (Note: Remove the Mac Catalyst portion before building to avoid nuget.exe failures caused by symlinks)
    • iOS (Alternative): prebuilt_core\ios\couchbase-lite-core-ios.zip (Full framework including Mac Catalyst)
    • Android: prebuilt_core\android\<arch>\lib\libLiteCore.so
  11. Identify the available Couchbase Lite Support packages

    master

    The native binaries are bundled in the following support packages. While the main Couchbase.Lite package handles dependencies automatically, you may encounter these names in your dependency tree:

    • Couchbase.Lite.Support.Android
    • Couchbase.Lite.Support.Apple
    • Couchbase.Lite.Support.NetDesktop
    • Couchbase.Lite.Support.WinUI
    Couchbase.Lite.Support.{Android|Apple|NetDesktop|WinUI}