The Daily Parker

Politics, Weather, Photography, and the Dog

F is for F#

Blogging A to ZWe're up to day 6 of Blogging A-to-Z challenge, FFS.

The last few days I've written about the two main object-oriented languages that come with Visual Studio and .NET: C# and VB.NET. Today I want to diverge just a little into Microsoft's functional language, F#.

At first glance, F# looks a lot like C#. It is, in fact, a flavor of C#; and as it runs on the .NET CLR, it uses .NET constructs. But as Microsoft says, "F# is a programming language that provides support for functional programming in addition to traditional object-oriented and imperative (procedural) programming." Part of this support is the ability to express functions as first-class values. That means you can pass functions around as variables, and do things with them, in ways you can't with C# or other object-oriented languages (sort of—C# can do this too as of 4.7).

Here's an example:

let celsius (f: float) : float = (f - 32.0) * (5.0 / 9.0)

let main argv =
    let c = 68.0
    printfn "%f Fahrenheit is %f Celsius" c (celsius c)

This is just one step up from "Hello World," in that it actually does something. Two interesting bits: (a) You don't actually need to run this using the EntryPoint identifier; you can run it interactively; and (b) More importantly, celsius is just a variable.

I would love to spend another hour on this post, but I can't do the topic justice. Scott Wlaschin, on the other hand, will show you how to use F# for fun and profit. I recommend his site if you want to learn more.

But here's the sad truth: it's not very practical yet. And C# allows you to pass functions as parameters, even anonymously, so F# no longer has a monopoly on functional programming.

Remember, these A-to-Z posts aren't meant to exhaustively describe the topics. I'm only hoping to outline them and provide some follow-up reading links. And with F#, after a 45 minutes on one post, that's about all I'm up for today.

Construction complication in Dunning

No, not the Dunning of Kruger fame; Dunning, the community area on the far northwest side of Chicago.

Workers building a new school in the neighborhood discovered that not only was it the former site of a poor house, but also that 38,000 people may be buried there:

“There can be and there have been bodies found all over the place,” said Barry Fleig, a genealogist and cemetery researcher who began investigating the site in 1989. “It’s a spooky, scary place.”

Workers have until April 27 to excavate and clear the site, remediate the soil and relocate an existing sewer line. The school is scheduled to open in time for the 2019-20 academic year, though a spokesperson for Chicago Public Schools would not say what type of school it will be.

Fleig said he’s “nearly certain” there are no intact caskets buried underneath the proposed school grounds — bodies were primarily buried in two formal cemeteries, though scattered human remains have been discovered during previous construction projects near the campus.

In 1854, the county opened a poorhouse and farm and gradually added an insane asylum, infirmary and tuberculosis hospital to the property. At its peak, a thousand people were buried on the grounds each year.

The state took over in 1912 and changed the official name to Chicago State Hospital. Buildings were shuttered in 1970 and operations moved west of Oak Park Avenue to what is now Chicago-Read Mental Health Center. 

In 1854, the site would have been a few hours' ride from the city. So I'm glad to see that the American tradition of dumping the poor in places where they can't possible thrive was as strong then as now. I'm a little shocked that a pauper's cemetery acquired so many corpses in sixty years, though.

E is for Encapsulation

Blogging A to ZWelcome to day 5 of the Blogging A-to-Z challenge.

In object-oriented design, we talk about a number of basic concepts that make code easier for humans to read and maintain. Encapsulation is fundamental, by hiding the internal data of a class so that only the class can use it. To access data within the class, you can't just reach in and grab it; you need to use the public properties and methods of the class.

Here's a stupid class:

#region Copyright ©2018 Inner Drive Technology

using System;
using System.Collections.Generic;


namespace InnerDrive.DailyParkerAtoZ.WeekOne
	public class Encapsulation
		public string Name { get; private set; }

		public void ChangeName(string newName)
			if (string.IsNullOrWhiteSpace(newName))
				throw new ArgumentException("Name must have a value", nameof(newName));
			Name = newName;

		internal void Clear()
			Name = string.Empty;

		public IEnumerable<string> NameList => new List<string>(_names);

		private readonly List<string> _names = new List<string>();

