April 2005 Entries

Watch "The Corporation"

The Corporation I know I'm late to the game, but since I rely on Netflix, I'm always watching movies long after the general population has seen them. However, we just finished watching the documentary "The Corporation" and I couldn't recommend it more if you haven't seen it already.

Even if you're a tried and true Capitalist (like I am), it's worth watching as it does a pretty good job of raising questions about how we define wealth and corporate responsibility among other things.

It certainly provides insight into the question of whether corporations should act purely on self interest. Corporations should definitely be responsible to their shareholders, but perhaps also to their stake holders. If a corporation is owned by people in the U.S., but pollutes the air in Chile, it's being responsible to its share holders, but what about the stake holders?

In the end, I think the big take away from the documentary is that for corporations to be truly responsible to shareholders, they must redefine what it means to provide "value" to shareholders. Value is more than immediate cash profit. Value is also provided via sustainability. Clean air is valuable. Clean water is value.

A second take away is that when our news agencies are in the pockets of big corporations, how will people get the truth so they can make more rational decisions about policy regarding the environment and corporations? That's a real disheartening topic.

Well not one to underestimate human nature, it leaves me with the big question of how do you make it profitable for companies to be sustainable? That's certainly one way to enact change. But it has to be done in such a way that it is inherently profitable to be sustainable. Enacting policies might just make corporations leave U.S. soil. One approach is to wait till the environment has been plundered so much that there's no other way. I'd prefer we not wait so long.

Too funny to pass up. President Bush Pays Tribute to John Lennon.

This is too funny to pass up. Apparently some remixers have sliced and diced Bush's snippets of Dubya speaking into a song that's a mix of John Lennon's Imagine and Lou Reed's Walk on the Wild Side.

Take a listen [mp3].

Using Embedded Resources for Client Script Blocks in ASP.NET

A while ago Patrick Cauldwell highlighted a wonderful technique of using embedded resources for unit testing with external files.

Fully on board with Pat, I’ve applied that technique to client script blocks when building web controls and ASP.NET pages.

How often have you written (or had to deal with) crap like this.

string script = "<script language=\"javascript\">"
  + "function SomeFunction(someParam)" + Environment.NewLine
  + "{" + Environment.NewLine
  + "    alert(’Man, this sucks!’);" + Environment.NewLine
  + "}" + Environment.NewLine
  + "</script>";

A preferred approach is to have your client script code in a separate file. For web controls, I generally have a folder named Resources that contains a folder named Scripts. I’ll add my client script files there as embedded resources. In figure 1 below, you can see that I have two script files in my project.

Embedded Scripts
Figure 1 Script files.

To make sure these files are compiled as embedded resources, I select the files and set the build action to embedded resource in the Properties window as in figure 2.

Embedded Resource
Figure 2 Build Action = Embedded Resource.

Now when I need to display these scripts in a page, I can use the following code which makes use of my handy dandy ScriptHelper class.

if(!Page.IsClientScriptBlockRegistered("PairedDropDownHandler"))
{
  string script = ScriptHelper.UnpackScript("PairedDropDown.js");
  Page.RegisterClientScriptBlock("PairedDropDownHandler", script);
}

The contents of my embedded script files do not contain the <script> tags. I leave that responsibility to my ScriptHelper class so that these script files can be used as stand alone script files as well. The code for my script helper class is below.

/// <summary>
/// Utility class for extracting embedded scripts.
/// </summary>
/// <remarks>
/// Uses a naming convention. All scripts should be placed 
/// in the Resources\Scripts folder. The scriptName is just 
/// the filename of the script.
/// </remarks>
public static class ScriptHelper
{
  /// <summary>
  /// Returns the contents of the embedded script as
  /// a stringwrapped with the start / end script tags.
  /// </summary>
  /// <param name="scriptName">FileName of the script.</param>
  /// <returns>Contents of the script.</returns>
  public static string UnpackScript(string scriptName)
  {
    string language = "javascript";
    string extension = Path.GetExtension(scriptName);
  
    if(0 == string.Compare(extension, ".vbs", true
      , CultureInfo.InvariantCulture))
    {
      language = "vbscript";
    }
        
    return UnpackScript(scriptName, language);
  }

  public static string UnpackScript(string scriptName, string scriptLanguage)
  {
    return "<script language=\"Javascript\">"
      + Environment.NewLine
      + UnpackEmbeddedResourceToString("Resources.Scripts." + scriptName)
      + Environment.NewLine
      + "</script>";
  }
 
