Search:

Search all manuals
Search this manual
Manual
Getting Started with Membase and C#
Additional Resources
Community Wiki
Community Forums
Couchbase SDKs
Parent Section
Getting Started with Membase and C#
Chapter Sections
Chapters

3. Hello C# Membase

3.1. Membase API overview
3.2. Conclusion

The easiest way to create and compile C# programs is by using Visual Studio 2010. Let's go into Visual Studio and create a HelloMembase 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 HelloMembase

  4. Click OK to create the new project

    Figure 1. Figure 1: Solution Explorer for HelloMembase solution.

    Solution Explorer for HelloMembase solution

  5. Right click the HelloMembase 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 Membase.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 HelloMembase 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.

Figure 2. Figure 2: Solution with added references.

Solution with added references

Next you will need to configure the client library to talk with Membase. 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="membase" type="Membase.Configuration.MembaseClientSection, Membase"/>
  </configSections>

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

  <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 Membase 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 Membase server. Enter the code in Listing 2 into Program.cs:

Listing 2: Simple C# Application

using System;
using Enyim.Caching.Memcached;
using Membase;

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

                if ((spoon = client.Get<string>("Spoon")) == null)
                {
                    Console.WriteLine("There is no spoon!");
                    client.Store(StoreMode.Set,
                                 "Spoon",
                                 "Hello, Membase!",
                                 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, Membase!
Press any key to continue

The code creates an instance of a MembaseClient in a using block so that it will be properly disposed of before the program exits. Creation of the MembaseClient 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 Membase.

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 Enyim Membase 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 Membase 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.