skip to Main Content

Finds of the Week – March 2, 2008

Programming

C#.NET

.NET Tips & Tricks

  • Did you know you can give threads any names you want (MSDN)? The names are extremely useful when it comes to debugging time:

    Thread names and debugging

  • System.IO.Directory.CreateDirectory will create all directories and subdirectories as specified by the path parameter. No need to write code to create each directory in the chain. Just do this:
    Directory.CreateDirectory(@"c:\MyApp\Env\Dev");
  • System.IO.Path.GetDirectoryName returns the directory name from a fully qualified file name.

Powershell

  • Round-robin game scheduling algorithm in Powershell. By Scott Hanselman. Check out my C# 2.0 algorithm in the comments section.
  • Mitch Denny wrote How To: Host the PowerShell Runtime.
  • Use Powershell array expression syntax @(…) allows you to force a scalar return value to be wrapped in a array, if it’s not already in an array. I learned about this the hard way while trying to figure out while Get-Childitem sometimes returns an array and sometimes a scalar. Bruce Payette wrote more about it here.

Windows Mobile / Pocket PC

  • I needed a way to stream music and other media to my Windows Mobile phone (Samsung SCH-i760) and all the PCs around the house. Orb seems to be the answer. I’ve only had it running for a few days but it seems to be working great. I can stream music and photos (have not tested videos yet) to any PC in the house or anywhere on the net. I can also listen to my entire music library on my i760 phone anytime, anywhere through Verizon Wireless’s unlimited (with a catch… not to exceed 5GB) EDVO connection.

    Orb Mycast

  • I am a Google Mobile guy, but Yahoo! Go for Windows Mobile also looks very cool. I downloaded it to my Samsung SCH-i760 a few days ago. I am still checking it out but here are a few things I like:
    • Nice and responsive interface.
    • Built-in RSS Reader.
    • Street and satellite maps.

      Here are a few screenshots:

      Yahoo! Go

      Yahoo! Go

      Yahoo! Go Weather 

Software and Tools

  • You can configure Notepad++ to always use spaces for tabs/indentation. The option is a little hidden. It’s in Settings/Preferences/MISC, under Tab Setting:

    Notepad++ tab to spaces setting

Something a Little Different

Try/Catch Blocks Can Hurt Performance

Over at Programmers Heaven.com, there’s an interesting article on the potential performance impact of try/catch blocks. The article concluded that the average cost of a try/catch block is essentially nothing (sorry there’s no author information on the post so I couldn’t tell who wrote it), and that .NET/C# programmers should not think twice about using try/catch blocks.

The author is right that a try/catch block has essentially zero cost. However, like most coding performance issues, exceptions and try/catch blocks do not have performance implications until they occur in some type of loop. Something like this will do the job:

Dictionary<int, int> numbers = new Dictionary<int, int>();
Stopwatch w = new Stopwatch();
w.Start();
int notFound = 0;
for (int i = 1; i <= 1000000; i++)
{
    try
    {
        int value = numbers[i];
    }
    catch (KeyNotFoundException)
    {
        notFound++;
    }
}

w.Stop();
Console.WriteLine(notFound);
Console.WriteLine("Elapsed: " + w.ElapsedMilliseconds + ".");

In the block of code above, I am trying to find the number of integers from 1 to 1,000,000 that are not in the numbers dictionary. One way to do it is to try to access the dictionary item by key. Since the Dictionary class will throw a KeyNotFoundException if the key is not found, that’s how I am going to know whether each value is in the dictionary or not.

Well, let’s just see how long that code takes to run. On my virtual PC it took … hold on a sec, it’s till running… still waiting… not quite there yet… finally: 101031 (101 seconds).

If you have any doubt, this is the type of try/catch block or exception handling they advice against. 🙂

The above logic, when implemented correctly without using a try/catch block, took only 10 milliseconds. Yes, that’s not a typo: 10 milliseconds. Oh, only about 10,000 times faster.

Here’s the correct code:

Dictionary<int, int> numbers = new Dictionary<int, int>();

Stopwatch w = new Stopwatch();
w.Start();

int notFound = 0;
for (int i = 1; i <= 1000000; i++)
{
    if (! numbers.ContainsKey(i))
    {
        notFound++;
    }
}

w.Stop();
Console.WriteLine(notFound);
Console.WriteLine("Elapsed: " + w.ElapsedMilliseconds + ".");

So, do consider performance impact when using exceptions and try/catch blocks. Avoid using exception handling to implement normal program flow. Here are some links on exception handling best practices in .NET:

kick it on DotNetKicks.com

Finds of the Week – February 24, 2008

.NET Programming

WCF

Something Different

  • Learning to Smoke. It’s not permitted. It pisses people off. It makes you puke. It confuses you, and it brings clarity. It makes you an outcast, and it helps you meet wonderful strangers. Lessons from a man who did the unthinkable.

Finds of the Week – February 17, 2008

.NET

Software and Tools

  • Looking for a free sharepoint host? You can get a free sharepoint account with 5MB disk space, 5 users from Frontpages Web Hosting Network. Link is here.

