Coding for Food

Thursday, October 10, 2013

Fun with Functional

I recently uploaded my first NuGet package. It contains my first shot at playing with functional programming with my favorite computer language. This has been inspired by the things I’ve learned in the book Functional JavaScript.

Thinking from a functional programming standpoint is quite different than traditional OOP thinking. Sometimes I call it ‘inside-out thinking’. It can lead to some seriously efficient code. You’ll see that with a powerful tested functional library, you end up writing less code; and the less code you write, the less code you have to test, and the less code that can go wrong. Remember that you can probably write a 5 line program that has no bugs. I recall seeing my college Lisp instructor code faster and more powerfully than any C coder I’ve ever met. To be sure, there are a lot of good functional languages to learn these techniques, among them Clojure, F Sharp, and Nemerle. As a C Sharp guy, I’ll start with a library, and apply functional programming to my C sharp code. You can see much of the influence of functional programming when exploring LINQ. I’ll be using some of the LINQ extensions in my library.

Sometimes I write code like this:

for(int i= 0; i< 5; i++) fn(i);

or this:

IList<int> result = new List<int>();
for(int i=0;i < 5; i++) result.Add(fn(i));

Let’s do this from a functional standpoint. We’ll build with bricks. One of the first things I've discovered is the conflict between operators and functions. I can pass around functions, but I can't pass around operators. Thus, we'll make the operators in to functions. Here are some bricks:

public static class Functional<T> {
    public static Func<int, int, bool> gt = (l, r) => (l > r);
    public static Func<int, int, bool> lt = (l, r) => (l < r);
    public static Func<int, int, bool> equ = (l, r) => (l == r);
    public static Func<int, int, bool> neq = (l, r) => (l != r);
    // many more are not displayed here
    :
}

One of the takeaways from functional programming is the increasingly blurry line between code and data. You may see the term “code = data”. Note that these are almost the same thing:

IEnumerable<int> x1 = new List<int>() { 0, 1, 2, 3, 4 };
IEnumerable<int> x2() { for(int i = 0; i < 5; i++) yield return i; }

These are not completely interchangeable, as we can declare the list implementation in a function, but not the function implementation. Had we been able to have a yield return in a lambda, we could have. We’ll make another brick.

    public static IEnumerable<int> range(int start,int end) {
        int step = ((end - start) > 0) ? 1 : -1;
        for (int i = start; neq(i, end); i += step) yield return i;
    }

The full-featured version would be:

    public static IEnumerable<int> range(int start, int end, int step = 1) {
       int Step = ((end - start) > 0) ? Math.Abs(step) : -Math.Abs(step);
       Func<int, int, bool> condition = ((end - start) > 0) ? lt : gt;
       for (int i = start; condition(i, end); i += Step) yield return i;
    }

Code = data, replacing a list of integers with a range. Now these are the same:

IEnumerable<int> x1 = new List<int>() { 0, 1, 2, 3, 4 };
IEnumerable<int> x2 = Functional<int>.range(0,5,1);

Functional programming promotes recursion over iteration. Often one will build a function that takes a list, and does something with the first element, and the then calls itself with the rest of the list, recursively. Therefore a couple useful functions are to get the first element of a list, and a function to return the rest of the list. I use some LINQ functions for this.

    public static Func<IEnumerable<T>,T> first = (lst) => lst.First();
    public static Func<IEnumerable<T>,IEnumerable<T>> rest = (lst) => lst.Skip(1);

Back to my original code, these bricks:

    public static Action<IEnumerable<T>, Action<T>> each = (lst, fn) => { foreach (T t in lst) fn(t); };
    public static IEnumerable<U> map<U>(IEnumerable<T> lst, Func<T, U> fn) { return lst.Select(fn); }

make this:

for(int i= 0; i< 5; i++) fn(i);

becomes:

Functional<int>.each(Functional<int>.range(0,5,1),fn);

And this:

Func<int,int> fn = (x) => x * x;
IList<int> result = new List<int>();
for(int i=0;i < 5; i++) result.Add(fn(i));

becomes:

IEnumerable<int> result = Functional<int>.map<int>(Functional<int>.range(0,5,1),(x) => x * x);

Another couple of bricks are:

    public static Func<string,IEnumerable<char>> Chars = (s) => s.AsEnumerable();
    public static T reduce(IEnumerable<T> lst, Func<T, T, T> acc, T initialItem) {
        return lst.Aggregate(initialItem, acc);
    }

