Koen about .Net

June 28, 2011

Thread safe DateTime for unit testing

Filed under: Development, dotnetmag, Testing — Tags: — koenwillemse @ 16:00

We’ve been using the construction of a wrapper class around the DateTime for unit testing which Ayende described here.

Today one of my colleagues discovered that there is a possibility to run multiple unittests in parallel. How to do that is described here. However, the approach we used with the SystemDateTime class no longer worked, since it uses a static field which caused problem with two tests running at the same time. I tweaked it a bit to fix this, so I wanted to share the code we use for it.

/// <summary>
/// Facade for the System.DateTime class that makes it possible to mock the current time.
/// </summary>
public static class SystemDateTime
    private static Func<DateTime> now;

    private static Func<DateTime> today;

    /// <summary>
    /// Returns the current time as a DateTime object.
    /// </summary>
    public static Func<DateTime> Now
        get { return now ?? (now = () => DateTime.Now.Truncate()); }
        set { now = value; }

    /// <summary>
    /// Gets the current date.
    /// </summary>
    public static Func<DateTime> Today
        get { return today ?? (today = () => Now().Date); }
        set { today = value; }

Hope it helps some of you.


February 16, 2011

Custom C# formatter for Selenium

Filed under: Development, dotnetmag, Testing — Tags: , , — koenwillemse @ 22:20

In my previous post I mentioned that I had been working on a C# formatter for selenium which uses MSTest as test framework and also FluentAssertions to make the tests more readable. After a few hours last Saturday night I had something working which looks pretty ok for now. I guess I’m not the only one wanting to generate this code, so I wanted to share what I’ve got.

I started off by taking the source of the C# formatter which is installed together with the selenium IDE. Note that there is a bug (maybe more, but I ran into this one Winking smile) in the source, which results in a lack of options to set in the IDE. The problem is regarding the configForm setting, which is done in the options. This is pretty strange if you look at it, because that configForm is used to generate the UI for the options (which options are available can be found here). The configForm should be set outside the options. I tried to modify the source, but that’s not possible, it’s read-only. If you still want to use the NUnit formatting as done in the formatter, you can add another formatter and add the modified source. You can download the modified source here.

Now to the formatter I wrote. I wanted a few things:

  • MSTest as test framework
  • use FluentAssertions for readability
  • Start the selenium server when starting test run (and close it when tests finished)

There is a description here on how to start creating a custom formatter. However, I was lazy, so I copied the source from the existing C# formatter and modified it to accommodate my needs. First of all I fixed the problem with the options, which I described above.
Next I changed the assertion methods to use the FluentAssertions syntax.
I updated the generated header and footer, since I don’t want all the initialization of a Selenium instance etc. to be done on every TestInitialize since it takes several seconds. I changed it to be done on a central location.

The biggest change I made was add formatting for a test suite, which is not available in the default C# formatter. In the code for the test suite, I added methods for AssemblyInitialize and AssemblyCleanup. In these method, I will start and tear down the selenium server process and the selenium instance. This uses a static selenium instance, so this will cause problems if you want to use it in a multi-threaded environment, but for now, it matches my needs. The complete source of the formatter can be downloaded here.

I hope some of you find this helpful also. If you have some good suggestions for the formatter, then please let me know.

Edit 22-02-2011: The links to the sources were incorrect. I updated the links now, so you can download the files from my skydrive.

February 15, 2011

Comparison of Web UI Testing toolkits

Filed under: Development, dotnetmag, Testing — Tags: , , — koenwillemse @ 16:00

I wanted to started using web UI tests because the current project I’m working on I lacking this and for my personal web shop application I also need it. So I had to make a choice for a testing framework. I already knew of Coded UI Tests in Visual Studio 2010 and Selenium. Another colleague at my current project also mentioned Watin, so I decided to do a quick test of the three and see if it matches my expectations.

Coded UI Tests in Visual Studio

This was my first choice, since it’s integrated in Visual Studio which makes it easier when testing my deployed applications from a build server. So I started by creating the test in de Visual Studio IDE and I clicked some pages. Then added a few assertions and done. Generated the coded test and I looked at the coded that was generated. And that what a bit of a shock Sad smile. It was very unreadable code, which actually shouldn’t matter since it’s generated code, but when you would like to tweak or edit it a bit (like I want) it’s not very nice to do that. I wanted to edit the tests to be able to use some parameters and stuff to make the tests more robust.
Now there is also the option of created tests using the Test Manager in Visual Studio 2010, but I haven’t tried this. That’s something I still want to do, to see if this makes it easier or better. For now, I’m a bit disappointed in using the coded UI tests. When I’ve got some time left, I’m going to check how the creation of coded UI tests is when using the Visual Studio 2010 Test Manager


