/asp-net-mvc

Getting started with Couchbase on ASP.NET MVC

Primary LanguageC#

Getting started with Couchbase on ASP.NET MVC

With this guide you’ll create a "hello world" ASP.NET MVC web application that uses Couchbase.

What you’ll build

You’ll build an ASP.NET MVC website that will run on your development machine. You will access it through your browser at an address like:

http://localhost:1655/

With this website, you’ll be able to perform all the basic CRUD (Create,Read,Update,Delete) operations.

In this demonstration, you’ll be interacting with Profiles, which consist of "first name" and "last name". The Couchbase database will contain one "bucket" that contains people documents. Each document will be represented in JSON:

{
    "firstName": "Matt",
    "lastName": "Groves",
    "type": "Profile"
}

And each document will have a key that is the username of the profile.

What you’ll need

  • 15-30 minutes

  • Visual Studio 2015 installed (2013 will probably work too)

  • NuGet (it should be pre-packaged with Visual Studio already)

  • Couchbase Server 4.x (follow the instructions to install Couchbase and create a bucket - this guide assumes you will have it running locally). If you want to use Couchbase Server 5.x, check out the Couchbase Server 5.x with ASP.NET WebAPI Starter Kit.

How to complete this guide

This guide assumes you have some familiarity with the ASP.NET MVC framework. You should understand at least the basics of: Controllers, Views (we’ll be using Razor), and C#.

Build Setup

Get the "starter" source code sample that I’ve made available. Open git bash, clone the repo using git clone command. From Visual Studio, File→Open Project/Solution, navigate to the "starter" folder, and select the Starter.sln solution file.

You should be able to compile that project in Visual Studio, and you should also be able to run the website. When you do so before completing this guide, you’ll get some exceptions which contain hints on what code you need to write.

Code

Now that we’re starting from a common baseline, let’s start writing some code to use Couchbase.

Adding the necessary libraries

The first thing we’ll need to do is add the Couchbase .NET client. You can do this with the NuGet UI by right-clicking on "References", clicking "Manage NuGet Packages", clicking "Browse", and then searching for "CouchbaseNetClient".

NuGet Screenshot

Now let’s setup the ASP.NET app to be able to connect to Couchbase. The first thing we need to do is locate the Couchbase Cluster. The best place to do this is in the Global.asax.cs when the application starts. At a minimum, we need to specify one node in the cluster, and give that to the ClusterHelper. This only needs to be done once in Application_Start. When the application ends, it’s a good idea to close the ClusterHelper in order to clean up and dispose of resources that aren’t needed.

/Starter/Global.asax.cs

link:starter_complete/Starter/Global.asax.cs[role=include]

Once the ClusterHelper is initialized, we can use it to access buckets.

Data model and data access

In C#, you can model a Couchbase document by using a Plain Old CLR Object (POCO). Let’s model a very simple Profile class. Although C# and Couchbase can certainly handle more complexity, the goal of this guide is to get you up and running. We will explore more complex data models in other guides.

/Starter/Models/Profile.cs

link:starter_complete/Starter/Models/Profile.cs[role=include]

Note that I’m creating a string property of Type, which will be set to "Profile". A Couchbase bucket is a heterogenous collection of documents, so this is a convenient way to set Profile documents apart. You’ll see shortly how that property gets used.

Now let’s create a class that will access Couchbase data. Locate and open ProfileRespository.cs. There are many data access patterns that you can explore, but let’s look a simple repository pattern.

/Starter/Models/ProfileRepository.cs

link:starter_complete/Starter/Models/ProfileRepository.cs[role=include]

For this guide, I’m going to skip talking about ScanConsistency, because it would add complexity to this guide. There are trade-offs to consider when using different ScanConsistency options. However, RequestPlus is the easiest to use for a simple guide like this one.

Also, under normal circumstances, we’d prefer the IBucket to be injected with an IoC container, but it is omitted from this guide for the sake of simplicity.

With this repository, we can perform all of the CRUD operations. Let’s discuss each method individually:

GetProfileByKey

Each document in a Couchbase bucket has a unique key. Think of a bucket as a giant Dictionary<string,string> (that’s a gross oversimplification, but it’s a starting point). This method will return a document given a key. This is an extremely fast operation in Couchbase, and it’s always good to work with keys when possible.

GetAll

This method uses the Couchbase N1QL (Non-First Normal Form Query Language). N1QL is a superset of SQL, and allows you to construct very powerful queries. In this case, we’re simply getting all Profile documents with no limits or ordering. I’m formatting the results in such a way that the results of the query will map nicely into a KeyValuePair object (and ultimately a Dictionary). But paging, ordering, filtering, and many other powerful things can be done with a N1QL query. If this seems a little awkward to you, then I urge you to check out the Linq2Couchbase library (not officially supported by Couchbase, yet, but an amazing tool).

Save

Save is using "upsert", which operates on the document key.

If a document with the key already exists, it will update the value of the document (this is the UP in UPsert).

If a document with the key doesn’t exist, a new document will be created with that key. The only restriction on keys is that they must be unique within a bucket. I’m choosing to make the username the key.

Delete

Delete will remove the document with the given key.

CRUD ASP.NET MVC actions:

The sample code has an MVC controller HomeController already set up with some Actions and Views. The actions use the repository you created and pass along objects to the views. Views. The actions use the repository you created and pass along objects to the views.

You can view these by starting at HomeController.cs.

Once you’ve implemented the repository and added the setup code to Global.asax.cs, you should be ready to compile and run.

Run

After compiling and running the site for the first time, you should be taken to the Home Index page, which will show you a message that it didn’t find any Profile documents.

Initial view in browser

Click the "Add Profile" link in the navigation toolbar at the top, and you should be taken to a plain-looking form.

Create form

After saving, you should be redirected to the home index view, and you’ll see the new profile in the list. Feel free to do this multiple times to make the list grow.

List of profile documents in home index view

Now, pick one to edit and click the [Edit] link. You should see a form to edit a profile. Make some changes and click Submit.

Edit a profile

We’ve covered Read, Create, Update, so all that’s left is delete. Click a [Delete] link.

Delete a profile

Summary

Congratulations! You’ve just developed an ASP.NET MVC application that uses Couchbase.