Introduction

This guide provides information for developers who want to use the Couchbase .NET SDK to build applications that use Couchbase Server.

Getting Started

This chapter will get you started with using Couchbase Server and the.NET (C#) Client Library. This article will walk you through the following:

  1. Downloading and installing the Couchbase client library.

  2. Setting up a command-line driven C# application in Visual Studio 2010, and referencing the Couchbase client library.

  3. Writing a simple program to demonstrate connecting to Couchbase and saving some data in the database.

  4. Exploring the Couchbase client library’s API so that you are better equipped to begin to write more complex applications.

This section assumes you have downloaded and set up a compatible version of Couchbase Server and have at least one instance of Couchbase Server and one data bucket established. If you need to set up these items, you can do with the Couchbase Administrative Console, or Couchbase Command-Line Interface (CLI), or the Couchbase REST API. For information and instructions, see:

The TCP/IP port allocation on Windows by default includes a restricted number of ports available for client communication. For more information on this issue, including information on how to adjust the configuration and increase the available ports, see MSDN: Avoiding TCP/IP Port Exhaustion.

After you have your Couchbase Server set up and you have installed the Couchbase SDK, you can compile and run the following basic program.

Downloading the Couchbase Client Library

The Couchbase.NET client library is a.NET library that can be downloaded from the Couchbase Client Library language center http://memcached.enyim.com. It is shared with a lower-level library implements the memcached protocol (which is also the low-level protocol supported by Couchbase), along with more functionality through the enhancements that Couchbase provides.

Hello C# Couchbase

The easiest way to create and compile C# programs is by using Visual Studio 2010. Let’s go into Visual Studio and create a HelloCouchbase project by completing the following steps (see Figure 2):

  1. Click on File > New > Project

  2. Choose: Visual C# > Windows > Console Application as your template

  3. Give the project the name HelloCouchbase

  4. Click OK to create the new project

  5. Right click the HelloCouchbase project in the solution explorer and choose Add | New Folder, and name the new folder Libraries

  6. Drag and drop all of the.dll,.pdb, and.xml files from the.NET Client Library zip-file you downloaded into the Libraries folder

  7. Right click on References and choose Add Reference

  8. Click on the Browse tab and then find the Libraries folder and choose the Enyim.Caching.dll and the Couchbase.dll

  9. Since the project is not a web application, we need to reconfigure it so that a few of the System.Web assemblies are referenced. To do this, we also need to switch to the full.NET 4.0 profile instead of the client profile. Start by right clicking the HelloCouchbase project and choosing Properties and in the ‘Target Framework’ drop-down list, choose ‘.NET Framework 4’.

  10. Next, add another reference from the.NET tab of the Add Reference dialog, choose “System.Web (Version 4.0.0.0)”.

After you have done these steps, your solution should look like that shown in Figure 2.

Next you will need to configure the client library to talk with Couchbase. This is most easily done by editing the App.config file to add a configuration section. You can also do your configuration in code, but the benefits of adding this to the.config file is that you can change it later without having to recompile. Also, when you start writing web applications using ASP.NET you can add the same configuration to the Web.config file.

Listing 1: App.config file

<?xml version="1.0"?>
<configuration>

  <configSections>
    <section name="couchbase" type="Couchbase.Configuration.CouchbaseClientSection, Couchbase"/>
  </configSections>

  <couchbase>
    <servers bucket="private" bucketPassword="private">
      <add uri="http://10.0.0.33:8091/pools/default"/>
    </servers>
  </couchbase>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
</configuration>

You would change the uri to point at your server by replacing 10.0.0.33 with the IP address or hostname of your Couchbase server machine. Be sure you set your bucket name and password. You can also set the connection to use the default bucket, by setting the bucket attribute to “default” and leaving the bucketPassword attribute empty. In this case we have configured the server with a bucket named “private” and with a password called “private”. Feel free to change these to whatever you have configured on your server.

Now you are ready to begin your first C# application to talk with your Couchbase server. Enter the code in Listing 2 into Program.cs:

Listing 2: Simple C# Application

using System;
using Enyim.Caching.Memcached;
using Couchbase;

namespace HelloCouchbase
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var client = new CouchbaseClient())
            {
                String spoon = null;

                if ((spoon = client.Get<string>("Spoon")) == null)
                {
                    Console.WriteLine("There is no spoon!");
                    client.Store(StoreMode.Set,
                                 "Spoon",
                                 "Hello, Couchbase!",
                                 TimeSpan.FromMinutes(1));
                }
                else
                {
                    Console.WriteLine(spoon);
                }
            }
        }
    }
}

If you run this program without debugging, by hitting Ctrl-F5, you will initially see the following output:

There is no spoon!
Press any key to continue

If you then press Ctrl-F5 again, you will see some different output:

Hello, Couchbase!
Press any key to continue

The code creates an instance of a CouchbaseClient in a using block so that it will be properly disposed of before the program exits. Creation of the CouchbaseClient instance is an expensive operation, and you would not want to create an instance every time you need one. Usually this would be done once in an application, and stored for when it is needed.

Next the code makes a call to the generic client.Get>T> method. If you know that you’ve stored a string in a particular database key this method allows you to return the string without having to perform a typecast. If you get the type wrong, a ClassCastException will be thrown, so be careful. Any type marked with the [Serializable] attribute can be stored into Couchbase.

Press Ctrl-F5 again. You’ll notice that there is no spoon. Where did it go? If you notice, the client.Store() method was given a TimeSpan parameter indicating the expiry time of the key in the database. After that amount of time the key will cease to exist and its value will be forgotten. This is convenient to store information that has a short lifetime, such as a user session, or other data that is expensive to calculate, but is only valid for a short period of time like the daily bus schedule for a given bus stop, or the number of people that have visited a particular web page since midnight.

The Couchbase client library also has a very useful way of keeping keys from expiring without having to write new data into them, called the Touch() method. In order to use this, you must have a very recent Couchbase server (currently version 1.7 or higher) that supports the Touch operation. If your server is new enough, try adding the following line in bold to the else block:

else
                {
                    Console.WriteLine(spoon);
                    client.Touch("Spoon", TimeSpan.FromMinutes(1));
                }

Now you will be able to press Ctrl-F5 every 30 seconds for the rest of your life if you wanted to. The expiry time of the Spoon value will be extended every time the application is run, keeping it nice and fresh. If you stop for more than one minute Spoon will expire again.

Couchbase API overview

The Couchbase client library has many API methods that you can use to implement whatever you desire. The following tables outline some API categories, the methods that are available, and a short description of what those methods do.

Memcached methods

These methods allow all of the operations defined for the memcached protocol, which is implemented in the Enyim client library inside the Enyim.Caching.MemcachedClient class. A few of these methods have generic versions that allow automatic type casting of serializable objects to be retrieved. Many of these methods can also return a Boolean value indicating whether the operation succeeded or failed.

Append Append some bytes to the end of a key.
Decrement Decrement a key and return the value.
FlushAll Flush all data on all servers for the connected bucket.
Get Get the value for a key.
Increment Increment the value of a key.
Prepend Prepend some bytes to the start of a key.
Remove Removes a key from the database.
Stats Return statistics about a key, or about the servers in the cluster.
Store Stores a value for a key.
TryGet Tries to get a value, and returns a Boolean if the value was successfully retrieved.

Check And Set

The MemcachedClient has a number of methods that allow a Check and Set operation to be performed on keys in the database. Check and Set operations (CAS) are a way to prevent data loss in a distributed database without heavy locks or transactions. Before you write data into the database you can obtain the current cas value, which is effectively like a version number for the data in the database. When you write your new data into the database you pass along the version you think the data is supposed to have. If, by the time the write happens, the value is no longer valid your code will be told that your write failed. You will then be able to take corrective action such as reading the new value, its cas, and retrying your operation.

