Saturday, December 27, 2008

How to align checkboxes and their labels consistently across browsers

I was trying today to get a checkbox and its label to look consistent across browsers and finally came up with this solution. I tested it in IE6, FF2 and Chrome and it rendered same pixel by pixel in all the three browsers (also browsershots.org confirmed the result for other browsers). Hopefully this will save time for someone else.

<style type="text/css">
*
{
    padding: 0px;
    margin: 0px;
}
#wb
{
    width: 15px;
    height: 15px;
    float: left;
}
#somelabel
{
    float: left;
    padding-left: 3px;
}
</style>

<div>
<input id="wb" type="checkbox" /><label for="wb" id="somelabel">Web Browser</label>
</div>

* If you don't want to set the padding and margin to zero for all elements as I did here, you could only set them for the label and checkbox.

Wednesday, October 15, 2008

A problem when setting the page title dynamically in ASP.NET

Today I encountered a weird problem with ASP.NET. What I wanted to do was really simple. I wanted to change the page title dynamically in code, that's all. In my scenario I had a page that inherits from a basepage class. In that base page class I append the site name to the page title, e.g. if the page title is 'page title' (without the quotes) and the site name is 'mysite.com', I add the site name to the page title so that it becomes 'page title - mysite.com'

In my page, I overrode OnLoad and set the page title in there, but for an unknown reason I always got an empty string for the page title in the basepage class. So, I created a test page, overrode OnLoad() and set the page title in there, surprisingly that worked. I couldn't see any difference between the two pages, I commented all my code and still got a blank title in the basepage class. Finally, I noticed that the only difference between the two pages is that in my page, the title is set to an empty string in the page directive (ie. Title=""). While in the test page, the title is set to the default value (which is "Untitled Page"). By not keeping the title set to an empty string (just put anything in there) it finally worked.

This seems like a bug, I doubt this behavior is by design. Anyway, to sum up. If you want to set the page title dynamically in your code, make sure you have a "non empty string" for the page title, i.e., if you have Title="" in your page directive, replace it with any other value, e.g. Title="some value" (even though you're going to change this value), otherwise, it will not work.

Thursday, September 4, 2008

Are Web Designers Getting too Lazy?!!

Recently, I changed the color scheme on my computer because I was literally starting to look like a raccoon (with incredibly dark circles under my eyes). Anyway, I changed the background color of all windows to black and the text color to light gray. After I made the changes, I started to surf the net to realize that so many websites don't specify the colors for the page background and/or the text. They leave them to the browser's default colors!! I had strange (and ugly) looking websites on my computer (sadly, so many of them for well-known and popular websites). I got some pages with white background (they specified the background color correctly) but with light gray for the text! which is almost unreadable. Some other websites had black for the text color and also black for the background! which is completely unreadable! (they specified the text color but not the background color), and many websites didn't specify both, so you have black background and light gray text with the images having white background which is really ugly!

What the heck is going on?! Are web designers getting so lazy that they decided to depend on the browser's default color settings as if they were hard-coded?!! Didn't it come to their minds that anybody can change the color scheme? It's only two lines in CSS for God's sake!!!!

Tuesday, May 27, 2008

The Myth of for being faster than foreach

You probably, like me, heard this so many times that for is faster than foreach and you should use it whenever you can. Well, today I wanted to know how much this is true so I did a little test (find below the test and results). As you can see in the results of the test they are both identical but as I find using foreach is much more convenient for many reasons (including thread safety in some scenarios) so it makes more sense to use foreach whenever possible.

More details:

The release build was used in the test
Software used in the test:
  • Windows XP Pro SP2
  • .NET Framework 2.0

The specs of my computer (where the test was done) are:
  • CPU Intel 1.6GHz Dual Core
  • 1024 MB RAM


Used Code
using System;
using System.Collections.Generic;
using System.Text;

namespace for_vs_foreach
{
    class Program
    {
        static void Main(string[] args)
        {
            const int LOOP_COUNT = 10000000;
            int myVar;
            MyCustomObject[] customObjects = new MyCustomObject[LOOP_COUNT];
            for (int i = 0; i < LOOP_COUNT; i++)
            {
                customObjects[i] = new MyCustomObject(i);
            }

            System.Threading.Thread.Sleep(1000);

            // foreach
            //
            DateTime beforeForeach = DateTime.Now;
            foreach (MyCustomObject customObject in customObjects)
            {
                myVar = customObject.Var;
            }
            DateTime afterForeach = DateTime.Now;

            // for
            //
            DateTime beforeFor = DateTime.Now;
            for (int i = 0; i < LOOP_COUNT; i++)
            {
                myVar = customObjects[i].Var;
            }
            DateTime afterFor = DateTime.Now;

            Console.WriteLine("{0} (foreach test results)", afterForeach.Subtract(beforeForeach));
            Console.WriteLine("{0} (for test results)", afterFor.Subtract(beforeFor));
            Console.Read();
        }
    }

    public class MyCustomObject
    {
        public MyCustomObject(int var)
        {
            _var = var;
        }

        private int _var;
        public int Var
        {
            get
            {
                return _var;
            }
            set
            {
                _var = value;
            }
        }
    }
}
Results: 00:00:00.0625000 (foreach test results)
00:00:00.0625000 (for test results)

Saturday, May 10, 2008

Efficiently Copying Items from One Array to Another in C# (Also generally in .NET)

I've been searching recently for an efficient way in C# to copy items from an array to another. At first it seemed that efficient way simply didn't exist. In C++ you can do this very easily by copying the memory block using memcpy() or memmove() but in C# you can't do this in a safe way (sure you can write some unsafe code but this is not really what I wanted, I just wanted to do it the 'clean and safe way'). Anyway, my options were to use Array.Copy() or a for loop (iterate through the source array and copy the items to the destination array). Unfortunately the documentation for Array.Copy() clearly states that it's an O(n) operation where n is length, so, it seemed that the for loop and Array.Copy() were almost equivalent so I decided I could use any of them as it wouldn't make any real difference (my decision was based on what's written in the documentation about Array.Copy() being an O(n) operation)

Anyway, today I was using .NET Refelctor to view the code for List<T>.ToArray(), I found that the Array.Copy() was used in the code, see below the code for List<T>.ToArray() copied from .NET Reflector:

public T[] ToArray()
{
    T[] destinationArray = new T[this._size];
    Array.Copy(this._items, 0, destinationArray, 0, this._size);
    return destinationArray;
}

So, I wanted to have a look on Array.Copy(), this is how it shows in .NET Refelctor:

[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)
{
    Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length, false);
}

