Skip to main content

Posts tagged with 'or'

Swashbuckle is a handy library to easily bring Swagger support to your ASP.NET Core (or ASP.NET) application. It is especially handy when developing an HTTP based API. It creates a form of interactive documentation based on the OpenAPI Specification.

Before diving into Swashbuckle: Merry Christmas! This blog is being posted on December 25th, 2017. It’s the final post of the very first C# Advent Calendar. Please check out the other 24 posts in the series! This event has gone so well, that I’m already planning on doing it again in 2018. Thank you, again, to everyone who participated (whether you are a writer or you’ve just been following along).

The full source code used in this example is available on Github.

ASP.NET Core HTTP API

I’m going to assume some level of familiarity with ASP.NET Core and creating a REST API. Here’s an example of a GET and a POST. These endpoints are reading/writing from a JSON text file (in a way that is probably not thread-safe and definitely not efficient, but it’s fine for this example).

public class ValuesController : Controller
{
    [HttpGet]
    [Route("api/teams")]
    public IActionResult GetTeams()
    {
        var jsonFile = System.IO.File.ReadAllText("jsonFile.json");
        var teams = JsonConvert.DeserializeObject<List<Team>>(jsonFile);
        return Ok(teams);
    }

    [HttpPost]
    [Route("api/team")]
    public IActionResult PostTeam([FromBody]Team team)
    {
        var jsonFile = System.IO.File.ReadAllText("jsonFile.json");
        var teams = JsonConvert.DeserializeObject<List<Team>>(jsonFile);
        teams.Add(team);
        System.IO.File.WriteAllText("jsonFile.json",JsonConvert.SerializeObject(teams));
        return Ok(team);
    }

    // etc...

To try out the GET endpoint, the simplest thing I can do is open a browser and view the results. But to try out the POST endpoint, I need something else. I could install Postman or Fiddler (and you should). Here’s how that would look.

Postman

Postman is great for interacting with endpoints, but Postman alone doesn’t really tell us anything about the endpoint or the system as a whole. This is where Swagger comes in.

Swagger

Swagger is a standard way to provide specifications for endpoints. Usually, that specification is automatically generated and then used to generate an interactive UI.

We could write the Swagger spec out by hand, but fortunately ASP.NET Core provides enough information to generate a spec for us. Look at the PostTeam action above. Just from reading that we know:

  • It expects a POST

  • The URL for it is /api/team

  • There’s a Team class that we can look at to see what kind of body is expected

From that, we could construct a Swagger spec like the following (I used JSON, you can also use YAML).

{
	"swagger": "2.0",
	"info": { "version": "v1", "title": "Sports API" },
	"basePath": "/",
	"paths": {
		"/api/team": {
			"post": {
				"consumes": ["application/json"],
				"parameters": [{
					"name": "team",
					"in": "body",
					"required": false,
					"schema": { "$ref": "#/definitions/Team" }
				}]
			}
		}
	},
	"definitions": {
		"Team": {
			"type": "object",
			"properties": {
				"name": { "type": "string" },
				"stadiumName": { "type": "string" },
				"sport": { "type": "string" }
			}
		}
	}
}

But why on earth would you want to type that out? Let’s bring in a .NET library to do the job. Install Swashbuckle.AspNetCore with NuGet (there’s a different package if you want to do this with ASP.NET).

You’ll need to add a few things to Startup.cs:

In the ConfigureServices method:

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Info { Title = "Sports API", Version = "v1"});
});

In the Configure method:

app.UseSwagger();

Aside: With ASP.NET, NuGet actually does all this setup work for you.

Once you’ve done this, you can open a URL like http://localhost:9119/swagger/v1/swagger.json and see the generated JSON spec.

Swagger spec in JSON

Swagger UI with Swashbuckle

That spec is nice, but it would be even nicer if we could use the spec to generate a UI.

Back in the Configure method, add this:

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Sports API v1");
});

Now, open your site and go to /swagger:

Swagger UI generated by Swashbuckle

Some cool things to notice:

  • Expand/collapse by clicking the URL of an endpoint (note that you must use Route attributes for Swashbuckle to work with ASP.NET Core).

  • "Try it out!" buttons. You can execute GET/POST right from the browser

  • The "parameter" of the POST method. Not only can you paste in some content, but you get an example value that acts like a template (just click it).

Giving some swagger to your Swagger

