Latest Entries »

warning image

It is a good programming practice –   if you optimize your source code , handle all type of memory leaks, remove the warnings,  document your code , provide better spacing, etc.

This provides another one to look into your code so easily.

Today, let me discuss something about WARNINGS..🙂

  • You can disable all the compiler warning using the compiler switch /w : Oh no.. this is so dangerous, and i think, this is a bad programming practice.
  • You can treat all warnings as errors using the switch /WX. : This is nice programming.. but it takes a lot of precious time to complete your app.
  • using /Wdn, you can disable the specified warning..

The default warning level for VS 2008 is Level 3, (i think so), but MSDN says

For a new project, it may be best to use /W4 in all compilations. This will ensure the fewest possible hard-to-find code defects. cool..🙂

suppose in a function like,

int DumpMe(int nCount, int nMode)
{
    return nCount++;
}

here, we are not using the variable nMode now, but at a later version of your app, you are going to use the nMode.

During compilation, definitely, you will  get the warning

warning C4100: 'nMode' : unreferenced formal parameter (if the warning level is 4)

Here to avoid that warning message, you can use 2 ways.

1. comment the nMode variable. like

int DumpMe(int nCount, int /*nMode*/)

2. Use the UNREFERENCED_PARAMETER macro. like

UNREFERENCED_PARAMETER(nMode);

It’s just to suppress the warning – and the compiler will optimize it out since the code doesn’t do anything.

– For vctipsplusplus,

BIJU

Do you know how to add RTCI support to your class?
  • Derive the class from CObject.

class CSimple : public CObject

{

};

  • Use the DECLARE_DYNAMIC macro in your class declaration, as shown here:
class CSimple : public CObject
{
DECLARE_DYNAMIC( CSimple )
};
  • Use the IMPLEMENT_DYNAMIC macro in the implementation file (.CPP) of your class. This macro takes as arguments the name of the class and its base class, as follows:
IMPLEMENT_DYNAMIC(CSimple, CObject )
for vctipsplusplus,
BijU
“We cannot have everything in life, but God is aware and is generous to give what we need.”

Do you know how to add RTCI support to your class?
Derive the class from CObject.

class CSimple : public CObject{
};Use the DECLARE_DYNAMIC macro in your class declaration, as shown here:class CSimple : public CObject{DECLARE_DYNAMIC( CSimple )};Use the IMPLEMENT_DYNAMIC macro in the implementation file (.CPP) of your class. This macro takes as arguments the name of the class and its base class, as follows:IMPLEMENT_DYNAMIC(CSimple, CObject )for vctipsplusplus,BijU”We cannot have everything in life, but God is aware and is generous to give what we need.”

Search for a file

The _searchenv routine searches for the target file in the specified domain. The varname variable can be any environment or user-defined variable that specifies a list of directory paths, such as PATH, LIB, and INCLUDE.

The routine searches first for the file in the current working directory. If it does not find the file, it looks next through the directories specified by the environment variable. If the target file is in one of those directories, the newly created path is copied into pathname. If the filename file is not found, pathname contains an empty null-terminated string.

(c)MSDN

Gone are the days of my past,
Gone are the days of my childhood innocence,
Gone are the days of my first and last.
Gone are the days of being carefree,
Gone are the days of my elation,
Gone are the days of my glee.
Gone are the days of my fear.
Gone are the days of savor.
Gone are the days I spent here.

Gone, Gone, Gone are the days
And I fear
It’s becoming more clear!

Shell Path Handling functions..🙂

On my career start, I worked a lot with windows folders,files etc..like, creating folder/files,  copying file from one location to another, rename folders/files, verify the given name is a file or folder like that.

For doing such things, at that time, I regularly used the basic file handling functions in MFC or Win32 and most of the processing are done with the very familiar CString class.

By ‘processing’ means adding or removing the back slash character, adding the filename at the end of a path name, adding a file extension etc🙂

Now i’m used with some Shell Path functions.. http://msdn.microsoft.com/en-us/library/bb773559(VS.85).aspx

here are some quite interesting shell functions and their description from MSDS

  1. PathAddBackslash- Adds a backslash to the end of a string to create the correct syntax for a path. If the source path already has a trailing backslash, no backslash will be added.
  2. PathCompactPath-Truncates a file path to fit within a given pixel width by replacing path components with ellipses.
  3. PathGetDriveNumber-Searches a path for a drive letter within the range of ‘A’ to ‘Z’ and returns the corresponding drive number.
  4. PathRemoveExtension-Removes the file extension from a path, if one is present

