jQuery Validation – How to Use to Get Rid Of Even The Toughest Stains

So you want to use jQuery validation, huh?

What is it? Something that was added to the holy jquery site and is an easy way to validate input from users. Now this should in no way take over for server side validation, but it helps to at least catch a few things without having to send anything to the server. So how do ya do it?

Well to start, you need some files:

jquery-1.3.2.js and jquery.validate.js.

Now oddly enough the validation file isn’t hosted on the holy jquery site but how to use it is.

Ok now you have the files, what’s next? Well you need form, and I can do that for you.

So basically it’s a simple form with one input that is required.

jQuery(document).ready
    (
      function()
      {
        jQuery("#PrimaryForm").validate
        (
          {
            errorLabelContainer: "#ErrorDiv",
            wrapper: "div",
            rules:
            {
              FirstName :
              {
                required : true
              }
            },
            messages:
            {
              FirstName:
              {
                required : 'First Name is required.'
              }
            },
            onfocusout : false,
            onkeyup: false,
            submitHandler: function(label)
            {
              postSubmit();
            }
          }
        );
      }
jQuery("#PrimaryForm").validate

Real simple, just setting the validator to the primary form on the page.

 errorLabelContainer: "#ErrorDiv",

This sets the errors to show up in the ErrorDiv. Now this is optional, as you can have it show the errors next to the FirstName text box but personally I think that looks horrible. Setting up the ErrorDiv puts all the errors in one central location and allows for styling the actual div.

 rules:
 {
    FirstName :
    {
      required : true
    }
  },

This matches an element with the id of FirstName to the required rule, meaning that FirstName is required. Rocket science.

  messages:
  {
    FirstName:
    {
       required : 'First Name is required.'
    }
  },

If you can’t figure this out, I hear circus is hiring for the “World’s Dumbest Person”. You’ll fit in with Jub Jub the Dog Boy.

  onfocusout : false,
  onkeyup: false,

Basically this prevents the validation when leaving the textbox or on every key press. This is just another preference.

  submitHandler: function(label)
  {
    postSubmit();
  }

If the submit is successful, call this method.

But… BUT WHAT IF IT’S AN EMAIL?!??! WHAT WILL I DO???!?!?

Well for one, stop being such a child. And two, look here.

Some what different, as you can see it’s now email and there is one extra requirement in the rules:

  rules:
  {
    EmailAddress :
    {
      email : true,
      required : true
    }
  },
  messages:
  {
    EmailAddress:
    {
      required : 'Yo, email fool.',
      email : 'So not an email address.'
    },
  },

See? It has nice built in rule for email. Simple.

BUT WHAT IF I NEED A REGULAR EXPRESSION?!??! WHAT WILL I DO???!?!?

I swear if you don’t stop that, I’m turning this post around and going home.

Fine here it is.

  jQuery.validator.addMethod
  (
    "isZipCode",
    function(value, element)
    {
      return value.match(new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/));
    }
  );

Just have to create a method and “add it” to the validator itself. And then there’s the use:

  rules:
  {
    ZipCode :
    {
      required : true,
      isZipCode : true
    }
  },
  messages:
  {
    ZipCode:
    {
      required : 'For the love of me, enter a zip code!.',
      isZipCode : 'Serioulsy?  Do you know what a zip code is?'
    },
  },

Woo hoo right?

Don’t do it… Don’t you yell.

But what if one input depends on another?

Much better. Well that’s not as hard as it may seem and here’s the example.

  rules:
  {
    InputB :
    {
      required :
      {
        depends : function(element) { return jQuery('#InputA').val() != "" }
      }
    }
  },

As you can see, you can change how the required method works by adding in a depends handler. Works out pretty well.

Yes I will show you how to make sure two inputs match. I swear you ask for a lot.

  rules:
  {
    Password :
    {
      equalTo : "#ConfirmPassword"
    },
  },

Couldn’t be easier unless I wrote it out for you. Wait, I did.

So here you’ve either learned a bit about jQuery validation or have just spent the last few minutes drooling uncontrollably. Either way, I’m done with this post and you’re left to do whatever it is you do, you sick f—.

Side note: I haven’t actually been to Htmlgoodies since eh college? but wow did that place sell out. How fitting that an introduction to html page now looks like it was designed by someone just starting out… in the 90s.

.Net 4.0 Beta 2 Entity Framework – How To Set Up Complex Types, Now With More POCO

So something I’ve seen but just have now conquered is the whole complex type thing in Entity Framework. Not only that, but with the cool new Persistence Ignorance thing all the kids are talking about. (And boy am I glad there’s a new kind of ignorance on this site now.) You might ask: What’s a complex type? Course you might ask: Why is it so hard to make a decent movie about huge robots that transform into cool vehicles and have really big guns? Well I can answer the first question.

Complex types, in the simple minded way I see them, are a way to split information retrieved from a table into a object within an object. Confused yet? I hope so.

