Recently in Programming Category

LINQ to JavaScript

No Comments No TrackBacks

I’ve been using LINQ in C# since shortly after Visual Studio 2008 was released. It was an awesome addition to the language, allowing you to call into a database model in a method that is identical to how you deal with in-memory collections. Admittedly, LINQ is basically an entire data-munging framework built around various classic functional programming constructs such as map and reduce.

If LINQ has a problem, it’s that writing a new provider can be really difficult, since it requires pretty deep understanding of .NET expression trees, however most people won’t ever need to do that. Plus, LINQ is one of the primary reasons why extension methods were added to .NET, and even if LINQ wasn’t as great as it is, extension methods are something to get excited about in a statically-typed language.

Anyway, for manipulating pure data, LINQ is a wonderful too, and Chris Pietschmann has released a version of LINQ for JavaScript. And it’s in the flexible Microsoft Reciprocal License, so it’s easy to download and use. It’s about 7k raw, with very clean code, and about .7k after minification and gzip, for a minimal impact on page weight. And, if you’ve ever written LINQ, the syntax is basically identical to the lambda syntax.

var myList = [
  {FirstName:"Chris",LastName:"Pearson"},
  {FirstName:"Kate",LastName:"Johnson"},
  {FirstName:"Josh",LastName:"Sutherland"},
  {FirstName:"John",LastName:"Ronald"},
  {FirstName:"Steve",LastName:"Pinkerton"}
];
var exampleArray = 
        JSLINQ(myList)
        .Where(function(item){ return item.FirstName.match(/^Jo/); })
      .OrderBy(function(item) { return item.FirstName; })
      .Select(function(item){ return item.FirstName; });

/**
 * exampleArray = [ "John", "Josh" ]
 **/

Now, the blurb that Chris wrote for JSLINQ is a bit wrong. He says the following:

LINQ to JavaScript (JSLINQ for short) is an implementation of LINQ to Objects implemented in JavaScript. It is built using a set of extension methods built on top of the JavaScript Array object. If you are using an Array, you can use JSLINQ.

The important distinction is that JSLINQ works on array-like objects, such as HTMLCollections. But, also that I first red the ‘extension methods’ comment to mean that he was modifying Array.prototype. Thankfully, that’s not the case, which is why you need to call JSLINQ on your collection first.

Personally, I think the ability to query the DOM with this is less useful than the ability to query over data sets, especially since YUI3 already provides pretty rich support (using CSS Selectors built into modern browsers). However, the ability to take an existing list and filter it down using LINQ style expressions can be very useful. YUI3’s NodeList is not an array-like object. There are basically two options.

The following example will get all the anchor tags on a given page which reference internal links (links to the same domain as the page):

JSLINQ(Y.NodeList.getDOMNodes(Y.all('a')))
    .Where(function(item){ return item.href.match(location.host); }
    .Select(funtion(item) { return item; }

Y.all('a[href*=' + location.host + ']');

The second example does require the ‘selector-css3’ submodule to be loaded (it isn’t by default), but it’s a far cleaner syntax for querying the DOM, so the examples of JSLINQ that query the DOM aren’t necessarily the most useful, but if you need to do any client-side filtering or munging of data, LINQ is a really nice syntax for doing that, which is SQL-like, but still unique to your environment. If you’re already familiar with .NET 3.5 and LINQ in that world, then I’d suggest looking at JSLINQ for your projects, it’s familiar, and it looks as though it should work well.

  • StumbleUpon Toolbar Stumble It!

The Power of Vim

2 Comments No TrackBacks

I am a reformed emacs user.

Used it for years, on a dialy basis, as my sole programming environment. Eventually, I got tired of it. It took forever to start up (I didn’t just leave it open), it wasn’t always available, like when booting from a Live CD or something, and it was disturbingly overkill for any need to perform a simple edit on a configuration file. Unfortunately, the default editors that were (and are) on most Linux distributions are dinosaurs like pico or nano, which are downright unpleasant to use.

Oh, sure I’d tried Vi before, but it had seemed so obtuse. A model text editor? Why would I want modes on my text editor? But over time my love for emacs waned. Doing simple things like copying text required mastery of obscure chorded commands, and hardly an incantation existed that didn’t require a half dozen modifier keys. It was originally the desire for a text editor that I didn’t mind opening for quick edits, one that I didn’t feel I needed to marry just to learn to use, that originally drew me to vim.

Soon, switching between entry modes was second nature. The first time I wanted to search, and found it no further away than the Perl regex language…I knew I couldn’t go back.

Then, I found myself out in the workplace, a free software hacker trapped in a Microsoft Ghetto (it’s a big ghetto, don’t get me wrong). Sure, I could have installed Vim on Windows, and I did, but I’ve always found Visual Studio makes for a painful tool when trying to use other editors. Sure, other’s have done it, but it wasn’t worth it for me. However, recently, I’ve decided to refocus on learning vim. In part, because I’m tired of hearing people brag about features of their editors that Vim has had forever, but also because those skills finally translate into my day job, now that there are bindings for Visual Studio 2010 to behave like vim.

Still, there is much to learn. Rob Conery, a former Microsoftie who’s since gone out on his own, has started posting Vim Kata on his blog, an extension of the code kata’s that have gained popularity lately, this is just a repetitive set of instructions you can repeat to get a little better at certain vim commands. Plus, Drew Neil is doing weekly vimcasts, which lack the repetition of the kata’s, but provide great information and more explanation than Conery has.

Lately I’ve also been looking at modules for vim to make it more complete. To help with my recent YUI3 presentation, I started using SnipMate, a port of TextMate’s snippets to vim, creating a custom snippets file for that. I’ve installed the Gist script, to make working with Github Gists easier. I’ve been learning to configure vim so that I automatically get the file formatting rules I want for whatever platform I’m working with.

I won’t say that Vim isn’t a complex editor, and that the modal editing takes some getting used to. However, I will say that since I’ve really worked to learn Vim, I’ve found there is a logic to everything it does, and that my programming has probably gotten faster. Certainly, there is something to be said for the tools in Visual Studio which aid in refactoring, or IntelliSense, which helps make sense of an immensely complicated API. However, ultimately these editors are just text editors, and I’m increasingly convinced that no editor mangles text as efficiently as vim.

  • StumbleUpon Toolbar Stumble It!

Portland Code Camp 2010 Recap

No Comments No TrackBacks

If I had to choose a single word to sum up the Portland Code Camp event, it would be ‘inspiring’. I sat through some excellent presentations, which certainly have recharged my interest in technologies like F# and Clojure, but also the scale that the organizers for this event managed to meet was awesome. We were lucky, in that we were able to meet with the organizers for a short while in the evening and get some really amazing advice that we hope to use to make our own event a success this fall.

What were some of the impressive things about this event? Well, they had the Mayor of Portland on hand to talk about Technology companies in the area, with questions submitted via Twitter. Presenters and Volunteers were provided with work-quality Polo Shirts, instead of T-Shirts that I would likely never have worn again. There were hundreds of people present, and while I haven’t seen a final count just yet, I’m certain they reached their goal of 600+ people. In all, it was by far the most professional code-camp that I’ve seen.

If it had a weakness, it’s a similar weakness that all Code Camps I’ve been to have had: They feel too heavy with Microsoft technologies, which is a turn off for a certain segment of the coding population, including myself though (and perhaps because) I deal with these technologies on a daily basis. However, having spoken with the organizers, they were trying to work with the Bar Camp Portland people to try and bring that Open Source perspective into the Code Camps. I hope that our event, since there is basically no open-source heavy events to compete with, might help bridge that gap.

I also took the opportunity to test taking notes via the Mind Mapping method of taking notes, trying the VYM software package I found in the Ubuntu Repositories. I’ll have to try a few other software packages, but I found VYM easy to use for simple mapping, though I couldn’t discover keyboard shortcuts for flagging entries or changing colors. I didn’t have time to look very hard though.

I began with the F# talk given by Microsoft’s Michael Hale, a PM at Microsoft on Visual Studio and F#. I’ve been hearing about F# for several years, and been meaning to look into it, having been exposed to Functional Programming via LISP in college, and believing in the potential of functional programming for making concurrency far easier to solve. F#’s syntax kind of reminds me of JavaScript, in that it’s a LISP-derivative that looks more like C, though admittedly, F#’s syntax is further from C than JavaScript’s.

F# is still a .NET language, so it’s object model is the same as in every other .NET language, which makes sense in that F# can be merged seamlessly in with other .NET code. Plus, Michael gave us several examples of code written in ‘normal’ iterative methods, and expanded into how they could be rewritten functionally. In some ways, I think the syntax of F# is more clear than the languages from which it is derived. Rather than nesting functions with parenthesis as you do in LISP, you can basically pipe commands together, the only weakness to that method being that the pipe can only be applied to the last argument of a method. However, that’s only a minor inconvenience. Best part about F#? Not only does it work in Mono, but Microsoft actually provides an install script for Mono. Awesome. And it encourages me to spend some more time with F# in the near future.

My next hour was spent learning more about the Reactive Framework, which is a pretty interesting way of looking at events (I just hope Microsoft doesn’t enforce any patents I’m positive they’ve applied for on this technology). Basically, with the Reactive Framework, you subscribe to a sequence of events, but then you can easily mash events up to do things like “When X happens, followed by Y, do Z.” With Rx, this can be done with a couple of lines of code, instead of dozens of lines of state machine and state tracking code. Given that Rx has been ported to JavaScript, and my favorite framework, I’ll definitely do an upcoming post on Rx and YUI3.

Speaking of YUI, my talk went well. I had a dozen or so people come, some of whom left early (I assume I was being too basic, but that was my intent), and I had some really good discussion. I might have done too many comparison’s to jQuery, but jQuery is the 800 pound gorilla in the JavaScript room right now, and since Microsoft endorsed jQuery last year, most people programming in the MS ecosystem have little to no exposure to any other options. It is something I’m going to consider revising for September however, when I hope to also do a section on creating custom YUI3 modules.

I also had the opportunity to meet Ryan Grove, YUI Core Team member, and it was nice to finally meet in person someone from the team, as well as have them feel that I’d done a good job of describing the framework. I freely admit to being a bit of a YUI cheerleader, and I fully intend to continue telling people about it and trying to convince them to give it a shot.

After my talk, I decided to go to a conversation about Clojure and the Semantic Web. To be clear, I was more interested in the Semantic Web discussion, which barely happened, but Clojure was an interesting Java-based LISP. Unforuntately, the version in Ubuntu 10.04 seems to be just a bit out of date, and some of the code examples he presented didn’t work. Still, it might warrant a bit more looking, though at this point I’m a bit more interested in F#.

I ended the day learning about the Mobile Web from a developer who seems to know what she’s talking about. This is a relevant session to me, as I’m planning to do a mobile version of one of our websites this summer. There was a ton of great, useful information in this post, and I think it definitely provided me with a solid framework for starting this project. If I have a complaint about the talk, it was that it kind of felt like a sales pitch for her class sometimes. I can’t really begrudge her mentioning the class, but there did seem to be a lot of ‘we go more in depth on this during my class’ kinds of comments. Still, Gail was very knowledgeable, and certainly got me excited to get going on mobile web development, even in spite of the fact that doing it right is going to be more work than I’d hoped it would be.

In all, it was another successful event. I got some great information, met some pretty awesome people, and got back in touch with some people from years or events past. It was a really long day (some 14 hours), but I’m exceedingly glad to have gone, and if our event can be even a quarter as good as this one was, I’ll be thrilled.

  • StumbleUpon Toolbar Stumble It!

Recently, a coworker expressed frustration over the way he was having to handle errors in WCF Asynchronous callbacks. For Synchronous WCF calls, fault handling is simple:

var webService = new WebServiceWrapper();

try {
    var answer = webService.callMethodSynchronous(arguments);

    // Handle answer 
} catch (FaultException) {
    // Handle Specific Exception
} catch (Exception) {
    // Handle General Exception
} finally {
    // Clean-up
}

Prety basic and normal exception handling code, textbook really.

However, in WCF, when using an async callback the suggested code looks more like this:

var webService = new WebServiceWrapper();

webService.methodAsyncCompleted += (sender, response) => {
    if (response.Error == null) {
        // Handle Success Case
    } else {
        Type exceptionType = response.Error.GetType();
        if (exceptionType == typeof(FaultException)) {
            // Handle Specific Exceptions
        } else { 
            // Handle General Exception
        }
    }
    // General Clean-up
};
webService.callMethodASync(arguments);

The if-statements can be more concisely written as follows:

var webService = new WebServiceWrapper();

webService.methodAsyncCompleted += (sender, response) => {
    if (response.Error == null) {
        // Handle Success Case
    } else {
        if (response.Error is FaultException) {
            // Handle Specific Exceptions
        } else { 
            // Handle General Exception
        }
    }
    // General Clean-up
};
webService.callMethodASync(arguments);

I jokingly suggested rethrowing the Exception:

var webService = new WebServiceWrapper();

webService.methodAsyncCompleted += (sender, response) => {
    if (response.Error == null) {
        // Handle Success Case
    } else {
        try {
            throw response.Error;
        } catch (FaultException) {
            // Handle Specific Exceptions
        } catch (Exception) {
            // Handle General Exception
        }
    }
    // General Clean-up
};
webService.callMethodASync(arguments);

When we wrote this up really quick, our reaction was similar. It really feels like something we shouldn’t do, but it also seems a bit cleaner. On one hand, a Catch block is a great way to determine the exact type of any class deriving from System.Exception (.NET doesn’t allow you to throw Non-Exceptions, other platforms may not have that limitation). But is it worth the potential style faux-pas? And are there any other downsides to this. To see, I checked the IL of a simple application.

For the if-else typeof case:

IL_0000:  ldarg.0 
IL_0001:  callvirt instance class [mscorlib]System.Type class [mscorlib]System.Exception::GetType()
IL_0006:  stloc.0 

IL_002b:  ldloc.0 
IL_002c:  ldtoken [mscorlib]System.ArgumentException
IL_0031:  call class [mscorlib]System.Type class [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
IL_0036:  bne.un IL_004f

For those not fluent in IL, I’ll give a line-by-line: 1. Load the first argument onto the evaluation stack, prepare to use it. 2. Call System.Exception::GetType(), which returns an instance of System.Type 3. Store the return value of the previous operation into location 0 4. Load the value in location 0 onto the evalution stack 5. Load the token representing System.ArgumentException onto the evalution stack 6. Call GetTypeFromHandle to get a Type reference to the token loaded previously, this will use the top of the evaluation stack, and will put the return valeu on it. 7. If the two values are not equal (bne) than jump to IL_004f, which happens to be the instruction where our Else block begins

For the if-else is case:

IL_0000:  ldarg.0 
IL_0001:  isinst [mscorlib]System.ApplicationException
IL_0006:  brfalse IL_001f
  1. Load argument 0 onto execution stack
  2. Take the top of the execution stack, check if it’s an instance of System.ApplicationException, put a boolean on the execution stack
  3. If false is on top of the execution stack, go to IL_001f

And now for the try-catch version:

.try { // 0
 IL_0000:  ldarg.0 
 IL_0001:  throw 
 IL_0002:  leave IL_0046

} // end .try 0
catch class [mscorlib]System.ApplicationException { // 0
 IL_0007:  pop 
 // Do whatever
 IL_0017:  leave IL_0046

} // end handler 0

Breakdown: 1. Load the value of the Exception on the evaluation stack 2. Throw it 3. This will never be hit in this example. It would jump to the finally block. 4. Clear the value off the top of the stack 5. Go to the Finally block.

It certainly is more IL, but from a pure IL perspective, it doesn’t seem…bad, except for the fact that it does create a LOT more blocks, and leaving those blocks is a more expensive operation, since the Try and Catch blocks are considered ‘protected’ regions of code. Setting up and entering these might be more expensive, I’m not really sure, and I’d love someone more familiar with .NET Runtime internals to post their take on it.

After looking over both the IL and the C# code, I’m left thinking that using the ‘is’ operator is the best option in this case. It generates the least amount of code. The simplest code. The only downside is that it has you testing exceptions using code that doesn’t resemble exception handling anywhere else. For that reason alone, the Try-Catch mechanism may really be best, though I am leaning toward simply using ‘is’.

What are your thoughts?

  • StumbleUpon Toolbar Stumble It!

Visual Studio 2010 Gotchas

2 Comments No TrackBacks

A quick update about trying to upgrade to VS2010:

  1. VS2010 does not have a version of BIDS (Business Intelligence Development Studio). This means you can not modify certain classes of Database Projects in VS2010, like any SSIS tasks. I was lucky, all my SSIS tasks are in seperate solutions from the rest of the projects for my code. If your’s aren’t, you’ll need to extract them. VS2010 will happily update an SLN file and simply disable any DTPROJ files in the solution.
  2. VS2010 can not cross-compile .NET 3.5 Test Projects. If you’re doing any Unit Testing, your Test projects will be automatically updated to .NET 4.0, even if you’re trying to stay on .NET 3.5 or lower for a little while. You’ll need to either disable your Test projects, or be prepared to upgrade everything to .NET 4, even if you’re don’t want to (or are unable to)
  3. Not a VS2010 issue, but Workflow Foundation 4 doesn’t support State Machine Workflows (yet), so if you’re using State Machine Workflows currently, you can’t update to .NET 4 at all.

Actually #3 is a huge issue, since there is no timeline on the state machine workflow support for .NET 4 (other than it’s been stated that it is being worked on). Basically, we’re down to the choice of forking our solution files, so that we have some that are VS2010 solutions running .NET 4, and some that are VS2008 solutions running .NET 3.5, or simply not upgrading to VS2010/.NET4 at all, since we have interdependencies that complicate the issue (we strive to adhere to the DRY principle). I was really looking forward to VS2010, but the reality of the situation has tempered my enthusiasm drastically, between pointless incompatibilities (unit testing) and feature regression (state machine workflows), it might be a while before we’re able to upgrade.

I’m disappointed. Really disappointed.

  • StumbleUpon Toolbar Stumble It!

StyleCop in Hudson, revisited

No Comments No TrackBacks

As noted in the comments to my post on Tuesday, the original solution I had to this ended up being a lot less flexible than I thought. For one, StyleCop will apparently only parse out StyleCop.Settings files above the folder from which you began executing StyleCop. So, any StyleCop.Settings files below the directory with my controlling MSBuild file won’t actually be processed. That also means that the suggestion by Jason Allor on that post, to set the StyleCopEnabled Property in the CSProj file, didn’t have any effect, StyleCop doesn’t parse out CSProj files.

It turns out that the suggestion that I’d based my solution off of was a little too simple. It didn’t allow me to prevent StyleCop from running on a given project. It didn’t allow me to prevent StyleCop from running on a given set of files or projects. It wasn’t properly letting me modify rulesets for different projects. In short, it just flat didn’t work for anything but the most simple of circumstances. On the one hand, I can’t blame Craig Berntson, who gave that Boise Code Camp presentation, for over simplifying the situation, but on the other hand, it didn’t work well.

Of course, Mr. Allor from Microsoft has already posted on his blog about the real solution to this problem. Basically, run the code in every single CSProj file. This is a little shitty, since I had about 30 projects to modify, and Visual Studio does not make it trivial to modify the core templates that are used to create new projects. In the next month, I’m going to put together some tooling to make it easy to add custom code to every template matching a certain pattern in VS2010 (we’re going to be switching as soon as we can). This might be an external tool, but I’m looking at seeing if I can take advantage of VS2010’s extensibility model. I’m only in the earliest stages of contemplating this.

For now, I’m hand managing the CSProj files to insert the Include that is from the link above, but we did have one special requirement. At least one member on our team didn’t want StyleCop running on every build. My experience with StyleCop’s caching is that it’s not really an issue, but MSBuild makes this pretty easy to handle. We have a three-target build process: Debug, Test, and Release. When run from our controlling build script, Test will push to our Test server, and Release to our production server. Generally speaking, we always run Debug from Visual Studio, Test from CI, and Release only when we’re pushing stable builds, so the following block in all our CSProj files:

    <Import Project="$(MSBuildExtensionsPath)\Microsoft\StyleCop\v4.3\Microsoft.StyleCop.targets" />
    <PropertyGroup>
        <StyleCopEnabled>false
    </PropertyGroup>
    <PropertyGroup Condition="'$(Configuration)' == 'Test'">
        <StyleCopEnabled>true
    </PropertyGroup>

This ensures that StyleCop only runs when doing a “Test” build. For projects that I don’t want to run StyleCop against, I simply exclude the second PropertyGroup (and usually the Import as well, why bother importing what you’re not using?)

I’m not saying that you should exclude StyleCop from developer builds. But it is nice to know MSBuild makes it pretty easy to do.

  • StumbleUpon Toolbar Stumble It!

Boise Code Camp 2010

No Comments No TrackBacks

This last weekend marked the third year I’ve been able to attend the Boise Code Camp, an excellent developer-focused, community run event help each spring in Boise, ID. This has, in the past, been the largest code-camp event of the year in our region, but it’s numbers were down this year, probably in part because of the Utah Code Camp (link is to their HTML version, the Silverlight Version hangs my machine. Unsure if that’s an issue with moonlight, or my box) was held on day one of the event, which prevented some people who may have come up to Boise before from coming up this year.

We’ve noticed that this year is really heavy with Code Camp events in the Spring, with Boise’s having just finished, Seattle’s the weekend after next, and Portland about five weeks after that. For this reason, our own Palouse Code Camp, won’t be held until September, though we’ll need to work with Utah to ensure we don’t schedule for the same weekend.

Despite the lower turnout than in years past, it was still a fantastic event. With some fantastic sessions. As usual, if I have any complaint with Code Camp, it’s simply that they do tend to focus on Microsoft technologies (though they don’t have to), and Microsoft stack developers tend to be really focused on what exists within that stack. Or, at least, they mostly only know much about what’s in that stack. Of course, I didn’t put together my YUI3 talk, so I can’t complain about all the jQuery talks too loudly, but I will have such a presentation for the Palouse event in September.

Some of the sessions I went to, I didn’t get as much out of as I would have liked. I began my first day, hoping to learn about using CouchDB in C#. Unfortunately for me, the talk was more an intro to CouchDB in general, but I did learn a bit, and was able to contribute to some discussion about the benefits of NoSQL (though we didn’t touch on the possible harm). Then, I went to a talk live-demoing web application vulnerabilities, which keyed me in to a few tools, but ended up being more basic than I had hoped. Also on the first day were a few talks on Progressive JavaScript by a person who didn’t seem as keyed into the topic as I had hoped, even going so far as to claim that ‘there are no JavaScript-only developers’. Admittedly, most developers don’t get to focus solely on the JavaScript side of front-end engineering, but there are plenty who do, and they spend a lot of time working to promote professional-grade JavaScript practices. I do think others got stuff out of the talk, but for me, it was two sessions almost entirely wasted.

The best talk I attended on Saturday, was, by far, Chris Billson’s “Powershell for Production Programmers” presentation. Powershell is basically a UNIX-like shell for Windows, where commands (and commandlets) can return .NET objects instead of just strings. Imagine a shell where you can pipe the output of ls to another program to easily filter out things based on file attributes, while being able to access those attributes as object properties instead of parsing strings by hand. I really want a python-based UNIX shell that can pipe around python objects instead of just strings now.

Powershell has some warts, which I’ll expound upon at a later time, but for the most part, it’s an awesome technology.

Sunday, I learned about Django, and some of what’s been added since 1.0, and about the south module, which provides truly awesome schema migration. South alone was enough reason to attend this presentation, and I really need to find something to with Django soon.

Finally, the last session I attended was from Microsoft MVP Craig Berntson, on what to do now that you’ve got Continuous Integration up and running. Namely, he wanted to discuss setting up StyleCop and FxCop, both of which I’ve looked at to integrate into our own CI build process (though I’m likely to use Gendarme instead of FxCop).

Automating things in your build to tell you about potential code ‘smells’ is possibly even more important that running automated unit tests, but most people just stop about the unit tests. Admittedly, StyleCop and Gendarme have a lot to complain about in our codebase right now, but that’s largely because we haven’t identified which rules we want to ignore. By integrating this into our build, we’ll be forced to start taking action (whether to ignore or fix), and then we can make these issues actual errors, instead of being too afraid to apply these tools.

I’ve got some posts coming on some of this tech that we covered, and how we’re integrating it into our environment. And there were some awesome sessions I wasn’t able to go to, like on the new version of Entity Framework, which might actually get us off of LINQ-to-SQL.

Our next code camp will most likely be the one in Portland, but Seattle is a possibility as well (it’s just so soon…). If you’re in a region that has a code camp within a few hours, I absolutely suggest going. There is a lot to be learned.

  • StumbleUpon Toolbar Stumble It!

Recently I was building a simple web application form where one of select boxes was driven by the value of a different box. The original code for this seemed pretty straightforward, but while the code worked perfectly in Firefox and Chrome, it was producing amazingly strange behaviour in Internet Explorer. Namely, when I’d rebuild the select box, IE would not position the text correctly inside of it, the dropdown wouldn’t appear reliably, and when it would, it wouldn’t necessarily show the correct text for the selections. In one case it was actually displaying four selections, when there were in fact only two. You could use the keyboard to select the values correctly, but this was still absolutely unacceptable behaviour.

I’ll do a write up on the behaviour later this week, but I decided to jump the gun and present the solution I developed first, since I don’t have good simple examples just yet. I ended up trying several ways of creating the options before appending them to the select element, but eventually, I had to completely recycle the selectbox in order to make it behave correctly. I’ve had other pages that didn’t misbehave in quite this way, so I’m trying to figure out the minimum case to recreate the problem before I send it to Microsoft.

Luckily, JavaScript makes it pretty easy to branch code based on browser in a way that doesn’t require doing the browser check all the time. Below is a generic version of the function to do the replacement, which includes calling a ‘change’ event handler, which unfortunately can’t be anonymous (at least in YUI3) since ‘change’ events can’t be simulated. Actually, having to rebind the changeeventhandler every time you change the contents of the select box is the only possible ‘challenge’ in the problem.

var rebuildSelectBoxOptions = Y.UA.ie > 0 ? function(box, options, change_event_handler) {
    var newOption, newSelector;
    newSelector = Y.Node.create(box.set('innerHTML', '').get('outerHTML'));
    for (var i = 0; i < options.length; i += 1) {
        newSelector.append('<option value="' + options[i].value + '">' + options[i].text + '</option>');
    }
    newSelector.set('selectedIndex', 0);
    box.replace(newSelector._node);
    if (Y.Lang.isFunction(change_event_handler)) {
        change_event_handler({target: newSelector});
        newSelector.on('change', change_event_handler);
    }
} : function(box, options, change_event_handler) {
    box.set('innerHTML', '');
  for (var i = 0; i < options.length; i += 1) {
        box.append('<option value="' + options[i].value + '">' + options[i].text + '</option>');
    }
    box.set('selectedIndex', 0);
    if (Y.Lang.isFunction(change_event_handler)) {
        change_event_handler({target: box});
    }
};

The non-IE version is a couple of hundred bytes lighter, and should be faster (though for most use cases, the difference is likely negligible). I’m not sure yet what the increased garbage collection load of this will do to IE, but in my case, that’s not likely to be a problem.

  • StumbleUpon Toolbar Stumble It!

Introducing gallery-slideshow for YUI3

No Comments No TrackBacks

Recently, at work, we had a desire to update an instance of a flash-based slideshow widget on our commencement website. This widget did absolutely nothing special, but the real problem we had was that, we didn’t actually have a license for Flash, and the way the slideshow had been built, we needed to be able to build the SWF file from scratch in order to update the order. Since our users rarely come to us with anything that isn’t some sort of emergency, we had to take the flash files to another department to make our quick change and compile a new SWF.

Of course, I knew there was no reason to continue to use unconfigurable Flash for this, but YUI didn’t have a slideshow widget. So, I decided to start writing one. Due to the excellent widget framework, I had a quick-and-dirty example written in a mere couple of hours. Of course, that was not something I was really going to release, though I did push it up to my github.

It was about a week before I was able to return to the project, but I have now submitted a very basic, but functional widget to the Y! CDN.

The javascript to run the above slideshow is simple, for the user:

The CSS that it requires is straightforward, and is part of the widget’s assets:

The widget will automatically take care of placing the images in the upper-left hand corner of the widget’s content box, as well as cycling through all the images using the transition sent in via the animation configuration option.

The core of slideshow is mostly done at this point. I plan to add support for the an image to transition in, instead of only having the top image transition out. Most functionality will likely be added via the plugin framework. And I have several plugins planned.

  • Titles - Adds the widget header which will be populated with the ‘title’ value from the images array.
  • Descriptions - Like Titles, but in the footers. I’m thinking this will take either a string or a function to generate the content of the footer div.
  • Image Centering - This will center all the images in the content box, allowing the slideshow to consist of images of different sizes.
  • Image Navigation - Buttons (probably images with click events, but you get the idea) which will allow the user to force transition between images.

The plugin framework is great because it allows you to customize a widget with exactly the kind of features you need. There are a lot of other kinds of plugins that would be appropriate, and I’m certainly open to feature requests, or pull requests would be better!

  • StumbleUpon Toolbar Stumble It!

Software Testing Club Magazine

No Comments No TrackBacks

The Software Testing Club, an organization I had never heard of before Ara Pulido who works for Canonical on the QA Team, mentioned it on her blog, recently released the first issue of the own Community Magazine. Having downloaded and read it over the last few days, I was pretty pleased with the content, and will likely continue to read, especially since my testing chops could use some improvement as I’m expected to be a developer and tester in my current position.

And I would argue that even developers not in dedicated test roles should read this magazine, since it provides good feedback, especially on bug reporting and the mechanisms (and importance) of testing. Unfortunately, the Magazine doesn’t seem to have made any efforts to sort of bridge that gap between developers and testers. To be fair, it was written by people focusing on test, and developers have often been harsh toward testers, so I’m not necessarily blaming them for the making fun of developers that’s done. I merely found it interesting how prevalent media around this conflict are.

The only real complaint I have with the magazine is that it does have some editing issue. Sentences getting cut off at page breaks, obvious typos, etc. I hope that the STC can improve their processes and put out a more polished community magazine in the future. Still, for a first effort it’s a good read, and it has plenty of information I’m still mulling over.

  • StumbleUpon Toolbar Stumble It!