F#: Creating your own mocks using Object Expressions… Wow

This just in from the “Wow, I can’t believe how easy this is” update desk:

You can roll your own mocks “dynamically”, even when mocking an interface. No, this isn’t too good to be true. No that weird tingling isn’t from your bullsh@# meter going off. (But you really should get that tingling checked by a doctor) This is F#. And this isn’t SPARTA!!! AHRHARHARHRAhRHARHR SO FUNAY!11

Say you have a test method that wants to call a method Validate on the Validator : IValidator class. Here is the IValidator class:

  type IValidator<'a, 'b> =
    abstract AddValidationMethod : ('a -> MethodResult<'b>) -> IValidator<'a, 'b>

(Side note: the ‘a and ‘b are just F#’s generic notation. Generic members are preceeded by a ‘)

Somewhere in your code this IValidator is called by someone, say a controller action:

  member public x.LoginPost(userName:String, password:String) =
    let loginModel = new LoginModel(userName, password)
    let result = x.ControllerValidator.Validate(loginModel)

And of course you would have a controller definition look like this:

  type MainController(validator:IValidator<LoginModel, LoginModel>) =
    inherit Controller()
      member private x.ControllerValidator with get() = validator

So you are set up for mocking.

There are three way, but if you’re already bored (And I assume you are) then just go to 3.

1) Mock the IValidator

As you can imagine, this could be obnoxious to mock up as the AddValidationMethod is adding a method that takes in ‘a and a MethodResult<‘a> and then returns an IValidator<‘a, ‘b>. Can it be done? I would asssume so, but there is another way.

2) Create a new class (Class file) that implements IValidator.

This is the most simple way of doing it. You just make a class that implements IValidator and just pass back what you want. Problem is: This isn’t very reusable as it is now a static class.

3) Create a class on the fly.

