8
Apr

Option type implementation in C#

by Mikael Lundin in F#, Programming

F# has this clever functionality called Option<’a>. This means that, instead of returning null from a function, you return an option. This option could have the value Some x or None, where x is the value you want to return, clearly indicating that this method could return a value or not.

let getIndexOfSubstring (s : string) (substring : string) =
    let index = s.IndexOf(substring)
    match index with
    | -1 -> None
    | n -> Some n

Function signature:

val getIndexOfSubstring : string -> string -> int option

And for those of you not fluent in F#, this means that getIndexOfSubstring takes two strings and returns an option of int. This option could be Some int, or it could be None if the substring is not found.

What you win, is that option is now part of the method signature. As a method invoker you will have to handle the None option. As with NULL references, a null return value is often a side effect of the method and often unexpected.

Implement Option<’a> in C#

The option type is a type that we use as return value from a method.

public Option<int> GetIndexOfSubstring(string s, string substring)
{
    var index = s.IndexOf(substring);
    if (index == -1)
        return new None<int>();

    return new Some<int>(index);
}

What does this mean?

  1. The implementation clearly states that the method returns some value or no value at all.
  2. If the return type is an option, you need to return both Some and None for the construct to be valid. The caller of this method expects that both Some and None are possible values.

The method signature also provides you with better test names.

[Test]
public void ShouldReturnSomeIndexForExistingSubstring()
{
    /* Test implementation */
}

[Test]
public void ShouldReturnNoneWhenSubstringDoesNotExist()
{
    /* Test implementation */
}

What are Some and None?

The example code makes much more sense if you look at the class diagram of Some/None.

The code for the option is very abstract.

// Used as return type from method
public abstract class Option<T>
{
    // Could contain the value if Some, but not if None
    public abstract T Value { get; }

    public abstract bool IsSome { get; }

    public abstract bool IsNone { get; }
}

We could implement IsSome/IsNone by comparing this type with Some/None class, but I don’t like the idea of a superclass reference any subclass.

The implementation of Some and None are pretty straight forward.

public sealed class Some : Option
{
	private T value;
	public Some(T value)
	{
		// Setting Some to null, nullifies the purpose of Some/None
		if (value == null)
		{
			throw new System.ArgumentNullException("value", "Some value was null, use None instead");
		}

		this.value = value;
	}

	public override T Value { get { return value; } }

	public override bool IsSome { get { return true; } }

	public override bool IsNone { get { return false; } }
}

public sealed class None : Option
{
	public override T Value
	{
		get { throw new System.NotSupportedException("There is no value"); }
	}

	public override bool IsSome { get { return false; } }

	public override bool IsNone { get { return true; } }
}

Creating a Some instance with null value is only ridiculous, and that is why we throw an exeption. The same goes for calling Value on None.

How do you call a method that returns Option<T>?

Here is some code that will call my first example and act differently if the result is Some or None.

// Get string before substring
private string SubstringBefore(string s, string substring)
{
    var operations = new StringOperations();
    var index = operations.GetIndexOfSubstring(s, substring);

    if (index.IsSome)
        return s.Substring(0, index.Value);

    return s;
}

What are the benefits of the calling method?

  • The result must immediately be checked if it is Some/None before you start using the value. Of course you could ignore the check and go directly to index.Value if you’re willing to take the exception when index is None. (just like null values)
  • It’s clear for the reader that GetIndexOfSubstring might not return a value and that has to be dealt with.

Using Option<T> with reference types

Value types like int already have this functionality with Nullable<T>. Nullable works the same way with a different purpose, to give value types a null value.

With value types it is quite clear that “null” means “no value”, but with reference types it could mean

  • Abscense of value. The method states that for given input there is no output value.
  • Empty set. Specially working with databases, null could mean that the result set was empty.
  • Unknown. The method does not know how to respond and throw us a null (when it really should throw an exception)
  • Not initialized. An object has not been initialized and the reference is null.

The real danger of null in .NET is when it comes from the framework or a third part library and we where not expecting it. That is when you’ll see the NullReferenceException, the most – and it could pop up at any time in production.

This is why we don’t allow null values into Some. Better to fail early when we’re creating the result set of the method, than letting the program run in a faulted state until it tries to use that value.

public Option<User> FindUserByName(string name)
{
	var query = from user in Users
				where user.FirstName.Contains(name) || user.Surname.Contains(name)
				select user;

	var found = query.FirstOrDefault();
	if (found == null)
		return new None<User>();

	return new Some<User>(found);
}

What has to be noticed in this example, is that found really have to be checked for null before entered into Some, or it may blow up. This means that Some/None null checks would be all over the place violating DRY. Could we fix it with an extension method?