Cas Perform a Check And Set operation.
Decrement Some of the Decrement overloads support returning a CasResult.
GetWithCas Perform a Get and also return a CasResult.
Increment Some Increment overloads support passing back a CAS to check for whether the operation succeeded.
TryGetWithCas Returns a Boolean so your code knows if the value exists or not, and returns a CasResult if it succeeds.

Specialized Couchbase Methods

The Couchbase library includes the CouchbaseClient class, which is a subclass of the MemcachedClient class. It has a set of methods that provide very powerful ways to interact with data and extent the expiry time concurrently. You will be able to use all of these methods (get, touch and CAS equivalents) on both both Couchbase and Memcached buckets in Couchbase 1.7, except for the Sync operation. Sync is only supported on Couchbase buckets.

Get A special form of Get, sometimes referred to as Get and Touch, which a returns the value but allows the expiry time to be reset.
GetWithCas Get a value, its CAS, and also reset the expiry, all at once.
Sync A very new operation that allows you to wait for data in the database to change in specific ways. Allows you to know when data has been persisted, replicated, or mutated. Remember this operation can only be performed on Couchbase buckets.
Touch Reset a keys expiry date without getting its value.
TryGet Try to get a value, a Boolean indicates success, reset the expiry, all at once.
TryGetWithCas Swiss army knife. Gets a Boolean indicating if the operation succeeded, gets a CasResult and also resets the expiry time of value.

Conclusion

We hope you have enjoyed this very brief introduction to using the Enyim client library to connect your C# programs to your Couchbase database. We would encourage you to spend some time working though the Tutorial application as well.

.NET Method Summary

.Net Connection Operations

API Call object.new CouchbaseClient([ url ] [, username ] [, password ])
Asynchronous no
Description Create a connection to Couchbase Server with given parameters, such as node URL. The connection obtains the cluster configuration from the first host to which it has connected. Further communication operates directly with each node in the cluster as required.
Returns (none)
Arguments
string url URL for Couchbase Server Instance, or node.
string username Username for Couchbase bucket.
string password Password for Couchbase bucket.

The easiest way to specify a connection, or a pool of connections is to provide it in the App.config file of your.Net project. By doing so, you can change the connection information without having to recompile. You can update App.config in Visual Studio as follows:

<servers bucket="private" bucketPassword="private">
      <add uri="http://10.0.0.33:8091/pools/default"/>
      <add uri="http://10.0.0.34:8091/pools/default"/>
</servers>

You should change the URI above to point at your server by replacing 10.0.0.33 with the IP address or hostname of your Couchbase server machine. Be sure you set your bucket name and password. You can also set the connection to use the default bucket, by setting the bucket attribute to default and leaving the bucketPassword attribute empty. In this case we have configured the server with a bucket named ‘private’ and with a password ‘private.’

Connections that you create with the.Net SDK are also thread-safe objects; for persisted connections, you can use a connection pool which contains multiple connection objects. You should create only a single static instance of a Couchbase client per bucket, in accordance with.Net framework. The persistent client will maintain connection pools per server node. For more information, see MSDN: AppDomain Class.

Store Operations

The Couchbase .NET Client Library store operations set information within the Couchbase database. These are distinct from the update operations in that the key does not have to exist within the Couchbase database before being stored.

Store Methods

The Store() methods adds a value to the database with the specified key, but will fail if the key already exists in the database and the StoreMode is set to Add.

API Call object.Store(StoreMode storemode, string key, object value)
Asynchronous no
Description Store a value using the specified key, whether the key already exists or not. Will overwrite a value if the given key/value already exists.
Returns Boolean ( Boolean (true/false) )
Arguments
StoreMode storemode Storage mode for a given key/value pair
string key Document ID used to identify the value
object value Value to be stored

The Store() method is used to persist new values by key. Any class decorated with the Serializable attribute may be stored.

StoreMode.Set will behave like StoreMode.Add when the key doesn’t exist and StoreMode.Replace when it does.

client.Store(StoreMode.Add, "beer", new Beer() {
    Brewer = "Thomas Hooker Brewing Company",
    Name = "American Ale"
});

API Call object.Store(storemode, key, value, validfor)
Asynchronous no
Description Store a value using the specified key, whether the key already exists or not. Will overwrite a value if the given key/value already exists.
Returns Boolean ( Boolean (true/false) )
Arguments
StoreMode storemode Storage mode for a given key/value pair
string key Document ID used to identify the value
object value Value to be stored
TimeSpan validfor Expiry time (in seconds) for key
client.Store(StoreMode.Set, "beer", new Beer() {
    Brewer = "Peak Organic Brewing Company",
    Name = "IPA"
}, TimeSpan.FromSeconds(60));

API Call object.Store(storemode, key, value, expiresat)
Asynchronous no
Description Store a value using the specified key, whether the key already exists or not. Will overwrite a value if the given key/value already exists.
Returns Boolean ( Boolean (true/false) )
Arguments
StoreMode storemode Storage mode for a given key/value pair
string key Document ID used to identify the value
object value Value to be stored
DateTime expiresat Explicit expiry time for key
client.Store(StoreMode.Replace, "beer", new Beer() {
    Brewer = "Six Point Craft Ales",
    Name = "Righteous Rye"
}, DateTime.Now.Addhours(1));

API Call object.Store(StoreMode storemode, string key, object value)
Asynchronous no
Description Store a value using the specified key, whether the key already exists or not. Will overwrite a value if the given key/value already exists.
Returns Boolean ( Boolean (true/false) )
Arguments
StoreMode storemode Storage mode for a given key/value pair
string key Document ID used to identify the value
object value Value to be stored

The ExecuteStore() method is used like the Store methods, but instead of a Boolean, returns a IStoreOperationResult, which provides detailed information about the success of the operation.

var result = client.ExecuteStore(StoreMode.Add, "beer", new Beer() {
    Brewer = "The Alchemist",
    Name = "Heady Topper"
});

if (! result.Success) {
    logger.Error(result.Message, result.Exception);
}

API Call object.ExecuteStore(storemode, key, value, validfor)
Asynchronous no
Description Store a value using the specified key, whether the key already exists or not. Will overwrite a value if the given key/value already exists.
Returns IStoreOperationResult ( Store operation result )
Arguments
StoreMode storemode Storage mode for a given key/value pair
string key Document ID used to identify the value
object value Value to be stored
TimeSpan validfor Expiry time (in seconds) for key
var client.ExecuteStore(StoreMode.Set, "beer", new Beer() {
    Brewer = "Cambridge Brewing Company",
    Name = "The Audacity of Hops"
}, TimeSpan.FromSeconds(60));

API Call object.ExecuteStore(storemode, key, value, expiresat)
Asynchronous no
Description Store a value using the specified key, whether the key already exists or not. Will overwrite a value if the given key/value already exists.
Returns IStoreOperationResult ( Store operation result )
Arguments
StoreMode storemode Storage mode for a given key/value pair
string key Document ID used to identify the value
object value Value to be stored
DateTime expiresat Explicit expiry time for key
var result = client.ExecuteStore(StoreMode.Replace, "beer", new Beer() {
    Brewer = "Long Trail Brewing Company",
    Name = "Long Trail Ale"
}, DateTime.Now.Addhours(1));

Retrieve Operations

The retrieve operations get information from the Couchbase database. A summary of the available API calls is listed below.

Get Methods

The Get() methods allow for direct access to a given key/value pair.

API Call object.Get(key)
Asynchronous no
Description Get one or more key values
Returns Object ( Binary object )
Arguments
string key Document ID used to identify the value
var beer = client.Get("beer") as Beer;