And this is the good stuff. F# allows the creation of a class (That implements an interface) “inline”… not sure what word I’m looking for so just go with it.

  let validatorWithFalseReturn = 
    { 
      new IValidator<'a, 'b> with
        member x.AddValidationMethod(methodToAdd:('a -> MethodResult<'b>)) =
          new Validator<'a, 'b>() :> IValidator<'a, 'b>

        member x.Validate(model:'a) =
          (new MethodResult<'b>()).AddErrorMessage("")
    }

    let mainController = new MainController(validatorWithFalseReturn)

(Side note: you might see the :> notation. This is basically the same as (SomeInterface)SomeClass in C#.)

As you can see, I created a new type and set it into the instantiated controller. As you can imagine, you could create a method that takes in a method to set AddValidation to. This has some really great potential like rolling your own mocking system.

So once again F# is looking to be an amazing language.

F#: Duck typing with generic constraints and why you will be speechless

So I’ve been working on a validation design that basically allows validation methods to be added to a list and then run. A small part of it:

    member x.Validate(valueToCheck:'a) =
      methodList 
      |> Seq.map (fun (methodToRun) -> methodToRun(valueToCheck)) 
      |> Seq.reduce (fun(outer) inner -> outer.MergeResults(inner))

What this is saying is take a list of methods, run them and make a list of their results, then merge the results into one. While I won’t get into what the results are (And I almost typed that as resluts which makes me think there is a refurbishing factory for sluts.) just know that each result can merge with another and combine values.

The biggest problem I was running into was a way to allow any method to be added and let the method decide what it needs to run correctly. In C# this can be done easily with dynamic:

  public static MethodResult ValidatePasswordExistence(dynamic modelToCheck)
  {
    var returnResult = new MethodResult(); 
    if (string.IsNullOrEmpty(modelToCheck.Password))
    {
      returnResult = returnResult.AddErrorMessage(UserError.PasswordIsNullOrEmpty);
    }

    return returnResult;
  }

The use of a dynamic parameter means that all validation methods can have the same signature which makes it really easy to send the same class into any method in the list. The problem with F# is there is no ready way to use dynamic and I’m not sure it should be. F# is heavily based on typing and dynamic kind of goes in the opposite direction. So I thought my ship was sunk, that is if I had a ship to sink and said ship hand’t sunk already.

Thanks to some help from the O, i was able to get past this not only without dynamic, but a way to strongly type any object coming into the method:

  let inline UserNameExists (userModel) =
    let userName = (^a : (member UserName : String with get) (userModel))

    let result =
      match userName with 
        | null -> (new MethodResult()).AddErrorMessage(UserErrors.UserNameIsNullOrEmpty)
        | "" -> (new MethodResult()).AddErrorMessage(UserErrors.UserNameIsNullOrEmpty)
        | _ -> new MethodResult()

    result

The important part is the second line. This line basically says that anything coming into the method as userModel has to have a property of UserName. One of the dangerous issues with dynamic is there are no compile time checks to make sure that any object going in will have the property or method you need it to. This isn’t true of F#. You not only get to pass in any object you want (That has what is required by the check) but you get complile time errros if you try to pass in an object that doesn’t fit the requirements.

Yup, that’s right. You’re speechless.

jQuery Validator: Build Rules and Messages Dynamically

Ok so here’s your typical code for the jQuery Validator:

  jQuery(ELEMENT_FORM).validate({
    errorLabelContainer: ELEMENT_ERROR_DIV,
    wrapper: 'div',
    rules: {
      textboxEmailAddress: {
        required: true,
        email: true
      }
    },
    messages: {
      textboxEmailAddress: {
        required: ERROR_EMAIL_ADDRESS_REQUIRED
      }
    },
    ....

As you can see, the elements like “textboxEmailAddress” are hard coded in there which means if that name changes in the markup, this breaks. So the question is: How do I script the rules and messages so that I don’t have to hard code the element names?

Sorry was just waiting for you to finish you question. Ok, here’s the answer and it has to do with how great Javascript is as a language. (And oddly enough a trick I got from Python)

  var validationRules = new Object();
  validationRules[ELEMENT_TEXTBOX_EMAIL] = {required:true};

  var validationMessages = new Object();
  validationMessages[ELEMENT_TEXTBOX_EMAIL] = {required:ERROR_EMAIL_REQUIRED};

  jQuery(ELEMENT_FORM).validate({
            errorLabelContainer: ELEMENT_ERROR_DIV,
            wrapper: 'div',
            rules: validationRules,
            messages: validationMessages,
            ....

Where ELEMENT_TEXTBOX_EMAIL is a constant somewhere. How does this work? Well because the way dynamic languages like Javascript and Python work, objects can be treated like dictionaries which means you can add properties to them the way you would add a record to a dictionary:

  someObject['somePropertyName'] = 'hi';

is just like:

  someObject.somePropertyName = 'hi';

In fact I’m pretty sure the new Dynamic keyword in C# works in the same manor.

Now you could be a annoying and point out that replacing textboxEmailAddress with ELEMENT_TEXTBOX_EMAIL is still hard coding, and I would agree… to a point. The constant does two things:

1) Removes a “magic string” from your code.

2) Makes it really easy to update that string if the element name/id is changed in the HTML. Having only to look at one place to replace is a lot easier than 1+ places.

So there, smarty pants. What you gots to say now?

Simple Property Merge for Python Objects

Not sure if this is useful to other people, but then again if I cared that would make me human.

So here’s a quick way to merge two objects in python:

def mergeObjectProperties(objectToMergeFrom, objectToMergeTo):
    """
    Used to copy properties from one object to another if there isn't a naming conflict;
    """
    for property in objectToMergeFrom.__dict__:
        #Check to make sure it can't be called... ie a method.
        #Also make sure the objectobjectToMergeTo doesn't have a property of the same name.
        if not callable(objectToMergeFrom.__dict__[property]) and not hasattr(objectToMergeTo, property):
            setattr(objectToMergeTo, property, getattr(objectToMergeFrom, property))

    return objectToMergeTo

This is a good example of how the whole dynamic addition of properties happens in Python. The objects in this example have a __dict__ property that is basically where the property/method/other stuff information is held in dictionary form. What does this mean? It means that if you use the setattr method you can then later call the property like you would normally.

  setattr(someObject, 'someProperty', 'some value')

  someObject.someProperty == 'some value

Knowing this is important as it allows you to really do some fun dynamic stuff that a lot of other languages just don’t allow.

ASP.Net MVC: Upload Image to Database and Show Image “Dynamically” Using a View

Oddly enough this came about from me wanting to do this, figuring it out, and then deciding not to bother with it. So there’s a possibility this will happen to you too. Well that’s not completely true. The first half where I was uploading and showing from a database, but showing an image through a view to mimic the .ashx functionality of WebForms is still pretty useful.

Saving the Image

First off, here’s the look of the table:

Table

So pretty simple table. Most important parts are the ImageData and ContentType. Why? Well let’s look at the action needed to save the image:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Upload(PhotoForSingleItem photo)
{
  //PhotoForSingleItem is just a class that has properties
  // Name and Alternate text.  I use strongly typed Views and Actions
  //  because I'm not a fan of using string to get the posted data from the
  //  FormCollection.  That just seems ugly and unreliable to me.

  //PhotoViewImage is just a Entityframework class that has
  // String Name, String AlternateText, Byte[] ActualImage,
  //  and String ContentType
  PhotoViewImage newImage = new PhotoViewImage();
  HttpPostedFileBase file = Request.Files["OriginalLocation"];
  newImage.Name = photo.Name;
  newImage.Alt = photo.AlternateText;

  //Here's where the ContentType column comes in handy.  By saving
  //  this to the database, it makes it infinitely easier to get it back
  //  later when trying to show the image.
  newImage.ContentType = file.ContentType;

  Int32 length = file.ContentLength;
  //This may seem odd, but the fun part is that if
  //  I didn't have a temp image to read into, I would
  //  get memory issues for some reason.  Something to do
  //  with reading straight into the object's ActualImage property.
  byte[] tempImage = new byte[length];
  file.InputStream.Read(tempImage, 0, length);
  newImage.ActualImage = tempImage ;

  newImage.Save();

  //This part is completely optional.  You could redirect on success
  // or handle errors ect.  Just wanted to keep this simple for the example.
  return View();
}

And here’s the mark up to get this ball a rollin’:

<form method="post" enctype="multipart/form-data" action="Photo/Upload">
  <div>
    <span>
     Name:
   </span>
   <span>
     <input type="text" id="Name" name="Name" />
   </span>
  </div>
  <div>
    <span>
      Alternate Text:
    </span>
    <span>
     <input type="text" id="AlternateText" name="AlternateText" />
    </span>
  </div>
  <div>
    <span>
      Image
    </span>
    <span>
      <input type="file" id="OriginalLocation" name="OriginalLocation" />
    </span>
  </div>
  <div>
    <input type="submit" value="Upload" />
  </div>
</form>

Biggest thing to notice in the markup is the enctype=”multipart/form-data”. This is a must to upload images. It was something I was missing originally and annoyed the hell out of me.

Showing the Image

So now that we have a we to upload the image, how the hell do you use it? Well that’s not too hard. It just involves a new type of result, an action, and an img element.

So the first thing you need is an image result, and in using my superior intellect I came up with such a thing. And by superior intellect I mean I used StackOverflow. Oddly enough though, it’s actually the second post that I got it from and I changed it a little. However, it was very useful.

using System.Web;
using System.Web.Mvc;
using System.IO;

public class ImageResult : ActionResult
{
  public String ContentType { get; set; }
  public byte[] ImageBytes { get; set; }
  public String SourceFilename { get; set; }

  //This is used for times where you have a physical location
  public ImageResult(String sourceFilename, String contentType)
  {
    SourceFilename = sourceFilename;
    ContentType = contentType;
  }

  //This is used for when you have the actual image in byte form
  //  which is more important for this post.
  public ImageResult(byte[] sourceStream, String contentType)
  {
    ImageBytes = sourceStream;
    ContentType = contentType;
  }

  public override void ExecuteResult(ControllerContext context)
  {
    var response = context.HttpContext.Response;
    response.Clear();
    response.Cache.SetCacheability(HttpCacheability.NoCache);
    response.ContentType = ContentType;

    //Check to see if this is done from bytes or physical location
    //  If you're really paranoid you could set a true/false flag in
    //  the constructor.
    if (ImageBytes != null)
    {
      var stream = new MemoryStream(ImageBytes);
      stream.WriteTo(response.OutputStream);
      stream.Dispose();
    }
    else
    {
      response.TransmitFile(SourceFilename);
    }
  }
}

And here’s how you use the actual result.

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult ShowPhoto(Int32 id)
{
  //This is my method for getting the image information
  // including the image byte array from the image column in
  // a database.
  PhotoViewImage image = PhotoViewImage.GetById(id);
  //As you can see the use is stupid simple.  Just get the image bytes and the
  //  saved content type.  See this is where the contentType comes in real handy.
  ImageResult result = new ImageResult(image.ActualImage, image.ContentType);

  return result;
}

And the markup would go a little sumthin’ like dis:

  <img src="/Photo/ShowPhoto/1" alt="" />

And now you too can upload an image to a database, show it, and then decide just to physically host the images anyway. Next post will be about how to use this with jQuery and asynchronously. I bet you can’t wait!

jQuery Slide Menu… Another Cause I Can Experiment

So for no real reason at all I had it in my mind that I wanted to make a horizontal menu with jQuery that would work like that weird scrolling menu thing that Macs have. No idea what it’s called. So basically I don’t need it, have no reason for it, but damnit I’m going to make it happen and I did it with only 3 things from jquery.com; 1.3.2, ui 1.7.2, and jquery.timer . Now this is still rough in the sense it has no real styling but it works tried and true functionality wise.

The main idea is that there are two scroll arrows, one on each side, and X amount of divs. Now at the start, a certain amount of divs are hidden (global variable). When hovering over the left pager, for example, it causes one on the right to hide while one on the left appears giving the feeling of the items sliding.

EXAMPLE HERE!!11

The markup is simple, a holder with x number of elements that are “menuitems” and two pager divs.

<div class="mainHolder">
  <div class="leftPager green floatLeft"><</div>
  <div class="menuItem floatLeft blue">1</div>
  <div class="menuItem floatLeft red">2</div>
  <div class="menuItem floatLeft yellow">3</div>
  <div class="menuItem floatLeft blue">4</div>
  <div class="menuItem floatLeft red">5</div>
  <div class="menuItem floatLeft yellow">6</div>
  <div class="menuItem floatLeft blue">7</div>
  <div class="rightPager green floatLeft">></div>
</div>

I think from the classes you can tell what you need to know about them.

First thing we need from jQuery is methods to find various elements in the container when paging.

//When using the left pager, it's important to find the first visible element
//then find the item before it so that it can be shown.
function getNextInLineBack(menuItems)
{
  var oneBefore = null;

  for (var loopCounter = 0; loopCounter < menuItems.length; loopCounter++)
  {
    if(jQuery(menuItems[loopCounter]).is(":visible") && loopCounter > 0)
    {
      oneBefore = jQuery(menuItems[loopCounter - 1 ]);
      break;
    }
  }

  return oneBefore;
}

//Find the first visible element from the beginning.
//This will be needed when paging right since it will have to be hidden
function getFirstVisible(menuItems)
{
  var firstVisible = null;

  for (var loopCounter = 0; loopCounter < menuItems.length; loopCounter++)
  {
    if(jQuery(menuItems[loopCounter]).is(":visible") && loopCounter < menuItems.length - maximumToShow)
    {
        firstVisible = menuItems[loopCounter];
        break;
    }
  }
  return firstVisible;
} 

//Get the last possible visible item
//If the item is in an index less than the maximum number to show, then null is returned since there has to be no more or less than the maximumToShow.
function getLastVisible(menuItems)
{
  var lastVisible = null;
  for (var loopCounter = menuItems.length - 1; loopCounter > maximumToShow - 1; loopCounter--)
  {
    if(jQuery(menuItems[loopCounter]).is(":visible"))
    {
      lastVisible = menuItems[loopCounter];
      break;
    }
  }

  return lastVisible;
}

//Find the first visible from the end
//Pretty simple, this will be important when paging left since this
//will be the next item to be hidden
function getNextInLineFront(menuItems)
{
  var lastOne = null;

  for (var loopCounter = menuItems.length-1; loopCounter > -1; loopCounter--)
  {
    if(jQuery(menuItems[loopCounter]).is(":visible"))
    {
      lastOne = menuItems[loopCounter + 1];
      break;
    }
  }

  return lastOne;
}

Next is a method that is just used to stop having to repeat the same thing over and over when needing a list of all the menu items.

function getMenuItems(mainHolder)
{
  return jQuery(mainHolder).children(".menuItem");
}

Next is the method to handle what item to show and what item to hide when the pager has the mouse over it. Instead of having methods for the right and left pager, I just ended up having the methods for finding the item to hide and show sent through as parameters.

function showHideOnHover(pager, timer, getHideMethod, getShowMethod)
{
  //This is just candy for changing the color of the pager when the mouse
  //is over it
  jQuery(pager).removeClass("green");
  jQuery(pager).addClass("orange");

  //Remember those methods I passed through, well here they
  //are in use.  I'm using them to get the item to hide and the item
  //to show along with the list of items.
  var menuItems = getMenuItems(jQuery(pager).parent());
  var hide = getHideMethod(menuItems);
  var show = getShowMethod(menuItems);

  //If neither is null, then go ahead and show/hide
  //If either one is null, something isn't right and the timer
  //needs to be stopped.... timer??  Well I'll get to that
  //next.
  if(show != null && hide != null)
  {
    jQuery(hide).hide( "slide", { direction: "right" } , 0);
    jQuery(show).show( "slide", { direction: "left" } , 100);
  }
  else
  {
    timer.stop();
  }
}

Now for the method above the last one, this one involves the timer passed in the last method. This method actually sets the mouseover/mouseout events (aka hover). When mouseover, the timer is created and the showHideOnHover method is called every 500 units, that’s we’ll call tools, (Not sure how much that is, seems like a half second) after the first time it’s called. On mouseout, the timer is stopped, nulled out, and the pager changes it’s color.

function setPager(pager, hideMethod, showMethod)
{
  //Making the timer variable "global" to the events so that I know
  //I have the same timer for both mouseover and mouseout.
  var newTimer;
  pager.hover
  (
    //Mouseover method
    function()
    {
      var first = true;
      //This sets the timer, consequently starting the method for the first time.
      //Why timer doesn't have a start method I don't know.  Ask jquery.com.
      //The first thing is just so that the first time around it runs right away,
      //then each call afterwards comes every 500 tools.
      newTimer = jQuery.timer
                      (
                         0, //First time through, runs after 0 tools.
                         function(timer)
                         {
                           showHideOnHover(pager, timer, hideMethod, showMethod);
                           //If this is the first time through, reset
                           //timer to run every 500 tools.
                           if(first)
                           {
                              timer.reset(500);
                              first = false;
                           }
                         }
                       );
    },

    //Mouseout method
    function()
    {
      //mouse is done, stop the timer
      newTimer.stop();
      newTimer = null;
      jQuery(pager).addClass("green");
      jQuery(pager).removeClass("orange")
    }
  );
}

Now for the method above the one… above. This is used to set the children of the passed in holder.

function setChildrenDivs(mainHolder)
{
  //Get the items for the holder
  var menuItems = getMenuItems(mainHolder);

  //Hide all the items after the first X items (maximumToShow)
  for (var loopCounter = 0; loopCounter < menuItems.length; loopCounter++)
  {
    if(loopCounter > maximumToShow - 1)
    {
      jQuery(menuItems[loopCounter]).hide();
    }
  }

  //set the pagers.
  setPager(jQuery(mainHolder).children(".leftPager"), getLastVisible, getNextInLineBack);
  setPager(jQuery(mainHolder).children(".rightPager"),getFirstVisible, getNextInLineFront);
}

FINALLY THE END! This is the document.ready method used to set this whole joke in motion. maximumToShow is just how many items to show at a time and is global.

var maximumToShow = 5;

jQuery(document).ready
(
  function()
  {
    //Find every holder on the page and set everything in motion.
    var mainHolders = jQuery(".mainHolder");
    for (var loopCounter = 0; loopCounter < mainHolders.length; loopCounter++)
    {
      setChildrenDivs(mainHolders[loopCounter]);
    }
  }
);

Why the timer? If you haven’t figured that out yet, well it’s because I had issues with how to get the menu to keep doing it’s thing as long as the user had his/her mouse over a pager. I didn’t want this to be a click menu because, let’s be honest, that would be much easier. So as is, the timer is started the moment the mouse is over a pager and hides/shows an item. Then every 500 tools the mouse is over the pager, it continues the hide/show until it runs out of items to show/hide. (End of the list)

Uhg that’s annoying to type out even with cut and paste so I will host it here.

I suppose the next part of this would have the items blow up or something when hovering over them but that should be much easier than this was.

ASP.NET MVC: Attributes and Semi Dynamic Check for Request Parameters

If I were self involved I would say something silly like IN THIS AWESOME POST but I’m not. However in this post that is awesome I gave some examples of how to use attributes to set defaults or just check to see if an incoming id could be matched to a record somewhere… Sorry lost my track of thought. Watching the begining of Transformers… You know the part where it could have been good.

Anyway, I figured I’d add another debatable use for an attribute, the CheckForGivenRequest one. Basically in the other post I had something that was specific it was checking for, this is used if you are checking for a request parameter but you don’t want to make an attribute for each and every one of them.

  //This is so you can use it many times on the same method
  //I know, I know... duh
  [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
  public sealed class CheckForGivenRequestAttribute : ActionFilterAttribute
  {
    //The constructor to set what should be looked for
    //Default amount is what it should be set if not there
    public CheckForGivenRequestAttribute(String requestParameterName, Object defaultAmount)
    {
      DefaultAmount = defaultAmount;
      RequestParameterName = requestParameterName;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
      base.OnActionExecuting(filterContext);
      //Check the extra request parameters (ie &someId=1) for if it exists
      //If it doesn't exist, then add it
      if (!filterContext.ActionParameters.ContainsKey(RequestParameterName))
      {
        filterContext.ActionParameters.Add(RequestParameterName, null);
      }

      //If it's null set to the default
      filterContext.ActionParameters[RequestParameterName] =
         filterContext.ActionParameters[RequestParameterName] ?? DefaultAmount;
    }

    //Just the properties, nothing to see here.  Go away...
    private Object DefaultAmount { get; set; }
    private String RequestParameterName { get; set; }
  }

And then the use of it:

  [CheckForGivenRequestAttribute("someStupidId", 1)]
  public ActionResult INeedAnExample(Int32 someStupidId)
  {
    ...
  }

Now you might ask why not make that attiribute generic to avoid boxing.

Why not make that attribute generic to avoid boxing?

Glad you asked. Turns out that you can’t make attributes generic. Aparrently it’s somwhat debatable why but not possible at the time being. Besides, the ActionParameters collection is <String, Object> anyhow, so at some point any stuct would be boxed anyhow.

On a side note, I never noticed this before, but when one of the non descript Autobots crashes near a pool, some kid is there to ask if he is the Tooth Fairy? Seriously? Are kids really that dumb? Cause every picture I’ve seen of the Tooth Fairy has been a 20 foot tall metal thing with no discernible features.

jQuery Slide and Pairing a Div’s Hover With a Div’s Slide

So this could be filed under “I did it because I can” (which is a really good mantra in science…) and am not sure I’ll use it but it is useful in the concept.

LIVE EXAMPLE HERE

The idea is to set the hover on one div to show/hide another div WITHOUT having to use some kind of id/name trick (as in setting the id to “divHide1”) and to have it be completely self setting in the .ready method. Why would this be at all useful? Say you want to roll through a list of things and generate the divs, but want to defer the jQuery until the page has loaded. And you don’t want to have to resort to:

    <div id="someDiv<%= someId %>"></div>

like structure where you parse some identifier from the id property. Mostly because you have no idea how many someDiv1s there could be on the page. It could be a highly reused name (someDiv) and that could lead to a mess.

Also the reason ‘cuz. If you have any more questions of why after that answer, well you’re just being annoying.

Anywho, here’s the actual html for structure.

   <div class="mainDiv">
      <div class="showDiv" id="oneTop">
        Kaneda?
      </div>
      <div class="slideDiv" id="one">
        What do you see?!
      </div>
    </div>
    <div class="clear"></div>

Now I get that this isn’t off a foreach, but it doesn’t take much to figure out that it’s easily made into a loop if you just loop it over and over. Why? Because first there are no ids or names so that you can’t have two of the same name and also because that chunk is self contained.

So what is going on there? Simple, you have a parent container that holds a div to hold and a div to hover over and the other that will be shown/hidden.

Here’s the styles involved just incase you care:

    <style type="text/css">
        .clear
        {
        	clear:both;
        }

        .leftDiv
        {
        	float:left;
        }

        .mainDiv
        {
        	margin:5px;
        	height:200px;
        }

        .rightDiv
        {
        	float:left;
        }

        .showDiv
        {
        	float:left;
        	margin-right:5px;
        	height:200px;
        	background-color:Silver;
        }

        .slideDiv
        {
        	background-color:Teal;
        	height:200px;
        	position:absolute;
        	float:left;
        	z-index:100;
        }
    </style>

That doesn’t entirely matter, but it does to show the div “sliding” over another div. Kind of a little somethin’ somethin’ I threw in at no extra cost. Now for the jQuery:

First the method for setting the mouse over and out events for the show div, we turn to .hover:

    function setHover(currentSlideDiv, currentStableDiv)
    {
      currentStableDiv.hover
      (
        //first parameter is the method for showing the div on mouse over
        function()
        {
          if (currentSlideDiv.is(":hidden"))
          {
            currentSlideDiv.show("slide", { direction: "left" }, 100);
          }
        },
        //second parameter is the method for hiding the div on mouse out
        function()
        {
          if (currentSlideDiv.is(":visible"))
          {
            currentSlideDiv.hide("slide", { direction: "left" }, 100);
          }
        }
      );
    };

Now for the method that actually uses these:

    //This is used to take in one of the main divs and set all the
    //show and slide divs within.
    function setChildrenDivs(mainDiv)
    {
      //get all the show and slide dvis within the main div
      var mainChildrenStableDiv = jQuery(mainDiv).children(".showDiv");
      var mainChildrenSlide = jQuery(mainDiv).children(".slideDiv");

      //loop through the list of show divs
      for (var loopCounter = 0; loopCounter < mainChildrenStableDiv.length; loopCounter++)
      {
        //Get the show div and it's corresponding slide div using the
        //two lists and the current counter.
        var currentStableDiv = jQuery(mainChildrenStableDiv[loopCounter]);
        var currentSlideDiv = jQuery(mainChildrenSlide[loopCounter]);

         //This is to make sure the slide is where it should be.
         //to the right of the show div.
         var containerPosition = jQuery(currentStableDiv).position();
         jQuery(currentSlideDiv).css({ left: containerPosition.left + currentStableDiv.width() });
        //Set the mouse over and the mouse out on the show div
        setHover(currentSlideDiv, currentStableDiv);
      }
    }

Now the final touch, the .ready method:

    jQuery(document).ready
    (
      function()
      {
        //hide all the slide divs
        jQuery(".slideDiv").hide();

        //find all the parent divs
        var mainDivs = jQuery(".mainDiv");

        //set the children
        for (var loopCounter = 0; loopCounter < mainDivs.length; loopCounter++)
        {
          setChildrenDivs(mainDivs[loopCounter]);
        }
      }
    );

And boom, now you have multiple show/hide (Slide in this instance). Now if I could just find a use for it…

Oh yeah and you’ll need jQuery 1.3.2 and jQuery ui 1.7.2 to use this. At least those are the versions I know this works with.

Update: Due to popular demand… one person… Source can be found here.

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, 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);
        }
    )