Selenium is a tool which I’ve heard of several times, so I wanted to give it a try now myself. First you’ll have to install some stuff. I installed the following:

After installing all stuff (which is more work than I wanted Winking smile) I started creating my first test. Clicking the test and verifications is also pretty easy with the integration in Firefox. Then creating the code. There are a few formatters available, one of them being for c#, so I generated the code, but unfortunately it was based on NUnit and there was some stuff in it I didn’t like. But before I gave up, I looked a bit better in Selenium IDE and I saw that there is also the possibility to create your own formatter, so I decided to give that a try. It took some time with some mistakes that I made, but eventually I had a working formatter which created the C# code the way I wanted it. So I started the tests in visual studio (after starting the java application for the selenium server) and it worked Smile.


Because my colleague mentioned this framework, I wanted to give it a try. Unfortunately there was no IDE or something to create the tests. Since I was already more convinced of both other frameworks, I didn’t want to spend more time on this one, since it was also more difficult to work with it in code only mode.


So a small comparison

  Coded UI Tests Selenium Watin
  • Integrated in Visual Studio, so no installation required
  • Control over the generated code
  • Code easy to modify / extend
  • Ugly generated code
  • IDE is a bit buggy
  • Custom installation required
  • No IDE
  • Difficult to work with

So eventually I chose selenium for now, since some other people on my current project are also trying it out and were positive about it. I’ll write another blog post on the custom formatter I’ve been working on. It generates code for the MSTest framework and makes use of the FluentAssertions to make the tests more readable.

February 8, 2011

Crystal reports runtime for .NET 4.0

Filed under: Development, dotnetmag — Tags: , — koenwillemse @ 00:00

A few years ago I created an application which is used by an tutoring institute. It’s not the best application I’ve ever created (and that’s a bit of an understatement), but it works. There are some bugs now and then, some new feature request, which I do when I’ve got some spare time. One part of the application is generating invoices. I used Crystal reports to generate the invoices (first version in VS 2005, later in VS 2008).

A while ago I upgraded my solution to Visual Studio 2010 and then the problems began. Crystal Reports is no longer included in Visual Studio but needs to be downloaded separately from SAP site. Problem one, it took a long time before the final version for .NET 4.0 and Visual Studio 2010 was available. I started using the beta version when I upgraded and it worked OK. The problem however was that there was decent no runtime installation available. I found a blog post (unfortunately I don’t have the link anymore) which indicated that you could redirect the newer assemblies to the ‘old’ VS 2008 version runtime. This worked out good for me so I was ok.

In November last year, the production release of Crystal Reports for Visual Studio 2010 was ready. So when I got my new work laptop in December, I installed this last version. But then, last week I fixed a few minor bugs and made a little improvement, and I got in trouble with the deployment which complained about the Crystal Reports references. So I wanted to quickly download the runtime for the newer Crystal Reports version and install it on the client computer. However, that wasn’t done quickly. It took me a while to finally find the links to the redistributables and merge modules of the new runtime. One thing became clear and that was that I really dislike the SAP web site.

I finally found the links, so I wanted to post them here, so maybe some other people don’t have to spend the same amount of time as I had to, to find the installers (with thanks to Coy Yonce):

  • Standard EXE installation package which installs SAP Crystal Reports for Visual Studio into the Visual Studio 2010 IDE can be found here.
  • Click-Once installation package used to create self-updating Windows-based applications which can be installed and run with minimal user interaction can be found here.
  • Merge Modules installation package used to install components which are shared by multiple applications can be found here.
  • Redistributable installation (32 bit) can be found here.
  • Redistributable installation (64 bit) can be found here.

I hope this saves some time for you.

September 2, 2010

Configuration of WIF

Filed under: Development, dotnetmag — Tags: , — koenwillemse @ 16:15

The current project I’m working on is a Identity Management Solution for a client. We’re working with WIF (as you might have noticed in my previous posts) and SPML v2. I’ve been beating my head against a wall for the last few days because we had all kind of problems to get the Identity Delegation scenario working. Eventually it was a small thing which caused all kinds of problems, but I’ll elaborate on that in a different post.

