Thursday, December 2, 2010

C# Puzzle No.22 (beginner)

The .FirstOrDefault(…) LINQ’s method is quite handy until you realize that “default” in fact means default(T) which then means “null” if you deal with reference types. This could cause problems if you expect anything but null.

class Program
{
    static void Main( string[] args )
    {
        List<User> Users = 
             new List<User>() { new User() { Name = "u1" } };
 
        var name = 
            Users
                .FirstOrDefault( u => u.Name == "u2" )
                // boom! FirstOrDefault returns null
                .Name;
 
        Console.WriteLine( name );
        Console.ReadLine();
    }
}
 
class User
{
    public string Name;
}

What if you have a Null Object you’d like to provide as the “default” instead of default(T)?

class User
{
    public string Name;
 
    public static User NullValue
    {
        get
        {
            return new User() { Name = "NULL" };
        }
    }
}

The easiest workaround is to add an additional, overloaded version of FirstOrDefault which could accept a reference to an object which should be returned as the “default”:

class Program
{
    static void Main( string[] args )
    {
        List<User> Users = new List<User>() { new User() { Name = "u1" } };
 
        var name = 
            Users
                // use new, overloaded FirstOrDefault implemented below
                .FirstOrDefault( u => u.Name == "u2", User.NullValue )
                .Name;
 
        Console.WriteLine( name );
        Console.ReadLine();
    }
}
 
public static class LinqExtension
{
    public static T FirstOrDefault<T>( 
        this IEnumerable<T> Entites, 
        Func<T, 
        bool> Predicate, 
        T Default )
    {
        var entity = Entites.FirstOrDefault( Predicate );
 
        // return provided Default if there are no matching entities
        if ( (object)entity != (object)default( T ) ) 
            return entity;
        else
            return Default;
    }
}
 
class User
{
    public string Name;
 
    public static User NullValue
    {
        get
        {
            return new User() { Name = "NULL" };
        }
    }
}

Your goal is to achieve the same effect but with no new extension methods. In other words – you are restricted to the standard set of LINQ operators.

class Program
{
    static void Main( string[] args )
    {
        List<User> Users = new List<User>() { new User() { Name = "u1" } };
 
        var name = 
            Users
                // linq query here which returns the matching object
                // or User.NullValue as the "default"
                // so that this field reference below always succeeds 
                .Name;
 
        Console.WriteLine( name );
        Console.ReadLine();
    }
}
 
class User
{
    public string Name;
 
    public static User NullValue
    {
        get
        {
            return new User() { Name = "NULL" };
        }
    }
}

Wednesday, December 1, 2010

WIF, WS-Federation and Single Sign-out from Multiple Relying Parties

As I get into more and more details on WIF and all the WS-Federation related stuff, I’ve been extremely interested in how single sign out should work. While single sign-on is easy, the Identity Provider Security Token Service (IP-STS) maintains its own session (probably protected with Forms Authentication or similar mechanism) and responds to wasignin1.0 requests from federated applications (Relying Parties), the single sign-out should somehow involve sending requests to each single authenticated Relying Party to inform it that the user is about to sign out of the Identity Provider.

Unfortunately, the STS template generated by Visual Studio when you “Add STS Reference” and “Create new STS” is not very helpful. What it does it signs you out from a single RP:

else if ( action == WSFederationConstants.Actions.SignOut )
{
     // Process signout request.
     SignOutRequestMessage requestMessage = 
        (SignOutRequestMessage)WSFederationMessage.CreateFromUri( Request.Url );                
     FederatedPassiveSecurityTokenServiceOperations.ProcessSignOutRequest( 
        requestMessage, 
        User, 
        requestMessage.Reply, 
        Response );

Fortunately, there’s this fantastic book by Vittorio Bertocci, Programming Windows Identity Foundation, which covers WIF deeply while being very clear and understandable at the same time. Vittorio explains that the RP-side modules (FAM & SAM, responsible for negotiating and maintaining a session between the RP and the IP) respond to wsignoutcleanup1.0 message appended to any request to an RP page and the result of such request would be:

a) to destroy the session at the RP’s side

b) to return an image of a green check mark image to mark a successfull operation

What a handy idea! The sign-out from multie RPs, according to Vittorio, is then:

a) to keep track of consecutive RPs signing in via the IP at the IP side, Vittorio suggests that this information could be persisted in a cookie to save the IP’s resources but probably the session could also be used