The generic form of the Get method allows for retrieval without the need to cast. If the stored type cannot be serialized to the generic type provided, an InvalidCastException will be thrown.

var beer = client.Get<Beer>("beer");

API Call object.ExecuteGet(key)
Asynchronous no
Description Get one or more key values
Returns IGetOperationResult ( Get operation result )
Arguments
string key Document ID used to identify the value

ExecuteGet() behaves as does Get() but returns an instance of an IGetOperationResult instead of directly returning the item for the key.

Beer beer = null;
var getResult = client.ExecuteGet("beer") as Beer;
if (getResult.Success && getResult.HasValue) {
    beer = getResult.Value as Beer;
} else {
    logger.Error(getResult.Message, getResult.Exception);
}

ExecuteGet() also has a generic form to allow an item to be retrieved without casting.

var beer = client.ExecuteGet<Beer>("beer").Value;

API Call object.GetWithCas(key)
Asynchronous no
Description Get one or more key values
Returns CasResult<ulong> ( Cas result of bool )
Arguments
string key Document ID used to identify the value

GetWithCas() will return a CasResult with the Cas value for a given key.

var casResult = client.GetWithCas("beer");
var beer = casResult.Result;
beer = "Heady Topper";
var storeResult = client.Cas(StoreMode.Replace, "beer", beer, casResult.Cas);

API Call object.Get(keyarray)
Asynchronous no
Description Get one or more key values
Returns Object ( Binary object )
Arguments
List keyarray Array of keys used to reference one or more values.

Calling Get() with multiple keys returns a dictionary with the associated values.

client.Store(StoreMode.Set, "brewer", "Cottrell Brewing Co.");
client.Store(StoreMode.Set, "beer", "Old Yankee Ale");

var dict = client.Get(new string[] { "brewer", "beer" });
Console.WriteLine(dict["brewer"]);
Console.WriteLine(dict["beer"]);

API Call object.ExecuteGet(keyarray)
Asynchronous no
Description Get one or more key values
Returns IGetOperationResult ( Get operation result )
Arguments
List keyarray Array of keys used to reference one or more values.

Calling ExecuteGet() with multiple keys returns a dictionary where the values are instances of an IGetOperationResult.

client.Store(StoreMode.Set, "brewer", "Cottrell Brewing Co.");
client.Store(StoreMode.Set, "beer", "Old Yankee Ale");

var dict = client.ExecuteGet(new string[] { "brewer", "beer" });
Console.WriteLine(dict["brewer"].Value);
Console.WriteLine(dict["beer"].Value);

API Call object.Get(key, expiry)
Asynchronous no
Description Get a value and update the expiration time for a given key
Returns (none)
Arguments
string key Document ID used to identify the value
object expiry Expiry time for key. Values larger than 30*24*60*60 seconds (30 days) are interpreted as absolute times (from the epoch).

Calling the Get() method with a key and a new expiration value will cause get and touch operations to be performed.

var val = client.Get("beer", DateTime.Now.AddMinutes(5));

API Call object.ExecuteGet(key, expiry)
Asynchronous no
Description Get a value and update the expiration time for a given key
Returns IGetOperationResult ( Get operation result )
Arguments
string key Document ID used to identify the value
object expiry Expiry time for key. Values larger than 30*24*60*60 seconds (30 days) are interpreted as absolute times (from the epoch).

ExecuteGet() when called with an expiration will update the time to live for an item and return an instane of an IGetOperationResult

var val = client.Get("beer", DateTime.Now.AddMinutes(5));

Update Operations

The update methods support different methods of updating and changing existing information within Couchbase. A list of the available methods is listed below.

Append Methods

The Append() methods allow you to add information to an existing key/value pair in the database. You can use this to add information to a string or other data after the existing data.

The Append() methods append raw serialized data on to the end of the existing data in the key. If you have previously stored a serialized object into Couchbase and then use Append, the content of the serialized object will not be extended. For example, adding an List of integers into the database, and then using Append() to add another integer will result in the key referring to a serialized version of the list, immediately followed by a serialized version of the integer. It will not contain an updated list with the new integer appended to it. De-serialization of objects that have had data appended may result in data corruption.

API Call object.Append(key, value)
Asynchronous no
Description Append a value to an existing key
Returns Object ( Binary object )
Arguments
string key Document ID used to identify the value
object value Value to be stored

The Append() method appends information to the end of an existing key/value pair.

The sample below demonstrates how to create a csv string by appending new values.

client.Store(StoreMode.Set, "beers", "Abbey Ale");
Func<string, byte[]> stringToBytes = (s) => Encoding.Default.GetBytes(s);
client.Append("beers", new ArraySegment<byte>(stringToBytes(",Three Philosophers")));
client.Append("beers", new ArraySegment<byte>(stringToBytes(",Witte")));

You can check if the Append operation succeeded by using the checking the return value.

var result = client.Append("beers", new ArraySegment<byte>(stringToBytes(",Hennepin")));
if (result) {
    Console.WriteLine("Append succeeded");
} else {
    Console.WriteLine("Append failed");
}

API Call object.Append(key, casunique, value)
Asynchronous no
Description Append a value to an existing key
Returns Object ( Binary object )
Arguments
string key Document ID used to identify the value
ulong casunique Unique value used to verify a key/value combination
object value Value to be stored

Append() may also be used with a CAS value. With this overload, the return value is a CasResult, where success is determined by examining the CasResult’s Result property.

var casv = client.GetWithCas("beers");
var casResult = client.Append("beers", casv.Cas, new ArraySegment<byte>(stringToBytes(",Adoration")));

if (casResult.Result) {
    Console.WriteLine("Append succeeded");
} else {
    Console.WriteLine("Append failed");
}

API Call object.ExecuteAppend(key, value)
Asynchronous no
Description Append a value to an existing key
Returns IConcatOperationResult ( Concat operation result )
Arguments
string key Document ID used to identify the value
object value Value to be stored

The ExecuteAppend() method behaves similar to Append() but returns detailed results via an instance of an IConcatOperationResult instead of a Boolean

The sample below demonstrates how to create a csv string by appending new values.

var result = client.Store(StoreMode.Set, "beers", "Abbey Ale");
Func<string, byte[]> stringToBytes = (s) => Encoding.Default.GetBytes(s);
client.Append("beers", new ArraySegment<byte>(stringToBytes(",Three Philosophers")));
client.Append("beers", new ArraySegment<byte>(stringToBytes(",Witte")));

if (! result.Success) {
    logger.Error("Operation failed. Status code: " + result.StatusCode);
}

API Call object.ExecuteAppend(key, casunique, value)
Asynchronous no
Description Append a value to an existing key
Returns IConcatOperationResult ( Concat operation result )
Arguments
string key Document ID used to identify the value
ulong casunique Unique value used to verify a key/value combination
object value Value to be stored

As with Append() ExecuteAppend() may also be used with a CAS value. With this overload, the return value is a IConcatOperationResult.

var getResult = client.ExecuteGet("beers");
var concatResult = client.ExecuteAppend("beers", getResult.Cas, new ArraySegment<byte>(stringToBytes(",Adoration")));

if (concatResult.Success) {
    Console.WriteLine("Append succeeded");
} else {
    Console.WriteLine("Append failed");
}

Cas Methods

The check-and-set methods provide a mechanism for updating information only if the client knows the check (CAS) value. This can be used to prevent clients from updating values in the database that may have changed since the client obtained the value. Methods for storing and updating information support a CAS method that allows you to ensure that the client is updating the version of the data that the client retrieved.

The check value is in the form of a 64-bit integer which is updated every time the value is modified, even if the update of the value does not modify the binary data. Attempting to set or update a key/value pair where the CAS value does not match the value stored on the server will fail.

