Wednesday, December 22, 2010

Get Network status

Tip -
Get Network status Using System Event Notification Service (SENS) and Windows Management Instrumentation(WMI)


SENS or WMI can be used in applications to get the status of a local system, whether it is connected or disconnected to/from a network( LAN/WAN).
- Get Network status
- Notify you when local system is connected/disconnected  to/from a network

SENS APIs will not work in crossover cable network, where WMI will work both in LAN/WAN and cross-cable network.
   (crossover cable is a type of Ethernet cable used to connect computing devices together directly where they would normally be connected via a network switchhub or router,
     such as directly connecting two personal computers via their network interface controllers.)

The System Event Notification Service (SENS) now provides  a unique set of connectivity functions and notifications  in the operating system, creating a uniform connectivity and notification interface for applications.
          - Get Network status
   The IsNetworkAlive function determines whether or not a local system is connected to a network, and identifies the type of network connection.

- Notify you when local system is connected/disconnected  to/from a network
   If applications want to be notified when local system is connected or disconnected to/from a network, we can use  ISensNetwork interface of SENS.
   The following methods of ISensNetwork interface will be notified when local system is connected or disconnected  to/from a network.
   ConnectionMadeNoQOCInfo ()

2. WMI
WMI(Windows Management Instrumentation) is a new management technology allowing scripts to monitor and control managed resources throughout the network.
          - Get Network status
The IWbemServices interface is used by clients and providers to access WMI services.
The interface is implemented by WMI and WMI providers, and is the primary WMI interface.
  We can use  IWbemServices::ExecQuery() to get the current network status.
  The following query string can be used to get the current network status
             SELECT NetConnectionStatus FROM Win32_NetworkAdapter WHERE NetConnectionID  = 'Local Area Connection’

- Notify you when local system is connected/disconnected  to/from a network
IWbemObjectSink::Indicate() method  of WMI will automatically invoked whenever network connection is established or dropped.
IWbemServices::ExecNotificationQueryAsync() method on WMI will be called for subscribing the network connection and drop notifications.
The following query string can be used to get the notifications
            SELECT * FROM MSNdis_StatusMediaConnect
SELECT * FROM MSNdis_StatusMediaDisconnect

WMI is slow to query data and if you are trying to use it during start up it can delay you starting as the WMI service takes a long time to come up.
However, WMI information is richer, as in you need to sometimes make several API calls to get the same amount, some information is a lot easier to get at and the filtering syntax can dramatically reduce the amount code you have to write.
If speed isn't a massive issue, it is better to lean towards WMI.

