CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Darrell Norton's Blog [MVP]

Fill in description here...

December 2004 - Posts

  • 2005 New Years Resolutions

    Here are some of my 2005 resolutions:

    Professional

    • Learn Python – I’m going to start learning a new programming language every year. This year is going to be Python. I’ve already learned a good bit, and I really like Python’s way of working with lists. Expect some posts on that.
    • Post more articles – I have some I’ve already written, and some that I have ideas for. And since that is probably what you read this blog for, I’ll finally start blogging them!
    • Upgrade my MCSE to Windows Server 2003 – I’ve been putting this off since April.
    • Learn more about design patterns – I’m not at the level I would like to be. I’ve got a couple books in mind to help out, as well as constant use at work. I’d also like to reread Patterns of Enterprise Application Architecture.
    • WeProgram.NET – our user group is doing well, and we’re planning some great stuff in 2005!
    • Read at least 12 professional development books – this includes books on .NET, Python, general software development, design patterns, consulting, business, and management.

    Personal

    • Get married and take a nice long honeymoon in Hawaii.
    • Then get a puppy – I want a Labrador Retriever, she wants a Yorkshire Terrier.
    • Spend lots of quality time with family and friends.
    • Read the KJV Study Bible all the way through, preferably every day.
  • Lord of the Rings extended edition DVD set

    Lord of the Rings DVD collectionLast night I peeled the shrink wrap off one of my most highly anticipated Christmas gifts, The Lord of the Rings extended DVD collection. I only got to watch The Fellowship of the Ring, which took long enough considering the extra half-hour of film. I liked the added and extended scenes since they made the movie more continuous, although I can see why they were cut from the movie for time reasons. And I didn't even take a look at the 2 extra DVDs, From Book to Vision and From Vision to Reality. Or the commentary included on the 2 movie DVDs. Sheesh! All I can say is it rocks!

    I'm looking forward to the extra 43 minutes in The Two Towers and 50 minutes in The Return of the King!


  • How to remove search engines from the Firefox search box

    On Windows:

    • Go to C:\Program Files\Mozilla Firefox\searchplugins
    • Each search engine has two files; a .src and either a .png or a .gif file. All you have to do is delete the two files for the search engine you wish to remove (for example google.src and google.gif) and restart Firefox.
  • A Path.Combine method that takes any number of arguments

    Python has a function similar to the .NET Framework’s Path.Combine method, except that Python can take any number of string parameters. I decided to port this to .NET. Here’s the code for a Utils.Path.Combine method that takes a string array of paths and returns the concatenated path:

         1: using System;
         2: using System.Text;
         3: using ioPath = System.IO.Path;
         4:  
         5: namespace Utils
         6: {
         7:     public sealed class Path
         8:     {
         9:         private Path() { }
        10:  
        11:         public static string Combine(params string[] paths) {
        12:             if (paths.Length == 2) return ioPath.Combine( paths[0], paths[1] );
        13:  
        14:             StringBuilder combined = new StringBuilder(50);
        15:             foreach(string path in paths) {
        16:                 if (path == null) throw new ArgumentNullException("path array item");
        17:                 Path.CheckInvalidPathChars(path);
        18:                 if ( path.Length > 0 ) {
        19:                     if (ioPath.IsPathRooted(path)) {
        20:                         combined = new StringBuilder(50).Append(path);
        21:                     }
        22:                     else {
        23:                         char ch1;
        24:                         if (combined.Length > 0) {
        25:                             ch1 = combined[combined.Length - 1];
        26:                         }
        27:                         else {
        28:                             ch1 = path[path.Length - 1];
        29:                         }
        30:                         if (((ch1 != ioPath.DirectorySeparatorChar) && 
        31:                                 (ch1 != ioPath.AltDirectorySeparatorChar)) && 
        32:                                 (ch1 != ioPath.VolumeSeparatorChar)) {
        33:                             combined.Append(ioPath.DirectorySeparatorChar);
        34:                             combined.Append(path);
        35:                         }
        36:                         else {
        37:                             combined.Append(path);
        38:                         }
        39:  
        40:                     }
        41:                 }
        42:             }
        43:             return combined.ToString();
        44:         }
        45:  
        46:         internal static void CheckInvalidPathChars(string path) {
        47:             if (-1 != path.IndexOfAny(System.IO.Path.InvalidPathChars)) {
        48:                 throw new ArgumentException("InvalidPathChars");
        49:             }
        50:         }
        51:     }
        52: }

    You call it like this:

    1: result = Path.Combine( @"C:\ProgramFiles", "someDir", @"anotherDir\", "someFile.txt" );

    I tried to call the Path class's public members as much as possible to improve upgradability to the next version of the .NET Framework. The CheckInvalidPathChars internal method is the same as the System.IO.Path class's method of the same name. I used Reflector to check it out.

    From my performance testing, the built-in Path.Combine performs about 60 nanoseconds faster on two arguments. For three arguments or more, it outperforms the built-in function in an increasing manner. Maybe it's not all that useful, but it was fun to do.

    I did use Test-Driven Development, I just didn't show the code. The majority of the effort was in performance tuning, but the test harness kept the code running as intended.

    Update: Changed lines 33-34 per James Curran's suggestion. I missed the boxing that line would cause. Now the code clearly outperforms the built-in Combine method for any number of paths greater than two.

  • Soople, easier advanced searching using Google

    Not sure how to tap the full power of Google? Advanced operators got you down? Try Soople, the easy search in Google. As a shortcut-loving geek I’ll probably never use it, but it could be good for the average computer user. Soople is not endorsed by Google.

  • Mailinator is down for the year

    Bummer, it looks like my favorite way to avoid spam is down (hopefully not out). From the website:

    MAILINATOR IS --- DOWN !!!

    That's right -- sorry folks, mailinator is down, down, down -- as in "not up".

    It is not accepting emails at all and this is really the only active webpage.

    The good news is that its only temporary. The bad news is, well, I guess you already know that - its down!

    Mailinator gets attacked daily and as you can imagine gets buckets of spam. In addition, its used as a cesspool by many services to dump their junk mail and such. Its been a long battle to fight that stuff but I'm happy to say none of that has smushed it so far. Shutting it down for the rest of 2004 will give the bazillions of servers banging on it a chance to say "hey .. its .. um ... gone". Maybe some of them will go bang elsewhere.

    Consider it a purge if you will. Sorry for the inconvenience. Mailinator WILL be back up the first week or so of 2005.

    See you in 2005!
    Paul

  • Profling .NET applications with nprof

    Recently I had to do some performance profiling for one of our applications that was almost ready for production. Always on the lookout for new tools, I decided to check out what open source profilers were available.

    The best one I found was nprof, the .NET profiler. Download the zip file and extract to a folder on your computer. Following the instructions, I ran the RegisterProfilerHook.bat file to register the hook file. Then I started nprof and was getting work done almost immediately. There is also a file that will register nprof as a Visual Studio add-in. Make sure you close all instances of Visual Studio before running the batch file, a fact I learned the hard way. Then under the Tools menu you should see nprof Profiling. Expand that and click it to turn profiling on. Click again to turn profiling off.

    For this example, I am using an application that John Robbins wrote to illustrate the features of Visual Studio’s new Enterprise Performance Tool in MSDN Magazine’s December 2004 issue. Download the code from that article, install it and compile it before continuing. I also follow the article pretty closely, and end up getting similar results to John Robbins. I highly suggest reading his article because the concepts will be similar, although the new EPT tool will have a lot more functionality than nprof. But you can’t beat free!

    To profile, go to the File menu and select New. The screen looks like this:

     Create Profiler Project UI

    The File radio button lets you select standard windows and console applications to profile. The ASP.NET radio button is for profiling web sites. The Debug profiler hook is supposed to allow you to debug into the application you are profiling, but I haven’t gotten it to work. The Profile started applications option tells nprof whether to profile any applications your application starts (such as a windows form application starting Excel). If you are using the Visual Studio add-in, you won’t need to setup this screen at all unless you want to change the default options.

    For this, click the browse button next to “Application to run” and navigate to the AnimatedAlgorithm.exe file. Then click the “Create Project” button. You know have an unsaved profiling project. You can save it if you expect to reuse it. In fact you should save it because proper performance profiling goes through a process of profiling, make a code change, and then profile again to see if the change improved performance or not. So save the project as AnimatedAlgorithmProfile and click save. Your screen should now look like this:

    Blank nprof UI

    The File menu is standard stuff, so let’s skip to the Project menu. Currently the only options we have are to Start a project run and Options. Clicking the options menu item takes you back to the Create Profiler Project dialog we saw earlier.

    Select Start project run or press F5 to start profiling. If everything is setup properly, the Animated Algorithm Display form should launch. Everything that you do to the application will be recorded by nprof for performance data. Click the Sort button with “Bidirectional Bubble Sort” selected in the dropdown list. Watch the pretty display. When it’s done, close the Animated Algorithms form. Nprof will now crunch through the data, which may take a little bit of time depending on the speed of your computer and how much data was gathered during profiling.

    Now nprof should look similar to this:

    Profile results UI

    The first thing to notice is that nprof groups the profiling data based on which thread the code ran on. Unfortunately there is no combined view to see everything from all threads, but the feature may make it into a future version. It’s not necessary, just nice to have.

    Now take a look at main window underneath “Filter signatures”. The Signature column is the method signature that was called. You will probably recognize most of these, as they are mostly calls to the .NET Framework. If your app is relatively performant, it is expected that most of the time be taken up with system calls.

    The “# of Calls” column is just that, the total number of calls to that method. Clicking on the column header sorts the data by that column’s value, and clicking again reverses the sort.

    The next column is the “% of Total” column, which shows how long the application spent in that method as a percentage of the total profiled run time. If you sort by this column and you’re on the first thread (which it should be by default), you’ll notice that the biggest number is only like 0.05 or so. What gives? Well, the main thread isn’t doing that much work compared to the other threads. Click on one of the other threads to see higher numbers.

    Making sure that the percent of total column is sorted descending (with higher numbers at the top), find the thread that has the application Main. The signature will be “static voic AnimatedAlgorithm.AnimatedAlgorithmForm::Main()”. Notice that it is called once and the percent of time in the method should be close to 98 or 99%. One might think this is where we should start our performance analysis, but hold on!

    The next column, “% in Method”, shows the percentage of the time the program actually spent in the method. On my computer that number is zero. If the time spent in the method is 0%, and the total percent is 99%, then the percentage spent in called methods must also be 99%. And that is exactly what the next column, “% in Children”, tells us. So that means any performance efforts will not happen in this method. The final column, “% Suspended”, shows how much time the method was waiting for something to happen not in a called method. If the suspended percentage is much above 0.1%, it is probably worth checking out to see why.

    Click the “% in Method” column to sort by which methods actually ran the longest. If you’re on the right thread, the RunMessageLoopInner should be the highest, which is perfectly fine. What we need to do is see what code (if any) that John Robbins wrote or that is included in the NSort assembly is slow.

    Fortunately nprof provides a handy namespace treeview on the left below the thread tree. Uncheck the System and Microsoft namespaces. Now you’ll notice that while the RunMessageLoopInner is still on top, the Wintellect.SortDisplayGraph.SorterGraph::UpdateSingleFixedElement is the next highest with 1.03%. The next method after that only has 0.12%. At least now we are to code that we can change to improve the application. Alternatively, you can uncheck the All Namespaces node and then check the Wintellect, NSort, and AnimatedAlgorithm namespaces. This finally gets rid of that pesky RunMessageLoopInner.

    Looking at the results, we can see that the UpdateSingleFixedElement is the best looking candidate for performance improvement on this thread. Clicking up to the second thread, the Wintellect.SortDisplayGraph.GraphSwapper::Swap method is the highest with 1.59%, and the next method with a mere 0.12%. On the first thread there is nothing over 0.05% anyway, so it’s not even worth looking at, unless you are really obsessed.

    If you select a method signature, the callees and callers will be filled in. The callees are those methods that the selected method calls. The data includes how much time is spent in each of the called methods. The callers are the methods that make a call to the selected method. You can click on methods in the callee/caller tabs and it will select that method in the main method signature area, which will then show you the callees and callers of that method.

    Now we have at least two good candidate methods to look at to improve performance. I’m not going to go any further until John Robbins posts his follow-up article. Until then, happy profiling!

    Posted Dec 22 2004, 07:22 AM by darrell with 5 comment(s)
    Filed under:
  • Mozilla ad in the New York Times

    The Mozilla ad appearing in the New York Times.

  • The Chronicles of Narnia, coming to a theater near you

    First The Lord of the Rings extended edition trilogy set comes out on DVD, and now I find out that Andrew Adamson, director of Shrek, is going to direct The Lion, The Witch and The Wardrobe from The Chronicles of Narnia series by C.S. Lewis. Coming in December, 2005.

  • Argument Exception utility

    Nils Jonsson has posted a code sample on The Code Project that makes it easy to raise argument exceptions. You know, argument exceptions are those exceptions you are supposed to raise when the parameters passed in to your method don’t match what you thought they would be? Nils makes it easy by including the following 9 base methods (plus overloads):

    • ThrowIfArgumentDifferentType() throws ArgumentException if an argument is not an instance of a given type.
    • ThrowIfArgumentIncompatibleType() throws ArgumentException if an argument cannot be cast to a given type.
    • ThrowIfArgumentInvalidEnumValue() throws InvalidEnumArgumentException if an argument is not a constant in a given enumerated type.
    • ThrowIfArgumentNull() throws ArgumentNullException if an argument is a null reference (Nothing in Visual Basic).
    • ThrowIfArgumentOutOfRange() throws ArgumentOutOfRangeException if an argument is less than a given minimum or greater than a given maximum.
    • ThrowIfArgumentOutOfRangeExclusive() throws ArgumentOutOfRangeException if an argument is less than or equal to a given lower bound or greater than or equal to a given upper bound.
    • ThrowIfArgumentOutOfRangeIncludeMax() throws ArgumentOutOfRangeException if an argument is less than or equal to a given lower bound or greater than a given maximum.
    • ThrowIfArgumentOutOfRangeIncludeMin() throws ArgumentOutOfRangeException if an argument is less than a given minimum or greater than or equal to a given upper bound.
    • ThrowIfArrayArgumentDifferentRank() throws RankException if an array argument does not have a given number of dimensions.

    With these methods, it takes a single line of code to check a parameter and throw the appropriate exception. I’ve been writing methods similar to this in an ad-hoc manner for a while, but now I can take advantage of someone else’s hard work. In true TDD spirit, Nils also includes 620 NUnit test cases developed with the fabulous TestDriven.NET add-in by Jamie Cansdale!

  • A new Beta announcement Monday morning

    A lot of people are hinting at what’s going to be announced in Beta Monday morning at 10 PST. MSN is having a teleconference call where anyone can call in. Here’s how (from the MSNSearch weblog):

     When: Monday, Dec. 13, 2004; Teleconference begins at 10 a.m. PST
     Call-in number (U.S.): (800) 559-9370
     International: +1 (847) 619-6819

    My guess is MSN Desktop Search is being announced.

  • FireFoxView Mozilla extension for IE

    Previously, Raymond Chen engaged his massive blog readership in developing a View in Firefox capability in IE for me. Raymond specifically notes that his solution is for advanced users, meaning us. :)

    Recently I stumbled upon FireFoxView on the Mozilla extensions homepage. Interestingly, it uses the Firefox extension installer process to install an ActiveX control that enables the same functionality. Because of this you have to install the extension, close Firefox, and then restart Firefox before the item will show up in the IE context (right-click) menu.

  • Cross-browser DHTML behaviors (.htc files)

    Grant points us to a cross-browser drag-and-drop example. Good stuff, and Grant was the king of Javascript at a previous employer, so I’ll listen to his recommendation. etLux’s implementation, though, seems to rely on pasting code into too many different places.

    I like the simplicity of Dean Edward’s moz-behaviors (bold emphasis mine).

    • moz-behaviors.xml is an XBL binding that allows Mozilla browsers (Netscape, Mozilla, Firefox etc) to use Microsoft DHTML Behaviors with little or no conversion. Mozilla and Explorer may then reference the same DHTML Behaviors (.htc files).
    • moz-behaviors.xml is the only file you need to enable DHTML Behaviors for Mozilla browsers.
    • the XBL binding includes code that implements the addBehavior method for Mozilla’s HTML Elements. The code has been compressed using the javascript packer available from this site.
    • you do not need to write any additional code to implement DHTML Behaviors for Mozilla.
    • further, when writing behaviors, you do not need to do any browser sniffing. Mozilla’s object interfaces have been extended to enable browser compatibility.
    • you can view a working example here: /my/examples/moz-behaviors/
    • you can download the wrapper and the example here: /download/
  • Open searches from the Firefox search bar in a new tab

    Someone recently asked me, “Do you know if there is a way to enter a search, and then tell firefox to open the search in a new tab?”

    Yes there is! You need to install the Tabbrowser Preferences (TBP) v1.1.1. Then go to Tools -> Options and select the Tabbed Browsing icon in the left pane of the dialog box. On the right you will see “Load the following in new tabs:”; underneath that select the “Searches from the search bar” option. Then choose whether you want the results to load in the foreground (change focus to the results) or the background (a new tab with your current page keeping focus).

    There are many other options available in TBP. Read through the various options to see all of the customizability.

    Update: You can also press Alt + Enter. Thanks Mike Vincent!

    - Darrell

  • Using Active Directory in .NET

    Most of the applications I’ve developed have used Active Directory in one capacity or another. .NET support for Active Directory in v1.0-1.1 pretty much sucks. Things are supposed to get better in 2.0, but for now these resources are invaluable:

    Accessing Active Directory Through the .NET Framework by Robert Chartier – this is an excellent article on using the System.DirectoryServices namespace to manage users. Robert also creates a sample data access layer wrapper for modifying users. Nice!

    Viewing Active Directory Objects via ASP.NET by Erick Sgarbi – Erick focuses on enumerating local users and binding the results to a DataGrid.

    Querying Active Directory using .NET classes and LDAP queries by Sriram Chitturi – this article on CodeProject develops a nice Windows application that will allow you to test your LDAP queries.

    Microsoft Visual Studio.NET Server Explorer Extensions for Active Directory – This server explorer add-in allows you to build Active Directory queries. After building queries, the add-in will create System.DirectoryServices.DirectorySearcher and System.DirectoryServices.DirectoryEntry objects. These objects are ready to be used as part of your application. 1373 KB

    Using the .NET C# LDAP Library – Novell has some an LDAP library written in C# to go along with Mono. You can also download the LDAP libraries from Novell Forge and grab the Developing with the System.DirectoryServices Namespace API for Mono PowerPoint slide deck.

More Posts Next page »

Our Sponsors