Manage your Constant’s List More Easily By using Enums.

18 11 2008


List of constants and their count. Every programmer have used it atleast once in his life time. A list of constants can be any for instance, if its an image processing software, it can be a list of image types, the application can manage. And we also used to keep the count of constants present.

manageconstantlistasenum2

Yes. I know you need an example. Well, lets take the image processing application itself. It might keep a constant list as follows.

const int IMAGE_TYPE_BMP = 0;
const int IMAGE_TYPE_JPG = 1;
const int IMAGE_TYPE_GIF = 2;
const int IMAGE_TYPE_COUNT = 3;

Think what all you’ve to do if you need to add a new image type? You’ve to insert the constant at end, then update the count. Like this,

const int IMAGE_TYPE_BMP = 0;
const int IMAGE_TYPE_JPG = 1;
const int IMAGE_TYPE_GIF = 2;
const int IMAGE_TYPE_JPG_LOSSY = 3;
const int IMAGE_TYPE_COUNT = 4;

If you want to append the variable, its okay. You just have to append at end and update the count. But what if you want to insert the variable at middle? In this case JPG_LOSSY seems to be more good just after the JPG. isn’t it? In that case you’ve to update all following constants.Like this,

const int IMAGE_TYPE_BMP = 0;
const int IMAGE_TYPE_JPG = 1;
const int IMAGE_TYPE_JPG_LOSSY = 2;
const int IMAGE_TYPE_GIF = 3;
const int IMAGE_TYPE_COUNT = 4;

Assume if your constant list have 50 items! Well, is there any easy trick?


Yes! You can use anonymous enums to avoid the headache. Just declare the constants as follows.

enum
{
IMAGE_TYPE_BMP = 0,
IMAGE_TYPE_JPG,
IMAGE_TYPE_GIF,
IMAGE_TYPE_COUNT
};

And if you want to insert another constant at middle, just insert it. You don’t have to modify anything else. For instance,

enum
{
IMAGE_TYPE_BMP = 0,
IMAGE_TYPE_JPG,
IMAGE_TYPE_JPG_LOSSY,
IMAGE_TYPE_GIF,
IMAGE_TYPE_COUNT
};


Since, they are anonymous enums, you can use the constant name directly in code.
Just insert and forget the rest. It will get self adjusted. :D Cool! isn’t it.


Targeted Audience - Intermediate.





How to Debug the Release Build?

16 11 2008


“Debugging in release build!!! Is it possible?” I’ve heard this questions a couple of time, especially from Visual C++ Novices. Yes! its possible. But why?
I still remember my first project. We did everything right, debugged and fixed all bugs in debug build and released the application. But client tested the release version and it was like FatMan, a lot of crashes.

So, Debugging in release build is important because, even though the debug build can catch most of issues, there might be some bugs or crashes still hiding under the release version of application. For catching them, there is now way other than to debug the release build itself.

debuginreleasebuild


Well, basically compiler needs debug information for stepping into code while debugging and In release build, by default there will not be any debug information. Compilers cannot interpret or understand optimized code and in release build, optimization will be enabled by default. For debugging in release build, you’ve to generate debug information and to turn off optimizations. Follow the steps about how to tweak project settings for that.

1) Take project settings by Alt+F7.
2) Select Release configuration.
3) Select “C/C++” tab. Set “Optimizations” as “Disable Debug” and “Debug Info” as “Program Database”.

debuginreleasebuild1

4) Take “Link” tab. Enable “Generate Debug Info“.

debuginreleasebuild2

5) Now from menu, take - “Build > Set active configuration…” and select Release build as default.

debuginreleasebuild3

6) Rebuild the project by F7.
7) Now what are you waiting for? Press F5 to debug and enjoy!


Since my first project, I don’t forget how to debug in release version. :D and this is my advice for you - “Its fine to do the entire debugging in debug build, because its tuned to catch a lot of bugs. But before releasing check the release build too.”


Targeted Audience - Beginners.





Watch byte streams in Memory Window more easily.

13 11 2008


Assembly programming! It fascinates me always. I love sending packets of data to hardware, parsing back the replies, etc. You might be using BYTE arrays for doing such stuffs. well, in that case, instead of watch window, memory window is preferable to see the byte stream, because it will be so easy to see the entire message.

For instance, assume that we need to send a packet of data in following format.
memorywindow1

Following code snippet generates similar array. Ofcourse in legacy coding style.

// Data packet.
const int DATA_PACKET_LEN = 12;
BYTE DataPacket[DATA_PACKET_LEN] = { 0 };

int Index = 0;

