How to Install/Using NantContrib BECAUSE THE DOCUMENTATION SUCKS

I understand I’m not what you call the sharpest bulb in the bunch, but readmes shouldn’t be painful. They should be helpful. They should be kind and gentle, and remind you that the world is great and wonderful. Not put you on the verge of a three figure body count. In a way, this is why I’ve shied away from a lot of open source stuff since the readme files read like instructions for putting together something from IKEA. And not the horrible broken English ones, more like the ones with all those funny squiggly lines. (I think it’s call “Chinese”) Why is it always so painful to figure something out WHEN YOU HAVE INSTRUCTIONS? Best hint on writing instructions, always assume the person you’re writing to is an idiot. You can infer from that whatever you want.

Anyhow, NantContrib, the library of things that adds on to Nant (With brilliant ideas like being able to add an else to an if WOW), is a victim of nothumanenoughtowriteadecentreadmefileinawaythatnormalhumansunderstanditis (Otherwise known as Thoreau Syndrome) so I thought I would save you some together time between your head and your monitor.

Now you could go download it from wherever it is, or you can just grab this which is nantcontrib post “fixing” it. Basically if you get my version, all you have to do is drop it somewhere, anywhere, and extract. I put it in the same directory that Nant is, so they sort of sit side by side but separate. A happy little couple, at least for the first few years until Nant has a mid life crisis and decides it’s time to get a Corvette and start rolling for college girls at which point nantcontrib starts eying the Fedex guy. Right now, its idealistic bliss.

Once you’ve done that, all you have to do is drop this bit into your nant script, probably above your properties, but it possibly can go other places. I haven’t really looked into that.

<loadtasks>
  <fileset>
    <include name="c:\nantcontrib\bin\lib\" />
  </fileset>
</loadtasks>

And now you are ready to go.

Now you might be curious about what I did to the directory structure of the nantcontrib stuff. It’s actually pretty simple. I just took the bin folder and split it up. (Something I kind of pieced together from random pages) I took what I understand to be the important stuff (All the dlls except CollectionGen.dll and SlingShot.core.dll.. wait I’m sorry SLiNgshoT.core.dll cause f—ed up casing means its that much better. ITS HARDCORE MAN! TO THE XXXXXXXTREEEEMEEEE!) and put it into a new folder “lib” that still resides in the bin folder. The rest of the stuff went into a new folder “tasks”. Then I had the loadtask command include everything in bin\lib. Boom, everything works as it should.

Force Embeded Video Behind A JQuery Modal Dialog

Another quick one, [insert joke about sexual performance… HAHAHAHEHARHAHRAH] and I’ll probably file this under “I don’t care you if need this but I’m posting it because I have a bad memory”. When you use the jQuery Modal Dialog with an embedded video, like say something from youtube, and you have a modal dialog on the same page, you might notice that the video stays in front of the dialog. This would be considered contrary to design. Nice thing is, it’s an easy fix:

<object class="nospace" data="http://www.youtube.com/v/jU_lNNwCLp0&hl=en_US&fs=1&" height="320" type="application/x-shockwave-flash" width="400" >
  <param name="movie" value="http://www.youtube.com/v/jU_lNNwCLp0&hl=en_US&fs=1&" />
  <param name="allowFullScreen" value="true" />
  <param name="allowscriptaccess" value="always"/>
  <param name="wmode" value="opaque"/> <----- RIGHT THERE LOOK SEE IT?????
</object>

It’s the last parameter in that block. I posted the whole thing because it just seemed easier.

Element ‘Embed’ Is Not Supported: Embedding YouTube Video Without The Embed Tag

This should be quick, so don’t expect my usual charming self. If you’ve run into this problem, and chances are you have, you’re probably as frustrated as a thumbless hitchhiker. Good thing is, I have the solution and you can watch it here on video:

HAHAH THAT WAS FUNNY! Yeah I’m not that big of a bag. I actually will give you the code. Go figure.

