With this guide you’ll create a "hello world" ASP.NET Core MVC web application that uses Couchbase.
You’ll build an ASP.NET Core MVC website with Visual Studio 2017 that will run on your development machine. You will access it through your browser at an address like:
http://localhost:39856/
(Port number may vary)
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 information in a Profile, which consists of "firstName" and "lastName". The Couchbase database will contain one "bucket" that contains Profile 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 (like "mgroves").
-
15-30 minutes
-
Visual Studio 2017 installed
-
Couchbase Server 5.0+ - follow the instructions to install Couchbase and create a bucket - this guide assumes you will have it running locally. Also note that Couchbase Server 5.0 is currently in beta at the time of writing 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#. Some jQuery is used in the Views, but you do not need any JavaScript knowledge to complete this guide.
Get the "starter" source code sample that I’ve made available in this repository. 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 aspnetcorestarter.sln
solution file.
You should be able to compile that project in Visual Studio, and you should also be able to run the website (F5 or Ctrl+F5 will automatically compile, run, and open the site in a browser). When you do so before completing this guide, you’ll get some exceptions which contain hints on what code you need to write.
After you’ve installed Couchbase Server, you’ll need to:
-
Create a bucket (I named mine "starterbucket")
-
Create a user (I named mine "aspnetuser")
-
Give necessary permissions to the user (it’s easiest to select "Cluster Admin" permission, but you may want to choose more fine-grained permissions, depending on what your app is going to do)
Login as administrator to the Couchbase Web Console (typically this is at http://localhost:8091
.
-
Navigate to "Buckets"
-
Click "ADD BUCKET"
-
Name the bucket "starterbucket".
-
We don’t need a very large bucket, so specify "128" for the memory quota.
-
All the other default settings are fine. Click "Add Bucket"
While still logged in as administrator:
-
Navigate to "Security"
-
Click "ADD USER"
-
Give the user an name of "aspnetuser"
-
Specify a password ("password" will be fine for this starter kit - but please don’t use that on a server exposed to the internet)
At this point, you can specify permissions for this user. Starting with Couchbase Server 5.0, you must use a user’s credentials to get access to buckets. For this starter kit, we only need one user, and it’s easiest to give that user access to almost everything. So, just select "Cluster Admin".
Finally, click "Save" to create the user.
We’re going to use a N1QL query in this starter guide. Proper indexing is vital when using N1QL, but for this guide all that’s needed is a simple primary index.
-
Navigate to "Query"
-
Enter the query:
CREATE PRIMARY INDEX ON starterbucket;
Now any N1QL query can be executed. However, this sort of index is not recommended for production apps. It’s the equivalent of a "table scan", and will not provide adequate performance with larger data sets.
Now that we’re starting from a common baseline, let’s switch back to Visual Studio 2017 and write some code to use Couchbase.
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 "Dependencies", clicking "Manage NuGet Packages", clicking "Browse", and then searching for "CouchbaseNetClient".
Click "CouchbaseNetClient" and then click "Install".
Next, 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 Startup.cs
where the application starts. At a minimum, we need to specify one node in the cluster and provide authentication credentials to the cluster. This only needs to be done once in the startup, in the Configure
method.
/aspnetcorestarter/Startup.cs
link:starter_complete/aspnetcorestarter/Startup.cs[role=include]
At this point, IBucket
is available as a service to the controllers, and it will correspond to a bucket called "starterbucket".
In C#, you can model a Couchbase document by using a Plain Old CLR Object (POCO). Let’s model a very simple Profile
class. Althought 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/aspnetcorestarter/Models/Profile.cs[role=include]
Note that I’m creating a string property of Type
, which will be always be "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/aspnetcorestarter/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.
Once you create this class, you can wire it into the Startup.cs
to be provided as a service:
link:starter_complete/aspnetcorestarter/Startup.cs[role=include]
We’ll see how this is used in the Controllers, later. But right now, ASP.NET Core knows how to create an IBucket
, and it knows how to create a ProfileRepository
(which requires an IBucket
in its constructor.
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 an N1QL query. If you’d rather use Linq than write N1QL strings, then I urge you to check out the Linq2Couchbase library.
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 (this is the SERT from upSERT). 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.
The sample code has an MVC controller HomeController
already set up with some Actions an 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.
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.
Click the "Add Profile" link in the navigation toolbar at the top, and you should be taken to a plain-looking 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.
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.
We’ve covered Read, Create, Update, so all that’s left is delete. Click a [Delete] link.