// Add the first DWORD.
DataPacket[Index] = 1;
Index += sizeof( DWORD );

// Add the second WORD.
DataPacket[Index] = 2;
Index += sizeof( WORD );

// Add the third WORD.
DataPacket[Index] = 3;
Index += sizeof( WORD );

// Add the forth DWORD.
DataPacket[Index] = 4;
Index += sizeof( DWORD );

If you watch DataPacket in memory window, it will look like this.
memorywindow2
A chunk of bytes. It seems hard to read and interpret values. isn’t it? More over that, in intel machines, the values are stored in LSB format which makes the readability even more worse. well is there any trick which helps to read the format even better.


If you right click in the Memory window, you’ll get the context menu and in that you can select the preferred byte ordering.
memorywindow3

Select “Long Hex Format” to group bytes as DWORDs. Well, now you can read the byte stream, as such in the packet format picture. cool! isn’t it?
memorywindow4


Yes! i know. You’re thinking about this - the second and third parameter get swapped. Well, its due to the fact that Intel machines follows LSB layout for storing values in memory. This is not perfect solution but it does make life easier and having something is better than nothing! isn’t it? ;)


Targeted Audience - Intermediate.





How to add font to system, programmatically?

29 10 2008


Diablo
! It was my favorite game during my childhood. Chopping down monsters, bats… Wow!!! I love it. Every time when i start the program one thing that attracted me is its font.Later when I searched net, i found that there is a font named diablo. But what will happen if the font is not present in the system? The game screen will be wired? The application might be installing the font, if its not present in the system. But how to do it?


Well, You can use the api - AddFontResource(). You have to provide the path of font file to be added to system. Have a look at the code snippet.

// Path of font to be added.
CString csFontPath = _T( "C:\\Diablo.ttf" );

// Add font to system.
if( 0 == AddFontResource( csFontPath ))
{
   // Adding font to system failed.
}


Well, the latest version of diablo is Diablo III. Its superb! Have a look at it. ;)


Targeted Audience - Intermediate.





How to kill process in batch by using wildcard filters?

24 10 2008

I often get irritated while working in huge frameworks. A lot of application might be running simultaneously and it fills up my task bar. Usually I drag and adjust my taskbar, 3X more taller than usual. But still they fill up my taskbar. Most of them were servers running in command prompts or executable have some common prefix and Its a real burden while closing all windows. I’ve to close them one by one. Is there any command gun to kill them all in one shot? ;)


You could use the command taskkill. Have a look at the syntax.

Syntax: taskkill /IM <ExeName>
E.g.
C:\>taskkill /IM note*
SUCCESS: The process "notepad.exe" with PID 2428 has been terminated.
SUCCESS: The process "notepad.exe" with PID 3588 has been terminated.
SUCCESS: The process "notepad.exe" with PID 4960 has been terminated.
SUCCESS: The process "notepad.exe" with PID 3320 has been terminated.
SUCCESS: The process "notepad.exe" with PID 4704 has been terminated.


Note that taskkill command is available from Windows XP onwards. So take care.


Targeted Audience - Beginners.





How to set Transparent Dialogs?

7 10 2008


The Invisible Man” by HG Wells. I still remember reading the translated version of that classic, when i was a kid. And even thought to conduct some experiments to become invisible. You could guess, what happened then. :) I couldn’t. But now I feel happy that atleast I could find a magic portion which can make dialogs invisible. ;)  Well, how to change the transparency of dialogs?


The secret is Layered windows. For that you’ve to enable WS_EX_LAYERED style and set the alpha of dialog by calling SetLayeredWindowAttributes(). See the code snippet below.

// Enable WS_EX_LAYERED window extended style.
LONG ExtendedStyle = GetWindowLong( GetSafeHwnd(),
                                    GWL_EXSTYLE );
SetWindowLong( GetSafeHwnd(),
               GWL_EXSTYLE,
               ExtendedStyle | WS_EX_LAYERED );

// Select the transparency percentage.
// The alpha will be calculated accordingly.
double TransparencyPercentage = 50.0;

// Set the alpha for transparency.
// 0 is transparent and 255 is opaque.
double fAlpha = TransparencyPercentage * ( 255.0 /100 );
BYTE byAlpha = static_cast<BYTE>( fAlpha );
SetLayeredWindowAttributes( GetSafeHwnd(),
                            0,
                            byAlpha,
                            LWA_ALPHA );


Layered windows are available from Windows 2000 onwards. So don’t forget to add _WIN32_WINNT=0×0500 to project settings for preparing the dialog invisible portion. ;)