  // Unpacks the embedded resource to string.
  static string UnpackEmbeddedResourceToString(string resourceName)
  {
    Assembly executingAssembly = Assembly.GetExecutingAssembly();
    Stream resourceStream = executingAssembly
      .GetManifestResourceStream(typeof(ScriptHelper), resourceName);
    using(StreamReader reader = new StreamReader(resourceStream, Encoding.ASCII))
    {
      return reader.ReadToEnd();
    }
  }
}

You’ll be seeing this ScriptHelper class again when I highlight some controls you might find useful. If you’re already using ASP.NET 2.0 (aka Whidbey), there’s an even better way to handle client files.

UPDATE: I just realized I was using code from a StringHelper class I wrote. I updated that bit to inline the simple functionality.

Technorati tags:

AdSense relevance...

Orange Chicken In my comments, Barry winces at the relevance of some Ad Sense ads he sees.

For the most part, I've been quite impressed by AdSense relevancy. For a while now, I've had nice colorful Family Guy ads on my home page. When I wrote about my Orange Chicken incident, a commenter pointed out that I hilariously had ads for Orange Chicken on my blog.

But ad-sense can backfire as well. I had one post where I was critical of the Republican party and I noticed that Google was showing ads seeking fund raisers for the GOP. I laughed out loud and figured, hey, that's a good way to keep my blog balanced. Everytime I criticize the Republican party, my ads will balance that by advertising for them. I'll criticize the ineffective Democrats as well so that this post gets ads for Libertarians or the Green party.

UPDATE: Looks like Rory's noticing how eerily relevant AdSense can be.

Give Readers a Choice on RSS Ads

Well I didn't get much of an on topic response to my question of whether readers would be bothered by ads in an RSS feed, but I did get into a nice chat about hosting at home verse with a service. Apparently Robb Allen has enough computers at home to supply a third-world country. Think about it Robb? They can really use it. ;)

But it appears that a general backlash is brewing against the idea. It's the battle between the Utopian view of RSS and market pressures. Personally, if a feed is interesting enough to me, I'd be happy to tolerate ads as long as the ads weren't too distracting or garish. For small fries like me, it's a nice way to supplement the income, especially as one who has recently made the jump to be independent.

Having said that, it's almost always a bad move to alienate readers (unless your taking a principled stance on an important issue you believe in). The best choice (for me at least) is to offer a choice (paper or plastic?). I'll probably keep my main feed ad free, but add a separate (but equal) rss feed that would contain an occasional ad. At that point I'll cajole, grovel, and beg subscribers to switch to the feed with ads to help a brotha out.

New Plants for the Office

This past weekend Akumi and I headed over to the downtown flower mart to purchase some plants. We came home with a couple money trees and some bamboo for my office.

Bamboo

There's something about Bamboo that is very soothing for me. Sometimes if I look at it long enough, I can swear that the leaves are moving gracefully, twisting upwards.

[Listening to: Undo - Björk - Vespertine (5:38)]

Google AdSense in RSS Ineffective?

As you've probably heard, Google is testing AdSense within RSS on a single site.

I love the idea of being able to include a Google AdSense ad within my RSS feed and watching the money roll in. At least in theory. Once ads proliferate in RSS feeds, ad-blockers within RSS aggregators will proliferate. Just look at this prototyped ad-blocker for RSS Bandit that Torsten developed.

Another issue that comes to mind is that the audience for web ads is not the same audience for rss feeds. I have a theory that those who find my site via a Google search are more likely to click on an ad than someone who is subscribed to my RSS feed?

Why is that? It boils down to the fact that a subscriber via RSS isn't likely to be in the middle of a search for a particular piece of information while reading my blog as would a Google user. Rather, I suspect that he or she is a friend or a geek wondering if I'll finally be inspired someday to write something worthwhile because I once wrote something interesting enough some time ago that encouraged this person to add me to his or her aggregator and now only inertia keeps this person from unsubscribing. But I digress.

Unfortunately, I don't have any hard (or even soft) numbers to back this claim up because I don't have ads in my RSS feed. Recently I was linked to on Scoble's link blog which jumped up the number of aggregator views, while my web views remained constant. Likewise, my tiny advertising revenue for that day stayed constant as would be expected because those who read my blog via an aggregator aren't likely to take their time to look at the actual site and click on an ad. I'd love to know what the effect would have been had my feed included an ad.

When I post something that users find via Google, my web views jump as does my advertising revenue, which makes perfect sense. I'll be watching with interest to see how Google's experiment with Longhorn blogs does and if they end up rolling it out to everyone. I'll certainly experiment with it to see if my conjecture is correct unless I get a backlash from commenters saying they'd rather not see it in personal blogs. Thoughts?