Now suppose we had a string “abcdefg”, and we want to transform that to “a.b.c.d.e.f.g”. In the old days, I might do this:

string Interleave(char c,string source) {
    string result = source[0].ToString();
    for(int i=1; i<source.Length;i++) {
        result = result + c.ToString() + source[i].ToString();
    }
    return result;
}

Now I depend on a functional style:

Func<char, string, string> Interleave = (c, s) => {
     IEnumerable<char> seq = Functional<string>.Chars(s);
     string result = Functional<char>.reduce<string>(
        Functional<char>.rest(seq),
        (st, ch) => st + c + ch,
        Functional<char>.first(seq).ToString()
    );
    return result;
};

It’s often useful to know if two sequences are the same. I have a function that does this, and is very useful in my tests.

    public static Func<IEnumerable<T>, IEnumerable<T>, Func<T, T, bool>, bool> same = (lst1, lst2, fn) => {
        IEnumerator<T> i1 = lst1.GetEnumerator();
        IEnumerator<T> i2 = lst2.GetEnumerator();
        bool result = true;
        bool b1 = i1.MoveNext();
        bool b2 = i2.MoveNext();
        while (result && (b1 && b2)) {
            result = fn(i1.Current, i2.Current);
            b1 = i1.MoveNext();
            b2 = i2.MoveNext();
        }
        return (result && (b1 == b2));
    };

With this I can verify that:

IEnumerable<int> result = Functional<int>.map<int>(Functional<int>.range(0, 7), x => x + 5);
bool success = Functional<int>.same(result, Functional<int>.range(0 + 5, 7 + 5),Functional<int>.equ);

There is a strange function called always. Sometimes it's useful to have a function that always return a specific value.

    public static Func<T> always(T t) { return () => t; }

Interestingly, making two functions with the same value, does not return the same function.

Func<int> x = Functional<int>.always(3);
Func<int> y = Functional<int>.always(3);
// x != y

Just to tighten the potential proliferation of functions a bit, I provide the alwaysTrue and alwaysFalse functions:

    public static Func<bool> always(bool b) { return (b) ? alwaysTrue() : alwaysFalse(); }
    public static Func<Func<bool>> alwaysTrue = () => () => true;
    public static Func<Func<bool>> alwaysFalse = () => () => false;

There are times where it's useful to combine two or more sequences in some way, and return the new sequence.

    public static IEnumerable<U> map<U>(IEnumerable<T> lst1, IEnumerable<T> lst2, Func<T, T, U> fn) {
        IEnumerator<T> one = lst1.GetEnumerator();
        IEnumerator<T> two = lst2.GetEnumerator();
        while ((one.MoveNext()) && (two.MoveNext())) {
            yield return fn(one.Current, two.Current);
        }
    }

So testing the three sequence of this would be painful without the sequence compare function called same. We'll start with this brick:

    public static Func<bool, bool, bool> and = (l, r) => l && r;

Now to test the three-sequence combiner.

bool success = true;
// t f f t
IEnumerable<Func<bool>> test = new List<Func<bool>>() {
    Functional<bool>.always(true),
    Functional<bool>.always(false),
    Functional<bool>.always(false),
    Functional<bool>.always(true)
};
IEnumerable<char> first = Functional<string>.Chars("xoxo");
IEnumerable<char> second = Functional<string>.Chars("xxoo");
IEnumerable<char> third = Functional<string>.Chars("xooo");
IEnumerable<Func<bool>> result = Functional<char>.map<Func<bool>>(first, second, third,
    (x, y, z) => Functional<bool>.always(Functional<bool>.and((x == y), (y == z))));
success = Functional<Func<bool>>.same(result, test,(x,y)=>x()==y());

The key is passing a function that knows how to compare elements of the sequences. The == operator fails this, so the functional style of passing functions to functions saves us.

Finally, I have some curry functions. This is a technique to creating a function on the fly, and also configuring it. Suppose that I have a function that can add two integers (as I do)

    public static Func<int, int, int> add = (x, y) => x + y;

Now suppose that we need a function that takes an integer, and returns the sum of that integer, and 6. In the recent past, I would be tempted to write:

int addSix(int x) { return x + 6; }

