Which is better for teaching? C# or F#

Recently I have had the pleasure of training a couple of colleagues in the wonders of programming. At work we use C# for most of our applications so naturally I started preparing my material in C#.

I did not get very far before it occurred to me: This is going to be a long haul…

Now, my colleagues are smart, really smart, much smarter than me, but they do not have much experience in programming. They have been using SQL, some VBA, and perhaps a bit of R, but none of them have been doing real application development and they know nothing about OO theory.

Unfortunately, you do not get very far with a language such as C# without knowing just a little bit about OO programming.

Let’s start with the compulsory and useless “Hello, world” example:

using System;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, world");
        }
    }
}

That’s a lot of code just to print out a stupid message on the screen.

“What are all those things for?” my colleague complains and I answer “We’ll get to namespaces, classes, static, void, arrays, and more stuff later”. He’s not happy and continues “Do I really need to write all those curly braces and semicolons?”. And when I tell him yes, and don’t forget that it’s all case sensitive, he breaks down and says “I miss VBA…”.

Of course curly brackets and case sensitivity has nothing to do with OO but I think we can all agree that OO is really, really hard. Heck, I don’t even master it after years of C++ and C#.

I find that it takes a long time for beginners to grasp OO and when they start to see the light they will abuse inheritance and create everything as singletons. And interfaces seem to be impossible to understand even though I do my best with lousy metafors such as cars and DVD playsers.

Usually, beginners actually tend to completely ignore that C# is object oriented and they take a straight forward approach and create a very long Main function.

So, perhaps teaching my colleagues C# is not the right approach. Perhaps I should try teaching them a functional language instead such as F#? Now, I am not saying that functional languages are easy but I do think that you can get really far with F# without knowing advanced stuff such as monads. In F# the “Hello, world” example boils down to

printfn "Hello, world"

Very simple. Not much to talk about.

Besides, there are a couple of important points to consider when bringing F# to the table:

  • My colleagues are all mathematicians and functional languages are perfect for math stuff.
  • F# is a .NET language and will work together with all the C# code in our company.
  • F# can work as a scripting language for makeshift assignments.

I am thinking that it would suffice to teach the basics of F# such as record types, functions, pattern matching, the Seq module, type providers, and perhaps partial application.

What do you think? Would F# be easier to grasp or should I go for the usual C#?

Changing Work Item Templates on Team Foundation Service

Introduction
If there is one thing that Team Foundation Service (TFS) does really well, it is the use of work items.  A work item can be a lot of different things.  For example, it can be a bug, a task, a user story, an epic, or a test case. It can even be a request for a code review.

You can define relations and dependencies between work items and you can assign work items to changesets (commits).  The possibilities seem endless.

The work items available to you are decided by the template that your admin chooses for you when she creates a so-called team project.

image

At work we have been using TFS since the dinosaurs walked the earth.  Back then TFS was a whole lot different than it is today which means that the templates looked a lot different.  For example, the template used for the team project we are using on my team is based on some old Microsoft Foundation framework which only allows bugs and tasks.  I does not allow us to create cool things like user stories or code review requests.

So I decided to upgrade the templates.  There is not built-in way to upgrade so you have to do it manually. I am no TFS expert but I found out that the process is: 

  1. Export the work item templates from TFS.
  2. Edit the templates if necessary.
  3. Import the templates to TFS.

Sounds easy, right?  Well, it’s not hard but it is kind of cumbersome.

Changing the work item templates is only possible on on-premise TFS. Don’t try this on Visual Studio Team Services (at visualstudio.com).

Exporting Templates

Work item templates (WITs) are defined as XML-files so first you want to export the XML-files that you want to use from TFS.  The export is done through Visual Studio and the tricky part is that you need to do it from a Visual Studio version that corresponds to your TFS version.  So, in my case we are on TFS 2015 so I need to do the export from Visual Studio 2015.

To export the WITs go to the menu Team –> Team Project Collection Settings –> Process Template Manager.  Here you need to decide which template you wish to upgrade to. If you want to upgrade to the “Agile” template, then that is the one you should download.

image

Click the “Download” button to download the XML-files.