and a lot more..🙂

for VCTips++

BijU

Contentment is not the fulfillment of what you want, but the realization of how much you already have.

Loop Unrolling

Consider the following code:
int *buff = new int[3];
for (int i =0; i<3; i++)
buff[i] = 0;
This loop is inefficient:🙂
On every iteration, it assigns a value to the next array element. However,precious CPU time is also wasted on testing the counter and incrementing the counter’s value and performing a jump statement. To avoid this overhead, the compiler can unroll the loop into a sequence of three assignment statements, as follows:
buff[0] = 0;
buff[1] = 0;
buff[2] = 0;

for https://vctipsplusplus.wordpress.com/

BijU

If your actions inspire others to dream more, learn more, do more and become more, you are a leader

ODBC and Visual C++

Hi All,

The number of  database applications done by using Visual C++ is very less compared to other languages like VB, C#, ASP, Java etc. (Hope you agree with me😉 ).

Here I’m explaining steps for doing a database application using Visual C++/My SQL /ODBC.

ODBC is a call-level interface that allows applications to access data in any database for which there is an ODBC driver. Using ODBC, you can create database applications with access to any database for which your end user has an ODBC driver. ODBC provides an API that allows your application to be independent of the source database management system (DBMS).(C)MSDN

Step 1. You must include <sqlext.h> and link to ODBC32.LIB When creating an application that uses the ODBC C API.

Step 2. Establish a connection using a connection string that contains the data source name, user IDs, passwords, and other information required by the data source.

a sample connection string is look like this

DRIVER=MySQL ODBC 5.1 Driver;SERVER=”localhost”;PORT=3306;DATABASE=”MyDataBase”;UID=”DBUser”;PWD=”DBUserPwd”;

Step 3. Allocate the different ODBC handles and set different attributes

    • Allocate the ODBC environment by SQL_HANDLE_ENV using the method SQLAllocHandle()
    • Set the ODBC version environment attribute using SQLSetEnvAttr()
      • for eg: SQLSetEnvAttr( m_hSqlEnv, SQL_ATTR_ODBC_VERSION, (void*) SQL_OV_ODBC3, 0 );
    • Allocate the connection handle by SQL_HANDLE_DBC using the method SQLAllocHandle()

Step 4. Connect to the data source by using the connection string and method SQLDriverConnect()

Now you established a connection with the database.🙂

Now, we are trying to retrieve the data.

Step 5. Allocate the ODBC statement handles by SQL_HANDLE_STMT

Step 6. Execute the prepared statement using SQLExecDirect()

for eg: SQLExecDirect(m_hSqlStmt, (SQLTCHAR*)szQuery, SQL_NTS)

  • Some Tips :
    • You can get the number of COLUMNS in the result set using the method SQLNumResultCols()
    • also the number of ROWS by using SQLRowCount()

Step 7.  Fetch the data result set using SQLFetch()

Step 8. Read the data using SQLGetData();

    • for eg: SQLGetData(m_hSqlStmt, 1, SQL_C_TCHAR, m_szName, 255, &cbName);

Step 9. Close the Connection using SQLDisconnect() and then free the different allocated handles usingSQLFreeHandle().

For vctipsplusplus,

BijU..

To acquire knowledge, one must study; but to acquire wisdom, one must observe

Implementing a COM interface means that the object uses code that implements each method of the interface and provides COM binary-compliant pointers to those functions to the COM library. COM then makes those functions available to any client who asks for a pointer to the interface, whether the client is inside or outside of the process that implements those functions.

Windows Privileges Issues !!

