Implementing OpenId with ASP.Net MVC

January 16, 2009

OpenId is awesome. I first discovered it when I started using OpenId allows users to create a single account that they can use to login to any website that accepts it. All the user has to do is create an account with an OpenId provider (I happen to use The nice thing about this for developers is that it completely offloads all the managing of users, profiles, passwords, authentication, and other headaches associated with developing a site to someone else.

Here is a diagram and an explanation of the sign-in process.

Get a Provider
The first thing you need to do is to setup an account with an OpenId provider. RpxNow has a “Basic” package for free that has everything you need to get started. They also allow users to sign-in using their existing accounts fomr places like Facebook, AOL, Google, and several others. This is awesome if you don’t want your users to deal with the hassles of createing yet another account.

Add a Login Link
Now we need to provide a link to allow the user to sign-in to our site. Add the following code in the <Head> section of your page.

<script src="" type="text/javascript"></script>
<script type="text/javascript">
        RPXNOW.token_url = "";
        RPXNOW.realm = "myRpxAccountName";
        RPXNOW.overlay = true;
// -->

Then add the Login link to your page:

<a class="rpxnow" onclick="return false;" href="">Login</a>

A couple of things to note here. The “myRpxAccountName” is the developer account you get when you register with RpxNow, and the “; link is where the authentication token gets sent (you’ll see this part below). Also, the only thing really needed for the link to work is for it to have a the “rpxnow” class assigned to it.

Setup Controller Action
Once the user logs in through they’re OpenId provider we get an authentication token returned to us. It gets sent to the “; link we specified above. Using the “Default” routing of {controller}/{action}/{id} we can setup our controller like this:

public class AccountController : Controller
     // Matches
     public ActionResult Login(string token)


Get User Information
The most complicated part of the process is sending the token to the Rpx Webservice and getting the user profile information back. The good news is they give us the code to help use get started. I’ve modified the code slightly which you can download at the end of this post.

public ActionResult Login(string token)
     XElement profile = Rpx.GetProfileData(token);

/* Example of returned data.
    <rsp stat="ok">
          <formatted>Micah Martin</formatted>

    //Determine if user is new and if so then create
    //a new record in the database and map the recordId
    //to the openId
       Rpx.Map(openId, userId);

    //Login user
    FormsAuth.SetAuthCookie(username, rememberMe);
    return RedirectToAction("Index", "Home");

Essentially what happens here is we call into the Rpx webservice and get the profile data back. You then determine if the user already exists in the database. If not then create a new record and pass the new record Id along with the OpenId (in my case into the Rpx.Map function. Now all future login requests for the user will contain a <primaryKey> node with recordId of the user. Last thing to do is just call a FormsAuth function to finish the login.

All told it probably took less than 45 minutes to get it implemented. The longest part was understanding the work flow, and even that wasn’t bad. I hope this has been helpful. You can download the Rpx class file Here Rpx. You will need to rename it from .doc to .cs.

kick it on


Solution: Styling a large amount of controls

December 11, 2008

I’m really on this “Attached Property” kick. I’m probably totally over using them, but I think it’s such a powerful tool when used in the right scenario. I’m not really sure what the right scenario actually is, but I keep running into situations where to me they just make sense. Also there’s something about adding behavior to objects without actually inheriting from them that gives me a sense that I’m doing something really cool, cutting edge, and adventerous…alright that’s a little ridiculous. Moving on…

So I had posted a question on StackOverflow (by the way this is such an awesome site) and also wrote here about finding the best approach to applying styles to a large amount of controls. I spent an hour or so on the phone with Karl Shifflett discussing the pro’s and con’s of the various approaches to take which I wont re-hash here. I finally landed on this idea that uses my good buddy DependencyProperty.RegisterAttached.

What I’ve done is create 4 styles in a resource dictionary

  1. A style for the containing panel (i.e. Grid, StackPanel, etc.)
  2. A style for the first item(s)
  3. A style for the last items(s)
  4. A style for all the items in between


The reason I create different styles is that depending on where the object is in the panel I may want to apply more or less margin, or to different amounts on different sides. Obviously this is just one particular scenario, but you get the point. Then I set the the attached property on the containing grid like this (can also be a StackPanel/DockPanel):

<Grid local:AttachedProperties.IsStandardContainer="True">

Essentially what the attached property does is iterates through all the children in the Panel and applies one of the specified styles to each element. Care is taken not to override any explicit styles set on any child objects.

Here is a full example including the code for the attached property. Make sure you change the extension from .doc to .zip.

kick it on

Consolidating XAML Namespaces

October 9, 2008

I’m working on a project that has numerous namespaces. Each time I need to use a class in XAML I have to add a new namespace declaration to the XAML file. This quickly becomes unwieldy when you start using multiple namespaces like this:


Then of course you have to figure out what namespace each item is in order to use in XAML.

An easy way around this is to consolidate all of the namespaces at the assembly level using the XmlnsDefinitionAttribute from the System.Windows.Markup namespace. In the AssemblyInfo.cs (or .vb) you add this attribute for each namespace you want to consolidate like this:



There is an optional parameter you can pass in that specifies which assemblies the namespaces live in. This allows you to consolidate namespaces across multiple assemblies.

Now back to our XAML, we can blow out all of these namespace declarations for a much simpler, cleaner approach:


kick it on

WPF Record Navigator (VCR) Control

October 5, 2008

I haven’t seen any examples of a record navigator in WPF so I decided to create one.

What it is:

  • Allows you to bind to a collection of elements and navigate through each one.

What it isn’t:

  • Currently it doesn’t have any hooks for styling.
  • The Current Index is read-only and can only be navigated using the buttons.

The implementation is pretty straight forward. It uses routed commands to handle all the navigation. The trick to making the implementation simple was to forward everything on to a ListBox. The template contains a ListBox named “PART_List” which has it’s visibility set to Collapsed. This allows me to bind the TextBlocks that display the Count and Current Position directly to the ListBox. Also for all of the navigation commands, the Command Executed handlers simply forward their calls to the corresponding methods on the ListBox. The ListBox also just binds it’s ItemsSource and IsSynchronizedWithCurrentItem directly to the corresponding Dependency Properties on the RecordNavigator.

I hope this control is useful to some of you. I’ll be further refining it to support styling and allow the user to jump to a specific index. Please give me any feedback you have. If there is any bugs or anything it should do that it doesn’t, please let me know.


You can download the code here: record-navigator. Make sure to change the extension from .doc to .zip.

kick it on

Changing the Data Template for the Currently Selected Item

September 28, 2008

Let’s say I have some sort of list control and I want to show or hide additional information for an item based on whether or not it is currently selected. The easiest way to do this is to create two separate DataTemplates and swap them when needed (For brevity this example just changes the color of the selected item, but this can easily be modified to show more complex information).

Typically when you create a data template for an ItemsControl you create it as a resource and set the “ItemTemplate” property like this:

<DataTemplate x:Key="ItemTemplate">
    <TextBlock Text="{Binding}" Foreground="Black"/>
<ListBox ItemTemplate="{StaticResource ItemTemplate}" />

Behind the scenes WPF is actually wrapping each one of our TextBlocks in a ListBoxItem control. In other words, our DataTemplate get’s set as the Content of the ListBoxItem (which inherits from ContentControl). This ListBoxItem is where the IsSelected property lives that we need to get a hold of in order to swap out our data template. What we need then is to setup a trigger for the ListBoxItem when the IsSelected property changes.

<DataTemplate x:Key="ItemTemplate">
    <TextBlock Text="{Binding}" Foreground="Black"/>
<DataTemplate x:Key="SelectedTemplate">
    <TextBlock Text="{Binding}" Foreground="White"/>
<Style TargetType="{x:Type ListBoxItem}" x:Key="ContainerStyle">
    <Setter Property="ContentTemplate" Value="{StaticResource ItemTemplate}" />
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="ContentTemplate" Value="{StaticResource SelectedTemplate}" />

Now the ListBox declaration looks like this:

<ListBox ItemContainerStyle=”{StaticResource ContainerStyle}” ItemsSource=”{Binding MyData}” />

One thing to take note of here is that I am no longer setting the ItemTemplate property on the ListBox. Instead It is being set through the ContentTemplate property of the ListBoxItem. The reason is that setting it directly on the ListBox overrides the ContentTemplate property of the ListBoxItem.

Download the full code here: data-templates-example-092808. Remember to change the file extension from .doc to .zip.

kick it on