<object class="nospace" data="http://www.youtube.com/v/jU_lNNwCLp0&hl=en_US&fs=1&" height="320" type="application/x-shockwave-flash" width="400" >
  <param name="movie" value="http://www.youtube.com/v/jU_lNNwCLp0&hl=en_US&fs=1&" />
  <param name="allowFullScreen" value="true" />
  <param name="allowscriptaccess" value="always"/>
</object>

And there it is. Easy as something other than pie because pie isn’t f—ing easy to make.

Using Subversion With Nant: Automated Checkouts From Config File

This is the first part of a I HAVE NO CLUE HOW MANY part thing involving Nant and how to use it to make your life easier. Of course you might wonder why I’m using Nant over say MSBuild, (Though I’m sure you were actually wondering if you really can get ripped in two weeks) and I have no real reason other than at some point this will tie into Cruise Control for easy deployments. Fact is, the debate between nant and msbuild is an ongoing war between the hopeless broken records known as Microsoft haters and the mindless Microbots. Personal, I don’t really care since they are both fine. I may some day switch to MSBuild but for the scope of this article that MIGHT BE A BIT STUPID AND HYPOCRITICAL.

Also you might wonder about why I’m using subversion instead of say Team Foundation Server. (And no you can’t get ripped in two weeks) Probably has to do with the 10k I don’t have to shell out for something that is about two generations behind subversion… and that’s saying something since subversion is about two generations behind source control in general. But my subversion hosting is 3.95 a month. So it really comes down to what is the only thing that matters when developing: Money.

Say you have someone new coming in and you want to be able to have said person be able to get a project from a subversion repository without really thinking. (You can’t assume new people think.) This is mostly helpful because chances are you’re place of employment is a revolving door just like every other place. So the thought of automation comes to mind. What if I told you getting things from a subversion repository is as easy as a config file? “Balderdash!”, you say. “The f— is balderdash?”, I reply. And at somepoint we talking an common language and I show you this:

<project name="ToolInstall" default="download">
  <property name="toolProject" value="ToolsProject" />
  <property name="svnLocation" value="c:\program files\subversion\bin\svn.exe" />

  <target name="clean" description="cleans build directory">
    <delete dir="${toolProject}" verbose="false" failonerror="false"/>
  </target>

  <target name="download" description="gets projects from repository" depends="clean">
   <exec program="${svnLocation}" commandline="checkout http://some.repository.com/trunk/src/ToolProject ToolProject --username tool --password somepassword"/>
  </target>
</project>

What’s all of this? Well I am here to break it down. Oh Oh Whoooaaa.

<project name="ToolInstall" default="download">

First element of the file has to be project. The name isn’t all that important to this example, however Default means whith taget it will run first if you don’t tell it.

  <property name="toolProject" value="ToolsProject" />
  <property name="svnLocation" value="c:\program files\subversion\bin\svn.exe" />

Think of a Property as a variable. They just allow you to take out as many repeated strings as possible. You’ll see that the svnLocation Property points to where subversion was installed. This will vary per computer if you didn’t specify the name of the install directory.

  <target name="clean" description="cleans build directory">
    <delete dir="${toolProject}" verbose="false" failonerror="false"/>
  </target>

A target is basically a task you need to have done. It could be anything from deleting junk, running tests, or getting you a date. (HAHA ITS FUNAY CAUSE THATS IMPOSSIBLE) For this one, it is simply removing a folder that may exist. You can use this same idea to remove bin and obj folders if you use nant to build your project or simply clean it… But I’ll get to building in another post.

  <target name="download" description="gets projects from repository" depends="clean">
   <exec program="${svnLocation}" commandline="checkout http://some.repository.com/trunk/src/ToolProject ToolProject --username tool --password somepassword"/>
  </target>

And there’s the best part of the post, using nant to grab something from a subversion repository. As you can see, I’ve used the svnLocation property to make it easier to set what Program to use. I think this target is pretty much self explanitory for anyone with an IQ higher that that of a potato.

Next step is just to create a batch file to call nant and run this config file. Let’s assume you called it Nant.install. I know, it’s so descriptive, it’s genius. Shut up, I get the sarcasm.

Here’s the batch file:

@..\nant\nant.exe -buildfile:Nant.install

Mind you @..\nant\nant.exe will change depending where your copy of nant.exe is, but I figured I leave that in the way it is just to show that it doesn’t have to reside in the same place.

And there you have it, subversion and nant together like two children frolicking in the forests of Bavaria. (Assuming they have forests there and me mentioning kids isn’t creepy) In my next post I’ll probably go more into nant itself, this was just kind of on a whim. And I don’t know why I am appologizing for this. Stop f—ing judging me.

How to Use a Factory Method With Castle / WindsorContainer

In my last post, I showed you the wonder of the WindsorContainer and creating concrete objects from a config file… but I wasn’t done yet. In fact, if you looked at my example and used your keen sense of observation (I’m suspending my disbelief) you might have noticed a little somethin’ somethin’ in the config file that I didn’t explain:

  <component id="factoryB"
    type="CastleConfigTest.Factory.FactoryB, CastleConfigTest">
  </component>

  <component id="childClassB"
   type="CastleConfigTest.Interface.IBaseClassB, CastleConfigTest"
   factoryId="factoryB"
   factoryCreate="Create">
  </component>

And:

  <facilities>
    <facility id="factorysupport" type="Castle.Facilities.FactorySupport.FactorySupportFacility, Castle.Microkernel" />
  </facilities>

What are these??? Could they be the proof of intelligent life we’ve been looking for? Sadly no, since they actually are part of something that sounds a lot more complicated then it is. Say you have this interface:

  public interface IBaseClassB
  {
    String ClassName();
  }

And this class:

  public class ChildClassB : IBaseClassB
  {
    public String ClassName()
    {
      return "ChildClassB";
    }
  }

Which is all pretty straight forward much like that woman’s answer to you asking her out, “God no.”

If you had read this post, you might guess where this is going. Or you might guess that I’m going to re-explain it because you are too lazy to go and read it. One of those is correct.

Once again like my last post I do something simple like this:

  var test = new ObjectFactory().Create<IBaseClassB>();

And what I get is a brand new shiny ChildClassB. I can hear the yawns from here SO I’ll change it up a bit. What if I need ChildClassB to come from a Factory? How the hell would I pull that off?

  public class FactoryB
  {
    public static IBaseClassB Create()
    {
      var test = new ChildClassB();
      //Do some stuff to test
      return test;
    }
  }

I no longer can just replace IBaseClassB with ChildClassB directly because I need FactoryB to do something for me first. (I cheated by just adding a comment where code might go.  Point is, something happens to ChildClassB before the factory returns it.) OH NO! WHAT AM I TO DO? HOW CAN I SOLVE THIS? DOES THE CAPSLOCK ADD SUSPENSE?

Guess what? That’s right, that’s where that config stuff at the top comes in. Here’s the config file in full:

<configuration>
  <components>
    <component id="factoryB"
      type="CastleConfigTest.Factory.FactoryB, CastleConfigTest">
    </component>
    <component id="childClassB"
     type="CastleConfigTest.Interface.IBaseClassB, CastleConfigTest"
     factoryId="factoryB"
     factoryCreate="Create">
    </component>
  </components>
  <facilities>
    <facility id="factorysupport" type="Castle.Facilities.FactorySupport.FactorySupportFacility, Castle.Microkernel" />
  </facilities>
</configuration>

Ok so I lied, that’s not the full thing I have in my example that you can download, but it is what you need for this part. It’s actually pretty simple too. You just need to declare three things:

The factory class “FactoryB”

    <component id="factoryB"
      type="CastleConfigTest.Factory.FactoryB, CastleConfigTest">
    </component>

The interface you want to mask with the factory return (IBaseClassB)

    <component id="childClassB"
     type="CastleConfigTest.Interface.IBaseClassB, CastleConfigTest"  //This is the interface to look for
     factoryId="factoryB"  //This is the id from above where you declared the factoryB section
     factoryCreate="Create">  //This is the method to use
    </component>

and the Castle part for using factories

  <facilities>
    <facility id="factorysupport" type="Castle.Facilities.FactorySupport.FactorySupportFacility, Castle.Microkernel" />
  </facilities>