public static class OptionExtensions
{
    public static Option<T> SomeOrNone<T>(this T reference)
        where T : class
    {
        if (reference == null) return new None<T>();
        return new Some<T>(reference);
    }
}

And this changes the previous example to.

var found = query.FirstOrDefault();
return found.SomeOrNone();

When is it elegible to return Some<T> instead of Option<T>?

When we have a reference return type that we want to communicate, “could never be null”, we could use Some as the return type, but this would feel a bit weird at the method invokers end.

You could communicate the same thing with Microsoft Code Contracts.

Here’s really three possible state of Option<T>, Some/None and Null. How do I protect myself from a method with Option<T> return type, from returning null?

Microsoft Code Contracts is also the answer here, or you could look into AOP and write an aspect that will throw an exception when you try to return null instead of an instance of Option<T>.

If you’ve decided on the method signature, you probably also agree on the pattern Some/None. But the method signature could be forced upon you with an interface, and in that case some security measure that makes sure that you don’t return null could be useful.

All the source code in a nice packaged VS2010 solution can be downloaded from here.

7
Apr

Forwarding events in C#

by Mikael Lundin in Uncategorized

Yesterday I learned a new syntax in C# that I didn’t know about. I learned how you can forward events.

Let’s say I want a class that takes a schema, and validates html to that schema. The class would encapsulate the XmlReaderSettings, but code from the outside would want to subscribe to the ValidationEventHandler on that private field. The code would look something like this.

public class HtmlValidator
{
    private readonly string html;
    private XmlReaderSettings xmlValidationSettings;

    public HtmlValidator(string @namespace, string schemaPath)
    {
        this.html = html;

        /* Load the schema */
        var xmlSchema = XmlReader.Create(schemaPath);

        xmlValidationSettings = new XmlReaderSettings();
        xmlValidationSettings.Schemas.Add(@namespace, xmlSchema);
        xmlValidationSettings.ValidationType = ValidationType.Schema;
    }

    public void Validate(string html)
    {
        var htmlReader = new StringReader(html);

        // Trigger this event on schema validation errors
        // xmlValidationSettings.ValidationEventHandler += HandleValidationErrors; 

        // Read and validate htmlOutputStream
        var xmlValidatingReader = XmlReader.Create(htmlReader, xmlValidationSettings);
        while (xmlValidatingReader.Read()) ;
    }
}

How could the code calling on Validate, subscribe to ValidationEventHandler on xmlValidationSettings? We would need to create an event on HtmlValidator that forwards the ValidationEventHandler.

I add a public forwarding event like this.

public event ValidationEventHandler OnValidationError
{
    add { xmlValidationSettings.ValidationEventHandler += value; }
    remove { xmlValidationSettings.ValidationEventHandler -= value; }
}

Now we can subscribe to this event, and it will subscribe to the inner ValidationEventHandler. Study the following tests.

[TestFixture]
public class Test
{
    private int CountHtmlErrors(string html)
    {
        // Create validator
        var validator = new HtmlValidator("urn:unordered-list", "UlLiSchema.xsd");

        // Add event handler
        var errors = 0;
        validator.OnValidationError += (o, e) => errors++;

        // Validate html
        validator.Validate(html);
        return errors;
    }

    [Test]
    public void HtmlShouldBeValid()
    {
        var html = @"<ul xmlns=""urn:unordered-list""><li></li><li></li></ul>";

        // Assert the result
        Assert.That(this.CountHtmlErrors(html), Is.EqualTo(0));
    }

    [Test]
    public void HtmlShouldBeInvalid()
    {
        var html = @"<ul xmlns=""urn:unordered-list""><p>Hello</p></ul>";

        // Assert the result
        Assert.That(this.CountHtmlErrors(html), Is.EqualTo(1));
    }
}

At line 11 I subscribe to the external event that will trigger the error++ code on validation errors. Pretty neat, huh!?

2
Apr

Samsung Omnia 7 – Windows Phone 7 Review

by Mikael Lundin in Technicalities

I’ve had my Samsung Omnia 7 WP7 mobile phone now for some days and here’s what I think of it. I will compare it to two other smart phones that I’ve been in contact with, my previous iPhone 3G and my wife’s HTC Desire HD.

Hardware

I was choosing between the Samsung Omnia 7 and HTC 7 Mozart, and took the former because of the display and powerful 1500mA battery. The first thing you’ll notice is that the screen is as good as the reviews says. Very strong colors and sharpness. The 1 Ghz Snapdragon CPU makes this phone a dream compared to my previous iPhone. Everything runs smoothly and I’ve not yet to experience any lag or long waits.

(* due to Apples operating system upgrades my old iPhone eventually got so slow, that any task took longer than the screensaver timeout)