Swagger and Swashbuckle have done a lot with just a little bit. It can do even more if we add a little more information in the code.

  • Response: The ProducesResponseType attribute will let Swagger know what the response will look like (this is especially useful if you are using IActionResult and/or an endpoint could return different types in different situations).

  • Comments: If you are using XML comments, you can have these included with the Swagger output.

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Info { Title = "Sports API", Version = "v1" });
    var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "swashbuckle-example.xml");
    c.IncludeXmlComments(filePath);
});

(Also make sure you XML Documentation output for your project enabled)

Here’s an example of a GetTeams method with both XML comments and ProducesResponseType:

/// <summary>
/// Gets all the teams stored in the file
/// </summary>
/// <remarks>Baseball is the best sport</remarks>
/// <response code="200">List returned succesfully</response>
/// <response code="500">Something went wrong</response>
[HttpGet]
[Route("api/teams2")]
[ProducesResponseType(typeof(Team), 200)]
public IActionResult GetTeams2()
{
    var jsonFile = System.IO.File.ReadAllText("jsonFile.json");
    var teams = JsonConvert.DeserializeObject<List<Team>>(jsonFile);
    return Ok(teams);
}
  • Customize your info: there’s more to the Info class than just Title and Version. You can specify a license, contact, etc.

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Info
    {
        Title = "Sports API",
        Version = "v1",
        Description = "An API to list and add sports teams",
        TermsOfService = "This is just an example, not for production!",
        Contact = new Contact
        {
            Name = "Matthew Groves",
            Url = "https://crosscuttingconcerns.com"
        },
        License = new License
        {
            Name = "Apache 2.0",
            Url = "http://www.apache.org/licenses/LICENSE-2.0.html"
        }
    });
    var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "swashbuckle-example.xml");
    c.IncludeXmlComments(filePath);
});

Here’s a screenshot of the UI that has all three of the above enhancements: response type, XML comments, and more customized info.

Swagger with more swagger

Summary

Working on HTTP-based APIs? Bring Swashbuckle and Swagger into your life!

More resources:

Thanks again for reading the 2017 C# Advent!

This is a repost that originally appeared on the Couchbase Blog: ASP.NET Core with Couchbase: Getting Started.

ASP.NET Core is the newest development platform for Microsoft developers. If you are looking for information about plain old ASP.NET, check out ASP.NET with Couchbase: Getting Started.

ASP.NET Core Tools to Get Started

The following video will take you from having no code to having an HTTP REST API that uses Couchbase Server, built with ASP.NET Core.

These tools are used in the video:

Getting Started Video

In the video, I touch quickly on Scan Consistency. For more details on that, check out the Scan Consistency documentation or read a blog post that I wrote introducing AtPlus, which also covers the other types of Scan Consistency.

Summary

This video gives you the absolute minimum to get started with Couchbase by walking you through a simple CRUD application.

If you have any questions, please leave a comment. Or, you can always ask me questions on Twitter @mgroves.

This is a repost that originally appeared on the Couchbase Blog: Performance Testing and Load Testing Couchbase with Pillowfight.

Performance testing and load testing are important processes to help you make sure you are production ready. For testing Couchbase Server clusters, there is an open-source command line utility called "cbc-pillowfight". It’s part of libcouchbase.

Before you begin

You’ll need a Couchbase Server cluster up and running. You can try it out directly on your local machine (download Couchbase for Linux, Windows, and Mac) or in a Docker container.

If you’re just trying out pillowfight, you may want to create a bucket on your cluster just for that purpose. I created a bucket called "pillow".

After you have Couchbase Server installed, you’ll need to download and install libcouchbase:

  • Mac: brew install libcouchbase

  • Windows: download a zip file (latest at the time of writing is libcouchbase-2.8.1)

For more information, including Linux instructions, check out the libcouchbase release notes.

Pillow fight for Performance Testing

If you used homebrew to install on a Mac, you can type cbc-pillowfight --help straight away for the command line help screen.

On Windows, unzip the libcouchbase zip file wherever you’d like. You’ll find cbc-pillowfight.exe in the bin folder.

Performance testing tools

The simplest pillowfight you can run is:

.\cbc-pillowfight.exe -U couchbase://localhost/pillow -u Administrator -P password

This is for a Windows Powershell command line, but it will be very similar on other OSes.

A pillow fight will start for the cluster running on your local machine (localhost), with the "Administrator" user that has a password of "password" (your username and password may be different).

