Reading and Writing from Windows Registry

The following is an example of reading and writing from Windows Registry using C++. The code have been created based on examples from MSDN. I have provided the MSDN references in the code in case you want to lookup the documentation.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program shows example of reading and writing from registry
#include <windows.h>
#include <iostream>

using namespace
std;

#define WIN_32_LEAN_AND_MEAN

void
writeToRegistry(void)
{

DWORD lRv;
HKEY hKey;

//Check if the registry exists
//http://msdn.microsoft.com/en-us/library/ms724897(VS.85).aspx
lRv = RegOpenKeyEx(
HKEY_CURRENT_USER,
L"Software\\Zahid"
,
0
,
KEY_WRITE,
&
hKey
);


if
(lRv != ERROR_SUCCESS)
{

DWORD dwDisposition;

// Create a key if it did not exist
//http://msdn.microsoft.com/en-us/library/ms724844(VS.85).aspx
lRv = RegCreateKeyEx(
HKEY_CURRENT_USER,
L"Software\\Zahid"
, //"Use Multi-Byte Character Set" by using L
0,
NULL,
REG_OPTION_NON_VOLATILE,
KEY_ALL_ACCESS,
NULL,
&
hKey,
&
dwDisposition
);


DWORD dwValue = 1;

//http://msdn.microsoft.com/en-us/library/ms724923(VS.85).aspx
RegSetValueEx(
hKey,
L"Something"
,
0
,
REG_DWORD,
reinterpret_cast
<BYTE *>(&dwValue),
sizeof
(dwValue)
);


//http://msdn.microsoft.com/en-us/library/ms724837(VS.85).aspx
RegCloseKey(hKey);
}
}


void
readValueFromRegistry(void)
{

//Example from http://msdn.microsoft.com/en-us/library/ms724911(VS.85).aspx

HKEY hKey;

//Check if the registry exists
DWORD lRv = RegOpenKeyEx(
HKEY_CURRENT_USER,
L"Software\\Zahid"
,
0
,
KEY_READ,
&
hKey
);


if
(lRv == ERROR_SUCCESS)
{

DWORD BufferSize = sizeof(DWORD);
DWORD dwRet;
DWORD cbData;
DWORD cbVal = 0;

dwRet = RegQueryValueEx(
hKey,
L"Something"
,
NULL,
NULL,
(
LPBYTE)&cbVal,
&
cbData
);


if
( dwRet == ERROR_SUCCESS )
cout<<"\nValue of Something is " << cbVal << endl;
else
cout<<"\nRegQueryValueEx failed " << dwRet << endl;
}

else

{

cout<<"RegOpenKeyEx failed " << lRv << endl;
}
}


int
main()
{

writeToRegistry();
readValueFromRegistry();
return
0;
}


The output is as follows:

Difference between procedures and functions in C++

In very simple terms in C++ a procedure is a function with return type as void.

Generally speaking we use the term procedure to refer to a routine, like the ones above, that simply carries out some task (in C++ its definition begins with void). A function is like a procedure but it returns a value; its definition begins with a type name, e.g. int or double indicating the type of value it returns. Procedure calls are statements that get executed, whereas function calls are expressions that get evaluated.

A simple program to show the difference as follows:


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program shows difference between functions and procedures
#include<iostream>

using namespace
std;

//function
bool checkIfPositive(int x)
{

if
(x >= 0)
return
true;
return
false;
}


//procedure
void printIfPositive(int x)
{

bool
isPositive = checkIfPositive(x);
if
(isPositive)
cout<<"x is positive and its value is "<<x<<endl;
}


int
main()
{

printIfPositive(3);
printIfPositive(-54);
printIfPositive(710);
return
0;
}


The output is as follows:


Traditional SaaS vs Cloud enabled SaaS

Inspired by Gilad's great summary on the Cloud Programming model, I try to summarize the difference that I observe between the traditional SaaS model and the "cloud-enabled SaaS model". Although cloud providers advocates zero effort is need to migrate existing applications into the cloud, it is my belief that this "strict-port" approach doesn't fully exploit the full power of cloud computing. There are a number of characteristic that cloud is different from traditional data center environment, application which design along these characteristic will take more advantages from the cloud.

I believe a Cloud-enabled-Application should have the following characteristic in its fundamental design.

Latency Awareness

