Author Archives: shane

Some(“F#”) is better than None

I’ve been doing object oriented programming since 2002. I’ve been looking to expand my horizons for a little while. Not that I believe OOP is bad. I have found that in some cases, modelling everything in classes can be extremely difficult and you end up with an over engineered and complex solution (usually by accident).

I started tinkering with Erlang around 2013. I really enjoy Erlang. I like the syntax, and the pattern matching is absolutely fantastic. I am also a fan of the actor model. My only issue is the problems I am solving for work don’t fit Erlang solutions (yet). Currently we primarily create desktop applications. The newer applications are in C#.

This is where F# comes in. F# is a functional language which runs on the CLR. This means you can start using F# and have it interop easily with your existing .Net applications. Below are a few reasons I started using F# over C#.

REPL (Read Evaluate Print Loop)

One advantage to using F# is the REPL. This allows you to get immediate feedback during your development process. Write a function, test it in the REPL. Modify the function, test it again. No compiling and no external test runner is required. A more apt definition of REPL would be Rapid Evolving Program Logic.

Pattern Matching

I like F#’s pattern matching. It can be concise and easier to read than a bunch of if statements. An example is comparing application versions to determine if the user requires an update.

// uMaj, uMin, uBld = user's Major, Minor, Build version
// lMaj, lMin, lBld = latest Major, Minor, Build version

// C#
if (uMaj < lMaj)
    return "Major";
else if (uMaj == lMaj && uMin < lMin)
    return "Minor";
else if (uMaj == lMaj && uMin == lMin && uBld < lBld)
    return "Build";
    return "None";

// F# - The user's version numbers are either matched or 
// bound to x for comparison
match (uMaj, uMin, uBld) with
| (x, _, _)       when x < lMaj -> "Major"
| (lMaj, x, _)    when x < lMin -> "Minor"
| (lMaj, lMin, x) when x < lBld -> "Build"
| (_, _, _)                     -> "None"

Option Type

F# tries to eliminate null values as much as possible. Nulls are still needed for working with non F# libraries. When an F# function needs the ability to return a value or no value (if there is an error), you can use the Option type. When the function returns a value you wrap it in Some, when no value is to be returned you use None. This gives you a function having a return of either Some (value) or None. A simple example of this is a divide function.

let divide a b =
   match b with
   | 0 -> None
   | _ -> Some (a/b)

After obtaining the result, you can use pattern matching to determine whether you received Some value or None. You end up with fewer NullReferenceExceptions by using options.

There are more reasons to use F#, discriminated unions, agents, and it’s fun. After a little practice and experience with F#, you find you write less code to accomplish the same task than in other .Net languages. All you need to know to get started with F# is the keywords “let“, “|>” (pipe forward), and “fun“. Happy learning!

Great F# resources:

Having a backup is not enough

I got the call on a Friday afternoon. It was shortly after 4:30 pm. The call nobody wants. A customer of one of my clients had been hit by a version of the cryptolocker ransomware virus. Their tech removed the virus, however half of their data files were encrypted. They were going to be fine. They were going to recover their data from a backup.

They paid their tech person to setup and do their backups. Except that someone did it poorly. This customer was not going to be fine. The daily backups were overwriting the same file every time. This meant that as time went on, the ransomware slowly digested the data files, the system happily backed up those newly encrypted files and overwrote any chance we had of recovering their data.

It’s very hard to believe that in this day of age with cloud and inexpensive hardware, that tech people still get this wrong.

I’ll give you a quick checklist of what I’ve been doing for a long time. If you have to wonder if what you are doing is actually a backup? It probably is not. This is a great blog that I direct everyone to when they ask me questions about backups.

I was never going to blog about this topic. Never thought I had to. Thinking now, maybe everyone should have a blog post about doing backups. Then there are no excuses.

A quick list of things I like to have for important backups:

– Multiple versions of backups. My backups never overwrite the same file. I create new backup files. Depending on what I’m backing up, I may keep the seven, fifteen, or thirty most recent backups.

– Multiple locations. My backup files are copied to multiple external hard drives, and another computer.

– Have a backup go offsite. Let a backup be Elvis, and leave the building. Take an external hard drive home with you. Use the cloud. Anything is better than nothing.

– RESTORE your backups once in a while! This is another situation I have seen in my days of doing support. “We have backups. We’ve always done backups.” I had to respond with “I’m sorry, but these backups are not going to work. It’s been backing up the wrong files.” Test your backups! A good and well practiced restore plan makes things a lot less stressful when under pressure.

Always have a reliable set of backups and know how to restore your backups in case things go wrong.

High School: CSI

Computer Science Ignored

Saturday July 20th, 2013 was going great. I got up with my son and we watched cartoons. I went golfing with some friends in a tournament, and we won. I had a wonderful supper with my family and my parents. I then went with my wife to a social (dance). We danced and talked with friends. It had been a great day.

During a conversation with a friend, who is a teacher, I was figuratively punched in the gut. I found out the local high school had its computer science class cut. This was a shock to Haley and I. The class had just started being taught the previous year. It had been about ten years since it was last taught. We went to the class and gave a small presentation and answered any questions the class (including the teacher) had. That was a fun day. However, it’s all over.

There was a lot of excitement for the upcoming year. Haley had been working with the teacher on a course outline to help improve the curriculum. We were more than happy to help out with anything they needed. We were really excited to be involved. I am currently heartbroken.

I’m left asking a lot of questions.
– Was it lack of student interest? I don’t think so. There were eleven students in the class last year, boys and girls. There were already ten new students signed up for next year. This is a school from kindergarten to grade 12 with around 470 students.

– Why is computer science still considered a sub-standard or ignorable topic in high schools? My thoughts are computer science is viewed less as a science, but more of a skilled trade. Maybe the school boards don’t understand that computer science or programming is all about problem solving, experimentation, and analysis.

– Do all physics majors become physicists? How about chemistry majors? I’m not asking this to bash the other sciences, I just don’t know the answer. I really liked physics, and the degree I was originally going for in university was chemistry. I have one friend who has a degree in chemistry and he runs his own company building houses.

– Why is it, the only way to learn programming at an early age is to do it on your own? This does seem to perpetuate the stereotype that computer geeks are anti-social. Maybe the kids just don’t have an opportunity to explore computers outside their own basement? While golfing earlier that day, one guy was talking about his wife getting frustrated with their son for watching youtube videos of minecraft instead of cartoons or playing outside. That seems like a child who would possibly be interested in a computer science course. There are a lot of video games that are good at enhancing problem solving skills.

I am going to followup and try to get the reasons for the cancellation. That way I don’t have to speculate ‘why?’.

As of writing this, the school has a forensics class. That is cool!

Windows 8 Start Screen Displays Wrong Tile Icons

My wife’s laptop had an interesting issue. The start screen in Windows 8 was showing the wrong icon for a lot of the other applications. This would appear in the start screen as well as in the taskbar when the applications were running. This made it difficult to quickly differentiate the applications when a lot of the icons showed as Photoshop.

I searched the web for an answer. The most common answer was to delete the ‘IconCache.db’ and restart the computer. This did not solve my particular problem.

After a while, I noticed it was only the applications where the icon was an external file. Any of the applications whose icons were embedded in the executable were unaffected.

I checked the file associations for extension ‘.ico’ (Control Panel -> Default Programs). It turns out Photoshop had been assigned as the default application for opening ‘.ico’ files. I changed the ‘.ico’ to be opened with ‘Windows Photo Viewer’ (the default is Paint). This didn’t fix the problem immediately, I also had to recreate the start screen tiles for those applications affected.

The problem was finally resolved.

Local High School Visit

Friday May 17, 2013, Haley and I went to the local high school to speak with the computer science class. We did a small presentation followed by any questions the students had. We presented some myths in the industry, best practices, things we like and don’t like, and some tools we use.

I was very nervous at the beginning of the presentation. It had been over four years since I gave a presentation. My voice was a little shaky until I got through the first joke. Once everyone started laughing, I settled in and did the presentation well (at least that’s what everyone told me). Haley answered questions and added comments to the presentation.

The students asked a wide variety of excellent questions. Things like “where do you find clients?”, “what programming language do you mainly use?”, and “why are we typing (null,null) here?”. One question that was an unexpected surprise was when we mentioned we create windows phone apps. One student asked if we create apps for Windows Phone 7 or Windows Phone 8. I thought that was awesome! I had just assumed all the students had iPhones or Androids.

It was a very fun day for Haley and me to go and speak with the students. We look forward to doing it again.

WP8: Linq to Sql MissingManifestResourceException

I was making a major overhaul of a windows phone 8 application yet to be released. It was my own fault, I made a lot of changes in a short time. I did make sure all my tests still passed. Running the application in the emulator gave me a MissingManifestResourceException. I never had this problem before. The error would occur in the base constructor for the DataContext.

The full error message was:
Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "Microsoft.Phone.Data.Resources.resources" was correctly embedded or linked into assembly "Microsoft.Phone.Data.Internal" at compile time, or that all the satellite assemblies required are loadable and fully signed.

I did the usual checks for Neutral Language setting in the Assembly Information. I made sure the Supported Cultures were correct. I added a resource file to the project. I thought maybe the template I had used to create the app didn’t include the appropriate resource file. Still nothing.

I couldn’t find anything that would confirm or deny the fact that linq to sql required cultural resource files.

After much thrashing, I found the cause of my issue. It was in the connection string. Can you see the problem?
"Data Source=isostore;/children.sdf"

It’s the semi-colon. The connection string should have been:
"Data Source=isostore:/children.sdf"
My typo in the connection string gave me an obscure error which lead me on a wild goose chase down the wrong path.

So, lesson learned. Always double check you are using a colon ":" in your connection string.

Raspberry Pi and Adafruit Starter Pack: Ambient Light Warning

Let me start by saying I am not an expert nor an engineer.

I received my adafruit start pack and proceeded through the tutorials with the parts I had available.

This is the result of combining the Basic Resistor Sensor Reading and Raspberry Pi E-Mail Notifier Using LEDs tutorials. You should read/do those tutorials.

I made this system that would turn on the green led when there was ample light, blue for the transition between light and dark, and red for when there is minimal or no light. The reason for doing this? I had no other sensors to connect at the time.

So, let’s begin.

* I assume you already have the Pi Cobbler inserted in the breadboard.
* Warning: Don’t have your Raspberry Pi connected to the breadboard or don’t have power to your Raspberry Pi. We really don’t want to fry something while setting things up.

  • Connect the GND pin (ground) to the blue power rails (-ve).
  • Connect the 3V3 pin (3.3 Volts) to the red power rails (+ve).
  • Use jumper wires to relocate pins #23, #24, and #25 to individual and easily accessible rows on the breadboard.
  • Add resistors (any values from 330 ohm up to 1000 ohm should be fine) to each of the jumper wire rows, connecting to the other corresponding side.
  • Connect your LEDs where the short leg (-ve) connects to the blue rail and the long leg (+ve) connects to the same row as an inserted resistor. (On my board, the Green LED is on #23 and row 24, Blue LED is #24 and row 27, and Red LED is #25 and row 30).
  • Connect a jumper wire from pin #22 to an available and accessible row.
  • Connect the 1uF capacitor’s -ve leg to the blue rail and the other to the row with the newly attached jumper wire for pin #22.
  • Connect one side of the photocell to pin #22 and the other to the red power rail (3V3).

The overhead shot of my setup:

Now to program the Raspberry Pi. The OS I used was adafruit’s occidentalis.

Getting the necessary packages: (If you already have them you may skip this part)

$ sudo apt-get install python-dev
$ sudo easy_install rpi.gpio

Once those packages are installed we can write the program.

$ sudo vi
#!/usr/bin/env python

import RPi.GPIO as GPIO, time, os
# The levels required changing based on the type of light I was in.
# In sunlight, the photocell readings ranged from 15 to 105. In 
# artificial light the readings were much higher.

# Artificial light
#LEVEL1 = 160
#LEVEL2 = 300 

# Sunlight
LEVEL1 = 30
LEVEL2 = 60

RED_LED = 25

def RCtime (RCpin):
	reading = 0
	GPIO.setup(RCpin, GPIO.OUT)
	GPIO.output(RCpin, GPIO.LOW)

	GPIO.setup(RCpin, GPIO.IN)

	while (GPIO.input(RCpin) == GPIO.LOW):
		reading += 1
	return reading

def ResetWarningLights ():
	GPIO.output(GREEN_LED, False)
	GPIO.output(BLUE_LED, False)
	GPIO.output(RED_LED, False)

def SetWarningLight (level) :
	if (level <= LEVEL1) :
		GPIO.output(GREEN_LED, True)
	elif (level <= LEVEL2):
		GPIO.output(BLUE_LED, True)
		GPIO.output(RED_LED, True)

while True:
	level = RCtime(22)
#	print level

Save your file, double check your board layout, connect the raspberry pi to the breadboard, and run your program.

$ sudo ./

If everything is correct you should have an LED on based on the amount of ambient light.
full lighthalf_lightdark

A Different Thought Process: OOP to Erlang

I’ve been dabbling in functional programming lately, more specifically in erlang. I am familiar with recursion. I do use recursion on occasion when code simplicity outweighs the possible performance cost. I am reading Erlang Programming by Francesco Cesarini & Simon Thompson. I am enjoying the book, although I’ll admit I’m not very far into it. I would like to share a realization that I had during one of the exercises: don’t think in objects, think pattern matching.

The exercise consisted of creating a simple database. The underlying structure was a key/value pair contained in a list. The interface consisted of new, destroy, write, delete, read, and match. I am going to focus on the read(Key, Db) function, where Db is the list obtained from calling new. After adding data consisting of key/values, I would call the read function with the specified Key.

My initial implementation was as such:

read(_Key, []) -> {error, instance} ;
read(Key, Db) -> 
  [Head | Tail] = Db,
  case Head of
    {Key, Data} -> {ok, Data} ;
    {_,_} -> read(Key, Tail)

I want it to be known that this does work. It looks horrid, but it does work. Imagine if this were a more complex operation? My problem at the time was thinking the Db argument was a list. I would then pull out the Head (first item in the list) and Tail (remaining list items) once in the function. This was so wrong of me. I was thinking OOP and not pattern matching.

When I remembered Pattern Matching can be used for deep matches. I refactored the read operation to three lines.

read(_Key, []) -> {error, instance} ;
read(Key, [{Key, Data} | _Tail]) -> {ok, Data} ;
read(Key, [_ | Tail]) -> read(Key, Tail).

The first implementation was using pattern matching. The matches were based on an empty list and a non empty list. The refactored code pattern matches on an empty list, a non empty list where the first item contains the key we were looking for, and a non empty list where the first item’s key did not match.

When pattern matching with functions in erlang, it seems less about what the arguments are, and more about what you want them to be.

ActiveRecord and MySQL Setup on Ubuntu 12.04.1

As a .Net developer I thought I would give Ruby and ActiveRecord a try for a simple web application. When I say simple I mean it’s only two operations. One consists of non-authenticated data entry and the other of data retrieval. Install of everything went fine, or so I thought. It turns out that there are some intricacies in getting the right activerecord to work on Ubuntu.

This is a quick blog post of getting activerecord to work with MySQL on Ubuntu 12.04.1 LTS. This is a result of me searching a bunch of other blogs and tutorials to figure out what I was doing wrong.

Getting the files

>sudo apt-get install mysql-server
>sudo apt-get install ruby
>sudo apt-get install rubygems
>sudo gem install activerecord
>sudo apt-get install libmysqlclient15-dev
Note: this may install “libmysqlclient-dev” instead, which should be fine.
>sudo gem install activerecord-mysql2-adapter

You should now have all the required files.

Setup test database

Connect to MySQL and create a database and table.

>create database dummy;
>use dummy;
>create table tests(id bigint primary key auto_increment, text varchar(100));

A test ruby file: atest.rb

#! /usr/bin/ruby
require ‘rubygems’
gem ‘activerecord’, ‘=3.2.9’
require ‘active_record’

class Test < ActiveRecord::Base

ActiveRecord::Base.establish_connection( :adapter => ‘mysql2’,
  :host => ‘localhost’,
  :username => ‘username’,
  :password => ‘password’,
  :database => ‘dummy’

Record = Test.create(:text => ‘new record text’)
Inserted_records = Test.where(:id => 1)
# It is recommended to use “find” instead of “where“ when selecting by the primary key.
# I used where as a test to make sure I had everything installed and working
Puts inserted_records[0].text

Make sure you have a reference to the gem in your ruby file. If you don’t, when you go to use the ”where” method you will receive a method_missing error. As of writing, the active record gem version was 3.2.9.
Also make sure the adapter in the establish_connection method is ‘mysql2’. Using the older ‘mysql’ adapter will also cause issues.


I did skip creating a new user and granting access to the mysql database as that was an easy web search.

Initial thoughts on the HTC 8x 16GB WP8

I recently picked up two Windows Phone 8 devices. The HTC 8x 16GB and a Nokia Lumia 920. Out of the kindness of my heart, I gave the Nokia to my wife and I kept the HTC. I am giving my thoughts after using the HTC 8x for a few days.

Now, let me preface this by saying the HTC 8x is a very nice device. I do like it. There are a couple of issues that I am going to have to get used to. These issues may go away when I get a case for the phone. It also may sound like I am envious of my wife’s Lumia 920. This may be the case, but there are things about my phone that she is envious of. To be honest, if I had the choice again… to hell with being nice. I would keep the Nokia Lumia 920 for myself.

Starting with what came out of the box. The phone, of course. A micro usb cable, a 5v 1A charger, and documents. This is the basics. I was a little surprised there were no earbuds and mic. I thought for sure there would be considering it has Beats Audio. My wife’s Nokia Lumia 920 had head phones. Maybe I received a box where the earphones were missing? It’s ok though. I can use the ones that came with my Samsung Focus. Basics out of the box are phone, micro usb cord, charger, and documents.

I do like the sound the phone is able to reproduce. The HTC 8x automatically enables Beats Audio when you plug headphones in. I was testing using earbuds from my old Samsung Focus. I thought the music sounded pretty good. The speaker itself did well providing I didn’t have it muffled on my desk. I was going to test the audio for movies, but that will have to wait until we are allowed to load movies purchased through Zune. Overall, I thought the speakers and Beats Audio were very well done.

The HTC 8x had four custom apps out of the box. The HTC came with a flashlight app, unit converter app, photo enhancer app, and the HTC app (this includes local weather, news, and stock quotres). My wife is envious of the unit converter app. The app is elegant, fast, and easy to switch unit types. Photo enhancer is for adding effects to your pictures, such as making them look vintage. The Lumia 920 on the other hand came with an array of apps. I think there were four camera apps alone for the Lumia 920. There are a modest number of apps for the HTC 8x compared to the Lukia 920.

I haven’t had a chance to tinker with all the settings on this phone. There is a setting for those with hearing aids. This will increase the volume while you are talking on the phone. There is also attentive phone. This allows the phone to adjust to external actions during ringing. When enabled, the phone can quiet the ring on pickup, mute the ringer if you flip over your phone, or use a loud ring when the phone is in your pocket or purse. I don’t get many phone calls, that’s why I haven’t gotten to all the settings.

The phone is a good size and aesthetically pleasing. It is smaller and lighter than the Lumia 920. The HTC 8x has a nice feel to it. There are issues for the way I hold my phone. I prefer holding the phone using three edges instead of using a death grip on two. I hold the phone with my pinkie finger supporting the bottom edge of the phone. The phone has rounded edges on all sides and the micro usb port is located on the bottom edge. I find that because the phone is rounded, the edges of the usb port rub against my finger. This will probably not be an issue once the gel cover case arrives. The screen is very clear and the phone looks very nice.

Now, here is my main gripe with the phone. The power button is located on the top edge. I am finding it very inconvenient since I hold the phone using the bottom edge. Whenever I want to turn on the phone I either have to adjust the phone in my hand (fingers aren’t quite long enough) or use my other hand. Two hands to turn on your phone is non-optimal. This is where the Lumia 920 is really better suited for me. All three buttons are on the right edge of the phone. Ideal for one handed access and use of all three phone buttons. I may get used of it, or become more eficient of one handed turn on using my face (chin works well. I may look stupid in public though). The power button on the top is kind of a deal breaker for me.

Results so far: If I had known then what I know now. I would have gone with the Lumia 920. Just so I could have the power button on the side. Other than that, the HTC 8x is a very nice phone. At 16GB it is less than what the Lumia 920 has, but I never filled my old Samsung Focus with only 8GB. Am I happy with this phone? Yes, for the most part.

I know what people are thinking, “don’t hold it like that”.