API Call object.Cas(storemode, key, value)
Asynchronous no
Description Compare and set a value providing the supplied CAS key matches
Returns CasResult<bool> ( Cas result of bool )
Arguments
StoreMode storemode Storage mode for a given key/value pair
string key Document ID used to identify the value
object value Value to be stored

Store a value and get a CasResult with the Cas for that key.

var casResult = client.Cas(StoreMode.Set, "somekey", "somevalue");
logger.Debug("Cas value: " + casResult.Cas);

API Call object.Cas(storemode, key, value, casunique)
Asynchronous no
Description Compare and set a value providing the supplied CAS key matches
Returns CasResult<bool> ( Cas result of bool )
Arguments
StoreMode storemode Storage mode for a given key/value pair
string key Document ID used to identify the value
object value Value to be stored
ulong casunique Unique value used to verify a key/value combination

Cas() may also be used with a CAS value. With this overload, the return value is a CasResult, where success is determined by examining the CasResult’s Result property.

var casv = client.GetWithCas("somekey");
var casResult = client.Cas(StoreMode.Set, "somekey", "somevalue", casv.Cas);
if (casResult.Result) {
    logger.Debug("Cas result was successful");
}

API Call object.Cas(storemode, key, value, validfor, casunique)
Asynchronous no
Description Compare and set a value providing the supplied CAS key matches
Returns CasResult<bool> ( Cas result of bool )
Arguments
StoreMode storemode Storage mode for a given key/value pair
string key Document ID used to identify the value
object value Value to be stored
TimeSpan validfor Expiry time (in seconds) for key
ulong casunique Unique value used to verify a key/value combination

Perform a check and set operation, setting a TimeStamp expiration on the key.

var casv = client.GetWithCas("somekey");
var casResult = client.Cas(StoreMode.Set, "somekey", "somevalue", TimeSpan.FromMinutes(30), casv.Cas);
if (casResult.Result) {
    logger.Debug("Cas result was successful");
}

API Call object.Cas(storemode, key, value, expiresat, casunique)
Asynchronous no
Description Compare and set a value providing the supplied CAS key matches
Returns CasResult<bool> ( Cas result of bool )
Arguments
StoreMode storemode Storage mode for a given key/value pair
string key Document ID used to identify the value
object value Value to be stored
DateTime expiresat Explicit expiry time for key
ulong casunique Unique value used to verify a key/value combination

Perform a check and set operation, setting a DateTime expiration on the key.

var casv = client.GetWithCas("somekey");
var casResult = client.Cas(StoreMode.Set, "somekey", "somevalue", DateTime.Now.AddMinutes(30), casv.Cas);
if (casResult.Result) {
    logger.Debug("Cas result was successful");
}

API Call object.ExecuteCas(storemode, key, value)
Asynchronous no
Description Compare and set a value providing the supplied CAS key matches
Returns IStoreOperationResult ( Store operation result )
Arguments
StoreMode storemode Storage mode for a given key/value pair
string key Document ID used to identify the value
object value Value to be stored

Store a value and get an IStoreOperationResult return value.

var storeResult = client.ExecuteCas(StoreMode.Set, "somekey", "somevalue");
logger.Debug("Cas value: " + storeResult.Cas);

API Call object.ExecuteCas(storemode, key, value, casunique)
Asynchronous no
Description Compare and set a value providing the supplied CAS key matches
Returns IStoreOperationResult ( Store operation result )
Arguments
StoreMode storemode Storage mode for a given key/value pair
string key Document ID used to identify the value
object value Value to be stored
ulong casunique Unique value used to verify a key/value combination

ExecuteCas() works like Cas() and may also be used with a CAS value. With this overload, the return value is an instance of an IStoreOperationResult.

var getResult = client.ExecutGet("somekey");
var storeResult = client.Cas(StoreMode.Set, "somekey", "somevalue", getResult.Cas);
if (storeResult.Result) {
    logger.Debug("Cas operation was successful");
}

API Call object.ExecuteCas(storemode, key, value, validfor, casunique)
Asynchronous no
Description Compare and set a value providing the supplied CAS key matches
Returns IStoreOperationResult ( Store operation result )
Arguments
StoreMode storemode Storage mode for a given key/value pair
string key Document ID used to identify the value
object value Value to be stored
TimeSpan validfor Expiry time (in seconds) for key
ulong casunique Unique value used to verify a key/value combination

Perform a check and set operation, setting a TimeStamp expiration on the key. Return an instance of an IStoreOperationResult.

var getResult = client.ExecutGet("somekey");
var storeResult = client.Cas(StoreMode.Set, "somekey", "somevalue", TimeSpan.FromMinutes(30), getResult.Cas);
if (storeResult.Result) {
    logger.Debug("Cas operation was successful");
}

API Call object.ExecuteCas(storemode, key, value, expiresat, casunique)
Asynchronous no
Description Compare and set a value providing the supplied CAS key matches
Returns IStoreOperationResult ( Store operation result )
Arguments
StoreMode storemode Storage mode for a given key/value pair
string key Document ID used to identify the value
object value Value to be stored
DateTime expiresat Explicit expiry time for key
ulong casunique Unique value used to verify a key/value combination

Perform a check and set operation, setting a DateTime expiration on the key. Return an instance of an IStoreOperationResult.

var getResult = client.ExecutGet("somekey");
var storeResult = client.Cas(StoreMode.Set, "somekey", "somevalue", DateTime.Now.AddMinutes(30), getResult.Cas);
if (storeResult.Result) {
    logger.Debug("Cas operation was successful");
}

Decrement Methods

The Decrement() methods reduce the value of a given key if the corresponding value can be parsed to an integer value. These operations are provided at a protocol level to eliminate the need to get, update, and reset a simple integer value in the database. All the.NET Client Library methods support the use of an explicit offset value that will be used to reduce the stored value in the database.

API Call object.Decrement(key, defaultvalue, offset)
Asynchronous no
Description Decrement the value of an existing numeric key. The Couchbase Server stores numbers as unsigned values. Therefore the lowest you can decrement is to zero.
Returns CasResult<ulong> ( Cas result of bool )
Arguments
string key Document ID used to identify the value
object defaultvalue Value to be stored if key does not already exist
Integer offset Integer offset value to increment/decrement (default 1)

Decrement the inventory counter by 1, defaulting to 100 if the key doesn’t exist.

client.Decrement("inventory", 100, 1);

API Call object.Decrement(key, defaultvalue, offset, validfor)
Asynchronous no
Description Decrement the value of an existing numeric key. The Couchbase Server stores numbers as unsigned values. Therefore the lowest you can decrement is to zero.
Returns CasResult<ulong> ( Cas result of bool )
Arguments
string key Document ID used to identify the value
object defaultvalue Value to be stored if key does not already exist
Integer offset Integer offset value to increment/decrement (default 1)
TimeSpan validfor Expiry time (in seconds) for key

Decrement the inventory counter by 1, defaulting to 100 if the key doesn’t exist and set an expiry of 60 seconds.

client.Decrement("inventory", 100, 1, TimeSpan.FromSeconds(60));

API Call object.Decrement(key, defaultvalue, offset, expiresat)
Asynchronous no
Description Decrement the value of an existing numeric key. The Couchbase Server stores numbers as unsigned values. Therefore the lowest you can decrement is to zero.
Returns CasResult<ulong> ( Cas result of bool )
Arguments
string key Document ID used to identify the value
object defaultvalue Value to be stored if key does not already exist
Integer offset Integer offset value to increment/decrement (default 1)
DateTime expiresat Explicit expiry time for key

Decrement the inventory counter by 1, defaulting to 100 if the key doesn’t exist and set an expiry of 5 minutes.

