Entity Framework: LINQ to Entities only supports casting Entity Data Model primitive types

So in typical tool fashion I posted this little gem without realizing a glaring error… the order by clause. The whole idea is to create a method that can get a collection, sort it, then grab a certain number for paging. The issue was this:

    Expression<Func<K, IComparable>> orderBy

The problem comes in when the entire expression is run, meaning when Entity Frame work takes:

    context.Select(selectMethod).Where(whereClause).OrderBy(orderBy).ToList();

and creates SQL out of it. Entity Framework doesn’t really know how to handle IComparable as it has not primitive/sql type to match to it. Why it can’t see the underlying type of say DateTime, no idea, but this is life.

So this should be an easy fix, right? Eh… yeah. First I thought instead of IComparable I could just convert to some kind of primitive type so that the EF could be on it’s merry. Not so much. Turns out this probably isn’t possible.

Well thanks to a push from Ben M at The O Flow I got to thinking about how to attack this. Instead of sending in an expression for the order by, why not send in a method that would take in a query and tell it how to order itself. Sounds hard right? (If not then you’re obviously too cool for this school) Well it’s not, just a different way to think about it.

Right off the bat, the change to the method signature would look like this:

Old order by parameter signature:

    Expression<Func<K, IComparable>> orderBy

New order by parameter signature:

    Func<IQueryable<T>, IOrderedQueryable<T>> orderBy

So what does that mean? It means that I am going to supply the method with a method that will take in a query and return an ordered query… well not ordered yet per se but the blueprint on how to order when that time comes around. Now here’s how that’s used:

First you need the query:

    var initialQuery = query
    .Where
    (
        somethingEqualsSomething
    );

Then you apply the orderby method, and in the case of the original paging method, the paging too:

    var orderedQuery = orderBy(initialQuery);

    returnValue = orderedQuery
      .Skip(numberToShow * realPage)
      .Take(numberToShow)
      .ToList();

So overall, doesn’t look too much different. Just instead of supplying the OrderBy method with a Func, you give a method that creates an ordered query.

How would you use this? Remember the signature was (whereClause, selectClause, orderBy, pageNumber, numberToShow, realPage, totalCountOfPages)

    Tools.GetListForGrid
    (
      tool => tool.EntityId == userId,
      tool => new { Name = tool.Name },  //Select Clause, I'll get to that next
      toolOuter => toolOuter.OrderBy(toolInner => toolInner .Name),  //OrderBy
      ...
    )

Two things you might notice. One would be the OrderBy signature:

   toolOuter => toolOuter.OrderBy(toolInner => toolInner .Name),

What the hell? Remember the method you are sending takes in a query and returns an ordered query. toolOuter is your query, toolOuter.OrderBy(toolInner => toolInner .Name) is your blueprint (IOrderedQueryable) on how it should be queried.

Second thing is that when I showed how to use the OrderBy method above:

    var orderedQuery = orderBy(initialQuery);

    returnValue = orderedQuery
      .Skip(numberToShow * realPage)
      .Take(numberToShow)
      .ToList();

I didn’t include the select clause. Partially because I didn’t want to complicate it yet, partially because it has it’s own issue. If you’re like me, you use the select clause a lot. Why? Because it limits the amount of information you take from the database. Say if you are trying to fill a drop down list, why select an entire Tool object (Which could have a ton of mapped properties) when all you need is Id and Name? Seems silly. That’s where the Select clause comes in. Now the issue is where to put the order by. You would think after the select clause, since you want to sort on only what you are selecting. Problem is, with paging that gets screwed up. The way sql server “pages” is that it selects twice.

Select all the things that match this where clause.
Select a certain number of items from that starting at X.

The first select creates a dataset with row numbers, and the second one selects the items based on those row numbers. IE take 5 starting at row 5. Now the way the EF handles the order by is to grab the info you need from the Select (Ordered by something… you don’t get to choose) and THEN order and grab. As you can guess this may not give the needed results. So how can this be solved? Order before the select as witnessed in the new and improved method:

public static IList<K> GetListForGrid<T, K>
(
    this ObjectQuery<T> query,
    Expression<Func<T, Boolean>> somethingEqualsSomething,
    Expression<Func<T, K>> selectClause,
    Func<IQueryable<T>, IOrderedQueryable<T>> orderBy,
    Int32 pageNumber,
    Int32 numberToShow,
    out Int32 realPage,
    out Int32 totalCountOfPages
)
{
    IList<K> returnValue;

    Int32 totalItemCount =
        query
        .Count
        (
          somethingEqualsSomething
        );

    totalCountOfPages = Methods.TotalCountOfPages(totalItemCount, numberToShow);
    realPage = Methods.GetRealPage(totalCountOfPages, pageNumber);

    var initialQuery =
      query
      .Where
      (
        somethingEqualsSomething
      );

   var orderedQuery = orderBy(initialQuery);

    returnValue = orderedQuery
      .Select
      (
        selectClause
      )
      .Skip(numberToShow * realPage)
      .Take(numberToShow)
      .ToList();

      return returnValue;
}

And usage:

    Tools.GetListForGrid
    (
       tool => tool.Id == userId,
       tool => new { Name = tool.Name },  //Select Clause
       toolOuter => toolOuter.OrderBy(toolInner => toolInner .Name),  //OrderBy
       pageNumber,
       amountToShow,
       out realPage,
       out totalCountOfPages
    );

Now this one actually works with Entity Framework and not just Linq to objects like the last one.

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.

Entity Framework: Reusable Paging Method

OBSOLETE… sort of. Found an issue with this and am posting the issue today. (07/21/2009)

A while back I decided to show some paging stuff and I forgot that recently, well ok in the last few months, I actually put together a sort of generic extension method to take care of most of the paging situations I was running into. Reason being is I got tired of writing the same method over and over. I figured I’d share it in hopes that somehow, somewhere, it would keep someone’s dream alive. That and I figured I needed to make up for not posting for a while… which to some of you might have been a good thing.

Anywho, it’s not to difficult actually. Small note though, when reading the code you will see the TotalCountOfPages method and the GetRealPage method. If you can’t figure out what those are then I just don’t know what to do. (HINT: They are linked somewhere in this very post! Side note: This post is on track to match the normal self linking per post quota on atypical Codding Horror post)

public static IList<K> GetListForGrid<T, K>
(
  this ObjectQuery<T> query,  //Extension method syntax... basically takes in any SomeEntities.SomeTableRepresentation
  Expression<Func<T, Boolean>> somethingEqualsSomething,  //Where clause
  Expression<Func<T, K>> selectClause,
  Expression<Func<K, IComparable>> orderBy,  //Turns out order by just needs anything that is IComparable
  Int32 pageNumber,
  Int32 numberToShow,
  out Int32 realPage,
  out Int32 totalCountOfPages
)
{
   IList<K> returnValue;
   //Get the total count of the items.  Need this to do proper paging.
   Int32 totalItemCount =
      query
      .Count
      (
         somethingEqualsSomething
      );

   totalCountOfPages = TotalCountOfPages(totalItemCount, numberToShow);
   realPage = GetRealPage(totalCountOfPages, pageNumber);

   returnValue = query
   .Where
   (
      somethingEqualsSomething
   )
   .Select
   (
      selectClause
   )
   .OrderBy(orderBy)
   .Skip(numberToShow * realPage)
   .Take(numberToShow)
   .ToList();

   return returnValue;
}

As you can see there are a lot of expressions going on and that’s the way this works. It takes care of the annoying stuff that you would have to copy an paste while you supply it the stuff that changes like what you want to select and what the needed items have to match to be selected. Even has something for an order by. What the usage look like?

  ToolEntities.Tools.GetListForGrid
  (
    something => something.SomethingId == passedInSomethingId,  //Where clause
    found => found,  //Select: Simple here.  Usually I use classes to hold info... next post
    found => found.Name,  //Order by
    pageNumber,
    amountToShow,
    out realPage,
    out totalCountOfPages
  );

Really simple, eh?

Why totalCountOfPages and RealPage out? Well the whole idea is that this infomation is valuable to the picker control you will be constructing outside this method call. RealPage is nice for showing what page the pager is on and how to figure out what the previous and next pages will be. TotalCountOfPages is useful for the last page possible. Now the nice thing about the RealPage method is that it won’t give you a non existent page. It will only give you the best possible page if the pageNumber parameter is over the possible amount of pages.

Also do notice that this is an extention method meant to be used with the Entity Framework’s built in system of handling the Table representations say ToolEntities.Tools.(Method will show up here in intellisense). This makes it cleaner to me than having to pass in the actual current context. As in:

GetListForGrid(ToolEntities.Something, …) vs ToolEntites.Something.GetListForGrid(…)

In the end, either way is fine.

ASP.Net MVC, jQuery, JSon, and paging… how’s that for a SOE title?

One of the things I’ve come to realize is how easy it easy to do a lot of things with these three buzzwords. In fact, I’m pretty convinced it’s so easy that it’s actually complex and I am a genius. Not buying it? Neither am I.

So for an experiement the other day I decided to try my hand at some sort of dynamic grid using jQuery’s ajax fun and JSon. Just so happens that this works really well with MVC’s REST like makeup. Don’t know what REST is? On a very tool level, it’s using a url and a command to tell the server what to do. So something like:

www.byatool.com/users/dostuff

Could mean either get all users (if using get) or create a user (If using post). And yes that is probably a ridiculously simplistic view so I’d suggest consulting the Wikitruth. In an MVC sense this would be:

Controller: Users
Action: dostuff

Now most likely your Get All Users action isn’t going to the same as your Add A User action, but it was just a stupid example ok?

However, with jQuery what this means is you have a simple url that it can call and get information from, making it incredibly easy to set up a dynamic grid.

So first off, lets say I have a Forum controller with an action of IndexJquery… yeah I know cheesy name, but it gets the job done. Basically the method IndexJquery would have to take in a page number and optionally (And for this example) how many items to show along with a sort. With that it should return a JSon “object” that will be in this example holds first page, last page, next page, previous page, sortBy, and some kind of list of stuff. (For the two people actually reading this, comment if you want the c# code. It’s really just basic MVC stuff.)

The markup for this is pretty simple. I have a div to hold the grid, four directional divs that work as buttons (First, Previous, Next, Last), and two div “butons” for how many items to show.

    <div>
        <div id="divHolder">
        </div>
    </div>
    <div>
        <div id="divFirstPage" class="divLink floatLeft">
            <<
        </div>
        <div id="divPreviousPage" class="divLink floatLeft">
            <
        </div>
        <div id="divNextPage" class="divLink floatLeft">
            >
        </div>
        <div id="divLastPage" class="divLink floatLeft">
            >>
        </div>
    </div>
    <div class="clear"></div>
    <div>
        <div id="divAmountToShowOne" class="divLink floatLeft">
            1
        </div>
        <div id="divAmountToShowFive" class="divLink floatLeft">
            5
        </div>
    </div>
    <div class="clear"></div>

As you can see exactly as advertised.

Ready for the call? It’s waaaaay hard:

        function getGrid(pageNumberIn, amountToShowIn, sortByIn)
        {
            jQuery.getJSON
            (
               //This is the url for the information I need
               "http://www.someurl.com/Forum/IndexJquery/",
               //this is the construction of the "object" to send... really this just
               //means that I have a method somewhere looking for pageNumber,
               //amountToShow, and sortBy
               {
                   pageNumber: pageNumberIn,
                   amountToShow: amountToShowIn,
                   sortBy: sortByIn
               },
               //This is the method to call once this ajax transaction has completed...
               //transaction may not be the best word.  Basically it has to be a method
               //that takes in the result from the getJSon call
               returned
            );
        }

Next would be the script to actually create the grid. Looks verbose, but most likely thats because I didn’t refactor much.

    function returned(jsonObject)
    {
        //Have to remove all the previous click event handlers since because
        //this is all client side, there's no "refresh" and therefore the object
        //is still in memory.  So even though I might call the method to get the
        //information, the "objects" are still in memory.
        jQuery("#divFirstPage").unbind("click");
        jQuery("#divLastPage").unbind("click");
        jQuery("#divNextPage").unbind("click");
        jQuery("#divPreviousPage").unbind("click");
        jQuery("#divAmountToShowOne").unbind("click");
        jQuery("#divAmountToShowFive").unbind("click");

        //Ok so now that the event is not being listened to, set up the listeners
        //The idea is to call that getGrid method and pass in the values straight
        //off the previously returned json object.  Using jQuery's easy .click method
        //makes this so simple.
        jQuery("#divFirstPage").click(function() { getGrid(jsonObject.FirstPage, jsonObject.AmountToShow, jsonObject.SortBy); })
        jQuery("#divPreviousPage").click(function() { getGrid(jsonObject.PreviousPage, jsonObject.AmountToShow, jsonObject.SortBy); })
        jQuery("#divNextPage").click(function() { getGrid(jsonObject.NextPage, jsonObject.AmountToShow, jsonObject.SortBy); })
        jQuery("#divLastPage").click(function() { getGrid(jsonObject.LastPage, jsonObject.AmountToShow, jsonObject.SortBy); })
        jQuery("#divAmountToShowOne").click(function() { getGrid(0, 1, jsonObject.SortBy); })
        jQuery("#divAmountToShowFive").click(function() { getGrid(0, 5, jsonObject.SortBy); })

        //Again since this is client side, the divHolder "object" still is holding
        //the previous results.  These have to be cleared.
        jQuery("#divHolder").children().remove();

        //Create the table and loop through the list.
        var mytable = document.createElement("table");
        var mytablebody = document.createElement("tbody");

        for (loopCounter = 0; loopCounter < jsonObject.ListForViewing.length; loopCounter++)
        {
           var currentItem = something.ListForViewing[loopCounter];
           var mycurrent_row = document.createElement("tr");

           var mycurrent_cell = document.createElement("td");
           var currentText = document.createTextNode(currentItem.ForumName);
           mycurrent_cell.appendChild(currentText);
           mycurrent_row.appendChild(mycurrent_cell);

           mytablebody.appendChild(mycurrent_row);
        }

        mytable.appendChild(mytablebody);
        //Don't forget to add the table to the div!!11
        jQuery("#divHolder").append(mytable);
        return false;
    }

And boom. So easy even a ca… tool can do it. Now if you want this grid to come preloaded, it’s pretty easy:

    jQuery(document).ready
    (
        function setPage()
        {
            getGrid(0, 10, null);
        }
    )

Entity Framework: Possible Lazy Loading Solution

So been a while since I posted last, and I’m sure everyone has been worried. Turns out that I’ve been banging my head against the wall named MVC. And man I have a slew of new posts back logged for when I have more time. However, due to the new project I’ve been working one, I forced myself to tackle Lazy Loading in the Entity Framework. Turns out the solution isn’t that hard since it has everything needed to make it work.

One of the biggest waaaaahbumlance calls is the fact that Entity Framework doesn’t have lazy loading. This isn’t true. It does, you just have to do a little work, which is to be expected from a FRAMEWORK. Now I have to admit, I wish there were a slightly less odd way of doing this, but eh it’s not too bad.

Say you have a class named Topic and it has a reference to a Forum class named ParentForum. Now this is just a property on the actual class created by the E-Work to represent a many to one foriegn key relationship between the Topic table and the Forum table. Now the problem comes in when you try to use something from that property like:

    Int32 someInt = topic.ParentForum.ForumId;

If you didn’t use the Include method when you got that topic:

    context.Include("ParentForum").Select(topic => topic);

You are screwed because the ParentForum property will return a null. So this forces you to use Include every time you want to get a Topic and access it’s ParentForum property. Sucks.

So next thought is to find out how to lazy load and then plunk it into that generated property. Eh I don’t know about you, but that sounds like a bad idea to mess around with a generated file. You have no idea when the E-Work will just trash the file and rebuild.

Next thought was to create a proxy property to check the real one and then load if it’s not already loaded. Something like:

    public Forum ParentForumLazyLoaded
    {
        get
        {
           //check and return
        }
    }

Ok so that’s not horrible except two things: The name looks dumb and people can still get at the original ParentForum property.

So in comes my solution and it’s pretty simple. Rename the property name on the class to something ParentForumInner and make it private.

bat_lazyload1

Then you can create a much nicer outward facing property like:

    public Forum ParentForum
    {
      get
      {
          if (!ParentForumInnerReference.IsLoaded)
          {
              ParentForumInnerReference.Load();
          }

        return ParentForumInner;
    }
    set
    {
        ParentForumInner = value;
    }
}

Now one of the issues with this is that although outside the class only the ParentForum property can be seen, within the class they both can be seen which can lead to issues like:

    context.Topics.Where(topic => topic.ParentForum.ForumId == id);  //boom

Where you should be using:

    context.Topics.Where(topic => topic.ParentForumInner.ForumId == id);  //yay

E-Work doesn’t know how to handle that situation when evaluating that expression and the kicker is that it does just fine compile time. You won’t know this is bad until runtime.

Other issue is that you have to do a little more work then just some setting on the property which is what most people wish for. I guess that may be true, but again this is a framework. It gives you all the tools you need to makes things work, you just have to do some coding.

The plus side to this is that with minimal coding, you can completely get rid of Include which to me is huge.

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.

Just Use the Stupid Functionality

So something I’ve come across time and time again since starting to use ORMs (about 3 or so years ago) was the infamous “hydrate a reference object just to save another.” If you haven’t had this before, you probably will anyhow, but here’s what it is. Say I have a “Manny” object and I need to assign some kind of “fertility drug type” to it. Now this “fertility drug type” is basically representative of a table that has an id and description and nothing else really. Now the question is, if I know the ID of “HCG” is 1, should I bother even getting it from the database? I mean after all:

  Drug totallyNotUsingVitamins = toolContext.Drugs.Select(drug => drug.Name == "HCG");
  manny.DrugOfChoice = totallyNotUsingVitaminS;

Looks pointless when I can do this:

  playersObject.DrugTypeReference.EntityKey =
     new EntityKey("ToolEntities.BallPlayers", "drugOfChoiceID", 1);

Which was taken from here.

So here’s the problem: Why should I have to hit the database if I know what the ID is? I mean, that’s a trip I don’t have to make right?

If you’re asking that question, then it’s possible you don’t understand how a lot of ORMs work, or in this site’s case: The Entity Framework.

What it really comes down to a couple arguments:

  • What is the cost if it hits the database?
  • Is it actually hitting the database?
  • It’s just easier to set the ID

What is the cost if it hits the database?

Now the first one you could almost make an argument, after all what’s the point of hitting it if you don’t need to? This might seem silly:

  using(ToolEntities toolContext = new ToolEntities())
  {
    Drug totallyNotUsingVitamins = toolContext.Drugs.Select(drug => drug.Name == "HCG");
    manny.DrugOfChoice = totallyNotUsingVitaminS;
  }

If that is the only time you’re using this. A one off like that does seem to beg overdoing it. But really is it? This is probably the strongest argument for the straight ID set and really what is the real cost? In order to persist the object, a connection has to be created and the entity has to be persisted. So in reality, you have to create a connection any how, so the actually getting and hydrating of the reference object is just sort of tagged onto that and unless there is something wrong with the table or connection, this adds a minimal amount of time.

Is it actually hitting the database?

But what if this has to be run a million times? Then what? I have to get that item a million times and now my hits have gone from one million to two million?

  using(ToolEntities toolContext = new ToolEntities())
  {
    for(Int32 loopCounter = 0; loopCounter < someNumber; loopCounter ++)
    {
      Drug totallyNotUsingVitamins = toolContext.Drugs
                                       .Select(drug => drug.Name == "HCG")
                                       .First();
      manny.DrugOfChoice = totallyNotUsingVitaminS;
    }
  }

Ok not the best example, but the point is that within that using you will be updating a million records which you would assume that

  Drug totallyNotUsingVitamins = toolContext.Drugs.Select(drug => drug.Name == "HCG");

Would be run a possible two million times. You could make the argument that Entity Framework does make a select against the database even if the object is in the context. This is something I’ve thought rather odd myself. However, it’s just a query on an already open connection. And since creating the query is done the first time around, the acutal query being run is minimal in effort. Basically the hard work was does the first time around. The next time is nothing to really consider.

It’s just easier to set the ID

Ok so this one is hard to discredit since it is easier. It’s about one line less easier. Is one line really worth this? Is it worth the ease of understanding? From the first example, it’s pretty easy to understand what I’m setting. Select a drug type of “HCG”. Second one, not so much. All I see is an ID, so if I want to know what drug that is, I’d have to go searching for what that ID is. Also, from a spec level, it’s more clear to say:

Set DrugOfChoice to “HCG”

Then

Set DrugOfChoice to 1

Now I may be reaching on this last example, but as I said, it will be hard to prove that the second example isn’t “easier” coding wise. After all it’s one less line. However, when things like readablity comes in, I can’t see the second being a winner in that contest.

Once a person understands how an ORM like the Entity Framework works, it becomes apparent that some of the old ways of thinking need to be abandoned as in the long run they only hold overall development back. And beyond that, sometimes when we think we’re optimizing, we could actually doing more harm than needed. Losing readability for the sake of ridiculously small amounts of time just doesn’t make sense anymore.

Website Spotlight: Iconshock.com

Website: Iconshock ( http://www.iconshock.com/ )
Description: From their website – Iconshock offers the largest icon collection over the internet, with nearly 500,000 unique icons (they don’t include sizes or file types in this estimation, only different and unique icons) with the highest quality and most of them including source files to allow you to make your own changes. All those icons are included in about 200 different collections with different design styles to choose from according to your application GUI.

Icons & Logos
Iconshock.com offers great looking icons and logos for reasonable prices. Both their icons and logos are of very high quality. Source files are also included so that you can modify them as needed. Personally, I am a fan of the Super Vista and Lumina sets. Iconshock offers the ability to purchase single sets or create your own bundle of sets to purchase at a reduced price. You can also subscribe and get all the icons they offer plus any new icons added during your subscription. The website is quick and easy to navigate. If you need a custom logo or icons created specifically for you, Iconshock can do that as well. I have been a web developer for over 10 years, and their portfolio of custom work is AMAZING!

Example Logo
Example Logo

The Community
What sets Iconshock apart from their competition is a community portal which rewards people for their participation. Each week, Iconshock allows users to vote on which free set of icons the community receives. Users can collect free icon sets by swapping with other members. Free sets can also be unlocked by earning points by simply logging in or posting in their forums. You can join the community on their website or by searching Twitter for #Iconshock. Recently, community members were recognized for their participation when they were awarded full icon sets. You can read more about these awards on the Iconshock Blog.

You can browse through some of their icons below:

Icon Set Specifics
Sizes

  • Normal: 256×256, 128×128, 72×72, 64×64, 48×48, 32×32, 24×24, 16×16 pixels (available in png only)
  • Hot: 128×128, 48×48, 32×32, 24×24, 16×16 pixels (available in png only)
  • Disable:128×128, 48×48, 32×32, 24×24, 16×16 pixels (available in png only)
  • ico:256×256, 128×128, 48×48, 32×32, 24×24, 16×16 pixels
  • gif :128×128, 48×48, 32×32, 24×24, 16×16 pixels
  • bmp:128×128, 48×48, 32×32, 24×24, 16×16 pixels

Color States

  • Normal: Normal color
  • Hot: Contrasted Colors, useful in rollovers, active buttons
  • Disabled: Gray Scale colors, useful in inactive buttons

Formats

  • PNG
  • GIF
  • ICO
  • BMP

Paging and the Entity Framework, Skip, and Take Part 4

Get the total count of pages. | Get the real page number. | Using Skip and Take to Page | The Actual Paging Controls

Now onto the fourth part of this epic saga that George Washington once called, “The most astounding exercise in futility”

Ok so let’s say you have a grid, items to fill it with, and four buttons. Each button has a direction, say one back, all the way back, one forward, all the way forward. No big deal. Now you want them to page correctly when used. After all, it’s always a bonus when things go right. First you need to set the CommandArguments on the buttons themselves to whatever page they are responsible for.

private void SetAndBind(Int32 pageNumber)
{
  Int32 realPage;
  Int32 totalCount;

  IList<ToolItem> inviteList =
    ToolClass
    .GetSomeTools("Sean", 20, pageNumber, out realPage, out totalCountOfPages);

  btnFullBack.CommandArgument = Convert.ToString(0);
  btnOneBack.CommandArgument = Convert.ToString(realPage - 1);
  btnOneForward.CommandArgument = Convert.ToString(realPage + 1);
  btnFullForward.CommandArgument = Convert.ToString(totalCountOfPages);

  BindGrid(inviteList);
}

First off, GetSomeTools is just a method that is the same as I presented in the third installment of this epic saga that George Washington once called, “The most astounding exercise in futility”. If you’ve been reading up to this point, then you’ll know that. If not, you might have some reading to do.

So, here’s a simple method used to get the info we need (using the page number) and set the buttons. As seen before, realPage is the actual possible page (In case someone passed in page 21 when there are only 20 pages) and totalCountOfPages gives us how many possible pages there are. This makes setting the button CommandArguments cake. Now for the button event:

  private void btnPaging_Click(Object sender, EventArgs e)
  {
    SetAndBind(Convert.ToInt32(((Button)sender).CommandArgument));
  }

And then you just set all the click events to that:

  btnFullBack.Click += btnPaging_Click;
  btnOneBack.Click += btnPaging_Click;
  btnOneForward.Click += btnPaging_Click;
  btnFullForward.Click += btnPaging_Click;

And boom, you’re pretty much set.