The code for Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length, false); can't be viewed using .NET Reflector, here's what you get:

[MethodImpl(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
internal static extern void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, bool reliable);

To make a long story short I just was curious to see whether using Array.Copy() is really equivalent to using a simple for loop, so, motivated by my inability to view the code for Array.Copy(),I decided to do my own testing (see the code and results below). Well, despite what's written in the documentation about Array.Copy() being an O(n) operation, Array.Copy() was 10 times faster on my computer! So my guess is that it internally uses some memory copying so it's not really an O(n) operation.

Update:

Just to be clear, when I said the operation is not O(n), I was referring to the implementation not using a for loop to copy the items (ie. from the performance point of view). I realize it's technically incorrect to say it's not O(n). My apology for the confusion.

More details:

The release build was used in the test
Software used in the test:
  • Windows XP Pro SP2
  • .NET Framework 2.0

The specs of my computer (where the test was done) are:
  • CPU Intel 1.6GHz Dual Core
  • 1024 MB RAM


Used Code
using System;
using System.Collections.Generic;
using System.Text;

namespace array_copy
{
    class Program
    {
        static void Main(string[] args)
        {
            const int ArraySize = 5000;
            const int LoopCount = 100000;

            MyCustomObject[] customObjects1 = new MyCustomObject[ArraySize];
            MyCustomObject[] customObjects2 = new MyCustomObject[ArraySize];
            for (int i = 0; i < ArraySize; i++)
            {
                customObjects1[i] = new MyCustomObject(i);
                customObjects2[i] = new MyCustomObject(i);
            }

            // Array.Copy()
            //
            DateTime beforeArrayCopy = DateTime.Now;
            for (int j = 0; j < LoopCount; j++)
            {
                Array.Copy(customObjects1, 0, customObjects2, 1, customObjects1.Length - 1);
            }
            DateTime afterArrayCopy = DateTime.Now;

            // For Loop Copy
            //
            DateTime beforeForLoopCopy = DateTime.Now;
            for (int j = 0; j < LoopCount; j++)
            {
                int length = customObjects1.Length - 1;
                for (int i = 0; i < length; i++)
                {
                    customObjects2[i + 1] = customObjects1[i];
                }
            }
            DateTime afterForLoopCopy = DateTime.Now;

            Console.WriteLine("{0} Array.Copy()", afterArrayCopy.Subtract(beforeArrayCopy));
            Console.WriteLine("{0} For Loop Copy", afterForLoopCopy.Subtract(beforeForLoopCopy));

            Console.Read();
        }
    }

    public class MyCustomObject
    {
        public MyCustomObject(int var)
        {
            _var = var;
        }

        private int _var;
        public int Var
        {
            get
            {
                return _var;
            }
        }
    }
}
Results: 00:00:00.5937500 Array.Copy()
00:00:04.9062500 For Loop Copy

Friday, April 25, 2008

Redirecting The Ouput of a Command to the Clipboard

I very often use the command line to list file names using the dir command (for web design and other purposes). I usually need to have those file names in notepad. One way to do that is to redirect the command ouput to a file (copy the text from the file then delete it) or mark the text in the command line window and press Enter to copy it to the clipboard. A nicer and cleaner way though is to redirect the output of the command to the clipboard. Unfortunately there's no built-in way for doing this in Windows XP, however, it can be added very easily. In Windows 2003 we have a file called clip.exe (under the Windows or system32 directory, not sure, so search for it), which we can use to redirect the output of any command to the clipboard, but first if you're using Windows XP, copy this file to the Windows or System32 directory on your computer (obviously you'll need a computer with Windows 2003 to get this file, you might as well try seraching the internet, it's most probably there).

Now to redirect the output of your command to the clipboad, just use a pipe with clip, for example:

dir /b | clip

* If you're wondering what the /b switch does, it displays the bare file names (only the file names with no headers or any other information)

Thursday, April 24, 2008

My Favorite Windows Keyboard Shortcuts

I'm pretty much a keyboard freak, I don't really use the mouse unless I'm forced to :) or in other words, unless I want to do something that cannot be done using the keyboard. In case you didn't know that, you can actually move the mouse cursor using the keyboard, this a feature called MouseKeys which I use when I have a problem with the mouse. To activate MouseKeys, press and hold the left Shift and left Alt keys then press the Num Lock key (you may search google for MouseKeys to get more details about that and to know what keys you should use to move the mouse, they are the Numpad keys by the way)

I use keyboard shortcuts in most applications (IE, FireFox, HTML Help .. etc), but I'm going to list here only the Windows Keyboard shortcuts (by the way, I use Windows XP but most of these keyboard shortcuts are from earlier versions starting from Windows 95, note though that a few of these keyboard shortcuts don't work in Vista but the majority do). So, here's a list of the keyboard shortcuts that I use quite frequently in Windows (or more accurately what I remember now):

  • Ctrl + Shift + Esc (to show the task manager)
  • Alt + Enter (while an icon is selected, e.g. a file, a folder or an icon on the desktop, to open the properties window for that icon)
  • Windows Key + Pause (to show the System Properties window)
  • Windows Key + E (to open a Windows explorer window, I follow this by Ctrl + E twice to hide the folders view)
  • Windows Key + F (to show the serach window)
  • Ctrl + E or Ctrl + F (while in a folder window to show the search side panel)
  • Alt + D (while in a folder window to move the focus to the address textbox in the address bar)
  • Alt + Space (to activate the system menu of an application)
  • Alt + Space + X (to maximize the current window, press them in the same sequence)
  • Alt + Space + N (to minimize the current window, press them in the same sequence)