A very interesting tip..
For my current project, I need to set the system time with some reference time. Quite easy!!. The SetSytemTime (). The syntax is like this
BOOL WINAPI SetSystemTime(
__in          const SYSTEMTIME* lpSystemTime
);
The time must be in the form of SYSTEMTIME struct.  And I implement it in my code as
SYSTEMTIME st = NewTime;
bSuccess = SetSystemTime(&st);
🙂. The problem is on the way.
The SetSystemTime function enables the SE_SYSTEMTIME_NAME privilege before changing the system time. This privilege is disabled by default. (©MSDN)
for changing the privileges, we need to implement some authorization functions. In the following order
1-  OpenProcessToken() – opens the access token associated with a process
2-  LookupPrivilegeValue() – Retrieves the locally unique identifier (LUID) used on a specified system to locally represent the specified privilege name
3-   AdjustTokenPrivileges()-enables or disables privileges in the specified access token.
After that, change the system time with SetSystemTime() method.
Then again reset the privileges by using the function AdjustTokenPrivileges().
It works well in WindowsXP. No problems for setting the new time.  J
But , the problem comes from Windows 7 and Windows Vista.
Then, I start debugging my code in Windows 7. All authorization functions works fine for me.  Like OpenProcessToken(),LookupPrivilegeValue() and AdjustTokenPrivileges(). But I felt something bad about the execution of the last method. AdjustTokenPrivileges()..
I checked the GetLastError() return value. Instead of ERROR_SUCCESS
, it returns ERROR_NOT_ALL_ASSIGNED J
So my investigation is now in that way. How to handle that? Its all because of UAC (User Access Control) problems. Because the SE_SYSTEMTIME_NAME require administrative privilege.
My colleague gave me a tip about Manifests.
The description from MSDN is like Manifests are XML files that accompany and describe side-by-side assemblies or isolated applications. Manifests uniquely identify the assembly through the assembly’s <assemblyIdentity> element. They contain information used for binding and activation, such as COM classes, interfaces, and type libraries, that has traditionally been stored in the registry. Manifests also specify the files that make up the assembly and may include Windows classes if the assembly author wants them to be versioned. Side-by-side assemblies are not registered on the system, but are available to applications and other assemblies on the system that specify dependencies in manifest files.
Manifest files enable administrators and applications to manage side-by-side assembly versions after deployment. Every side-by-side assembly must have a manifest associated with it. The installation of Windows XP installs the supported Microsoft side-by-side assemblies with their manifests. If you develop your own side-by-side assemblies, you must also install manifest files
I turn on the manifests for my application also. Its very simple.
Project Settings > Linker > Manifest File.
And make the options as indicated in the figure.
Including manifest for project
The Rebuild All  and Execute..
🙂
BijU
Gravity is not responsible for people to fall in love. It just happens.

A very interesting tip..

For my current project, I need to set the system time with some reference time. Quite easy!!. Using SetSytemTime (). The syntax is like this

BOOL WINAPI SetSystemTime(

__in          const SYSTEMTIME* lpSystemTime

);

The time must be in the form of SYSTEMTIME struct.  And I implement it in my code as

SYSTEMTIME st = NewTime;

bSuccess = SetSystemTime(&st);

🙂. The problem is on the way.

The SetSystemTime function enables the SE_SYSTEMTIME_NAME privilege before changing the system time. This privilege is disabled by default. (©MSDN)

for changing the privileges, we need to implement some authorization functions. In the following order

1-  OpenProcessToken() – opens the access token associated with a process

2-  LookupPrivilegeValue() – Retrieves the locally unique identifier (LUID) used on a specified system to locally represent the specified privilege name

3-   AdjustTokenPrivileges()-enables or disables privileges in the specified access token.

After that, change the system time with SetSystemTime() method.

Then again reset the privileges by using the function AdjustTokenPrivileges().

It works well in WindowsXP. No problems for setting the new time.  :) But , the problem comes from Windows 7 and Windows Vista.

Then, I start debugging my code in Windows 7. All authorization functions works fine for me.  Like OpenProcessToken(),LookupPrivilegeValue() and AdjustTokenPrivileges(). But I felt something bad about the execution of the last method. AdjustTokenPrivileges()..

I checked the GetLastError() return value. Instead of ERROR_SUCCESS, it returns ERROR_NOT_ALL_ASSIGNED J

So my investigation is now in that way. How to handle that? Its all because of UAC (User Access Control) problems. Because the SE_SYSTEMTIME_NAME require administrative privilege.

My colleague gave me a tip about Manifests.

