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

Do It Yourself

A question came up about an earlier post on how I construct my grids shown in a few examples.


Now as you can see, it looks like a table, acts like a table, so it must be a table right? Well it isn’t. It’s actually done with divs and styles, something I’ve worked hard on getting right since moving to MVC.

I’m not bagging on the question asked because I’m probably a mutant and the only person that thinks the way I do (and have written below). I just have a philosophy that if you can do it yourself, do it yourself.

For starters, I’m not against new stuff, I think that’s pretty obvious. I’m also not completely against third party stuff seeing as a lot of my newer posts deal with jQuery. I do, however, avoid third party tools I don’t need, namely grid builders or things of that nature. I figure that if I can do it myself, I’ll do it myself. This kind of hits on the debate of using Visual Studios’s drag and drop feature for designing pages or not. Sure it’s easy and for the most part works, but you are really doing yourself a disservice. Why? Because most of the time you can get away with it, it’s those few times that it just won’t do what you want it to do that kill you.

When you use helper tools, you could be cheating yourself out of knowledge

Now I’m not saying that you should develop your own tools for rendering 3d graphs. Some things you just don’t have the time or the ability to create, but when it comes to simple things like markup, do the work. The knowledge you gain from this is substantial. Hell, I used to hate style sheets. I used to hate javascript. Quite frankly, they were a pain in the a– at first. However, taking the road less travelled has given me a new perspective on both. I no longer fear them and in fact would rather just type the markup out myself than trust some third part thing that I can’t fix when something goes wrong. I know that if I have to create a quick mock up that looks like the real deal, I can do that with notepad and a browser. I know that if I have to teach someone how to use style sheets or javascript, I can do that without just telling them to go to some page or to use some random tool. I have confidence in my knowledge.

More time now, less time later.

Now I know in Perfectworld, there is always enough time allotted to doing what needs to be done. In Realworld (Not the stupid MTV show) everyone is running around, heads a blaze. So the biggest excuse to not learn proper markup is that there isn’t time. A company isn’t going to pay you to learn when things need to be done. Well sure, but flash forward a couple months when someone tells you that you have to adjust the grid you didn’t build yourself to add something you have no idea how to add or else the world is going to end. Last thing that person will want to hear is “It can’t be done.” In fact, most business people have some crazy allergic reaction to that phrase that causes them to turn really, really red. It’s weird but happens a lot. At this point you can either:

Laugh and lose your job.

Go on the forums and hope there is a solution.

Die a quick and painful death.

Always expect people to want 20% more than what was originally written. Unless you have one of the best project managers that says the phrase “Work request form” on instinct, you will run into this situation. That’s where doing it yourself comes in real handy. It may have taken you a while to figure it all out, but you will for certain be able to fix the issue quickly.

You never know when you’ll actually have to know how to build things from scratch

Tech Interviews. When looking for a job, you’ll probably run into these. Best way to be prepared for these? Have the real world knowledge. How do you get that? By doing a lot of the work yourself. I have been through interviews where I was given a simulated work item and told to produce code for it on the spot. Some of it had to do with the actual markup needed to display the data. (This was before MVC days, WebForm stuff) The people were far more impressed that I was typing out the mark up than if I had just done drag and drop stuff. Why? Because there is a stigma, fair or not, that drag and drop people are displaced VB Weenies, and the real programmers don’t bother with it. Knowing how to hand code mark up on the spot is far more impressive than using visual tools or completely blanking out because you’ve had to rely on third party software.

At this point I realize I’ve mostly talked about markup, but this whole idea extends to a lot of the programming world. Digging in and forcing yourself to do the work will substantially improve you abilities over time. If you can’t do this at work then find some time on your own to work on a side project to learn. Build your own error handling system. Build your own pager creating method. Build your own Url creating method for MVC. I promise that you will be in a much better position.

Final Note

You could argue that coming to a site like this and using copy/paste is against my spiel. Fact is, I’ve copy and pasted plenty of code to get to where I want to go. Difference between this and third party tools is you can learn from what you copy and paste. Actually I would argue that you have the responsibility to learn about what you are copying before you do anything with it. If you copy AND you take time to understand what you are copying, that can be just as helpful. If nothing else, it’s better than just using some third party method.

ASP.Net MVC: Attibute to Check if Route Value Exists and… and Means Something!

Get ready for a roller coaster ride around the insanity that is me. You might actually find it amusing but most likely you’ll just leave sick or underwhelmed. Don’t feel bad if you do, you wouldn’t be the first and, thanks to somehow being impervious to Natural Selection, you won’t be the last. Be proud.

Here’s what this post is about: Say you have a url like eh:

/User/View/1