MDI Applications Keyboard Shortcuts

  • Ctrl + F4 (to close the currently active MDI child window)
  • Alt + - (to activate the system menu for the currently active MDI child window)
  • Alt + - + X (to maximize the current MDI child window, press them in the same sequence)
  • Alt + - + N (to minimize the current MDI child window, press them in the same sequence)
  • Ctrl + F6 (to move focus between child MDI windows)

Using the Keyboard with the Mouse

  • Double clicking an icon while holding the Alt key (this will open the properties window for this item instead of opening/running the item itself)
  • Double clicking a folder icon while holding the Ctrl key (this will open the folder in a new window, note that the folder has to be unselected before you double click it)

If you're Worried About Performance, Avoid Using Type Initializers (aka static constructors)

I'm currently trying to write a highly scalable web application (using C# and .NET Framework 2.0), so, I simply trying to squeeze every drop of performance of the CPU, the DB .. etc. I'm doing a lot of performance testing to everything I use in my application. In my application, I'm using static constructors heavily as they seem to make things easier, well, this is until I realized that they really affect performance! Actually, I discovered this by accident while doing another test. I wanted to test the performance of using nested static classes vs. using singletons, in the process I used a couple of static constructors in the classes (see the code below), the point was to use the static constructor to initiate the variable used for holding the singleton object reference so that we can remove the lazy loading if condition which I expected it would improve performance, well, this is what I thought but the result was surprising to me, the classes that have static constructors take much more time to be accessed than those that don't have static constructors (see the results at the end of this post). My wild guess is that every time a class with a static constructor is accessed the runtime checks whether the static constructor was called or not which causes the performance hit. Without further ado, here's the code below and the results of running the test on my computer .

