Skip to main content

Posts tagged with '.net core'

This is a repost that originally appeared on the Couchbase Blog: Distributed caching with ASP.NET Core and Couchbase.

Distributed caching can help to improve performance of an ASP.NET Core application. This is especially true for an ASP.NET application that’s deployed to a server farm or scalable cloud environment. Using Couchbase Server for caching is one of the many features that make it an ideal choice for your engagement database needs.

In this blog post, I’ll show you how to use the Couchbase.Extensions.Caching middleware plugin to easily add distributed caching capabilities to your application.

You can follow along with the sample code I wrote for this post on GitHub.

Please note that Couchbase.Extensions.Caching is currently in a beta2 release (as I’m writing this blog post), so some things may change.

Basic setup of Couchbase

First, you’ll need a Couchbase Server cluster running (you can install it on-premise, or with Docker, or even in Azure if you’d like).

Next, you’ll need to create a bucket in Couchbase where cached data will be stored. I called mine "cachebucket". You may want to take advantage of the new ephemeral bucket feature in Couchbase Server 5.0 for caching, but it is not required.

If you are using Couchbase Server 5.0, you’ll also need to create a user with permissions (Data Writer and Data Reader) on that bucket. To keep things simple, create a user that has the same name as the bucket (e.g. "cachebucket").

Distributed Caching with Couchbase.Extensions

The Couchbase.Extensions (GitHub) project aims to make working with Couchbase Server and .NET Core simpler. Caching is just one of these extensions.

You can add it to your ASP.NET Core project with NuGet, via Package Manager: Install-Package Couchbase.Extensions.Caching -Version 1.0.0-beta2, or with the NuGet UI, or you can use the .NET command line: dotnet add package Couchbase.Extensions.Caching --version 1.0.0-beta2.

Couchbase extension for distributed caching available on NuGet

Once you’ve added this to your project, you’ll need to make a couple minor changes to your Startup class in Startup.cs.

First, in ConfigureServices, add a couple namespaces:

using Couchbase.Extensions.Caching;
using Couchbase.Extensions.DependencyInjection;

This will make the Caching namespace available, and specifically the AddDistributedCouchbaseCache extension method for IServiceCollection. Next, call that extension method from within the ConfigureServices method.

The other namespace in there, DependencyInjection, is necessary to inject Couchbase functionality. In this case, it’s going to be used only by the Caching extension. But you can use it for other purposes too, which I will cover in a future blog post.

But for now, it’s just needed for the AddCouchbase extension method on IServiceCollection.

Finally, put them both together, and your ConfigureServices method should look like this:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddCouchbase(opt =>
    {
        opt.Servers = new List<Uri>
        {
            new Uri("http://localhost:8091")
        };
    });

    services.AddDistributedCouchbaseCache("cachebucket", "password", opt => { });
}

Using distributed caching

Now that you have distributed caching setup with Couchbase in your ASP.NET Core project, you can use IDistributedCache elsewhere in your project.

Injecting IDistributedCache

A simple example would be to use it directly in a controller. It can be injected into constructors as you need it:

public class HomeController : Controller
{
    private readonly IDistributedCache _cache;

    public HomeController(IDistributedCache cache)
    {
        _cache = cache;
    }

    // ... snip ...

}

Caching strings

You can use the GetString and SetString methods to retrieve/set a string value in the cache.

// cache/retrieve from cache
// a string, stored under key "CachedString1"
var message = _cache.GetString("CachedString1");
if (message == null)
{
    message = DateTime.Now + " " + Path.GetRandomFileName();
    _cache.SetString("CachedString1", message);
}
ViewData["Message"] = "'CachedString1' is '" + message + "'";

This would appear in the "cachebucket" bucket as an encoded binary value (not JSON).

String cached in Couchbase

In the sample code, I simply print out the ViewData["Message"] in the Razor view. It should look something like this:

Cached string output to Razor

Caching objects

You can also use Set<> and Get<> methods to save and retrieve objects in the cache. I created a very simple POCO (Plain Old CLR Object) to demonstrate:

public class MyPoco
{
    public string Name { get; set; }
    public int ShoeSize { get; set; }
    public decimal Price { get; set; }
}

Next, in the sample, I generate a random string to use as a cache key, and a random generated instance of MyPoco. First, I store them in the cache using the Set<> method:

var pocoKey = Path.GetRandomFileName();
_cache.Set(pocoKey, MyPoco.Generate(), null);
ViewData["Message2"] = "Cached a POCO in '" + pocoKey + "'";

Then, I print out the key to the Razor view:

Cached POCO output to Razor

Next, I can use this key to look up the value in Couchbase:

Cached POCO in Couchbase

Also, notice that it’s been serialized to JSON. This not only means that you can read it, but you can also query it with N1QL (if you need to).

Distributed caching with expiration

If you want the values in the cache to expire after a certain period of time, you can specify that with DistributedCacheEntryOptions (only SlidingExpiration is supported at this time).

var anotherPocoKey = Path.GetRandomFileName();
_cache.Set(anotherPocoKey, MyPoco.Generate(), new DistributedCacheEntryOptions
{
    SlidingExpiration = new TimeSpan(0, 0, 10) // 10 seconds
});
ViewData["Message3"] = "Cached a POCO in '" + anotherPocoKey + "'";

In the sample project, I’ve also set this to print out to Razor.

Cached POCO with expiration

If you view that document (before the 10 seconds runs out) in Couchbase Console, you’ll see that it has an expiration value in its metadata. Here’s an example:

{
  "id": "xjkmswko.v35",
  "rev": "1-14e1d9998125000059b0404502000001",
  "expiration": 1504723013,
  "flags": 33554433
}

After 10 seconds, that document will be gone from the bucket, and you’ll see an error "not found (Document does not exist)".

Tearing down distributed caching

Finally, don’t forget to cleanup the resources used by the Couchbase .NET SDK for distributed caching. One easy way to do this is with the ApplicationStopped event. You can wire this up in Startup:

appLifetime.ApplicationStopped.Register(() =>
{
    app.ApplicationServices.GetRequiredService<ICouchbaseLifetimeService>().Close();
});

Note that you will have to add IApplicationLifetime appLifetime as a parameter to the Configure method in Startup if you haven’t already.

Summary

Using Couchbase Server for distributed caching in your ASP.NET Core application is a great way to improve performance and scalability in your application. These kind of "engagement" use cases are what Couchbase Server excels at. To see customers that are using Couchbase Server for caching, check out the Couchbase Customers page.

If you have questions or comments about the Couchbase.Extensions.Caching project, make sure to check out the GitHub repository or the Couchbase .NET SDK forums.

As always, you can reach me by leaving a comment below or finding me on Twitter @mgroves.

This is a special crossover episode of Cross Cutting Concerns with the Eat Sleep Code podcast, hosted by Ed Charbeneau (Microsoft MVP). This was recorded at the Stir Trek conference.

Show Notes:

Ed Charbeneau is on Twitter

Want to be on the next episode? You can! All you need is the willingness to talk about something technical.

Theme music is "Crosscutting Concerns" by The Dirty Truckers, check out their music on Amazon or iTunes.

This is a repost that originally appeared on the Couchbase Blog: C# Tuples: New C# 7 language feature.

C# tuples are a new feature of C# 7. I’m going to show you the basics of how C# tuples work. I’m also going to mix in a little Couchbase to show tuples in action. However, if you don’t want to install Couchbase just to play around with tuples, don’t worry, you will still be able to follow along.

Note: If you’ve been using C# for a while, you might remember the Tuple Class that was introduced in .NET 4. That class still exists, but it is not the same thing as the new tuple feature of C#.

What are C# tuples?

A "tuple" is a name for a mathematical concept that is just a list of elements. In the LISP family of languages, coding is built almost entirely around the idea that everything is a list. C# once again borrows the kernel of an idea from the functional programming world and integrates it into a non-functional language. So, we get C# tuples (check out the original C# tuple proposal by Mads Torgersen for more details and background).

Remember anonymous types?

But, to make it simple, let’s consider something you may already be familiar with in C#, an anonymous type. To review, you can instantiate a new object without specifying a type:

var myObject = new { Foo = "bar", Baz = 123 };

Behind the scenes, there actually is a type that inherits from the base Object type, but generally speaking, we only deal with the object, not its type.

Additionally, I can’t return an anonymous type from a method, or pass an anonymous type as a parameter without losing the type information in the process.

private object GetAnonymousObject()
{
    return new {Foo = "bar", Baz = 123};
}

private void AnotherMethod()
{
    var obj = GetAnonymousObject();
    Console.WriteLine(obj.Foo); // compiler error :(
}

They are useful, certainly, but I generally refer to these as anonymous objects as I use them, for these reasons.

What’s this got to do with C# tuples?

I think of C# tuples as richer anonymous types. They are a way to create a "class" on the fly without actually defining a class. The syntax for tuples is to simply put parenthesis around a comma separated list of types and names. A tuple literal is just a comma separated list of literals also surrounded by parenthesis. For instance:

(string FirstName, string LastName) myTuple = ("Matt", "Groves");