One thing that I found frustrating is the lack of documentation for WIF and especially that it’s difficult that way to configure the identity related stuff correctly. We figured out now what all the configuration items in the microsoft.IdentityModel section mean, so I’m sharing it here so that other people starting with WIF don’t have the same giant learning curve we had ;-).

For a consuming application, the following is a common configuration when using an active STS (note that we use the .NET 3.5 targeted assemblies):

    <service saveBootstrapTokens="true">
        <issuerNameRegistry type="Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, Microsoft.IdentityModel, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
                <add thumbprint="9dbc8c485022a10788832ab285a6281fe18a22de" name="CN=sts" />
            <add value="http://frontend" />
            <wsFederation passiveRedirectEnabled="false" issuer="https://sts/SecurityTokenService.svc" realm="http://frontend" requireHttps="false" />
            <cookieHandler requireSsl="false" />
            <certificateReference x509FindType="FindByThumbprint" findValue="4fa9361d1ddda6e8847313a56ab96412dd40f13b" storeLocation="LocalMachine" storeName="My"/>

Now what does all this mean and what is it for?

  1. saveBootstrapTokens=”true”
    This means that when WIF makes an ClaimsIdentity from a received SecurityToken, that the property BootstrapToken of the ClaimsIdentity will be the actual token received. I wish I had found about this earlier.
  2. issuerNameRegistry
    This section indicates which sts you trust. Here you add the certificate(s) which are used to sign the tokens you receive from the STS
  3. audienceUris
    This section is used to check whether the received information from the STS is applicable to you as the calling application. It should match the AppliesTo property which you set when you issue a RequestForSecurityToken to your STS.
  4. securityTokenHandlers
    In this section you can remove the default handlers and add your own token handlers. Note 1: Don’t clear the collection, because most of them are necessary. If you want to use a custom, then only remove the default of the type you want to add. Note 2: Be very careful with what you do here. One wrong decision here has cost us a lot of hours of bug hunting.
  5. federatedAuthentication
    This section contains information to determine if you are using an active or passive scenario. When you have a passive scenario (when the browser handles the redirects etcetera for you) then you set passiveRedirectEnabled=”true”. You have to make sure then that the correct issuer and realm and other related attributes are set.
    The cookieHandler requireSsl attribute indicates whether the written session cookie requires SSL. When you are working on a non-ssl connection and you forget to set this to false, your cookies won’t be preserved over postbacks.
  6. serviceCertificate
    This section was the least clear to me when starting out. It is for defining which certificate should be used to decrypt the incoming SecurityToken.

When you setup these values correctly, you should get up and running pretty quickly. This post is just for making clear what each section of the configuration is for. To get an overview of all steps to do for getting up and running using an active STS, please read my previous post about making a web application use an active STS.

I hope this helps some of you to save some time when configuring WIF.

August 2, 2010

Making a web application use an active STS

Filed under: Development, dotnetmag — Tags: , , , — koenwillemse @ 19:46

At my current assignment we’re working on a solution which among others consists of a custom Security Token Service which is used for the authentication of users in a web portal. In our case we’ve created an active STS by using Windows Identity Foundation and WCF. We’re now working a demo web application which uses the STS (and some other functionality we’re building) to show the team which creates the portal how they should consume the STS.

Since there is almost NO decent documentation about WIF, I started googling. The problem which I ran into was that the information I found was almost all about scenario’s with a passive STS. I found a bit information about consuming an active STS but all not complete, so I’ll put all the steps I had to take right here, so it can help some others.

First of all, I eventually found this blog post, which made it almost work for me. There was just some information missing which caused me to search for another 1 – 2 hours.