Say you have a User table and on that table you have the typical user information including a bunch of stuff like Name, Sex, City, State, and Zip. Now you could set up the user class to look like this:

  public class User
  {
    public String Name { get; set; }
    public String City { get; set; }
    public String State { get; set; }
    public String Zip { get; set; }
  }

Nothing wrong with that, but what if you have an Address class:

  public class Address
  {
    public String City { get; set; }
    public String State { get; set; }
    public String Zip { get; set; }
  }

That you wanted to map the values from the User table to the User class to so that the User class looked more like this:

  public class User
  {
    public String Name { get; set; }
    public Address Address { get; set; }
  }

Well I’m here to tell you that you can and I have plenty of pictures to back it up.

Keeping with the design from this guy, I am going to add a new class called AdDimension which will have Height and Width, effectively replacing the Height and Width properties on the Ad class.

RECAP – Old class diagram:

AddAdtype

So the first thing I have to do is is create the complex type in the Model Browser. That’s pretty easy. There’s a section called “Complex Types” and you just add one.

ComplexTypeAdd

See, there’s a picture. Next step is adding properties to the newly created complex type.

ComplexTypePropertyAdd

Another picture! Ok so now you’ve created on, big deal. Now what? Well you have to add a complex type property to the main class, Ad in this case.

ComplexTypeAddToEntity

Now if you have more than one complex type, you might have to set the property type to the correct one. Just right click the complex property and click on properties:

ComplexTypePropertyProperties

Now, you’ll have to adjust the mapping for the entity itself. So click on the object and bring up mapping properties. From there, select the correct mapping for the correct column. In this example it’s width and as you can see in the drop down there is a AdDimension.Width property to set it to. Cool huh?

ComplexTypeSetMapping

And that’s it for the object model. Next you have to add the AdDimension class and add a property to the Ad class.

  public class AdDimension
  {
    public Int32 Height { get; set; }
    public Int32 Width { get; set; }
  }
  public class Ad
  {
    ...
    public AdDimension AdDimension { get; set; }
    ...
  }

And then how do you set it?

  someAd.AdDimension = new AdDimension();
  someAd.AdDimension.Height = 10;
  someAd.AdDimension.Width = 10;

And it can even be used in queries:

  context.Ads.Where(ad => ad.Width > 10);

Now there are things to be aware of. Complex types can’t inherit from other complex types and the property can’t be null when saving. Just be aware of that.

I’m telling you man, this s– is the s— man. It’s the s—.

.Net 4.0 Beta 2 Entity Framework – Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue

So the next step in the New Entity Framework saga was to make a many to one relationship and get it to save. After all, with the last version I had far more issues with many to one than any other kind of relationship. Turns out, the steak is still in tact.

Taking the structure from the last post, I added an AdType. It’s very simple. Columns are AdTypeId (Int Primary) and Description (Varchar). I added a AdTypeId column to the Ad table and created a foreign key to the AdType table with it.

Basically Many Ads to One AdType.

Then I did the usual Update Model From Database with the .edmx file. Same old same old. Well this added the AdType class and the relationship:

AddAdtype

So far, so good. Now with this it also means that I need to create the AdType class and add the AdType property to the Ad class along with the AdTypeId property.

Side Note:

Far as I can tell, you need the AdTypeId property despite also having the AdType property. Don’t forget this.

Here’s the AdType class:

  public class AdType
  {
    public Int32 Id { get; set; }
    public String Description { get; set; }

    public virtual IList<Ad> Ads { get; set; }
  }

And on the Ad class I had to “Ad” (HARHRHARHR) the AdType property along with the AdTypeId property:

  public class Ad
  {
    public Int32 Id { get; set; }
    public DateTime CreatedDate { get; set; }
    public String Name { get; set; }
    public DateTime? LastUpdated { get; set; }
    public Int32 Height { get; set; }
    public Int32 Width { get; set; }

    //Interesting note: Works even if this is private and non virtual
    private Int32 AdTypeId { get; set; }

    public virtual AdType AdType { get; set; }
    //Note:
    //If properties are to be lazy loaded, must be virtual
    public virtual IList<Newpaper> Newspapers { get; set; }
  }

Classes are done. Should be good to go right? WRONG YOU ARE SO F-ING WRONG! Just try this, I dare you:

   Ad ad = new Ad();

   ...
   ad.AdType = someAdType();
   context.Ads.Add(ad);
   context.SaveChanges();

DUN DUN DUUUUN INSERT statement conflicted with the FOREIGN KEY constraint.

You try it? Idiot. You just got stuffed by a foreign key error. Why? Well The Big M has an answer:

In this example, Customer is a pure POCO type. Unlike with EntityObject or IPOCO based entities, making changes to the entity doesn’t automatically keep the state manager in sync because there is no automatic notification between your pure POCO entities and the Entity Framework. Therefore, upon querying the state manager, it thinks that the customer object state is Unchanged even though we have explicitly made a change to one of the properties on the entity.