Console.WriteLine(myTuple.FirstName); // no compiler error :)
Console.WriteLine(myTuple.LastName);  // no compiler error :)

Note: Right now I’m preferring PascalCase for tuple properties. I don’t know if that’s the official guideline or not, but it "feels" right to me.

C# tuples in action

I put tuples to work in a simple console app that interacts with Couchbase.

I created a BucketHelper class that is a very simple facade over the normal Couchbase IBucket. This class has two methods: one to get a document by key and return a tuple, and one to insert a tuple as a document.

public class BucketHelper
{
    private readonly IBucket _bucket;

    public BucketHelper(IBucket bucket)
    {
        _bucket = bucket;
    }

    public (string Key, T obj) GetTuple<T>(string key)
    {
        var doc = _bucket.Get<T>(key);
        return (doc.Id, doc.Value);
    }

    public void InsertTuple<T>((string Key, T obj) tuple)
    {
        _bucket.Insert(new Document<T>
        {
            Id = tuple.Key,
            Content = tuple.obj
        });
    }
}

To instantiate this helper, you just need to pass an IBucket into the constructor.

Tuple as a return type

You can then use the GetTuple method to get a document out of Couchbase as a tuple.

var bucketHelper = new BucketHelper(bucket);

(string key, Film film) fightClub = bucketHelper.GetTuple<Film>("film-001");

The tuple will consist of a string (the document key) and an object of whatever type you specify. The document content is JSON and will be serialized to a C# object by the .NET SDK.

Also, notice that the name of the tuple properties don’t have to match. I used obj in BucketHelper but I used film when I called GetTuple<Film>. The types do have to match, of course.

Tuple as a parameter type

I can also go the other way and pass a tuple as a parameter to InsertTuple.

string key = Guid.NewGuid().ToString();
Film randomFilm = GenerateRandomFilm();
bucketHelper.InsertTuple((key, randomFilm));

The GenerateRandomFilm method returns a Film object with some random-ish values (check out the GitHub source for details). A tuple of (string, Film) is passed to InsertTuple. The Couchbase .NET SDK takes it from there and inserts a document with the appropriate key/value.

Running the console app, you should get an output that looks something like this:

C# tuples sample console output

Note that the Couchbase .NET SDK at this time doesn’t have any direct tuple support, and it may not ever need it. This code is simply to help demonstrate C# tuples. I would not recommend using the BucketHelper as-is in production.

TUH-ple or TOO-ple?

I seem to remember my professor(s) pronouncing it as "TOO-ple", so that’s what I use. Like the hard-G / soft-G debate of "GIF", I’m sure there are those who think this debate is of the utmost importance and are convinced their pronunciation is the one true way. But, both are acceptable.

If you have questions about tuples, I’d be happy to help. You can also contact me at Twitter @mgroves or email me matthew.groves@couchbase.com.

If you have questions about the Couchbase .NET SDK that I used in this post, please ask away in the Couchbase .NET Forums. Also check out the Couchbase Developer Portal for more information on the .NET SDK and Couchbase in general.

This is a repost that originally appeared on the Couchbase Blog: ASP.NET with NoSQL Workshop.

I delivered an ASP.NET with NoSQL workshop at the recent Indy.Code() conference in Indianapolis. I had a lot of fun at this conference, and I recommend you go next year. If you were unable to attend, don’t worry, because I’ve got the next best thing for you: all the material that I used in my workshop.

ASP.NET Workshop in 4 parts

This workshop contained four main parts:

  • Install a NoSQL database (Couchbase Server)

  • Interact with Couchbase Server (using both the Web Console and the .NET (or .NET Core) SDK)

  • Create a RESTful API using ASP.NET (or ASP.NET Core) WebAPI

  • Consume the RESTful API with an Angular frontend

Try it yourself

If you’d like to try it yourself, the ASP.NET with NoSQL Workshop materials are available on GitHub. Each part of the workshop contains a PPT and PDF file for you to follow along. Also, the "completed" version of each workshop is available.

If you get stuck or have any questions, please ask away in the Couchbase .NET Forums. Also check out the Couchbase Developer Portal for more information on the .NET SDK and Couchbase in general.

You can also contact me at Twitter @mgroves.

Bill Wagner is writing .NET Core documentation.

Show Notes:

Bill Wagner is on Twitter

Want to be on the next episode? You can! All you need is the willingness to talk about something technical.

Theme music is "Crosscutting Concerns" by The Dirty Truckers, check out their music on Amazon or iTunes.

Matthew D. Groves

About the Author

Matthew D. Groves lives in Central Ohio. He works remotely, loves to code, and is a Microsoft MVP.

Latest Comments

Twitter