If you chose to download the “Agile” process template, the files will be placed in a subfolder called “Agile”.  The interesting files for WITs are located under “Agile\WorkItem Tracking”.

If you take a look at the files in the folder “Agile\WorkItem Tracking\TypeDefinitions” you will see that there is an XML-file for each work item type, for example Bug, UserStory, Task, TestCase, CodePreviewRequest.  The files define the fields and states for the work items. These are the files that you need to import to our legacy team project to upgrade it to a newer process template.

For the import you need to use the witadmin.exe tool from the command prompt.  You have to use witadmin.exe for the right version of Visual Studio and TFS.  For Visual Studio 2015 and TFS 2015, witadmin.exe is located at

%programfiles(x86)%\Microsoft Visual Studio 14.0\Common7\IDE

So let’s start importing the work item templates. Unfortunately, I have been unable to find a way to batch import all the files in one shot so you have to do it one file at a time.

witadmin importwitd /collection:"http://mytfsserver/tfs/MyCollection" /p:"MyTeamProject" /f:"C:\downloadedtemplates\Agile\WorkItem Tracking\TypeDefinitions\Bug.xml"
witadmin importwitd /collection:"http://mytfsserver/tfs/MyCollection" /p:"MyTeamProject" /f:"C:\downloadedtemplates\Agile\WorkItem Tracking\TypeDefinitions\CodeReviewRequest.xml"
witadmin importwitd /collection:"http://mytfsserver/tfs/MyCollection" /p:"MyTeamProject" /f:"C:\downloadedtemplates\Agile\WorkItem Tracking\TypeDefinitions\CodeReviewResponse.xml"
...

You may encounter errors when trying to import. I ran into a number of renaming errors:

TF26177: The field Microsoft.VSTS.Common.BusinessValue cannot be renamed from '
Business Value - Microsoft Visual Studio Scrum 1_0' to 'Business Value'.

If fixed the errors by manually editing the XML-files. In the above case I searched for “Business Value” in the XML-file that failed and changed it to “Business Value – Microsoft Visual Studio Scrum 1_0”. It didn’t seem to matter anywhere in TFS after the import.

After all the WITs have been imported (without errors!) the final step is to import the categories. For example, the file categories.xml define which work items can be created directly by the user in TFS, and which work items are hidden, such as code preview requests that are created indirectly through code review requests in Visual Studio.

witadmin importcategories /collection:"http://mytfsserver/tfs/MyCollection" /p:"MyTeamProject" /f:"C:\downloadedtemplates\Agile\WorkItem Tracking\Categories.xml"

And that’s it! Now you should be able to create all the fancy Agile work items from within TFS, and you should be able to request code reviews from Visual Studio.

Building C# 7.0 on On Premise TFS

At work we are running on premise Team Foundation Service 2015 (yeah, I know, right?).

We have been struggling a bit to build C# 7.0 code on it.

We installed Visual Studio 2017 on the build machine but it seemed that no matter what we did, we were only able to choose between “Visual Studio 2015” and “Visual Studio “15” Preview” in the build step. As you may know, the latter is a preview for Visual Studio 2017 and it just did not do the job for us.

The solution is quite simple and it is a bit embarrassing that we did not find out faster.

It turns out that all you have to do is use an MSBuild step instead of af Visual Studio Build sted. Under the “Advanced” section, you put in the path for the latest msbuild.exe on your build machine.

If you put Visual Studio 2017 or even better, the Visual Studio 2017 build tools on your build machine, you should be able to find msbuild.exe in there somewhere.

