Saturday, August 2, 2008

Hello World - c++ Windows Application

In this post I'm going to explain the details of writing a hello world program for windows. To start we should look at the version for a console application:


#include <iostream&rt;
using namespace std;
void main() {
cout << "Hello World" << endl;
}


For windows it isn't much different. But instead of declaring a main we need to instead declare a WinMain.


#include <windows.h&rt;

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShowCmd) {
MessageBox(NULL,L"Hello World",L"MyCaption",MB_ICONINFORMATION | MB_OK);
}


1. We include windows.h to give us access to the windows library functions.

2. The keyword WINAPI instructs the program to reverse the argument list. For our purposes this doesn't matter but under the hood windows needs this.

3. HINSTANCE is a handle to an instance. The main program receives a instance to itself (hinstance) and a handle to a previous instance of the same program. The previous instance is legacy and is NULL for modern applications. But is still provided for legacy code.

4. lpCmdLine is the entire command string that was used to execute the program.

5. nCmdShowCmd are options indicating how the window should open.

6. Once our method is called we can then call MessageBox to display the message.

We can now look into the MessaegBox command in more detail. The signature for the command is:


int MessageBox(HWND hWnd,
LPCTSTR lptext,
LPCTSTR lpcaption,
UINT utype);


The first argument HWND, is a handle to the window the created this message box. In our case we haven't created a window, so we supply NULL which instructs Windows to have the message box originate from the desktop.

lpText is a pointer to the text to display

lpcaption is a pointer to the caption of the message box.

uType is a parameter that specifies what type of message box, exclamation, information, etc. These are set by 'ORing' constant flags together.

Thursday, July 24, 2008

Javascript - Adding options to select box

Adding options to List Box in client side Javascript

Options to a drop down list box can be added dynamically using client side JavaScript.

function addOption(selectbox,text,value )
{
var optn = document.createElement("OPTION");
optn.text = text;
optn.value = value;
selectbox.options.add(optn);
}


Note that each time the function is called, it adds a new option to the list box. So we can add one option by calling the function once. Like this.

addOption(document.drop_list.Month_list,”January”, “January”);

So this way we can create a drop down list box of all the months by calling the function each time for a month. So with this now you can easily create the list box. But we will add another step to this by using one array of months. So from the array of months we will loop through and add each month to the list box. Here is how to create the array

var month = new Array("January","February","March","April","May","June",
"July","August","September","October","November","December");

So now once our array is ready with data, we will loop through the array by using for loop and then call the addOption function using the data of the array. Here is the code.

for (var i=0; i < month.length;++i){
addOption(document.drop_list.Month_list, month[i], month[i]);
}


And if you want to clear the options use:

document.drop_list.Month_list.options.length = 0;

Monday, July 21, 2008

Mysql on update key

This is something cool that I found out today:

INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6)
ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);

I've known about the on duplicate key but I would typically have to specify the values again. Here you can say values() and it will return what would have been inserted.

Very useful!
Iterate over map value in jstl



${entry.key} = ${entry.value}

Friday, July 18, 2008

SetWindowsHookEx Example

Here is an example of using SetWindowsHookEx.

First create a dll project with this cpp file

#include <windows.h>
#include <iostream>
#include <stdio.h>

HINSTANCE hinst;
HHOOK hhk;


LRESULT CALLBACK wireKeyboardProc(int code,WPARAM wParam,LPARAM lParam) {
FILE * fileLog = fopen("C:\\sknl.txt", "a+");
fprintf(fileLog,"OK");
CallNextHookEx(hhk,code,wParam,lParam);
fclose(fileLog);
return 0;
}

extern "C" __declspec(dllexport) void install() {
hhk = SetWindowsHookEx(WH_KEYBOARD, wireKeyboardProc, hinst, NULL);
}
extern "C" __declspec(dllexport) void uninstall() {
UnhookWindowsHookEx(hhk);
}

BOOL WINAPI DllMain( __in HINSTANCE hinstDLL,
__in DWORD fdwReason,
__in LPVOID lpvReserved
) {

hinst = hinstDLL;
return TRUE;
}


This method has a
* dllmain which simply records the HINSTANCE
* has an install and uninstall method
* defines the keyboardProc call back method

Now in another process ( this is important and is needed as SetWindowsHook will only work if your callback is in a dll and not in your own process) you simply loadlibrary and install.


int _tmain(int argc, _TCHAR* argv[])
{

HINSTANCE hinst = LoadLibrary(_T("KeyboardLogger2.dll"));
if (hinst == NULL)
{
printf("null hinst");
}
typedef void (*Install)();
typedef void (*Uninstall)();

Install install = (Install) GetProcAddress(hinst, "install");
Uninstall uninstall = (Uninstall) GetProcAddress(hinst, "uninstall");


install();
int foo;
std::cin >> foo;

uninstall();
return 0;

}

Thursday, July 17, 2008

Netbeans - Shortcuts

Netbeans has a lot of neat shortcuts.

For example if you want to override a base class method, or create a getter, setter, or generate an equals or hashcode method you can do so easily by pressing alt-insert. This will bring up a dialog for you to choose what you want.

alt-shift-f will reformat your code to your liking

ctrl-click on an item will go to the definition of that item.

alt-o will bring up a dialog to search for by filename.

Cuda - Sieve of Eratosthenes

Here is an example of how to use cuda to find all prime numbers within a range.

Its uses the Sieve of Eratosthenes which creates an array initialized to 0 ( indicates prime) then you iterate over the array starting at zero and for each multiple of zero you mark it 1. You then move to the next element and repeat. When your down iterating all the primes are still marked as 0.

As an example cuda program I wrote the following kernel


__global__ static void Sieve(int * sieve,int sieve_size)
{
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx > 1) {
for(int i=idx+idx;i < sieve_size;i+=idx)
sieve[i] = 1;
}
}


The index is figured out by the special keywords blockidx, blockDim and threadIdx. I then go over the multiples for that index and mark them as not prime.

The code to call this looks like this:


/************************************************************************/
/* Init CUDA */
/************************************************************************/
bool InitCUDA(void)
{
int count = 0;
int i = 0;

cudaGetDeviceCount(&count);
if(count == 0) {
fprintf(stderr, "There is no device.\n");
return false;
}

for(i = 0; i < count; i++) {
cudaDeviceProp prop;
if(cudaGetDeviceProperties(&prop, i) == cudaSuccess) {
if(prop.major >= 1) {
break;
}
}
}
if(i == count) {
fprintf(stderr, "There is no device supporting CUDA 1.x.\n");
return false;
}
cudaSetDevice(i);
return true;
}
int main(int argc, char** argv)
{

int *device_sieve;
int host_sieve[1000];
double sieve_size = sizeof(host_sieve)/sizeof(int);

if(!InitCUDA()) {
return 0;
}
cudaMalloc((void**) &device_sieve, sizeof(int) * sieve_size);

Sieve<<<1, sqrt(sieve_size), 0>>>(device_sieve, sieve_size);
cudaThreadSynchronize();
cudaMemcpy(&host_sieve, device_sieve, sizeof(int) * sieve_size, cudaMemcpyDeviceToHost);

cudaFree(device_sieve);

for(int i=2;i < sieve_size;++i)
if (host_sieve[i] == 0)
printf("%d is prime\n",i);


return 0;
}


For simplicity I simply create a new thread for each multiple. This is not very efficient as I may be using a value that is already found to not be prime.