As for my advertising revenue in case you were wondering, I'm strictly a small fry, though I do make more than enough to pay for hosting.

[Listening to: 3-2-1 Fire! - Fat Boy Slim - Fatboy Slim: Live On Brighton Beach (4:34)]

Should Corporations Act Purely on Self Interest?

I saw this post on Don Park's blog...

My perspective on this latest hot topic is that I think companies should act only in interest of itself, the Microsoft shareholders in this case, and not anyone else, including its employees. So I think the discussion should have been about whether leaders of Microsoft made the right decision in the interest of its shareholders.

I don't understand this mode of thinking. Should people in general act purely on self interest and not for the common good? Why should corporations be any different? After all, they are made up of people, both shareholders and employees. It seems not all companies agree as Boeing, Nike, Coors, HP, and others supported the bill.

I suppose Microsoft would have continued to support the bill if it was rewritten to state that gays are not protected under anti-discrimination laws to own stocks in major corporations. Oh then you'd see some major rallying around gay rights.

I understand that having a corporation get behind a political cause is a touchy situation. Whose values do you support? Your employees? Your shareholders? America at large? But it's clear that this bill supports values Microsoft already holds dear. Microsoft has in the past supported this bill and has shown itself to be progressive in its own policies.

And Ballmer's worry of discriminating against anti-gay bigots is a real piece of work. Here's a snippet.

What message does the company taking a position send to its employees who have strongly-held beliefs on the opposite side of the issue?

As Shelley eloquently points out, this bill doesn't deny rights to others. And the message would have already been sent by the fact that Microsoft's own policies are reflected in this bill. So if you're worried about the bigots feelings Mr. Ballmer, are you going to change your policies to reflect that as well?

We've all seen what acting purely on corporate self-interest produces. Oh, Enron springs to mind, sweat shops, destruction of the environment, and countless other examples. Corporations have all the rights of a person without many of the implicit responsibilities. Corporations are members of the community. It's time they start acting like it.

Matching HTML With Regular Expressions Redux

UPDATE: Mea culpa! Maurice pointed out that (except for the casing) my original expression WAS correct. I only needed the RegexOptions.SingleLine option. I didn't need to add the (\s|\n) everywhere. Here's a corrected post. Thanks Maurice!

Last time I talked about matching HTML with regular expressions, I published a regular expression with a couple small bugs. The first bug was not my fault, but rather the fault of the rich text editor that comes with .TEXT. It was being overly “helpful” when I tried to edit the post and uppercased some of the code. As you know, “\S” is much different than “\s” to a regular expression.

The second bug is entirely my fault and I write this as a confession and to provide a fix. You see, I assumed (and you know what happens when we assume) that complete tags tend to be on a single line. Well that's not the always the case. You might encounter something ugly like this:

<div     id = "blah" alt=" man
this is ugly html "
> fire this guy... </div>

The expression I had posted wouldn't have matched the div tag sitting in plain sight there so I went in there and corrected that sucker all by itself. It requires using the RegexOptions.SingleLine option so that the . character matches \n. Here's the expression reprinted (with correct casing) for your reference.

</?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)/?>

The main difference is now I'm including \n anywhere I'm matching whitespace (via \s). In order for this to work, you need to use the RegexOption SingleLine. Here's a code snippet that uses this expression to match the above html.

string html = "<div\n\tid=\"blah\" alt=\" man\n"

    + "\tthis is ugly html \"\n"

    + "\t>"

    + "fire this guy...\n"

    + "</div>";

 

Regex regex = new Regex(@"</?\w+((\s+\w+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>", RegexOptions.Singleline);

 

MatchCollection matches = regex.Matches(html);

Console.WriteLine(".....Original Html......");

Console.WriteLine(html + Environment.NewLine);

Console.WriteLine(".....Each Tag......");

foreach(Match match in matches)

{

    Console.WriteLine("TAG: " + match.Value.Replace("\n", " "));

}

This produces the output:

.....Original Html......
<div
id="blah" alt=" man
this is ugly html "
>fire this guy...
</div>

.....Each Tag......
TAG: <div id="blah" alt=" man this is ugly html " >
TAG: </div>

So sorry about that. Hope this one treats you better.

It's the Little Touches - Trillian and MSN Messenger.

Yesterday I wrote about a neat Trillian feature that highlights words with their Wikipedia definition.

Today Dimitri told me via MSN Messenger that I caused him to buy some music online. While I was out for a walk, I had left my iTunes playing. I'm using the new 7.0 version of MSN Messenger which allows you to automatically publish what you are currently playing as your status message. Apparently something I was listening to (as I have fantastic taste in music) caught his attention enough that he clicked on the song and bought it.

