Skip to content

couchbase-guides/asp-net-core-mvc

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Getting started with Couchbase on ASP.NET MVC

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

What you’ll build

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").

What you’ll need

  • 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.

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#. Some jQuery is used in the Views, but you do not need any JavaScript knowledge to complete this guide.

Build Setup

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.

Couchbase Server Setup

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)

Create a bucket

Login as administrator to the Couchbase Web Console (typically this is at http://localhost:8091.

  1. Navigate to "Buckets"

  2. Click "ADD BUCKET"

  3. Name the bucket "starterbucket".

  4. We don’t need a very large bucket, so specify "128" for the memory quota.

  5. All the other default settings are fine. Click "Add Bucket"

Add new bucket

Create a user

While still logged in as administrator:

  1. Navigate to "Security"

  2. Click "ADD USER"

  3. Give the user an name of "aspnetuser"

  4. Specify a password ("password" will be fine for this starter kit - but please don’t use that on a server exposed to the internet)

Give necessary permissions

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.

Add User

Create a primary index for N1QL

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.

  1. Navigate to "Query"

  2. 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.

Code

Now that we’re starting from a common baseline, let’s switch back to Visual Studio 2017 and write 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 "Dependencies", clicking "Manage NuGet Packages", clicking "Browse", and then searching for "CouchbaseNetClient".

NuGet Screenshot

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".

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

CRUD ASP.NET MVC actions:

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.

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 Core MVC application that uses Couchbase Server.

About

Starter kit for ASP.NET Core MVC with Couchbase Server

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published