Thursday, October 28, 2004

Threading in C#

I am hella excited. I am going to attend my first Oklahoma City .NET Users Group meeting on Monday.

Paul Ballard is going to be giving a talk on .NET multi-threading. My last project
was severely multi-threaded, but that was C++/MFC so I thought I would write a small multi-threaded C# program to get a little bit of background.

My last project involved reading data from piece of hardware. These values were floating point values that tended to bounce a bit. I have done very little C#, so I thought I would write a multi-threaded program that would simulate the variance in these values. I figured it would introduce me to random number generation as well as threading, and I am sure I will need random numbers at some point. I am not going to offer much commentary, but here is the code:



using System;
using System.Threading;

namespace CSThreads
{
class Class1
{
// Flag to tell data provider
// thread how long to run
public static bool isRunning;

// The data point of interest
public static double dataPoint;

// Sync's access to the data
// point
public static Mutex myMutex;

[STAThread]
static void Main(string[] args)
{
// Set running flag
isRunning = true;

// Init Mutex
myMutex = new Mutex();

dataPoint = 100.0;

// Data providing thread
Thread myThread = new Thread(
new ThreadStart(
ThreadProc));

// Start the data providing
// thread
myThread.Start();

// Read data from other thread
for (int i = 0; i < 20; ++i)
{
// Wait a bit
Thread.Sleep(500);

// Wait to access resource
// until it is safe
myMutex.WaitOne();

// Retrieve the value
// of interest
double currentValue
= dataPoint;

// Unlock resource
myMutex.ReleaseMutex();

// Give the output
Console.WriteLine("The value
of the data point is
{0}",
currentValue.ToString());
}

// Tell data providing thread
// to terminate
isRunning = false;
}

static void ThreadProc()
{
// Use the number of the beast
// as the initial seed
int i = 43;

// Do until the other
// thread tells us not to
while (isRunning)
{
// Initialize Random object,
// increase seed for variety
Random r = new Random(i++);
// Wait to access resource
// until it is safe
myMutex.WaitOne();

// Generate a random number
// between 95.0 and 105.0
dataPoint = (double)r.Next(
-5000, 5000)/1000.0
+ 100.0;

// Unlock the resource
myMutex.ReleaseMutex();

// Wait a bit
Thread.Sleep(500);
}
}
}
}

Getting Started Blogging for Free

Hi, kids!

For some strange reason, not all of my friends who have access to a thing called the Internet have blogs. This post is an attempt to rectify this horrible travesty.

Blog Definition

To begin, let's define what a blog is. From whatis.com, a blog is defined as:

On the Internet, a blog (short for weblog) is a personal journal that is frequently updated and intended for general public consumption.


Blog Benefits

I have some things that I publicly want to rant about from time to time. Well, blogging is great tool for such moments. It is more socially acceptable than than accosting fellow passengers on public transportation with insane diatribes about asparagus or the Red Sox. Plus, people don't have physical access to you to beat you up when they don't like your opinions.

Blogging has also improved communication between my remote friends and me. Most people have to answer some typical boilerplate type questions in a personal email. Blogs will allow you to answer them only once. It is a great way to keep friends and family up to date with what you are doing. You can tell all your loved ones about last night's bender at the cock fights in one fell swoop. That's the beauty of technology people!

Blogging can help you professionally, even if your blog is a bit off color. (i.e. Rory Blyth) Rory's blog has some great technical content, but he also writes about random personal experiences, weird dreams, world events, and whatever else. Rumor has it his blog was very instrumental getting him his new job at Microsoft.

Reading Blogs

Here are some resources for getting started reading blogs:

  • Feedster - A good search engine for RSS feeds, although the bastards haven't found me yet.
  • SharpReader - A great, free RSS aggregator.

    (Siren noises) Acronym police! I have used the acronym RSS a couple of times without defining it. RSS stands for Really Simple Syndication. You subscribe to an RSS feed for a blog or website that you are interested in reading. An RSS aggregator will give you automatic notifications when new content is available. This is was cooler than manually checking a friend's blog for new content only to be disappointed because your friend is being a lazy blogger. RSS also makes it monumentally easier to keep up with a large number of blogs. You could be the next Robert Scoble.