Basically because these objects aren’t really being watched by the State Manager, it has no idea anything has changed and should be persisted. Therefore, it has no idea that the AdType property has changed and that the AdTypeId should be updated to reflect this. That’s right, it just ignored the AdType property and left the AdTypeId to it’s default… 0 (That’s a Zero or as the English say, Zed). How do you get around this? This little option.

  context.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);

This tells it to persist the changes that it didn’t know about. Now I’m still picking this up as I go so bare with me as I might have the best explanations yet on why things work with the New Entity Framework. Then again, this is a site by a tool.

.Net 4.0 Beta 2 Entity Framework – How To Start

So I just recently turned my laptop into a 4.0 workstation since it is kind of expendable and I won’t feel inclined to nerd rage if it gets tooled. With this step forward, I decided that I probably won’t be doing much with the old Entity Framework version since the new one is supposed to be the end all/be all until the next end all/be all version comes out. What does this mean for you? This post could be filled with useful information or f— all. Just depends on what you care about.

After doing a little reading, and by little I mean as little as humanly possible while still having an idea of what I’m doing, I got the new EF to persist an object. Mind you, it took a bit of patience followed by slamming my head into my desk and then more patience, but I did it.

First off, the actual creating of the edmx file is the same, there’s really no difference. You still go through the wizard, you still go through the connection set up, and you still grab the tables you want. No change there.

However, once you have it created, click on the .edmx file in your solution explorer, right click, then click properties. You’ll see something like this:

BAT - EntityFramework_RemoveCustomTool

You can see where there is nothing in the Custom Tool area of properties. That’s because I deleted the text. That’s the first part of what you need to do. Next is creating the needed classes. For this example I have two, Ad and Newspaper:

namespace Beta2Test.Data.Entity
{
  public class Ad
  {
    public Int32 Id { get; set; }
    public DateTime CreatedDate { get; set; }
    public String Name { get; set; }
    public DateTime? LastUpdated { get; set; }
    public Int32 Height { get; set; }
    public Int32 Width { get; set; }

    //Note:
    //If properties are to be lazy loaded, must be virtual
    public virtual IList<Newspaper> Newspapers { get; set; }
  }
}

and

namespace Beta2Test.Data.Entity
{
  public class Newspaper
  {
    public Int32 Id { get; set; }
    public Int32 Circulation { get; set; }
    public DateTime CreatedDate { get; set; }
    public DateTime LastUpdated { get; set; }
    public String Name { get; set; }

    //Note:
    //If properties are to be lazy loaded, must be virtual
    public virtual IList<Ad> Ads { get; set; }
  }
}

Three things you might notice:

  1. The classes don’t inherit from anything. Yay
  2. The namespace is Beta2Test.Data.Entity. Fact is, I left it there to show that the namespace can now be anything. Yay
  3. Both collection properties are virtual. This is a must when dealing with collections that represent a relationship and you have lazy loading enabled (See below context class). For this, there is a many to many relationship between Ads and Newpapers. The Ads and Newspapers collection represent that. Why do that have to be virtual? Has to do with Entity Framework needing a way to override the properties so it can tell when they are accessed. (Read: Lazy Loading)
  4. There is no fourth thing. You are wrong if you think there is.

So far so good, but what about that like whole linking to that persistence layer stuff. You know like them entity objects yo.

Thank you for that poorly worded inquiry, but valid none the less. Remember those entity context classes that it used to generate for you? Well that whole “custom tool” dohickey I removed would have built it for me. However, that’s not the path we’re going down anymore. It’s now time to brave the unknown. We, yes we, will build the context. Yes the context.

using System.Data.Objects;
using Beta2Test.Data.Entity;

namespace Beta2Test.Data
{
  public class Beta2TestContext : ObjectContext
  {
    private ObjectSet<Ad> _ads;
    private ObjectSet<Newspaper> _newspapers;

    public Beta2TestContext() : base("name=InterviewDemoEntities", "InterviewDemoEntities")
    {
      _ads = CreateObjectSet<Ad>();
      _newspapers = CreateObjectSet<Newspaper>();

      //This makes sure the context lazy loads by default
      ContextOptions.LazyLoadingEnabled = true;
    }

    ///
    /// This is used to set up the "queryable" collection.
    ///
    public ObjectSet<Ad> Ads
    {
      get
      {
        return _ads;
      }
    }

    public ObjectSet<Newspaper> Newspapers
    {
      get
      {
        return _newspapers;
      }
    }

    ///
    /// This creates an ad that allows it "to be used with the Entity Framework."
    ///
    ///
    public Ad CreateAttachedAd()
    {
      return EntityContext.Context.CreateObject<Ad>();
    }

    public Newspaper CreateAttachedNewspaper()
    {
      return EntityContext.Context.CreateObject<Newspaper>();
    }
  }
}

The CreateAttached methods aren’t needed on the Context class itself, I just put them there. They could go on the Ad/Newspaper class but at this point I’m not sure if that blurs the lines or not. Haven’t gotten into best practices mode yet.