msbuild
(screenshot is from https://www.visualstudio.com/ but you get the idea).

Be a responsible developer

The world is evolving around software. Software controls everything we do from toasting bread to sending people into space. Software enables people and companies. It is in fact really hard to think of a job or a task that does not include software in some way, at least in the Western hemisphere.

That puts us, the developers, in a special spot. We are the ones that make it all possible. It gives us great power and as you know, with great power comes great responsibility.

Not all software developers live up to that responsibility. The recent WannaCry ransomware attack is one such example where evil-minded software developers take advantage of laymen’s lack of knowledge when it comes to computers and software.

But we also need to be responsible developers on a smaller scale, when developing everyday software such as mobile phone apps and web sites for commercial and other purposes.

What do I mean by being a responsible developer? I mean that you need to be nice and respectful. Don’t be pushy and annoying. Don’t pretend that your app can do stuff that it cannot. Be helpful and serviceminded.

Just last week I downloaded an app to my iPhone from Apple App Store. The app was a calendar and todo-list for things you need to do around your house. On the first run it requested permission to show notifications which I allowed because – you know – it sort of makes sense to get notifications from a calendar/todo-list.

It did not take long before the app started acting up. Within an hour or two, the app popped up a notification with some kind of click-bait message, trying to lure me into opening the app.

I immediately uninstalled the app. The developer should be ashamed for being irresponsible and wasting everybodys time.

A couple of months ago my father bought a new laptop. Nothing fancy, just a laptop for checking emails and netbanking. The machine came with a bunch of unrelated, useless blotware that is only used for marketing stunts. My father is in his seventies. He has no idea what a computer does and he does not stand a chance against bloatware. Of course, I removed it all. Lenovo, I am looking at you. Start being responsible.

The list of examples goes on and on…

Some of the worst examples are social media. They will bug you and bother you in an endless stream of emails, toasts, badges and what-not until you cave in and open their app. Even after you have disabled all kinds of notifications they will email you just to make sure.

I know we are all under pressure form CEOs and CMOs that want to drive traffic to your apps and web sites but we, the developers, are the last line of defence, and we need to step up and create software that is useful and a joy to use. I believe that in the long run this will make your more money than being annoying.

Setting up ASP.NET Core in Visual Studio 2017 with npm, webpack, and TypeScript: Part II

Example code on Github.

This is the second part in my small series on ASP.NET Core and the coolest of the cool JavaScript libraries out there, except that they are probably already outdated by the time I finish writing this.

In part I we took a look on how to install npm and webpack into our ASP.NET Core project. In this part we will set up TypeScript. Visual Studio (VS) will compile TypeScript for you automatically but we will disable that feature and let webpack do the TypeScript build just for the fun of it.

Set up TypeScript
Start by installing TypeScript using npm (this is all described on in webpack’s documentation):

npm install --save-dev typescript ts-loader

Notice how package.json is updated with typescript and ts-loader. You may be wondering what ts-loader is. I know I was. It is a “TypeScript loader for webpack” which really does not say much but it is the thing that makes webpack take care of our TypeScript code.

While we are at it let’s install Knockout.js which we will use for building view models in TypeScript.

npm install --save-dev knockout @types/knockout

By using @types we tell npm to install the typings for Knockout as well. I tend to think of typings being to TypeScript what header-files are to C++. The typings go into the node_modules folder as everything else.

Next we need to create a configuration file for TypeScript. Right-click your project node in VS solution explorer and click “Add New Item”. Search for “json” in the templates dialog and choose “TypeScript JSON Configuration File”. The file must be name “tsconfig.json”. Change the contents so that it looks something like this:

{
  "compilerOptions": {
    "outDir": "./wwwroot/build/",
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "compileOnSave": true
  },
  "exclude": [
    "node_modules",
    "wwwroot"
  ]
}

Notice that I have told the TypeScript loader to put the generated .js files in the folder “wwwroot/build”, and that I have told it to resolve any 3rd party modules by using “node” (i.e. it will look in the “node_modules” folder).

Test TypeScript build
Let us test that we can build TypeScript files. By default VS will build what ever .ts files you add to the project. Start by creating af Script folder in your project next to the wwwroot folder. Add a TypeScript a file named “myviewmodel.ts” to the folder. We will create a Knockout view model class so start by importing Knockout to the .ts file by adding the following line at the top.

import * as ko from "knockout"

Note how VS IntelliSense kicks in as you type. Very cool. Above we set “modeResolution” to “node” so that the TypeScript loader knows to look in node_modules to find Knockout. Now lets add a view model with two observable fields using the Knockout TypeScript definitions. The last line applies the Knockout bindings to the view.

import * as ko from "knockout"

class MyViewModel {
    firstname: KnockoutObservable<string>;
    lastname: KnockoutObservable<string>;

    constructor(firstname: string, lastname: string) {
        this.firstname = ko.observable(firstname);
        this.lastname = ko.observable(lastname);
    }
}

ko.applyBindings(new MyViewModel("Jakob", "Christensen"));

Now if you build your project in VS, you will see a new folder underneath “wwwroot/build” with the compiled .js file.

Set up the webpack TypeScript load
Instead of letting VS do the TypeScript build we want webpack to do it and we already installed ts-loader to do it for us. Why would we want to do that now that VS can do it for us? I like to do it because I prefer to keep everything front-end-ish together. So, webpack does the build, the bundling, the code splitting, etc.

Now, add a file called webpack.config.js to your project at the project root. Paste the following into the file.

var path = require('path');

module.exports = {
    entry: {
        site: [
            './wwwroot/js/site.js', 
            './scripts/myviewmodel.ts']
    },
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'wwwroot/dist/')
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: 'ts-loader',
                exclude: /node_modules/,
            },
        ]
    },
    resolve: {
        extensions: [".tsx", ".ts", ".js"]
    }
};