client.Decrement("inventory", 100, 1, DateTime.Now.AddMinutes(5));

API Call object.Decrement(key, defaultvalue, offset, casunique)
Asynchronous no
Description Decrement the value of an existing numeric key. The Couchbase Server stores numbers as unsigned values. Therefore the lowest you can decrement is to zero.
Returns CasResult<ulong> ( Cas result of bool )
Arguments
string key Document ID used to identify the value
object defaultvalue Value to be stored if key does not already exist
Integer offset Integer offset value to increment/decrement (default 1)
ulong casunique Unique value used to verify a key/value combination

Decrement the inventory counter by 1, defaulting to 100 if the key doesn’t exist.

var casv = client.GetWithCas("inventory");
client.Decrement("inventory", 100, 1, cas.Cas);

API Call object.Decrement(key, defaultvalue, offset, validfor, casunique)
Asynchronous no
Description Decrement the value of an existing numeric key. The Couchbase Server stores numbers as unsigned values. Therefore the lowest you can decrement is to zero.
Returns CasResult<ulong> ( Cas result of bool )
Arguments
string key Document ID used to identify the value
object defaultvalue Value to be stored if key does not already exist
Integer offset Integer offset value to increment/decrement (default 1)
TimeSpan validfor Expiry time (in seconds) for key
ulong casunique Unique value used to verify a key/value combination

Decrement the inventory counter by 1, defaulting to 100 if the key doesn’t exist and set an expiry of 60 seconds.

var casv = client.GetWithCas("inventory");
client.Decrement("inventory", 100, 1, TimeSpan.FromSeconds(60), cas.Cas);

API Call object.Decrement(key, defaultvalue, offset, expiresat, casunique)
Asynchronous no
Description Decrement the value of an existing numeric key. The Couchbase Server stores numbers as unsigned values. Therefore the lowest you can decrement is to zero.
Returns CasResult<ulong> ( Cas result of bool )
Arguments
string key Document ID used to identify the value
object defaultvalue Value to be stored if key does not already exist
Integer offset Integer offset value to increment/decrement (default 1)
DateTime expiresat Explicit expiry time for key
ulong casunique Unique value used to verify a key/value combination

Decrement the inventory counter by 1, defaulting to 100 if the key doesn’t exist and set an expiry of 5 minutes.

var casv = client.GetWithCas("inventory");
client.Decrement("inventory", 100, 1, DateTime.Now.AddMinutes(5), cas.Cas);

API Call object.ExecuteDecrement(key, defaultvalue, offset)
Asynchronous no
Description Decrement the value of an existing numeric key. The Couchbase Server stores numbers as unsigned values. Therefore the lowest you can decrement is to zero.
Returns IMutateOperationResult ( Mutate operation result )
Arguments
string key Document ID used to identify the value
object defaultvalue Value to be stored if key does not already exist
Integer offset Integer offset value to increment/decrement (default 1)

Decrement the inventory counter by 1, defaulting to 100 if the key doesn’t exist. Returns an IMutateOperationResult.

var result = client.ExecuteDecrement("inventory", 100, 1);

if (result.Success) {
    logger.Debug("New value: " + result.Value);
}

API Call object.ExecuteDecrement(key, defaultvalue, offset, validfor)
Asynchronous no
Description Decrement the value of an existing numeric key. The Couchbase Server stores numbers as unsigned values. Therefore the lowest you can decrement is to zero.
Returns IMutateOperationResult ( Mutate operation result )
Arguments
string key Document ID used to identify the value
object defaultvalue Value to be stored if key does not already exist
Integer offset Integer offset value to increment/decrement (default 1)
TimeSpan validfor Expiry time (in seconds) for key

Decrement the inventory counter by 1, defaulting to 100 if the key doesn’t exist and set an expiry of 60 seconds. Return an instance of an IMutateOperationResult.

var result = client.ExecuteDecrement("inventory", 100, 1, TimeSpan.FromSeconds(60));

API Call object.Decrement(key, defaultvalue, offset, expiresat)
Asynchronous no
Description Decrement the value of an existing numeric key. The Couchbase Server stores numbers as unsigned values. Therefore the lowest you can decrement is to zero.
Returns CasResult<ulong> ( Cas result of bool )
Arguments
string key Document ID used to identify the value
object defaultvalue Value to be stored if key does not already exist
Integer offset Integer offset value to increment/decrement (default 1)
DateTime expiresat Explicit expiry time for key

Decrement the inventory counter by 1, defaulting to 100 if the key doesn’t exist and set an expiry of 5 minutes. Return an instance of an IMutateOperationResult.

var result = client.Decrement("inventory", 100, 1, DateTime.Now.AddMinutes(5));

API Call object.ExecuteDecrement(key, defaultvalue, offset, casunique)
Asynchronous no
Description Decrement the value of an existing numeric key. The Couchbase Server stores numbers as unsigned values. Therefore the lowest you can decrement is to zero.
Returns IMutateOperationResult ( Mutate operation result )
Arguments
string key Document ID used to identify the value
object defaultvalue Value to be stored if key does not already exist
Integer offset Integer offset value to increment/decrement (default 1)
ulong casunique Unique value used to verify a key/value combination

Decrement the inventory counter by 1 using check and set, defaulting to 100 if the key doesn’t exist. Return an instance of an IMutateOperationResult.

var getResult = client.ExecuteGet("inventory");
var mutateResult = client.ExecuteDecrement("inventory", 100, 1, getResult.Cas);

API Call object.ExecuteDecrement(key, defaultvalue, offset, validfor, casunique)
Asynchronous no
Description Decrement the value of an existing numeric key. The Couchbase Server stores numbers as unsigned values. Therefore the lowest you can decrement is to zero.
Returns IMutateOperationResult ( Mutate operation result )
Arguments
string key Document ID used to identify the value
object defaultvalue Value to be stored if key does not already exist
Integer offset Integer offset value to increment/decrement (default 1)
TimeSpan validfor Expiry time (in seconds) for key
ulong casunique Unique value used to verify a key/value combination

Decrement the inventory counter by 1 using check and set, defaulting to 100 if the key doesn’t exist and set an expiry of 60 seconds. Return an instance of an IMutateOperationResult

var getResult = client.ExecuteGet("inventory");
var mutateResult = client.ExecuteDecrement("inventory", 100, 1, TimeSpan.FromSeconds(60), getResult.Cas);

API Call object.ExecuteDecrement(key, defaultvalue, offset, expiresat, casunique)
Asynchronous no
Description Decrement the value of an existing numeric key. The Couchbase Server stores numbers as unsigned values. Therefore the lowest you can decrement is to zero.
Returns IMutateOperationResult ( Mutate operation result )
Arguments
string key Document ID used to identify the value
object defaultvalue Value to be stored if key does not already exist
Integer offset Integer offset value to increment/decrement (default 1)
DateTime expiresat Explicit expiry time for key
ulong casunique Unique value used to verify a key/value combination

Decrement the inventory counter by 1 using check and set, defaulting to 100 if the key doesn’t exist and set an expiry of 5 minutes. Return an instance of an IMutateOperationResult.

var getResult = client.ExecuteGet("inventory");
client.ExecuteDecrement("inventory", 100, 1, DateTime.Now.AddMinutes(5), getResult.Cas);

Remove Methods

API Call object.Remove(key)
Asynchronous no
Description Delete a key/value
Returns Object ; supported values:
COUCHBASE_ETMPFAIL
COUCHBASE_KEY_ENOENT
COUCHBASE_NOT_MY_VBUCKET
COUCHBASE_NOT_STORED
docid
Arguments
string key Document ID used to identify the value

The Remove() method deletes an item in the database with the specified key.

Remove the item with a specified key

client.Remove("Budweiser");