You have to love these small details that make software more interesting to use. Trillian's wikipedia integration puts knowledge at your fingertips (to use a much bandied about Microsoft phrase), while Messenger connects us via the universal language of music. I love checking Messenger to see what people are playing at any given moment.

So Dare (currently playing something by, whoelse?, 50 cent), much kudos to you and your team on the latest messenger as well as for helping unleash the inner consumer whore within each of us. :)

[Listening to: Athena - Tiësto - Parade of the Athletes (6:17)]

So There Was a Real Hattori Hanzo

Hattori Hanzo A while ago I wrote about Seppuku, Katanas, and Samurai and made a joking reference to Hattori Hanzo.

In my comments someone named Lazken notes that a Hattori Hanzo did exist, but he did not make swords. You can read about Hanzo in the samurai archives.

Lazken goes on to say that we watch too many Kill Bill movies. Umm... dude... there's only two of them. ;)

Trillian Wikipedia Integration

I'm chatting with my buddy Micah who will ask me a question and then annoyingly answer it himself immediately after. For example, he asked me how FireFox picks up an icon from web pages. I replied that there's a favicon protocol but that I didn't know the details. He then proceeded to explain how to format the link tag properly.

Apparently the latest version of Trillian will highlight words with links to their definition in Wikipedia. So as you chat with your friends, you become a living breathing dictionary. That's a rather nice feature for IM conversations.

Pensamiento de Cancun (Thinking About Cancun)

CancunPlanning a vacation is proving to be a challenge now that I'm independent. Last year, Akumi and I decided that we were going to England for two weeks this April. Well April has come and is about to go, and we're no closer to Jolly old England (and Old Trafford).

With my project ramping up, I just don't think we can do two weeks of vacation in a row. Of course, this isn't really fair to my wife as I'm still going to Burning Man at the end of August. We need a shorter vacation for the two of us, so I thought of our good neighbors next door. Mexico!

Having surveyed her Mexican expatriate coworkers, my wife reported that they unanimously declare Cancun as the place to go. Armed with that information, we nearly jumped on an all-inclusive deal that would have us flying out of Los Angeles this Saturday. But good sense (or something resembling it) took hold and we stopped ourselves (for the moment).

I'm skeptical of all-inclusive deals because of the simple fact that once they have you there, they don't have much incentive to step up the quality of food. Imagine travelling all the way to Mexico for bad Mexican food. ¡Aye Carumba!

So now we're looking at November as a good time to enjoy the turquoise beaches of Cancun and Tulum. However, if you've been there and had a great time (or not), I'd love to hear about it. ¡Muchas Gracias!

[Listening to: Dreaming (Percussion Mix) "Vamos a Jugar en el Sol!" - Ruff Driverz Pres. Arrola - Trance: A State of Altered Consciousness (5:25)]

4/20. Where'd Your Coworker Go Around 4 PM?

In some circles, today's a very special day. And 4:20 today is a special time for this special day. If your coworker has a serious need to take a smoke break around 4 o'clock today and comes back with a lot of munchies, you know what's up.

DataGrid With a Title Row

One thing I've found annoying at times with the DataGrid control is there's no way to specify a title to be displayed above the headers. Being lazy, I often resorted to adding a label above the data grid followed by a br tag.

But no longer! I wanted to have the title display in its own row within the data grid structure so I created a custom data grid control that does just that. See the example below for how it renders.

This is the Title
Column 1 Column 2 Column 3
See Spot Run
Run Spot Run!
Flee the Maniacs

The key to this is to override the OnItemCreated method and set my own rendering method for the header item.

/// <summary>

/// Assigns our own render method for the header item.

/// </summary>

/// <param name="e"> E. </param>

protected override void OnItemCreated(DataGridItemEventArgs e)

{

    if (ListItemType.Header == e.Item.ItemType && Title != null && Title.Length > 0)

    {

        e.Item.SetRenderMethodDelegate( new RenderMethod(RenderTitle));

    }

    else

    {

        base .OnItemCreated(e);

    }

}

When ASP.NET is ready to render the Header, it'll call my method instead which is named RenderTitle.

/// <summary>

/// Renders the title as its own row.

/// </summary>

/// <param name="writer"> Writer. </param>

/// <param name="ctl"> CTL. </param>

protected virtual void RenderTitle(HtmlTextWriter writer, Control ctl)

