A blog about one man's journey through code… and some pictures of the Peak District

Most languages have a version of the switch statement as far as I’m aware; I must admit, I don’t remember one from Spectrum Basic, but ever since then, I don’t think I’ve come across a language that doesn’t have one. The switch statement in C was interesting. For example, the following was totally valid:

switch (value)
{
case 1:
printf("hello ");
case 2:
printf("world");
}

If you gave it a value of 1 would print “hello world”. When C# came out, they insisted on using breaks at the end of case statements, or having no code (admittedly there were a few bugs in C caused by accidentally leaving break statements out):

Anyway, fast forward around 17 years to C# 7.x, and it basically has the same switch statement; in fact, as far as I’m aware, you could write this switch statement in C# 1.1 and it would compile fine. There’s nothing wrong with it, so I imagine MS were thinking why fix it if it’s not broken.

There are limitations, however; for example, what if I want to return the string, like this:

From C# 8, you can do just that. The switch statement will return its value. The case syntax is disposed of, and there’s no need for a break statement (which, to be fair, can encourage people to write large swathes of code inside the switch statement – if you don’t believe me then have a look in the Asp.Net Core source!).

And that’s not all. Pattern matching has also been brought in; for example, take the following simple class structure:

Screenshot included because you couldn’t possibly imaging what a blue rectangle looks like.

Start the app using VS Code

A quick note on VS Code. If you select Terminal -> New from the menu, you can run the React application directly from the IDE; and the best part is that if there’s something already running on the port, VS Code will just give you a new one:

I thought it might be time for another of my patented “C# Developer’s Guide to…”. Basically, a guide to React for someone that understands programming (C# ideally), but doesn’t know anything about ReactJs.

There are a couple of VS templates for React; however, after working with it for a while, you realise that most of the React people live in the command line; there’s a tool called create-react-app:

You can use Powershell or Bash as your command line of choice. Start by installing the tool:

npm i -g create-react-app

This assumes that you have installed npm.

Create

To create a new application, navigate to the directory that you wish to create the application in and type:

create-react-app [app-name]

For example:

create-react-app context-menu-test

Once created, it tells you how you can start the app:

Run

First navigate into the directory that it’s just created (otherwise you’ll get errors when you run).

npm start

Will launch the server, and navigate to the Url with the default browser:

cd context-menu-test
npm start

This runs on port 3000 by default, so if you run a couple of instances then you might get the error:

Up until very recently, creating a Windows Service was the domain of the .Net Framework. However, since the release of the Windows Compatibility Pack that has all changed. In this article, we’ll create a .Net Core Windows Service from scratch.

I’m using the preview version of Visual Studio 2019 for this post. As far as I’m aware, there is absolutely no functional difference between this and VS2017; however, the initial New Project screen does look a little different.

Create the Project

There are no “New Windows Service (.Net Core)” options in Visual Studio, so we’re just going to create a console application (everything is a console application in .Net Core):

Installing

For Framework apps, you could use InstallUtil, but if you try that on a Core app, you get an annoyingly vague error! Instead, you need to find the place where the binary has been compiled; for example:

If you wanted to produce a self-signed certificate, the way to do this used to be makecert. It was part of the Windows SDK. Since Microsoft removed the Visual Studio Command Prompt (not sure why), you would run it like so:

I’m afraid this is another of those: “What has AddMvc()” ever done for us posts. Today, I was creating a brand new .Net Core 2.1 Api and, instead of calling AddMvc in ConfigureServices, I instead used AddMvcCore:

If you’ve ever used an IoC container, you’ll know that one of their benefits and burdens is that they abstract away from you the hassle of managing your dependencies. Just declare your interfaces as constructor parameters and then register those dependencies at startup, and the IoC container will propogate your class. Your registration may look like this:

container.RegisterType<IMyService, MyService>();

But what about when your class has state? For example, what if I have this sort of thing:

container.RegisterType<IMyData, MyData>();

Here we’re using unity, but it appears that the default behaviour for most IoC containers is transient – that is, they are created each time they are resolved. This is important, not just because you will lose data that you thought you had (in fact that’s one of the better scenarios – because it’s obvious that it’s not behaving how you expect), but because if you’re caching results of queries and so forth, you might find your application is going back for data that you thought it already had. Here’s an example, using Unity, that proves this:

Different IoC containers have slightly different life times – in fact, in the .Net Core IoC, you have to now explicitly register as Singleton, Transient or Scoped. In Unity, you can do something like this:

I recently wanted to do a very quick proof of concept, regarding the use of setInterval versus setTimeout after reading that setTimeout was referable if you were calling the same function very rapidly. I thought I’d note down my journey from File -> New Project to having the POC running so that next time, I don’t have to re-lookup the various parts.

File -> New Project

If you create a brand new Asp.Net Core 2.1 project, select empty project, and then run the generated code, you’ll see this:

This won’t actually do anything yet, because by default, Asp.Net Core does not serve static files, nor does it know the enormous significance of naming something “Index”.

Step 2 – Configure Asp.Net

Startup.cs is where all the magic happens; this is what it looks like out of the box:

public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}

The `context.Response.WriteAsync` goes, and instead we tell Asp.Net Core to serve static files, and the call to `UseDefaultFiles` means that it will search for Index or Default files. It’s also worth pointing out that the order of these matters:

In this post, I introduced (to me) a new method of installing client side Javascript libraries for a .Net Web Application.

In this follow-up, I’m going to cover how this can be used in conjunction with npm in order to simply move the files into the correct location. Note that this is a new tool in Visual Studio, and you’ll need VS 15.8.0 or higher for it to work. Let’s start by creating an empty .Net Core Web App. Once you’ve done so, you’re app probably looks like this:

Now you’ll need to launch a bash or powershell console:

npm init
npm install jquery

Refresh your project and show all files:

As you can see, you now have a node_modules directory. The problem is that the files need to be under wwwroot. Obviously, you could copy it, but let’s try the client side manager:

In the resultant dialog, select File System; navigate to the JQuery directory and select the files that you want:

Abusing the system

Okay – so that’s very nice; but now that we have a system that will copy files from wherever into wherever (the rule is that you have to go deeper in the files structure – so you couldn’t copy that file back again) then we, presumably, could use this for other things. For example, have you ever had a file (an image or something) that you need to include in your project:

Obviously, c:\tmp above could just as easily be \\shareddrive\images.

To be clear, I’m unsure whether this is abusing the system, or it was meant for this exact thing. It is possible that this type of usage may become unsupported in future (so you’ve been warned).

As a relative newcomer to the web front-end, one thing that always surprised me was how many moving parts you need to get something running. This is probably true elsewhere (i.e. in back-end development, and desktop development) but we just do a better job of hiding it. In the past, people writing web-pages have always has an uneasy relationship with Microsoft. Maybe it started in the late nineties when, in order to win the battle of the browsers with Netscape, Microsoft started giving its product away. Since then IE became more and more bloated, as it had to support 10 years worth of old technology, and people have had to ensure it still worked on IE 6 and 7.

But now things are different, Microsoft is a rebranded company and nobody hates them anymore… and when you create a brand new Asp.Net Core 2.1 project, you can use npm to install client side packages, use them in your web page and it all just works – end of the post.

Except that hasn’t happened. In fact, the client side package management for the web seems (to me) to be in a bit of a mess – especially where Microsoft is concerned.

Create a brand new Asp.Net Core 2.1 MVC project from the template and it comes with jquery, supplied by bower; except Microsoft aren’t continuing support for bower anymore.

Okay, so it puts it in ‘node_modules’ – I can reference the library directly from there, right?

Nope – it needs to be in wwwroot\lib.

Errr – so I copy it across manually?

You can. Although that’s kind of the problem that package managers were invented to solve.

I can create a gulp task to take the files out of the downloaded directory and place them into the lib directory!

Yes – yes, you can. Although now you have a gulp task, and an npm restore, all so that you can include one or two files in your project. This all just seems too hard!

LibMan

Introducing LibMan. It isn’t a Package Manager; but it might just be the correct answer to the question: “Why the hell is this whole thing so difficult – I only want one file!”

Here is the context menu for the in the lib folder after v15.8 (this has been available in preview for a while):

That gives you the following dialog:

This is amazing, I can pick the library that I want, and where I want it to go! I can also select specific files that I want – this almost feels like a sensible way to manage client side packages. Click install and bang:

You can see what it’s done by either selecting “Manage Client Side Packages…” from the solution context menu:

Alternatively, you can just have a look at the libman.json file (they both do the same thing as of 15.8.7, which makes me wonder whether “Manage Client Side Packages…” will do something different one day – the ellipses kind of give it away).

And There’s More…

There’s a CLI for it (which seemed to balk a bit when I tried to install it via NuGet), and you can use this as a replacement for Gulp to copy files around, by just selecting “File System” as the source (although this sort of solves that problem further down the tree).