Always Get Better

Archive for the ‘General Programming’ Category

C#: using Statement

Thursday, May 14th, 2009

One of my absolute favourite statements in C# is the using statement (not to be confused with the using directive, which is what we use to import libraries like System.Web into our projects).

using forces us as programmers to be honest about releasing memory to the CLR. Whenever we use an unmanaged resource like an SQL connection or file IO handler, the garbage collector will eventually eliminate any open streams or connections associated with that resource. However, “eventually” doesn’t cut it when we’re dealing with SQL connections on a production server – we need to make sure the connections are released no later than when we’re done with them.

If you come from the C++ world, you’re probably (hopefully) used to calling delete to deallocate any memory you reserved. You also know that forgetting the delete (or delete [] on arrays) results in a memory leak. You might think of Dispose() as C#’s implementation of the delete statement.


using ( SqlCommand cmd = new SqlCommand( sqlStatement, sqlConnection ) )
{
// Do something
}

using acts as a try…catch…finally block, so if your code fails your object will still be disposed. The using statement keeps everything wrapped into a neat little package so you don’t forget to keep your local variables in scope.

Like I said, this is one of my favourite features in .NET (lock { } is similarly beautiful). You can use the same construct in VB as well.

Prevent Link Rot From Suffocating Your Blog or Web Site

Sunday, May 3rd, 2009
Anchor Chain
Creative Commons License photo credit: chefranden

Link rot occurs when a page linked to from within your web site becomes invalid. Visitors to your site who click on that link will receive a 404 “Not Found” message rather than the quality content they were expecting to find. This matters to you as a web site operator because:

  1. The value of your content is diminished because your well-selected links no longer provide value to your readers
  2. Search engines indexing your site treat the broken links as a sign that your page is out-dated and therefore needs to be relegated to the bottom of their indexes

Fortunately, it’s very easy to deal with link rot. Essentially it boils down to arming yourself with a link validation tool – I recommend Xenu as the best free tool for this purpose – and run it periodically (once a month should suffice for smaller sites). Xenu will point out which links on your site are no longer working and on which pages they can be found so you can take action. The only problem Xenu has is that Wikipedia blocks this application so any links you make to Wikipedia will have to be manually checked (but, you really shouldn’t be linking to Wikipedia anyway, it is not good reference material).

When you find a broken link, you have a few options available:

Fix It

Sometimes website owners change their site’s structure without regard for incoming links. When you operate your own site, try to take all possible steps to prevent this from happening. If you are the victim of this kind of foolishness, you may be able to go to the offending site and find your link’s new path.

Change It

If you have referenced a news article or other topical content, try searching for it on the host site as above. This kind of content is the worst for being removed by its owners when it is no longer current, but often the same content can be found on another news organization’s site. If that’s the case, make the change. The original site won’t benefit from your link, but they don’t deserve to anyway.

Remove It

If your content can be re-written so removing the link doesn’t reduce its usefulness, this can be an option.

Remove the Article

If your post is written in response to content that no longer exists, just delete your post since it isn’t useful anymore. Be sure to protect the validity of any incoming links by checking your site for any internal references to the post. In order to maintain incoming links from other web sites, you may consider writing a brief explanation as to why the content is no longer available and poitning toward some of your newer work.

Credit where credit is due: I thought to write this post because of a prompting from Problogger who featured an article dealing with link checking on blogs this weekend. I found a good number of broken links on my various sites and ended up re-discovering and updating content I hadn’t thought about for some time.

Flex 3: Downloading URL after Clicking on Button

Tuesday, March 3rd, 2009

Suppose you have a button in your Flex program. When the user clicks on your button, they are prompted to choose where they would like to download a file. But… the file never comes:

protected function buttonClick():void
{
var mpRequest:URLRequest = new URLRequest(“soundbyte.mp3″);
var localRef:FileReference = new FileReference();

try
{
// Prompt and downlod file
localRef.download(mpRequest);
}
catch (error:Error)
{
trace(“Unable to download file.”);
}
}

The reason the file never downloads is because as soon as the function completes, it goes out of scope. As far as I know, this has to do with the event model using weak referencing by default when triggered by clicking on the button.

The simplest solution is to simply move the variables outside the button:

protected var mpRequest:URLRequest;
protected var localRef:FileReference;

protected function buttonClick():void
{
mpRequest = new URLRequest(“soundbyte.mp3″);
localRef = new FileReference();

try
{
// Prompt and downlod file
localRef.download(mpRequest);
}
catch (error:Error)
{
trace(“Unable to download file.”);
}
}

Implementing Lazy Load Using a Proxy Class

Saturday, February 28th, 2009

Lazy load is a design pattern wherein an object is not instantiated until the last possible minute. This is very handy when working with lists of items whose contents are expensive to retrieve from the data store.

There are typically three ways of implementing lazy load:
1. Lazy Initialization – The object is set to null and checked/loaded when data is needed
2. Proxy – A proxy class for the object is created using the same interface as the original class; whenever a property is called, the proxy creates the object and returns the correct data
3. Ghost – The class loads only a partial set of its information until more is needed

Example Situation

In my example situation, we handling a catalogue of artists owned by a fictional record label. For each artist, we will store a name, musical genre, web site address, and number of albums.

UML for Artist Class

UML for Artist Class

Let’s pretend we have thousands of artists on our roster, and we need to print a catalogue containing all of their information. Rather than loading all of that data into memory right away and having to wait until that process is done before we can begin printing, it makes more sense to get a list of how many artists will be printed (so our software knows how many pages to print) but to only load the actual information when we are ready to print it.

The solution is to create an ArtistProxy class. ArtistProxy has an _artist variable who is set to null when it is initialized. Whenever we try to access the artist’s name, web site, etc from ArtistProxy, the class creates an Artist (only if not already done) and returns the property from _artist.

Our print function is never aware of ArtistProxy – as far as it is concerned it only ever deals with Artist. We accomplish this by creating an interface – IArtist – which acts as a contract for both ArtistProxy and Artist. If we add more properties to Artist later on, IArtist will keep us honest by forcing us to also update ArtistProxy.

Artist, ArtistProxy, and IArtist UML Diagram

Artist, ArtistProxy, and IArtist UML Diagram

Now that we understand how our classes relate to each other, it’s time to use them in code:

// Our printArtists() function looks something like this.
// Notice how we are unaware whether the artist is
// an actual object, or a whether it is a proxy.
public function printArtists( IArtist [] artistList )
{
foreach ( IArtist artist in artistList )
{
printOneArtist( artist );
}
}

// Implementation of the IArtist interface
public interface IArtist
{
string Name { get; set; }
string Genre { get; set; }
string Website { get; set; }
int getNumberOfAlbums();
}

// Implementation of Artist class
public class Artist : IArtist
{
private int _id;
private string _name;
private string _genre;
private string _website;

public Artist( id )
{
_id = id;
}

public string Name
{
get { return _name; }
set { _name = value; }
}

public string Genre
{
get { return _genre; }
set { _genre = value; }
}

public string Website
{
get { return _website; }
set { _website = value; }
}

public int getNumberOfAlbums()
{
return fictionalDataConnection->getNumberOfAlbums( _id );
}
}

// Implementation of ArtistProxy class
public class ArtistProxy : IArtist
{
private Artist _artist;
private int _id;

public ArtistProxy( id )
{
_artist = null;
_id = id;
}

public string Name
{
get
{
if ( null == _artist ) _artist = new Artist( _id );
return _artist.Name;
}
set
{
if ( null == _artist ) _artist = new Artist( _id );
_artist.Name = value;
}
}

public string Genre
{
get
{
if ( null == _artist ) _artist = new Artist( _id );
return _artist.Genre;
}
set
{
if ( null == _artist ) _artist = new Artist( _id );
_artist.Genre = value;
}
}

public string Website
{
get
{
if ( null == _artist ) _artist = new Artist( _id );
return _artist.Website;
}
set
{
if ( null == _artist ) _artist = new Artist( _id );
_artist.Website = value;
}
}

public int getNumberOfAlbums()
{
if ( null == _artist ) _artist = new Artist( _id );
return _artist.getNumberOfAlbums();
}
}

Of course for the sake of convenience a few things are missing from my example:
1. An actual data source
2. Delegates (presumably one would include a ‘LoadArtist’ delegate so the proxy will be able to pass the actual loading of its artist to the data layer)

Python file upload

Friday, January 2nd, 2009

I recently needed to handle file uploads from a Flash form post using CGI and Python. I made two discoveries:

  1. Python’s CGI library ignores query string variables on POST requests.
  2. After you’ve done it once, working with POST variables whether uploaded files or otherwise is dead simple!

Here is the file I came up with:

#!/usr/bin/python
import cgi, sys, os

UPLOAD_DIR = “/home/user/uploads”

postVars = cgi.FieldStorage()

if postVars.has_key(“myFile”):
fileitem = postVars["myFile"]

# If myFile doesn’t contain a FILE, exit
if not fileitem.file:
return

# Strip file extension
(name,ext) = os.path.splitext( fileitem.filename )

# If a binary file, ensure write flags are binary
if ext == “.jpg” or ext == “.png” or ext == “.gif”:
ioFlag = “wb”
else:
ioFlag = “w”

# Save file data to disk stream
fileObj = file(os.path.join(self.path, fileitem.filename),ioFlag)
while 1:
chunk = fileitem.file.read(100000)
if not chunk: break
fileObj.write(chunk)
fileObj.close()

Bonus points for checking for and creating a new directory to store the uploaded file in, if needed.

Create Directory in Python

Thursday, January 1st, 2009

I needed to learn how to create directories using Python and found this great resource (digression: check out this author’s page headers – way cool!)

Although I didn’t really add anything new to the code, I ended up creating the following commented function which I share here in case it helps more users to understand.

# If directory (path) doesn’t exist, create it
def createPath(path):
if not os.path.isdir(path):
os.mkdir(path)

# Example of Windows file path
createPath( “C:\\Python\\myNewDirectory” )

# Example of Linux file path
createPath( “/home/username/myNewDirectory” )

Apple is Having Babies

Monday, December 1st, 2008

We rented Baby Mama this weekend. I was happily surprised to find PC Guy in the role of the fertility doctor – perhaps a nod to Mac Guy’s film appearances. It warms my heart to see those references transitioning into the cultural lexicon. All this got me thinking about Apple’s “Get a Mac” campaign; there have been some funny ads circulating around the net lately, including some Flash videos seemingly spreading between ad spots (how do they do that?).

The newest byte is that due to a shortage of trained developers, talented programmers can earn $125-$200 per hour by developing iPhone applications.  Unbelievable!  Where is my old iBook when I need it – buried under a stack of music CDs with an old version of OS X that doesn’t support the iPhone SDK.  Maybe the time is right to spring for a new laptop if there is a potential to earn $250,000 by creating a decent marketable application.  Gold rushes like this don’t act long – talk about striking when the iron is hot!


SEO Powered by Platinum SEO from Techblissonline