API Call object.ExecuteRemove(key)
Asynchronous no
Description Delete a key/value
Returns IRemoveOperationResult ( Remove operation result )
Arguments
string key Document ID used to identify the value

The ExecuteRemove() method deletes an item in the database with the specified key and returns an instance of an IRemoveOperationResult.

var result = client.ExecuteRemove("Coors");

if (!result.Success) {
    if (result.InnerResult != null) {
        logger.Error(result.Message, result.InnerResult.Exception);
    }
}

Increment Methods

The Increment() methods increase the value of a given key if the corresponding value can be parsed to an integer value. These operations are provided at a protocol level to eliminate the need to get, update, and reset a simple integer value in the database. All the.NET Client Library methods support the use of an explicit offset value that will be used to reduce the stored value in the database.

API Call object.Increment(key, defaultvalue, offset)
Asynchronous no
Description Increment the value of an existing numeric key. Couchbase Server stores numbers as unsigned numbers, therefore if you try to increment an existing negative number, it will cause an integer overflow and return a non-logical numeric result. If a key does not exist, this method will initialize it with the zero or a specified value.
Returns CasResult<ulong> ( Cas result of bool )
Arguments
string key Document ID used to identify the value
object defaultvalue Value to be stored if key does not already exist
Integer offset Integer offset value to increment/decrement (default 1)

Increment the inventory counter by 1, defaulting to 100 if the key doesn’t exist.

client.Increment("inventory", 100, 1);

API Call object.Increment(key, defaultvalue, offset, validfor)
Asynchronous no
Description Increment the value of an existing numeric key. Couchbase Server stores numbers as unsigned numbers, therefore if you try to increment an existing negative number, it will cause an integer overflow and return a non-logical numeric result. If a key does not exist, this method will initialize it with the zero or a specified value.
Returns CasResult<ulong> ( Cas result of bool )
Arguments
string key Document ID used to identify the value
object defaultvalue Value to be stored if key does not already exist
Integer offset Integer offset value to increment/decrement (default 1)
TimeSpan validfor Expiry time (in seconds) for key

Increment the inventory counter by 1, defaulting to 100 if the key doesn’t exist and set an expiry of 60 seconds.

client.Increment("inventory", 100, 1, TimeSpan.FromSeconds(60));

API Call object.Increment(key, defaultvalue, offset, expiresat)
Asynchronous no
Description Increment the value of an existing numeric key. Couchbase Server stores numbers as unsigned numbers, therefore if you try to increment an existing negative number, it will cause an integer overflow and return a non-logical numeric result. If a key does not exist, this method will initialize it with the zero or a specified value.
Returns CasResult<ulong> ( Cas result of bool )
Arguments
string key Document ID used to identify the value
object defaultvalue Value to be stored if key does not already exist
Integer offset Integer offset value to increment/decrement (default 1)
DateTime expiresat Explicit expiry time for key

Increment the inventory counter by 1, defaulting to 100 if the key doesn’t exist and set an expiry of 5 minutes.

client.Increment("inventory", 100, 1, DateTime.Now.AddMinutes(5));

API Call object.Increment(key, defaultvalue, offset, casunique)
Asynchronous no
Description Increment the value of an existing numeric key. Couchbase Server stores numbers as unsigned numbers, therefore if you try to increment an existing negative number, it will cause an integer overflow and return a non-logical numeric result. If a key does not exist, this method will initialize it with the zero or a specified value.
Returns CasResult<ulong> ( Cas result of bool )
Arguments
string key Document ID used to identify the value
object defaultvalue Value to be stored if key does not already exist
Integer offset Integer offset value to increment/decrement (default 1)
ulong casunique Unique value used to verify a key/value combination

Increment the inventory counter by 1, defaulting to 100 if the key doesn’t exist.

var casv = client.GetWithCas("inventory");
client.Increment("inventory", 100, 1, cas.Cas);

API Call object.Increment(key, defaultvalue, offset, validfor, casunique)
Asynchronous no
Description Increment the value of an existing numeric key. Couchbase Server stores numbers as unsigned numbers, therefore if you try to increment an existing negative number, it will cause an integer overflow and return a non-logical numeric result. If a key does not exist, this method will initialize it with the zero or a specified value.
Returns CasResult<ulong> ( Cas result of bool )
Arguments
string key Document ID used to identify the value
object defaultvalue Value to be stored if key does not already exist
Integer offset Integer offset value to increment/decrement (default 1)
TimeSpan validfor Expiry time (in seconds) for key
ulong casunique Unique value used to verify a key/value combination

Increment the inventory counter by 1, defaulting to 100 if the key doesn’t exist and set an expiry of 60 seconds.

var casv = client.GetWithCas("inventory");
client.Increment("inventory", 100, 1, TimeSpan.FromSeconds(60), cas.Cas);

API Call object.Increment(key, defaultvalue, offset, expiresat, casunique)
Asynchronous no
Description Increment the value of an existing numeric key. Couchbase Server stores numbers as unsigned numbers, therefore if you try to increment an existing negative number, it will cause an integer overflow and return a non-logical numeric result. If a key does not exist, this method will initialize it with the zero or a specified value.
Returns CasResult<ulong> ( Cas result of bool )
Arguments
string key Document ID used to identify the value
object defaultvalue Value to be stored if key does not already exist
Integer offset Integer offset value to increment/decrement (default 1)
DateTime expiresat Explicit expiry time for key
ulong casunique Unique value used to verify a key/value combination

Increment the inventory counter by 1, defaulting to 100 if the key doesn’t exist and set an expiry of 5 minutes.

var casv = client.GetWithCas("inventory");
client.Increment("inventory", 100, 1, DateTime.Now.AddMinutes(5), cas.Cas);

API Call object.ExecuteIncrement(key, defaultvalue, offset)
Asynchronous no
Description Increment the value of an existing numeric key. Couchbase Server stores numbers as unsigned numbers, therefore if you try to increment an existing negative number, it will cause an integer overflow and return a non-logical numeric result. If a key does not exist, this method will initialize it with the zero or a specified value.
Returns IMutateOperationResult ( Mutate operation result )
Arguments
string key Document ID used to identify the value
object defaultvalue Value to be stored if key does not already exist
Integer offset Integer offset value to increment/decrement (default 1)

Increment the inventory counter by 1, defaulting to 100 if the key doesn’t exist. Return an instance of an IMutateOperationResult.

var result = client.Increment("inventory", 100, 1);

if (result.Success) {
    logger.Debug("New value: " + result.Value);
}

API Call object.ExecuteIncrement(key, defaultvalue, offset, validfor)
Asynchronous no
Description Increment the value of an existing numeric key. Couchbase Server stores numbers as unsigned numbers, therefore if you try to increment an existing negative number, it will cause an integer overflow and return a non-logical numeric result. If a key does not exist, this method will initialize it with the zero or a specified value.
Returns IMutateOperationResult ( Mutate operation result )
Arguments
string key Document ID used to identify the value
object defaultvalue Value to be stored if key does not already exist
Integer offset Integer offset value to increment/decrement (default 1)
TimeSpan validfor Expiry time (in seconds) for key

Increment the inventory counter by 1, defaulting to 100 if the key doesn’t exist and set an expiry of 60 seconds. Return an instance of an IMutateOperationResult.

var result = client.Increment("inventory", 100, 1);

if (result.Success) {
    logger.Debug("New value: " + result.Value);
}

API Call object.ExecuteIncrement(key, defaultvalue, offset, expiresat)
Asynchronous no
Description Increment the value of an existing numeric key. Couchbase Server stores numbers as unsigned numbers, therefore if you try to increment an existing negative number, it will cause an integer overflow and return a non-logical numeric result. If a key does not exist, this method will initialize it with the zero or a specified value.
Returns IMutateOperationResult ( Mutate operation result )
Arguments
string key Document ID used to identify the value
object defaultvalue Value to be stored if key does not already exist
Integer offset Integer offset value to increment/decrement (default 1)
DateTime expiresat Explicit expiry time for key