You can check the WMI query using wbemtest.exe tool. (
Click Start, click Run, and then type wbemtest.exe.

Reference   -

Examples are available in

Posted By :Ajay Kumar S.

C++ Debugger Tips: Special expression and format specifiers

[  Tip  ]
There are special expression and format specifiers that you can use to better examine the content in the debugger's watch windows.

Visual Studio's (native) C++ debugger has many useful features that can make your debugging much more pleasant, if you know what they are.

1.  by, wo, and dw operators
    For example, say we break after the following bit of code:
         int i = 0x12345678;
    You can use the by, wo, and dw operators to view contents of a variable as an unsigned byte, word, or dword:
          i                 0x12345678             int
          by i            0x78 'x'                    unsigned char
          wo i           0x5678                    unsigned short
          dw i           0x12345678            unsigned long

    You can also use the operators on a register to do the same to the destination of the register: 
         eax 0x0012ff2c                       unsigned long
          by eax       0x78 'x'                 unsigned char
          wo eax      0x5678                 unsigned short
          dw eax      0x12345678         unsigned long
      These come in handy when debugging through assembly.

    Another way to change debugger output is through format specifiers.  These are directives passed after the expression, separated by a comma.
    For example, to change the radix out the output, you can append ',o' for octal, ',d' for decimal, or ',x' for hex:
          i       42                                  int
          i,o     052                              int
          i,d     42                                int
          i,x     0x0000002a                 int

3.  s, s8 ,su  operators
    To interpret a pointer expression as a string, you can use ',s' for an simple null-terminated string, ',s8' for a UTF-8 string, or ',su' for a Unicode string.
    (Note that the expression has to be a pointer type for this to work).

          char str[] = "hello";
          wchar_t str2[] = L"world";

    str                          0x0012ff00 "hello"                        char [6]
          str,s                        "hello"                                            char [6]
          str2                         0x0012fee8 "world"                     wchar_t [6]
          (void*)str2,su      "world"                                           void *

4.  m, mb, mw, md, mu, mq, ma  operators
    The memory operators can be used to display up to 64 bytes of memory in the preview line, as bytes, words, dwords, quads, or ascii characters. 
     str,m          0x0012ff00   68 65 6c 6c 6f 00 cc cc cc cc cc cc cc cc cc cc  hello.                   char [6]
       str,mb        0x0012ff00    68 65 6c 6c 6f 00 cc cc cc cc cc cc cc cc cc cc  hello.                   char [6]
       str,mw       0x0012ff00    6568 6c6c 006f cccc cccc cccc cccc cccc                                      char [6]
       str,md        0x0012ff00    6c6c6568 cccc006f cccccccc cccccccc                                          char [6]
       str2,mu      0x0012feec    0077 006f 0072 006c 0064 0000 cccc cccc  world.??              wchar_t [6]
       str,mq        0x0012ff00    cccc006f6c6c6568 cccccccccccccccc                                            char [6]
       str,ma         0x0012ff00    hello.(..(......T..                                                                     char [6]

5.  wc, wm, hr operators
    You can use ,wc ,wm and ,hr to view data as a window class, window message, or HRESULT.

       0x00400000,wc     WS_OVERLAPPEDWINDOW                                                   int
       0x10,wm               WM_CLOSE                                                                                   int
       0x10,hr                 0x00000010 The directory cannot be removed.                              Int

6.  !  operator
    You can use ,! to turn off STL visualizations on the expression:

      str       "hello world"                                                                                                       std::basic_string< ... >
       str,!     {_Bx={...} _Mysize=0x0000000b _Myres=0x0000000f}                               std::basic_string<...>

All of these operators can be used to ease the way you get to data while debugging, and become necessary when creating custom visualizations.
You can check-out the autoexp.dat file in your Visual Studio directory for examples of how to combine these operators and the visualization language to create custom visualizers for your own data.

Reference         -

Posted By :Ajay Kumar S.

Visual Studio's pseudo-registers

Tip -
Visual Studio's pseudo-registers

Details -
   Open up the watch window and type in "@err" (without quotes) - This will give you the numeric value of the error code
   Open up the watch window and type in "@err,hr” (without quotes) - To get the useful text right there in the watch window

2. Expanding Pointers
There is an easy way in the watch window to expand pointers however far you want. Simply do the following when you have the pointer in your watch window
           Where x is any integer value >= 0. Note if x = 0, it behaves like the standard expansion.

 What if you had an array of 100 or even a thousand and you only wanted to look at a portion of it? Well that too is possible.
       (pMyPointer + x),y
           Where x is the offset from the base address you want to seek to. x is any integer value and y again is any integer value >= 0. Note x can be negative.

No smart expansions on custom classes. Whenever you use a certain structs/classes you will often get "smart" expansion in the watch window. The POINT struct is a good example of this. Wouldn't it be nice if we could get the same smart expansions for our own classes? We can, and it turns out to be very simple. There is a file called "autoexp.dat" in Common\MSDev98\Bin. You can open up the file in notepad and instantly see how you can add your own expansions to it. A simple example for a class named Vector3D would be:
; Comment can go here
Vector3D =<m_x>, <m_y>, <m_z>
Then when you place a variable of that type in the watch window you get a nice formatted output without having to expand it out manually.

4.Simple method of timing instructionsThis tip isn't really a solution to some great problem, but is still very useful. Everyone should use profilers to inspect functions and locate bottlenecks in their code but there is a quick and dirty way to see how long instructions or functions take while debugging. We will use another pseudo-register for this. We use the “@clk” register. This is a clock register that is only available in the watch window when debugging. With the use of a clever trick we can get timings for each step we take while debugging. If we put @clk in the watch window chances are it will display a rather large number. Then each time we step over a statement, it will grow in size. We could subtract off the previous clk value and then we'd have our value for that step. However, we know that the watch window gets evaluated from top to bottom so we can use a trick. On one line we will put @clk just like normal. Then on the line directly below that we put "@clk = 0". This will set the register to zero thus resetting it for the next instruction. That's all there is to it. You can use this as a simple way to time things.

Reference         -

Posted By :Ajay Kumar S.

Guidelines for Better Coding Style

Tip - 

1. Rules of binding references to rvalues.
2. The notion of comma-separated expressions .

Details -
1. Binding a Reference to an Rvalue
Rvalues and lvalues are a fundamental concept of C++ programming. In essence, an rvalue is an expression that cannot appear on the left-hand side of an assignment expression. By contrast, an lvalue refers to an object (in its wider sense), or a chunk of memory, to which you can write a value. References can be bound to both rvalues and lvalues. However, due to the language's restrictions regarding rvalues, you have to be aware of the restrictions on binding references to rvalues, too.
Binding a reference to an rvalue is allowed as long as the reference is bound to a const type. The rationale behind this rule is straightforward: you can't change an rvalue, and only a reference to const ensures that the program doesn't modify an rvalue through its reference. In the following example, the function f() takes a reference to const int:

void f(const int & i);
int main()
 f(2); /* OK */

The program passes the rvalue 2 as an argument to f(). At runtime, C++ creates a temporary object of type int with the value 2 and binds it to the reference i. The temporary and its reference exist from the moment f() is invoked until it returns; they are destroyed immediately afterwards. Note that had we declared the reference i without the const qualifier, the function f() could have modified its argument, thereby causing undefined behavior. For this reason, you may only bind references to const objects.
2. Comma-Separated Expressions
Comma-separated expressions were inherited from C. It's likely that you use such expressions in for- and while-loops rather often. Yet, the language rules in this regard are far from being intuitive. First, let's see what a comma separated expression is.
An expression may consist of one or more sub-expressions separated by commas. For example:
if(++x, --y, cin.good()) /*three expressions*/
The if condition contains three expressions separated by commas. C++ ensures that each of the expressions is evaluated and its side effects take place. However, the value of an entire comma-separated expression is only the result of the rightmost expression. Therefore, the if condition above evaluates as true only if cin.good() returns true. Here's another example of a comma expression:
int j=10;
int i=0;
while( ++i, --j)
 /*..repeat as long as j is not 0*/

Reference         -

Posted By :Ajay Kumar S.

Tuesday, December 21, 2010

Preventing Memory Fragmentation

Tip -
Frequent allocation and deallocation of dynamic memory leads to heap fragmentation,  especially if the application is running for long periods and allocates small memory chunks

Details -
Applications that are free from memory leaks but perform dynamic memory allocation and deallocation frequently tend to show gradual performance degradation if they are kept running for long periods. Finally, they crash. Why is this? Recurrent allocation and deallocation of dynamic memory causes the heap to become fragmented, especially if the application allocates small memory chunks. A fragmented heap can have many free blocks, but these blocks are small and non-contiguous. To demonstrate this, look at the following scheme that represents the system's heap. Zeros indicate free memory blocks and ones indicate memory blocks that are in use:

The above heap is highly fragmented. Allocating a memory block that contains 5 units (i.e., 5 zeros) will fail, although the systems has 12 free units in total. This is because the free memory isn't contiguous. On the other hand, the following heap has less free memory but it's not fragmented:

What can you do to avoid heap fragmentation? First of all, use dynamic memory as little as possible. In most cases, you can use static or automatic storage instead of allocating objects dynamically. Secondly, try to allocate large chunks rather than small ones. For example, instead of allocating a single object, allocate an array of objects at once, and use these objects when they are needed. If all these tips don't solve the fragmentation problem, you should consider building a custom memory pool.

Reference         -

Posted By :Ajay Kumar S.

Wednesday, December 15, 2010

Allocate object at predefined memory

Tip                   :   Placement new technique: You can decide on which memory address your class object to be allocated.
Details          :    Usually we use new operator to allocate objects. The new operator will allocate memory for object and calls the object’s constructor. We can construct our object in predefined memory location by using Placement new.
In placement new, you can pass the preferred memory location to the new operator at which the object to be constructed. During placement new, the new operator just calls the constructor. Responsibility of memory allocation is ours. After usage we should call the destructor manually to delete the object. Please see the following code block about usage of placement new, which is self explanatory.

The advantages of placement new are as follows -
1) We can allocate a pool of memory/block and construct objects on our wish.
2) This prevents memory allocation failure fear in runtime, because pool of memory is already allocated.
3) Object creation will be a bit faster, because memory is already allocated and only the constructor is to be called.
4) Since you can place your objects at your preferred memory locations, it is very useful in embedded programming. For instance the hardware may be placing 255 bytes of data at memory location – 0×1000. In that case, write a class with an array of 255 Bytes as member variable and construct the object at 0×1000. Now you can access the data by using that object.