You may notice the ObjectSet collections on the context. These are the collections you will query to get items most likely, much like the old context class from the last version:

Context.Ads.Where(ad => ad.Id == 1)

Pretty nice, huh?

Also, I noted above about the virtual properties on the Ad/Newspaper classes and how it had to do with lazy loading.

ContextOptions.LazyLoadingEnabled = true;

That line and the virtual properties ensure that lazy loading will occur when the property is used. Both have to be used together. Now you don’t have to put that line in the constructor if you do create a context every time you are retrieving things, you could just set it on a case by case basis. Up to you. I use a singleton like context so I just set it true in the constructor and don’t worry about it.

The main thing I had trouble with was this line:

public Beta2TestContext() : base("name=InterviewDemoEntities", "InterviewDemoEntities")

Because I wasn’t sure what the second string should be. First one is easy, it’s whatever the key in the config file for the connection string. Second, chances are, is the same depending on how you set it all up in the wizard. I think it’s the same name when you right click on the opened .edmx file and view properties. There should be a property named “Entity Container Name”.

Here’s a method I used for testing to create an Ad:

  public Ad CreateAd(Boolean persist)
  {
    Ad ad = null;

    if (persist)
    {
      ad = EntityContext.Context.CreateAttachedAd();  //This is the CreateAttachedAd method above in use
    }
    else
    {
      ad = new Ad();
    }

    ad.CreatedDate = DateTime.UtcNow;
    ad.Height = RandomTool.RandomInt32(0, 10);
    ad.LastUpdated = DateTime.UtcNow;
    ad.Name = RandomTool.RandomString(10);
    ad.Width = RandomTool.RandomInt32(0, 10);

    if (persist)
    {
      AddEntityForRemoval(ad);  //Ignore, for persistence removal after testing is completed
      EntityContext.Context.Ads.AddObject(ad);  //Ad the ... ad to the context
      EntityContext.Context.SaveChanges();  //Persist
    }

    return ad;
  }

There are some things you can ignore because I didn’t feel like removing code. As you can see though, it’s not very complicated. Use the CreateAttachedAd, fill in the properties, ad to the Ad collection on the context, and save.

The End

Sure you had to do more work than in the earlier version of Entity Framework, but on the other hand I have a fully detached class that can inherit from any class I WANT it to as opposed to the EntityObject class. Not to mention I now have an easy way to do lazy loading. Far cleaner than the old way I did it. The other interesting thing to note, and this may not be a big deal to anyone else, but above I have a note about this:

  AddEntityForRemoval(ad);  //Ignore, for persistence removal after testing is completed

This method just adds the object to a collection of EntityObjects that later I use to delete the object from the database on test cleanup. After moving to this version of EF, I had to change it to a collection of Objects. Interesting thing is:

  EntityContext.Context.DeleteObject(currentObject);

Didn’t care. It still knew that the object was attached to the context somehow, despite the CLASS not being an EntityObject. Just an odd note.

Two Errors I came across:

System.InvalidOperationException: Mapping and metadata information could not be found for EntityType ‘Beta2Test.Data.Ad’.

If you get this, there is a really good chance you screwed up a property name or are missing it completely. If the property name doesn’t exactly match one in the .edmx class designer template, you’re screwed. If you don’t have it on the class but it’s on the class designer template, you’re screwed. If you add it to the class designer template, it has to be on the class as far as I can tell. Now, it doesn’t have to be public. I have tested it as private and it works just fine.

The required property ‘Newspapers’ does not exist on the type ‘Beta2Test.Data.Ad’.

This most likely happens if you didn’t remember to make it a property:

public IList<Newpaper> Newpapers;  //Forgot the { get; set; }
public IList<Newpaper> Newpapers { get; set; };  //Forgot the Virtual

Opps.

ASP.Net MVC: Attributes, ActionFilterAttribute, and Why You Might Want To Use Them

So if you’ve used MVC, and I know you have because you want to be cool like me, you’ve most likely run into an error like this:

Certain parameter wasn’t found. Make [parameter] nullable.

In other words, the parameter didn’t show up in the URL and therefor MVC can’t assign a value to it. This would of course happen with anything that isn’t nullable. Now you could do this:

  void SomeAction(Int32? pageNumber)
  {
    if(someParameter.HasValue)
    {
      ..
    }
  }

But do you really feel like putting that in every stupid method that happens to have the same parameter? Say the parameter is something simple like pageNumber. Taking the above code, you would have to see if pageNumber has a value and if it doesn’t, continue to set some variable to a default. Kind of annoying to have to repeat that over and over again when you know you will be looking for pageNumber on many actions. Well Attributes, or more importantly ActionFilterAttribute, are the way to get around this.

