We’re Moving!

June 13, 2010

I’ve decided to move this blog to my own domain to give me a little more control of the content that I can deliver. I’ll continue to check back here periodically, but all new blog entries will happen at the new address.

http://www.imtraum.com


IEnumerable<T> Paging with LINQ

January 26, 2010

I am a big fan of LINQ to Objects, especially when it comes to working with collections. 

There are a lot of samples that illustrate how to use Skip() and Take() to locate a page of data in a collection, however most examples leverage inline code.  While I appreciate the simplicity of demonstrating code in this manner, I think it promotes bad programming practices.  Rather than find a concept and integrate it intelligently into their application, most developers will plagerize the sample and move on their merry way without a thought of how the code “should” be integrated.

A method that I use (but by no means the only one) to integrate LINQ pagination into your application is to use an extension method.  This is an elegant approach because it encapsulates the pagination logic in a method that extends the functionality of IEnumerable<T>, and exposes paging functionality to all IEnumerable<T> collections in your application. 

The extension method: 

public static IEnumerable<T> GetPage<T>(this IEnumerable<T> source, int page, int recordsPerPage, out double totalPages)
{
    if (recordsPerPage <= 0)
    {
        throw new ArgumentOutOfRangeException("recordsPerPage", recordsPerPage, string.Format("recordsPerPage must have a value greater than zero.  The value you provided was {0}", recordsPerPage));
    }
    // get the first record ordinal position
    int skip = (page - 1) * recordsPerPage;

    // get the records per page
    var totalRecords = source.Count();

    // get the total number of pages
    var tp = totalRecords / (double)recordsPerPage;
    totalPages = Math.Ceiling(tp);

    return source.Skip<T>(skip).Take<T>(recordsPerPage);
}

Now, if you have a collection, perhaps something like… 

List<string> names = new List<string>();
names.Add("josh");
names.Add("penelope");
names.Add("linda");
names.Add("lauren");
names.Add("amy");
names.Add("cullen");
names.Add("kevin");
names.Add("john");

You can easily query the collection for a page of data like so…

double totalPages;
var pageOfNames = names.GetPage(1, 3, out totalPages);

The extension method extended the functionality of the List<T> (names) with a method that will get a specific page of data from the collection.  While the LINQ query itself is simple, this is far more reusable than having paging code all over your app.

Enjoy!


jQuery fadeIn / fadeOut vs. IE ClearType Rendering

January 21, 2010

jQuery makes fading html elements trivial, and ever day I see JavaScript fade in/out effects used all over the web.  I’ve used this UI trick on a few of the sites I’ve been working with lately and like everyone, I’ve experienced the frustrating jagged text issue in IE.  You know what I’m talking about if you use Facebook and have posted a comment on someone’s wall post.  After you make the comment it will show up inline in typical AJAX fashion and its font will look like it was rendered on a Commodore 64.  There are a few posts like this one that address the issue with jQuery and CSS modifications, however I’ve not had much luck using this method and it’s not very flexible.  Fortunately there is an alternative commonly used by flash developers that I’ve found to be easier to implement, more reliable and most importantly works seamlessly across all modern browsers.

Let’s start with some content that we want to fade in and out.  In this case we’ll make a simple widget that displays a series of rotating banners to your site visitors.

First, we’ll create two container div elements to hold our banners.

<div id="outerContainer" style="background:#F00;height:175px;width:215px;">
    <div id="bannerContainer" style="position:relative;"></div>
</div>

You’ll notice that I’ve set the bannerContainer position to “relative” and provided a fixed size (height and width) to the outerContainer div.  Both will be very important later on.

Next, lets add the content that we want to fade in and out.  In this case, div’s that will hold our banners.

