How to convert CString to char* or LPTSTR?

17 12 2008


Without a second thought, I can say that it will be one of the first problems that beginners face - How to convert a CString to LPTSTR. I’ve seen this question several times in forums. Well, i think the CString to LPTSTR conversion is just like this picture. ;)

cstringtolptstr


Well, you can use CString::GetBuffer() to access the internal buffer of CString. But one thing to take care is that - you should release the buffer by calling CString::ReleaseBuffer() after use. Check the code snippet below,

// Our CString object.
CString String = "HelloWorld";

// Get the internal buffer pointer of CString.
LPTSTR pString = String.GetBuffer( 0 );
...

// Use the pString and then release it.
String.ReleaseBuffer();


Now get rid of that nasty error message - error C2664: ‘Hello’ : cannot convert parameter 1 from ‘class CString’ to ‘char *’. ;)


Targeted Audience - Beginners.





How to find the Relative Path to other Common Folders - More Easily?

16 12 2008


Well you know what a relative path is. The “.\..\..\Folder” thing. Usually in project settings, while referring the path of other common include folders, relative path is being used. Because, it won’t break the project settings even though the entire development folder structure is moved from one location to another.

To be more specific, If you have specified absolute path like - “c:\Source\BlahBlahProject\Libs” in the project settings, if you move Source folder to D:\ your project won’t compile. Relative paths are good, but its a bit difficult to calculate it. I saw people calculating it with their memory by touching the folder structure in monitor. ;) Some advanced guys uses the windows explorer’s auto complete feature to get the relative path. But is there any other easy method to get it?

relativepath


Well, You can use Visual Studio for it. Just follow the steps. Assume you want to get the relative path from your project folder to the common lib folder - “c:\Source\BlahBlahProject\Libs”.

1) Load you project in visual studio.
2) Create a file hello.cpp in folder - “c:\Source\BlahBlahProject\Libs”.
3) Add the file to your project by using menu - Project > Add To Project > Files.
4) Right click the file and take Properties.
relativepath1

5) In the properties, you can get the relative path from “Persist as” editbox.
relativepath2


The only limitation is our imagination. Isn’t it? ;)


Targeted Audience - Intermediate.





Windows File Protection - How to check whether the file is protected?

15 12 2008


Windows have got a set of files which are essential to the working of system. Chances are lot that those files to be corrupted accidentally or intentionally. But windows have taken care about it and those files are under protection. So if your user selects the filename of a protected system file to save his data, its the duty of a responsible windows citizen  application to check whether its a system file and to warn the user. Well, how to check whether the file is a protected system file?

windowsresourceprotection


You could use the function - SfcIsFileProtected(). Check the code snippet.

#include "Sfc.h"
...
// Check whether the file is protected or not.
WCHAR* pProtectedFile = L"C:\\Windows\\system32\\kernel32.dll";
BOOL bProtected = SfcIsFileProtected( NULL, pProtectedFile );

How to get the list of protected files?
Well, iterating the protected file list will be nice. isn’t it? You can use the function - SfcGetNextProtectedFile() for that. Check the code snippet below.

// Get the protected file list - one by one.
PROTECTED_FILE_DATA ProtectedFileInfo = { 0 };
while( SfcGetNextProtectedFile( NULL, &ProtectedFileInfo ))
{
    // Print the filename.
    cout << ProtectedFileInfo.FileName << endl;
}


Well, for some reason the SfcGetNextProtectedFile() is removed from vista. So keep in mind that it will work only on XP and 2000 machines. Well, don’t forget to include sfc.lib in your project settings. ;)


Targeted Audience - Beginners.





How to check whether the Pointer is allocated in Stack or Heap in Debug?

14 12 2008


What if you call delete operator by using a stack pointer? Like that, while writing frameworks sometimes we expects the pointer that gets passed to the function should point a valid memory block which is allocated on heap itself. So how can we check whether the pointer points to stack or heap in debug version?

stackorheap


You can use the function - _CrtIsValidHeapPointer(). Its an undocumented CRT function. But it works only in debug version. Well, please check the code snippet below,

#include "malloc.h"
...

// Check heap pointer.
int* pInteger = new int;
BOOL bHeap = _CrtIsValidHeapPointer( pInteger );

// Check stack pointer and you'll get an assertion.
char CharArray[100];
bHeap = _CrtIsValidHeapPointer( CharArray );


Its annoying that its not available in release version. Well, atleast we could make our framework to notify the user while debugging in the debug build. isn’t it?


Targeted Audience - Beginners.





How to reduce the size of Microsoft Word files?

7 12 2008


Documentation is inevitable for developers. Mostly we use Microsoft Word for documentation and you’ve already noticed the huge file size of word files. It often gets several megabytes in size. Its mostly when you copy paste images to document. While pasting, the images are embedded as bitmaps and hence the huge size. Well if you zip it, then it will drastically reduce the size. Well, is there any other method to reduce the size without zipping?

reducewordfilesize


Microsoft Word have built in feature for compressing images. Follow the steps below.