Starting pillowfight

You should see a message like "Thread 0 has finished populating".

What is a pillow fight?

At this point, the pillowfight is going to start creating, updating, and reading documents from the "pillow" bucket. It’s going to do all these operations ("ops") according to the command line settings you specify (or fall back to the defaults).

For instance, with the -I flag, you can specify how many total documents you want to operate on. The default is 1000. So, if you run the above command, you will soon see 1000 documents show up in the pillow bucket.

It doesn’t just create 1000 documents and quit. Pillowfight will keep "getting" and "updating" those documents until you terminate the process. It’s called a "pillowfight" because it will put your Couchbase Cluster into battle (with actual exertion), but it’s really more of a battle simulation.

While the fight is happening, you can monitor bucket statistics to see how your cluster is performing under load.

Performance testing monitoring

As I type this, the fan on my laptop is whirring to life as I stress test the single node Couchbase cluster that I’ve installed on it. (I suspect my home desktop would create a much more impressive set of charts, but I am traveling a lot this month).

There are a lot of statistics available for you to look at on a bucket level. Check out the Couchbase Server documentation on Monitoring Statistics for more details.

Options for performance testing

The default pillowfight settings may not be optimal for the type of application that you’ll be using with Couchbase. There are many ways to adjust your pillow fight to make it better fit your use cases. For the full list of options, type cbc-pillowfight --help at the command line.

But here are some notable options you might want to try out:

  • -I or --num-items with a number, to specify how many documents you want to operate on.

  • --json to use JSON payloads in the documents. By default, documents are created with non-JSON payloads, but you may want to have real JSON documents in order to test other aspects of performance while the pillow fight is running.

  • -e to expire documents after a certain period of time. If you are using Couchbase as a cache or short term storage, you will want to use this setting to monitor the effect of documents expiring.

  • --subdoc to use the subdocument API. Not every operation will need to be on an entire document.

  • -M or --max-size to set a ceiling on the size of the documents. You may want to adjust this to tailor a more realistic document size for your system. There’s a corresponding -m and --min-size too.

Here’s another example using the above options:

.\cbc-pillowfight.exe -U couchbase://localhost/pillow -u Administrator -P password -I 10000 --json -e 10 --subdoc -M 1024

This will start a pillowfight using 10000 JSON documents, that expire after 10 seconds, uses the sub-document API, and has a max document size of 1024 bytes.

Note: there is a -t --num-threads option. Currently, if you're using Windows (like me), you are limited to a single thread (see this code).

Summary

Couchbase is committed to performance. We do extensive performance testing to make sure that we are delivering the speed you expect. Check out recent blog posts on our Plasma storage engine and N1QL enhancements. But no one knows your use case and infrastructure better than you. With pillowfight, you have a tool to help you do performance testing, load testing, and stress testing.

Thanks go out to Sergey Avseyev for helping with this blog post, and his contributions to libcouchbase.

Please reach out with questions on Couchbase by leaving a comment below or finding me on Twitter @mgroves.

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

Distributed session is a way for you to store your session state outside of your ASP.NET Core application. Using Couchbase to store session state can help you when you need to scale your web site, especially if you don’t want to use sticky sessions.

You can follow along with the code samples I’ve created, available on GitHub.

Note that Couchbase.Extensions.Session is a beta release at the time of this writing.

Review of session

Session state is simply a way to store data for a particular user. Typically, a token is stored in a user cookie, and that token acts as a key to some set of data on the server side.

If you’re familiar with ASP.NET or ASP Classic, this is done using Session. All the cookie work is done behind the scenes, so you simply use Session as a dictionary to store and retrieve whatever data you want.

if(Session["IsLoggedIn"] = false)
    Session["Username"] = "matt";

By default, in ASP.NET and ASP Classic, this information is stored in memory, as part of the web application process.

In ASP.NET Core, you can also opt-in to this by configuring session with AddSession.

First, in Startup.cs, in the Configure function, tell ASP.NET Core to use session:

app.UseSession();

Then, in the ConfigureServices function, use AddSession to add a session provider service.

services.AddDistributedMemoryCache();
services.AddSession();

(This will use the default session settings, see the ASP.NET Core documentation for more information).

Why distributed session?