<div id="outerContainer" style="background: #F00;height:175px;width:215px;">
    <div id="bannerContainer" style="position:relative;">
        <div id="banner1" style="display:none;">
            <p>Hey, click here and buy our stuff!</p>
        </div>
        <div id="banner2" style="display:none;">
            <p>Clicky Clicky!</p>
        </div>
        <div id="banner3" style="display:none;">
            <p>Clicking here is good for you!</p>
        </div>
    </div>
</div>

Here I’ve set the banner div style display property to “none” to give a starting point where all the banners are hidden; we’ll dynamically pick the first banner to display with a bit of jQuery code.

Finally, we’re going to add the thing that will make all of this work.  I call it, “the hat”.

<div id="outerContainer" style="background: #F00;height:175px;width:215px;">
    <div id="bannerContainer" style="position:relative;">
        <div id="banner1" style="display:none;">
            <p>Hey, click here and buy our stuff!</p>
        </div>
        <div id="banner2" style="display:none;">
            <p>Clicky Clicky!</p>
        </div>
        <div id="banner3" style="display:none;">
            <p>Clicking here is good for you!</p>
        </div>
        <div id="bannerHat" style="position:absolute;background:#00F;top:0;left:0;height:175px;width:215px;display:none;"></div>
    </div>
</div>

bannerHat is a child of bannerContainer who’s style is set to position: absolute, top: 0 and left: 0, and display: none.  Additionally the bannerHat has the same display style (size, background, etc) as outerContainer.  This setup allows the bannerHat to be used to fade the banners without encountering the IE text fading issues.

The JavaScript that makes this work is very straight forward, but is a bit “backward” compared to the process of fading an item without the hat method.  The process looks like this (pseudo code):

  1. (First time only)  jQuery.Show() one of the banners, it doesn’t matter which one.
  2. After a period of time jQuery.fadeIn() the bannerHat div.  This will hide the banner with a nice fading out effect.
  3. jQuery.Hide() the currently “visible” but hidden div.
  4. jQuery.Show() one of the other banners.
  5. jQuery.fadeOut() the bannerHat div.  This will show the banner with a nice fading in effect.
  6. Wash, rinse, repeat.

So, let’s look at the JavaScript that will give us a random, rotating banner widget.

$(document).ready(function(){
 var options = {
  startIndex: 0,
  fadeInDuration: 1000,
  fadeOutDuration: 1000,
  rotationInterval: 10000,
  startDelay: 0
 };

 var rotator = function(containerSelector, hatSelector, options){
  var children = $(containerSelector).children();
  var startIndex = options.startIndex;
  var totalItems = children.length - 1; // this is so that we exclude the hat (the -1 part)
  
  $(children[startIndex]).show();
   setTimeout(function(){
    setInterval(function(){
     $(hatSelector).fadeIn(options.fadeOutDuration, function(){
      $(children[startIndex]).hide(function(){
       // determine the actual start index by adding one, then taking the modulus
       // this will give us the correct start index regardless of the number
       // of items we have to work with.
       startIndex = (startIndex + 1) % totalItems;
       $(children[startIndex]).show(function(){
        $(hatSelector).fadeOut(options.fadeInDuration);
       });
      });
     });
    }, options.rotationInterval);
   }, options.startDelay);
  };
  
  // randomly pick a start index and then initiate the rotation
  options.startIndex = Math.floor(Math.random()*3);
  rotator('#bannerContainer', '#bannerHat', options);}
 );
});

The JavaScript is pretty self-explanatory and shows how to use the hat to fade the banners in and out without directly fading the banners themselves.  This circumvents the issue with cleartype fonts when fading text in IE, works great in all the major browsers, and should be easy to adapt to any situation where you need to fade textual elements with JavaScript.

So now there shouldn’t be any excuses for terrible fading in IE (yeah, I’m lookin at you Facebook…).


Alienware M15x Laptop

January 18, 2010

I ordered a new laptop from Alienware last Monday and found over the weekend that I’ll be getting it over a week early!  I’m really excited for it to arrive since it will replace my extremely aged Dell Inspiron 8600 and decouple me from my home built gaming workstation, and it will be nice to have a single machine for gaming and programming.