And that’s really it. From that, this should work:

    [TestMethod]
    public void Create_ClassB()
    {
      //This will call FactoryB.Create to create the ChildClassB for me
      var test = new ObjectFactory().Create();
      Assert.IsTrue(test.ClassName().Equals("ChildClassB"));
    }

Woo hoo! Now you can run home and impress your Wife/Husband/fiance/partner/thing that lives in your apartment and always seems to pay the rent late but doesn’t have any issue with eating everything in your fridge! Enjoy!

Castle, Rhino, Mocking, and Possibly You

So here’s the issue, you have a class that you new up within a class.

class SomeClass
{
  private HelperClass someHelperClass;

  public SomeClass()
  {
    someHelperClass = new HelperClass();
  }

  public String DoSomething()
  {
    return someHelperClass.DoSomeThing();
  }
}

You with me? Cause if you’re not, you’ve probably made a serious error in career choice.

Now what’s the problem with that situation? Testing. That SomeClass is tightly coupled with the HelperClass so that if you want to unit test DoSomething, you’re kind of screwed. Why? Say HelperClass has a database connection or does something that would update the database? Do you really want to create bad data every time you run this test? Do you really want the overhead of creating those connections and who knows what else? If you answered yes, again reconsider your career.

Now you could do something like this:

class SomeClass
{
  ....
  public SomeClass(HelperClass injectAHelperClass) <-- Change is right here genius.
  {
    someHelperClass = injectAHelperClass;
  }
  ...
}

Next step would be to mock the HelperClass in a unit test and pass in the mock object. But there’s a deeper problem. Deeper than G.I. Joe public service announcements. Yes that deep. What if you can’t pass in a mock through the constructor?? What if that helper class is being newed (Yes that’s a f–king word on this site) up in something like an attribute? What if your hair were to spontaneously catch on fire? Well you are back in the world of hurt my friend, except the hair thing might be an improvement. For the other two, there is something that can help and it’s name is Castle.

What is Castle? Well besides a word, it’s a collection of lots of stuff that helps with anything from mocking to tooth aches, but for this example we only need something that allows instantiation from a config file.

Now you might ask, “How can I be awesome like this site?” to which I answer, “You can’t.” Defeated you now turn your eyes back to the dilema and ask, “Config file? Instantiate? What will that do for me?”

Imagine this if you will… and I know this kind of thinking hurts you but just hang in there… Suppose you have a factory method that creates a instance for you. Something like this:

class SomeClass
{
  ....
  public SomeClass()
  {
    someHelperClass = new ObjectFactory().Create<IHelperClass>();
  }
  ...
}

BUT HOW DO IT CREATE THEM OBJECT FROM INTERFACE? Good question, though horribly asked.

Now it might seem odd since I am using a factory to create a helper but I haven’t shown you how the factory finds what to create. What if I told you there’s a way that it would simple look to a config file and know the type to create? What if I told you that in your test project the factory would create MockHelperClass but in the ui project it creates a HelperClass like before? You might think it’s magic. You might think Over the Top is the best movie of all time. You would be wrong on both accounts.

Now the answer is here if you don’t feel like reading the rest, and I can’t really blame you since I stopped reading after the first paragraph. However, if you actually want to see some of the magic in writing, mush on.

First thing you need are four dlls are Castle.Core, Castle.DynamicProxy, Castle.MicroKernel, Castle.Windsor, and Castle.ImSorryButThePrincessIsInAnother. (THERE ARE FIVE DLLS) Ok so one of those is a lie, but I’ll leave it up to you to figure it out. You could use my example to get them or go to here and try to figure out where they are. Course you could also spin around in a chair for five minutes because that would be about as brilliant as not just using my easy to find example. Either way, you need them.

Next the example needs an interface. Why an interface? Because it’s simple. Could I do this with a class? Far as I know as long as it’s not sealed and the concrete object inherits it. However for this example, ITS A MOOT POINT BECAUSE I’M USING AN INTERFACE.