Say with the pageNumber example you want a default of 1 if it doesn’t exist. Well that’s easy to do, it would be something like this:

    public sealed class CheckPageNumberAttribute : ActionFilterAttribute
    {
        private const String DefaultPageNumber = 0;

        //This will fire automatically on page load.
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            //ActionParameters.Values holds all the request parameters after the ? as in ?pageNumber=1
            //See if it exists first.  If not, add it
            if (!filterContext.ActionParameters.ContainsKey("pageNumber"))
            {
                filterContext.ActionParameters.Add(RequestConstants.PageNumber, null);
            }

            //Set to default if it's not null
            filterContext.ActionParameters["pageNumber"] = filterContext.ActionParameters["pageNumber"] ?? DefaultPageNumber;
        }
    }

So the method looks more like this now:

  [CheckPageNumberAttribute]
  void SomeAction(Int32 someParameter)
  {
    ...
  }

And you can now do your … without worry.

But what if the url is like this?

ShowMeACoolRoom/Index/1/

And you have your route set up like:

  {controller}/{action}/{roomId}

And you want to make sure that not only does that userId exist in the url, but the user actually exists. Well you don’t look to the ActionParameters.

  public sealed class RoomExistsAttribute : ActionFilterAttribute
  {
    public override void OnActionExecuting(ActionExecutingContext context)
    {
      base.OnActionExecuting(context);

      ChatRoom foundRoom = null;
      //RouteData.Values holds all the values in the url it was able to match to a route
      //Check the Values list in the RouteData for the id
      if(context.RouteData.Values.ContainsKey("id"))
      {
        //Convert to an integer, ConvertTo is just a method I've made.
        Int32? roomId =
          Convert.ToString(context.RouteData.Values["id"]).ConvertTo();
        if(roomId.HasValue)
        {
            foundRoom = ChatRoom.GetRoomByID(roomId.Value);
        }
     }

     //If the room isn't found, handle the error.
     if (foundRoom == null)
     {
       //redirect on error...
       context.Result =
         new RedirectToRouteResult
         (
           GeneralConstants.RouteName,
           new RouteValueDictionary
           {
              { "controller", "sharedError" },
              {  "action", "error" },
              { "name", "someErrorKey" }
            }
          );
       }
    }
  }

Now the new method looks something like this:

  [RoomExistsAttribute]
  [CheckPageNumberAttribute]
  void SomeAction(Int32 roomId, Int32 someParameter)
  {
    ...
  }

And once again you are free to … without worry of the room not existing. Next post I plan on adding some more “advanced” attributes… hahaha advanced? This site? hahahaha sorry. But I will be adding a new post about certain attribute solutions I’ve found that work well.

ASP.Net MVC: Routes, Route Contraints, and My Love Hate Relationship

So something that has been somewhat of an uphill climb as of late is routing in MVC. I think part of it is the way it works and part of it is that I’ve approached MVC like a 10 year old with a new game; F- the instructions, I’m all up in this.

What goes out must come in…

The biggest misconception I had with routes is that the route definitions meant something when a page is loading. This is bad. Now before the nerd rage starts to build, I will qualify that statement. Route definitions mean nothing beyond a simple mapping of values. What? Well suppose I have two routes:

   routes.MapRoute
   (
     ...
      "{controller}/{action}/{roomId}/{name}",
     ...
   );

and

   routes.MapRoute
   (
     ...
     "{controller}/{action}/{userId}/{name}",
     ...
   );

Now on the way out, the system can find the route easy if you supply the correct route data: (Lets say for the second route)

  routeValues = new RouteDicationary()
  routeValues.Add("controller", "Room");
  routeValues.Add("action", "Index");
  routeValues.Add("userId", 1);
  routeValues.Add("name", "ProgramminTool");

  neededHelper.RouteUrl("SecondRoute", routeValues);

Which will give me a wonderful address of:

  /User/Index/1/ProgramminTool

Awesome, the routing system did what I wanted. Problem is, I assumed too much coming in, ie when the page is loading from the url. (Say from a clicked link) I kept getting an error like:

RoomId doesn’t exist. Make roomId nullable. Blah blah blah I hate you and you should quit programming and do something more equal to your ability level like spinning in circles.

Though I might have take some artist license on the error, the meaning was simple: it was trying to run that url against the Room controller and it couldn’t find the roomId parameter in the request. Well that doesn’t make sense, after all it’s obvious that it should be looking for the user controller and use the route with the userId paramter. Sadly, it doesn’t work that way and not sure it could. Why? Well look at the url.

/User/Index/1/ProgramminTool

Now if you were too look at that, what would you think? You have four values, values that you can’t really guess the type since you have no real context. After all there could easily be a method that takes in a string userId as opposed to an integer userId. On top of that, it has no idea what the 1 is. There’s no userId=1 to tell it what it is. So what does it do? It goes down the route table and finds the best fit. Now you tell me, which does this url fit better?

  "{controller}/{action}/{roomId}/{name}"

Or

  "{controller}/{action}/{userId}/{name}"