My Alienware M15x Configuration

  • Intel Core i7 720QM 1.6GHz (2.8 GHz Turbo Mode, 8MB Cache)
  • 4GB Dual Channel DDR3 at 1333MHz 2 x 2048MB
  • 15.6-inch Wide FHD 1920×1080 (1080p) WLED
  • 1GB NVIDIA GeForce GTX 260M
  • 500GB SATAII 7,200RPM
  • Genuine Windows 7 Ultimate, 64bit, English
  • Primary – 6-cell (56Watt) Lithium-Ion Battery
  • I’m not a believer in cutting edge hardware, so I usually spec my machines with the highest end componentry at the point where the price starts to dramatically increase, but isn’t out of hand.  I find that you get the best bang for your buck when buying your hardware with this in mind.  I could have spec’d the machine with the highest end stuff available, and it would have cost around $3600 without any extended warranty or accidental coverage.  Instead my laptop came in at $2100.00 for the hardware configuration, $2600.00 ish when you factor in the 3 year extended warranty with accidental damage coverage.  Since I am somehow prone to having other people wreck my stuff, I figure I can’t go wrong with the accidental coverage…

    The processor is a good example of getting good bang for the buck.  This was only a $100.00 upgrade from the stock processor, while the next one up cost $400.00 and only gave you a nominal core speed increase.  Considering the applications that I run are not CPU bound, this was a choice that saved quite a bit of money and still gave me a fast quad core processor that can be upgraded at a later date if I find the machine lacking in horsepower.

    I decided on 4GB of memory rather than my initial instinct to max the box out at 8GB.  While more RAM would be great, I generally don’t find myself running out of memory.  When I do, the machine will take 8GB and upgrading should be fairly inexpensive in a year or two.  Going with 4GB saved me $300.00 over the 8GB upgrade.

    Finally, I elected to stay with the stock 6 cell battery rather than upgrade to the 9 cell version.  After reading reviews I found that the 9 cell only gave about 90 minutes of battery life; a moderate 30 minute increase over the stock 6 cell battery.  For a $100.00 upgrade, this just didn’t seem like that great of a deal considering this laptop will rarely find itself in a starbucks or any other scenario where I don’t have access to power.  I’ll plug the box in when in my living room; it will be faster that way anyway.

    I’ll do a more detailed write up after I get this thing set up and get some time to poke around.  I can’t wait!


    the status of .netSavant…

    November 11, 2009

    I have this awesome little ADO.NET code generator called .netSavant.  It analyzes your stored procedures and generates an optimized wrapper class that encapsulates the logic for execution.  After using it myself for quite some time, I thought, oddly, that I could make a little extra cash from the endeavor.  Heh, sadly I was wrong.  Dispite a lot of interest, few people were interested in paying $50 for a visual studio addin that saved a LOT of time and buggy code.  Wierd, but whatever.

    So, with mixed feelings I killed the project.  It simply cost too much money to maintain the website and merchant account for a product that only sold a handful of licenses over the 18-24 months.

    I’m left wondering what to do with the project.  There are a few options:

    1. Create a codeplex project
    2. Host the source code myself
    3. Release the addin as freeware (no source code)
    4. Release the addin as freeware with sponsorship (uhg, gross right?) (no source code)
    5. Leave the project inactive and move on to other exciting technologies

    I’m wondering if I really want to spend more effort supporting the project as a whole, though with so much time invested, its hard to walk away from it.  Part of me would like to see more people use .netSavant, if only to justify the time I spent creating it.  I’d also like the challenge of updating some of the methodology used to generate the source code, and possibly provide some extensibility points to enhance the analysis features that it supports.

    Perhaps some day .netSavant will be resurrected in a better form.  Until that time, thanks for your interest and support.

    Joshua


    Follow

    Get every new post delivered to your Inbox.