Over a million developers have joined DZone.

.NET Core with Visual Studio Code

In this post we take a look the tooling that you can use to write .NET Core code using Visual Studio Code. Read on for more information!

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

Jeff Morris already wrote a great blog post to introduce the Couchbase .NET Core SDK, which is now in developer preview.

I’m going to show you some of the tooling that I’m using to write .NET Core on Windows: Visual Studio Code (VSC) and extensions.

Getting Started

Here’s what I’m using on Windows, but note that this shouldn’t be much different on Mac or Linux!

Once you have Visual Studio Code installed, I recommend that you install these extensions:

You can install these extension right in Visual Studio Code using the UI, or you can use Ctrl+P and then type ext install net-core-project-manager or ext install csharp. Keep Ctrl+P in your mind, because once you have the NuGet Project Manager installed, you will also use it to install NuGet packages.

Let’s Write Some Code

Use Powershell or CMD to make a project folder. Once you are there:

This will create some files: Program.cs and project.json.

Running dotnet new to create a new .NET Core project

Then, to get the dependencies listed in project.json, run another command:

You might now notice a project.lock.json file. This is generated by NuGet to figure out the dependency graph. You don’t need to commit this to your source code repository, and I’ve omitted it from the source code for my example.

Now, I’m going to open up this folder in Visual Studio Code by running:

At this point, the project is ready to execute. You can go back to Powershell/CMD if you’d like, or you can use Ctrl+` to use the Integrated Terminal within VSC. To run the program:

If you ran that now, you’d get a "Hello World". Let’s add some Couchbase to this project.Start with Ctrl+P, then type ">nuget" until "Add New Package" appears. Enter a search term, like "couchbase". "CouchbaseNetClient" should appear in the list. Select it, and then you should be able to select a version.

Using NuGet to install the Couchbase .NET Core SDK

Currently, for .NET Core, you’ll need to select 2.4.0-dp2, since .NET Core support is still a "developer preview".

Once you have this added to your project, working with the .NET Core SDK should be familiar to you if you’ve used the .NET SDK. Inside of the Main method, here’s how you connect to a cluster and setup a bucket:

// connect to a cluster, get a bucket
ClusterHelper.Initialize(new ClientConfiguration {
    Servers = new List<Uri> { new Uri("couchbase://localhost")}
});
var bucket = ClusterHelper.GetBucket("default");

Next, I’m inserting an "electric bill" document using the bucket object. Note that I’m using the Async method. According to Jeff’s blog post, the synchronous API may be going away, so I’m trying to get used to the asychonous API. I’m using Task.WaitAll, so it’s still running synchronously for the purposes of this sample console app.

// insert a document with some random values
var document = new Document<dynamic> {
    Id = Guid.NewGuid().ToString(),
    Content = new {
        invoiceNumber = Path.GetRandomFileName(),
        amountDue = new Random().Next(10,300),
        type = "electricbill"
    }
};
Task.WaitAll(bucket.InsertAsync(document)); // wait for async method to finish
Console.WriteLine("New electric bill created.");
Console.WriteLine();
// get all electric bills with N1QL and list them
var query = Couchbase.N1QL.QueryRequest.Create("SELECT b.* FROM `default` b WHERE type = $1");
query.AddPositionalParameter("electricbill");
query.ScanConsistency(ScanConsistency.RequestPlus);
var result = bucket.QueryAsync<dynamic>(query).Result;  // calling QueryAsync synchronously

Again, this is using the Async API, but since I’m calling .Result, it’s functionally synchronous. Finally, based on the results of the N1QL query, I’m either outputting error information or I’m looping through the results and writing them to console.

Console.WriteLine("Success: " + result.Success);
if(!result.Success) {
    Console.WriteLine("Message: " + result.Message);
    Console.WriteLine("Exception: " + result.Exception?.GetType().Name);
    Console.WriteLine("Exception Message: " + result?.Exception?.Message);
    result.Errors.ForEach(e => Console.WriteLine("Error: " + e?.Message));
    return;
}

Console.WriteLine();
Console.WriteLine("Bills:");
Console.WriteLine("------");
foreach(var bill in result.Rows) {
    Console.WriteLine($"{bill.invoiceNumber} - {bill.amountDue.ToString("C")}");
}

When I run this program, it will create a new document (each time) and list all the documents it’s created cumulatively.

Running .NET Core project using Couchbase

Note: if you are having trouble getting started with Couchbase Server, or you are getting errors, especially in regards to N1QL indexing, you may want to revisit some of my "Getting Started" blog posts: Couchbase with Windows Part 1 and Couchbase with Windows Part 2 in particular.

What’s Different?

For the most part, this feels very much like working with full Visual Studio and .NET. Visual Studio Code is not as full-featured, yet, but already has a great library of extensions. For Couchbase developers, working with the .NET Core SDK is practically identical.

One thing that it may take some time to get used to is the lack of ReSharper. I don’t know if ReSharper is going to come to VSC (JetBrains has their own light-weight C# IDE called Rider). I have a habit of using Alt+Enter to add using statements, and that same keyboard shortcut doesn’t work in VSC (by default). The refactoring lightbulbs still show up, and here are the namespaces for the record:

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Couchbase;
using Couchbase.Configuration.Client;
using Couchbase.N1QL;

It’s also a little strange to create a project with dotnet new instead of File→New, but that’s something I can get used to.

Summary

Even if you don’t plan on writing .NET Core code just yet, you should still check out Visual Studio Code. It’s a great text editor, if nothing else. If you are currently writing .NET with Couchbase, the Couchbase part of your transition to .NET Core should be painless (your mileage may vary getting used to the new .NET Core tooling).

The full source code for this .NET Core example using Couchbase is available on GitHub.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:
.net ,visual studio code ,tooling ,microsoft ,web dev

Published at DZone with permission of Matthew Groves, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}