Traditional SaaS App typically run within a single data center and assume low latency among server components. Now in the cloud environment that span many distant geographic locations, but the assumption of low latency cannot hold any more. We need to be “smarter” when choosing where to deploy to avoid the situation of putting frequently communicating components between far-distant locations. “Cloud-enabled SaaS app” need to be aware of latency difference and built in self-configuring and self-tuning mechanism to cope with that.

Cost Awareness

Traditional SaaS app typically run on already purposed hardware where utilization efficiency is not a concern. Now with the “pay as you go” model, application need to pay more attention to its usage pattern and efficiency of underlying resources because it will affect the operation cost. Cloud-enabled SaaS application need to understand the cost model of different resources utilization (such as CPU cost may be very different from Bandwidth cost) and adjust their usage strategy to minimize the operation cost.

Security Awareness

Traditional SaaS app typically run on a fully trusted data center based on perimeter security. But in the Hybrid cloud model, the perimeter being drawn is very different now. Application need to carefully select where to store its data such that sensitivity will not be leaking. This involve careful determination of storage provider or use encryption for protection.

Capitalize on Elasticity

Traditional SaaS App is not used to large-scale growth / shrink of compute resources and typically haven’t designed well to handle how data get distributed to newly joined machines (in a growth scenario) or redistributed among remaining machines (in a shrink scenario). This ends up having a very inefficient use of network bandwidth and results in high cost and low performance. More sophisticated data distribution protocol that align with the growth and shrink dimension is needed for “Cloud-enabled SaaS app”

A Macro Pitfall Question

Assuming that two macros are defined in the following way
#define max1(a,b) a < b ? b : a
#define max2(a,b) (a) < (b) ? (b) : (a)

what would be the value of x in the following cases:
x = max1(i += 3, j);
x = max2(i += 3, j);

and why?

Assume that initial value of i = 5 and j = 7 in both the cases. What is the value of i and j after the Macro?

Answer:
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
In case of max1, x = 12, i = 12 and j = 7. The reason being the substitution will happen like this:
i += 3 < j ? j : i += 3
which using operator precedence rules and language rules means:
i += ((3 < j) ? j : i += 3). Since 3 < 7, i = i + j = 12 which is the same as x.

In case of max2, x = 11, i = 11 and j = 7. The reason being the substitution will happen like this:
(i += 3) < (j) ? (j) : (i += 3). Since 5+3 = 8 which is > 7, i+=3 will be executed again (2nd time) so 5+6 = 11 which is the value of i and x.

Measuring elapsed time in C++ using timeGetTime()

Continuing our theme of Performance Measurement by getting the elapsed time between different instances, today we look at another approach using timeGetTime() method. The code and approach is the same as GetTickCount() case except that the call is replaced.

So whats the difference and which one is better. timeGetTime() has a default resolution of around 5ms but by using the timeBeginPeriod(1) the accuracy can be made upto 1ms. GetTickCount accuracy and jitter cannot be guaranteed. timeGetTime() has more overhead than GetTickCount() so it should not be used in the case where the calls will be frequently made.

Another thing which may be obvious is that GetTickCount() actually calculates the time based on the number of clock interrupts and multiplies it by clock frequency. timeGetTime() reads a field called interrupt time which is updated by Kernel periodically.

Finally, if possible always use QueryPerformanceCounter() as thats better and receommended.



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program shows example of Getting Elapsed Time
#include <iostream>
#include <Windows.h>

using namespace
std;

unsigned long
startTime_;

void
startTime()
{

startTime_ = timeGetTime();
}


unsigned int
calculateElapsedTime()
{

unsigned int
diffInMilliSeconds = timeGetTime() - startTime_;
return
diffInMilliSeconds;
}


int
main()
{

//Increasing the accuracy of Sleep to 1ms using timeBeginPeriod
timeBeginPeriod(1); //Add Winmm.lib in Project
unsigned int diffTime = 0, lastTime = 0, newTime = 0;
startTime();
cout<<"Start Time = "<<calculateElapsedTime()<<endl;

Sleep(100);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 100ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
lastTime = newTime;

Sleep(100);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 100ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
lastTime = newTime;

Sleep(5);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 5ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
lastTime = newTime;

Sleep(50);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 50ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;

timeEndPeriod(1); //Must be called if timeBeginPeriod() was called
return 0;
}


The output is as follows. Notice more reliable and jitter free output:

Measuring elapsed time in C++ using QueryPerformanceCounter()

Yesterday we saw a primitive approach to getting the elapsed time, today we will have a look at the most popular and standard way of getting the elapsed time using QueryPerformanceCounter and QueryPerformanceFrequency approach.

Unlike the GetTickCount approach, which is not very reliable and does not have good resolution, this approach is quite reliable and has very good resolution, often better than a ms. The only problem with this approach used to be that in old systems it may not be very reliable. For example in some old OS (before XP sp2) in case of multiple processors present, and if the clocks of both the processors are not very well synchronised (doe to buggy hardware) then you can get different results each time the QueryPerformanceCounter call is made. Another problem with some chipsets with regards to their power saving is that the frequency changes while we use GetPerformanceFrequency call only once during the program. This can result in incorrect timing being returned. There were some other problems being present as well but they have now all seem to be fixed either in firmware or in the OS. It is recommended that this calls should only be used in OS greater than or equal to Windows XP SP2.




//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program shows example of Getting Elapsed Time
#include <iostream>
#include <Windows.h>

using namespace
std;

LARGE_INTEGER timerFreq_;
LARGE_INTEGER counterAtStart_;

void
startTime()
{

QueryPerformanceFrequency(&timerFreq_);
QueryPerformanceCounter(&counterAtStart_);
cout<<"timerFreq_ = "<<timerFreq_.QuadPart<<endl;
cout<<"counterAtStart_ = "<<counterAtStart_.QuadPart<<endl;
TIMECAPS ptc;
UINT cbtc = 8;
MMRESULT result = timeGetDevCaps(&ptc, cbtc);
if
(result == TIMERR_NOERROR)
{

cout<<"Minimum resolution = "<<ptc.wPeriodMin<<endl;
cout<<"Maximum resolution = "<<ptc.wPeriodMax<<endl;
}

else

{

cout<<"result = TIMER ERROR"<<endl;
}
}


unsigned int
calculateElapsedTime()
{

if
(timerFreq_.QuadPart == 0)
{

return
-1;
}

else

{

LARGE_INTEGER c;
QueryPerformanceCounter(&c);
return
static_cast<unsigned int>( (c.QuadPart - counterAtStart_.QuadPart) * 1000 / timerFreq_.QuadPart );
}
}


int
main()
{

//Increasing the accuracy of Sleep to 1ms using timeBeginPeriod
timeBeginPeriod(1); //Add Winmm.lib in Project
unsigned int diffTime = 0, lastTime = 0, newTime = 0;
startTime();
lastTime = calculateElapsedTime();
cout<<"Start Time = "<<lastTime<<endl;

Sleep(100);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 100ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
lastTime = newTime;

Sleep(100);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 100ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
lastTime = newTime;

Sleep(5);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 5ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
lastTime = newTime;

Sleep(50);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 50ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;

timeEndPeriod(1); //Must be called if timeBeginPeriod() was called
return 0;
}


The output is as follows:

Measuring elapsed time in C++ using GetTickCount()

There are variety of ways to obtain the elapsed time in a program. We will look at some of the ways in the next few posts. The first approach is using the GetTickCount() method. It should be mentioned that this method is not very accurate and some people have gone to the extent of saying that this should be deleted from the standards. Nevertheless it is quite widely used for cases where high resolution is not required.




//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program shows example of Getting Elapsed Time
#include <iostream>
#include <Windows.h>

using namespace
std;

unsigned long
startTime_;

void
startTime()
{

startTime_ = GetTickCount();
}


unsigned int
calculateElapsedTime()
{

unsigned int
diffInMilliSeconds = GetTickCount() - startTime_;
return
diffInMilliSeconds;
}


int
main()
{

//Increasing the accuracy of Sleep to 1ms using timeBeginPeriod
timeBeginPeriod(1); //Add Winmm.lib in Project
unsigned int diffTime = 0, lastTime = 0, newTime = 0;
startTime();
cout<<"Start Time = "<<calculateElapsedTime()<<endl;

Sleep(100);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 100ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
lastTime = newTime;

Sleep(100);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 100ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
lastTime = newTime;

Sleep(5);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 5ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
lastTime = newTime;

Sleep(50);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 50ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;

timeEndPeriod(1); //Must be called if timeBeginPeriod() was called
return 0;
}


The output is as follows:

Check out this stream