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.

Off Topic Sunday: Does Not Liking Quentin Tarantino Make Me A Mutant?

COMPLETELY NOT PROGRAMMING RELATED

Any time I declare this I always get the same look people had when that one dude in Total Recall took off his glove and had that weird chicken wing arm thing. I can’t think of many directors that get the same free pass as he does for making, in my crazy mutant opinion, two good movies: Pulp Fiction and that one part of Four Rooms with the Zippo lighter bet. Ok so one movie and a section of another. Maybe Kill Bill 2 could be in there. Maybe.

Now I have to admit that I’ve been accused of having less than main stream opinions on movies. I’m not one of those people that only like a movie if it’s made on a 10k dollar budget and ends up just as depressing as it started. (IE Every independent movie ever.) I enjoy movies that are thought provoking and relevant as questions like “What would green smell like?” or “Why do I have 10 ten toes?” However, I liked Star Trek: The Motion Picture the most out of the six because I felt it was very Star Trek like and the most intense of the bunch. I liked Alien 3 more than Aliens (Only after watching the Director’s cut version though) because it had more thought out undertones. I think that Kill Bill 2 is far more interesting than 1 because it had story minus a bunch of tools running around like they’re athletic (See The Matrix). I also still find Godzilla versus Mechagodzilla to be the best, even though Godzilla 2000 is far superior in ever aspect, because that one part where Gozilla and King Caesar are standing in front of and behind, respectively, Mechagodzilla and they think they have it flanked when it turns it’s head around to look at King (With it’s laser eyes) and swings out it’s missle hands at Godzilla almost as if it was sayin, “You thought you got me, but I got missles b–ch. You ain’t got s–t. ”

Three things you can take from that: I probably don’t line up with your tastes, I do have thought out excuses for my “condition”, and I am a massive geek. I honestly feel that at this point I need to boost a car, take some E, and bench press 800 pounds at the same time to offset the horrendous black hole of geek I just created that threatens to pull us all in to an alternate, more geeky version of the world. No one wants that. No one but Adam Savage wants that.

At this point, you might see where I’m coming from. I’m clinically insane. However, that doesn’t mean I’m not entitled to an opinion on Tarentino. The guy is like a 12 year old with a budget.

Remember when you were 12, watching Power Rangers, sitting in a rocking chair, while lathering yourself in a mixture of peanut butter and motor oil? Probably not (But if you do, call me) but you might remember watching a movie like Aliens and thinking “What if the aliens could talk?” or “What if the Aliens could use guns, that would be sweet cause they would be all like ‘What up!’ BLAM BLAM ‘Screw you Marines!'” And let’s be honest, there’s a reason why you weren’t making films at 12… or probably even now. (Honestly? Aliens using guns? What the hell were you on at 12?) Every time I see one of his movies now, that’s all I can see: Tarantino lathered up in pean… Wait… I see Tarantino sitting around writing some movie, probably a masterpiece about a child who is taken from his family, forced into slavery, and then finds a way to unite the slaves against the slavers and bring peace to the his people. Followed by weeks of “What if aliens some how helped him free his people?” and then “What if the aliens give him awesome laser weapons and then there’s a scene where he’s all like ‘I’m gonna make them pay’ while standing on a mound of dead slavers and then he points the gun at one that’s still sort of alive and shoots him and his head explodes and the aliens start dancing in joy! Oh man that’d be cool.” (You might also call this the “Lucas effect”) Somewhere, at some point, the good ideas he may have go from a smooth riding train to a train that just lost a wheel, jumped the track, and is plowing through some childrens’ hospital.

And guess maybe that’s the problem I have with him. It’s clear that the guy is good with conversations and characters. It’s clear that he could be a premier writer. It just seems like the 12 year old side of him takes over at some point. Oh well, that 12 year old has done him well financially so who am I to say what’s good?

In the end, it just comes down to preference. Maybe I don’t have the part of the mind that gets satisfaction from way over the top insanity in movie form (I think it’s seated somewhere in between the part that enjoys chili cheese fries and the part that makes people stop and stare at highway accidents.), and if you do well more power to you. Just don’t judge me based on my thinking he’s straight up overrated or that he isn’t a god of filming. Then again I’m not the kind of person who looks for religious overtones in the Star Wars series, so maybe I’m just too dumb to see the brilliance.

Oh and side note: HE HAD NOTHING TO DO WITH HERO EXCEPT WITH HELPING WITH PUSHING UP THE TIME LINE OF THE US RELEASE. Don’t f–king even think he had any real hand in what’s probably the best epic movie in existence.

Other Note: Apparently resident “computer wiz” Andre refused to read more than the title of this post. He’s one of them…

Random Add-On – Automapper

