Skip to Menu

The most recent posts to the Web Developer Blog are listed below. Licenced under a Creative Commons Licence.

JavaScript dates and timezone offsets

Wed, 23 Jul 2008 16:50:00 +0000

Working with dates can be problematic when handling dates returned by a remote server. They were returned in GMT format, but when displayed on a page, the time was either ahead or behind (depending on which timezone you are in). For example, if you have the date returned via JSON:

var dates = {"StartDate": new Date(1216944000000),"EndDate": new Date(1217030399000)}

So the date now has the timezone offset added:

dates.StartDate = Fri Jul 25 2008 01:00:00 GMT+0100 (GMT Standard Time)
dates.EndDate = Sat Jul 26 2008 00:59:59 GMT+0100 (GMT Standard Time)

So now, to take into account the timezone offset, getTimezoneOffset() can be used, along with setMinutes() and getMinutes()

dates.StartDate.setMinutes(dates.StartDate.getTimezoneOffset() + dates.StartDate.getMinutes());
dates.EndDate.setMinutes(dates.EndDate.getTimezoneOffset() + dates.EndDate.getMinutes());

For a useful JavaScript library for working with dates (it extends the native Date object), check out Datejs. 30kb download, under an MIT open source license.

There is also another library, a smaller download (so slightly less functionality) available with the jQuery datePicker plugin - http://code.google.com/p/jqueryjs/source/browse/trunk/plugins/datePicker/v2/demo/date.js, under a dual MIT / GPL license. For more localisations (as well as string and array manipulation), visit http://code.google.com/p/jqueryjs/source/browse/trunk/plugins/methods. Note: jQuery is not required for these libraries to work.

GPL Compatible Licenses

Wed, 23 Jul 2008 16:35:00 +0000

There is a useful diagram on the GNU site that lists what licences are compatible with the GNU GPL: A Quick Guide to GPLv3: New Compatible Licenses, plus a comprehensive list with more detailed compatibility information.

Link: HTML Agility Pack (.NET)

Tue, 22 Jul 2008 16:58:00 +0000

The HTML Agility Pack is an HTML parser for .NET, supporting XPATH and XSLT parsing. Basically the HTML equivalent of XmlDocument.

Example use (from site):

HtmlDocument doc = new HtmlDocument();
doc.Load("file.htm");
foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[@href]")
{
    HtmlAttribute att = link["href"];
    att.Value = FixLink(att);
}
doc.Save("file.htm");

Portable GIMP and fonts

Tue, 15 Jul 2008 16:58:00 +0000

GIMP (GNU Image Manipulation Program), the open source alternative to Photoshop can be downloaded as a portable version. However, due to being portable, the choice of fonts you can use is limited by what is on the operating system and part of the basic GIMP package, so if you use the font tool and choose a font that is not on another system, you may have problems. Thankfully, fonts are easy to copy (you can copy them from the Fonts applet in the control panel by just dragging them to another folder).

To make your fonts available wherever you use GIMP Portable, you just copy them to E:\PortableApps\GIMPPortable\App\gimp\share\gimp\2.0\fonts (where E: is the drive letter of your portable drive). Then you can go on any Windows PC (even without Office or OpenOffice installed) and still use your own fonts (those which you are licensed for).

JSON and JsonML

Mon, 07 Jul 2008 17:15:00 +0000

JSON (JavaScript Object Notation) is a data interchange format for transferring data between disparate systems. Unlike XML (which is also designed for this), it is far simpler and can be processed more easily by client applications (no validation, or other advanced features of XML) and easier to implement (no special parser needed like XML) - JSON: The Fat-Free Alternative to XML. There are examples of JSON messages (and the XML equivalent) on the JSON Example page. You can validate JSON online using JSONLint.

While its name suggests that it is only for programmers using JavaScript, it is useful for other programming languages as well. The JSON site lists implementations and even hosts code for several languages, e.g. JavaScript, C and Java.