And one more interesting information – The placement new is the only scenario in which we are legally allowed to call destructor explicitly as per C++ standards. The new ‘New’ information is interesting.. right..? J

Reference    :

Posted By :Krishnaraj S.

CMirrorFile - MFC class not found in documentation

Tip :   CMirrorFile class can write, delete a file. But if you wish you can rollback the changes at any point before committing.
Details :  In CMirrorFile, you can open a file like CFile and you can do as many operations. All the changes will be committed only if you call CMirrorFile::Close(). If you want to rollback the changes, then call CMirrorFile::Abort(). See the code snippet.

Actually when we open a file using CMirrorFile, It is really creating a temporary file. All the further changes that you apply is updated to the temporary file copy. When you call Close(), CMirrorFile, updates the temporary file copy, then replaces the master file with temporary file by using api – ReplaceFile(). When you call Abort(), CMirrorFile just deletes that temporary copy of file.
Cool! You can use CMirrorFile, if you want to do several operations without damaging the main file and can commit only if you need or else you are free to rollback at any point.

Reference    :

Posted By :Krishnaraj S.

Tuesday, December 7, 2010

CRT Debug support: Memory values

Tip - Debug heap will fill some values in memory which is managed. By checking the memory values of an address, we are able to identify the characteristic of memory allocation details.