1. Right click any of the pictures in your word document and select “Format Picture”
reducewordfilesize1

2. Now take  “Picture tab” and click Compress” button.
reducewordfilesize2

3. Now in the compression options, you could select accordingly. For optimal file size, select resolution as “Web/screen” and apply for “All Pictures in document”.
reducewordfilesize3

Now check the file size! Amazing. isn’t it? ;)


Well, no more zipping head aches, no more email bouncing due to attachment size. Complete Peace for Mind ;)


Targeted Audience - Beginners.





POLL: Which version of Visual Studio are you using?

2 12 2008




How to Set one Dll as Delay Loading Dll?

2 12 2008


Nobody like delays. All of us want everything to be on time. May the the most hated characteristic might be the delaying nature. Well, while everyone hates delays, there is one special guy who loves delays - the Windows loader. :D

delayloadingdll

Well, as you know the purpose of the windows loader is to load the an application file disk to memory and start the execution. While loading an executable, loader have to make sure that all the dlls required by application are also loaded to memory. But assume you have 50 dlls. Eventhough those dlls have to do nothing in application startup, its loader’s duty to load it. And when the dll count goes on, loader have to work more and there by your application needs more time to start. Well, how to make the startup more faster in this situation?


You could mark your dlls as delay loading dlls. If you have enabled delay loading dll option for the dll, then loader loads the dll only when application make the first function call to that dll. Hence, during application startup, the loader’s “load” can be reduced and it will improve startup time. In other words, you can call it as “Load on demand”.

Well for enabling delay loading for a dll, you have to specify the linker option /DELAYLOAD:dllname to linker settings. For instance, see the screenshot for how to enable delay loading for mydll.dll.

delayloadingdll2


Interesting to know that loaders love delays. Isn’t it? lazy loaders ;)


Targeted Audience - Intermediate.





How to Remove Unreferenced Formal Parameter warning?

26 11 2008

Hands on legacy code base is a different kind of game! You have to learn a lot of tricks. During old days, legacy codebases have the compiler default settings. But now, for better error catching, most will switch  the warning level to high. Well, did you ever ported your legacy codebase by updating its project settings such as by switching the warning level from Level 3 (default) to Level 4, most probably you’ll get this - “Warning C4100: ‘Param2′ : unreferenced formal parameter”.

In most of the case, it might be some unused stack variable. But in some other cases, it might be the unused function parameters as well. For instance, if base class have some pure virtual function, we have to implement that, even if we don’t have any specific implementation for it. In that case, the parameters will not be used and can cause the same warning. Well how to “kick out” those warnings easily?

unreferrencedvariablewarning


Well, there are two tricks.

1) Use the macro - UNREFERENCED_PARAMETER
The common trick is to use the macro UNREFERENCED_PARAMETER(). When it expands, it just assigns the variable to itself. Just like a=a. Which will remove the warning, since the variable is used to assign to itself.

// The function that derived class was forced to implement,
// since its pure virtual function defined in base.
void CRabbitDialogDlg::Function( bool Param1, bool Param2 )
{
    // Here Param1 and Param2 are not used which will
    // trigger warning. Now they won't.
    UNREFERENCED_PARAMETER( Param1 );
    UNREFERENCED_PARAMETER( Param2 );
}

2) Comment out the variable names.
Even though UNREFERENCED_PARAMETER() serves the need, its not efficient. isn’t it? It assigns the variable to itself and thus avoids the warning. Well there is another easy method. Just comment out the variable name. Check the code snippet below.

// The function that derived class was forced to implement,
// since its pure virtual function defined in base.
void CRabbitDialogDlg::Function( bool /*Param1*/, bool /*Param2*/ )
{
    // Since the variable name doesn't exist, how compiler can
    // complain that variable is not used. ;)
}


In one of my projects, I was forced write an empty implementation for a pure virtual function in derived class. And my client needs zero compilation warning. At that time I really struggled to remove this warning. :D Now when i shared it with you, it feels good!


Targeted Audiance - Beginners.





How to Rename Namespace?

23 11 2008


Namspaces are introduced to have logical grouping of classes. But as the framework grows you could often find that the namespace length grows which make the usage more difficult.

renamenamespaces

For instance, one namespace i’ve encountered is like this -

namespace Company
{
    namespace Product
    {
        namespace Communication
        {
            namespace Event
            {
                class CEventEx
                {
                };
            };
        }
    };
};

How much I’ve to go inside to address a class? Well, in big frameworks this kind of deep hierarchy is unavoidable. But, its a fact that it causes trouble to developer who uses it. Well, is there any idea to avoid that?


Well, you can rename the namespace to much more smaller one! Have a look at the code snippet below.

// Rename the namespace
namespace ThirdPartyEvent = Company::Product::Communication::Event;
...
// Create the object by using renamed namespace.
ThirdPartyEvent::CEventEx objEvent;


There are still a lot of gems inside C++. isn’t it? ;)


Targeted Audience - Beginners.





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.