No more. I have a class called Curry2 (big brother to Curry1) that takes a function, and when asked, will return a configured function.

    public class Curry2<T, U> {
        private Func<T, U, U> fn; // U fn(T t, U u)
        public Curry2(Func<T, U, U> fun) { this.fn = fun; }
        public Func<U, U> Create(T t) { return (x) => this.fn(t, x); }
    }

Creating the addSix function looks like this:

Curry2<int, int> add = new Curry2<int, int>(Functional<int>.add); //here
Func<int, int> addSix = add.Create(6);
int r = addSix(21); // 27

I’ve published version 0.0.9 here. Install it and try it out.

Friday, August 2, 2013

Web API testing with Node

As I’m building an application that requires a backend web-service, I am building that service using Node. I intend that service to be RESTful. I need a tool to test this service, and have created a tool that runs under Node.  I use the assert library for verification.


var endpoint = 'localhost';
var http = require('http');
var assert = require('assert');
var opts = {
host: endpoint,
port: 8000,
path: '/submit',
method: 'POST',
headers: { "Accept": "application/json", "Content-Type": "application/x-www-form-urlencoded" }
}
var req = http.request(opts, function(res) {
res.setEncoding('utf8');
var data = "";
res.on('data', function(d) {
data += d;
});
res.on('end', function() {
console.log(data);
//var result = eval(''+data);
//assert.strictEqual(data,'{"status":"ok","message":"this is fun"}');
});
});
req.write('unit');
req.end();

Wednesday, July 24, 2013

Morse code with an Arduino

In the hobby of amateur radio is a hobby called Radiosport. It is a competitive activity that combines RDF (radio direction finding) and orienteering, or land navigation. At the heart of this activity are a set of hidden transmitters that periodically transmits a coded message in Morse code. The goal is to locate all the transmitters in the minimum time. I have created some software for the Arduino, that with a gated oscillator and a hand-held radio, will make a good hidden transmitter for RDF activities like Radiosport or fox hunts.

The code for Arduino is called “Processing”. You can think of it as ‘C’, as the back end is a CPP compiler. The Arduino requires two functions to be implemented, and calls them when the device is powered on. The first function, ‘setup’ is called once soon after the device comes up, and then another function, ‘loop’ is called again and again forever, until the device is powered down.

 

I start with a few global variables. You’ll see this pattern many times in Arduino code.


/* Version 0.1 Support a-z and 0-9 and space */
/* Version 0.2 Support .,?!{}&:;=+-_"$@'/ */
int ledPin = 13;
int PTT = 12;


PTT means push-to-talk, a line to tell the transmitter to…transmit. The ledPin would connected to gate the output of an audio frequency oscillator. The output of that gated oscillator would go to the mic line of the transmitter.




int lengthDot = 200;
int lengthDash = 3 * lengthDot;
int CycleTime = 15000; // every 15 seconds


The length of a dot is 200 milliseconds, while the length of a dash is three times that. This transmitter transmits every 15 seconds.



I use a structure that contains a key, the number of symbols (sum of dots and dashes) and the code itself encoded from right to left. Dots are 0, while dashes are 1.




typedef struct {
char info;
byte length;
byte code;
} tagMorseLetter;


I create a table with 54 entries