This configures webpack to compile the .ts files. It also instructs webpack to take the compiled .js file and bundle it together with some other site.js file that we might have in our project and put it all into a file called bundle.js places in “wwwroot/dist”. This is the file you want to reference in your HTML files. By the way, the compiled .js files will no longer end up in the “wwwroot/build” folder so you can delete that.

Webpack build
To build and bundle, first edit your package.json so that the build block looks like this.

  "scripts": {
    "build": "webpack"
  },

Then remove the line containing “compileOnSave” from tsconfig.json.

Finally, go to the cmd prompt and run the following npm command from your project folder.

npm run build

You should now see the file bundle.js in “wwwroot/dist”.

Of course you don’t want to go to the cmd prompt every time you have changed something in your .ts files, so we want VS to run the npm build. Fortunately, the ever-present Mads Kristensen has created a VS extension that does it for you. After installing the extension you can see the npm custom build task in Visual Studio’s Task Runner Explorer. Right-click “build” to tell VS to run the build task before or after your normal VS build.

This will add a line to the package.json file.

"-vs-binding":{"BeforeBuild":["build"]}

Cleaning up
As I said above, VS automatically picks up .ts files and builds. You don’t want that when using webpack. To disable the VS build, right-click your project in Solution Explorer and choose “Edit [your project name].csproj”. Add the following line under the <PropertyGroup> element.

<PropertyGroup>
    <!-- ... -->
    <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
</PropertyGroup>

Also, you might want to remove bower.json and bundleconfig.json if present, as package.json and webpack.config.js replace them. As far as I know bundleconfig.json works with another Mads Kristensen extension to bundle .js files.

That’s it. Now it is up to you to take fully advantage of webpack for code splitting and uglifying and what not.

Setting up ASP.NET Core in Visual Studio 2017 with npm, webpack, and TypeScript: Part I

Example code on Github.

Things have been moving so fast in the last couple of years when it comes to web development.  The days of page refreshes on web sites are long gone.  The youngsters and hipsters want ajax, animations, spinners, and what not.  The JavaScript world has exploded with cool libraries and what is the newest, coolest, hottest library right now changes faster than I change my underwear (or maybe I’m just getting old, or I need to change my underwear more often).

Recently, Microsoft came out with the final release of Visual Studio 2017 (VS), and I figured now would be a good time to get my head around ASP.NET Core and all the cool JavaScript things.

The case in mind is a small intranet website that will allow the users to do some quick actuarial calculations.

Getting started
Let’s start by creating a Visual Studio ASP.NET Core project.  Start Visual Studio 2017 and create a new project from the “ASP.NET Core Web Application (.NET Framework)” template.  We will choose this template to make the code compatible with non-Core assemblies (the actuarial assemblies are compiled for .NET 4.5.2).

At the top of the dialog, choose which .NET framework you wish to be compatible with.

In the next dialog choose “Web Application”, and Visual Studio will set up a basic structure for your project.  Among other things, Visual Studio creates a folder named “wwwroot”.  This is where the files that will be published to the actual web server should be placed.  Don’t put anything else such as your code in that folder.