Gadgets

  • The HD format war is over. I am waiting for Blu-ray players go go down to the $150 range before I’ll get one.

And Now, Something A Little Different

Put GetOrdinal Method to Good Use

How often do you see DataReader code that looks like this?

using (IDataReader dr = cmd.ExecuteNonQuery())
{
    while (dr.Read())
    {
        int orderId = dr.GetInt32(0);
        string customerId = dr.GetString(1);
        int employeeId = dr.GetInt32(2);
        DateTime orderDate = dr.GetDateTime(3);
        double freight = dr.GetDouble(4);

        // do stuff
    }

    dr.Close();
}

If that looks like your code, you are not alone :-). Try searching codesearch.google.com for the following:

lang:c# (reader|dr)\.GetInt32\(

codesearch google

With the above code, anytime the order of columns in the SQL statement or stored procedure changes, the code is broken. And if you have lots of columns to read from, it’s a real nightmare to maintain the indexes.

The next time you write another DataReader loop, consider doing it this way instead:

using (IDataReader dr = cmd.ExecuteNonQuery())
{
    int ORDER_ID = dr.GetOrdinal("OrderID");
    int CUSTOMER_ID = dr.GetOrdinal("CustomerID");
    int EMPLOYEE_ID = dr.GetOrdinal("EmployeeID");
    int ORDER_DATE = dr.GetOrdinal("OrderDate");
    int FREIGHT = dr.GetDecimal("Freight");

    while (dr.Read())
    {
        int orderId = dr.GetInt32(ORDER_ID);
        string customerId = dr.GetString(CUSTOMER_ID);
        int employeeId = dr.GetInt32(EMPLOYEE_ID);
        DateTime orderDate = dr.GetDateTime(ORDER_DATE);
        double freight = dr.GetDouble(FREIGHT);

        // do stuff
    }

    dr.Close();
}

Using GetOrdinal makes the code much more readable and maintainable. You are calling GetOrdinal just once for each column, any performance penalty is insignificant compared to the benefits. Be careful not to put the GetOrdinal code inside the while block as that will unnecessarily slow you down (about 3% according to this article).

kick it on DotNetKicks.com

Finds of the Week – February 3, 2007

.NET

Software/Tools

Windows Mobile – Pocket PC

  • Looks like Google has fixed the problems that were plaguing Gmail IMAP on Windows Mobile devices. Read the blog entry from the official Gmail Blog here. And here’s a related article from PC World: Google fixes Gmail IMAP problem on Windows Mobile.
  • Viigo is a free RSS reader for Windows Mobile. I have not really used it that much but it seems to work ok.

    Viigo RSS Reader for Windows Mobile 

  • Skyfire is another promising Windows Mobile browser currently in private beta. Via Engadget.

  • If you have a Samsung Windows Mobile device, try the included PicSel browser. Here’s a review of Picsel browser, with a lot of useful how-to information included. By Tam Hanna.

And Now, For Something A Little Different

Nano

Finds of the Week – January 27, 2008

.NET Programming, C#

Powershell

Software and Tools

Windows Mobile / Pocket PC

Something Different

Finds of the Week – January 20, 2008

.NET, C#, Programming

Software and Tools

  • Jeff Atwood shared the Top Five Browser Shortcuts Everyone Should Know. I didn’t know about the middle mouse button browser shortcut. Very useful.
  • Reading Nazmul Idris’ post on Microsoft OneNote 2007 prompted me to try it myself…. and I loved it. It’s a great application to keep track of notes, journal entries, work logs, etc. It’s going to be an essential app for me from now on.

    OneNote 

    I especially like offline mode support for USB flash drives. You can keep your Notebooks on a flash memory card. OneNote automatically synchronizes its local cache with the flash card when the card is inserted. When not inserted, you can still work on the local cached copy.

    What I don’t like: no VBA macro support. One of the first thing I tried was pressing ALT+F11 to bring up the VBA IDE… nothing happened. A quick search in Online Help confirmed my sinking feeling: no VBA support. Supposedly, you can write add-ins.

Windows Mobile/Pocket PC

Gadgets

Something different

  • Watch dolphins blowing circles made of air bubbles.

Finds of the Week – December 13, 2008

.NET, C#, Programming

Software & Tools

  • Cpu-z is a cool little freeware application that provides information about your CPU. Here we are looking my brand new quad-core CPU.

    Cpu-z

  • Service Pack 1 Release Candidate for Windows Vista is available for public download. Maybe I’ll install it.
  • If you need a folder/file comparison/diff tool, try the SourceGear’s DiffMerge, now free. Via WebLog of Ken Cox.
  • Windows Vista has a very useful but hidden Copy as Path feature (Via Luke Foust). In Windows XP, the Send To X Powertoy used to provide this feature.

    Windows Vista Copy as Path

And Now, Something Different

  • I enjoy doing graphics design now and then. Here’s a cover I did this past weekend for the Richmond Vietnamese Association’s annual Tet (lunar new year) magazine issue (click image for full-size):

    image description

Back To Top