int entries = 54;
tagMorseLetter morseCode[] = {
//code is shifted from the left
{'a',2,0b00000010}, // .-
{'b',4,0b00000001}, // -...
{'c',4,0b00000101}, // -.-.
{'d',3,0b00000001}, // -..
{'e',1,0b00000000}, // .
{'f',4,0b00000100}, // ..-.
{'g',3,0b00000011}, // --.
{'h',4,0b00000000}, // ....
{'i',2,0b00000000}, // ..
{'j',4,0b00001110}, // .---
{'k',3,0b00000101}, // -.-
{'l',4,0b00000010}, // .-..
{'m',2,0b00000011}, // --
{'n',2,0b00000001}, // -.
{'o',3,0b00000111}, // ---
{'p',4,0b00000110}, // .--.
{'q',4,0b00001011}, // --.-
{'r',3,0b00000010}, // .-.
{'s',3,0b00000000}, // ...
{'t',1,0b00000001}, // -
{'u',3,0b00000100}, // ..-
{'v',4,0b00001000}, // ...-
{'w',3,0b00000110}, // .--
{'x',4,0b00001001}, // -..-
{'y',4,0b00001101}, // -.--
{'z',4,0b00000011}, // --..
{'1',5,0b00011110}, // .----
{'2',5,0b00011100}, // ..---
{'3',5,0b00011000}, // ...--
{'4',5,0b00010000}, // ....-
{'5',5,0b00000000}, // .....
{'6',5,0b00000001}, // -....
{'7',5,0b00000011}, // --...
{'8',5,0b00000111}, // ---..
{'9',5,0b00001111}, // ----.
{'0',5,0b00011111}, // ----- Stay away from the codes below here
{'.',6,0b00101010}, // .-.-.- _No_ hams know them
{',',6,0b00110011}, // --..--
{'?',6,0b00001100}, // ..--..
{'!',6,0b00110101}, // -.-.--
{'{',5,0b00001101}, // -.--.
{'}',6,0b00101101}, // -.--.-
{'&',5,0b00000010}, // .-...
{':',6,0b00000111}, // ---...
{';',6,0b00010101}, // -.-.-.
{'=',5,0b00010001}, // -...-
{'+',5,0b00001010}, // .-.-.
{'-',6,0b00100001}, // -....-
{'_',6,0b00101100}, // ..--.-
{'"',6,0b00010010}, // .-..-.
{'$',7,0b01001000}, // ...-..-
{'@',6,0b00010110}, // .--.-.
{'\'',6,0b00011110}, // .----.
{'/',5,0b00001001} // -..-.
};


The meat of the code. The variable ‘current’ is the index of current item in the message as it's being transmitted.




int current = 0;

void setup() {
pinMode(ledPin, OUTPUT);
pinMode(PTT, OUTPUT);
}
void loop() {
int timeSpent = DoTask(ledPin,"your callsign here");
int restOfTime = CycleTime - timeSpent;
if (restOfTime > 0) delay(restOfTime);
}


Because I want to transmit synchronously, I need to know how much time each function in my code takes (give or take). I can sum all the times, and know when to start my next transmission. When I send a message, that function tells me how long it took. Of course that requires that each call to send a character or a space returns the time that took, which of course requires that the call to send a dot or a dash also returns how long it took. It's turtles all the way down. And finally, I wrap it in a DoTask function.




int DoTask(int pin, char* sentence) {
return sendSentence(pin, sentence);
}



int sendSentence(int pin, char sentence[])
{
int result = 0;
boolean between = false;
digitalWrite(PTT, HIGH);
char* p = sentence;
while (0 != *p) {
if (between) result += InterLetter(pin);
if (*p == ' ') result += Space(pin);
else {
int entry = FindCode(*p); // unknown time
if (-1 != entry) {
result += sendLetter(pin,morseCode[entry].length,morseCode[entry].code);
between = true;
}
}
p++;
}
digitalWrite(PTT, LOW);
return result;
}


I use a mask to get the LSB of the current code. I shift it out, bit-by-bit, and depending if the result is a 0 or 1, I transmit a dot or a dash. Note that the symbols are coded right to left, so I must shift them out left to right. Of course I accumulate the time spent transmitting the symbols. Between each symbol is a gap, so I account for that also.




int sendLetter(int pin, byte length, byte code)
{
int result = 0;
boolean between = false;
for(byte i = 0; i<length; i++) {
byte lsb = code & 0b00000001;
if (between) result += Gap(pin);
if (lsb == 0b00000001) result += Dash(pin);
if (lsb == 0b00000000) result += Dot(pin);
code = code>>1;
between = true;
}
digitalWrite(pin, LOW);
return result;
}
int Dash(int pin) {
digitalWrite(pin, HIGH);
delay(lengthDash);
return lengthDash;
}
int Dot(int pin)
{
digitalWrite(pin, HIGH);
delay(lengthDot);
return lengthDot;
}
int Gap(int pin)
{
digitalWrite(pin, LOW);
delay(lengthDot);
return lengthDot;
}
/* The space between letters is the time of 3 dots */
int InterLetter(int pin)
{
digitalWrite(pin, LOW);
int totalDelay = lengthDot + lengthDot + lengthDot;
delay(totalDelay);
return totalDelay;
}
/* A space character is the time of 7 dots */
int Space(int pin)
{
digitalWrite(pin, LOW);
int totalDelay = lengthDot + lengthDot +
lengthDot + lengthDot +
lengthDot + lengthDot + lengthDot;
delay(totalDelay);
return totalDelay;
}