It’s kind of a trick question since the answer is neither. It will just fit it to the first one that it likes, and in this example it’s the roomId one. Problem is, now the user controller method that is looking for the userId fails because there is no userId. Uhg.

Computers are dumb, they can only do what we tell them.

Fact is, in this situation I have to make some rules for the routing system to take in and start digesting the url properly, and there’s a way to do this: IRouteConstraint.

Say that you have certain controllers or actions you don’t want to use the first route. For this example I’ll use user actions from my current project. On the room index view there is a button for adding the room as a favorite. Now the action/method it needs is on the user controller, not the room controller. Therefore I have to post some information to the user controller using a route that looks like this:

  "{controller}/{action}/{userId}/{roomId}"

But it is preceded by one that looks like:

  "{controller}/{action}/{id}/{name}"

See the issue? Now when MVC generates the url, everything is fine. After all it uses the route name and the parameters to pick the correct route. On the way in, not so good. It naturally tries to conform the url to the id/name route. BOOM HEADSHOT! Now the solution.

public class NotGivenAction : IRouteConstraint
{
  //This is the action that we want to prevent from the route accepting
  private String GivenAction { get; set; }

  public NotGivenAction(String givenAction)
  {
    GivenAction = givenAction;
  }

  public Boolean Match(HttpContextBase httpContext, Route route, String parameterName, RouteValueDictionary values, RouteDirection routeDirection)
  {
    String parameterValue = values[parameterName].ToString();
    //Make sure the parameter exists and it doesn't match the bad action
    return values.ContainsKey(parameterName) && parameterValue != GivenAction;
  }
}

The IRouteConstraint interface has a method Match that has to be given life. The short of it is take in the parameter name and find it’s value and then see if the value is the same as the action it’s looking for. For example, if I had an action of AddToFavorites, this would go through and make sure it isn’t that action. If it is, it knows to not use the current route for this action.

routes.MapRoute
(
  GeneralConstants.RouteIdName,
  "{controller}/{action}/{id}/{name}",
  new { controller = "Room", action = "Index", id = "0", name = "None" },
  new { action = new NotGivenAction(UserControllerConstants.AddToUserFavorite) }
);

routes.MapRoute
(
  GeneralConstants.RouteUserIdRoomId,
  "{controller}/{action}/{userId}/{roomId}",
  new { controller = GeneralConstants.ControllerUser, action =   UserControllerConstants.AddToFavorites, userId = "-1", roomId = "-1" }
);

So now it will skip the first and push to the second when the url looks like:

  /User/routes.MapRoute/AddToFavorites/1/2/

Take that you f-ing routes. KING KONG AIN’T GOT S- ON ME!

Dictionary Index Lookup Vs Contains Key Vs List Contains Vs Linq… Speed Test/Texas Tornado Match

Ok so with MVC comes the use of Routes which calls in the need to compare request values to see which route to use. Now before I even bother with that headache (Although it’s getting better AND will be a post) I ran into a situation where I would have to check a passed in string against a list of strings to see if it matches any of them.

One thing I like to do is use Dictionaries. They are just plain convenient when it comes to looking things up or matching values to get methods. But what if I don’t really have a value to find with a key? What if finding the key is all that matters? Say I have a list of strings and I just want to know if the list contains that string, sounds like a job for an array or list right? Wouldn’t it be silly to create a dictionary like:

  Dictiontary<String, String> someList = new Dictiontary<String, String>();
  someList.Add("INeedThis", ""); someList.Add("ThisToo", "");

and do this:

  if(someList.ContainsKey("INeedThis"))

If I don’t actually care about the attached value? I’m sure I’m breaking a rule somewhere… but what if it was faster overall? What if ContainsKey is faster than a list using Any, Contains, FirstOrDefault, or where? Turns out it is. Here’s the method I used.

  public void TimeRun(Holder toHold)
  {
    Int32 maxLength = 1000;

    Dictionary<String, String> stringDictionary = Enumerable.Range(0, maxLength).Select(item => RandomTool.RandomString(item)).ToDictionary(item => item, item => item);
    List<String> stringList = stringDictionary.Select(item => item.Key).ToList();

    String chosenString = stringList[RandomTool.RandomInt32(0, maxLength)];

    Stopwatch runTime = new Stopwatch();

    runTime.Start();
    stringDictionary.ContainsKey(chosenString);
    runTime.Stop();
    toHold.DictionaryContainsKeyTime = runTime.ElapsedTicks;
    runTime.Reset();

    runTime.Start();
    String junk = stringDictionary[chosenString];
    runTime.Stop();
    toHold.DictionaryStraightIndexCheck = runTime.ElapsedTicks;
    runTime.Reset();

    runTime.Start();
    Boolean junkThree = stringList.Contains(chosenString);
    runTime.Stop();
    toHold.ListContains = runTime.ElapsedTicks;
    runTime.Reset();

    runTime.Start();
    Boolean junkTwo = stringList.Any(item => item == chosenString);
    runTime.Stop();
    toHold.ListLinqAny = runTime.ElapsedTicks;
    runTime.Reset();

    runTime.Start();
    String junkFour = stringList.First(item => item == chosenString);
    runTime.Stop();
    toHold.ListLinqFirst = runTime.ElapsedTicks;
    runTime.Reset();

    runTime.Start();
    IEnumerable<String> junkFive = stringList.Where(item => item == chosenString);
    if (junkFive.FirstOrDefault() != String.Empty)
    {

    }
    runTime.Stop();
    toHold.ListLinqWhere = runTime.ElapsedTicks;
    runTime.Reset();
  }