The phone weights 138g (incl. battery) and has enough size to not fit your pocket. It is damn right ugly and uncomfortable to hold in one hand for long. The ugliness comes mostly from the choice of putting the Samsung logo and Windows logo on the front. I have no love for these trademarks and would prefer the Apple way – let the design speak for itself and put the logos where they’re least obtrusive.

The back button and search button in the picture are very sensitive touch buttons that are easy to accidently push when you least want to. Other buttons around the phone, camera, on/off and volume feel very cheap and plastic. That is the only thing however about this phone that feels cheap. Everything is glossy and shiny, Metallic edges and a plastic with the feel of aluminium on the back.

+ Screen is great
+ Battery life is acceptable

- Ugly with all the logotypes
- Uncomfortable to hold in one hand
- Easy to accidentially push front buttons
- Gets warm after some use

Compared to iPhone

Apple put a lot of effort into the feel of holding their devices. It is quite noticable when you get hold of something that is not just that well designed. I like that Apple does not use logotype’s on the front of the phone, but they have managed to create a visual design that speaks for itself. You don’t have to see the logotype to distinguish an iPhone from another smart phone.

With WP7 I love the diversity in hardware. I can select the manufacturer the way I want and does not have to stand for what Apple gives me.

Compared to HTC Desire HD

I like the HTC design. They make nice phones, that sometimes feels a bit plastic, but always are well designed. They put their logotype up front but it is very unobtrusive and not at all like SAMSUNG. I don’t like that they put too weak batteries into their phones for that much screen. The HTC Desire HD screen is 4.3″ (0.3″ more than Samsung) and it sucks juice like a new born baby.

I did not perceive HTC 7 Mozart as much more than a standard phone, and I wanted a bit more. The HTC HD7 phone seemed to have the same battery life problems as HTC Desire HD and I want to use my phone for the whole day without recharging, thank you!

Software

I really like the WP7 operating system. It is clean and minimalistic. It runs smooth on the hardware and yet it has details that are candy for the eye. Overall I really like the WP7.

The setup experience on the phone was done in a blast. I configured my Windows Live, Facebook and WiFi. Upgrading to latest version of the OS was not harder than connecting the phone to my computer and installing Zune. After that I was good to go. The phone had imported all my contacts and it took me no more than a few minutes to move missing contact details from my old iPhone to my new WP7.

I think that running Silverlight as development platform for the phone is genius. It really enables us developers to create nice looking applications very fast, and that was why I bought this phone. It is a developer friendly phone – quite the opposite to iPhone.

The Windows MarketPlace contained a lot more applications that I expected and I like the search and rate function. It was trivial to find applications like Twitter, Facebook, Adobe Reader and add them to the phone.

Thank you Samsung for not installing a lot of self developed crap applications that most manufacturers do to the phone. I really appreciate that.

+ Minimalistic design
+ Great virtual keyboard

- Sometimes buttons are too small

Compared to iOS

The end user iOS experience is a nice one, and what I really like about iOS is that I never have to read a manual to find out how to do stuff. Icons and design makes it all so obvious.

On the other hand, iOS is crap for developers. You will not only need to learn xcode and objective-c, but also have the latest and greatest of the MacOSX to use the development tools. Then, there is this developers fee for submitting applications to the AppStore where it will take months getting through the review process.

Did I mention that Apple does not care about developers? If you do something they don’t like, they will fight you. Overall they are a closed down company that will take a fee of 30% for selling your apps on their AppStore.

WP7 is not an iOS copy, and I really like that. They have tried to find their own design and go for it. There are some ideas in there that I like much more than iOS, that it becomes natural to span an application across several pages/swipes.

The demands of the user base will always give AppStore a lead on Windows Marketplace, but that doesn’t concern me. The quality of the service provided for developers on WP7 will encourage quality on apps in WP7 and draw attention of the likes like me.

Compared to Android

I find the Android operating system dull. It is exactly what you would expect from a phone operating system and nothing more. There are no innovative ideas and nothing that triggers the wow-factor.

With that said, I think that Android is a very stable platform and well thought through. The massive setup experience of the Android phone left it a complete and impressive machine after installation. There’s are a lot of good apps for Android and the system is open. The integration with google products are great and the diversity in hardware choices are fantastic.

The WP7 is much more interesting than Android, but Android is both a more open OS and more mature. I would recommend Android phones to my friends any day.

iTunes vs. Zune smackdown

I hate iTunes, I really do. It may be the worst wide spread application ever created for Windows. It really hates the user and does everything it can to annoy you. I know of people that wants to buy an iPhone but can’t, because they refuse to install that iTunes crap on their machine.

That is why I was initially sceptical to Zune. Same shit, different name. I might however been a tad too fast in my judgement. Zune is the same thing, a hub for your phone where you can sync data from your desktop computer. There are some subtle differences.

  • Zune is beautiful and follows the Windows 7 Aero graphical profile
  • When Zune wants to update itself, or download new content – it does not make the rest of your computer unusable
  • Adding stuff to your phone is much intuitive than iTunes
  • You can sync over wifi – no need to plug your phone in