namespace CastleConfigTest.Interface
{
  public interface IBaseClassA
  {
    String ClassName();
  }
}

Wow, beautiful. If you’re getting teary over that, you’re weird but I appreciate the passion. Now what else I need is a concrete class that implements said interface.

namespace CastleConfigTest.Class
{
  public class ChildClassA : IBaseClassA
  {
    public String ClassName()
    {
      return "ChildClassA";
    }
  }
}

Good golly Miss Molly, that’s fantastic. Now what does this all mean? It means that somehow using a config I will magically turn IBaseClassA into ChildClassA. Now for the hell of it, and for the ease of it, I have a test too.

    [TestMethod]
    public void Create_ClassA()
    {
      var test = new ObjectFactory().Create();
      Assert.IsTrue(test.ClassName().Equals("ChildClassA"));
    }

Ok so wait, what’s this ObjectFactory? It’s a class I’ve created that uses an object (WindsorContainer) that uses a config file to pull in specified types into a collection. Now I could get into that class, but I’d rather do the config file real fast. It’s name? Castle.config. AMAZING

<configuration>
  <components>
    <component id="childClassA"
     service="CastleConfigTest.Interface.IBaseClassA, CastleConfigTest"
     type="CastleConfigTest.Class.ChildClassA, CastleConfigTest">
    </component>
  </components>
</configuration>

So what does that all mean? Really nothing complicated. ‘service’ says, “Look for this” and ‘type’ says “Replace with this”. (No it doesn’t literally say that in the config file so stop looking) What’s the point of that? Simple, for every project you can have a separate Castle.config with the same ‘service’ value but a different ‘type’ value meaning that at run time you can replace the IBaseClassA with any class that implements IBaseClassA. Say in the test project you have a config:

...
     service="CastleConfigTest.Interface.IBaseClassA, CastleConfigTest"
     type="CastleConfigTest.Class.MockClassA, CastleConfigTest">
...

Now anytime IBaseClassA is called upon, MockClassA is almost instantly called in it’s place. Kind of like a stunt man in any action movie involving Bill Nighy.

Now one thing of special note, and by special I mean far from it, it helps if you set the config to Copy Always so that you know where the file is when the project is built. You don’t have to do that if you don’t want to, just like you don’t have to take showers. It’s just makes life easier for everyone.

Seems all great and good, but slight issue… What’s ObjectFactory? Well, here it is:

  public class ObjectFactory
  {
    //Tell it where the config file is.  Yes this is hardcoded but get over it.  You
    //  can change that if you like.
    private const String fileLocation = @"C:\Development\CastleConfigTest\CastleConfigTest\bin\Debug\";

    //This is the config file name.  I really hope you could tell that already.
    private const String fileName = "Castle.config";
    private WindsorContainer container;

    public ObjectFactory()
    {
      //Create a new container with the config file.
      container = new WindsorContainer(new XmlInterpreter(fileLocation + fileName));

      //Get all types in the container that implement IBaseClassA and make them
      // transient... ie only when needed.  If you don't believe me, go here and apologize later.
      // I'm sure you're used to that anyhow.
      var controllerTypes =
        Assembly
          .GetExecutingAssembly()
          .GetTypes()
          .Where(item => typeof(IBaseClassA).IsAssignableFrom(item));
      //And this I stole from someone but I can't remmeber who
      //  I don't really care though because chances are it was someone important
      //  and there's as much of a chance of someone important reading this as
      //  me sprouting a second me and doubling the worthless content on this site.
      //  After all, double of infinite is just the same damn thing.
      //  Not to mention this world isn't ready for that much pretty.
      controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
                            where typeof(IBaseClassA).IsAssignableFrom(t)
                            select t;

      foreach (Type type in controllerTypes)
        container.AddComponentWithLifestyle(type.FullName, type, LifestyleType.Transient);
    }

    //And then this is the wondrous and obviously complex method used to do the creating.
    public T Create() where T : class
    {
      return (T)container.Resolve(typeof(T));
    }
  }