JsonML is a way of transporting XML data by representing it in the JSON syntax. As a result, it can be be used for transmitting XHTML markup (represented as JSON rather than XHTML) which can then be added directly to the document (via the DOM, instead of innerHTML). For jQuery developers, there is a plugin for working with JsonML: JSONML Array to DOM - jQuery.ml

An overview of jQuery.browser

Thu, 03 Jul 2008 17:05:00 +0000

Update: jQuery.version should have been jQuery.browser.version. Added Firefox 3.0.1

If you are a user of jQuery, you may be aware of the basic browser sniffer that comes with it. However, it may seem to return the wrong version number for certain browsers (Firefox and Safari in particular). This is because it returns the version number of the rendering engine (i.e. the part of the web browser that determines how a page should look and function). To help simplify things, I have created a table of common user agents and what jQuery returns:

BrowserjQuery.browserjQuery.browser.version
Internet Explorer 6jQuery.browser.msie = true6.0
Internet Explorer 7jQuery.browser.msie = true7.0
Firefox 1.5 (first release)jQuery.browser.mozilla = true1.8 or 1.8.0
Firefox 1.5.0.9jQuery.browser.mozilla = true1.8.0.9
Firefox 2.0 (first release)jQuery.browser.mozilla = true1.8.1
Firefox 2.0.0.9jQuery.browser.mozilla = true1.8.1.9
Firefox 3.0jQuery.browser.mozilla = true1.9
Firefox 3.0.1jQuery.browser.mozilla = true1.9.0.1
Safari 2.0.2jQuery.browser.safari = true416.11 / 416.12
Safari 2.0.4jQuery.browser.safari = true418.x - 419
Safari 3.0.xjQuery.browser.safari = true522+, 522.x, 523.x
Safari 3.1.xjQuery.browser.safari = true525.x, 526+
Opera xjQuery.browser.opera = truex

I have listed Opera as 'Opera x' as the version number 'x' is always returned by jQuery.browser.version (so no extra work is required, unlike Firefox and Safari).

This table is based on information from UserAgentString.com. There is a Firefox 1.5.0.12, but I am unsure of the version number, plus there are Safari versions with a slightly different rendering engine version number (i.e. 2.0.2 is not always 416.11). Basically, with Safari, if the version number returned is less than 418, it is Safari 2 or lower and if it is around 525/526 it is Safari 3.1.

Link: FreeTechBooks.com

Tue, 01 Jul 2008 12:34:00 +0000

FreeTechBooks.com is a site that offers many computing and engineering related text books (topics include Computer Science, Mathematics, Programming etc) available to download for free./p>

Link: IconsPedia

Wed, 25 Jun 2008 10:58:00 +0000

IconsPedia is a site with many icons free for download. Check the license first to see if you can use it for the purpose you want it for (some have conditions - not for commercial use, and/or must attribute (give credit to) the author). You can also upload any icons that you have produced (as long as they are free).

Link: A list of .NET Cheat Sheets

Thu, 19 Jun 2008 11:27:00 +0000

.NET Cheat Sheets includes ".NET Format String Quick Reference", "ASP.NET 2.0 Page Life Cycle & Common Events", "Visual Studio 2005 Built-in Code Snippets (C#)" as well as links to several more.

Tabs without JavaScript

Tue, 17 Jun 2008 22:26:00 +0000

It is possible to implement a tabbing system without needing to use JavaScript. All you need is CSS and standard (X)HTML. The downside is that you won't get styling on the active tab to indicate that it is active.

CSS:

div.tabcontainer {
 width: 500px;
 background: #eee;
 border: 1px solid #000000;
}
ul.tabnav {
 list-style-type: none;
 margin: 0;
 padding: 0;
 width: 100%;
 overflow: hidden;
}

ul.tabnav a {
 display: block;
 width: 100%;
}

ul.tabnav a:hover {
 background: #ccc;
}

ul.tabnav li {
 float: left;
 width: 125px;
 margin: 0;
 padding: 0;
 text-align: center;
}