Increment the inventory counter by 1, defaulting to 100 if the key doesn’t exist and set an expiry of 5 minutes. Return an instance of an IMutateOperationResult.

client.ExecuteIncrement("inventory", 100, 1, DateTime.Now.AddMinutes(5));

API Call object.ExecuteIncrement(key, defaultvalue, offset, casunique)
Asynchronous no
Description Increment the value of an existing numeric key. Couchbase Server stores numbers as unsigned numbers, therefore if you try to increment an existing negative number, it will cause an integer overflow and return a non-logical numeric result. If a key does not exist, this method will initialize it with the zero or a specified value.
Returns IMutateOperationResult ( Mutate operation result )
Arguments
string key Document ID used to identify the value
object defaultvalue Value to be stored if key does not already exist
Integer offset Integer offset value to increment/decrement (default 1)
ulong casunique Unique value used to verify a key/value combination

Increment the inventory counter by 1 using check and set, defaulting to 100 if the key doesn’t exist. Return an instance of an IMutateOperationResult.

var getResult = client.ExecuteGet("inventory");

if (getResult.Success) {
    var mutateResult  client.ExecuteIncrement("inventory", 100, 1, getResult.Cas);

    if (mutateResult.Success) {
        logger.Debug("New value: " + mutateResult.Value);
    }
}

API Call object.ExecuteIncrement(key, defaultvalue, offset, validfor, casunique)
Asynchronous no
Description Increment the value of an existing numeric key. Couchbase Server stores numbers as unsigned numbers, therefore if you try to increment an existing negative number, it will cause an integer overflow and return a non-logical numeric result. If a key does not exist, this method will initialize it with the zero or a specified value.
Returns IMutateOperationResult ( Mutate operation result )
Arguments
string key Document ID used to identify the value
object defaultvalue Value to be stored if key does not already exist
Integer offset Integer offset value to increment/decrement (default 1)
TimeSpan validfor Expiry time (in seconds) for key
ulong casunique Unique value used to verify a key/value combination

ExecuteIncrement the inventory counter by 1 using check and set, defaulting to 100 if the key doesn’t exist and set an expiry of 60 seconds. Return an instance of an IMutateOperationResult.

var getResult = client.ExecuteGet("inventory");
var mutateResult = client.ExecuteIncrement("inventory", 100, 1, TimeSpan.FromSeconds(60), getResult.Cas);

API Call object.ExecuteIncrement(key, defaultvalue, offset, expiresat, casunique)
Asynchronous no
Description Increment the value of an existing numeric key. Couchbase Server stores numbers as unsigned numbers, therefore if you try to increment an existing negative number, it will cause an integer overflow and return a non-logical numeric result. If a key does not exist, this method will initialize it with the zero or a specified value.
Returns IMutateOperationResult ( Mutate operation result )
Arguments
string key Document ID used to identify the value
object defaultvalue Value to be stored if key does not already exist
Integer offset Integer offset value to increment/decrement (default 1)
DateTime expiresat Explicit expiry time for key
ulong casunique Unique value used to verify a key/value combination

Increment the inventory counter by 1 using check and set, defaulting to 100 if the key doesn’t exist and set an expiry of 5 minutes. Return an instance of an IMutateOperationResult.

var getResult = client.ExecuteGet("inventory");
var mutateResult = client.ExecuteIncrement("inventory", 100, 1, DateTime.Now.AddMinutes(5), getResult.Cas);

Prepend Methods

The Prepend() methods allow you to add information to an existing key/value pair in the database. You can use this to add information to a string or other data before the existing data.

The Prepend() methods prepend raw serialized data on to the end of the existing data in the key. If you have previously stored a serialized object into Couchbase and then use Prepend, the content of the serialized object will not be extended. For example, adding an List of integers into the database, and then using Prepend() to add another integer will result in the key referring to a serialized version of the list, immediately preceded by a serialized version of the integer. It will not contain an updated list with the new integer prepended to it. De-serialization of objects that have had data prepended may result in data corruption.

API Call object.Prepend(key, value)
Asynchronous no
Description Prepend a value to an existing key
Returns Object ( Binary object )
Arguments
string key Document ID used to identify the value
object value Value to be stored

The Prepend() method prepends information to the end of an existing key/value pair.

The sample below demonstrates how to create a csv string by prepending new values.

client.Store(StoreMode.Set, "beers", "Abbey Ale");
Func<string, byte[]> stringToBytes = (s) => Encoding.Default.GetBytes(s);
client.Prepend("beers", new ArraySegment<byte>(stringToBytes("Three Philosophers,")));
client.Prepend("beers", new ArraySegment<byte>(stringToBytes("Witte,")));

You can check if the Prepend operation succeeded by using the checking the return value.

var result = client.Prepend("beers", new ArraySegment<byte>(stringToBytes("Hennepin,")));
if (result) {
    Console.WriteLine("Prepend succeeded");
} else {
    Console.WriteLine("Prepend failed");
}

API Call object.Prepend(key, casunique, value)
Asynchronous no
Description Prepend a value to an existing key
Returns Object ( Binary object )
Arguments
string key Document ID used to identify the value
ulong casunique Unique value used to verify a key/value combination
object value Value to be stored

Prepend() may also be used with a CAS value. With this overload, the return value is a CasResult, where success is determined by examining the CasResult’s Result property.

var casv = client.GetWithCas("beers");
var casResult = client.Prepend("beers", casv.Cas, new ArraySegment<byte>(stringToBytes("Adoration,")));

if (casResult.Result) {
    Console.WriteLine("Prepend succeeded");
} else {
    Console.WriteLine("Prepend failed");
}

API Call object.ExecutePrepend(key, value)
Asynchronous no
Description Prepend a value to an existing key
Returns IConcatOperationResult ( Concat operation result )
Arguments
string key Document ID used to identify the value
object value Value to be stored

The ExecutePrepend() behaves similar to Prepend(), but instead of a Boolean it returns an instance of an IConcatOperationResult.

var concatResult = client.Store(StoreMode.Set, "beers", "Abbey Ale");
Func<string, byte[]> stringToBytes = (s) => Encoding.Default.GetBytes(s);
client.Prepend("beers", new ArraySegment<byte>(stringToBytes("Three Philosophers,")));
client.Prepend("beers", new ArraySegment<byte>(stringToBytes("Witte,")));

if (! concatResult.Success) {
    logger.Error(concatResult.Message, concatResult.Exception);
}

API Call object.ExecutePrepend(key, casunique, value)
Asynchronous no
Description Prepend a value to an existing key
Returns IConcatOperationResult ( Concat operation result )
Arguments
string key Document ID used to identify the value
ulong casunique Unique value used to verify a key/value combination
object value Value to be stored

ExecutePrepend() may also be used with a CAS value. With this overload, the return value is an instance of an IConcatOperationResult.

var getResult = client.ExecuteGet("beers");
var concatResult = client.Prepend("beers", getResult.Cas, new ArraySegment<byte>(stringToBytes("Adoration,")));

if (concatResult.Success) {
    Console.WriteLine("Prepend succeeded");
} else {
    Console.WriteLine("Prepend failed");
}

Touch Methods

The Touch() methods allow you to update the expiration time on a given key. This can be useful for situations where you want to prevent an item from expiring without resetting the associated value. For example, for a session database you might want to keep the session alive in the database each time the user accesses a web page without explicitly updating the session value, keeping the user’s session active and available.