{

    // TR is on the stack writer's stack at this point...

    writer.AddAttribute("colspan", this .Columns.Count.ToString(CultureInfo.InvariantCulture));

    writer.AddAttribute("align", "center");

   

    writer.RenderBeginTag("TD");

    writer.Write(Title);

    writer.RenderEndTag(); // Writes </TD>

    writer.RenderEndTag(); // Writes </TR>

 

    // Now we add the header attributes we

    // copied.

    this .HeaderStyle.AddAttributesToRender(writer);

 

    writer.RenderBeginTag("TR");

 

    //Render the cells for the header row.

    foreach (Control control in ctl.Controls)

    {

        control.RenderControl(writer);

    }

 

    // We don't need to write the </TR>.

    // The grid will do that for us.

}

The snippet shown here will style the title row the same as the header style. In my actual control, I defined a property named TitleCssClass to enable you to define your own Css class to use to style the title row. This required me to do a bit of hacking so that the HeaderStyle gets removed from the render stack and then gets added back later when rendering the Header row. If that makes no sense, you'll see what I mean. I've put the code for the control here.

Google Ads as Blog Decoration

Since I mentioned that the Family Guy was no longer cancelled on my blog, I've noticed that Google Ad Sense has been displaying a Family Guy banner ad on my homepage.

Family Guy In case it is gone by the time you read this, the image at left is a snippet from the full banner ad. It's colorful and looks rather nice at the top of my blog.

Now I agree that it's a bad idea to try to game the google AdSense system for profit, but what about gaming the system for pure fun? For example, coaxing the Google Ad-Sense system to display the most interesting (or offensive) ad possible.

Well I won't condone such behavior lest I'm removed from the program. I will merely mention the idea.

Community Server Licensing vs .TEXT

Before you upgrade to Community Server, be aware that they've turned it into a commercial product. Yes, there is a non-commercial license available, but it requires you to display the following image at the bottom of every page.

CS EULA I have no problem giving credit where credit's due, but this is in stark contrast to the BSD license employed by .TEXT and you should be aware of this if you plan to upgrade to CS.

For example, competitors to Telligent would probably want to purchase the commerical license rather than have to prominently display their logo on your blog.

In any case, I'll probably stick with .TEXT and start looking into what it will take to switch to DasBlog. I think I prefer the more focused approach DasBlog takes.

Community Server Fix for Posting Comments from Feed Readers and a Rant for Good Measure

Jayson Knight has been cutting his teeth on the latest version of .TEXT now called Community Server trying to get it's RSS and CommentAPI support to work.

Thankfully he posts his fix here for others to use.

I'm pretty sure he'd agree with me that given the chance, he wouldn't have upgraded to Community Server so soon after its release. To be fair, it's an ambitious release intending to integrate Forums, Blogs, and Photo Galleries all in one package. But for me personally, and I'd guess for a lot of .TEXT users, this wasn't a necessary feature. Especially not at the cost of having existing features break.

It seems to me that the Telligent guys have released this puppy a bit too early. It's really bothersome how much the RSS and commenting features regressed in this release. It's not a case of simply introducing a bug that accidentally disables a feature, but instead appears to be a case of dropping the code for existing functionality. Who, besides the ever patient beta community, tested this?

Installation is still a tricky beast with this software as I've had difficulty getting it up on my development machine. Understand that I was able to get .TEXT installed and CS is supposed to have simplified the installation process. As many of you know, installing .TEXT is a trip to the dentist without N2O.

The reason I had chosen .TEXT in the first place was for its SQL Server support, and its the primary reason I'll stick with it as running ad-hoc reports against my blog is quite convenient. I've considered DasBlog, but probably won't switch until someone (or myself) writes a SQL provider.

One thing I like about DasBlog is that it's focused on being a good blog engine. I think its that focus that will keep it very tight and without the annoyances of CS. So far, CS is a big disappointment.

Where Do These Bruises Come From?

Elbow Yesterday Akumi pointed at my elbow in shock and asked me what happened.

"What happened to what?" I replied?

"You're elbow. It's badly bruised."

Sure enough my entire elbow is covered in a dark shade of reddish purple. "Huh. How about that. I have no idea." I did go to a party the night before, but I'm pretty sure I managed to stay on my feet the entire night. I don't remember getting injured during soccer. It just showed up.

I'll be sure to install a web-cam in the bedroom tonight. I have a sneaking suspicion that Akumi beats me while I sleep. If she does, it's probably well deserved as I've been known to elbow her in the head while we sleep from time to time.... Hmmm. I better check her head.

The Collapse of Boolean Logic

What will this code write to the console?

public void SomeMethod()

{

    SqlInt32 x = 1;

 

    if(x == SqlInt32.Null)

    {

        Console.WriteLine("Null.");

    }

    else if(x != SqlInt32.Null)

    {

        Console.WriteLine("Not Null.");

    }

    else

    {

        Console.WriteLine("Neither? WTF!?");

    }

}