However, if you are scaling out your web application with multiple web servers, you’ll have to make some decisions about session. If you continue to use in-process session, then you must configure sticky sessions (the first web server that a user hits is the one they will "stick" with for subsequent requests). This has some potential downsides (see this thread on ServerFault and this article on Microsoft’s TechNet magazine).

If you don’t want to use sticky sessions, then you can’t use the in-process session option. You’ll instead need to use a distributed session. There are a lot of options for where to put session data, but Couchbase’s memory-first architecture and flexible scaling capabilities make it a good choice.

Using distributed session in ASP.NET Core

Before you start writing code, you’ll need a Couchbase Server cluster running with a bucket (I named mine "sessionstore"). You’ll also need to create a user with Data Reader and Data Writer permission on the bucket (I also called my user "sessionstore" just to keep things simple).

Adding Couchbase.Extensions.Session

Now, open up your ASP.NET Core application in Visual Studio. (I created a new ASP.NET Core MVC app, which you can find on GitHub). Next, with NuGet, install the Couchbase.Extensions.Session library:

  • Use the NuGet UI (see below), or

  • Install-Package Couchbase.Extensions.Session -Version 1.0.0-beta2 with the Package manager, or

  • dotnet add package Couchbase.Extensions.Session --version 1.0.0-beta2 with the dotnet command line

Couchbase Extensions with NuGet

Configuring Couchbase

To configure the session provider, you’ll be writing some code that looks familiar if you’ve been following along in this Couchbase.Extensions series.

The ConfigureServices method in Startup.cs is where you’ll be adding configuration code.

First, use AddCouchbase, which is done with the Dependency Injection extension.

After that, setup the distributed cache for Couchbase with AddDistributedCouchbaseCache, which I covered in a blog post on distributed caching.

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

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

Finally, configure Couchbase as a session store with AddCouchbaseSession.

services.AddCouchbaseSession(opt =>
{
    opt.CookieName = ".MyApp.Cookie";
    opt.IdleTimeout = new TimeSpan(0, 0, 20, 0);
});

You can configure the idle timeout (how long until the session expires after not being used), the cookie name, and more, if you need to. In the above example, I set the timeout to 20 minutes and the cookie name to ".MyApp.Cookie".

Writing to a distributed session

To access Session data, you can use HttpContext.Session.

First, I want to write something to session. In an About controller action, I used the SetObject method:

public IActionResult About()
{
    HttpContext.Session.SetObject("sessionkey", new
    {
        Name = "Matt",
        Twitter = "@mgroves",
        Guid = DateTime.Now
    });

    ViewData["Message"] = "I put a value in your session. Click 'Contact' to see it.";

    return View();
}

From this point on, whenever you click to view the "About" page, a new value will be stored in session with the key "sessionkey". If you switch over to Couchbase Console, you can see the data being stored.

Distributed session document in Couchbase

Note that a user’s session is represented by a single document. So, if I were to insert another session value (as below), that value would be stored in the same document.

HttpContext.Session.SetObject("sessionkey2", new
{
    Address = "123 Main St",
    City = "Lancaster",
    State = "OH"
});

The resultant document would look like:

Two distributed session keys

You should be careful not to go crazy with the amount of data you put into session, because Couchbase documents are limited to 20mb.

Reading from a distributed session

To get a value out of session, you can use GetObject and supply the session key. In the sample code, I did this in the Contact action:

public IActionResult Contact()
{
    ViewData["Message"] = HttpContext.Session.GetObject<dynamic>("sessionkey");

    return View();
}

After you visit the "About" page at least once, go to the "Contact" page. You should see the session object printed out to the page.

Output to ASP.NET from distributed session

That’s pretty much it. There are some other relatively self-evident methods available on Session. They are also outlined in the ASP.NET Core documentation.

One more thing: I named the cookie (".MyApp.Cookie"). You can view this cookie in the browser of your choice. In Chrome, use Ctrl+Shift+I and navigate to the "Application" tab. You will see the cookie and its value.

Session cookie

You generally don’t need to know this detail in your day-to-day as an ASP.NET Core developer, but it’s good to know how things work just in case.

Summary

The distributed session extension for Couchbase is another tool in your box for helping to scale your ASP.NET Core applications. These handy .NET extensions help to demonstrate how Couchbase is the engagement database platform that you need.

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

And please reach out to me with questions on all things .NET and Couchbase by leaving a comment below or finding me on Twitter @mgroves.

Ted Neward is using the actor model with Akka.

Show Notes:

Ted Neward 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