Crazy simple, and why shouldn’t it? Am I right? Am I right? Ok. As you can see, I gave all the methods a run and timed them using StopWatch. And then I ran it a given amount of times, 200 in this code but I tried up to 10000 also. (I’ll put the test code at the end) The test was to go through a list of a thousand strings, each string increasing in length. (Yeah I could have done random size strings but I’m lazy)

What did I find out? Well if it didn’t throw an exception, a straight index search on a dictionary is fastest:

someList["INeedThis"]

And pretty consistently fast. Around 2600 ticks or so on average on multiple runs. (so 10 iterations of parent method running 200-10000 interations of the test method) Next fastest was the ContainsKey method on the dictionary, usually around 2-4 times faster than the next in line good old List.Contains. What I did find surprising is that all the Linq methods failed on this one. I figured that once the first run was through, it would be at least as fast as Contains. (Linq always sucks the first time through) Yeah not so much though. Contains was always faster. Sometimes it was close. Sometimes not even. Here are some example runs:

Dictionary_ContainsKey: 15805
Dictionary_StraightIndexCheck: 2926
List_Contains: 34559
List_LinqAny: 96575
List_LinqFirst: 56541
List_LinqWhere: 64678 

Dictionary_ContainsKey: 7264
Dictionary_StraightIndexCheck: 2676
List_Contains: 29970
List_LinqAny: 41280
List_LinqFirst: 58313
List_LinqWhere: 45669 

Dictionary_ContainsKey: 6773
Dictionary_StraightIndexCheck: 2636
List_Contains: 32366
List_LinqAny: 38670
List_LinqFirst: 33859
List_LinqWhere: 41288

All in ticks. Now mind you, none of these are horribly slow so it probably just comes down to reability and ease of understanding. Personally I like the Dictionary way, so at least speed wise I’m on track. As for looks? That’s a personal thing.

Rest of the code. Here is the parent method. This is a unit test hense the .Assert but it could easily be adapted to any output.

  [TestMethod]
  public void RunTime()
  {
    Int64 overallDictionaryContainsKeyTime = 0;
    Int64 overallDictionaryStraightIndexCheck = 0;
    Int64 overallListContains = 0;
    Int64 overallListLinqAny = 0;
    Int64 overallListLinqFirst = 0;
    Int64 overallListLinqWhere = 0;
    Int32 loopMax = 200;

    for (Int32 loopCounter = 0; loopCounter < loopMax; loopCounter++)
    {
      Holder currentHolder = new Holder();

      TimeRun(currentHolder);
      overallDictionaryContainsKeyTime += currentHolder.DictionaryContainsKeyTime;
      overallDictionaryStraightIndexCheck += currentHolder.DictionaryStraightIndexCheck;
      overallListContains += currentHolder.ListContains;
      overallListLinqAny += currentHolder.ListLinqAny;
      overallListLinqFirst += currentHolder.ListLinqFirst;
      overallListLinqWhere += currentHolder.ListLinqWhere;
    }

    Assert.IsTrue
    (
      false,
      " Dictionary_ContainsKey: " + (overallDictionaryContainsKeyTime / loopMax) +
      " Dictionary_StraightIndexCheck: " + (overallDictionaryStraightIndexCheck / loopMax) +
      " List_Contains: " + (overallListContains / loopMax) +
      " List_LinqAny: " + (overallListLinqAny / loopMax) +
      " List_LinqFirst: " + (overallListLinqFirst / loopMax) +
      " List_LinqWhere: " + (overallListLinqWhere / loopMax)
    );
  }

And the holder class which is a nothing class. I just didn’t care for having to add parameters to the child mehod.

  public class Holder
  {
    public Int64DictionaryContainsKeyTime { get; set; }
    public Int64DictionaryStraightIndexCheck { get; set; }
    public Int64ListLinqAny { get; set; }
    public Int64ListContains { get; set; }
    public Int64ListLinqFirst { get; set; }
    public Int64ListLinqWhere { get; set; }
  }

Couple Notes:

  • StopWatch is in System.Diagnostics
  • RandomTool is actual a class of mine. Nothing special about it. Just makes a string of X length with all random letters.
  • This can not be rebroadcast or retransmitted without the express written permission of my mom.

Asp.net Mvc Master Page: System.Data.Entity Must Be Referenced

