Visual Studio 2019, .NET Core 3.0, and C# 8.0

This week it has been really fun being a .NET developer. Previews of Visual Studio 2019 and .NET Core 3.0 has been made available to the community, making it possible to try out the new upcoming features.

I will not just repeat information that you can find on other sites, instead I will provide some good links, some tips on how to set up VS 2019 in order to test .NET Core 3 and C# 8, and some personal reflections.

Visual Studio 2019 Preview

You can find a summary on all the new features in Visual Studio 2019 in the official release notes and download it from the official site.

One feature that I find really interesting that I didn’t know about before testing the 2019 preview is Visual Studio Live Share which comes enabled by default in the preview. I had the opportunity to try it out with one of my colleagues running a test TDD session where he wrote the tests and I wrote the implementation. It was a lot of fun! Live share is also available for Visual Studio Code, so you are not limited to .NET development or even Windows.

I was also able to install extensions, such as VsVim, without any issues. So hopefully your favorite extensions in Visual Studio 2017 works in 2019 as well.

So far I haven’t had any major issues with the preview, I had one crash where it stopped responding and automatically restarted after a short while, but nothing else. I will however keep testing it and try out more complex use cases, such as profiling and visual editing of XAML files.

If you are interested in trying out new things I really recommend testing the preview. It can be installed alongside your current Visual Studio version without impacting it, so you will be able to continue to work as normal when you wish.

.NET Core 3.0 preview and C# 8.0

.NET Core 3.0 will support C# 8.0. The preview supports some of the new features such as Nullable References, Ranges and indicies, and Asynchronous Streams. You can read more about upcoming C# 8.0 features here.

Visual Studio 2019 Preview has support for .NET Core 3.0 but it requires some configuration. First you need to install Visual Studio 2019 and select to install the .NET Core workflow (it can be done later through the Visual Studio Installer if you forgot to add it initially). Then you need to download and install the .NET Core 3.0 Preview SDK, create a new .NET core project and configure it for .NET Core 3.0 and C# 8.0.

Also, Nullable References is not enabled by default so once you have configured your project to use .NET Core 3.0 and C# 8.0 you still have to edit your project file (.csproj) to enable it. Note that this has to be done for each new project you add to the solution.

A tip is to also configure your projects to ”Treat warnings as errors”. By doing that your code will not compile if you don’t handle possible null references properly.

New null-related errors

Conclusion

It feels like it will be a good year to be a .NET developer next year. The new Visual Studio 2019 has the potential to make a great IDE even better and .NET Core 3.0 and C# 8.0 will add new improvements that will make it easier to write cleaner and safer .NET code.



Cleaner Code with Command Query Separation

What is Command Query Separation?

The Command Query Separation (CQS) concept is a way to structure your code and methods. The idea is that a method may either be a Command or a Query but not both. It was coined by Bertram Meyer in his book ”Object Oriented Software Construction” from 1994.

What identifies a Command method?

A Command is a method that typically alters the state of the program or system, but does not return any data. One example is adding a new item to an inventory:

public class Inventory
{
  // Command to add an Item to the inventory
  public void AddItem(Item item)
  {
     ...
  }
}

A Command method may call Query methods to request information about the current state if needed.

What identifies a Query method?

A Query is a method that returns information about current state of (a part of) the system. It may in no way alter the state of the system. Hence, a Query method may not call any Command methods. One example of a Query method is requesting information about an item in an inventory:

public class Inventory
{
  public Item Find(Query q)
  {
    // Look in the inventory for an Item matching the query
    ...
    return item;
  }
}

What are the benefits of CQS?

The really valuable benefit is that it makes it really easy to see which methods that modifies the state of the system and which don’t. Those methods that don’t modify the system can be re-arranged and called whenever needed, and those that do modify the state of the system must be handled more carefully. This makes it easier to work with the code and understand what happens in the system for different scenarios.

One of the worst practices I have seen is when the get section of a property modifies the state of the system:

// Never ever write code like this!
private int _x;
public int X { get => ++_x; set => _x = value; }

When would you not use CQS?

There are some scenarios when CQS doesn’t really fit. Martin Fowler mentions the Pop method on a Stack as an example. Pop usually removes the top element of the stack and returns it, hence both modifying the state and returning a value. Most of the time it is however a good idea to apply CQS.