The description from MSDN is like Manifests are XML files that accompany and describe side-by-side assemblies or isolated applications. Manifests uniquely identify the assembly through the assembly’s <assemblyIdentity> element. They contain information used for binding and activation, such as COM classes, interfaces, and type libraries, that has traditionally been stored in the registry. Manifests also specify the files that make up the assembly and may include Windows classes if the assembly author wants them to be versioned. Side-by-side assemblies are not registered on the system, but are available to applications and other assemblies on the system that specify dependencies in manifest files.

Manifest files enable administrators and applications to manage side-by-side assembly versions after deployment. Every side-by-side assembly must have a manifest associated with it. The installation of Windows XP installs the supported Microsoft side-by-side assemblies with their manifests. If you develop your own side-by-side assemblies, you must also install manifest files

I turn on the manifests for my application also. Its very simple.

Project Settings > Linker > Manifest File. And make the options as indicated in the figure.

Project Settings>Linker Options > Manifest

Project Settings>Linker Options > Manifest

Including manifest for project

The Rebuild All  and Execute..

🙂

for https://vctipsplusplus.wordpress.com/

BijU

Gravity is not responsible for people to fall in love. It just happens.

Environment variable are variables that can be available to all running programs.  You can access the environment variables using Control Panel > System > Advanced > Environment Variables (Lot of other methods are also available🙂 )

Environment Variables

Environment Variables

Environment Variables

Environment Variables

In Windows Registry, you can locate them on HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\ Control\ Session Manager\ Environment.

Some of the Environment Variables are TEMP, TMP, OS etc.

A number of situations may come during the coding phase to access those variables. For eg: getting the temp folder name, system folder name, lib path, include path etc.

We can access those items from environment variables using the following commands.

ExpandEnvironmentStrings()  – function expands environment-variable strings and replaces them with their defined values.

and ExpandEnvironmentStringsForUser()-function expands the source string by using the environment block established for the specified user.

Like this

CString strErrorMsg = _T(“”);

TCHAR szEnvPath[MAX_PATH];

DWORD dwLen = 0;

dwLen = ::ExpandEnvironmentStrings( _T(“%MSDevDir%”), szEnvPath, MAX_PATH );

if( 0 == dwLen)

{

// ExpandEnvironmentStrings() failed

strErrorMsg = _T(“Cannot Expand using ExpandEnvironmentStrings()”);

}

Now the value for the MSDevDir is in the szEnvPath variable.🙂

for https://vctipsplusplus.wordpress.com/

BijU

Every day you waste is one you can never make up

Turn Off your Monitor Display !!

On Off Switch

Image Source: http://thumbs.dreamstime.com/thumb_76/1154983417etR5O8.jpg

Nowadays, I’m experimenting with some hardware and Windows🙂.I’m very happy to work with this. Because, after a lot of reading and googling, doing some coding. Then again, reading a lot of documents🙂

A very interesting thing in doing this type of coding is that, we don’t get  much information from MSDN😀. Almost all information is available in the MSDN, but it’s up to you to find the best algorithm/class/technology that fit for you.

Yesterday, I tried a lot to get the information from our Desktop Monitor. My aim was to ON/OFF our Desktop Monitor. I have hands on experience with WMI (Windows Management Instrumentation) to query the details like motherboard, disks, Operating System etc. With that confidence I first look into the Win32_DesktopMonitor. And in that a method named SetPowerState() is available. And the information about that method give me immense pleasure.

Its like “The SetPowerState method sets the desired power state for a logical device and when a device should be put into that state. And the power state may have the following values, like(from MSDN)

1 Full power.
2 Power save — low-power mode.
3 Power save — standby.
4 Power save — other.
5 Power cycle.
6 Power off.

I’m very happy after reading this document.  Unfortunately, its not implemented by windows. Due to a lot of technical problems.

So..

But using the very common message like SendMessage can solve the problem so easily.

Just copy the below statement and execute..

SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, (LPARAM)2);

Hope you are familiar with first 2 params. Documentation from the  MSDN for the 3rd param is

SC_MONITORPOWER Sets the state of the display. This command supports devices that have power-saving features, such as a battery-powered personal computer.

And the 4th param may take the values like

-1 – the display is being on

1 – the display is going to low power

2 – the display is being shut off

I think it is so simple. Thanks to Microsoft..🙂

for https://vctipsplusplus.wordpress.com/

BijU

God won’t ask about the fancy clothes in your wardrobe, but will ask how many of those clothes helped the needy.