Setting up npm
To get all the JavaScript goodness into our project, we need to install the Node Package Manager (npm). As the name implies, npm is a package manager for JavaScript. Think Nuget for Javascript kind of thing. But npm can do more than that. It can also build TypeScript with the help of webpack which is what we will do later on.

You can install npm (Node.js) through the Visual Studio installer but you should always make sure that you are running the latest version. You can also download and install from the node.js web site.

Now we need to initialize node for our VS project directory. Open a command prompt and cd to the VS project folder (the folder where the .csproj file is located).

Run the command:

npm init -y

This will initialize npm for your project with default settings. The initialization creates a file named package.json. Notice how VS automatically recognizes the file and adds it to the web project.

You might want to open the package.json file and change the name attribute to all lower case since upper case letters are not supported (I have no idea why npm init does not change it to lower case while it is at it).

Run the following command to update npm at a later time.

npm install npm@latest

Installing webpack
Next up is webpack. Webpack seems to be the Swiss Army knife of JavaScript and it looks like people are moving from things like Grunt and Gulp to webpack. Also, in my humble opinion, the webpack documentation is far better than what you will se for a lot of the other “hot and cool” open source JavaScript libraries.

We will be using webpack for compiling TypeScript and for bundling script files.

Install webpack with npm by running the command

npm install webpack --save-dev

This will save webpack as a development (not production) dependency in package.json. We will be using webpack as part of the build process, hence the development dependency. The npm install command also creates a folder named “node_modules” in your project folder with dependencies. Do not include this folder in your project.

Next
In the next part of this series we will get up and running with TypeScript.

 

Autonomous F16 Wingman

The USAF is testing autonomous wingmen fighter jets.  While I am a sucker for all things fighter jet, especially the F16 Falcon, this is both very fascinating and very unsettling.

Photo via Lockheed Martin.

 

 

Top 5 Things, You Shouldn’t Say to a Diabetic

When you are a type 1 diabetic you have to put with a lot of “expert” advice.  Everybody seems to have an opinion on why you have diabetes and how you should treat it.  I put together a list of the top 5 annoying comments (the actual list seems endless):

Number 5:
“Diabetics can eat anything”

This is not entirely wrong. Theoretically I just have to take my insulin. But the amount of insulin is dependent on the amount of carbohydrates I eat. Everytime I eat I need to estimate the number of carbohydrates in my meal and calculate the amount of insulin I should take. This calculation depends on a lot of things like exercise, stress, inflammation, headache – you name it. If the carbohydrates reach my blood faster or slower than the insulin kicks in, or I miscalculate the amount of necessary insulin, my blood sugar can go too low (hypoglycemia – which can kill me now) or too high (hyperglycemia – which can kill me in the long run).  All in all, this is an extremely difficult task and the best advice is to eat slow carbohydrates and not too many.

Number 4:
“Have some cake. It won’t hurt you just this once.”

Maybe not, but if I eat a piece of cake every time someone says that to me, it will definitely hurt me (see number 5).

Number 3:
“This fruit/jam/candy/lemon/cola is organic, so you can eat/drink it. It’s good for you.”

While organic food may be good for you, it still contains lots of fast carbohydrates (see number 5).

Number 2:
“As long as you take your insulin, everything is fine.”

Nope, that’s not how it works. See number 5.

Number 1:
“I guess you should not have been drinking all that coke!”

It is true that I was addicted to Coke (the drink that is) for several years before I was diagnosed with diabetes but type 1 diabetes is an auto-immune disease where the immune system for some reason decides to attack and destroy the insulin-producing cells in the pancreas. This has nothing to do with how much sugar you intake. It is still unclear what causes the immune system to act this way but things such as vira, intestinal diseases, and stress are being investigated – anything that weakens your immune system. Some types of diabetes are even in your genes!.

Type 2 diabetes is a bit of different story. Research shows there is a correlation between type 2 diabetes and an unhealthy way of life.

 

Welcome – the first blog entry

Welcome to my new blog!

This is where I’ll be posting my ramblings on all things that interest med.  I hope some of it will be of use to you.

Also, check out the about page.