div.tabcontents {
 height: 290px;
 background: #ccc;
 overflow: hidden;
 border-top: 1px solid #011;
 padding: 3px;
 
}

div.tabcontents div.content {
 float: left;
 width: 100%;
 height: 102%;
 overflow-y: auto;
}

div.tabcontents div.content h2 {
 margin-top: 3px;
}

HTML:

<div class="tabcontainer">
 <ul class="tabnav">
  <li><a href="#tab1">Tab 1</a></li>
  <li><a href="#tab2">Tab 2</a></li>
  <li><a href="#tab3">Tab 3</a></li>
  <li><a href="#tab4">Tab 4</a></li>
 </ul>
 <div class="tabcontents">
  <div class="content" id="tab1">
   <h2>Tab 1</h2>
  </div>
  <div class="content" id="tab2">
   <h2>Tab 2</h2>
  </div>
  <div class="content" id="tab3">
   <h2>Tab 3</h2>
  </div>
  <div class="content" id="tab4">
   <h2>Tab 4</h2>
  </div> 
 </div>
</div>

Demo page

Recursive Directory Listing (PHP)

Fri, 13 Jun 2008 18:07:00 +0000

In PHP, it is possible to get a list of files and folders and save them into an array: PHP: List files in a directory. Building on this, I have added recursion to the dirList function detailed in the aforementioned link:

/**
* Return a list of all files within a directory
*
* @param string $directory The directory to search
* @param bool $recursive Go through child directories as well
* @return array
*/
function dirList($directory, $recursive = true) 
{
 // create an array to hold directory list
 $results = array();

 // create a handler for the directory
 $handler = opendir($directory);

 // keep going until all files in directory have been read
 while (false !== ($file = readdir($handler)))
 {
  // if $file isn't this directory or its parent, 
  // add it to the results array
  if ($file != '.' && $file != '..')
  {
   // if the file is a directory
   // add contents of that directory
   if(is_dir($directory.DIRECTORY_SEPARATOR.$file) && $recursive === true)
   {
    $results[] = array($file => dirList($directory.DIRECTORY_SEPARATOR.$file));
   }
   else
   {
    $results[] = $file;
   }
  }
 }

 // tidy up: close the handler
 closedir($handler);

 // done!
 return $results;

}

Now you can build a list of files/folders generated with dirList:

/**
 * Return an unordered html list of all files within a directory
 *
 * @param string $directory The directory to search
 * @param array $fileTypes Which fileTypes to show. To list all files use htmlDirList("mydir", array("*"))
 * @param bool $recursive Search through child directories as well
 * @param string $listClassName The class name to apply to the <ul>
 * @param function $displayName A function to call on the file to determine how it is displayed (e.g. change _ to space)
 * @return array
 */
function htmlDirList($directory, $fileTypes = null, $recursive = true, $listClassName = null, $displayName = null)
{
 // defaults (if null)
 // restrict by fileTypes
 $fileTypes = (is_null($fileTypes) ? array("doc","rtf","pdf") : $fileTypes);
 // the class name to apply to the <ul>
 $listClassName = (is_null($listClassName) ? "documents" : $listClassName);
 // set a default function for displayName
 $displayName = (is_null($displayName) ? create_function('$fileName,$extension', 'return str_replace("_", " ", $fileName);') : $displayName);
 
 // get list of files / folders
 $list = dirList($directory, $recursive);
 
 // use an array for building up the string
 $results = array();
 // create the list
 $results[] = "<ul class=\"$listClassName\">\n";
 foreach ( $list as $value )
 {
  // is a folder
  if(is_array($value))
  {
   $results[] = "<li class=\"directory\">".$displayName(key($value),"")."\n".htmlDirList($directory.DIRECTORY_SEPARATOR.key($value), $fileTypes, $recursive, $listClassName, $displayName)."</li>\n";
  }
  else
  {
   // the extension is after the last "."
   $extension = strtolower(array_pop(explode(".", $value)));
   // the file name is before the last "."
   $fileName = array_shift(explode(".", $value));
   // continue to next item if not one of the desired file types
   if(!in_array("*", $fileTypes) && !in_array($extension, $fileTypes)) continue;
   // add the list item
   $results[] = "<li class=\"file $extension\"><a href=\"".str_replace("\\", "/", $directory)."/$value\">".$displayName($fileName, $extension)."</a></li>\n";
  }
 }
 $results[] = "\n</ul>";
 
 // return the results as a string
 return implode("", $results);
}