If you said "Neither? WTF!?" then you'd be correct.

Doesn't that seem odd since x is either SqlInt32.Null or it isn't? Is this a case of fuzzy logic? Well not exactly. This is one of those gotchas with operator overloading. The == operator is overloaded by SqlInt32 to return a SqlBoolean instead of a boolean.

This caused me a few minutes of pain this week as I was stepping through code like this and examining the values in the debugger and I thought perhaps someone had slipped me a very strong hallucinogen because there I was with a value that was not null, but was null at the same time. It was one of those mind warping "This sentence is not true" moments.

As typical, I was thinking about rebooting when on a whim I decided to use intermediate variables and realized that the == was returning something neither true nor false. Honestly, I think this is a very poor and unnecessary use of operator overloading (correct me if I'm wrong) because it hides a real gotcha underneath a very common paradigm. If you overload the == operator, you should most definitely return a bool.

In this case, it's easy enough to fix. I should have been checking the IsNull property anyways like so:

public void SomeMethod()

{

    SqlInt32 x = 1;

 

    if(x.IsNull)

    {

        Console.WriteLine("Null.");

    }

    else

    {

        Console.WriteLine("Not Null.");

    }

}

This post by Cyrus motivated me to write about this.

When Drinking Flaming Shots

...be sure not to spill...(animated gif)

Image removed. Download from here.

Misspelling Might Be Your Friend

Looking through my statistics today and I noticed that I received a lot of hits from this post about Google Maps using satellite photography.

Looking in my referrer logs, I noticed that most of the visits were rolling off of Google form users who were searching for the term "Google Satelite". I just happened to be the fourth search result on the page.

"Cool" I thought to myself, "but they're all misspelling "satellite". Then it occurred to me that they weren't the only ones who were spelling challenged. I had inadvertently misspelled "satellite" in the title of my post.

I'm probably dredging up yesterday's news here, but it occurred to me that one could really get great search results for hot search words by misspelling them in ways that people commonly misspell them. This is the same thinking behind someone who tries to register "amazn.com" or "micrsoft.com" hoping that millions of typos will send users their way.

So if you want to be THE blog about "onomatopoeia", start writing about your love of "onomatopeia" or "onomatopoea". That'll create some buzz.

I'll have to figure out a way to register "hacked.com".

RSS Bandit v1.3.0.29 Released

This is a bug fix release. Check out Dare's list of fixes to find out more.

The installer is located here.

Threading Tips: Never Lock a Value Type. Never Lock "This".

UPDATE: As a commenter pointed out, the original code example did not properly demonstrate the problem with locking on the this keyword within a normal method. I have corrected this example and wrote a better example that demonstrates that this problem still exists even in a “normal” method.

Take a look at this code:

private bool isDisposed = false;
 
//... code...
~MyClass()
{
    lock(isDisposed)
    {
        if(!isDisposed)
        {
            //Do Stuff...
        }
    }
}

Hopefully you can see the problem here right away. The lock statement takes an object instance as a parameter. So what happens to the boolean isDisposed within the lock statement? That’s right! It gets boxed, meaning a new object instance is allocated and passed to the lock statement. Thus every time you lock on a value type, you’re locking on a new object.

Ok, so let’s try to fix this up a bit.

private bool isDisposed = false;
 
//... code...
~MyClass()
{
    lock(this)
    {
        if(!isDisposed)
        {
            //Do Stuff...
        }
    }
}

So is there anything wrong with this? You’ve probably seen the Microsoft examples locking on this. Well never give full trust to example code (especially as it’s unlikely you’ll add the code to the GAC) ;). Suppose this snippet is from a class MyClass. What do you think will happen with the following code:

MyClass instance = new MyClass();

Monitor.Enter(instance);
instance = null;

GC.Collect();
GC.WaitForPendingFinalizers();

You guessed it! Deadlock.

Every time you lock a .NET object, the runtime associates a SyncBlock structure to that object. Locking works by checking who owns an object’s SyncBlock when attempting to acquire a lock. Thus in the code sample above, the client code and the Dispose() Method are attempting to lock on the same object.

For a more in-depth discussion, I highly recommend Jeffrey Richter’s article Safe Thread Synchronization which is where I first learned about this subtle threading issue.

Likewise you might also take a look at Dr Gui’s Don’t Lock Type Objects post.

Technorati Tags: ,

Beware of @@Identity Theft in SQL Server