Now normally I'd run a binary search here, but this was just easier, and it works. In a future version, I’ll improve this.




int FindCode(char c) {
int found = -1;
for(int i = 0; i< entries; i++) {
if (morseCode[i].info == c) {
found = i;
break;
}
}
return found;
}

Monday, July 8, 2013

Day of the Week library

Some applications may need a Day Of The Week object. The application may be a business tool that may need to track something based on the day of the week, such as business hours. The application I am designing is using a bus schedule, which varies depending on if it's a weekday or on a weekend. A useful feature of such a class is: given today, what is tomorrow? It works the other way as well. If today is Tuesday, was yesterday a weekday? Is four days from today on a weekend?

DaysOfTheWeekContract.cs


namespace Library.Contracts {
public enum DaysOfTheWeek {
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
}
public enum DayClassification { WeekDay, WeekEnd }
public interface IDay {
DaysOfTheWeek DayOfTheWeek { get; }
DayClassification Classification { get; }
IDay Next { get; set; }
IDay Previous { get; set; }
}
public interface IWeek {
DayClassification Classification(DaysOfTheWeek day);
DaysOfTheWeek Tomorrow(DaysOfTheWeek today);
DaysOfTheWeek Yesterday(DaysOfTheWeek today);
}
}



DaysOfTheWeekImp.cs

using Library.Contracts;
namespace Library.Impl {
public sealed class Day : IDay {
public DaysOfTheWeek DayOfTheWeek { get; private set; }
public DayClassification Classification { get; private set; }
public Day(DaysOfTheWeek dayOfTheWeek, DayClassification classification) {
this.DayOfTheWeek = dayOfTheWeek;
this.Classification = classification;
}
public IDay Next { get; set; }
public IDay Previous { get; set; }
}


public sealed class Week : IWeek {
private IList<IDay> Days;
public Week() {
this.Days = new List<IDay>();
IDay sunday = new Day(DaysOfTheWeek.Sunday, DayClassification.WeekEnd);
IDay monday = new Day(DaysOfTheWeek.Monday, DayClassification.WeekDay);
IDay tuesday = new Day(DaysOfTheWeek.Tuesday, DayClassification.WeekDay);
IDay wednesday = new Day(DaysOfTheWeek.Wednesday, DayClassification.WeekDay);
IDay thursday = new Day(DaysOfTheWeek.Thursday, DayClassification.WeekDay);
IDay friday = new Day(DaysOfTheWeek.Friday, DayClassification.WeekDay);
IDay saturday = new Day(DaysOfTheWeek.Saturday, DayClassification.WeekEnd);
sunday.Previous = saturday;
sunday.Next = monday;
monday.Previous = sunday;
monday.Next = tuesday;
tuesday.Previous = monday;
tuesday.Next = wednesday;
wednesday.Previous = tuesday;
wednesday.Next = thursday;
thursday.Previous = wednesday;
thursday.Next = friday;
friday.Previous = thursday;
friday.Next = saturday;
saturday.Next = sunday;
saturday.Previous = friday;

this.Days.Add(sunday);
this.Days.Add(monday);
this.Days.Add(tuesday);
this.Days.Add(wednesday);
this.Days.Add(thursday);
this.Days.Add(friday);
this.Days.Add(saturday);
}
public DayClassification Classification(DaysOfTheWeek today) {
return this.Days[(int)(today)].Classification;
}
private int indexOfToday(DaysOfTheWeek today) {
return (int)(today);
}
public DaysOfTheWeek Tomorrow(DaysOfTheWeek today) {
return this.Days[(int)(today)].Next.DayOfTheWeek;
}
public DaysOfTheWeek Yesterday(DaysOfTheWeek today) {
return this.Days[(int)(today)].Previous.DayOfTheWeek;
}
}
}


Your code would look like this:


:
:
IWeek week = new Week();
DaysOfTheWeek today = DaysOfTheWeek.Wednesday; // munge this from DateTime
int count = 0;
while (week.Classification(today) != DayClassification.WeekEnd) {
today = week.Tomorrow(today);
count++;
}
// count contains the number of days until the weekend.


Saturday, April 28, 2012

Behavior flexability of IEnumerable<T>

One of the ways to de-couple your code from specific types, what I'll call hard types, is to use the IEnumerable. I'll call this a soft type, and it can be used many places you might otherwise find a read-only version of IList. Rather than pass around an IList, which is an object with state and memory, if you can pass around an IEnumerable, you should.

