NameValue, now with Distinct() support

One of the more useful little classes in my utility box is NameValue. It’s so veryeasy to fill with useful data from a Linq query, and once filled so easy to move betweenlayers, in a way that a projection simply can’t be used. The simple little NameValueclass bind just fine to a drop down menu, and will bring you tea after you finishwith that stupid girl that didn’t like your pony/monkey chimera.

I recently had to add equality checks and an override for == and != in order to makemerging two lists of name value pairs together possible. Now .Distinct() works ona List<NameValue>! There’s some goodmaterial out there for how to make a quality equality implementation.

[Serializable] public class NameValue{ public object Name{ get { return _Name;} set {_Name = value;} } protected virtual object _Name{ get; set;} public object Value{ get { return _Value;} set {_Value = value;} } protected virtual object _Value{ get; set;} public override bool Equals(object obj){ if (obj == null) return false; if (this.GetType() != obj.GetType()) return false; // safebecause of the GetType check NameValuenv = (NameValue)obj; // usethis pattern to compare reference members if (!Object.Equals(this.Value,nv.Value)) return false; if (!Object.Equals(this.Name,nv.Name)) return false; return true;} public override int GetHashCode(){ return Name.GetHashCode() ^ Value.GetHashCode();} public static bool operator ==(NameValuen1, NameValue n2) { return n1.Equals(n2);} public static bool operator !=(NameValuen1, NameValue n2) { return !n1.Equals(n2);} }

Simple ASP.NET Custom Forms Authentication

So, I’ve been a really happy CSLA.NET user for a while, but I’ve been finding thatgenerating the code has becoming tedious and my development velocity has been slowingdown on my CSLA libraries. And so, rather than getting back involved with blood sacrifice,I figured I’d experiment with another layer in there. I’m currently working up somecode with LLBLGen Pro (becausellblgen lite is for suckers!), and it’s working great….but Rocky made it so easyto do forms authentication with CSLA. It was just a couple’a pages in the book andit worked just fine and ….well…. I don’t understand how it works. Now that I’mnot including his framework, I need to figure it out.

So, follow along with me as we figure it out. Here’s how it’s done.

Step 1: Some configuration

First thing I tried was putting a Label on a form and assigning HttpContext.Current.User.ToString()to it. The result? “System.Security.Principal.WindowsPrincipal”

Right. My application is still out-of-the-box set to Windows authentication (Kerberos.ActiveDirectory. NSA Backdoor.) Let’s change that.

<?xmlversion=”1.0″?> <configuration> <system.web> <authentication mode=”Forms” /> </system.web> </configuration>


Good. What’s in that label now? “System.Security.Principal.GenericPrincipal” Muchbetter.

Step 2: The Password is ‘Joshua’!

This step is a big one. There are 27 members defined in the MembershipProvider contract,so go get some coffee, lithium, and a rotisserie chicken, and we’ll get started.

Make a new class, call it MyMembershipProvider.cs. Make it extend MembershipProvider:

using System; using System.Web.Security; using System.Web; namespace Website1{ public class MyMembershipProvider: MembershipProvider


Go ahead and let Visual Studio define all of the inherited members. We’re only goingto change one:

public override bool ValidateUser(string username, string password){ return true;}


Now we’ve got another little configuration change to make.

<configuration> <system.web> <authentication mode=”Forms” /> <membership defaultProvider=”HscMembershipProvider”> <providers> <add name=”MyMembershipProvider” type=”Website1.MyMembershipProvider” enablePasswordRetrieval=”false” enablePasswordReset=”false” requiresQuestionAndAnswer=”false” applicationName=”/” requiresUniqueEmail=”false” passwordFormat=”Clear” /> </providers> </membership> </system.web> </configuration>


Go head and drop a Login control and a LoginStatus on the form and try it out. Itlogs you in! No matter what you enter! Sure, you could put in some code that checksagainst your database to see if people are allowed in or not, but that’s just elitist,isn’t it? Creating an ‘In-group’ and an ‘Out-group’ and segregating them? Next thing,you’ll be wanting to beat up blue eyed people because they prefer Lord of the Ringsto Star Wars. Well, if you’re going to put in some authentication code, go for it.I won’t stop you.

Step 3: The Principal’s Orifice

Ok. So there’s a little gotcha at this point. If all you’re looking for is a loginand password check…then it’s time to feed your brain to the zombies, ’cause youwon’t need it anymore. But if you want more than just a username logged in, we’vego some stuff to do. Forms auth never gives you anything but the GenericPrincipal.It will be marked ‘IsAuthenticated’ if it is…and you can use the Roles providerto fill in the roles if you want. It also looks like it’s possible to fill in theroles manually using an event handler in Global.asax.

But here’s the thing. While I really dig on the login functionality of ASP.NET Membership,I’m not so convinced that Roles or Profiles provide a meaningful, robust implementationthat’s useful for more than a toy web forum. Can you give the branch manager for theSalem office full privileges to the customers there without letting him check on PresidentObama’s secret pornography transactions at the Hillsboro branch? With just IsInRole(string)?It sure doesn’t seem like it. The major advantage of Profiles seems to be that youcan use web.config to define the fields….which is great until the point where youwant to find all users within 50 miles of Denver….and then you’re stuck in an abandonedwarehouse with the vampires. Serialized XML doesn’t query too very well. There’s probablysolutions to these problems, but not out-of-the-box and why work really hard to havea decoupled design with a provider model that is so customized and complicated toimplement that you won’t ever be swapping it out?

This is a job for a Custom Principal. That’s what it is. Implement just enough tomake the ASP.NET controls happy and then add the real meat to your own object. Theprincipal also encapsulates an IIdentity object. You could go ahead and implementboth of these, but since I’m lazy and want to go play Rock Band, I’m going to do bothin onefell swoop. (Note that this is untested, and may put cracks in your DilithiumCrystals requiring embarrassing compromises with pimps.

using System; using System.Security.Principal; namespace Website1{ [Serializable()] public class MyPrincipal: IPrincipal, IIdentity { public static MyPrincipalLogin(string username, string password){ MyPrincipal loginUser = new MyPrincipal(); if (!string.IsNullOrEmpty(password)){ loginUser.Name = username;loginUser.IsAuthenticated = true; return loginUser;} return loginUser;} public bool RussianRoulettePermission(){ Random random = new Random(); if (random.Next(1, 6) == 3) return false; return true;} #region IPrincipalMembers public IIdentityIdentity { get { return this;} } public bool IsInRole(string role){ return false;} #endregion #region IIdentityMembers public string AuthenticationType{ get { return Custom;} } public bool IsAuthenticated{ get; private set;} public string Name{ get; private set;} #endregion }}


I accept that you and your fascist friends will probably want to do more passwordchecking than making sure that the user typed a letter. Goodfences make good neighbors, right? The real point is that you can put your ownCrazy User Code in here and have it available when your pages want to use it.

Now we can fix the Membership Provider to use our new shiny principal object!

public override bool ValidateUser(string username, string password){ HttpContext.Current.User = MyPrincipal.Login(username,password); return HttpContext.Current.User.Identity.IsAuthenticated;}


Give it a try!

Step 4: Dammit!

I set Current.User to my Principal. I did. I did. I did. Why doesn’t my damn labelchange from GenericPrincipal when I log in? It’s cheesin’ me off here!

The problem here is the Forms Authentication uses it’s own principal and sets thecontext to it on each page load. This is what it’s supposed to do, but we want better!We’re going to add a few methods and fix the problem. One caveat here (and why dopeople want to eat caves? And which Cave are you At when that happens? Where’s mylithium?): I’m going to trust the forms authentication cookie. I think that’s enoughof a ticket to bypass password authentication. If you don’t, you might want to jumpthrough some extra hoops. I’m also trusting that my developers won’t use the bypassmethods to create secret login backdoors and the like. I figure if you can’t trustthe coders then…well, you work at my office. But anyways….

To the principal!

public static MyPrincipalGetLoggedInUser(string username){ MyPrincipal loginUser = new MyPrincipal();loginUser.Name = username;loginUser.IsAuthenticated = true; return loginUser;} public static MyPrincipalGetLoggedOutUser(){ return new MyPrincipal();}


And in Global.asax!

protected void Application_AcquireRequestState(object sender,EventArgs e) { if (User.Identity.IsAuthenticated){ HttpContext.Current.User = MyPrincipal.GetLoggedInUser(User.Identity.Name);} else {HttpContext.Current.User = MyPrincipal.GetLoggedOutUser();} }


Step 5: And now for a magic trick.

Happy Day! Kill Ugly One-Horned Mule!

My cheap and dirty Membership implementation works. Now I can put this in my Form_Loadmethod:

Label1.Text = You’reLogged in: +HttpContext.Current.User.Identity.IsAuthenticated + Andyou’re dead!: + ((MyPrincipal)HttpContext.Current.User).RussianRoulettePermission();


Sweet! You can find out if you’re logged in. And if you’re dead. All at the same time.

Next Steps: Drunk on Cookie Magic

Obviously we’re going to need some code to check passwords. Probably fetching againstthe database. No problem. I’m planning on encapsulating my DTOs from LLBLGen intomy principal. That way I can expose read access to user objects for the logged-inusers. I can also put in complex permissions right there. I’m going it my way.Sweet!

It’s worth noting that this implementation goes off to the DB for each page load.That can sure suck up the performance points under a real load. However, a littlebit of effort can store the principal in the session object and then you get it back,deserialized, instead of requiring a round-trip. Just remember to code for the casewhere the session expires, but the forms cookie does not.


until next time, remember: the skin is the best part.

Installing Visual Studio 2005 on Vista 64

Wouldn’t you know it? I have my shiny new Vista machine all built and hopping alonghappily, and I need to do a quick recompile of one of my old VS2005 projects. Luckilymy 2005 disc is right here. This should be easy, right?

Things you’ll need:

  1. Visual Studio 2005 install media and key.
  2. 30g powdered aluminum.
  3. VisualStudio Team Sweet 2005 SP1 (KB 928957). You might think you need an x64 versionof this…but you don’t so don’t worry about it.
  4. 80g iron oxide powder.
  5. VisualStudio 2005 SP1 Update for Windows Vista (KB 929470). Again you only need thex86 version.
  6. A length of magnesium ribbon.
  7. A brazing torch or other high-heat fire producer.

The process:

  1. Insert the VS2005 disc, and start up the setup. Enter your keys and the like. Getthe thing started.
  2. This is going to take a while, so if you haven’t gotten the other ingredients listed,now’s the time to get on eBay and order some up.
  3. At certain points during the install, Vista and the setup will complain that it’snot compatible with Vista and ask you to confirm that you should run certain command.Go ahead and accept/allow all those warnings.
  4. Run the installation to completion.
  5. Execute the Visual Studio SP1 installer.
  6. By this time, the packages will have arrived from eBay, unless you used UPS, in whichcase, there will be a sticker on your door and the packages will be available until1pm at the local depot. Go pick them up.
  7. When you get back the installer should be done.
  8. Run the Update for Vista.
  9. While this is working, mix the aluminum with the iron oxide. They aren’t reactiveat room temperatures, so you really don’t need any special apparatus, but I alwaysrecommend using a filter mask and eye protection when working with powdered chemicals.The mix is unbalanced by weight, but should be about even by volume. Mix them togetherin a bowl or styrofoam cup until very even. If you’d like, you can then mix the resultingmixture 4:1 with playdoh (more thermite than dough) for portability, or just leaveit in the cup.
  10. Once that installer is done, you should be FINALLY able to run Visual Studio.
  11. Place the magnesium ribbon into the cup of thermite, and tape over the top to preventspills. Leave the cup on top of your computer, with the torch handy. I find that havinginstant flaming death hanging over my machine’s head keeps the poor thing in a stateof terror. It prevents so many of those lazy blue screens and has really improvedmy Vista file copy performance. (I think it’s afraid to run that darned search indexernow.)