In the Wikipedia article on CQS it is stated that CQS can make it harder to implement multi-threaded software. As an example it shows a method that increments and returns a value:

private readonly object _lock = new object();
private int _x;
public int IncrementAndGetValue()
{
  lock (_lock)
  {
    _x++;
    return _x;
  }
}

which, when adhering to CQS would need to be separated into two different methods, one to increment x and one for returning it’s value:

private int _x;

public void Increment()
{
  _x++;
}

public int GetValue()
{
  return _x;
}

With this, the locking has to be done everywhere Increment and GetValue is called instead of locally in IncrementAndGetValue. However, I do not see this as a real issue since it is often better avoid locks in low level methods in order to avoid the overhead in all cases where locking isn’t needed.

My suggestion is that you try to use CQS as often as possible. But when cases presents itself where breaking CQS is the most intuitive, like Pop on a Stack, or when enforcing CQS clearly makes the code more complex, it is okay to break the rule.

C# 8 and The Future of Null

The nullable types

If you have been coding C# for a while you have probably come across Nullable types (Microsoft link). A Nullable type is in instance of System.Nullable<T> where T can be any non-nullable value type (such as int, float, bool). An instance of System.Nullable<T> can represent any value of the underlying type T and also null. When declaring Nullable types the ’?’ shorthand is usually used. For example:

int? a = null; // a is an instance of System.Nullable<int>

Naturally this does not apply to Reference Types (instances of classes) since they can always be null, without wrapping them in a System.Nullable. However, in C# 8, the upcoming major version of C#, this is about to change.

Nullable Reference Types

The header above might sound strange, aren’t all reference types nullable? The answer is, yes, they are. However, starting from C# 8, references that are welcome to be null should be clearly marked as such. The way to mark a reference as nullable will be to use the ’?’ shorthand, these new reference types are what will be called Nullable Reference Types. An example:

// NOTE: This code is only valid from C# 8
public string? FindJohnMayReturnNull()
{
  IEnumerable<string> names = GetNames();
  return names.Where(name => name.StartsWith("John").FirstOrDefault(); // Returns null if there is no match
}

public string FindJohnShouldNotReturnNull
{
  IEnumerable<string> names = GetNames();
  return names.Where(name => name.StartsWith("John").FirstOrDefault() ?? string.Empty; // Returns empty string if there is no match
}

Note that I use the word should. It will be possible to compile your code even without using ’?’ to indicate nullable references, but it will give you a warning.

Conclusion

The introduction of Nullable Reference Types will most certainly make parts of the code better by making developers clearly express their intent (should this reference be nullable or not), and it will hopefully increase awareness for when you need to handle possible null values.

I would love to see code where we can avoid situations like this:

public class MyClass
{
  MyClass(ObjectOne o1, ObjectTwo o2, ObjectThree o3)
  {
    if (o1 == null) throw new ArgumentNullException(nameof(o1));
    if (o2 == null) throw new ArgumentNullException(nameof(o2));
    if (o3 == null) throw new ArgumentNullException(nameof(o3)); 
    ...
  }

  public void DoSomething(Param1 p1, Param2 p2)
  {
    if (p1 == null) throw new ArgumentNullException(nameof(p1));
    if (p2 == null) throw new ArgumentNullException(nameof(p2));

    var values = p1.GetValues();
    if (values == null) throw new ArgumentException(...);
  }
}

However, I don’t think the introduction of Nullable Reference Types will completely remove the need for null checks for all references that aren’t declared as nullable. There will most likely be cases where this is still needed, but hopefully we can reduce it, and over time the code will hopefully be both easier to read and more robust.

For more information see this article from Microsoft on the topic.

A functional alternative to returning null

Last week I wrote about alternatives to returning null. There was however one alternative that I left out, the Maybe functor.

The reason I left it out last week was that I hadn’t had the time to read up on it properly. Now that I do have read up on it, and had some time to implement it and play around with it a bit, it is time to write a bit about it.

The Maybe functor, or Maybe monad, is a concept that is used in many functional languages such as Haskell, Scala, and F# (although it is called option in F#), and also in Rust (see docs).

In C# there is no support for the Maybe functor in the language itself, you have to implement it yourself. What you want to create is a generic class, Maybe<T>, that may, or may not, have an Item of type T associated to it. A method that maybe returns an int can look like this:

public Maybe<int> Parse(string s)
{
  if (int.TryParse(s, out var i))
    return new Maybe<int>(i);

  return new Maybe<int>();
}

As can be seen above the method signature makes it very clear that the parsing might fail, this makes it really hard for the caller to forget to cover the error case:

var parsed = Parse("42");
if (parsed.HasItem)
  Console.WriteLine($"The value was successfully parsed as {parsed.Item}");
else
  Console.WriteLine("Parsing failed");

Personally I like this alternative, but I am unsure how well it will fly with other C# developers.

If you like to read more about it, and see how it can be implemented, I strongly recommend you to visit Mark Seeman’s excellent blog. He writes about the Maybe functor in http://blog.ploeh.dk/2018/03/26/the-maybe-functor/

C# alternatives to returning null

What is problematic with returning null?

A common pattern, both in the code I am used to work with, and in parts of the .NET Framework, is to return null in methods if for some reason a valid return value is not available.

One example of this is the Find method of List<T>:

var persons = new List<Person>();
var bandit = persons.Find(p => p.Name == "Billy the Kid"); // Returns default(Person) which is Null (assuming Person is a reference type)
if (bandit == null)
{
  ...
}
else
{
  ...
}

So, why would you consider handling this, and similar cases, differently?

My first argument is, returning null makes code hard to use. Let me show you by example.

Assume that you write code that will call the following public method:

public Person GetPersonByName(string name)
{
  ...
}

Is there any way for the user to tell, by looking at the method signature, whether he needs to guard for the return value being null or not? No there is not. He will have to check the documentation, or the code (if available). Would it not be better if he could tell directly? You could achieve that by naming the method GetPersonByNameOrNullIfNotFound but that is not very desirable.

My second argument is, returning null forces the caller to pollute his code with multiple checks and if/else forks:

var dude = persons.GetPersonByName("Jesse");
if (dude == null)
{
  log.Error("Could not find Jesse");
}
else
{
  var car = cars.FindByOwner(dude);
  if (car == null)
  {
    log.Error("Dude, Where's My Car?");
  }
  else
  {
    ...
  }
}

This makes the code much harder to read.

So what alternatives are there?

Alternative 1: The null object pattern

The Null Object Pattern (wikipedia link) says that instead of returning null you should return a valid object, but with empty methods and fields. That is, an instance of the class that just doesn’t do anything. For example:

public Person GetPersonByName(string name)
{
  var id = _db.Find(name);
  if (id == 0)
  {
    return Person.Nobody;
  }
  return Person(id);
}

Here the Person class implements a static property, Nobody, that returns the null object version of Person.

Advantages

There are a couple of advantages of using this pattern over returning null.

  • Users do not need to add null checks in the calling code, making it simpler.
  • The risk of NullReferenceException being thrown is eliminated.

Disadvantages

All alternative ways have some disadvantages, using the null object pattern may:

  • Hide errors/bugs, since the program might appear to be running as expected
  • Force the introduction of just a different type of error checking

The last point here is interesting. If you, when implementing this pattern, realize that need to check the returned value anyway. Then this pattern is not suitable for your situation and you should consider a different solution.

Alternative 2: Fail fast

If you analyze your code and come to the conclusion that the case where null is returned is an exceptional case and really indicates an error condition, you can choose to throw an exception instead of returning null. One example of this is the File class in the .NET framework. Calling File.Open with an invalid path throws an exception (different exceptions depending on the type of error, for example FileNotFoundException if the file does not exist). A system that fails directly when an error condition is detected is called a Fail-fast system (wikipedia link).

I have worked in a large project where this philosophy was applied. Actually we didn’t throw exceptions, we directly halted the entire system, dumped all memory, stack and logs and reported the error. The result was that once the system went live it was really robust (having multiple levels of testing, some that ran for days or weeks simulating real load, also helped a lot).

Advantages

  • Makes errors visible
  • Forces you to fix any errors early, leading to a more robust system once in production
  • Reduces cost of fixing failures and bugs since it is cheaper to fix them early in the development process

Disadvantages

Failing fast might not be suitable in all situations. Assume for example that you are dependent on data from an external system, or user. If that system provides invalid data you do not want your system to fail. However, in situations where you are in control I recommend failing fast.

Alternative 3: Tester-Doer pattern

If you are depending on external systems and need to consider cases like your system being provided with corrupt data, shaky networks, missing files, database servers being overloaded, etc, throwing exceptions and halting the system won’t work for you. You could still throw exceptions and let the user add a try-catch clause to handle the exceptions, but if some scenarios are really error prone, throwing exceptions a lot, it might impact performance to the extend it is unacceptable (microsoft link). One way to approach this situation is to split the operation in two parts, one that checks if the resource is available and a second that gets the data. For example if you want to read a file but don’t know in advance that it is available you can do this:

if (File.Exists(path)) // Test if file exist
{
  var content = File.ReadAllText(path); // And if it does, read it
}

This idea can be expanded to test a lot of different preconditions and if they are fulfilled, do the operations.

Advantages

  • Allows you to verify that the operation will probably succeed
  • Removes the overhead of exception handling (exceptions are really bad for performance)
  • The calling code can be made quite clear

Disadvantages

  • Even though the test passes, the accessing method might fail. For example, in a multi threaded system the resource may have been deleted by another thread between the test and the accessing method.
  • Requires the caller to remember to do both calls and not just call the accessing method.

Alternative 4: Try-Parse pattern

A different version of the Tester-Doer Pattern is the Try-Parse pattern. One example where this is used in the .NET framework is the int.TryParse  method that tries to parse a string to an integer. It returns a boolean value that indicates whether the parsing succeeded or failed. The actual integer value is supplied by an out-parameter in the method call:

if (int.TryParse(aString, out var i))
{
  Console.WriteLine($"The value is {i}");
}

Advantages

  • Same as tester-doer, with the addition that you only need one call, hence the thread safety issue is taken care of.

Disadvantages

  • Obscure method signature where the return value is not the data you requested, instead an out variable is needed.

Summary

This post have hopefully provided you with some alternatives to returning null and some ideas on why and when it can be good to do so. As always, most important is that you try to make the code as clear and simple as possible. Now, code!

How to debug a Blazor project

Why is debugging Blazor applications different from Angular or React?

When you run a JavaScript framework, like Angular or React, the JavaScript code is available on the client-side. This makes it possible to use the built-in developer tools in the browser to inspect and step through the code. When running Blazor applications you execute a .NET runtime that runs your compiled C# code, a totally different story.

The first thing to realize is that you will not be able to use the regular developer tools, since they only support JavaScript at this time. A second ”aha” moment comes when you realize that you need to have your application compiled in debug mode in order to have debugging symbols available.

But if the built in developer tools does not support Blazor, what to use?

Current support

At this time there is only very early support for debugging client-side Blazor applications. And the only browser where debugging is supported is in Chrome.

The reason only Chrome is supported at this time is because Blazor provides a debugging proxy that implements the Chrome DevTools Protocol. This allows the DevTools in Chrome to talk to the proxy, which in turn connects to your running Blazor application. In order for the proxy to be able to connect to the running application, remote debugging must be enabled in Chrome. It’s a bit cumbersome, but I will go through the steps required in detail below.

Hopefully the Blazor team will focus on improving the debugging support since it is a very important ingredient if Blazor is to be popular among developers.

Debugging – step-by-step guide

Follow these steps and you will have a debugging session up and running in no time. I will assume you have Chrome installed and a working Blazor application that you wish to debug.

  1. Open up the application in Visual Studio (I was unable to start the debugging session when started on the command line)
  2. Ensure that Visual Studio is set up for building the application in Debug mode and the target browser is set to Chrome (see image below)
  3. Press F5 to start the application and it should open up Chrome and load it
  4. Press Shift+Alt+D (I use Dvorak keyboard layout where the QWERTY layout D is mapped to the letter E, so I had to press Shift+Alt+E)
  5. Chrome will open a new tab, showing an error message that it wasn’t started with remote debugging enabled
  6. Follow the instructions in the error message (close Chrome, then restart it using Win+R and paste a command similar to ”%programfiles(x86)%\Google\Chrome\Application\chrome.exe” –remote-debugging-port=9222 http://localhost:54308/)
  7. In the new Chrome window, press Shift+Alt+D again
  8. A new tab should open in Chrome showing the remote debug utils
  9. You should be able to find a heading named ”Sources” (see image below) where you find the Blazor DLL and under that the source files
  10. Add breakpoints and switch back to the other tab to interact with the application. Once a breakpoint is hit Chrome will display a message saying that the application is paused since it is stopped at a breakpoint

Figure 1. Visual Studio set up for debugging the Blazor application

Figure 2. Debugging the Blazor application in Chrome

Limitations

Remember that I wrote that debugging support is still in a very early stage. This means that there are a lot of things that are not supported in the debugger yet. Limitations include, but may not be limited to:

  • No support for stepping into child methods
  • Values of locals of other types than int, string, and bool cannot be inspected
  • Values of class properties and fields cannot be inspected
  • It is not possible to see values of variables by hoovering over them
  • Expressions cannot be evaluated in the console

Ending words

As you understand by now there is still a lot of work to do in order to get full debugging support with Blazor, but the fact that there are some debugging support in place is promising. It is a bit cumbersome to start a debug session, but it is not hard. I have worked in really large projects with custom build tools without a working debugger and it is not a good spot to be in. However, with Blazor I have good hopes that the development team understands the importance of a good debugger.

How to consume a REST API using Blazor

The RESTful service

A couple of blog posts ago I wrote about how to design a REST API with ASP.NET Core and now I intend to show how to create a front end that can interface this service in order to create and remove products from the repository.

To recap, the RESTful service was designed to manage a repository containing Products where a Product is defined like this:

public class Product
{
  public long Id { get; set; }
  public string Name { get; set; }
  public string Description { get; set; }
}

And the API to manage the Products looks like this:

URI Operation Description
/products GET Lists all the products
/products/{id} GET Returns information about a specific product
/products POST Creates a new product
/products/{id} PUT Replaces an existing product
/products/{id} DELETE Deletes a product

I will create an application, using Blazor, that can be used to list all products, create a new product, and delete an existing product.

Creating the Blazor application

Start by creating a new Blazor application. If you’ve never done this before there are some components that you need to install, follow the instruction on https://blazor.net/docs/get-started.html for details on how to do this.

Once you have all dependencies in place run the following command:

dotnet new blazor -o ProductsManager

which will create a new Blazor project named ProductsManager.

You can test that it works by changing directory to the new ProductsManager directory and running the application:

cd ProductsManager

dotnet run

You should now be able to open your web browser and see you Blazor application in action.

 

Notice the Fetch data link. Clicking this loads the FetchData component which we now will modify to fetch data via our REST API.

Fetching our Data

Open the ProductsManager project file in Visual Studio. A solution will be created automatically for you.

In the Pages folder you will find the FetchData component. If you open the source file (FetchData.cshtml) and scroll to the bottom you will find a call to HttpClient.GetJsonAsync that currently just reads a sample file located in wwwroot/sample-data.

The first thing we do is to replace the weather.json file with products.json in the wwwroot/sample-date/ and enter some sample data. Rename the weather.json file to products.json and replace the content with the following:

[
  {
    "Id": 1,
    "Name": "Unsteady chair",
    "Description":  "Chess player's secret weapon"
  },
  {
    "Id": 2,
    "Name": "Weather controller",
    "Description": "Control the weather with a simple click of a button. Requires two AA batteries (not included)"
  }
]

Now you will also need to update the FetchData component. Change the WeatherForecast class to look like the Product class above and update all related code to match these changes. The updated file is listed below:

@page "/fetchdata"
@inject HttpClient Http

<h1>Products listing</h1>

@if (products == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Description</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var product in products)
            {
                <tr>
                    <td>@product.Id</td>
                    <td>@product.Name</td>
                    <td>@product.Description</td>
                </tr>
            }
        </tbody>
    </table>
}

@functions {
    Product[] products;

    protected override async Task OnInitAsync()
    {
        products = await Http.GetJsonAsync<Product[]>("sample-data/products.json");
    }

    class Product
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }
}

Now, if everything works as expected you should be able to see the product listing from the sample file instead of the Weather Forecast when you click the Fetch Data link in your browser.

To get the data from an external web service via a REST API you simply need to change the ”sample-data/products.json” string to the URL of the web service. In my test I ran the server on localhost on port 44359. So when testing I added a const string:

private const string APIServer = "https://localhost:44359/api/products";

and then just changed the OnInitAsync method to look like this:

protected override async Task OnInitAsync()
{
  products = await Http.GetJsonAsync<Product[]>(APIServer);
}

Important: If you get access denied errors you need to ensure that you have set up Cross-Origin Resource Sharing (CORS) correctly in the RESTful service. You can read about how to do that here: https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.1

Once you have that working it should be quite straight forward how to extend the FetchData component to be able to add and remove products by using the REST API. Below I have a code listing of my working component:

@page "/fetchdata"
@inject HttpClient Http

<h1>Interfacing the Products API</h1>

@if (products == null)
{
  <em>Loading...</em>
}
else
{
  <table class="table">      
  <thead>          
  <tr>
    <th>Id</th> 
    <th>Name</th>            
    <th>Description</th>            
    <th></th>
  </tr>
  </thead>      
  <tbody>
  @foreach (var product in products)
  {              
    <tr>
      <td>@product.Id</td>
      <td>@product.Name</td>              
      <td>@product.Description</td>
      <td><input type="button" value="Delete" onclick="@(async () => await Delete(product.Id))" /></td>
    </tr>
  }
  </tbody>
  </table>

  <h2>Add a new product</h2>
  <form>
  <table>
  <tr>
    <td><label>Name</label></td>              
    <td><input type="text" bind="@Name" /></td>
  </tr>
  <tr>
    <td><label>Description</label></td>
    <td><input type="text" bind="@Description" /></td>
  </tr>
  <tr>
    <td></td>              
    <td><input type="button" value="Add" onclick="@(async () => await Add())" /></td>
  </tr>
  </table>
  </form>
}

@functions {
    private const string APIServer = "https://localhost:44359/api/products";

    private Product[] products;

    private string Name { get; set; } = "";
    private string Description { get; set; } = "";

    protected override async Task OnInitAsync()
    {
        products = await Http.GetJsonAsync<Product[]>(APIServer);
    }

    private async Task Add()
    {
        var newProduct = new Product { Name = Name, Description = Description };
        Name = string.Empty;
        Description = string.Empty;
        await Http.SendJsonAsync(HttpMethod.Post, APIServer, newProduct);
        products = await Http.GetJsonAsync<Product[]>(APIServer);
    }

    private async Task Delete(long productId)
    {
        await Http.DeleteAsync(APIServer + "/" + productId);
        products = await Http.GetJsonAsync<Product[]>(APIServer);
    }

    private class Product
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }
}