Where 1 represents a UserId to a user that exists in some matter of context. (Does that makes sense?) Well there are a couple of things that could go wrong here. For one, if you don’t want to have a nullable id in your signature:

  public ActionResult View(Int32? userId)

This could cause ouch:

/User/View/

But this problem is deeper. Much deeper. In fact so deep it deeper than even Piper Perabo has ever deeped before. Yrraaaahh!

What if the id doesn’t even refer to anything? Say the id is 101 but there’s no user with the id of 101? Beyond that, what if the id could be Id in some routes but UserId in others? WHAT WOULD YOU DO???

The idea here is to have something neato like this:

  [UserExistsById]
  public ActionResult View(Int32 userId)

And if that id is junk, then you redirect to an error page. Well if this sounds interesting, I’d be surprised, but read on in the event that it does.

Now this isn’t accomplished in the most simple manor, but for good reason: The more time in means the less time repeating. First method we need is something to simply check the route data to see if something exists:

  public static Boolean RouteDataValueExists(ActionExecutingContext filterContext, String idToCheck)
  {
    return filterContext.RouteData.Values.ContainsKey(idToCheck);
  }

Real easy. It either has been digested by MVC and regurgitated into some kind of route value or it hasn’t. Basically this is the first check. After all, if it doesn’t exist why bother going further?

Next is the method that will be calling this one. Mainly one that uses the RouteDataValueExists and if returns true, then it actually checks the value against where ever the user is persisted.

  public static Boolean ValueFoundAndItemExists
  (
    ActionExecutingContext filterContext,
    Enum idToUse,
    Func<ActionExecutingContext, Enum, Func<Int32, Boolean>, Boolean> check,
    Func<Int32, Boolean> exists
  )
  {
    Boolean checksOut = false;
    String convertedId = idToUse.ToString();

    if (RouteDataValueExists(filterContext, convertedId))
    {
      checksOut = check(filterContext, idToUse, exists);
    }

    return checksOut;
  }

Ok so kind of a lot at first and it’s hard to decide how to present this system, so just go with it.

  Enum idToUse,

This is a design choice. In reality this will be turned into a string anyhow, but the idea is it will be what to check the route values for. So if you are checking for UserId, you will pass in UserRequestTypes.UserId. Again this was a choice on my part as I hate passing text around.

  Func<ActionExecutingContext, Enum, Func<Int32, Boolean>, Boolean> check,

This is the method that will be used by ValueFoundAndItemExists to delegate out the actual checking if the id is an integer and is a real user.

Func<Int32, Boolean> exists

This will be the method that you will use to delegate the whole checking if it exists in the database. Something like:

  class User
  {
    public Exists(Int32 id)
    {
       return EntityContext.Context.User.Any(user => user.Id == id);
    }
  }

Still with me? No? Greeeeat. Next up is the base class that contains the

  Func<ActionExecutingContext, Enum, Func<Int32, Boolean>, Boolean> check,

parameter from above.

public abstract class BaseExistsAttribute : ActionFilterAttribute
{
  protected Boolean Exists
  (
    ActionExecutingContext filterContext,
    Enum idToUse,
    Func<Int32, Boolean> exists
  )
  {
    Int32? id = Convert.ToString(filterContext.RouteData.Values[idToUse.ToString()]).ConvertTo<Int32>();
    return id.HasValue && exists(id.Value);
  }
}

Ok so something might look familiar like well basically all the parameters. The reason for this is that there is a little bit of delegate passing going on with this whole system. One method passes on methods to other method in some kind of crazy method hoe down without the flanel shirts.

You will notice the use of the enum in this part:

  idToUse.ToString()

Again, you can easily just pass in a string instead of an enum, I just did this to stay away from strings.

Only thing that might be of interest is the ToConvert method that you can find here. You don’t have to use it, you can simply just do a try parse on the

  filterContext.RouteData.Values[idToUse.ToString()])

To get an integer. That’s up to you. I could have just put that in the code for you to see but then I couldn’t randomly plug another post of mine.

Finally you have the actual attribute class:

  [AttributeUsage(AttributeTargets.Method)]
  public class QuoteExistsByQuoteId : BaseExistsAttribute
  {
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
      base.OnActionExecuting(filterContext);

      if
      (
        !MvcMethods.ValueFoundAndItemExists
        (
          filterContext,
          UserRequestTypes.UserId,
          Exists,
          UserEntity.Exists
        )
      )
      {
        filterContext.Result = SiteMethods.ErrorOut(ErrorNames.General_PageError);
      }
    }
  }

And now it all comes together.

  UserRequestTypes.UserId

This is the enum I’ve been talking about this entire post! Now that I think of it, not really exciting.

  Exists

That’s the method on the base class that checks for everything.

  UserEntity.Exists

