If you have worked some with Windows Identity Foundation you probably know that most of the types that you work with are found in the Microsoft.IdentityModel.* namespaces. You have probably also noticed that more than a few of the type names in there are also used in corresponding locations in the System.IdentityModel.* namespaces of the base class library. Examples of such type names are Claim (in Microsoft.IdentityModel.Claims and System.IdentityModel.Claims) and RequestSecurityToken (in Microsoft.IdentityModel.Tokens and System.IdentityModel.Tokens). Of course, these types are not replaceable with each other, so you need to make sure to reference the correct namespace when dealing with them. And that would not be so tricky if it was not for the fact that many of them also share some dependencies.

For instance, let’s say you are working with Saml2SecurityToken (found in Microsoft.IdentityModel.Tokens.Saml2), it is derived from SecurityToken (found in System.IdentityModel.Tokens). In the same method, you need to use a SecurityTokenDescriptor. Working with Windows Identity Foundation, more often than not you will want to use the counterpart found in the Microsoft.IdentityModel.* namespaces rather than those found in System.IdentityModel.*. To resolve this you will need to use namespace aliases. I have found that when using ReSharper to resolve this, it tends to import the System.IndentityModel.* namespaces as usual, and set up aliases for the collisions in Microsoft.IdentityModel.*:

using System.IdentityModel.Tokens;
using SecurityTokenDescriptor = Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor;

I have also found that on a regular basis this is not very practical. For instance, quite a few of the types that you work with need to have aliases set up for them. In these cases I find it more practical to start off with manually setting up aliases for the few classes from the System.IdentityModel.* that I want to use, and then have ReSharper resolve the others. Typically this results in a smaller number of regular using directives.

As an example, in one of my code files the following using directives:

using System.IdentityModel.Tokens;
using Microsoft.IdentityModel.Claims;
using Saml2Attribute = Microsoft.IdentityModel.Tokens.Saml2.Saml2Attribute;
using Saml2AttributeStatement = Microsoft.IdentityModel.Tokens.Saml2.Saml2AttributeStatement;
using Saml2SecurityToken = Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityToken;
using SecurityTokenDescriptor = Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor;

...could be narrowed down to this:

using Microsoft.IdentityModel.Claims;
using Microsoft.IdentityModel.Tokens;
using Microsoft.IdentityModel.Tokens.Saml2;
using SecurityToken = System.IdentityModel.Tokens.SecurityToken;

OK, perhaps not a huge difference, but that last one looks a lot less like a workaround than the first one, to me at least.

kick it on DotNetKicks.com


I am working for a great consultancy company called Diversify, located in Sweden. We are hiring skilled .NET developers. If you are interested, don't hesitate to get in touch with me.

Yesterday on Twitter, Johan Normén drew my attention to a naming pattern for tests (which he quickly published a blog post about, and where most credit should apparently go to Patrik Löwendahl) that I found quite interesting. It was being compared to the naming convention that has previously been suggested by Roy Osherove (MethodName_StateUnderTest_ExpectedBehavior). The two naming conventions view the system under test from slightly different angles. While Roy's convention is "method based", this other convention can be said to be more "scenario based".

As a side effect, this also sparked a little discussion regarding the definition of a unit test. And it made me think a little bit. Is this urge to have a definition interesting? Does it add value? The intended value is probably that it can shorten communication a bit. I can say "unit test", and people I talk to will immediately know what I mean, have the same image of tests with a certain scope and level of isolation.

But that's not how we function, is it?

We can see this pattern all around, not only when discussing technicalities in code. Marco Arment posted an article a couple of days ago called "Right versus pragmatic", which highlighted how we often try to force "the right" way to do things on people, instead of observing how they actually behave.

I often feel that definitions like "unit tests" do the same thing. It doesn't matter if somewhere there is a definition saying that "a bucket can be labeled unit test only if it is not more than 50% full". No matter how hard we try, different people will still fill different amounts of water into the bucket and stick a "unit test" label on it.

Instead, I like to use a more pragmatic approach. The water in your bucket should not need any external connections. That's a good test. If you want to call it a "unit test", feel free to do so. The only thing I am interested in, is "is this test well-designed?". Sticking a label to it will not make it better or worse. It could, if all people could agree on one definition. In that case, this definition could contain characteristics for well-designed tests. But there will be no such agreement, because we are people. That's what we do. We absorb information, we apply our own experiences and preferences to it, and then we use it. What comes out will be different for different people.

A definition is supposed to make communication simpler, faster, shorter and more clear. Instead I often see how it creates discussion about the definition itself. Instead of helping us focus more on the challenge at hand, the definition becomes a challenge in itself.

So these definitions, do they not fill any purpose at all? Well, I think they do, but not they purpose the seem intended to fill. Instead of facilitate communication, I think that they facilitate thinking. They make us discuss, which forces us to think. Discussion and thinking creates and shares knowledge, and that adds value. But when I need things done, that’s not where they help me.

kick it on DotNetKicks.com


I am working for a great consultancy company called Diversify, located in Sweden. We are hiring skilled .NET developers. If you are interested, don't hesitate to get in touch with me.

Today's blog post is not about programming. Not directly anyway. Today I will talk about user experience.

