Install and Start Using the .NET SDK with Couchbase Server

    +
    The Couchbase .NET SDK enables you to interact with a Couchbase Server cluster from .NET using C# and other .NET languages. It offers an asynchronous API based on the Task-based Asynchronous Pattern (TAP).

    The Couchbase .NET client allows applications to connect to Couchbase Server using any Common Language Runtime (CLR) language, including C#, F#, and VB.NET. The SDK is written in C#, and some of its idiomatic patterns reflect that choice.

    Installing the SDK

    The Couchbase .NET SDK targets and is tested with .NET Standard 2.0 and 2.1, which in turn supports .NET Framework 4.6.2+ and .NET Core (e.g. netcoreapp) 2.1. A full list of supported platforms can be found in the .NET Standard documentation. The SDK also may use some dependencies that have not yet made it into .NET Standard; these can enabled by targeting .netcoreapp2.1 or .netcoreapp3.0. Eventually as they are added to the standard, these platform targets will be removed. The library is distributed in a number of ways:

    NuGet

    NuGet package host at nuget.org (recommended)

    Zip

    Zip files for each release are linked from the Release Notes here.

    Build from Source

    Build the library from source available on GitHub (not officially supported)

    Hello Couchbase

    Start a new console project (in Visual Studio or VS Code, etc). Install the latest 3.0 CouchbaseNetClient NuGet package.

    The following code samples assume:

    • Couchbase Server is installed and accessible locally (Do a Quick Install if you don’t already have Couchbase Server installed).

    • You have create a bucket (perhaps using the travel-sample dataset, or by creating a new bucket).

    • You have created a Couchbase user named "username" with permissions to access the cluster (at least Application Access permissions).

    Firstly, you will need to have a few using statements at the top of Program.cs in your console program:

    using System.Threading.Tasks;
    using Couchbase;

    Then you can connect to the cluster:

    var cluster = await Cluster.ConnectAsync("couchbase://localhost", "username", "password");

    Couchbase uses Role Based Access Control (RBAC) to control access to resources. If you’re developing client code on the same machine as the Couchbase Server, your URI can be couchbase://localhost.

    Then open the bucket:

    // get a bucket reference
    var bucket = await cluster.BucketAsync("bucket-name");

    Substitute whatever bucket name you want for bucket-name in the above example.

    The 3.0 SDK is ready for the introduction of Collections in an upcoming release of the Couchbase Data Platform. The latest release, Couchbase Server 6.5, brings a limited Developer Preview of Collections, allowing Documents to be grouped by purpose or theme, according to specified Scope. Here we will use the DefaultCollection, which covers the whole Bucket and must be used when connecting to a 6.5 cluster or earlier.

    // get a collection reference
    var collection = bucket.DefaultCollection();

    To get you started the following code creates a new document and then fetches it again, printing the result.

    // Upsert Document
    var upsertResult = await collection.UpsertAsync("my-document-key", new { Name = "Ted", Age = 31 });
    var getResult = await collection.GetAsync("my-document-key");
    
    Console.WriteLine(getResult.ContentAs<dynamic>());

    Other possible key/value CRUD Operations are described in detail on the KV Operations page.

    You can also perform a N1QL query with the cluster object:

    var queryResult = await cluster.QueryAsync<dynamic>("select \"Hello World\" as greeting");
    await foreach (var row in queryResult) {
        Console.WriteLine(row);
    }

    You can learn more about N1QL queries on the Query page.

    Full Example

    If you want to copy and paste to run the full example, here it is:

    • Local Couchbase Server

    • Couchbase Cloud Sample

    using System;
    using System.Threading.Tasks;
    using Couchbase;
    
    namespace examples
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                var cluster = await Cluster.ConnectAsync("couchbase://localhost", "username", "password");
                var bucket = await cluster.BucketAsync("bucket-name");
                var collection = bucket.DefaultCollection();
    
                var upsertResult = await collection.UpsertAsync("my-document-key", new { Name = "Ted", Age = 31 });
                var getResult = await collection.GetAsync("my-document-key");
                Console.WriteLine(getResult.ContentAs<dynamic>());
    
                var queryResult = await cluster.QueryAsync<dynamic>("select \"Hello World\" as greeting", new Couchbase.Query.QueryOptions());
                await foreach (var row in queryResult) {
                    Console.WriteLine(row);
                }
            }
        }
    }

    If you are connecting to Couchbase Cloud, be sure to get the correct endpoint as well as user, password, and couchbasecloudbucket — and see the Cloud section, below.

    using System;
    using System.Threading.Tasks;
    using Couchbase;
    using Couchbase.Query;
    using Couchbase.Management.Query;
    // using Microsoft.Extensions.DependencyInjection;
    // using Microsoft.Extensions.Logging;
    // using Serilog;
    // using Serilog.Extensions.Logging;
    
    namespace net3
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                // Update this to your cluster
                var endpoint = "cb.13d1a4bc-31a8-49c6-9ade-74073df0799f.dp.cloud.couchbase.com";
                var bucketName = "couchbasecloudbucket";
                var username = "user";
                var password = "password";
                // User Input ends here.
    
                // IServiceCollection serviceCollection = new ServiceCollection();
                // serviceCollection.AddLogging(builder => builder.AddFilter(level => level >= LogLevel.Trace));
    
                // var loggerFactory = serviceCollection.BuildServiceProvider().GetService<ILoggerFactory>();
                // loggerFactory.AddFile("Logs/myapp-{Date}.txt", LogLevel.Debug);
    
                // Initialize the Connection
                var opts = new ClusterOptions().WithCredentials(username, password);
                // opts = opts.WithLogging(loggerFactory);
                opts.IgnoreRemoteCertificateNameMismatch = true;
    
                var cluster = await Cluster.ConnectAsync("couchbases://"+endpoint, opts);
                var bucket = await cluster.BucketAsync(bucketName);
                var collection = bucket.DefaultCollection();
    
                // Store a Document
                var upsertResult = await collection.UpsertAsync("king_arthur", new {
                    Name = "Arthur",
                    Email = "kingarthur@couchbase.com",
                    Interests = new[] { "Holy Grail", "African Swallows" }
                });
    
                // Load the Document and print it
                var getResult = await collection.GetAsync("king_arthur");
                Console.WriteLine(getResult.ContentAs<dynamic>());
    
                // Perform a N1QL Query
                var queryResult = await cluster.QueryAsync<dynamic>(
                    String.Format("SELECT name FROM `{0}` WHERE $1 IN interests", bucketName),
                    new QueryOptions().Parameter("African Swallows")
                );
    
                // Print each found Row
                await foreach (var row in queryResult)
                {
                    Console.WriteLine(row);
                }
            }
        }
    }

    Cloud Connections

    For developing on Couchbase Cloud, if you are not working from the same Availability Zone, refer to the follorwing:

    Additional Resources

    The API reference is generated for each release. Older API references are linked from their respective sections in the Release Notes.

    The Migrating from SDK2 to 3 page highlights the main differences to be aware of when migrating your code.