Seriously, this is dumb. But it demonstrates some of the ways C# encapsulates data.

Line 12 creates a property called Name that any code anywhere can call, because it's public. But it also declares a setter method that is private, meaning only the Encapsulation class itself can set the value of Name.

Lines 14-22 show how this works. The ChangeName method first makes sure you are giving it a real value, then changes Name and adds the new name to a list of names that is itself private. So the only way to change Name is to use the ChangeName method. (There's another way to do this in the property setter, but I wanted to show how this works exactly.)

Lines 24-27 provide you a way of clearing Name, but the method is marked internal. That means only classes in the same assembly can use this method, which has consequences for our unit tests, below.

Line 29 does a nifty trick where, instead of actually giving outside code access to its private list of _names (line 31), it creates a copy of the list and sends that out. Otherwise, anyone would be able to change the contents of _names just by using the NameList property.

Now here's the unit test code:

#region Copyright ©2018 Inner Drive Technology

using System.Linq;
using InnerDrive.DailyParkerAtoZ.WeekOne;
using Microsoft.VisualStudio.TestTools.UnitTesting;


namespace InnerDrive.DailyParkerAtoZ.UnitTests
	public class EncapsulationTests
		public void CanSetNameOfObject()
			var thing = new Encapsulation();
			//thing.Name = "This won't compile";
			//thing._names.Add("This won't compile either");
			Assert.AreEqual("Ernie", thing.Name);
			Assert.AreEqual(1, thing.NameList.Count());

		public void CanClearNames()
			var thing = new Encapsulation();
			Assert.AreEqual("Ernie", thing.Name);
			Assert.AreEqual(1, thing.NameList.Count());

			// thing.Clear(); // oops—won't compile!

			// Assertions fail!
			Assert.AreEqual(1, thing.NameList.Count());

The comments explain what's going on.

So how can we test the Encapsulation.Clear() method? By adding this line to the InnerDrive.DailyParkerAtoZ.WeekOne.AssemblyInfo.cs file:

[assembly: InternalsVisibleTo("InnerDrive.DailyParkerAtoZ.UnitTests")]

Now all of the objects, properties, and methods in the WeekOne assembly marked internal are visible to the unit test class, and the tests pass.

Cool, right?

As always, the growing Visual Studio solution is here. The ZIP file contains the complete Git log of the project, by the way. Enjoy.

Parker update: home but on drugs

Cone of shame, shaved leg, drugged out of his mind: that's my boy. But at least he's home:

As I've been saying, the next few weeks will be rough. But he's going to get lots of attention, especially between now and Monday.

And then there's this:

He has physical pain, I have psychic pain. All because he ran up some stairs too fast.

Again: ouch.

D is for Database

Blogging A to ZWelcome to day 4 of the Blogging A-to-Z challenge. After yesterday's more theoretical post on the CLR, today will have a practical example of how to connect to data sources from C# applications.

Almost every application ever written needs to store data somewhere. If you're deploying a .NET website into Microsoft Azure (like this blog), you will probably connect it to an Azure SQL Database. Naturally, Visual Studio and C# make this pretty easy.

Here's the code that opens up a database connection and prints out to the Trace window what it's opened:

#region Copyright ©2018 Inner Drive Technology

using System.Configuration;
using System.Data.SqlClient;
using System.Diagnostics;


namespace InnerDrive.DailyParkerAtoZ.WeekOne
	public static class DataConnections
		private static string ConnectionString => ConfigurationManager.ConnectionStrings["Database"].ConnectionString;

		public static void Connect()
			using (var connection = new SqlConnection(ConnectionString))
				Trace.WriteLine($"Connected to {connection.DataSource}");

Let's take a look at that line by line.

Lines 3-6 tell the compiler that the objects referenced in the executable code come from those four namespaces (which I'll talk more about on April 16th). The SqlConnection class, for example, lives in the System.Data.SqlClient namespace. If I didn't have the using statement on line 5, I'd have to reference the class and its namespace as System.Data.SqlClient.SqlConnection, which is cumbersome.

Line 13 creates a ConnectionString property that gets its value from a configuration setting. More on that below.

Line 17 first sets up a different kind of using statement, which makes sure that whatever the expensive SqlConnection class does while its alive, it gets cleaned up when it finishes on line 21—even if it throws an exception. Then the same line creates a new SqlConnection object and assigns it to the variable connection.

Line 19 attempts to open the connection to the database. If it succeeds, line 20 prints out the name of the data source. If it fails, it throws an exception that whatever method called this one can catch.

The configuration file looks like this (but with a real database, user ID, and password):

<?xml version="1.0" encoding="utf-8" ?>
			connectionString="server={server name};initial catalog={database name};persist security info=True;user id={user ID};password={password};"

Notice that the name on line 5 corresponds to the configuration setting name on line 13 of the C# code. That's how the code knows which connection string to read from configuration.

Finally, there's also a unit test, which looks like this:

#region Copyright ©2018 Inner Drive Technology

using InnerDrive.DailyParkerAtoZ.WeekOne;
using Microsoft.VisualStudio.TestTools.UnitTesting;


namespace InnerDrive.DailyParkerAtoZ.UnitTests
	public class DataConnectionsTests
		public void CanConnectToDataSource()

If the call to DataConnections.Connect() succeeds, the test passes. If the call fails, the test fails and shows the exception that gets thrown.

You can download the code for all of these posts here. You'll have to change the configuration information in the unit test project's app.config file to make it work, of course.

Parker post-surgery update

Whew. Parker is just fine.

The surgeon said everything went very well. She reported he completely tore his meniscus and his right CCL (the doggy equivalent of a human's ACL), and it looked like the result of an acute injury, not age-related deterioration. This is good news because it means he has a much lower risk of doing this to his left leg than we worried about.

He's recuperating from the operation right now and will remain overnight for observation. He should be home after lunch tomorrow, with a healthy quantity of drugs and probably a really sharp appetite.

Recovery should take 6-8 weeks, though he should be able to go for actual walks within about 2 weeks. But wow, he's not going to like those two weeks.

Stay tuned. Photo tomorrow, I expect.

Parker update: surgery today

Parker did not have a good morning.

I woke him up early, then "forgot" to feed him, and wouldn't even let him lick the cream cheese off my knife when I had a bagel right in front of him. All he got was an unpleasant-tasting amino supplement and a pain pill.

He did get a ride in the car, though, which might have gotten his mind off his appetite.

But then he got unceremoniously carried up two flights of stairs (the elevator at the pet hospital was out of order) and handed off to someone who smelled like frightened cats.

Let's not even talk about the thunderstorms forecast for later today.

So, Parker is chilling at the hospital right now, with his surgery scheduled for this afternoon. Because he's in the late group, I won't get to visit him tonight, which is probably OK because that might just upset him. He should be ready to go home tomorrow late morning.

I'll post again when the surgeon calls after the operation.

C is for Common Language Runtime

Blogging A to ZDay 3 of the Blogging A-to-Z challenge brings us to the heart of .NET: the Common Language Runtime (CLR).

Microsoft defines the CLR as the run-time environment which "runs the code and provides services that make the development process easier." That isn't the most helpful definition, so let me try to elaborate.

As I described Sunday and yesterday, the .NET compiler takes your source code from C# or whatever other language you use and compiles it down to one or more managed modules containing intermediate language (IL), which get further compiled into assemblies.

When your program runs, the CLR is the thing running it. It loads your assemblies and then handles all the tasks your program needs to survive, like memory management, thread synchronization, exception handling, security, etc. It actually does this through Just-in-Time compilation (JIT), when it translates the IL into your machine's own language. This means that when an IL instruction is executed for the second time, it runs in native CPU code.

The CLR also manages .NET's common type system (CTS), which "defines how types are declared, used, and managed in the common language runtime," according to Microsoft. Types (my topic for April 23rd) are therefore a part of every .NET program, even (gasp!) Ruby.NET. I'm picking on Ruby because in that language, ever instruction gets interpreted at run time, making it possible to use types that you haven't defined. The CLR and the CTS prevent you from doing that.

To learn a lot more about the CLR, I strongly recommend Jeffrey Richter's CLR via C#, which I mentioned Sunday.

Canine User Experience

Yesterday, the Nielsen Norman Group released groundbreaking research on user interface design for dogs:

There are several key usability guidelines that help dogs to have the most usable experience on modern websites and apps, particularly on mobile, tablet, and other touch-based interfaces:

  • Consistency is critical. While consistency in any user experience is important, with dogs, it’s even more so. Experienced dog trainers will tell you that, for dogs to learn proper behavior, consistency in enforcing routines, expectations, and commands is critical. Some common UI culprits that provide extra difficulty for dogs are swipe ambiguity, gestures without signifiers, tap uncertainty for flat UI elements like ghost buttons, and unusual placement of common elements like navigation and search.
  • Tap targets must be large. We recommend 1cm2 for human tap targets, but paws (whether belonging to cats or dogs) require larger tap sizes (of at least 3-4cm2, or even larger for Labradors and Great Danes).
  • Gestures must be ergonomic for dog physiology. While many wearable interfaces now involve gestures such as swiping left or right to dismiss notifications or switch apps, these need to be modified for more ergonomic canine movements (such as “shake”). Dogs have a greater ability to move paws with precision up and down, but dogs’ range of motion along the horizontal axis is limited and relatively imprecise, so all gestures must account for this limitation.

They also give special guidance on the risks of using hamburger menus and pie charts.

B is for BASIC

Blogging A to ZFor day 2 of the Blogging A-to-Z challenge, I'm going to talk about the first computer language I learned, which is still alive and kicking in the .NET universe decades after it first appeared on a MS-DOS 1.0 system disk: BASIC.

BASIC stands for "Beginner's All-Purpose Symbolic Instruction Code." The original specification came from John Kemeny and Thomas Kurtz at Dartmouth College in 1964. Today it's one of the core .NET languages included with Visual Studio as "VB.NET" (for "Visual BASIC," Microsoft's dialect of BASIC released in 1991).

Yesterday I showed you a "Hello, World" application written in C#. (You can download the source code here.)

Here's the VB.NET version:

Module Program

	Sub Main()
		Console.WriteLine("Hello, World!")
	End Sub

End Module

What's different? Well, a lot of things: no braces, no include lines, no semicolon line endings...and that's just for a 2-line program.

But look at what's the same. Because this is a .NET program, the actual guts of it look almost exactly the same. There are two calls to different methods on the Console object, and except for the missing semicolons, they are identical to the calls in C#.

Here's the IL:

.method public static void  Main() cil managed
  .custom instance void [mscorlib]System.STAThreadAttribute::.ctor() = ( 01 00 00 00 ) 
  // Code size       19 (0x13)
  .maxstack  8
  IL_0000:  nop
  IL_0001:  ldstr      "Hello, World!"
  IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_000b:  nop
  IL_000c:  call       valuetype [mscorlib]System.ConsoleKeyInfo [mscorlib]System.Console::ReadKey()
  IL_0011:  pop
  IL_0012:  ret
} // end of method Program::Main

Wow. The IL is exactly the same. So both the VB.NET and C# code compile down to functionally identical assemblies.

And that's one of the most important characteristics of .NET: it lets you write code in any language you want (as long as someone has written a compiler for it), and run it on any platform you want (as long as there's a CLR for it).

I worked with Visual BASIC from versions 1 to 6, and then did one project in VB.NET before switching to C# in 2002. You really would need to pay me a lot of money to go back to it. I believe C# is more expressive, more concise, and more able to reflect my intentions than VB.NET.

But there is nothing wrong with VB.NET. If you want to use BASIC, enjoy. With the .NET ecosystem, it's up to you.