So if you’ve bothered reading my posts in the past, and don’t worry cause I haven’t, you might have seen me express my rule about not wanting to use third party stuff. Well things change. Actually they don’t, as I’m not bending the rule because I’m becoming a better person, just more lazy. This is where Automapper comes in.

Automapper is pretty much what it sounds like, it maps class properties automatically. Maybe a more clevererest name would have been ClassPropertyAutoMapper, but the guys who made it shouldn’t be persecuted for lacking creativity.

How simple is Automapper? Simple enough that even you can use it. Now that’s simple! Say you have two classes, a entity class and a model, and you want to map the model to the entity in the constructor. You could do:

  public class SomeModel
  {
    public SomeModel(SomeEntity someEntity)
   {
     SomeProperty = someEntity.SomeProperty;
   }
  }

But where’s the lazyiness? I expect so much less from you. But it’s ok, salvation is right here:

  public SomeModel(SomeEntity someEntity)
  {
    Mapper.CreateMap();
    Mapper.Map(someEntity, this);
  }

But… but what if there are properties on SomeModel that don’t directly map by name? Well, there’s an ap…i for that. (Not sure that even makes sense but it was clever.)

  public SomeModel(SomeEntity someEntity)
  {
    Mapper.CreateMap<FiftyPostUser, UserInfoViewModel>()
     .ForMember(test => test.Status, tester => tester.MapFrom(item => item.Status.ToString()));
    Mapper.Map(someEntity, this);
  }

So I know you’re thinking that there’s a catch, well there is. You have to actually get the dll and reference in your project. I know! Work is hard. Why can’t these guys just come to your place of work/home/mom’s basement and do it for you? What kind of world is it when you can’t get all that for free? Personally, I hate it.

State List in Dictionary Form

Tired of having to look this up from time to time, so I’m putting this here for my own use. If you get something out of it, good for you. In the end, I really don’t care.

    public Dictionary GetAllStates()
    {
      if(_stateList == null)
      {
        _stateList = new Dictionary();

        _stateList.Add("Alabama","AL");
        _stateList.Add("Alaska","AK");
        _stateList.Add("American Samoa","AS");
        _stateList.Add("Arizona","AZ");
        _stateList.Add("Arkanas","AR");
        _stateList.Add("California","CA");
        _stateList.Add("Colorado","CO");
        _stateList.Add("Connecticut","CT");
        _stateList.Add("Delaware","DE");
        _stateList.Add("District Of Colombia","DC");
        _stateList.Add("Federated States Of Micronesia","FM");
        _stateList.Add("Florida","FL");
        _stateList.Add("Georgia","GA");
        _stateList.Add("Guam","GU");
        _stateList.Add("Hawaii","HI");
        _stateList.Add("Idaho","ID");
        _stateList.Add("Illinois","IL");
        _stateList.Add("Indiana","IN");
        _stateList.Add("Iowa","IA");
        _stateList.Add("Kansas","KS");
        _stateList.Add("Kentucky","KY");
        _stateList.Add("Lousiana","LA");
        _stateList.Add("Maine","ME");
        _stateList.Add("Marshall Islands","MH");
        _stateList.Add("Maryland","MD");
        _stateList.Add("Massachusetts","MA");
        _stateList.Add("Michigan","MI");
        _stateList.Add("Minnesota","MN");
        _stateList.Add("Mississippi","MS");
        _stateList.Add("Missouri","MO");
        _stateList.Add("Montana","MT");
        _stateList.Add("Nebraska","NE");
        _stateList.Add("Nevada","NV");
        _stateList.Add("New Hampshire","NH");
        _stateList.Add("New Jersey","NJ");
        _stateList.Add("New Mexico","NM");
        _stateList.Add("New York","NY");
        _stateList.Add("North Carolina","NC");
        _stateList.Add("North Dakota","ND");
        _stateList.Add("Northern Mariana Islands","MP");
        _stateList.Add("Ohio","OH");
        _stateList.Add("Oklahoma","OK");
        _stateList.Add("Oregon","OR");
        _stateList.Add("Palau","PW");
        _stateList.Add("Pennsylvania","PA");
        _stateList.Add("Puerto Rico","PR");
        _stateList.Add("Rhode Island","RI");
        _stateList.Add("South Carolina","SC");
        _stateList.Add("South  Dakota","SD");
        _stateList.Add("Tennessee","TN");
        _stateList.Add("Texas","TX");
        _stateList.Add("Utah","UT");
        _stateList.Add("Varmont","VT");
        _stateList.Add("Virgin Islands","VI");
        _stateList.Add("Virginia","VA");
        _stateList.Add("Washington","WA");
        _stateList.Add("West Virginia","WV");
        _stateList.Add("Wisconsin","WI");
        _stateList.Add("Wyoming","WY");
      }

      return _stateList;
    }