I hope you found this at least a bit helpful. If anything is unclear just add a comment. And If you want me to publish the code on GitHub just let me know and I will do that as well.

C# In-Memory File System

Unit testing code that reads or writes to the filesystem can be difficult. One thing that can help is an in-memory file system that lets you emulate the actual file system just for testing purposes.

This morning I stumbled across a blog post by Jason Roberts, a five time Microsoft MVP, freelance developer, writer, and Pluralsight course author, where he describes how to use System.IO.Abstractions and System.IO.Abstractions.TestingHelpers (available through Nuget) to set up an in-memory file system that you can use when you want to unit test your file system dependent classes.

Check out his blog at http://dontcodetired.com/blog/post/Unit-Testing-C-File-Access-Code-with-SystemIOAbstractions

Blazor – first impressions

What is Blazor?

To quote the official Blazor homepage

”Blazor is a single-page web app framework built on .NET that runs in the browser with WebAssembly.”

The natural follow-up question is then ”What is WebAssembly?”. From the official WebAssembly homepage we can read that

”WebAssembly (abbreviated Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable target for compilation of high-level languages like C/C++/Rust, enabling deployment on the web for client and server applications.”

That is a very technical description, most likely formulated by a software engineer. I will make an attempt to describe Blazor and WebAssembly in my own words.

Blazor is a framework for building applications for the web, similar to AngularJS and React. However, Blazor makes it possible to write your applications in a .NET language, such as C#, instead of JavaScript. Since the JavaScript engines in the browsers are limited to executing JavaScript another solution is required for running compiled programs in binary format. This new format is called WebAssembly, Wasm, and is supported by Chrome, Edge, Firefox, and Safari.

Part of the Blazor project is to create a .NET Runtime in the Wasm format that runs in the browser and executes .NET bytecode.

Why Blazor over AngularJS or React?

Currently Blazor is still experimental so you should not use it in live products, yet. However, when it reaches a more stable state it should make a pretty awesome alternative to the JavaScript based frameworks. If you already write your Middleware and Backend code using .NET or .NET Core than it should be appealing to be able to use C# for the front-end as well, being able to go full stack using C#.

Another big thing is that compiled binary code in WebAssembly executes up to 5-10 times faster than JavaScript. In a time where JavaScript performance is becoming a bottleneck for web applications this is major deal.

Then there are a bunch of other things that makes it appealing to run .NET in the browser, like great development tools, well known APIs and stable build tools.

How is it to develop with Blazor right now?

I set up Blazor and went through a couple of tutorials and I must say that it feels really stable and performant already, even though it is still at an experimental stage. Being a .NET developer spending most of my time writing code in C# it felt really nice to be able to use that instead of JavaScript. Even though JavaScript is perfectly fine and I have nothing against developing in JavaScript if the job requires it, I feel a lot more comfortable with C# so it’s nice to be able to write both the backend code and the frontend code using C#.

When you create your web application with Blazor you create components which are HTML and C# code that you can either choose to display separately or as part of other components. The concept is easy to grasp and if you are comfortable working with HTML and C# you should be able to understand what’s going on in the code right away.

If you are a C# developer interested in web development I highly recommend that you give Blazor a try. My guess is that it will become one of the major web frameworks for creating Single Page Applications (SPA).

How can I get started?

Visit the official Blazor web site at https://blazor.net where you will find instructions on how to get started as well as a tutorial that will guide you through the basic concepts.

You may also want to visit the official WebAssembly homepage at https://webassembly.org to learn more about Wasm.

How to design a REST API with C# in ASP.NET Core 2

What is REST?

REST is short for Representational State Transfer,  and is way to design web services. So called RESTful web services.

Usually the RESTful service is accessible via a URI and HTTP operations such as  GET, POST, PUT, and DELETE are used to get or modify the data that is often stored in a database behind the web service.

Data being retrieved or sent to the web service is often formatted as JavaScript Object Notation, JSON.

Defining the API

Let’s assume we have a database containing Products that we wish to be able to Create, Read, Update, and Delete (CRUD) using the API. The service that handles the requests will be accessed using HTTP operations as listed below:

URI Operation Description
/products GET Lists all the products
/products/{id} GET Returns information about a specific product
/products POST Creates a new product
/products/{id} PUT Replaces an existing product
/products/{id} DELETE Deletes a product

Note that it does not matter whether the client that will be using the API is a mobile app, a desktop app, a web app, or something else.

Creating the RESTful Service

I am using Visual Studio 2017, Version 15.8.5 and .NET Core 2.1. If you use different versions, things may work a little different.

Start by selecting File -> New -> Project and in the ”New Project” dialog box choose Visual C# -> Web -> ASP.NET Core Web Application. Name the project ”ProductsAPI” and click OK.

 

In the next dialog that pops up, select ’API’ and click OK.

When you use this template, code will be generated that sets up some basic configuration and adds a dummy controller so that you can build and run the application. If you press ’Ctrl + F5’ the application should start and open up a new browser tab displaying ”value1” and ”value2” formatted as JSON.

Implementing the API

Creating a Product model

Let’s start by adding a Product model. Looking at the API definition above we can see that we want the Product to have an Id. It should also have a Name and a Description, so let’s add that as well:

public class Product
{
  public long Id { get; set; }
  public string Name { get; set; }
  public string Description { get; set; }
}

I created a Models folder on project level and added the Product class there.

Creating a ProductContext and a DbSet

Since we are using ASP.NET I want to take advantage of Entity Framework when working with the database. Entity Framework is an Object-Relational Mapper (O/RM) which let’s you work with domain specific objects and don’t have to worry so much about how to interface with the database. The Entity Framework types that we will be using are the DbContext and the DbSet. The DbContext represents the connection to the database and one or more tables. The tables are represented by DbSets.

Confusing? Let’s look at some code:

public class ProductContext : DbContext
{
  public DbSet<Product> Products { get; set; }

  public ProductContext(DbContextOptions<ProductContext> options) : base(options)
  {
  }
}

The code above informs us that we expect to have a database containing a table of Products. The constructor argument is of type DbContextOptions and will contain configuration options for the database connection.

Registering the ProductContext with the Dependency Injection container

In order to make it easy to be able to query and update the database I will register the ProductContext with the Dependency Injection container which is a built in component of ASP.NET Core. Doing that will make it possible to automatically instantiate objects that takes a ProductContext as a constructor parameter. I will use that later on when designing the ProductsController.

When the project was generated from the API template one of the files that were automatically added and populated was the Startup.cs. This class contains a couple of methods that gets called by the runtime during application startup. We will register the ProductContext in the ConfigureServices method by adding this line of code:

services.AddDbContext<ProductContext>(options => options.UseInMemoryDatabase("ProductList"));

This single line registers the ProductContext as a service in the Dependency Injection service collection and specifies an in memory database, named ProductList to be injected into the service container. Not bad for a single line of code, don’t you think?

Creating a controller to handle the HTTP requests

So far we have only created scaffolding, but no implementation to actually handle any HTTP requests. Now it’s time to change that.

Looking back at the API definition we expect that a user should be able to list all the products in the database by a GET request using the URI /products. The most straightforward way to accomplish this is to add a ProductsController, that takes a ProductContext in it’s constructor, and then add a Get action that returns the list of products.

There should be a folder in the projects that is named Controllers. Add a new API Controller to it and name it ProductsController. The code should look like this:

[Route("api/[controller]"]
[ApiController]
public class ProductsController : ControllerBase
{
  private readonly ProductContext _context;
  public ProductsController(ProductContext context)
  {
    _context = context;
    if (_context.Products.Count() == 0)
    {
      _context.Add(new Product
      {
        Name = "Ford Mustang",
        Description = "Classic American car."
      });
      _context.SaveChanges();
    }
  }

  [HttpGet]
  public ActionResult<IEnumerable<Product>> GetAll()
  {
    return _context.Products.ToList();
  }
}

As you can see, I add a new Product, a Ford Mustang, in the case that the database is empty. This is just so that we can see that it works as expected.

Pressing Ctrl+F5 and browsing to http://localhost:<some_port>/api/products should now result in something similar to this:

Implementing the rest of the API is pretty similar. I will just throw the code right at you:

[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
  private readonly ProductContext _context;

  public ProductsController(ProductContext context)
  {
    _context = context;
    if (_context.Products.Count() == 0)
    {
      _context.Add(new Product
      {
        Name = "Ford Mustang",
        Description = "Classic American car."
      });
      _context.SaveChanges();
    }
  }

  [HttpGet]
  public ActionResult<IEnumerable<Product>> GetAll()
  {
    return _context.Products.ToList();
  }

  [HttpGet("{id}", Name = "GetProduct")]
  public ActionResult<Product> GetById(long id)
  {
    var p = _context.Products.Find(id);
    if (p == null)
    {
      return NotFound();
    }
    return p;
  }

  [HttpPost]
  public IActionResult Create(Product product)
  {
    _context.Products.Add(product);
    _context.SaveChanges();

    return CreatedAtRoute("GetProduct", new { id = product.Id }, product);
  }

  [HttpPut("{id}")]
  public IActionResult Update(long id, Product product)
  {
    var p = _context.Products.Find(id);
    if (p == null)
    {
      return NotFound();
    }
    p.Name = product.Name;
    p.Description = product.Description;

    _context.Products.Update(p);
    _context.SaveChanges();

    return NoContent();
  }

  [HttpDelete("{id}")]
  public IActionResult Delete(long id)
  {
    var p = _context.Products.Find(id);
    if (p == null)
    {
      return NotFound();
    }

    _context.Products.Remove(p);
    _context.SaveChanges();

    return NoContent();
  }
}

Take some time to look through the code, it should hopefully be quite straight forward to figure out how it works. If you want me to add a working example on GitHub, let me know in the comments.

I you want to test the API during development I recommend a tool like Postman. It is a good tool for sending HTTP requests and checking the responses.