More details:

I used the release build in the test (not the debug build as it very often gives very wrong results)
Software used in the test:
  • Windows XP Pro SP2
  • .NET Framework 2.0

The specs of my computer (where the test was done) are:
  • CPU Intel 1.6GHz Dual Core
  • 1024 MB RAM


Used Code
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace singleton_vs_nested_classes
{
    class Program
    {
        static void Main(string[] args)
        {
            const int LOOP_COUNT = 1000000000;
            int tempVar = 0;
            Thread.Sleep(3000);

            // TestStatic
            //
            tempVar = TestStatic.TestVar;
            DateTime beforeTestStatic = DateTime.Now;
            for (int i = 0; i < LOOP_COUNT; i++)
            {
                tempVar = TestStatic.TestVar;
            }
            DateTime afterTestStatic = DateTime.Now;

            // TestStaticWithTypeInitializer
            //
            tempVar = TestStaticWithTypeInitializer.TestVar;
            DateTime beforeTestStaticWithTypeInitializer = DateTime.Now;
            for (int i = 0; i < LOOP_COUNT; i++)
            {
                tempVar = TestStaticWithTypeInitializer.TestVar;
            }
            DateTime afterTestStaticWithTypeInitializer = DateTime.Now;

            // TestNested
            //
            tempVar = TestNested.MyNestedClass.TestVar;
            DateTime beforeTestNested = DateTime.Now;
            for (int i = 0; i < LOOP_COUNT; i++)
            {
                tempVar = TestNested.MyNestedClass.TestVar;
            }
            DateTime afterTestNested = DateTime.Now;

            // TestSingltonLazyLoading
            //
            tempVar = TestSingltonLazyLoading.Singlton.TestVar;
            DateTime beforeTestSingltonLazyLoading = DateTime.Now;
            for (int i = 0; i < LOOP_COUNT; i++)
            {
                tempVar = TestSingltonLazyLoading.Singlton.TestVar;
            }
            DateTime afterTestSingltonLazyLoading = DateTime.Now;

            // TestSingltonInitInTypeInitliazer
            //
            tempVar = TestSingltonInitInTypeInitliazer.Singlton.TestVar;
            DateTime beforeTestSingltonInitInTypeInitliazer = DateTime.Now;
            for (int i = 0; i < LOOP_COUNT; i++)
            {
                tempVar = TestSingltonInitInTypeInitliazer.Singlton.TestVar;
            }
            DateTime afterTestSingltonInitInTypeInitliazer = DateTime.Now;

            // Show results
            //
            Console.WriteLine("{0} TestStatic", afterTestStatic.Subtract(beforeTestStatic));
            Console.WriteLine("{0} TestStaticWithTypeInitializer", afterTestStaticWithTypeInitializer.Subtract(beforeTestStaticWithTypeInitializer));
            Console.WriteLine("{0} TestNested", afterTestNested.Subtract(beforeTestNested));
            Console.WriteLine("{0} TestSingltonLazyLoading", afterTestSingltonLazyLoading.Subtract(beforeTestSingltonLazyLoading));
            Console.WriteLine("{0} TestSingltonInitInTypeInitliazer", afterTestSingltonInitInTypeInitliazer.Subtract(beforeTestSingltonInitInTypeInitliazer));
            Console.Read();
        }
    }

    public static class TestStatic
    {
        private static int _testVar = 5;
        public static int TestVar
        {
            get
            {
                return _testVar;
            }
        }
    }

    public static class TestStaticWithTypeInitializer
    {
        static TestStaticWithTypeInitializer()
        {
            _testVar = 5;
        }

        private static int _testVar;
        public static int TestVar
        {
            get
            {
                return _testVar;
            }
        }
    }

    public static class TestNested
    {
        public static class MyNestedClass
        {
            private static int _testVar = 5;
            public static int TestVar
            {
                get
                {
                    return _testVar;
                }
            }
        }
    }

    public static class TestSingltonLazyLoading
    {
        private static TestSinglton _singltonInstance;
        public static TestSinglton Singlton
        {
            get
            {
                if (_singltonInstance == null)
                {
                    _singltonInstance = new TestSinglton(5);
                }
                return _singltonInstance;
            }
        }
    }

    public static class TestSingltonInitInTypeInitliazer
    {
        static TestSingltonInitInTypeInitliazer()
        {
            _singltonInstance = new TestSinglton(5);
        }

        private static TestSinglton _singltonInstance;
        public static TestSinglton Singlton
        {
            get
            {
                return _singltonInstance;
            }
        }
    }

    public class TestSinglton
    {
        public TestSinglton(int testVar)
        {
            _testVar = testVar;
        }

        private int _testVar;
        public int TestVar
        {
            get
            {
                return _testVar;
            }
        }
    }
}
Results: 00:00:01.2656250 TestStatic
00:00:12.8437500 TestStaticWithTypeInitializer
00:00:01.2812500 TestNested
00:00:03.2187500 TestSingltonLazyLoading
00:00:09.3125000 TestSingltonInitInTypeInitliazer