So now you can get create documents within a folder and have a page listing all those documents, all linked to. In your PHP page:

<?php echo htmlDirList("documents") ?>

The generated code is not formatted, but doing so would add further complexity and be of no benefit (apart from readability).

<ul class="documents">
<li class="file doc"><a href="files/File1.doc">File1</a></li>
<li class="file pdf"><a href="files/File_2.pdf">File 2</a></li>
<li class="file rtf"><a href="files/File_3.rtf">File 3</a></li>
<li class="directory">more
<ul class="documents">
<li class="file doc"><a href="files/File4.doc">File4</a></li>
<li class="file pdf"><a href="files/File_5.pdf">File 5</a></li>
<li class="file rtf"><a href="files/File_6.rtf">File 6</a></li>
</ul></li>
</ul>

There are also more options available, e.g. you may want an image listing:

<?php echo htmlDirList("images", array("jpg","gif","png"), true, "images") ?>

Simple JavaScript/CSS gzipping

Fri, 13 Jun 2008 17:02:00 +0000

I'm sure some may already do this, but compressing textual content can save bandwidth but also make it easier to maintain (by just including a php file instead of a CSS or JavaScript one). For example, create a file jquery.php in the same directory as JavaScript files:

<?php
ob_start("ob_gzhandler");
header("Content-Type: text/javascript");
include("jquery-1.2.6.min.js")
?>

Then include it instead of the normal JavaScript file:

<script type="text/javascript" src="/js/jquery.php"></script>

It's simple to maintain and could be improved (for example, some kind of caching). CSS files can also be used:

<?php
ob_start("ob_gzhandler");
header("Content-Type: text/css");
include("styles.css")
?>

Delete all cached thumbnails (thumbs.db on Windows system)

Fri, 06 Jun 2008 16:55:00 +0000

Not web related, but possibly of interest.

thumbs.db is a file that caches the thumbnails of images stored within a folder. There are tools for deleting these files, but they are often through the use of an application to be downloaded or installed. There is an easy way to do this without resorting to that, just by using the command prompt.

del *thumbs.db /s /ah

This will delete all files (and folders) ending in thumbs.db (e.g. myappthumbs.db), so don't run this if you are unsure (or run it in a folder other than C:\). The /ah parameter searches hidden files and folders as well (so you may get access denied on C:\RECYCLER)

Disclaimer: Be very careful with this as a typo could prove disastrous. Do not run this if you are not completely sure and don't have a backup if a mistake is made.

Google now hosting JavaScript libraries (jQuery, Prototype et al)

Wed, 28 May 2008 08:23:00 +0000

Google now offers a service for hosting popular JavaScript libraries, so for any website this is used on the performance will be better (the user may have already downloaded the file on another site and it is cached) and it will reduce the bandwidth your server uses. So far it hosts jQuery, prototype, script.aculo.us, Mootools and Dojo. You can either load it via the Google AJAX API or the <script/> tag. The advantage of using the Google API is that it can be used for Google's services as well (like Maps, RSS/Atom Feeds and Search (Analytics is missing from the list though)).

jQuery Quick Tip: Rollover images with jQuery

Thu, 17 Apr 2008 16:20:00 +0000

Update: Demo page created

