A newer version of this software is available
You are viewing the documentation for an older version of this software. To find the documentation for the current version, visit the Couchbase documentation home page.
This guide provides information for developers who want to use the Couchbase .NET SDK to build applications that use Couchbase Server.
This chapter will get you started with using Couchbase Server and the.NET (C#) Client Library. This article will walk you through the following:
Downloading and installing the Couchbase client library.
Setting up a command-line driven C# application in Visual Studio 2010, and referencing the Couchbase client library.
Writing a simple program to demonstrate connecting to Couchbase and saving some data in the database.
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:
Using the Couchbase Web Console, for information on using the Couchbase Administrative Console,
Couchbase CLI, for the command line interface,
Couchbase REST API, for creating and managing Couchbase resources.
After you have your Couchbase Server set up and you have installed the Couchbase SDK, you can compile and run the following basic program.
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.
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):
Click on File > New > Project
Choose: Visual C# > Windows > Console Application as your template
Give the project the name HelloCouchbase
Click OK to create the new project
Right click the HelloCouchbase project in the solution explorer and choose Add | New Folder, and name the new folder Libraries
Drag and drop all of the.dll,.pdb, and.xml files from the.NET Client Library zip-file you downloaded into the Libraries folder
Right click on References and choose Add Reference
Click on the Browse tab and then find the Libraries folder and choose the Enyim.Caching.dll and the Couchbase.dll
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’.
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.
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.
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. |
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. |
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. |
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.
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.
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.
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));
The retrieve operations get information from the Couchbase database. A summary of the available API calls is listed below.
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.Get(keyarray)
|
---|---|
Asynchronous | no |
Description | Get one or more key values |
Returns | Object ( Binary object ) |
Arguments | |
List |
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.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));
The update methods support different methods of updating and changing existing information within Couchbase. A list of the available methods is listed below.
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");
}
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.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("badkey");
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);
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");
}
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));
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
The following sections provide release notes for individual release versions of Couchbase Client Library.NET. To browse or submit new issaues, see Couchbase Client Library.NET Issues Tracker.
New Features and Behavior Changes in 1.0.0
Also updated in 1.0, classes, namespaces and the assembly have been renamed from Membase to Couchbase to reflect the server product name change.
What this means to you is that calling code will need to be updated and recompiled when referencing the new assembly.
For example
var config = new MembaseClientConfiguration();
var client = new MembaseClient(config);
is now
var config = new CouchbaseClientConfiguration();
var client = new CouchbaseClient(config);
The app config section and config section handler also references Couchbase, instead of Membase.
<configuration>
<section name="membase" type="Membase.Configuration.MembaseClientSection, Membase"/>
</configSections>
<section name="membase" type="Membase.Configuration.MembaseClientSection, Membase"/>
</configSections>
<membase>…</membase>
<startup>
</configuration>
is now
<configuration>
<section name="couchbase" type="Couchbase.Configuration.CouchbaseClientSection, Couchbase"/>
</configSections>
<section name="couchbase" type="Couchbase.Configuration.CouchbaseClientSection, Couchbase"/>
</configSections>
<couchbase>…</couchbase>
<startup>
</configuration>