So there. Hope you’re happy.

Back, Back from the Dead… Again

So Andre, the only person I know to argue with a toaster and lose, has mostly completed moving the site over to the new hosting. Issues? Well there are some lost comments. It’s sad, I know. Your 15 minutes of fame just got washed away like sand on a body of land that is within sufficient proximity of a body of water so that it is carried away if said body of water has the needed tide to carry it away. I’d cry for you but I have no tear ducts.

Going forward, you can feel confident that if you leave a comment it will exist until we change hosts and Andre has control of moving it again.

.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.

Sql 2008 – You have either made changes to a table that can’t be re-created or enabled the option Prevent saving changes that require the table to be re-created

If you’ve run into this issue:

Saving changes is not permitted. The changes that you have made require the following tables to be dropped and re-created. You have either made changes to a table that can’t be re-created or enabled the option Prevent saving changes that require the table to be re-created.

Normally I don’t like copy/paste solutions but I also can’t stand wading through Microsoft issue explanations. This is how you fix it in quick picture form:

Here it is.

Tools -> Options -> Designers

The worded Solution is from here.

While trying to save changes to a table, it’s because you’ve done this:

  • You change the Allow Nulls setting for a column.
  • You reorder columns in the table.
  • You change the column data type.
  • You add a new column.

And there it is folks, simple and done with.

.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: Quick Overview of Controller Structure

Wow, that’s a mouthful far as titles go, but couldn’t think of a better way to say it. Now what I’m about to go through is the “system” I have found that works pretty well when it comes to structuring controllers knowing that there will be asynchronous operations. Why is that a big deal? Well where you put certain methods can depend on which controller actually owns the action.

When I started using MVC, I had some issues on figuring out how to build controllers so that they made sense from a structural point of view. I slightly touched on it but I wanted to show where I progressed to in the vain hope that I can help prevent stumbling on your part.

One thing to be noted is the asynchronous part. I’ve become a firm believer that MVC is pointless without asynchronous operations. Why? Simply put, you can use them or you can come up with some annoying post and redirect for any create, update, or delete operations. If you’re going to do that, you might as well just be institutionalized because you are one masochistic mother f—er. For everyone else in the happy world, go with something like jQuery that makes it real easy to perform said operations.

With the last paragraph in mind, the part I had trouble with the most was figuring out where the actions go. You see, when I started using MVC, I grouped stuff in an ultra simple manor. Say I have a site for handling pictures. Well there would be a view controller that would have anything to do with viewing images and an admin controller that took care of the uploading, changing, deleting, ecting. As you can imagine, this was not what you might call ideal.

Once I got a feeling for MVC and how it worked, I started having things a little more separated but still didn’t feel right. I had actions for viewing a list of images on the image controller no matter if public or admin side which wasn’t really ideal to me since it kind of blurred what was public and what was restricted from a conceptual point of view.

It wasn’t until I started thinking in terms of unit testing that it started to make more sense. If I were creating controllers as if they were classes instead of pages like with WebForms, maybe it would work out better. Seems real profound right? Well it was at the time since I still had WebForms state of mind. All of a sudden, it made way more sense on how the controllers should be set up. In an odd way, the controllers almost became almost business layer like. If I wanted to update an Image, there would be an Update method on the image controller responsible for taking in the changes, validating, and dealing with the entity objects. Everything that had to do strictly with displaying information would be handled by a display controller like the before mentioned Admin controller. So something like:

Controller Outline

As you can see, the Admin controller has something to show all users. The User controller has the methods for things like updating, creating, and validation. Basically anything that would change an image is on one controller. Anything for showing it on the main section controller. That is, a controller that embodies an overall concept like say an Admin section of a site or possibly a controller for viewing galleries.

The sequence of events (bad word choice…) would be something like:

Open Admin/UserList/
Admin controller uses User Entity to retrieve list
Admin View shows User List
User clicks delete button/link on Admin View
Javascript/jQuery method invoked to send id to User/Delete
User controller receives id
User controller validates id to make sure it is valid
User controller validates current user to see if allowed to delete
User entity Delete method invoked by User Controller
Result of Delete Method is returned by User Controller (JSon preferably)
Admin View displays the result

Treating controllers like classes (and the use of anonymous actions) allows a very clean separation of actions resulting in a nice logical layout. Beyond this, it also allows for a greater separation between controllers which means its possible to do multiple parts of the entire project in parallel.

Maybe this is just stating the obvious, something I’m pretty good at, but my hope was to give a quick over view of laying out controllers for those who are just starting out.