And that’s the method I need to check the persistence if the user is real. Remember? Takes in an integer and returns a boolean? Yes? Yes? No?

What’s ErrorOut? Again this is just a method I made to create an ActionResult that is an redirect to an error page. Not hugely important. It’s just what handles the situation when the value is bogus…. dude.

  [UserExistsById]
  public ActionResult View(Int32 userId)

And there you have it. Hopefully it was useful in some way but I’m not of touch with reality.

jQuery: Find All Checked Checkboxes

So this is sort of a repeat of another post, but I figured it has some use on its own.

Say you have this:

  <div>
    <input type="checkbox" name="JqueryIdList" value="1"  />
    <input type="checkbox" name="JqueryIdList" value="2" />
    <input type="checkbox" name="JqueryIdList" value="3" />
    <input type="checkbox" name="JqueryIdList" value="4" />
  </div>
  <div onclick="getIds('JqueryIdList');">
    CLICK
  </div>

And you need the getIds method to find all the checked checkboxes from that markup. Well it’s actually fairly simple, or at least it wil be once I enlighten you. I should get paid for this…

  function getIds(checkList)
  {
    var idList = new Array();
    var loopCounter = 0;
    //find all the checked checkboxes
    jQuery("input[name=" + checkList + "]:checked").each
    (
      function()
      {
        //fill the array with the values
        idList[loopCounter] = jQuery(this).val();
        loopCounter += 1;
      }
    );
    ...
  }

The important part is this:

 jQuery("input[name=" + checkList + "]:checked").

As you can see, it is very simple. Give it the name of the checkboxes, add on the “:checked” and boom you have a list of checked checkboxes. Could it be more simple? I think not.

jQuery, Hidden Elements, and Why At Times I Hate It

So this is your situation, or at least it might be someday if you use jQuery:

You have a comment area that allows a user to view comments. Now this comment area is created using javascript (Read jQuery) only. When a user clicks on some kind of pager, a method is called to get a list of comments and recreate the comment table. Now you would think it would be a good idea to hide the table, recreate it, and then show it. Sounds like a decent way to go. So you try something like this:

  ...

  jQuery(commentTable).hide("slide", { direction: "up" }, 200 );

  ...

  //Get the comments and call a method to build the table.

  ...

  function buildTable(commentList, commentTable)
  {
    ...

    //Take the list and iterate.  Create a row

   ...

     jQuery(commentTable).appendChild(someCreatedDivRowWithAComment)  //BOOM

   ...
  }

Then you run it and bam you get an error saying that basically commentTable doesn’t exist. Now if this were WebForms and you did some kind of visible=”false” you would know that the markup for that table wouldn’t exist. However, in javascript style=”display:none;” doesn’t remove the element from the markup, it just hides it from the viewer. If you look at the source (Provided it’s not dynamically created) you will still see it in the mark up. So what’s the deal?

Well for some reason the creators of jQuery decided that there is a difference between a hidden element and a non hidden element to the point where you have to change your search (the jQuery() method is basically a search that looks for the element within the parenthesis) by adding on a “parameter”.

  jQuery(".someElement:hidden")

So if you do use the hide() method (Or fadeOut for that matter) you have to use the :hidden addon to find the stupid element. This can cause a big problem when things aren’t timed correctly. What does that mean? Well that 200 value I have in the hide method, that’s the time I want it to take to hide the element. Far as I can tell, and I’ve done some testing on this, the element is not :hidden until the animation completes. Which means there are 200 time units where it is not :hidden. Now if the time that it takes to get your comment list and start building the table is less than the time it takes to hide the element you’ve got an issue. Or conversely, if the 200 time units are up and it is now hidden, you’re really screwed because the normal search won’t work. You can try something like this:

   if(jQuery(this).children(".categoryBlockContainer").is(":hidden"))
  {
    categoryBlockContainer = jQuery(this).children(".categoryBlockContainer:hidden");
  }
  else
  {
    categoryBlockContainer = jQuery(this).children(".categoryBlockContainer");
  }

And this works ok most of the time, but you still might run into a situation where it’s still trying to finish the hide animation. Beyond that, it seems kind of asinine to have something like that in the code. It should find the element at all times, hidden or not.

This really kills the whole idea of animation.

Between this and javascript’s bizarre variable scope, I’ve had some thoughts of changing my profession.

ASP.Net MVC How To Handle Multiple Checkboxes With Views/Actions… jQuery too!

Just a note, this is kind of an add on to this post but it’s a much more simple (HOSTED) example and also deals with doing the whole check box thing with jQuery.

So one of the things I ran into some what recently was a grid… a grid with a death wish and a thirst for revenge. It also has a bunch of check boxes to allow multiple row deletes.

