Superfluous Extension Methods

September 14, 2009

I like readable code. I think extension methods can lend aid. Here are a few I like.

IsEmpty

Often I end up doing this to get default string values:

     String name = String.IsNullOrEmpty(someVar) ? "Default Name" : someVar;

But what I want is this:

     String name = someVar.OrIfEmpty("Default Name");

I personally think null strings count as empty strings too, so I don’t have the “OrIfNullOrEmpty.” Let’s implement this little guy.

     public static string OrIfEmpty(this string str, string alternateValue)
     {
        return String.IsNullOrEmpty(str) ? alternateValue : str;
     }

HasItems IsEmpty

So here’s another one. Often times I have IEnumerable items I’d like to check if they’re null, or empty. You can do the old and busted way:

     var items = new object[0];
     var empty = if(items!=null && items.length>0);

That doesn’t really work so nicely when chaining predicates in Linq2Objects. So, let’s make it a predicate-friendly way:

     var items = new object[0];
     var empty = (items??Enumerable.Empty<object>()).Count()>0;
     //that lets us do:
     var people = new[]{new Person("bob"),new Person("suzie")};
     var peopleWithChildren = people.Where(person => (person.Children??Enumerable.Empty<Person>()).Count()>0)

Kinda ooglay, so let’s do an extension method:

     public static bool HasItems<T>(this IEnumerable<T> possiblyNullCollection)
     {
        return possiblyNullCollection??Enumerable.Empty<T>();
     }
 
     //and we can do the inverse
     public static bool IsEmpty<T>(this IEnumerable<T> possiblyNullCollection)
     {
        return !possiblyNullCollection.HasItems();
     }
     //now we can do this somewhere else:
     var peopleWithChildren = people.Where(person => person.Children.HasItems());

RemoveNull I hate the huge stack you get when you hit nulls in the middle of your linq2objects query somewhere. So I’ve got this going:

     public static IEnumerable<T> RemoveNull(this IEnumerable<T> collectionWithNulls)
     {
        return collectionWithNulls.Where(item => item!=null);
     }
0

IE7 Href pwns us all

September 14, 2009

Just spent way too long working on this…so here’s the problem.

     <a id="test-link" href="hello/test.html">test</a>

In IE7 if you do the following:

     $("#test-link").click(function(){
        alert(this.href);
        return false;
     })

It will alert about:hello/test.html

WHAT?

This breaks any callback using the url as you get a security exception for XXS requests.

To fix, use the jQuery version.

     $("#test-link").click(function(){
        alert($(this).attr('href'));
        return false;
     })

When in doubt, blame the DOM!

0

Happy Things

September 3, 2009
0

Sad Things

August 31, 2009
  • Long method bodies
  • 3 nested if statements
    • nested in a for loop
    • nested in a try catch
      • in a long long long ass method
  • 14 thousand line class files (yes, srsly)
  • Large code behind files
    • Code behind files
  • Viewstate
  • asp.NET WebForms HTML markup rape:
     <div name="ctl00$Body$PrimaryPhoneContent" id="ctl00_Body_PrimaryPhoneContent">
0

Ruby 1.9 on Windows

August 14, 2009

There’s a new Ruby Installer for Windows. I’ve tried it on Windows XP and Windows 7 and it works really well. I use and recommend the Ruby 1.9 install as it’s smaller, installs faster, and runs much faster than the 1.8!

0

Large File Uploads with .NET

August 12, 2009

Uploading large files in .NET you will run into a few issues. There’s plenty documented other places on the web about this, but in summary IIS passes the entire file to your asp.NET HttpContext in memory. This means if someone uploads a 1 gigabyte file…congrats, you now have 1 gig of upload data loaded into ram. This might cause a tiny scalability problem.

I’ve got to get these specific requirements working:

  1. Ability to upload files around 1 gig max
  2. Status bar updated throughout process
  3. Ajax like page flow which means no going to other page after upload completes
  4. No damn viewstate allowed

I’ve got a vendor control at work that fufills the first three, however, it relies heavily on viewstate, is closed source, expensive, and damn near imposible to customize the styling. Now it’s throwing random NullReferenceException errors…so it’s time to upgrade.

There’s a really nice open-source project called Neat Upload which nicely impements the pain-in-the-ass code you’ve got to write on the server. Both to provide support for direct-to-disk streaming (see: no loading into memory) of the file as well as status updates. It comes packaged with both web controls (for the weak) and the ability to work straight from an HTML page with some javascript you’ve got to implement yourself. I found the client-side html only example to be a bit nasty, and still not exaclty as easy as it should be. So I looked a bit some more and found this hot hot script to provide the client-side goodness allowing for a totally customizable and very jQuery-esque experience.

Let’s tie the two pieces together, shall we?

The neat upload component will sniff incoming http requests for the post data with a special key. The key must be in this format:

NeatUpload_##SOMENUMBERHERE##-fileField

The ajax-upload client script allows us to configure the post key explicitly with it’s “name” configuration variable. Nice. So, we can set the name variable as follows

//we need to save this postback id when we do a callback for
//the status bar data
var postBackID = Math.round(Math.random() * 100000)+new Date().getTime();
new AjaxUpload('uploadDiv',{
    action:'upload.ashx',
    name:"NeatUpload_"+postBackID+"-fileField"
});

That is all that’s needed to have the Neat Upload handler pick up on the upload request.

The action ‘upload.ashx’ page is the handler which will be invoked after the upload is complete (or if it errors out). You can do post-processing on the upload afterwards. This is all pretty well documented in the neat upload examples.

The nice thing about the AjaxUpload library is it will run your upload request client-side in a separate, hidden iframe. This allows us to make repeated callbacks to our server to request status from NeatUpload and when the upload finishes, the page doesn’t redirect anywhere.

Now, we need to set up a few more config parameters on the AjaxUpload object to be able to call back to the server. Please note I’ve mixed in a bit of jQuery code below, but it should be easy enough to do this with your favorite library.

//we'll use this to store the window callback timer
var intervalID;
 
//we need to save this postback id when we do a callback for
//the status bar data
var postBackID = Math.round(Math.random() * 100000)+new Date().getTime();
 
new AjaxUpload('uploadDiv',{
    action:'upload.ashx',
    name:"NeatUpload_"+postBackID+"-fileField",
    onSubmit:function(){
        intervalID = window.setInterval(function(){
                   $.getJson('neatupload/progressjsonhandler.ashx?postBackID='+postBackID,
                   function(data){
                        //we get a json object back with the current upload status
                        //we can use the data to update a jquery status bar
                        //or anything else we see fit
                        console.log(data.PercentComplete);
                   });
        },1000);//callback interval every second, adjust as you see fit
    }
});

Presto. Ajax upload. Nice experience for the client and low load on the server.

0

dingo ate my posts

August 4, 2009

So some vietnamese hacker doods got into my dreamhost account some how.  Maybe they just brute-forced the password?  Not sure.  They got in, regardless, and installed some nasty malware scripts.  So I backed up my posts and took down the site until I could figure out what else to do.

I’ll be working on putting the posts back up sometime later, but as I did the code samples in a few different formats, I’m kinda feeling like maybe I should just move foward and leave the old ones in the drawer.  We’ll see.

0