Wait what? That’s it? Well for the most part. Only thing that was difficult was the ObjectFactory, but that’s so easy even a… well you know the rest. And why wouldn’t you? That f–ing phrase has burned into your skull for the last 5 years and that’s a conservative guess. And yes, there is room for improvement so save your nerd rage typing. After all, you have plenty of room for improvement but you won’t see me fist typing a list of things with disgruntled comic fan boy like intensity.

Anyways, that’s the short of it and since I gave you an example somewhere crazy hidden in this mess I call a post, you should be able to pick it up from there. If you can’t, consult your physician because you most likely suffer from acute brain loss. Don’t worry though, you can still have a long career as a PowerPoint instructor.

And if you haven’t figured it out yet, this post is my April Fools joke.  Actual useful content on this site.  Don’t get used to it.

Child IFrame Page Interacting with Parent Page… Yeah I went there.

Example here.

File this under “Why?” but I wanted to see if a child could talk to a parent and then receive information back from the parent to update itself with. As usual, my lack of intelligent wording probably has you scratching your head… if you do that. Personally I don’t get that expression as when I’m confused I more than likely will grab a jar of peanut butter and start lathering up with it, but to each his own.

So here’s the idea, and this post is only the start.

You have a parent page, Parent.htm, with an iframe and you want the parent to do something and alert the child that something happened. For now, it’s actually really simple.

On the parent I have a method:

  function callMethod(text, methodDelgate) {
    if (methodDelgate != null) {
      methodDelgate(text);
    }
  }

And this simple markup:

  <iframe id="myFrame" src="Child.htm"></iframe>

Wow huh? Well on the child I have this:

  function callParent(text) {
    if (top.callMethod != null) {
	  top.callMethod(text, changeText);
    }
  }

This is easy. If the parent has the method, send the text through and a method to call when finished. What is this method? Well its:

  function changeText(text) {
    jQuery('#returnText').text(text);
  }

Which simply sets the text on some div to show it actually worked.

What happens when I click a button that calls callParent? It talks to the parent, the parent calls the passed in method, and the child updates itself.

Not sure this is rocket science, but there will be more on it as I add in the idea of a dynamically created pop up on the parent being used by the child. Until then, try not to be yourself. You embarrass your mother.

Get the jQuery DatePicker to Work With jQuery Modal Dialog

Being that I am the man, I thought I would share this little thingy with you because… well I’m the man.

So here’s the issue:  You have a date picker, a modal dialog, and you can’t see the calendar when you click on the icon and/or textbox. First thought, ‘WHY DOES THIS HAPPEN TO ME???!?!’ Second though, ‘I wonder if that tool knows how to get past this.’ Good news! I do. Turns out it has to do with the z-index. The modal dialog by default has a z-index of 1000ish when showing. (And any modal dialog “above that” will increase it’s z-index to match.) If the calendar isn’t higher than that, no go.

Now you might be using the jquery styles from the jquery site and might be putting your through your keyboard thinking about having to deal with that mess. However, it’s actually a simple fix in there… there being the ui.datepicker.css file.

  .ui-datepicker { width: 17em; padding: .2em .2em 0; z-index:9000; }

And there you have it. Now the calendar will show up in front of anything lower than 9000, and as everyone knows: Anything over 9000 is impossible.

jQuery Validation: Adding Errors to the Error Containter… With Love!

Hello again, my wonderful audience, I have something great and fun planned for this post. If you read this post you might have been left wondering how to add custom messages to the error holder. It’s ok if you did, there’s nothing wrong with being confused all the time. It’s what makes you so adorable.

Say you have a form like this, and if you don’t I cry endlessly for your loss. My heart goes out to you.

<form id="ILoveEverythingForm">
    <div id="NotSoNiceThingsDiv" style="display:none;"></div>
	...
</form>

As you can see, there is an error div to hold mean things that we have to print out because the system just doesn’t like the user. As we both know, the user can’t help but be dumb. It’s just in his cute little nature. And that nature is just so darned cute.