Tuesday, January 8, 2008

Installing Windows XP in Virtual PC

When you create a new virtual machine in Virtual PC (2007 and earlier), you choose the operating system you want to install on that virtual machine so that the virtual machine settings are optimized for that operating system. Now when you choose Windows XP from the list of operating systems, you get a default value of 128 MB for the memory, don't use that default value! If you do, Windows XP will take ages to install on your virtual machine, so, change the default value to be at least 256 MB. This will make a huge difference.

Friday, January 4, 2008

Return value of ExecuteNonQuery() in the MySQL .NET Provider

As support for stored procedures was added in MySQL 5, I thought I'd blog about a difference in behavior I noticed between the SQL Server .NET Provider and the MySQL .NET Provider when executing stored procedures using ExecuteNonQuery().

You know that when you use ExecuteNonQuery() to execute a stored procedure (or any other SQL statements but we're going to talk about stored procedures here) it returns the number of records affected by the stored procedure. Now, what exactly is returned by the SQL Server Provider? I assume most developers who use the SQL Server Provider know that but in case you didn't know, the SQL Server Provider returns the total number of records affected by executing all statements in the stored procedure.

Let's take this example to make things clearer. For example, say that you have a stored procedure in which you first insert some records in a table then in the same procedure you update some records in another table. Let's assume that the procedure was executed and it inserted 5 records in the first table and updated 3 records in the second table, now what the SQL Server Provider returns exactly is the total number of records affected by executing this procedure which is 5 + 3 = 8.

On the other hand, the MySQL .NET Provider only returns the number of records affected by executing the last statement in the procedure, so referring to the preceding example, ExecuteNonQuery() will only return 3.

The point in this post is that if you're using the value returned from ExecuteNonQuery() for anything in your project, you just should be aware of the difference in behavior between the SQL Server Provider and the MySQL .NET Provider.

Happy programming!

Thursday, January 3, 2008

Sybase Annoyances

One of the things that I really hated about Sybase is its lack of support for the use of the top keyword in subquries, for example:

SELECT
    field1,
    (SELECT TOP 1 field1 FROM table2 WHERE id = table1.id) myfield
FROM
    table1

This works in SQL Server but not in Sybase.

This is as of Sybase ASE 12.5, I don't know if this changed in Sybase ASE 15, so, if you have any idea about it please share this with us in the comments section.

How to Open The Current Page in a New Tab in FireFox

In FireFox when you click Ctrl + T, a new tab is opened showing a blank page. But what if you want to open a new tab that shows the current page, it's simple but you'll have to do it in two steps:
1. Press Alt + D (notice that the current page address will be highlighted in the address bar)
2. Now, Press Alt + Enter (a new tab will be opened showing the current page)