Now there might be a moment of panic and doubt (Or doubt and panic, everyone reacts differently) when you realize you no longer have those cushy grid postback events. WHAT ARE YOU GOING TO DO???? Well first you’re going to feel disgust over your profuse sweating, cause lets be honest you’re pretty gross. Then you’re going to read on and find that all your panic, fun as it can be, was for nothing. Why? Because you have me… and not in some weird love kind of way because I don’t even know you. More of a “You can count on me because I’m like that cool older brother you never had and because of which you ended up a social degenerate ie a programmer” kind of way.

Now to start I’ve already hosted both the code and a working example:

Actual running thing on teh webz.

Hosted code

Because I’m such a nice guy. (And that’s true, I can list at least five people who aren’t my mom who can attest to that.) However, I wouldn’t be the nice guy that I am if I weren’t going to at least explain some of the code.

There are two ways I handle this situation in the example I hosted, one is with a form, action, and post back. The other is with jquery and an asynchronous call. Both are actually pretty easy to pull off.

First let’s look at the post back version. The mark up looks a little somethin’ like dis:

  <form action="/Test/CheckForIds/" method="post">
    <div>
      <input type="checkbox" name="IdList" value="1"  />
      <input type="checkbox" name="IdList" value="2" />
      <input type="checkbox" name="IdList" value="3" />
      <input type="checkbox" name="IdList" value="4" />
    </div>
    <div>
      <input type="submit" value="go" />
    </div>
  </form>

Looks like your standard form and if you’ve used MVC at all, you should be used to seeing something like that. The only thing of interest is that the checkboxes don’t have ids and do share the same name. There’s a good reason for the second one. Here’s the action method:

  [AcceptVerbs(HttpVerbs.Post)]
  public ActionResult CheckForIds(Int32[] idList)
  {
     return View(idList);
  }

Now it makes more sense, doesn’t it? The name attribute on the checkbox directly corresponds to the name of the array parameter. THAT’S AMAZING!!!1 Actually, kidding aside it is kind of nice. Not only does it match the checkboxes to the parameter, it also treats the values of the checkboxes (Checked ones) as a list of integers. Pretty slick.

And honestly, that’s about all it takes for traditional posting.

Now for the jQuery part:

  <div>
    <input type="checkbox" name="JqueryIdList" value="1"  />
    <input type="checkbox" name="JqueryIdList" value="2" />
    <input type="checkbox" name="JqueryIdList" value="3" />
    <input type="checkbox" name="JqueryIdList" value="4" />
  </div>
  <div onclick="getIds('JqueryIdList');">
    CLICK
  </div>

Wow, looks about the same. Go figure. Well that’s pretty much because the way hard part is the javascript itself.

  function getIds(checkList)
  {
    var idList = new Array();
    var loopCounter = 0;
    //find all the checked checkboxes
    jQuery("input[name=" + checkList + "]:checked").each
    (
      function()
      {
        //fill the array with the values
        idList[loopCounter] = jQuery(this).val();
        loopCounter += 1;
      }
    );
    //Send the list off
    jQuery.getJSON("/Test/CheckForIdsJson/", { idList: idList }, idsGotten);
  }

Ok maybe it wasn’t that hard or hard at all. But um… And here’s the action method:

  [AcceptVerbs(HttpVerbs.Get)]
  public ActionResult CheckForIdsJson(Int32[] idList)
  {
    JsonResult result = new JsonResult();
    result.Data = idList;

    return result;
  }

So again, the same signature. Amazing huh?

Side note:

When I was eating this morning in front of the television (Chocolate shredded mini wheats if you must know.) I came upon the good ole classic Iron Eagle. I never really thought about how utterly f-ing insane that movie was until now though, mostly because I haven’t seen it since I was a kid. I guess back then I could completely buy into the idea of some 17 year old, who can’t make it into the Air Force Academy, suiting up and learning to use (At the time) the most complicated fighter the US had to offer within what? one whole montage, steal a 18 million dollar plane (Planes were cheap back then), fly into crazy dangerous territory, get past who knows how many trained professionals, save his dad, and nothing really comes of it. Actually I think if I remember (as I didn’t get to watch the whole thing this time) he gets a place in the academy from this. IT’S A COMPLETELY BELIEVABLE STORY! The best part about it is that apparently between the time of the first and second movie his skills had depleted so fast that he gets popped at the beginning of the second one. I guess without the Saving Dad mojo, he’s just not the same. Tip your glass to good ole Thumper.

I really miss the 80s where movies didn’t really need to make any sense as long as they had some soundtrack filled with crazy obscure bands playing at random times in the movies itself followed by the movie characters commenting how great the music is.