Ok maybe you’re better at figuring out the obvious than I am, but this was annoying me. On my master page I happened to be using an object from another assembly that used the Entity Framework. Now by habit, I have this assembly:

System.Data.Entity, Version=3.5.0.0

Referenced to the UI project, so it was a little of a surpise to me that I was getting this error on the master page. (And the views, but I don’t use anything in Views not supplied by Models) I was at a loss as to how to get the thing to work.

Now I could use this:

<%@ Assembly Name=”System.Data.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089%>

On the page, but would be silly to do that all the thing, and DUH in WebForms… or ASP.Net Classic, is to put it in the stupid web config.

  <system.web>
    ...
    <assemblies>
      ...
      <add assembly="System.Data.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
      ...
    </assemblies>
  ...

No more problems.

The Mythical ++ Situation: ++ vs +=1

So this may be a post that most good programmers will think, “Well duh” but as I’m a tool this finally caught me.

I’d always heard that ++ evaluates differently than +=1, but I’d never run into a situation that would turn the old light bulb on so I really didn’t care. Well I met that situation today.

I was writing a method that basically checks to see if all the dates in a list are in order by creating a dictionary, assigning the index as the key, and sorting by the date. I then convert the keys to an array and make sure that the index is the same as the key. After all, if the dates are in order, the keys should mimic an index.

  Key     Date
  0        6-27-2008
  1        6-28-2008
  2        6-29-2008

So that the new array would be:

  [0]    0
  [1]    1
  [2]    2

And if anything was out of order, you would get something like this:

  [0]    0
  [1]    2
  [2]    1

So the code is basically:

  int loopCounter = -1;

  IDictionary<DateTime> timeSequence =
                dateList
                .ToDictionary(item => loopCounter++);
  var sequenceList =
                 timeSequence
                 .OrderBy(item => item.Value)
                 .Select(item => item.Key).ToArray();
  return sequenceList.Any(item => item != sequenceList[item]);

Now right off the bat you’ll see that I used loopCounter ++. The thought was that in order to get this correctly inline (Meaning the key would mock an index) I would have to keep adding to the loopCounter. Well my thought was simply to use ++ and thus I would have to set the loopCounter to -1 at first otherwise the first key would be 1. Well that’s not what happened. Turned out it looked like:

  [0]  -1
  [1]   0
  [2]   1

Wait what? -1? But I added to it! And here was the catcher. Turns out in this situation, the ++ acts out like:

  • Set the key to what the loopCounter equals right now.
  • Add 1 too the loopCounter
  • Continue with loop

It actually set the key BEFORE adding the 1 to it. So in reality with this I really needed loopCounter to start at 0 OR use +=1 which would actually add the 1 THEN set the key to the value. Guess I should have paid more attention in school instead of checking NBA message boards.

Side note: Light bulb apparently is two words. I learned TWO things today.

Entity Framework, Include, and Data Item classes

So found something interesting out the other day, and maybe you already knew this but I didn’t so I’m going to post about it. Don’t like it? Too bad.

One things nice about the Entity Framework is the ability to create or fill a class on the fly with the Linq query methods/language. You.. you have no idea what I’m trying to say. Fine. I’ll put it in programming speak:

  someList.Select(item => new { item.Name, item.ID })

  or

  from item in someList
  select new { item.Name, item.ID }

OR

  someList.Select(item => new DataItemClass { Name = item.Name, ID = item.ID })

  or

  from item in someList
  select new DataItemClass { Name = item.Name, ID = item.ID }

As you can see, they are two slightly different examples. One will create a list of anonymous types and the other a list of DataItemClass objects. Now that’s not really the point of this, the point is something like this:

  context.Topics
    .Select(topic =>
                new TopicItem
                {
                  TopicName = topic.Name ,
                  Creator = topic.User.UserName,
                  Category = topic.Category.Description
                }
              )

Now, here’s the thing that I assumed. When you select out a bunch of topics and you want to make sure that the one to on properties are “include”ed like thus:

  topicList
   .Include("User")
   .Include("Category")
   .Select(item => item);

Other wise when you try to access that User property you’ll get a null reference exception. So with this I thought that when you query like I did above to fill the TopicItem object, I would get the same problem as I would if I tried just accessing the property on a hydrated Topic. In other words:

  Creator = topic.User.UserName,

Would blow up mid query after all calling that property after a query would sans include. Come to find out, and I probably should have already known this, Entity Framework is just fine without having to have the Include method or any kind of join. Infact, adding the include method in the method chain:

  context.Topics
    .Include("User")
    .Include("Category")
    .Select(topic =>
                new TopicItem
                {
                  TopicName = topic.Name ,
                  Creator = topic.User.UserName,
                  Category = topic.Category.Description
                }
              )

Did nothing when I profiled the query. The SQL was exactly the same with or without the include. So it’s smart enough to know that if I am not actually hydrating an entire Topic object, it doesn’t need to bother with the includes. Go figure.