Targeted Audience - Intermediate.





How to adjust the drop down width of ComboBox?

5 10 2008


Combobox is good, because they utilize less space and at the same time they can show a list of options. But did you noticed one thing? By default the dropdown width of combobox is same as the width of combobox itself. If you add a loooong string to combobox, it will be displayed partially in the drop down list. So how to stretch the with of dropdown list of combobox?


If you are using MFC, you could use the api - CComboBox::SetDroppedWidth() or else you could use the message CB_SETDROPPEDWIDTH. First of all you’ve to iterate all strings in the combobox list and find out the required width. Then set the new drop down width of combobox. See the MFC code snippet for doing so. Code snippet is taken from MSDN and has been modified appropriately.

void CComboBoxDemoDlg::AdjustDropDownWidth()
{
    // Find the longest string in the combo box.
    CComboBox* pComboBox =
        ( CComboBox* ) GetDlgItem( IDC_CMB_STRINGS );
    int MaxWidth = 0;
    CDC* pDC = pComboBox->GetDC();

    // Iterate through all strings in Combobox and get MaxWidth
    CString String;
    CSize TextSize;
    for ( int Index = 0; Index < pComboBox->GetCount(); Index++ )
    {
        // Get n'th string.
        pComboBox->GetLBText( Index, String );

        // Get TextExtend
        TextSize = pDC->GetTextExtent( String );

        // Get MaxWidth.
        if( TextSize.cx > MaxWidth )
        {
            MaxWidth = TextSize.cx;
        }
    }

    pComboBox->ReleaseDC( pDC );

    // Adjust the width for the vertical scroll bar and
    // the left and right border.
    MaxWidth += ::GetSystemMetrics(SM_CXVSCROLL) +
                2 * ::GetSystemMetrics(SM_CXEDGE);

    // Set the dropdown width of combobox.
    pComboBox->SetDroppedWidth( MaxWidth );
}


You could achieve the same by sending CB_SETDROPPEDWIDTH by using SendMessage().


Targeted Audience - Intermediate.





_chdir() pitfall - error while opening file.

4 10 2008


I still remember that bug! Because it grabbed my two days and delayed the delivery. Well, the story goes like this - It was during late summer of 2004. I was working in a DVD writer project. Internally we were using a third party DVD writer library named BHA Gold. Well, my project was a wrapper library for the BHA Gold library.

Well, the bug was this - There is a config file in my project, which exist in the same folder, together with exe. Before writing DVD, I’ve to read some settings from the config file. But the bug is this. During startup, I could open the file. But if I write one DVD using BHA gold, then when i tried to open the same file once again, it shows error!


At last its been found that the culprit is the api - _chdir(). The DVD writing library was calling this api internally to prepare the directory tree, and once this api is called, the default directory will be changed to the specified directory and during next time, while opening the setting file, it shows an error that “file not found”! Since the setting file does not exist in the new default directory.


Well, in such cases you could use the api - SetCurrentDirectory(). See the code snippet to set the current directory as exe’s folder path.

#include "Shlwapi.h"
...
// Get the full path of current exe file.
TCHAR FilePath[MAX_PATH] = { 0 };
GetModuleFileName( 0, FilePath, MAX_PATH );

// Strip the exe filename from path and get folder name.
PathRemoveFileSpec( FilePath );    

// Set the current working directory.
SetCurrentDirectory( FilePath );


Don’t forget to add Shlwapi.lib to project settings. ;)


Targeted Audience - Advanced.





I’m Back Again!!!

3 10 2008

Guys,

Life! Everything that happens are so unexpected. During last few weeks, me too had some unexpected encounters in my personal life. The bad news is, during those days, I couldn’t make Weseetips alive. :( Well, the good news is, at last I’ve overcame the barriers and am smiling now! :D Now I am back to business! I thank my fellow readers for being patient. Yes! Lets rock on…





How to calculate log2 of any number?

10 09 2008


Few days back, my client give me one 4 inch long and 2 inch wide math equation to implement. Well, the equation contains log2 and while coding, my Visual Assist was not auto filling the log2 function. It just underlines the function by redline. When i checked the MSDN, I was shocked that log2 is not available as the part of standard library. So how to get the log2 of a number?


Log2 is pretty simple, nah? Its implementation as follows,

#include <math.h>
...
// Calculates log2 of number.
double Log2( double n )
{
    // log(n)/log(2) is log2.
    return log( n ) / log( 2 );
}


Its silly function, But I still blame standard library for not including it. Because I’m lazy. ;)


Targeted Audience - Beginners.