Hold on!? Why do we need this sync crap anyway?

The ideal experience would be if my phone could access all media from my media server and I could mark stuff for offline use directly on the phone. I should be able to subscribe to podcasts directly on the phone, and the phone would download new episodes when on Wifi.

Maybe we’ll see more of that in the future.

Windows Phone 7 in Sweden

Would I recommend this phone to someone that lives in Sweden?

- No.

Services like GPS, MarketPlace, XBOX Live are not fully released in Sweden so you have to run on UK account. That’s crap, but the Android had similiar problems and it took them years to get it all ready. I just hope that Nokia will speed up the process as they start putting demands on Microsoft.

Would I recommend this phone to somewhere in US or UK?

- Yes!

This is a delightful piece of machinery and I think you will enjoy it very much. If you’re a developer – even more so. Most of all, I would recommend it to companies that have need for self developed mobile applications for their employees. These companies would save lots of money in development and maintenance costs just by choosing this platform.

1
Apr

Zune software is not launched. Retry after making sure that Zune software is launched

by Mikael Lundin in Programming

I was getting started with some WP7 development today, but already on my first Compile/Run i ran into this error message. “Zune software is not launched. Retry after making sure that Zune software is launched.”

After some googling I found out that the default target after installing Zune with a real phone would be to run the project on the phone. Not interesting for me, while in this early stages of development. I want to run my project in the emulator.

Some more googling and I found out that there’s an option in the “Standard toolbar” where you can choose target. Not very obvious to me as I’ve removed all my toolbars to free up some screen space. A prime example on how non-default GUI options could backfire.

Enabling the “Standard toolbar” and changing the run target, did the trick.

23
Mar

56 useless buttons in your IDE

by Mikael Lundin in Programming

When did you last click a button in those toolbars in Visual Studio? Been a while, huh? Isn’t it time to give that space over to more code screen space?

You simply remove the toolbars by right click and deselect all checked. Don’t worry, you’re already using keyboard shortcuts for those things that you have up there. And if not .. here’s a short reminder.

Standard toolbar

# Name Keyboard shortcut
1 New Project Ctrl + Shift + N
2 Add New Item Ctrl + Shift + A
3 Open File Ctrl + O
4 Save File Ctrl + S
5 Save All Ctrl + Shift + S
6 Cut Ctrl + X
7 Copy Ctrl + C
8 Paste Ctrl + V
9 Undo Ctrl + Z
10 Redo Ctrl + Y
11 Navigate Backward Ctrl + -
12 Navigate Forward Ctrl + Shift + -
13 Start Debugging F5
14 Solution Configurations
15 Find in Files Ctrl + Shift + F
16 Find Ctrl + “
17 Solution Explorer Ctrl + W, S
18 Properties Window Ctrl + W, P
19 Team Explorer Ctrl + W, M
20 Object Browser Ctrl + W, J
21 Toolbox Ctrl + W, X
22 Start Page
23 Extension Manager
24 Command Window (other windows) Ctrl + W, A

Build toolbar

# Name Keyboard shortcut
25 Build Project Shift + F6
26 Build Solution F6
27 Cancel Ctrl + Break

Debug toolbar

# Name Keyboard shortcut
28 Start Debugging F5
29 Break All Ctrl + Alt + Break
30 Stop Debugging Shift + F5
31 Restart Ctrl + Shift + F5
32 Show Next Statement Alt + Num *
33 Step Into F11
34 Step Over F10
35 Step Out Shift + F11
36 Search for this line in IntelliTrace
37 Hexadecimal Display
38 Show Threads in Source
39 Breakpoints Ctrl + D, B

Text toolbar

# Name Keyboard shortcut
40 Display Object Member List Ctrl + K, L
41 Display Parameter Info Ctrl + K, P
42 Display Quick Info Ctrl + K, I
43 Display Word Completion Ctrl + K, W
44 Toggle Suggestion And Standard Completion Mode
45 Decrease Indent Shift + Tab
46 Increase Indent Tab
47 Comment Out Selection Ctrl + K, Ctrl + C
48 Uncomment Selection Ctrl + K, Ctrl + U
49 Display Quick Info Ctrl + K, I
50 Toggle Bookmark Ctrl + B, T
51 Goto Previous Bookmark Ctrl + B, P
52 Goto Next Bookmark Ctrl + B, N
53 Goto Previous Bookmark in Folder
54 Goto Next Bookmark in Folder
55 Goto Previous Bookmark in document
56 Goto Next Bookmark in document
57 Clear All Bookmarks Ctrl + B, C

And remember, you can change any keyboard shortcut that you’re not comfortable with.