Archive for December 2008


MacBook Pro “Bluetooth Not Available”

December 20th, 2008 — 1:27pm

Let me just say that I can't wait for Snow Leopard (the next version of Mac OS X).  I'm looking forward to the increased stability and performance promised by the Steve.  I'm especially interested in better multi-proc support as I'm constantly in and out of a Windows VM and I'm hoping that activity will be a little more smooth on a faster host OS.

I generally find Leopard to be very stable and haven't had too many issues but I do occasionally run into issues with the Bluetooth device not responding.  Intermittently the menu bar icon just says "Bluetooth Not Available".  It seems mostly to happen after connecting or disconnecting certain USB devices to the machine.

After hunting for a solution I came across this Apple support document.  It seems like a bit heavy handed, and I'm not exactly sure why: "Over time, the settings in the System Management Controller may become
unusable, which can result in operational anomalies with the computer.
"

However, it solved my problem and I'm once again mousing away with my fantastic Microsoft Bluetooth Notebook Mouse 500, which I highly recommend for the heavy laptop user like myself.

2 comments » | Mac

StackOverflow Love

December 17th, 2008 — 1:31pm

I love stackoverflow.com!  It doesn't get much better than a bunch of geeks answering each others' questions for merit badges ;)

Comment » | Uncategorized

jQuery vs. the ASP.NET Update Panel Revisited – Event Delegation

December 5th, 2008 — 1:17pm

Recently I was again struggling with the ASP.NET Update Panel killing my JavaScript interactions because it replaces the DOM elements it surrounds on every refresh.  My previous solution for this was simply to rebind those events after each Update Panel refresh was completed.  This works perfectly well, but it always seemed a little heavy handed to me.

So in digging into this issue a little more, I came upon a few posts that talked about using event delegation to solve this problem (thanks to everyone out there who wrote about delegation, cause you're smarter than I am).  The basic idea is that you attach events at a higher level in the DOM tree and use the DOM's event bubbling mechanism to catch them.  For example, let's say we have the following ASPX snippet:

<div id="container">
    <ul>
        <asp:UpdatePanel>
            <li class="listItem">Item One</li>
            <li class="listItem">Item Two</li>
            <li class="listItem">Item Three</li>
            <li class="listItem">Item Four</li>
        </asp:UpdatePanel>
    </ul>
</div>

Now let's assume that you've done this somewhere in JavaScript:

function bindLiEvents() {
    $("li.listItem").bind("click", function() { alert($(this).html()); });
}

When this JavaScript is executed jQuery loops over all the found elements and individually attaches an event handler to each.  So already there is an inherent performance gain to be had by not doing this looping.  Furthermore there is now the problem with the Update Panel.  If the user takes some action that causes the panel to refresh, then the four <li> elements are destroyed and recreated and unless I call bindLiEvents again after the refresh I loose this functionality.

Enter the event delegation concept.  Why not attach my handler to a DOM element that's outside the Update Panel – the <div> element in this case.  This may seem a bit counter intuitive, but if you're aware of how event bubbling works in the DOM you can see how this might work.

Event bubbling simply means that events at lower levels in the DOM tree are propagated to higher levels.  For example when an <li> is clicked in our example, the click event is also fired on the <ul> and the <div> and beyond.  We can use this behavior to our advantage in this instance because event bubbling is intrinsic to DOM elements – when new elements are added they automatically exhibit this behavior.

So now let's look at how we might attach an event to the <div> element:

function bindLiEvents() {
    $("#container").delegate("click", "li.listItem",
        function() { alert($(this).html()); });
}

Don't worry about where the delegate method comes from – it's not native to jQuery but I'll get to that.  What's happening here is that I'm binding a very generic event handler to the <div> element, and telling that handler to listen for click events on elements that match the "li.listItem" selector.  So now, when an event bubbles up from an <li> element the handler on the <div> fires, tests if the event originated on an <li> with a class of "listItem" and then calls the function callback.

There are advantages to using the approach.  First, event handlers are attached only once, and only at a single point which saves time when doing the initial bind.  Second, any new elements added to the Update Panel will automatically fire the delegated event handler – no rebind is required.

So if you want to try this out for yourself, here is a jQuery plugin for the delegate method:

(function ($) {
    var bubbledEvents = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove',
        'mouseover', 'mouseout', 'keydown', 'keypress', 'keyup'];
    var allowedEvents = { };
    $.each(bubbledEvents, function(idx,event) { allowedEvents[event] = true; });
    $.fn.extend({
        delegate: function (event, selector, func) {
            return $(this).each(function () {
                if (allowedEvents[event])
                    $(this).bind(event, function (e) {
                        var el = $(e.target), result = false;
                        while (!$(el).is("body")) {
                            if ($(el).is(selector)) {
                                result = func.apply($(el)[0], [e]);
                                if (result === false) { e.preventDefault(); }
                                return;
                            }
                            el = $(el).parent();
                        }
                    });
            });
        },
      
  undelegate: function (event) { return $(this).each(function () {
            $(this).unbind(event); }); }
    });
})(jQuery);

2 comments » | JavaScript, jQuery

Dynamic Expressions with LINQ to Entities

December 1st, 2008 — 1:47am

There's been a lot of buzz lately around LINQ to Entities (aka Entity Framework).  Some of the buzz has been positive, a lot has been negative, but it does appear that Microsoft will invest a lot in LINQ to Entities moving forward.  On a recent side project I had occasion to use EF to connect to a SQLite database running locally within a web application.  It's an interesting little architecture and despite it's obvious scaling issues, it's working really well for the problem space.

Anyway, one of the features I needed was search…and not just any search, a very dynamic search.  The application is an inventory tracking system and it allows a user to set up different kinds of items and create a unique list of properties that each of those items can have.  For example you might create an item of type 'Widget' with two properties 'Size' and 'Color'.  Another type might be 'Bobble' and it has properties 'Width', 'Volume', and 'Friction Coefficient'.  So in order to search for these types I'm forced to dynamically construct a search screen.

This dynamic search screen is where the issue comes in.  Because I'm searching an indiscriminate number of properties and I don't know at compile time what those properties are, I need to execute some type of dynamic query.  Those of you who are familiar with LINQ will know that this is easier said than done.  It's not like I can just construct a SQL statement at runtime and then pass it to the database for execution.  Enter the System.Linq.Dynamic namespace.

I found this blog post by ScottGu on the exact subject.  (The post is labeled Part 1 but I haven't been able to find a Part 2 anywhere…if you find it let me know.)  His post will point you to where you can download the source for the System.Linq.Dynamic assembly which you'll need to build and include in your project.  I did see mentioned that this is part of .NET 3.5 SP1, however I was unable to find it on my system.

Once you have the library referenced it becomes quite a bit simpler to generate a query at runtime.  The library parses an expression syntax that's pretty simple.  The primary use for generating queries at runtime is going to be setting up WHERE conditions; you can however create an entire query dynamically if you need to.  Here's an example of a LINQ query as it would be written at design time:

var items = (from InventoryItem item in db.InventoryItem
             where item.Category.ID = 7
             select item).ToList<InventoryItem>();

This is a pretty innocuous query and doesn't really warrent being turned into a dynamic query but for example's sake, here's how you'd write it:

var items = db.InventoryItem.Where("Category.ID = @0", 7).ToList<InventoryItem>();

It's really that simple.  After you include System.Linq.Dynamic in your using statements a new overload of the Where method is available.  This new version of Where takes a string predicate (the where statement) and an array of objects that are parameters for the query string.

Because you don't have the benefit of type safety within the query string, you'll have to be careful with your syntax.  For example, when using a property of a property (item.Category.ID in the above example) you have to remember to use the names you've assigned to entities in your model not the names in the underlying data source.

There are other ways to create a query dynamically including using ObjectQuery<T>, or building up predicates in a pseudo-recursive way as in this post from the C# 3.0 in a Nutshell guys.  However, I find the dynamic query method here to be easy to understand and very powerful.

Comment » | .NET

Back to top