I want to read strings from a file, or records from a database table. Rather that loop through and create a list of strings/records, I’ll just return an IEnumerable.

First, create a text file, and save it UTF-8 encoded.

Copy this code (sans line numbers)

1   using System;
2 usingSystem.Collections.Generic;
3 usingSystem.Text;
4 using System.IO;
5
6 namespace DonCode
7 {
8 public delegate IEnumerable<string> GetStrings(StreamReader sr);
9 public class Program
10 {
11 static void Main(string[] args)
12 {
13 Program p = new Program();
14 using (StreamReader sr = new StreamReader("file.txt", Encoding.UTF8)) {
15 GetStrings ReadFileStrings = null;
16 ReadFileStrings = p.ReadFileList;
17 // ReadFileStrings = p.ReadFileNoList;
18 IEnumerable<string> items = ReadFileStrings(sr);
19 foreach (string line in items) {
20 Console.WriteLine(line);
21 }
22 }
23 Console.ReadLine();
24 }
25 public IEnumerable<string> ReadFileNoList(StreamReader r)
26 {
27 string line = r.ReadLine();
28 while (!String.IsNullOrEmpty(line)) {
29 yield return line;
30 line = r.ReadLine();
31 }
32 }
33 public IEnumerable<string> ReadFileList(StreamReader r)
34 {
35 IList<string> list = new List<string>();
36 string line = r.ReadLine();
37 while (!String.IsNullOrEmpty(line)) {
38 list.Add(line);
39 line = r.ReadLine();
40 }
41 return list;
42 }
43 }
44 }


To see this work, put a break point here:


15                   GetStrings ReadFileStrings = null;



Run your code in the debugger (F5) and step through it using F11.



Switch comments:




16                   //ReadFileStrings = p.ReadFileList;
17 ReadFileStrings = p.ReadFileNoList;



Run the code in the debugger (F5) and step through it with F11.



The results are the same but the behavior is different. We went from creating a list and running a pair of loops, to running a single loop, and creating no list. The client code was not changed, nor was the contract altered. By using IEnumerable, we were able to be more flexible in our implementation but still deliver on our contract.

Tuesday, June 14, 2011

Coding with code snippets

My main coding tool is Visual Studio. That product has support for what they call "Code Snippets". Code Snippets are typically small chunks of code that you use frequently, that you can easily insert in to your code. It's like clip-board on steroids.


VS ships with a number of code snippets. They typically live here

C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC#\Snippets\1033\Visual C#.



Code snippets are straight XML files with a .snippet extension. Because that extension is registered with VS, clicking on such a file will open it up in VS. Notepad works fine too. We'll look at one of the shipping snippets, and use it for the bases of our own custom snippet. We'll look at prop.snippet:


<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Titlegt;prop</Title>
<Shortcut>prop</Shortcut>
<Description>Code snippet for an automatically implemented property
Language Version: C# 3.0 or higher</Description>
<Author>Microsoft Corporation</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>type</ID>
<ToolTip>Property type</ToolTip>
<Default>int</Default>
</Literal>
<Literal>
<ID>property</ID>
<ToolTip>Property name</ToolTip>
<Default>MyProperty</Default>
</Literal>
</Declarations>
<Code Language="csharp"><![CDATA[public $type$ $property$ { get; set; }$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>


A couple of things to note here. The shortcut is the "keyword" you can type in order to insert the code snippet in to your code. Open a C# file, and within a class, where you would normally insert a property, type prop, then hit the tab key twice. "prop" expands out to "public int MyPropery { get; set; }" Very cool. 28 keystrokes saved. Note that there are two fields that are "highlighted". Tabbing toggles between them. There is a replacement functionality that is available when you first insert a snippet, and the items that are "highlighted" are items that can be replaced. In this case, the author thinks that you'll probably want to replace the property type and the property name with your own, so you can tab from one to another and type in the replacement. In the code snippet, those replacements are in the Declaration section. Here is one:


<id>type</id>
<tooltip>Property type</tooltip>
<default>int</default>


This explains itself. In the code section, all instances of "$type$" will be replaced with "int", and be highlighted for modification. In this simple snippet, there is only one instance of each replacement, but in the more complex one we'll write, the same replacement will appear multiple times, and changing one with change all.

The code section looks like this:

<code language="csharp"><!--[CDATA[public $type$ $property$ { get; set; }$end$]]--></code>


The "$end$" is unknown to me, but perhaps is a built-in replacement for line-feed.

The first useful snippet I'll create is the the Assert that I use on non-null function arguments. I used code contracts once, but to fully take advantage of them you need to use a VS extension. Not an option for us VS Express hackers, so I've dropped back to using:

Debug.Assert(null != parameter);


Here is my implementation:


<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>assertnotnull</Title>
<Shortcut>asnot</Shortcut>
<Description>Code snippet to validate not-null parameters</Description>
<Author>pizza-code</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>parameter</ID>
<ToolTip>non-null Parameter</ToolTip>
<Default>argument</Default>
</Literal>
</Declarations>
<Code Language="csharp"><![CDATA[Debug.Assert(null != $parameter$);$end$]]></Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>


Save this file as "AssertNotNull.snippet" to your a "Code Snippets" directory in your Documents folder. Mine is:

C:\Users\codecore\Documents\Code Snippets\AssertNotNull.snippet


If notepad is your editor, additional work may be required to remove the ".txt" extension.
Now that you've written your new code snippet, or copied mine, how do you let VS know about it?
Menu->Tools->Code Snippet Manager

The "Code Snippets Manager" dialog contains entries for the code snippet locations that it knows about. If Language is "Visual C#", I see a "Refactoring" and a "Visual C#" entry. Use the "Add" button, and find the directory that you saved your new custom snippet file in. You have import individual snippet files directly using the "import" button. VS now knows about your snippets. The directory of snippets are loaded when VS starts, or when you add the directory to it's knowledge. Adding new snippet files to your snippet directory will not be known to VS. A VS restart, or remove-add will be required to pick-up the new snippets.


Should you be running an edition of VS that supports extension, there is a free snippet tool available, mentioned by Robert Greene in this excellent Channel 9 video: http://channel9.msdn.com/Shows/Visual-Studio-Toolbox/Visual-Studio-Toolbox-Creating-and-Using-Code-Snippets


Here are a couple more of my favorite snippets:
NotifyPropery.snippet aka "propf"


<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>propf</Title>
<Shortcut>propf</Shortcut>
<Description>Code snippet to implemented INotifyPropertyChanged property</Description>
<Author>pizza-code</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>type</ID>
<ToolTip>Property type</ToolTip>
<Default>string</Default>
</Literal>
<Literal>
<ID>back</ID>
<ToolTip>Backing Property name</ToolTip>
<Default>back</Default>
</Literal>
<Literal>
<ID>property</ID>
<ToolTip>Public Property name</ToolTip>
<Default>Property</Default>
</Literal>
</Declarations>
<Code Language="csharp"><![CDATA[
protected $type$ $back$;
public $type$ $property$ {
get { return this.$back$; }
private set {
if (value != this.$back$) {
this.$back$ = value;
this.FirePropertyChanged("$property$");
}
}
}$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>


Finally, here is FirePropertyChanged.snippet aka "fire"


<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>fire</Title>
<Shortcut>fire</Shortcut>
<Description>Code snippet for implementing INotifyPropertyChanged interface</Description>
<Author>pizza-code</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Code Language="csharp"><![CDATA[public event PropertyChangedEventHandler PropertyChanged;
protected void FirePropertyChanged(string propertyName) {
if (null != this.PropertyChanged) this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>

Thursday, October 7, 2010

Fun With MEF

I've been playing with MEF. I wanted to use it in the simplest way I could.

For those who don't know, MEF is a component that you can use to manage objects in your application. It's in the universe of "Dependency Injection". It has some features that make it really good for "Plug-In" architectures, but I'll be using it for object lifetime management. There is much less "noise" in using MEF, than the other (SimpleServiceLocator) DI that I have used. In many ways DI is like the Factory pattern on steroids. In any case, you decorate the class that you want to provide as a component with the Export attribute, and you mark the properties of your dependent classes with the Import attribute. MEF scans the assemblies in your directory for all the Exports, and scans all the Imports, and does a quick fix-up, matching Exports to Imports. If I need a IFileSystem object in my logger, I "automagically" get one. I don't need to new one up, or MyFileSystemFactory.Create(), or first register a constructor or factory with a static ServiceLocator. See Glenn's article for an in-depth tour.


I ran in to the problem that the Imports in a client assembly were not being satisfied, while the imports in the assembly where my MEF host class is defined were satisfied. Here is the ExtensibilityHost class that is in the Heat.dll host assembly:



//Heat.cs
namespace Heat
{
public static class Constants {
public const string NullOrEmptyString = "null or empty string";
public const string NullObject = "null object";
public const string EmptyString = "empty string";
public const string RangeError = "range error";
public const string SequenceError = "sequence error";
public const string ArrayLengthError = "array length error";
}
}





//HeatExtensibility.cs

using System;
using System.IO;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using System.Diagnostics.Contracts;

using Heat;
namespace Heat.Extensibility
{
public interface IExtensibilityHost : IDisposable
{
void Compose();
void SatisfyImports(object o);
}
public static class ExtensibilityHostFactory
{
private static IExtensibilityHost host = null;
public static IExtensibilityHost Get()
{
if (null == host) host = new ExtensibiltyHost();
return host;
}
private class ExtensibiltyHost : IExtensibilityHost
{
private enum Sequence
{
Initial = 0,
Compose = 1,
SatisfyImports = 2
}
private Sequence sequence = Sequence.Initial;
private CompositionContainer compositionContainer;
private AssemblyCatalog assemblyCatalog;
private DirectoryCatalog directoryCatalog;
public void Compose()
{
Contract.Requires(this.sequence == Sequence.Initial, Constants.SequenceError);
this.assemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
this.directoryCatalog = new DirectoryCatalog((new FileInfo(Assembly.GetExecutingAssembly().Location)).DirectoryName);
this.compositionContainer = new CompositionContainer(this.directoryCatalog);
this.compositionContainer.ComposeParts(this);
this.sequence = Sequence.Compose;
}
public void SatisfyImports(object o)
{
Contract.Requires(null != o, Constants.NullObject);
Contract.Requires(this.sequence != Sequence.Initial, Constants.SequenceError);
this.compositionContainer.SatisfyImportsOnce(o);
this.sequence = Sequence.SatisfyImports;
}
virtual public string AssemblyInfo()
{
return Assembly.GetExecutingAssembly().ToString();
}
virtual public void Dispose()
{
Contract.Requires(this.sequence != Sequence.Initial, Constants.SequenceError);
this.assemblyCatalog.Dispose();
this.directoryCatalog.Dispose();
this.compositionContainer.Dispose();
this.sequence = Sequence.Initial;
}
}
}
}




Here is the exported object. When a client assembly needs an IFileSystem object, MEF will find it (Heat.dll), instatiate only one (singleton), and deliver it to the instance of the class in need of it.




//HeatFileSystem.cs
using System.IO;
using Heat.Contracts;// IFileSystem
namespace Heat.Utility
{
[Export(typeof(IFileSystem))]
public class FileSystem : IFileSystem
{…}
}



Fortunatly, I work near The Guy who introduced me to MEF, and he steared me in the right direction. Thanks Glenn! It turns out IExtensibilityHost.Compose() will resolve the the dependencies in the Host assembly, it does not do this for the client assembly. In order satisfy those, I'll need to call another function, passing in an instance of the object that contains the imports. IExtesabilityHost.SatisfyImports(this) ends up calling the SatisfyImportsOnce function of the MEF composition container.

You'll know that this happens, because the TEST FileSystemTest.FileSystem() passes.

The UnitTestHeatFileSystem.cs file contributes to the client assembly UnitTest.dll.


//UnitTestHeatFileSystem.cs
using Heat.Extensibility;
using Heat.Contracts;//IFileSystem
using Heat.Tests.UnitTest;//ITest
using NUnit.Framework;
namespace Heat.Test.FileSystem
{
[TestFixture]
public class FileSystemTest : ITest
{
private IExtensibilityHost extensibilityHost = null;
[Import(typeof(IFileSystem))]
private IFileSystem filesystem;
[SetUp]
public void Setup()
{
this.extensibilityHost = ExtensibilityHostFactory.Get();
this.extensibilityHost.Compose();
this.extensibilityHost.SatisfyImports(this);
}
[TearDown]
public void TearDown() { this.extensibilityHost.Dispose(); }
[Test]
public void Sanity() { Assert.IsTrue(true); }
[Test]
public void FileSystem()
{
Assert.IsTrue(null != this.filesystem);
}
:
}
}