API Call object.Touch(key, expiry)
Asynchronous no
Description Update the expiry time of an item
Returns Boolean ( Boolean (true/false) )
Arguments
string key Document ID used to identify the value
object expiry Expiry time for key. Values larger than 30*24*60*60 seconds (30 days) are interpreted as absolute times (from the epoch).

The Touch method provides a simple key/expiry call to update the expiry time on a given key. For example, to update the expiry time on a session for another 60 seconds:

client.Touch("session", TimeSpan.FromSeconds(60));

To update the expiry time on the session for another day:

client.Touch("session", DateTime.Now.AddDays(1));

Sync Methods

API Call object.Sync(mode, keyn, replicationcount)
Asynchronous no
Description Sync one or more key/value pairs on a Membase cluster
Returns (none)
Arguments
mode
keyn One or more keys used to reference a value
replicationcount

Sync operations

Appendix: Configuring Logging

The following sections provide details on how to enable logging for the.NET Client Library

To enable logging, you can tap into the logging capabilities provided by the Enyim.Caching dependency. Enyim logging currently supports either log4net or NLog.

Start by adding a reference to either Enyim.Caching.Log4NetAdapter or Enyim.Caching.NLogAdapter. Both are available as part of the Couchbase.NET Client Nuget package or as part of the client library zip file.

You could also get the projects from . If you use these Visual Studio projects, you’ll also need to add a reference to log4net or NLog (depending on which adapter you choose). Each of these dependencies is located in a “binaries” directory under the root “EnyimMemcached” directory.

For log4net, your configuration should include an enyim.com section that defines which log factory to use along with standard log4net configuration.

The log4net configuration will vary by the type of appender you are using. For more information on log4net configuration, see .

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="enyim.com">
      <section name="log" type="Enyim.Caching.Configuration.LoggerSection, Enyim.Caching" />
    </sectionGroup>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <enyim.com>
    <log factory="Enyim.Caching.Log4NetFactory, Enyim.Caching.Log4NetAdapter" />
  </enyim.com>
  <log4net debug="false">
    <appender name="LogFileAppender" type="log4net.Appender.FileAppender,log4net">
      <param name="File" value="c:\\temp\\error-log.txt" />
      <param name="AppendToFile" value="true" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] &lt;%X{auth}&gt; - %m%n" />
      </layout>
    </appender>
    <root>
      <priority value="ALL" />
      <level value="DEBUG" />
      <appender-ref ref="LogFileAppender" />
    </root>
  </log4net>
</configuration>

You’ll also need to initialize (only once in your app) log4net in your code with the standard log4net initializer.

log4net.Config.XmlConfigurator.Configure();

NLog configuration requires setting the log factory to NLogAdapter and including the appropriate NLog configuration section.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="enyim.com">
      <section name="log" type="Enyim.Caching.Configuration.LoggerSection, Enyim.Caching" />
    </sectionGroup>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
  </configSections>
  <enyim.com>
    <log factory="Enyim.Caching.NLogFactory, Enyim.Caching.NLogAdapter" />
  </enyim.com>
  <nlog>
    <targets>
      <target name="logfile" type="File" fileName="c:\temp\error-log.txt" />
    </targets>
    <rules>
      <logger name="*" minlevel="Info" writeTo="logfile" />
    </rules>
  </nlog>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
  </startup>
</configuration>

See for more NLog configuration details.

Appendix: Release Notes

The following sections provide release notes for individual release versions of Couchbase Client Library.NET. To browse or submit new issues, see Couchbase Client Library.NET Issues Tracker.

Release Notes for Couchbase Client Library.NET 1.1.6 GA (07 June 2012)

New Features and Behavior Changes in 1.1.6

  • The 1.1.6 release of the Couchbase.NET Client library is a build only change, providing signed assemblies for both Couchbase.dll and Enyim.Caching.dll. The logging assemblies have also been signed.

Release Notes for Couchbase Client Library.NET 1.1.5 GA (30 May 2012)

These updates includes minor bugfixes to release (.92) as well as an upgrade to the current release of Enyim.Memcached (2.15)

New Features and Behavior Changes in 1.1.5

  • The 1.1.5 release of the Couchbase.NET Client library includes fixes for issues NCBC-42, NCBC-43 and NCBC-49. With this release, client bootstrapping is now performed off of /pools and the heartbeat check is configurable.

    Prior to version 1.1.5, the.NET client would get cluster information by first bootstrapping to a node at /pools/default. While this approach is generally safe, the client should have bootstrapped off of /pools as /pools/default might not be the correct second URI in the handshake sequence.

    <servers>
      <add uri="http://127.0.0.1:8091/pools&quot; />
      </servers>
    

    The.NET client performs a heartbeat check on the streaming connection it maintains by querying the bootstrapping node at periodic intervals. The URI it used previously for bootstrapping was the above bootstrapping URI. This release allows for this URI to be configured, along with the interval. Disabling the check is also allowed now.

    The default values are to check the /pools URI every 10 seconds. The heartbeatMonitor element is a sibling to the servers element.

    <heartbeatMonitor uri="http://127.0.0.1:8091/pools&quot; interval="10000" enabled="true" />
    

Release Notes for Couchbase Client Library.NET 1.1.0 GA (02 May 2012)

New Features and Behavior Changes in 1.1.0

  • The 1.1 release of the.NET Client Library contains a series of new API methods designed to provide developers with more details about the success or failure of an operation performed by the client.

    The existing API methods remain in place and as such, these changes are not breaking. Each of the new methods has the standard API method name prefixed by Execute. For example Store becomes ExecuteStore.

    var storeResult = client.ExecuteStore(StoreMode.Set, "foo", "bar");
    
    

    if (! result.Success) { Console.WriteLine("Operation failed: {0}", result.Message); }

    Each of the new Execute methods returns an instance of an IOperationResult, with is extended by various operation specific interfaces - IGetOperationResult, IStoreOperationResult, IConcatOperationResult, IMutateOperationResult and IRemoveOperationResult.

    IOperationResult defines common properties available to all results returned by Execute methods.

    IOperationResult opertionResult = client.Store(StoreMode.Set, "foo", "bar");
    
    

    //Was the operation successful (i.e., no errors or exceptions)? Console.WriteLine("Success: " + operationResult.Success);

    //Print out possible error, warning or informational message Console.WriteLine("Message: " + operationResult.Message);

    //Print out a caught exception Console.WriteLine("Exception: " + operationResult.Exception.Message);

    //Print out status code (nullable) Console.WriteLine("StatusCode: " + operationResult.StatusCode);

    //Print out InnerResult, which is populated on handled failures (i.e., IO exceptions) Console.WriteLine("InnerResult: " + operationResult.InnerResult.Message);

    Store, Get, Mutate and Concat operation results all return Cas values.

    var getResult = client.ExecuteGet("foo");
    
    

    //Print out the Cas value Console.WriteLine("Cas value for ‘foo’:" + getResult.Cas);

    Get operation results also expose HasValue and Value properties.

    var getResult = client.ExecuteGet("foo");
    
    

    //Print out whether getResult contains a value (shortcut for value null check) Console.WriteLine("getResult HasValue: " + getResult.HasValue);

    //Print out the item value Console.WriteLine("Value for ‘foo’:" + getResult.Value);

    Most failures are likely to fall into one of two categories. The first are conditions that the server won’t allow. For example, a Cas operation with an expired CAS value would be a failure. Attempting to add a key when that key already exists would also be failure. The second category of likely failures would occur when the client can’t connect to a node.

    Both categories of failures are likely to be reported by lower-level components within the client library. These components handle these errors gracefully and then log the problem. Before 1.1, these failure conditions were swallowed and did not propagate up to the caller. As a consequence, it is a good idea to check the InnerResult for a failed operation result.