0 Comments

Null conditional operator allows us to write more terse code. And unfortunately, more subtle bugs. The combination of Null Conditional Operator with Any() is easily my current favourite for The Winner of 2019’s Most Bugs Caused by a New C# Feature.

Combining Null Conditional Operator ?. with System.Linq.Enumerable.Any allows us to quickly check if our collection is not null AND not empty. So instead of writing this:

        public static void DoWork(List myWorkItems)
        {
            if (myWorkItems != null && myWorkItems.Any())
            {
                Console.WriteLine("Doing work");
                return;
            }

            Console.WriteLine("Nothing to do");
        }

We can use Null Conditional Operator and save few key strokes:

        public static void DoWork(List myWorkItems)
        {
            if (myWorkItems?.Any() == true)
            {
                Console.WriteLine("Doing work");
                return;
            }

            Console.WriteLine("Nothing to do");
        }

Maybe we could make the code even better, by reducing nesting by inverting the if:

        public static void DoWork(List myWorkItems)
        {
            if (myWorkItems?.Any() == false)
            {
                Console.WriteLine("Nothing to do");
                return;
            }

            Console.WriteLine("Doing work");
        }

Ah, no. Did you spot the bug?

image

If we expand the example, we get a better picture of the situation:

image

Why this happens? Because myWorkItems?.Any() doesn’t return false when the collection is null. It returns Nullable Boolean instead:

image

Getting around the issue is quite simple: Instead of checking for == false, we check for != true:

            if (myWorkItems?.Any() != true)
            {
                Console.WriteLine("Nothing to do");
                return;
            }

But do we always remember this? Based on the code I’ve seen this year the answer is quite simply no.

Maybe there’s a Roslyn Analyzer for spotting this automatically?

0 Comments

GrazeDocs is a new open source static documentation site generator. GrazeDocs converts your Markdown files into full-blown static HTML-pages which you can host anywhere. GrazeDocs uses Razor for themes and it is available as a .NET Core Global Tool.

Project home site: https://grazedocs.io

Project repository: https://github.com/mikoskinen/GrazeDocs

Features

Here’s a list of few interesting features provided by GrazeDocs:

  • Clean and light default theme
  • Automatically generated table of contents
  • Live preview

Live previews is one of the standout features: Live Preview automatically opens a browser with your published documentation site. Every time you update the documentation, the site is automatically updated. You don’t have to manually publish your site to make sure your site looks correct. The Live Preview is done using SignalR.

Getting started

GrazeDocs aims to make it easy to get started by using conventions but it also tries to offer customization options if you aren’t happy with the defaults. For more thorough guides, please visit the documentation available at https://grazedocs.io or the samples at https://github.com/mikoskinen/GrazeDocs/tree/master/samples

GrazeDocs is available as a global tool for .NET Core. To install:

1
dotnet tool install -g GrazeDocs

To start creating your documentation, use GrazeDocs -i . to initialize documentation into the current folder:

1
GrazeDocs -i .

After your happy with the documentation, use GrazeDocs -p to publish your complete site:

1
GrazeDocs –p

Examples and more information

GrazeDocs home page is created using GrazeDocs. You can find the site’s source code from https://github.com/mikoskinen/GrazeDocs/tree/master/docs

For more information, GrazeDocs samples are good starting point as is https://GrazeDocs.io.

0 Comments

Alias engine is a new MIT-licensed open source C# & .NET Standard based engine for creating aliases for your commands. It's inspired by the alias support which mIRC provides.

Example: Alias “ae” can be used to execute command “Alias Engine”.

The project can be found from GitHub and the engine is available through Nuget https://www.nuget.org/packages/AliasEngine/.

Background

What is an alias and what you can do with them? Aliases can be used to shorten commands. If your application provides a “help” command, you can provide a shorter alias “h” for running it.

Alias Engine can also be used to provide alias feature for the end user. Your application can provide a fixed set of commands like “help”, “show”, “create” and the user of your application can create aliases for executing the commands.

Features

Alias Engine supports these features:

  • Multi-Command aliases
  • Multi-Parameter aliases
  • Multi-Word parameters

Here’s a quick example of using the engine:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var converter =new AliasConverter(new InMemoryAliasStore(),new NullLogger<AliasConverter>());
converter.AddAlias("/x multiple return words");
converter.AddAlias("/j /join {0}");
...
[Test]
[TestCase("/x", ExpectedResult ="multiple return words")]
public string CanRunAlias(string alias)
{
var result = converter.Convert(alias);
return result[0];
}
...
[Test]
[TestCase("/j hello", ExpectedResult ="/join hello")]
public string CanRunAliasWithParameters(string alias)
{
var result = _converter.Convert(alias);
return result[0];
}

For more examples, the best place is to check Alias Engine tests: https://github.com/mikoskinen/AliasEngine/blob/master/src/AliasEngine.Tests/AliasEngineTests.cs

0 Comments

I’ve released a new open source extension for Visual Studio 2017&2019 which aims to make it easier to attach and to reattach the Visual Studio debugger to the correct dotnet.exe process:

With the default “Attach to process” –feature in Visual Studio it’s often hard to know what is the correct dotnet.exe to debug. Without the extension the visibility to dotnet.exe process is often this:

The extension aims to solve this issue by parsing the actual application from the process’ command line. In addition to displaying and attaching to a particular project, the extension provides “Reattach to dotnet.exe” command. This functionality works even if the process id changes (as it does when using dotnet watch).

Default shortcuts: 

  • Reattach: CTRL + Shift + Del
  • Attach: Shift + Del

Note: For now the extension has been mainly tested with ASP.NET Core 2.0 based applications. Later versions of ASP.NET Core and .NET Core may change things so it’s possible that the extension displays these processes incorrectly.

The extension is not yetavailable from Visual Studio Marketplace but I hope to see it there shortly. But you can download and install it from here: https://github.com/mikoskinen/AttachToDotnet/tree/master/releases/1.0.0.0

The source code for the extension is available through Github: https://github.com/mikoskinen/AttachToDotnet

0 Comments

AngleSharp is a HTML parser library for .NET. Previously I’ve mainly used Html Agility Pack for parsing, but AngleSharp seems to be getting quite much traction nowadays.

I had a scenario where I wanted to use AngleSharp to wrap all the images with links. Given the following HTML:

<img src="2019-02-17-13-10-47.png" class="img-fluid" alt="Test stuff">

I wanted to transform it to this:

<a href="2019-02-17-13-10-47.png" class="lightbox">
	<img src="2019-02-17-13-10-47.png" class="img-fluid" alt="Test stuff">
</a>

Here’s how you can do this:

  1. Create the new link wrapper
  2. Get image’s original parent element
  3. Replace the image parent element’s image with the link wrapper
  4. Set image as the child of the wrapper

In C# using AngleSharp:

                var wrapperLink = document.CreateElement("a");
                wrapperLink.SetAttribute("href", image.GetAttribute("src"));
                wrapperLink.ClassName = "lightbox";

                var imageParent = image.ParentElement;
                imageParent.ReplaceChild(wrapperLink, image);
                wrapperLink.AppendChild(image);
Where document is of type IHtmlDocument and image is of type IHtmlImageElement.