In T-SQL, you can use the @@IDENTITY keyword to obtain the value of the identity column when you insert a new record. For example, the following query inserts a record into an imaginary table and returns a result set containing the ID of the inserted column.

INSERT INTO SomeTable

    SELECT Value1, Value2

   

SELECT @@IDENTITY -- LAST INSERTED IDENTITY VALUE

There's the potential for a subtle bug here. Suppose later on, a coworker realizes that any time a record is inserted into [SomeTable] a record should also be inserted into the table [SomeTableAudit]. The simplest solution would be to add a trigger to [SomeTable] that inserts a record to [SomeTableAudit]. But in doing so, your coworker introduces a case of @@IDENTITY theft. Your original query will now return the value inserted into the IDENTITY column of the tabel [SomeTableAudit] instead of the IDENTITY value of [SomeTable] as you intended.

At this point some of you are shaking your heads muttering

 

Well I never use Triggers. Triggers are bad umkaaaay.

 

That's beside the point, you never know when someone else is going to apply that trigger resulting in this unintended consequence. It pays to program defensively. The issue here is that although @@IDENTITY is constrained to the current session, it is not constrained to the current scope. Instead, use the SCOPE_IDENTITY() function which will return the last IDENTITY column value inserted in the current scope, in this case the value inserted into [SomeTable].

INSERT INTO SomeTable

    SELECT Value1, Value2

   

SELECT SCOPE_IDENTITY() -- LAST INSERTED IDENTITY VALUE

As an aside, I'm fine with triggers in certain cases. One of the primary complaints about triggers mirrors the complaints about Aspects in AOP. Namely that triggers provide for unintended consequences that aren't visible when examining a stored procedure. However when used sparingly for cross-cutting functionality, I think they can add a lot of benefit. Much like Aspects.

UPDATE: Steven Campbell adds a great tip.

 

Another tip I can offer is that you should not use ADO in combination with SQLOLEDB to retrieve IDENTITY values. I refer specifically to the technique of:
myRS.AddNew
...
myRS.Update
myId = myRS("ID")

This fails to retrieve the correct ID, because (internally) the SQLOLEDB driver issues a SELECT @@IDENTITY statement to retrieve the newly created ID.
Technorati Tags: ,

Family Guy Uncancelled. Long Live Stewie!

Stewie This is old news, but I am so glad that the Family Guy is "uncancelled". It truly is of "The Simpsons" caliber of humor.

The irony of my statement is that we pretty much don't watch TV any more. Instead I look forward to new seasons appearing on DVD (and thus in our Netflix queue). We watched a DVD of old Family Guy episodes last night and I nearly burst a vein from laughing. I'm a very physical laugher.

My favorite character (shown) is the diabolical baby Stewie. He's also the source of my favorite quote in the show so far.

Damn you vile woman, you've impeded my work since the day I escaped your vile womb.

AddressInfo.cs: Converting State Codes to State Names and Vice Versa

I'm feeling a little uninspired to write anything interesting because my hands are hurting from the keyboard pounding I've been doing. Instead, I thought I'd dig up this really simple (and hopefully useful) AddressInfo class for you. The code is extremely basic, but it might save you the hassle of typing all fifty states (and some territories and the District of Columbia) and their two letter postal codes into your own class because I did it for you! Free of charge!

If I save one hand out there, my work here is done. The basic premise is this, the U.S. isn't adding states to the union very often, so it makes sense to have the list of states and state codes as an enumeration rather than a lookup table in the database. Makes it easier to re-use that information not to mention the speed. For example, here's a snippet of one of the StateCode enum available in the class.

public enum StateCode

{

    /// <summary>Alabama</summary>

    AL,

    /// <summary>Alaska</summary>

    AK,

    /// <summary>American Samoa</summary>

    AS,

    //,... Bunch of other states ...,

    /// <summary>Wyoming</summary>

    WY

}

And here's a snippet of the corresponding State enum.

public enum State

{

    /// <summary>AL</summary>

    Alabama,

    /// <summary>AK (Home Sweet Home)</summary>

    Alaska,

    /// <summary>AS</summary>

    American_Samoa,

 

    ///,... Bunch of other states...,

 

    /// <summary>WY</summary>

    Wyoming

}

The main AddressInfo class is used to hold an address, but isn't all that useful nor interesting. The interesting methods are the static methods used to convert from state codes to states and vice versa. Here's a couple examples of how you might use these methods:

// Get the state name based on the state code.

string stateName = AddressInfo.GetState(StateCode.AK);

Console.WriteLine(stateName); // Prints "Alaska"

 

// Get the state name based on the state code string

string stateCodeText = "CA";