Now let’s assume that you have something that sent back a bunch of mean messages when you tried to validate server side after all the cute client side validation was done. You might have a method to take in those jerk face messages. How do you display them in the bad place?

  function updateErrorDivContentWithLove(messages)
  {
    if(messages.length > 0)
    {
      var validator = jQuery('#ILoveEverythingForm').validate();

      for(var loopCounter = 0; loopCounter < messages.length; loopCounter ++)
      {
        validator.showErrors
        (
          {
             'SomeWonderfulElementName' : messages[loopCounter].Message
          }
        );
      }
    }
  }

Awwww kitties!

  

Only thing that may seem odd (And if it doesn’t, don’t worry you are still very special and loved in this world):

  'SomeElementName' : messages[loopCounter].Message

Not sure what element really needs to be here, basically anything in the form with a name tag. So if you’re good like I know you are, you have at least one element in that little old form with a name property set. I would say that this is pretty useless in situations where all the errors are shown in one div, as opposed to right next to the element, but that would be mean and I don’t do that.

Now I know you wanted something special from this post so I just wanted you to know that even though most of the world considers you hideous, I say you should be proud of being hideous because it makes you who you are. A unique miracle that only really has issues with dogs and small children. Embrace yourself in whatever way you take that!

Data Annotations, MVC, and Why You Might Like Them

So if you were like me before I knew what Data Annotations were, you most likely would be thinking, “What are Data Annotations?”. Well I’m glad I can read your mind and therefore I am glad you asked.

Now the fun part about this post is that I might have to admit I was wrong. Why would that be? Well in this post I suggested that validation rules would be set in the controller. Turns out, there is possibly a better place, on the model itself. How can this be done??? Well that’s what you’re about to find out.

Say you have a user create model:

  public class AddUserModel
  {
    public String UserName { get; set; }
    public String Password { get; set; }
    public String RepeatPassword { get; set; }
  }

Now you could have a method on the controller like:

  public ActionResult AddUser(AddUserModel model)
  {
    if(IsValid(model))
    {
      ...
    }
  }

Where you have to create the IsValid method for every model on the controller that you need to validate (And possibly on other controllers if you are sharing models between them…) Or you can have this:

  public ActionResult AddUser(AddUserModel model)
  {
    if(ModelState.IsValid)
    {
      ...
    }
  }

And that is already built in so no validation method needed. But how is that possible? Attributes on the model or namely the ValidationAttribute class.

First off you have to include the System.ComponentModel dll in the project. Simple enough. Please say you know how to do that or do me a favor and remind yourself to blink. OK done? Good.

Now you can use some of the built in attributes which is good. Things like required are nice:

  public class AddUserModel
  {
    [Required]
    public String UserName { get; set; }
    ...
  }

There you go. Now if the UserName is null or empty, the ModelState will no longer be valid and will fail this check:

  ModelState.IsValid

Now you might wonder what the error message will be for that? Honest answer: I have no f–king clue. That’s why you can actually set it. Those guys at Microsoft thought of everything.

  public class AddUserModel
  {
    [Required(ErrorMessage = "ENTER A USERNAME IDIOT!"]
    public String UserName { get; set; }
    ...
  }

The guys in the legal department have told me I have to note that your error message should change depending on your use and you shouldn’t use the one above. Whatever.

Now you might want to actually pass the errors back, and why wouldn’t you? You’re a fine, upstanding, and thoughtful person and I lie like a crook. The errors, if there are any, are in here:

  ViewData.ModelState.Values

And you can use two loops to get to all of them, but I think the parent loop will only run once.

  foreach (ModelState state in ViewData.ModelState.Values)
  {
    foreach (ModelError error in state.Errors)
    {
      messageList.Add(error.ErrorMessage);
    }
  }

Pretty nice huh? Maybe if you’re an idiot who just learned about this. For cool people like me, it’s old news.

What’s the point this? If “this” is data annotations: Well it helps move some of the validation off the controller if you are looking for a more “Fat model, skinny controller” design which I’m told is a good idea. This also gets rid of all the validation methods and saves time because of it.

If “this” is your life? I have no idea. But if you’re to the point that you’re asking me about the meaning of your life, you are in some serious trouble.