Writing Your Blog

There are any number of places to get free blogs (if you don't believe me, Google free blogs), but personally I use Blogger (until I spring for my own domain so I can put up more types of media).

But using a web form to enter information sucks. So get w.bloggar, a free tool that makes it easier to update your blog.

So get a blog, post a comment, and leave me a link. Blogging, more popular than open marriages on Friendster!

Wednesday, October 27, 2004

Finished. - Tips for Young/New Software Developers

I finished my first project at work today.

After almost two and half years, I locked the SourceSafe database. After three distinct ulcers, after 154,806 lines of C++, I am finally finished.

...and it feels great.

This was my first project right out of college. The project started out with me working on it by myself for about a year and eventually growing into a five developer effort.

I ended up:
  • Designing the majority of the architecture
  • Maintaining the project web pages
  • Serving as the SourceSafe administrator
  • Updating about 2/3 of the user documentation (and directing the updating of the other third)
  • Jointly developing the test strategy
  • Writing over half of the final code
  • Writing the installer
  • Doing the all graphics and a good chunk of the HTML for the help files
  • Writing a few other utilities along the way


Needless to say, I learned a quantity scientists would call "a shitload".

Here are some of the things I have learned:

  • When you think you are being productive by copying and pasting code, you are setting yourself up for ulcers and carpal tunnel. Stop what you are doing, and improve your design.

    Most experienced software engineers will think this is a no-brainer. But as a green optimistic developer, you think, "this code won't change, and I am not sure where a good spot would be for common code". It will change. It will change more than once. You will pay the price.

  • The resource editor in Visual Studio .NET 2002 is buggy and does not integrate well with Visual SourceSafe.

    The applications in our project had large dialog-based user interfaces. The static controls would randomly shrink and truncate the text they were supposed to display. The menu ID's would randomly revert to the the numeric value rather than symbol defined in the resource.h file.

    The other developers and I had multiple instances of making a change to the .rc file only to be prompted to check it out when you went to save it. When you checked it out, you had the two joyous options of either losing your changes or losing every change that occurred between the version in your working directory and the version you were about to check out.

  • The MSI is a hassle to deal with.

    I feel bad for the developers that wrote installers for earlier versions of windows. I was shocked to find out how convoluted the installation process was after taking installers for granted as a user for so many years. I think Microsoft is really getting it right with technologies like ClickOnce and No Touch Deployment.

  • Consistently formatted code is more valuable than you think.

    I read an article on this, and unfortunately I can't remember how I stumbled across it. How I wish I could post a link... Let me summarize, the author talked about an experiment where some psychologist or sociologist abandoned a car on the side of the freeway in a well populated area. The car was not particularly nice, but didn't look like a total clunker either. The car sat untouched for days. They picked the car up, drove it to a comparable area, broke out a window, and watched. The car was stripped within hours. The same kind of thing can happen to your code. We had several relatively simple, but poorly formatted sections of code that seemed to get buggier and buggier every time someone modified it. If your code is poorly formatted, it looks like a careless mess no matter how elegant the semantics of the code are. Psychologically, this will have an effect on your team members, and often times they will not be as careful when working with a piece of code like this.

    In hindsight, I would like to have had a beautifier that could take a coding standard definition and run on any checked out files as a pre-build step. I think it would have saved me and the rest of the team many a headache.

  • If you are planning on putting synchronous I/O in a user interface thread, think again. If it still seems like a good idea, think about several more times.

    The four applications in my team's project were serial I/O intensive. You can often get away with limited file I/O in UI threads, but reconsider doing anything else. In the earlier incarnates of the applications, they did the serial I/O in the UI thread. This brought the UI to a crawl. Like most new computer science graduates, I had done threading in school, found it difficult and intimidating, and the assignments I had been given in school did very little to indicate when a new thread was necessary. As far as not putting I/O in a UI thread, I would think this would be pretty obvious to an experienced developer, but the configuration management tool the organization I contract for uses has major TCP/IP I/O (not to mention our Nazi anti-virus software aggressively scanning all data as it comes in) going on in its UI thread. It starves the message pump for the UI from getting serviced and makes Windows think that the application is not responding. I have heard many of my co-workers complain they can't check in or out multiple files without making the application lock up, when in fact, they just need to wait it out. My other piece of advice would be to prefer asynchronous I/O to spawning a new thread for the I/O unless you can really justify it.

  • If you are in a position were you have any management duties (whether you are paid like it or not), prefer written instructions and guidelines to verbal ones.

    I think this had several benefits. There were certain times when I would give verbal guidelines on particular tasks, and when the tasks were "completed", I often found my instructions were half-followed/not followed. I was in a position where I knew what needed to be done and it seemed obvious to me, but it wasn't to other developers. This brought me much frustration. At times, I remember thinking, these other developers were going home at night and (they all had kids of various ages) it occurred to me that I bet they all had accused their kids at some point of not listening. Initially, I wished I could tell their kids "Well, your dad doesn't listen at work, so it is probably genetic". After the brief moment of internally venting, I realized that continuing to handle the other developers this way was not going to contribute to the success of our project, and ultimately would not reflect well on me. After deciding to give more written instructions, it occurred to me that there were times when I probably overloaded them with information and expected them to just "get it" more often than I should have.

    On the other hand, I am still not convinced every time was my fault (in a way). There were a few times were I thought a developer didn't follow my instructions to the "T" out of laziness. Well, we all get lazy now and then, and after all, Larry Wall said laziness is an important characteristic of a good developer (along with hubris and impatience). Let me get tangental a bit and say I am not criticizing any other developer that I worked with. I am merely stating that they are humans, and must be dealt with as such. I consider myself very enthusiastic about software development, but my motivation is not a constant, although I like to think it consistently high. But giving your developers written instructions allows them to refer back to the instructions, and it gives you traceability if you need to call a developer on not following instructions. The written (or typed, or printed) word carries more weight than the spoken. If your written instructions are in a informal format, add that you are available for clarification. If your instructions are in a formal document, either make it clear that you are available for clarification, or if you have a small enough team, check in with your developers after they have had adequate time to digest the instructions and offer clarification then. After all, we are all human, and we rarely get things right the first time.

  • Prefer to leverage existing tools to "rolling your own".

    If a developer's tool might exist for a task you need to do, for God's sake, search high and low for it. If one does exist, try like Hell to make it work even if it means tweaking the way you work a little bit. Think about it. If a tool has been sold to a fair number of developers and gotten halfway decent reviews, it is going to take you a long time to write a similar tool and get it to the level of stability as the existing tool. In most cases, the time you spend configuring that tool to work in your environment will be miniscule compared to the time it will take you to write a tool that caters to your environment, especially when "scope creep" or changing requirements come into play.

    I had written fairly sizeable serial communication library that was absolutely worthless outside of our applications. Then we found out that several of our users' managers had purchased laptops without serial ports and our code needed to accommodate users with USB to serial adapters. Greenleaf to the rescue! We hadn't really begun testing on other OSes at the time, but things I read later indicated that opening a serial port in an OS-agnostic way is non-trivial. The greenleaf serial communication library made it one line of code. Had we implemented code to deal with USB to serial adapters, it would have been all for naught. Sure, we had to write wrappers around greenleaf to preserve the established interface, but that was not near as time-consuming or discouraging as the alternative would have been.

  • Understand any code your project is dependent upon as much as necessary.

    For this project, we used MFC because we needed to be able to write a native application that targeted everything from Windows 95A to Windows XP SP 2. I have heard Carl Franklin make the statement that he wouldn't use any code wizard/generator that produced code he didn't understand. I dare to disagree, but Carl would be the first to admit that there is no development guideline that doesn't have an appropriate place to be broken. I think it all depends upon the size and scope of your application, and maybe to a certain extent, the age and reputation of the tool in question. Well, to understand the code that MFC generates in your application, you really have to read source for a good portion of the library. We certainly got burned a few times in situations that Carl was talking about--where the generated code acts subtly different than how you think it does. On the other hand, after getting more experience with MFC, we were able to assume more accurately and saved a significant amount of time by not reading MFC source to realize "hey, it does exactly what I thought it did". I know people dis MFC a lot, but that is neither here nor there, and I still think it was the best choice of technologies for the project requirements, even if it did make deployment more complicated.



Summary

I certainly admit this post is a bit scattered, and I am probably not saying anything new. But if it helps one other developer, its existence is justified. As far as being scattered, a young developer with such diverse responsibilities on his or her first project is going to learn important things on a wide variety of aspects of software development. I am glad this post is that way. It is not all about the code, people.

Looking at all this stuff I learned from I screwed up, I feel like I need to have a post outlining what I did right on the project.

Furthermore, I am not an expert on anything, so any comments offering valid counter-arguments are appreciated.

In closing, as Chris Sells would say, think deeply, code well.

Tuesday, October 26, 2004

Unfocused Update

I have been trying to come up with some interesting tech kind of post, but it just hasn't happened yet. But it has also been awhile since I posted, so I wanted to prove I am not lazy. Oh, wait, I am lazy.

I have been thinking about getting a new mobile phone like Scoble's. I think my current contract is up because my provider just sent me some promo for a new phone and contract. My current provider, Cingular, doesn't seem to offer a single SmartPhone.

I have been trying to break my unconventional typing habits and become a true touch typist. Being patronized by Mavis Beacon when you are already frustrated and feeling inadequate is enough to make you want commit suicide by headbutting your monitor repeatedly until the sparks fly.

I have been getting more into the podcasting thing lately. Oh yeah, maybe that will get my blog more hits. Podcasting, podcasting, podcasting! I am kind of shocked about all the naysaying about this technology. Rory Blyth had an entertaining piece defending podcasting's worth. My favorite part is the utter disregard for tact.

Saturday, October 23, 2004

Brush with Greatness 2: Electric Bugaloo

On Friday I was hanging out in the dotnetrocks chat room on efnet as I often do during the live show. The chatters were graced with the presence of Robert Scoble, Microsoft employee, the foremost authority on blogs, probably the world's most voracious blog reader (2200+), and from what I could tell, all around cool guy. A lot of people were responding to everything he said, so he kind of had to choose who he wanted to respond to. For a couple of minutes, that person was me. I thought that was hella cool. He told me story about urging Bill Gates to make a certain business decision about the future of Microsoft when he was in the process of getting hired.

I felt pretty cool about getting to chat with him. Then, my over-active analytical skills went to work and I began accusing myself of being a celebrity worshipper. After a brief period of self-deprecation, I realized that he has direct conversations with Bill Gates, Bill Gates runs Microsoft, and Microsoft is a significant player in determining relevant aspects of modern and future society. I am allowing myself to tard out over this a little. It is not like I was getting excited about chatting with someone like Jay Lenno or Julia Roberts. That would be pathetic...

Thursday, October 21, 2004

Okay, I would like to rant about bugzilla if i may. Here is a tool that is a hella good defect tracking tool. It seems like they strived (or is it stroved?) to a make a good, free, cross-platform bug tracking tool (All of which I am a fan of). But then the email notification totally depends on sendmail being installed in /usr/lib. Now sendmail is a mean, stupid, hard-headed animal. That is why they call it "Nature's president". If you get that reference, you are as big of a Mr. Show junkie as me. I have been cutting my teeth for the last few days trying to write a wrapper for sendmail for Lotus Notes. I would blame my current failure to do this on inadequate documentation for ::CreateProcess. CreateProcess takes LPCTSTR as a parameter for the command line to start this process. I have a diagnostics log that prints my command line parameter. I can paste that parameter from my log into a command line window and it works. Yet everytime bugzilla calls my wrapper program, I get GetLastErrorer() == 3 --> The path cannot be found. Anyone that can solve this issue will either make me feel like a retard or win eternal cool points, or maybe both.

Keystroke Shortcut Nerds Unite!

I don't know how many other people are in the same situation, but my workstation at work (and by workstation, I mean cubicle desk, keyboard tray, etc.) is a lot more comfortable using the keyboard than it is the mouse. Lately, I have been feeling the pain of early or mild carpal tunnel syndrome in my right wrist. This is particularly bad timing, because I am going through a lot of downtown at work waiting for other people to finish things. In my downtime, I have been trying to learn more about technologies I don't know so much about: COM, .NET, C#, ASP.NET, RSS to name a few. Since I am not made of money and company isn't going to buy books that may or may not be applicable to my next project, I have been reading technical documents on the web like a mad man. When every move and click of the mouse hurts early in day and becomes excruciating in the afternoon, you start to realize there are some improvements that could be made to make web browsing more friendly to keyboard only users. Here are some of the changes I would like to see:

  • HTML expanded so that links on pages can have shortcut keys - Let's face it, navigating links with Tab and Shift+Tab sucks. This could be a tough one. There are two big issues:

    1. Finding shortcut keys that won't collide with browser and OS shortcuts - My solution would be to use Like ALT+Windows KEY+letters and/or CTRL+Windows+letters. The drawbacks are that this puts more burden on web developers, and the windows key isn't always present. For Mac Users, it is never present, but hey, if you are Mac user, you always use the mouse anyway. And my response to the windows key not always being present is "GET WITH THE TIMES". Implementing this wouldn't be taking away functionality that the "windows-keyless" crowd has now, it would just be providing more functionality to those of us how have purchased a new keyboard since the Windows 95 era.
    2. Providing feedback to the user notifying her of the shortcut keys for each link - From a formatting/aestethic point of view, I don't think this is something that should be displayed all the time next to each link in parenthesis or something. Maybe pressing ALT+windows or CTRL+windows could pop up tooltips for each of the links that were visible in the client area. Maybe even the browser could determine the shortcut key so HTML designers wouldn't have the burden.

  • Extended right click menu accessibility via keystrokes - I would like to have a shortcut key to access right click menus of icons in my system tray and quick start menu.
  • Launching items from my quick start menu via keystrokes

I am sure there are probably others, but my wrist hurts so I am stopping here. If any of these features are available and I am just ignorant about them, feel free to lambaste/enlighten me.

This post was created with no use of the mouse whatsoever.

Tuesday, October 19, 2004

So work is officially under way on Charlie's and my "Top Double-Secret Hopefully Makes Us an Ass Load of Money" software project after discussing it for the past few days. Not much done so far, just a list of use cases we'll need for the project. I doubt the list is exhaustive, but it is a start. And it is a little bit further than I have gotten than several other software project I have dreamt about over the past few years. I am not going to give much detail about it, but when I random blurted out the need for this type of software, a very smart guy commented, "That would be cool". The smart guy in question tends to think more things are lame than cool, as do I, so I thought his semi-endorsement would good enough for a go ahead. That and it is excuse for me to write some real C#, learn ASP.NET, and maybe learn some other things along the way that will make me revered by geeks everywhere.

My homie Gus posted a great bit on his blog, and I feel I have a mildly entertaining reply to. It sucks getting older. Gus needs to tell his helluva talented writer of a girlfriend to quit being a lazy blogger to write more because her old stuff is hella entertaining.

Sunday, October 17, 2004

I don't generally sleep well. I am often bothered by dreams that are so disturbing or nonsensical that I would be way too uncomfortable to share them. But the other night, I had a dream that was entertaining and strange, but not so strange to earn me a spot on the government's super secret list of people to monitor because they are like bad and stuff. So here it goes...

While I am a moderately successful software engineer, my dream had me returning back to my high school job of concourse boy at the bowling alley. I was still the same age as I am now, so my opting to do this made little sense. The bowlers had changed since my stint there during high school. The bowlers were fatter, drunker, and angrier than I had remembered. Even though it was not part of my responsibility when I had the job in real life, apparently now I had to deliver food from the snack bar the the fat, drunk, angry bowlers. My first task was to deliver an eight foot long sub, which had been conveniently cut into two four foot sections, to a fat, drunk, angry bowler. I had somehow gotten some of the condiments of the sub on my hand, and I felt that was too un-hygenic, despite the fact that the fat, drunk, angry bowler probably should not have expected much in the way of cleanliness when ordering food from a bowling alley. I could find no napkins, no paper towels, nothing to get me out of my predicament. Panic set in. Suddenly, the owner's wife appeared. She told me I had a phone call, and I could take it her office. The sub magically disappeared from my hands. This is typical in my dreams as I have no patience for a segue when my focus has shifted. I pick up the phone and obviously the caller was Arnold Swarzenegger. He asked me why I had given him a bad review on his performance as California's governor. I was confused. Then I seemed to remember that I had earlier read an article on slashdot the stated Arnold was personally calling people who gave him bad reviews on an online survey he had setup. Slashdot had links to the survey, and I figured I would give him a bad review and see if he would call. I mean, if it has been posted on slashdot, surely he could no longer personally deal with of the bad reviews. So when he asks me, I completely froze up. All I kind think about was all the time I had spent as a kid watching Commando with my mom. I muttered out some half assed excuse about being very critical of all politicians and I was in a bad mood and I wasn't really even familiar with much of what he had done as governor. I am not sure where the dream went next. I think I woke up soon. My dreams don't ever really seem to climax, and apparently my blog posts don't either.



Thursday, October 14, 2004

Brush with greatness

A Verl Cool Thing® happened to me the other day. I bought Bob Reselman's book Coding Slave from Amazon. Initially, I tried to order from his site, but it did not accept Discover, and I had recently left my debt card/life line in an ATM that was kind of to destroy my card when I got distracted and forgot to retrieve it. So I get to the select payment method and Discover is not an option, so I back out and order from Amazon. A few days later, I got an email from Bob Reselman. Here is our exchange in reverse chronological order.


----------------------
Cool!

Maybe you can spread the word?

Bob

-----Original Message-----
From: James Barnett [mailto:XXXXXXX@XXXXXX.XXX]
Sent: Monday, October 11, 2004 12:29 PM
To: Bob Reselman (Coding Slave)
Subject: Re: Your Coding Slave Order

Bob,

I did not complete the transaction because
your site did not accept Discover Card.
I purchased Coding Slave via amazon.com.
I enjoyed it thoroughly. Great
work.

James Barnett

--- "Bob Reselman (Coding Slave)"
wrote:

> Hi James:
>
>
>
> I have an order here, in your name,
> dated 10/3/2004, for a copy of Coding
> Slave.
>
>
>
> Yet, I do not find an associated
> payment for the order in my bank's
> credit card report.
>
>
>
> Tell me please, do you have a
> transaction receipt?

>
> If so, will you please give me
> the transaction number so that
> I may give my bank a good
> talking to?
>
>
> Thanks,
>
> Bob
>
>

---------------------------------


Pretty cool, eh? Well, it is for a dork like me. I also had quip in the chatroom during the last .NET Rocks live show that Rory Blyth felt was worth repeating on the air. That's pretty cool, too, except for the fact that there is now permanent evidence that I sometimes have nothing better to do than to listen to people talk about programming on a Friday night. Yes, I am living la vida loca, something something, color Mocha, yada yada, wanna choke her, etc., etc,...

I am doing the questions for the 2004 Semi-Annual One-Time-Only Neopoleon.com "Get Your Grubby Little Hands On a Copy of VS.NET 2003 Special Edition" Contest. The first one question was easy. The second was marginally tedious, but I feel like I should have been able to guess the answer after reading some of Rory's blog posts.

Tuesday, October 12, 2004

An update not worthy of a title

So, I got back from B's wedding yesterday. His wedding was cool. Although I generally abhor ceremonies of any type (I didn't even go to my own college graduation), I actually enjoyed everything except the hideous process of getting to the Hilton in Santa Rosa, CA from the comfort of my ghettoed-out, pseudo-leather couch in Crackerville, I mean Mustang, OK. I got to see some good friends there, namely the brothers Thomas, aside from B. The drive back to the airport was an adventure. I had a crappy Cavalier that was the ever manly color I would call "late 70's sparkly motorcycle helmet blue". Punching the gas in that piece of crap was less impressive than rolling up the windows in my BMW. I also think I passed through a toll in one of those express lanes for people who have the special account. But I didn't get arrested or miss my flight, so it was a small victory.

Gus wrote and wished my a happy belated birthday. Much appreciated. He told me he started blogging, too, but didn't give me a link. Expect a link here soon. He's a good guy with interesting viewpoints on many things.

Friday, October 08, 2004

Happy day of birth to me

Yesterday was my birthday. Yippeee skipeee. Here are some other things you might not know about October 7th:


Gosh, with all of that going for October 7th, you think it would have been tough to have a crappy birthday. I guess I am always up for a challenge. Big ups to Susan for making my birthday a little brighter.