Details - Memory corruptions are every programmer’s nightmare. But Debug Heap provides some facility in debug build to help you to get rid of those memory corrupting problems. Depending to the type of memory allocation we have done, the debug heap will fill some magic value for the allocated memory contents. Take care that, this will be available only in debug build. Please see below.
1.     0xCD – The memory locations filled with this magic number are allocated in heap and is not initialized.
2.     0xFD – This magic number is known as “NoMansLand”. The debug heap will fill the boundary of the allocated memory block will this value. If you are rewriting this value, then it means, you are beyond an allocated memory block.
3.     0xCC – The memory locations filled with this magic number means, it’s allocated in stack but not initialized. You can see this when you a variable on stack and look at its memory location. You can use /GZ compiler option to get the same feature in release build.
4.  0xDD – The memory locations filled with this magic number are Released heap memory.  But when I checked I am getting 0xEEFE(freed memory pattern) always instead of 0xDD.

Reference    :

Posted By :Krishnaraj S.

Memory Leak Detection and Isolation - Part2: Set Breakpoints on a Memory Allocation Number

Tip - To identify which allocation in code causing memory allocation even we know line number and function name.
Details - Sometimes you know the line number and function name of the code which cause memory leak. But it can be executed several times and often it is difficult to track which and when allocation cause memory leak. The piece of information that allows you to do this is the memory allocation number. This is the number that appears in braces after the filename and line number when those are displayed. For example, in the following output, the memory allocation number is 109. It means that the leaked memory is the 109th block of memory allocated in your program.
The CRT library counts all memory blocks allocated during execution of the program, including memory allocated by the CRT library itself or by other libraries such as MFC. Therefore, an object with allocation number N will be the Nth object allocated in your program but may not be the Nth object allocated by your code. (In most cases, it will not be.)
If you can set the break point at the memory allocation number in you program, your debugger can break the execution at particular break point and is able to debug wisely to track the memory leak.

Fortunately CRT library provides you the methods to set break point at  memory allocation number. Two methods are described below.

Using _CrtSetBreakAlloc():
Call _CrtSetBreakAlloc(AllocationNumber); in your code.

Using Watch window of visual studio debugger:
Type ‘_CrtSetBreakAlloc’ in the name field of watch window. Type ‘{,,msvcr71d.dll}_crtBreakAlloc’ for multithreaded dll version of CRT library(/MD option).
After debugger evaluate the expression, edit the value field with memory allocation number to set the breakpoint.

Reference    :

Posted By :Krishnaraj S.

Memory Leak Detection and Isolation - Part1: Enabling MemoryLeakDetection

Tip - Visual Studio debugger and C run-time (CRT) libraries provide you with effective means for detecting and identifying memory leaks.
Details -The primary tools for detecting memory leaks are the debugger and the C Run-Time Libraries (CRT) debug heap functions.
To enable the memory leak detection on heap, add following piece of code in your program. For this make sure that your code is _DEBUG enabled.
#include <stdlib.h>
#include <crtdbg.h>
Next step is to insert _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ) to your main function of your application.
Now your application is ready to detect memory leak and it will display the logs in output window of your debugger or use Dbgview.exe . For release version, you required to enable _DEBUG preprocessor. A sample log look like as below.

Technique behind this is to use _malloc_dbg() and _free_dbg() instead of malloc() and free(). So that it is able to keep track of memory allocation and deletion. When we use CRT debug methods, compiler will use _malloc_dbg() and _free_dbg() for heap managing.
Note: You can manually dump the log using _CrtDumpMemoryLeaks() API. But remember that the destructors for any variables you declared at runtime (i.e. any variables declared not using the 'new' operator) have *NOT* been called yet. This makes the memory holding these variables look like leaked memory when in fact the memory will be cleaned up just prior to program exit. So highly recommended method is to use _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
Reference    :

Posted By :Krishnaraj S.