There are several sites that show you how to create rollover images with jQuery (just search Google, Ask, A9, Yahoo etc) for "rollover image jquery"), but they do sometimes have more code than needed (like using $(this).attr("src") instead of this.src for determining the image source. Here is another method that does not use jQuery unnecessarily (which may be faster if there are lots of images).

Create two images, for the 'off' state (when mouse is not over it) and the 'on' state (on mouse over). Name them button_off.gif and button_on.jpg (the button bit can be anything, as can the extension (.gif) - the important bit is the _off and _on suffix.

HTML code:

<a id="mylink" href="/go/somewhere/"><img src="/images/button_off.gif" alt="" title="" border="0" width="100" height="30" /></a>

Then in your $(document).ready:

$("#mylink img").hover(
 function()
 {
  this.src = this.src.replace("_off","_on");
 },
 function()
 {
  this.src = this.src.replace("_on","_off");
 }
);

Due to its generic nature, it can be applied to multiple images, e.g. those with a class .rollover set $("img.rollover").hover...

pastebin sites

Mon, 14 Apr 2008 11:09:00 +0000

A pastebin is a site that allows you to share text with other, most commonly source code, but could be anything else as well (like prose or poetry - e.g. you are writing a novel or poem and want to share what you write). They are useful if you do not have a web site to post what you have written and want to share it to get any feedback (like spotting any bugs or spelling mistakes).

They allow you to post without registering or paying and the pastes normally expire after a set period (e.g after a month) so as to reclaim any lost disk space for the host. Source Code highlighting is often a feature of many as well. Some of them offer more than this, like comparison (e.g. diff's), password protection / encryption and notifications (to alert you of new pastes, or replies to pastes - normally through a chat system like IRC). The open nature of them could render them susceptible to spam though.

The following is a list of pastebin's I am aware of. All offer syntax highlighting.

  • pastebin.com - possibly the first site to do this, you can view recent pastes and search them
  • pastebin.ca - more features than pastebin.com: encryption, tags and description
  • nopaste.info - description, name, tab width
  • LodgeIt! - very simple interface, powered by jQuery, reply to pastes, view diff's, remote queries (XML-RPC). You can't see recent pastes or perform a search though (although this probably mitigates spam somewhat)
  • pastie - separate code into sections, mark as private, select a theme when viewing pastes
  • dpaste - associate a title and your name / email

jQuery Quick Tip: Select text on focus

Wed, 27 Feb 2008 14:45:00 +0000

Just a quick tip on how to select all text when focus is given to a textarea or input (only if the value has not changed) .

$("input, textarea").focus(
 function()
 {
  // only select if the text has not changed
  if(this.value == this.defaultValue)
  {
   this.select();
  }
 }
)

ASP.NET: Binding alphabet to dropdown list

Thu, 31 Jan 2008 13:00:00 +0000

Update: Added VB code.

There may be some cases where you want a DropDownList to list all the letters in the alphabet (i.e. A - Z). Rather than add the letter individually (through using <asp:ListItem>) you can create an ArrayList and bind to that.

In your ASPX page:

<asp:DropDownList ID="Letters" DataSource='<%# Alphabet %>' runat="server" />

In your code behind. Create your Alphabet property:

private ArrayList _Alphabet;
protected ArrayList Alphabet
{
 get
 {
  if (_Alphabet == null)
  {
   _Alphabet = new ArrayList();
   for (int i = 65; i < 91; i++)
   {
    _Alphabet.Add(Convert.ToChar(i));
   }
  }
  return _Alphabet;
 }
}
Protected ReadOnly Property Alphabet() As ArrayList
 Get
  If _Alphabet Is Nothing Then
   _Alphabet = New ArrayList()
   For i As Integer = 65 To 91 - 1
    _Alphabet.Add(Convert.ToChar(i))
   Next
  End If
  Return _Alphabet
 End Get
End Property

Bind on Page_Load:

private void Page_Load(object sender, EventArgs e)
{
 if(!Page.IsPostBack)
 {
  DataBind();
 }
}
Public Sub Page_Load() Handles MyBase.Load
 If Not Page.IsPostBack Then
  DataBind()
 End If
End Sub

This will show A - Z (capitals) in the dropdown. For a - z (lower case), change 65 to 97 and 91 to 123 in Alphabet

Adding rounded corners to your web pages

Tue, 08 Jan 2008 17:55:00 +0000

There are several ways of adding rounded corners to your web page. There is a large list of methods found at Rounded Corners - css-discuss, but also a few other ways using JavaScript (some using jQuery):

  • The first (as far as I am aware) jQuery corner plugin (Dave Methvin)
  • An improved version (Mike Alsup) of the above plugin
  • curvyCorners - anti-aliased corners, supporting borders and background images
  • A modified version of curvyCorners made to work with jQuery.
  • The above plugin was rather big and couldn't be packed, so someone else made a futher modification that reduced its size and enabled it to be packed.
  • Cornerz - smooth, anti-aliased corners. Another jQuery plugin. Anti-aliased, but does not support backgrounds.
  • Rounded corners using <canvas>. <canvas> is a way of drawing/manipulating images via scripting (e.g. draw vector images, transformation, compositing, animations etc). There is a tutorial available on how to use it. Firefox 1.5+, Opera 9+, Safari only - excanvas adds support to Internet Explorer.

Implementations are not always heavily tested within different layouts and CSS, so while a preferred one may not work as expected, there should still be a way to add the effect (even if it involves more code).

A very light-weight way to do this would be via CSS 3 (as it supports multiple background images), but sadly only Safari supports this: demo. Could be some way off as the CSS 3 specification isn't finalized (but neither is CSS 2.1), although it is a useful feature that will likely not change (or be removed) and be adopted by newer versions of currently developed browsers (Firefox 3 and IE8 should hopefully have this).

Free Alternatives to Adobe Reader

Tue, 04 Dec 2007 14:51:00 +0000

As the years have gone by, Adobe Reader (formally Adobe Acrobat Reader) has got bigger (version 5.05 is 8.6MB and will probably still handle many PDF's OK, the latest, 8.1.1 is 22.3MB) and invariably slower with each release. Thankfully there are free alternatives, that are both a smaller download and much faster at opening PDF's.

  • SumatraPDF (< 1MB, still in beta, open source)
  • Foxit Reader (around 2MB download)
  • PDF XChange Viewer (13MB, but still smaller than Adobe Reader and supports comments/annotations, filling in forms and exporting text and images)

Alternatively, you could still have Adobe Reader, and use a tool that disables the plugins that slow the startup - e.g. Adobe Reader SpeedUp or PDF SpeedUp (although I haven't tested either of these).

Analyse performance of web pages with YSlow

Mon, 03 Dec 2007 12:20:00 +0000

YSlow is a plugin for Firefox developed by Yahoo that analyses your web pages and reports back on any performance issues (plus gives a grade). There is a performance report (which shows you areas which can be improved), stats (overview of what is loaded, cached/uncached, cookies and number of HTTP requests), components (page, CSS/JS,JPG etc - expiry, if gzip used, response time, ETag and file sizes) and various tools (view all CSS/JavaScript and a JSLint report).

This plugin depends on Firebug.

Form Layout Using CSS

Tue, 27 Nov 2007 17:45:00 +0000

I have created a sample for laying out fields within a fieldset (so that the labels are all lined up) - I use a fieldset as they are handy for grouping related fields together. Nothing too fancy, but it can be used as a basic for something better. Works with Internet Explorer 6 and 7, Firefox 2 and Opera 9.02.

Clearing tempororary files

Tue, 27 Nov 2007 17:29:00 +0000

Being a laptop user, disk space can be an issue and temporary files can be one of the things to clear out to free up some space. There are freeware applications that enable you do do this, but you can just use what is built into Windows to do the same thing. It is run from the command line and is the command rd or rmdir, which basically means 'remove directory'. It can be used to remove directories as well as its sub directories and files, by just typing rd C:\MyFolder\ /s /q (the /s switch is to include sub directories and /q prevents the prompt to remove a directory tree).

At first, I thought that running it on the temporary folders directory would remove it and somehow break windows, but it doesn't. This is because there are files within that directory that are in use, and as a result, it can't be deleted. However, all the files and sub directories that aren't locked are removed, freeing up space. I use a simple batch file that cleans up the temporary folders, which can be set to run as a scheduled task (assuming you have the computer on at the time).

cleanup.cmd

@echo off
rem clean up windows temp directory
rd C:\Windows\Temp\ /s /q
rem clean up users temp directory
rd %temp% /s /q

The advantage of doing it in a batch file is that you can easily add any directories that also have temporary files, for instance, to clean up you Internet Explorer temporary files add in rd "%homepath%\Local Settings\Temporary Internet Files\" /s /q (assuming you haven't moved the location of the temporary internet files folder).

You can also use the Disk Cleanup tool that is built into Windows: Right Click desired drive in 'My Computer', select 'Properties', then click the 'Disk Cleanup' button. This also compresses files that you don't access often, but takes some time.

Sorting Files by Name, Date, FileSize etc (C#)

Fri, 28 Sep 2007 12:25:00 +0000

It is simple to get a list of files in .NET, you simply do:

string folder = "c:\\windows\\";
string[] files = Directory.GetFiles(folder);

This will get all the files in C:\Windows (does not include subdirectories). However, they are sorted by name (A-Z) and there aren't any options in the GetFiles method to return them in any other order. Luckily, the results are returned as an array and they can be sorted with a custom comparer. I have created a FileComparer class that can be used to sort the files (works in both .NET 1.1 and 2.0):

public class FileComparer : IComparer
{
 public enum CompareBy
 {
  Name /* a-z */,
  LastWriteTime /* oldest to newest */,
  CreationTime  /* oldest to newest */,
  LastAccessTime /* oldest to newest */,
  FileSize /* smallest first */
 }
 // default comparison
 int _CompareBy = (int)CompareBy.Name;
 
 public FileComparer()
 {
 }
 
 public FileComparer(CompareBy compareBy)
 {
  _CompareBy = (int)compareBy;
 }
 
 int IComparer.Compare( object x, object y )
 {
  int output = 0;
  FileInfo file1 = new FileInfo(x.ToString());
  FileInfo file2 = new FileInfo(y.ToString());
  switch(_CompareBy)
  {
   case (int)CompareBy.LastWriteTime:
    output = DateTime.Compare(file1.LastWriteTime, file2.LastWriteTime);
    break;
   case (int)CompareBy.CreationTime:
    output = DateTime.Compare(file1.CreationTime, file2.CreationTime);
    break;
   case (int)CompareBy.LastAccessTime:
    output = DateTime.Compare(file1.LastAccessTime, file2.LastAccessTime);
    break;
   case (int)CompareBy.FileSize:
    output = Convert.ToInt32(file1.Length - file2.Length);
    break;
   case (int)CompareBy.Name:
   default:
    output = (new CaseInsensitiveComparer()).Compare( file1.Name, file2.Name );
    break;
  }
  return output;
 }
}

To use it is fairly simple:

string folder = "c:\\windows\\";
string[] files = Directory.GetFiles(folder);
IComparer comp = new FileComparer(FileComparer.CompareBy.FileSize);
Array.Sort(files, comp);
foreach(string file in files)
{
 Console.WriteLine(file);
}

This will output a list of files in the C:\Windows directory, sorted smallest to largest. If you want it the other way round, just call Array.Reverse(files) after the sort.

Google Code uses jQuery

Tue, 18 Sep 2007 16:15:00 +0000

Google Code is now another high profile site that uses jQuery. It is used to show Google Code Blog posts, featured projects and Google Tech Talks on the home page. It doesn't use jQuery's AJAX functionality to get the feeds though.