StateCode stateCode = AddressInfo.ParseStateCode(stateCodeText);

State state = AddressInfo.Convert(stateCode);

Console.WriteLine(state.ToString()); // Prints "California"

Let me know if you actually find this useful. The class itself can be downloaded here.

[Listening to: Psychedeliasmith / Give Me My Auger Back - Fat Boy Slim - On The Floor At The Boutique (4:21)]

My Brother Visited Last Week

Brian had some sort of conference to attend, so I didn't get to see much of him. But last Thursday he was at Venice Beach so I took a break from my work and drove out there. Soon enough, we got to doing that which all brothers must do when they haven't seen each other in a while.

Brothers at the Beach

Yeah, real nice to see you too!

Putting My Resume Online

I put up an HTML version of my resume on my blog. It has a slight bit more information than my Word resume which I think lends well to the online experience. For a moment I thought about using the Marquee and Blink tags all over and have animated dancing babies, but I don't have the design skills to do that tastefully. I even forgoed adding Google and Amazon ads all over.

Since I'm now an independent consultant, I think it's a good idea to have that sucker online, though I think my blog posts will give the potential client a better sense of my experience and abilities.

If you have suggestions for online resumes, let me know. I've thought about adding even more information in collapsible regions etc... in an effort to make it more “interactive” but I thought better of it. Maybe simplicity is best for now.

Writing For Magazines. Suggestions?

For some reason, I've always wanted to write a book. It started off as a desire to write the next Lord of the Rings classic, but has morphed into writing a reasonably useful technical book.

So after reading Mike Gunderloy's 8 part "Advice for Writers" and Eric Gunnerson's post "So You Want to Write a Computer Book", I've come to the conclusion that it might be better for me to start off with a few print articles.

Ultimately I'd love to contribute an article to Wired (the best damn magazine on Earth...and beyond), but for now, I'm looking at various .NET technical journals and magazines. If you have experience writing for a magazine and have recommendations on publishers who were great to work with, please let me know.

COOL! Google Maps Overlays Satellite Photographs

In case you wanted to see my neighborhood, you can check out this photograph. Then take your mouse and drag it around to see the surrounding area.

Home Sweet Home

Somewhere in there is a haacker.

CSS Question: Two Backgrounds on the Same Element?

As part of my site's redesign, I wanted to keep the drop shadow effect on the left and right borders of my main content area. No problem I naively thought, I'll simply add two background elements to the main div. I named the div "background" like so:

<div id="background">
</div>

And in my style sheet, I tried the following:

#background
{
    background: url(leftBorder.gif) repeat-y left;
    background: url(rightBorder.gif) repeat-y right;
}

Unfortunately this did not work as only one of the background images showed up. What I ended up resorting to was using two nested divs. The inner div would contain the main content and the right border while the outer div would display the left border.

<div id="backgroundLeft">
   <div id="background">
   </div>
</div>

At this point, I needed the two divs to overlap each other just right. The inner div needed to align over the outer div's right edge. On the left side, the inner div needed to expose the outer div's left edge so that the background image would be displayed. Here's the CSS I used.

#backgroundleft
{
    margin: 0px;
    background: url(leftBorder.gif) repeat-y left;
    width: 784px;
}

#background
{
    background: url(rightBorder.gif) repeat-y right;
    margin-right: -11px;
    margin-left: 11px;
    position: relative;
    top: 0px;
    left: 0px;
    padding-top: 3px;
    width: 783px;
}

So my question to you CSS gurus out there (if any), is there a better way for me to accomplish this?

Slight Redesign of Haacked.com

So I spent a bit of time today to "refresh" the look of my site. On the face of it, it's not a dramatic change, but under the hood, I tore out the table driven layout and replaced it with a CSS driven layout.

For you aggregator readers, take a look and let me know what you think?

And if it looks really wack, try a hard refresh (CTRL+F5) because the stylesheet may be cached on your computer. If it still looks wack, try drinking 6 beers in quick succession and let me know how it looks with beer goggles on.

I should also mention it looks better in FireFox than IE.

Reporting Back With 2GB RAM

Ok, I'm in nerdvana. I got my 2 x 1GB PC 3200 DDR 400 cards today and my machine is noticeably snappier today. On a lark, I decided to open every application on my machine just for kicks. Ok, maybe not. But doing DotNetNuke development is no longer a pain for me.

Yeahronimo Releases a Commodore Tablet PC

Yeahronimo, which owns the rights to the Commodore brand announced that they are nearing the release of a Commodore tablet PC called the Commodore 256, simply because that's twice the number of the last Commodore 128.

Microsoft Develops New MS Phone

Phone