b) to return a page containing multiple images with src attribute pointing to consecutive RPs with wsignoutcleanup1.0 when wasignout1.0 is requested from the IP (Vittorio’s book, page 121)

else if ( action == WSFederationConstants.Actions.SignOut )
{
    // Process signout request.
    SignOutRequestMessage requestMessage = 
        (SignOutRequestMessage)WSFederationMessage.CreateFromUri( Request.Url );                
    FederatedPassiveSecurityTokenServiceOperations.ProcessSignOutRequest( 
        requestMessage, 
        User, 
        null, // note the null here which does not force the redirect to the login page
        Response );
 
    string[] signedInUrls = SingleSignOnManager.SignOut();
    lblSignoutText.Visible = true;
    foreach ( string url in signedInUrls )
    {
        SignOutLinks.Controls.Add(
            new LiteralControl( string.Format(
                "<p><a href='{0}'>{0}</a>&nbsp;<img src='{0}?wa=wsignoutcleanup1.0' " +
                "title='Signout request: {0}?wa=wsignoutcleanup1.0'/></p>", url ) ) );
    }
}

Unfortunately, few details are missing here and this is the motivation of this entry.

First, it’s not possible to get a complete solution containing all the files. A link at O’Reilly site, which should probably point to book’s code samples, points to the WIF SDK which does not contain this particular example.

I’ve decided then to provide an implementation of this SingleSignOnManager class, which contains two methods. The SignOut is used in the above snippet to get the list of all RPs authenticated during the current user session. Another method, RegisterRP is used in the GetOutputClaimsIdentity of a SecurityTokenService at the IP’s side to store the information of the RP which authenticates via the IP:

/// <summary>
/// This method returns the claims to be issued in the token.
/// </summary>
/// <param name="principal">The caller's principal.</param>
/// <param name="request">The incoming RST, can be used to obtain addtional information.</param>
/// <param name="scope">The scope information corresponding to this request.</param> 
/// <exception cref="ArgumentNullException">If 'principal' parameter is null.</exception>
/// <returns>The outgoing claimsIdentity to be included in the issued token.</returns>
protected override IClaimsIdentity GetOutputClaimsIdentity( 
   IClaimsPrincipal principal, 
   RequestSecurityToken request, Scope scope )
{
    if ( null == principal )
    {
        throw new ArgumentNullException( "principal" );
    }
 
    // remember all the RPs to be able to perform a single sign-out
    SingleSignOnManager.RegisterRP( scope.ReplyToAddress );
 
    ClaimsIdentity outputIdentity = new ClaimsIdentity();
 
    // Issue custom claims.
    // TODO: Change the claims below to issue custom claims required by your application.
    // Update the application's configuration file too to reflect new claims requirement.
 
    ... 
 
    return outputIdentity;
}

The SingleSignOnManager would be as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace WebSTS
{
    public class SingleSignOnManager
    {
        const string SITECOOKIENAME = "StsSiteCookie";
        const string SITENAME       = "StsSite";
 
        /// <summary>
        /// Returns a list of sites the user is logged in via the STS
        /// </summary>
        /// <returns></returns>
        public static string[] SignOut()
        {
            if ( HttpContext.Current != null &&
                 HttpContext.Current.Request != null &&
                 HttpContext.Current.Request.Cookies != null 
                )
            {
                HttpCookie siteCookie = 
                    HttpContext.Current.Request.Cookies[SITECOOKIENAME];
 
                if ( siteCookie != null )
                    return siteCookie.Values.GetValues(SITENAME);
            }
                 
            return new string[0];
        }
 
        public static void RegisterRP( string SiteUrl )
        {
            if ( HttpContext.Current != null &&
                 HttpContext.Current.Request != null &&
                 HttpContext.Current.Request.Cookies != null
                )
            {
                // get an existing cookie or create a new one
                HttpCookie siteCookie = 
                    HttpContext.Current.Request.Cookies[SITECOOKIENAME];
                if ( siteCookie == null )
                    siteCookie = new HttpCookie( SITECOOKIENAME );
 
                siteCookie.Values.Add( SITENAME, SiteUrl );
 
                HttpContext.Current.Response.AppendCookie( siteCookie );
            }
        }
    }
}

