The Evolution of the Switch Statement (C#8)

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):

            int value = 1;
            switch (value)
            {
                case 1:
                    Console.Write("hello ");
                    break;
                case 2:
                    Console.Write("world");
                    break;
            }

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:

            int value = 1;
            string greeting = string.Empty;
            switch (value)
            {
                case 1:
                    greeting = "hello ";
                    break;
                case 2:
                    greeting = "world";
                    break;
            }

            Console.WriteLine(greeting);

Now it looks a bit cumbersome. What if we could write it like this:

            int value = 1;
            string greeting = value switch
            {
                1 => "hello ",
                2 => "world",
                _ => string.Empty
            };

            Console.WriteLine(greeting);

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:

    interface IAnimal
    {
        void Eat();
        void Sleep();            
        string Name { get;}
    }

    class Dog : IAnimal
    {
        public string Name { get => "Fido"; }

        public void Eat()
        {
            Console.WriteLine("Dog Eats");
        }

        public void Sleep()
        {
            Console.WriteLine("Dog Sleeps");
        }
    }

    class Cat : IAnimal
    {
        public string Name { get => "Lemmy"; }

        public void Eat()
        {
            Console.WriteLine("Cat Eats");
        }

        public void Sleep()
        {
            Console.WriteLine("Cat Sleeps");
        }
    }

We can put that into a switch statement like this:

            IAnimal animal = new Cat();
            string greeting = animal switch
            {
                Dog d => $"hello dog {d.Name}",
                Cat c => $"hello cat {c.Name}",                
                _ => string.Empty
            };

            Console.WriteLine(greeting);

We can actually do better that this (obviously better is a relative term). Let’s say that we wanted to do something specific for our particular cat:

            IAnimal animal = new Cat();
            string greeting = animal switch
            {
                Dog d => $"hello dog {d.Name}",
                Cat c when c.Name == "Lemmy" => $"Hello motorcat!",
                Cat c => $"hello cat {c.Name}",                
                _ => string.Empty
            };

            Console.WriteLine(greeting);

It’s a bit of a silly and contrived example, but it does illustrate the point; further, if you switch the case statements around for the general and specific form of Cat, you’ll get a compile error!

A C# Developer’s Guide to: ReactJS – Part 2 – Moving Controls

Following on from my previous post, I’m going to extend our ReactJS application by adding some boxes, and allowing the user to re-arrange them on the screen.

Concepts

There are two key concepts to consider when working with React, and we’ll cover one of them in this post; that is: state.

React has a special property of each component known as state. If you use that to bind any of the UI to, then React will refresh that component when the state changes.

Moving a UI Element

Okay – that sounds great, but how would we do this in practice?

Imagine that you have a HTML box drawn on the screen; you might have something like this:

<div style="height:100px; width:200px; background:#0000FF" />

We can draw a box. If you use this code, then your box will be on the top left of the screen; so we can tell it not to be by specifying the left and top; let’s try defining a CSS style:

<div style="left:10px; top:20px;height:100px; width:200px; background:#0000FF" />

With React, we can set those values to a value derived from the state; for example:

render() {
    const top = this.state.newY;
    const left = this.state.newX;

    const myStyle = {
        height: '100px',
        width: '200px', 
        top: `calc(${top}px)`,
        left: `calc(${left}px)`, 
        borderStyle: 'solid',
        borderColor: 'blue', 
        position: 'absolute',
        zIndex: 1,
        background: 'blue'
    };

    return ( 
        <div> 
            <div style={myStyle}>source</div>
        </div>
    );
}

What this means is that every time I change the state values, the values in the style will update.

To illustrate this, if we write a React application like this (only the timeout function is new):

render() {
    const top = this.state.newY;
    const left = this.state.newX;
    const myStyle = {
        height: '100px',
        width: '200px', 
        top: `calc(${top}px)`,
        left: `calc(${left}px)`, 
        borderStyle: 'solid',
        borderColor: 'blue', 
        position: 'absolute',
        zIndex: 1,
        background: 'blue'
    };

    setTimeout(() => {
        this.setState({newX: this.state.newX + 1, newY: this.state.newY + 1});
    }, 50);

    return ( 
        <div> 
            <div style={myStyle}></div>
        </div>
    );
}

We can make out box move diagonally across the screen:

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:

A C# Developer’s Guide to: ReactJS – Part 1 – Create & Run

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:

Something is already running on Port 3000

To fix this, in VS Code, open the folder:

node_modules/react-scripts/scripts/start.js

Find the following line (at the time of writing):

const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;

You can change the port 3000 to something that’s free.

Edit App.js:

class App extends Component {
  render() {
    return (
      <div className="App">
        <div>
          <p>Test</p>
        </div>
      </div>
    );
  }
}

Save and see the updated screen appear (which I think you’ll agree is much better than the default screen).

Creating a Windows Service using .Net Core 2.2

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):

The .Net Core application can target .Net Core 2.2:

Windows Compatibility

The next step is to install the Windows Compatibility NuGet package:

Install-Package Microsoft.Windows.Compatibility

Write the Service

Let’s start with the main method:

static void Main(string[] args)
{
    using (var service = new TestSevice())
    {
        ServiceBase.Run(service);
    }
}

You’ll need to Ctrl-. ServiceBase. TestService doesn’t exist yet, so let’s create that:

internal class TestSevice : ServiceBase
{
    public TestSevice()
    {
        ServiceName = "TestService";
    }

    protected override void OnStart(string[] args)
    {
        string filename = CheckFileExists();
        File.AppendAllText(filename, $"{DateTime.Now} started.{Environment.NewLine}");
    }

    protected override void OnStop()
    {
        string filename = CheckFileExists();
        File.AppendAllText(filename, $"{DateTime.Now} stopped.{Environment.NewLine}");
    }

    private static string CheckFileExists()
    {
        string filename = @"c:\tmp\MyService.txt";
        if (!File.Exists(filename))
        {
            File.Create(filename);
        }

        return filename;
    }

}

Not exactly a complicated service, I’ll grant you.

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:

C:\Users\pcmic\source\repos\ConsoleApp3\ConsoleApp3\bin\Debug\netcoreapp2.2

Now, launch a command prompt as admin, and type the following:

>sc create [service name] binpath=[full path to binary]

For example:

>sc create pcmtestservice binpath=C:\Users\pcmic\source\repos\ConsoleApp3\ConsoleApp3\bin\Debug\netcoreapp2.2\ConsoleApp3.exe

You should get the response:

[SC] CreateService SUCCESS

You can then either start the service from here:

>sc start pcmtestservice

Or locate it in the services utility and start it from there. You should now be able to start and stop the service and see it logging the events as you do so.

If you need to remove the service, use:

>sc delete pcmtestservice

References

https://stackoverflow.com/questions/7764088/net-console-application-as-windows-service

Short Walks – MakeCert is dead – long live New-SelfSignedCertificate

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:

"C:\Program
Files (x86)\Microsoft Visual
Studio\2017\Professional\Common7\Tools\vsdevcmd"

And then you could call MakeCert; for example:

makecert -r -pe
"CN=testcert" -b 12/12/2018 -e 12/12/2021 -sky signature -a sha256
-len 2048 -ss my -sr LocalMachine

However, one thing that you’ll notice now if you visit the MakeCert page is that it’s deprecated. The new way is a Powershell command; which can be used like so:

New-SelfSignedCertificate -Subject "CN=testcert" -KeySpec "Signature" -CertStoreLocation "Cert:\CurrentUser\My"

Short Walks – 406 Error While Creating a .Net Core Api

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:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvcCore();

When I tried to access the API, I got a 406 error.  The fix is very simple (and one that using AddMvc() does for you:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvcCore()
            .AddJsonFormatters();

Unity Lifetime Manager

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:

static void Main(string[] args)
{
    var container = new UnityContainer();
 
    container.RegisterType<IMyService, MyService>();
    container.RegisterType<IMyData, MyData>();
 
    container.Resolve<IMyData>().Test = "testing";
    container.Resolve<IMyService>().TestFunction();
 
    Console.ReadLine();
}

The service class might look like this:

public interface IMyService
{
    void TestFunction();
}
 
public class MyService : IMyService
{
    private readonly IMyData myData;
 
    public MyService(IMyData myData)
    {
        this.myData = myData;
    }
 
    public void TestFunction()
    {
        Console.WriteLine($"Test Data: {myData.Test}");
    }
}

And the data class:

public interface IMyData
{
    string Test { get; set; }
}
public class MyData : IMyData
{
    public string Test { get; set; }
}

If you run that, you’ll see that the output is:

Test Data: 

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:

static void Main(string[] args)
{
    var container = new UnityContainer();
 
    container.RegisterType<IMyService, MyService>(new ContainerControlledLifetimeManager());
    container.RegisterType<IMyData, MyData>(new ContainerControlledLifetimeManager());
 
    container.Resolve<IMyData>().Test = "testing";
    container.Resolve<IMyService>().TestFunction();
 
    Console.ReadLine();
}

Creating a Basic Web Site from an Asp.Net Core Empty Project

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 is generated by a line in Startup.cs:

app.Run(async (context) =>
{
    await context.Response.WriteAsync("Hello World!");
});

The target here is to get to a situation where the blank app is serving an HTML page with some attached Javascript as fast as possible. Here, I’ve got exactly three steps.

Step 1 – Create the HTML File

The application can only serve static files (HTML is considered a static file) from the wwwroot folder. The internal structure of this folder doesn’t matter, but that’s where your file must go:

The contents of this file are as follows:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <p>test</p>
</body>
</html>

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:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
            
    app.UseDefaultFiles();
    app.UseStaticFiles();                                    
}

Now it loads the Index.html. So technically it was only two steps – although we haven’t referenced any Javascript yet.

Step 3 – Adding the javascript… and let’s do something funky

Change the HTML to give the paragraph an ID and an absolute position. Also, reference the file site.js:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="site.js"></script>
</head>
<body>
    <p id="testElement" style="position:absolute">test</p>
</body>
</html>

Obviously, without adding site.js, nothing will happen (it also needs to be in wwwroot):

The Javascript code for that new file is here:

var divxPos = 0;
 
window.onload = function () {
    runCode();
};
 
function runCode() {
    var test = document.getElementById("testElement");    
    test.style.left = divxPos++ + 'px';    
 
    setTimeout(() => runCode(), 50);
};

If you run it, you’ll find the text running away with itself!

.Net Client Side Libraries

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:

Now refresh the project again and let’s see what we have:

This actually translates to a JSON file; libman.json looks like this:

{
  "version": "1.0",
  "defaultProvider": "filesystem",
  "libraries": [
    {
      "library": "node_modules\\jquery\\dist\\",
      "destination": "wwwroot/lib/dist/",
      "files": [
        "jquery.min.js"
      ]
    }
  ]
}

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).

Installing Client Side Libraries in Asp.Net Core

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.

So, use NuGet to install your package?

Nope – not on .Net Core!

So, use npm – that’s still supported?

Yep – here’s the Asp.Net Signal R client side package installed using npm:

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).

References

https://docs.microsoft.com/en-us/aspnet/core/client-side/bower?view=aspnetcore-2.1

https://blogs.msdn.microsoft.com/webdev/2018/08/22/libman-cli-released/

https://blogs.msdn.microsoft.com/webdev/2018/08/31/library-manager-release-in-15-8/