I usually think that Google does pretty well when it comes to the user experience. Today however, I stumbled upon a surprising and rather irritating... um, feature. You know how you can limit the search results in time, so that you get results from the last 24 hours, last week, last month and so on? Well, I wanted to do the opposite. I wanted results that was approximately one year old, or older. Luckily, in the end of the timing choices, there is a Custom range alternative.

02-fixed
The options for limiting the search result in time.

When you click on Custom range, the page will show a couple of text boxes where you can type the dates the dates between which the search should be limited.

03

Now, as you may know, dates is a messy field. Here in Sweden we write dates in one way (which happens to conform to the ISO standard). In the US dates are written entirely differently. In France, they write dates like in the US, but they the month and day switch places. In short, when you give the use a text box for writing dates, the ice gets very thin.

Google is obviously aware of this, so they provide an example of how they want you to write the date. Right above the Search button they show you a date in the form that they want, and it happens to be in the US format. Note how the date is carefully chosen so that the French shall not be confused. It is obvious that the first number is the month and the second is the day, since there are only 12 months in a year.

Great! So I put in the dates that interest me:

04

...and then I click the Search button. Now it gets confusing. Google tells me that they dates I entered are not valid.

05

So, just to try it out, I enter dates my way instead. I am after all using the Swedish Google site (even though I run it in English).

06

And when I click Search, this is what I get:

07

It works out just fine! Now, notice how the dates that I typed into the text boxes has now been translated into the US date format. If I just click the Search button again, I get the same error as before: that the dates are not valid.

Not very intuitive.


I am working for a great consultancy company called Diversify, located in Sweden. We are hiring skilled .NET developers. If you are interested, don't hesitate to get in touch with me.

This is the second of two parts. The first one is here: TaskCompletionSource in real life (part 1 of 2)

Yesterday I showed an example of how you can use TaskCompletionSource to mock calls that returns a Task for testing purposes. In the code samples I used an interface called IAsyncWebClient. This was of course no coincidence. WebClient happens to be a good candidate for showing the other major case where I use TaskCompletionSource.

Wrapping async operations that do not follow TPL-supported patterns

It should be no news that asynchronous programming in C# these days revolve around Task objects. Also, it should be no news that asynchronicity is not necessarily the same as starting a new thread for the work. Right from the beginning of .NET you had access to reading and writing streams asynchronously using the BeginRead/EndRead method pairs, along with an IAsyncResult. This would use a mechanism known as I/O completion ports which uses a pool of pre-allocated threads, making it way more efficient than creating new threads for such requests.

The Task Parallel Library supports this pattern through the TaskFactory.FromAsync method, which essentially lets you convert this asynchronous pattern into a Task. Unfortunately there are types in the Base Class Library that has asynchronous functionality but that do not follow this pattern and one of them is the WebClient class.

The pattern used in the WebClient class is that you subscribe to a Completed-event, then you invoke the method that will start the download, and finally the event will be raised when the operation completes (either because it was successful, cancelled or failed).

In yesterday's blog post I used the following interface, invented for the demo code in the article:

public interface IAsyncWebClient
{
    Task<string> GetStringAsync(Uri uri);
}

I want to use this interface to create a type that wraps a WebClient. For natural reasons, this is a tough one to make TDD style, simply because we have external dependencies that are not (easily) mocked (such as a server from which the test can download a document) so this time I will break my habit of presenting a test followed by the implementation. I will simply skip the test part and present the code, with lots of comments in it:

public class AsyncWebClient : IAsyncWebClient
{
    public Task<string> GetStringAsync(Uri uri)
    {
        // create completion source
        var tcs = new TaskCompletionSource<string>();

        // create a web client for downloading the string
        var wc = new WebClient();

        // Set up variable for referencing anonymous event handler method. We
        // need to first assign null, and then create the method so that we
        // can reference the variable within the method itself.
        DownloadStringCompletedEventHandler downloadCompletedHandler = null;

        // Set up an anonymous method that will handle the DownloadStringCompleted
        // event.
        downloadCompletedHandler = (s, e) =>
        {
            // Unsubscribe the event listener (to allow the WebClient to
            // be garbage collected).
            wc.DownloadStringCompleted -= downloadCompletedHandler;
            if (e.Error != null)
            {
                // If the download failed, set the error on the task completion source
                tcs.TrySetException(e.Error);
            }
            else if (e.Cancelled)
            {
                // If the download was cancelled, signal cancellation to the
                // task completion source.
                tcs.TrySetCanceled();
            }
            else
            {
                // If the download was successful, set the result on the task completion
                // source
                tcs.TrySetResult(e.Result);
            }

            wc.Dispose();
        };

        // Subscribe to the completed event
        wc.DownloadStringCompleted += downloadCompletedHandler;

        // Start the asynchronous download
        wc.DownloadStringAsync(uri);

        // Return the Task object from the TaskCompletionSource. This object will be monitored
        // by the calling code for the result, that is provided by the TrySetXxxx calls above.
        return tcs.Task;
    }
}

This way we can use the TaskCompletionSource to provide a Task-based wrapper around a type that provide asynchronous methods, but that deviate from the patterns that are directly supported by the Task Parallel Library.

I have posted this code at my BitBucket repository, slightly extended to also contain cancellation support and a simple winforms client (yes, winforms, I felt a bit retro and lazy).

kick it on DotNetKicks.com


I am working for a great consultancy company called Diversify, located in Sweden. We are hiring skilled .NET developers. If you are interested, don't hesitate to get in touch with me.