As you can see, each consecutive RP is added to the list of RPs remembered in a cookie created by the IP. The only possible drawback of this implementation is that there’s a chance that the cookie will overgrow the legal limit of a cookie size.

The last but not least detail is to add two controls to the IP’s authentication page (Default.aspx in the template example), a label lblSignoutText and a panel SignoutLinks.

When you build your custom test environment consisting of a IP-STS and two (or more) RPs, as the result of a sign-out (the easiest way to trigger the sign-out is to use the wif:FederatedPassiveSignInStatus control which shows a sign-out link) you’ll note that signing out no loger incorrectly redirects to the login page in a context of a single RP (leaving all other RPs logged in!) but rather it shows a page with links to consecutive RPs and images of green check marks next to all links to indicate the succesfull sign-out.

A next step of my research is to build a “virtualized” IP-STS, which serves as the IP for different data sources but from a single web application.

Wednesday, November 24, 2010

How to hire a skilled programmer?

There are wide and long discussions on how you can test programmers who apply for a job with you/in your company. Most of developers have some experience on that (because they apply for jobs themselves), few of them are actually on “the other side” and have to somehow pick the best from the best. The most skilled from skilled.

I am not going to elaborate on what is better, to freely talk to candidates, to order them to write code online, write code offline or to let them answer a dozen of specific questions to score points for correct answers. All these have their pros and cons and, based on my own experience and from what others say, it all depends on the specific profile, the size of the company, the kind of the job, the amount of candidates etc.

What works best for me (since I am responsible for the technical part of the recruitment procedure) is to ask candidates to write a simple but complete application focused on a precise specification. It could be a simple SQL query generator for POCO classes or a core of an IoC container. It does not really matter whether or not a candidate recognizes the notions from the specification, for example people implement perfect IoC containers based solely on my specs with no prior knowledge of what an IoC container is. They are allowed to work offline for few days (although for someone experienced the implementation should not take longer than few hours) and then we meet to discuss the details of the implementation. This is where I ask every candidate to write something fast, on demand, using only a pen and a sheet of paper. This could be “a method to sum an array of ints” or “a method to reverse a string”. People usually do some subtle mistakes so I test how they adopt to “I am a test engine and your implementation seems to throw NullReferenceException which is not expected, please correct this”.

After both these tests I know that:

a) the candidate can read, understand and follow a written specification even if he/she does not recognize some notions

b) the candidate can work under a pressure and knows the programming language well enough to implement a simple algorithm without a compiler at hand (from which I conclude that the real knowledge of the language, with the compiler at hand, is much deeper)

For some time, however, I am thinking of making some changes to the way the process is organized. Instead of a pen, sheet of paper and a consise, short specs of a tiny method, I am thinking of a virtual web-based environment, containing a text editor and a compiler so that the candidate could follow a more complicated specification, write, compile and test the code he/she submits as the proposed solution.

There are two great examples of how this could look like:

1. Codility. It’s a web-based environment where candidates are presented with a concise and precise specs of an algorithmic task and they can invoke a compiler (which sits on the server) to actually compile and test the solution. The engine performs some tests on the server-side so it not only detects that the implementation misses the specification (I wonder if Codility tests are hard-coded so that it’s possible to write a code which only solves the test cases by hardcoding the answers for test cases?) but also detects the complexity of the solution (so for example if a linear solution is expected, you get a lower score for a solution with quadratic complexity).

2. Pex for Fun. It’s actually pretty smart. Pex is an engine which follows all the control flow paths in given code and generates a complete set of test cases. Based on that, Pex for Fun has a “secret” implementation of a simple method (like “take x and return x * x”) but you are not allowed to see the implementation. Instead, you have to provide your own implementation for which the engine generates a set of test cases and feeds the secret implementation with it (and vice versa). You are then presented with a list of test cases both your and secret implementations and if there are some differences in the output, you have to change your implementation and follow the validation procedure until your implementation is semantically equivalent to the secret implementation (all test cases produce the same output for your and secret implementations). Beside being extremely fun, this one not only checks if someone writes a correct code but also – to what extent he/she can adopt to changing conditions (the answers of the Pex comparing engine change each time you ask it for comparision, as you change your implementation).

While implementing a custom solution which somehow follows the idea from Codility seems easy, I wonder if presenting “Pex for Fun”-style task for a candidate would be as fun for a candidate as it surely would be for me watching people who try to solve such puzzles :)