These are the steps to take when you want to consume an active STS from a web application:

  1. Add a reference to the Microsoft.IdentityModel assembly (WIF).
  2. Add the definition of the microsoft.IdentityModel config section to your config like this (check the correct version of the dll of course):
    <section name="microsoft.identityModel" type="Microsoft.IdentityModel.Configuration.MicrosoftIdentityModelSection, Microsoft.IdentityModel, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  3. Add the following two HttpModules to your config (when using IIS7, add them to you system.webserver section, otherwise to you system.web section):
    <add name="WSFederationAuthenticationModule" type="Microsoft.IdentityModel.Web.WSFederationAuthenticationModule, Microsoft.IdentityModel, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    add name="SessionAuthenticationModule" type="Microsoft.IdentityModel.Web.SessionAuthenticationModule, Microsoft.IdentityModel, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  4. The authentication mode should be set to None:
    <authentication mode="None" />
  5. Add the configuration for the microsoft.IdentityModel section, for instance:
    <issuerNameRegistry type="Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, Microsoft.IdentityModel, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
    <add thumbprint="{Add the thumbprint of the certificate used by your STS, for instance: 80481e4041bd6758400c62e2c811831b98eed561}" name="{Add the name of the certificate, for instance: CN=devsts}" />
    <add value="{Add the applies to url of your web application}"/>
    <wsFederation passiveRedirectEnabled="false" issuer="{The address of the STS, for instance: https://devsts/mySts.svc}" realm="{The applies to address of your web application, for instance: http://myrelyingparty.nl}" persistentCookiesOnPassiveRedirects="true" />
    <cookieHandler requireSsl="false" />
    <certificateReference x509FindType="FindByThumbprint" findValue="{The certificate used by your STS, for instance: 80481e4041bd6758400c62e2c811831b98eed561}" storeLocation="LocalMachine" storeName="My"/>

    As you can see, you register your information about the certificate being used by your sts and the information about your application, the relying party.
    The line about the cookieHandler was the one that caused me some problems because I didn’t have that. The problem is that my local site was working on http and not https, but the created cookies required https. I didn’t have this line at first, which had the effect that the session cookie was not maintained over postbacks.

  6. After you’ve configured everything, you can use the following code to consume your STS and get an IClaimsIdentity:
    // authenticate with WS-Trust endpoint
    var factory = new WSTrustChannelFactory(
    new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
    new EndpointAddress("<a href="https://devsts/MySts.svc">https://devsts/MySts.svc</a>"));
    factory.Credentials.UserName.UserName = usernameField.Text;
    factory.Credentials.UserName.Password = passwordField.Text;
    var channel = factory.CreateChannel();
    var rst = new RequestSecurityToken
    RequestType = RequestTypes.Issue,
    AppliesTo = new EndpointAddress("http://myrelyingparty.nl/"),
    KeyType = KeyTypes.Bearer
    var genericToken = channel.Issue(rst) as GenericXmlSecurityToken;
    // Now you parse and validate the token which results in a claimsidentity
    var handlers = FederatedAuthentication.ServiceConfiguration.SecurityTokenHandlers;
    var token = handlers.ReadToken(new XmlTextReader(new StringReader(genericToken.TokenXml.OuterXml)));
    var identity = handlers.ValidateToken(token).First();
    // Create the session token using WIF and write the session token to a cookie
    var sessionToken = new SessionSecurityToken(ClaimsPrincipal.CreateFromIdentity(identity));
    //Perform some redirect

In our situation, this was not complete, since we need the SAML token received from the STS furtheron to authenticate to WCF services which we consume. After using reflector and trying something out, it can be easily done by changing just two lines of code. I can be done by the following:

var identity = handlers.ValidateToken(token).First();
Thread.CurrentPrincipal = new ClaimsPrincipal(new IClaimsIdentity [] { new ClaimsIdentity(identity.Claims, token) });

The code itself looks probably a bit strange, since we get a ClaimsIdentity from the ValidateToken and then we create another ClaimsIdentity. I hoped that WIF would have used this way to construct the identity, of at least provide an overload or something to do this. I created the identity like this, since the securitytoken is now availalbe in the BootstrapToken property of the ClaimsIdentity. At first we were thinking that we had to keep the security token in session but that is not necessary when you do it like this. Now we can access it simply with the following lines of code:

var identity = Thread.CurrentPrincipal.Identity as ClaimsIdentity;
var theOriginalSecurityToken = identity.BootstrapToken;

I hope this helps somebody else. It would have saved me a lot of time if I could have found this information somewhere.

Update (17-8-2010)

We’ve been using the code as listed above, but we ran into some problems, because the retrieved token is a GenericXmlSecurityToken which caused problems when supplying it to our backend services.

After some searching I found that it is possible to get the BootstrapToken property filled by WIF, but you need to set a configuration switch (some decent documentation would really be helpfull). All you have to do is change the following in your web application configuration (add the saveBootstrapTokens attribute):

<service saveBootstrapTokens="true>
<issuerNameRegistry ……

The code to creating your principal is then the following:

var identity = handlers.ValidateToken(token).First();
Thread.CurrentPrincipal = new ClaimsPrincipal(new [] { identity });

Now the BootstrapperToken is a SamlSecurityToken which is exactly what we want to be able to authenticate to the backend services. I’ll show in a new post how we have all this tied together.

Create a free website or blog at WordPress.com.

%d bloggers like this: