Thursday, July 30, 2009

ArrayList to object[] and versa

A simple way to perform the conversion:
object[] tmp = new object[3]{1,2,3};

 
// to ArrayList
ArrayList arrayList = ArrayList.Adapter(tmp);


// to array
object[] tmp1 = arrayList.ToArray();

Friday, July 24, 2009

The CSS Sprites Creator

In order to decrease the traffic and website loading time you can use CSS sprites.
The Sprite Creator 1.0 is a nice tool for upload an image and select areas of the image to create the css for that sprite.

Sunday, June 28, 2009

The Singleton pattern

The singleton pattern is a design pattern that is used to restrict instantiation of a class to one object.
This is useful when exactly one object is needed to coordinate actions across the system.















C++ implementations:


Static singleton:

#include "iostream"


template <class T>

class Singleton

{

static T _instance;

public:


~Singleton(){ }

Singleton(){ }


T& GetInstance() {

return _instance;

}


private:

Singleton(Singleton&);

Singleton& operator=(Singleton&);

};

template <class T>

T Singleton<T>::_instance;

class MyData

{

public:

void Execute(){std::cout<<"Execute..."<<std::endl;}

MyData(){std::cout<<"Constructor..."<<std::endl;}

};

void main()

{

Singleton<MyData> singleton1;

singleton1.GetInstance().Execute();


Singleton<MyData> singleton2;

singleton2.GetInstance().Execute();

Singleton<int> singleton3;

singleton3.GetInstance() = 5;

std::cout<<singleton3.GetInstance()<<std::endl;

}



Static function singleton:

template <class T>

class Singleton

{

public:

~Singleton(){ }

Singleton(){ }


T& GetInstance() {

static T instance;

return instance;

}

private:

Singleton(Singleton&);

Singleton& operator=(Singleton&);

};


Dynamic singleton:
Unlike the static singletons, the dynamic is not thread safe.
You can use critical section as synchronization mechanism.

template <class T>

class Singleton

{

static T* _instance;

public:

~Singleton(){ }

Singleton(){ }


T& GetInstance() {


if(!_instance)

_instance = new T();

return *_instance;

}


private:

Singleton(Singleton&);

Singleton& operator=(Singleton&);

};


template <class T>

T* Singleton<T>::_instance=0;


C# implementation:

public class Singleton<T> where T : class, new()

{

private static T _instance = null;


static Singleton()

{

_instance = new T();

}


public static T Instance

{

get

{

return _instance;

}

}

}


class MyData

{

public void Execute() { Console.WriteLine("Execute..."); }

}


[STAThread]

static void Main()

{

Singleton<MyData>.Instance.Execute();

}

The static constructor for a class executes at most once in a given application domain.
It's used to initialize any static data, or to perform a particular action that needs performed once only and it is called automatically before the first instance is created or any static members are referenced.


Double-Checked Locking Singleton (lazy initialization):
    internal sealed class Singleton<T> where T : class, new()
    {
        private static T _instance = null;
        private static object _syncObj = new object();

        private Singleton()
        {
            // your implementation
        }

        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncObj)
                    {
                        if (_instance != null)
                            return _instance;
                        _instance = new T();
                    }
                }

                return _instance;
            }
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            Singleton<StringBuilder>.Instance.Append("Some text");
        }
    }
The double-checked locking optimization is designed to reduce the overhead of acquiring a lock by first testing the locking criterion.
Lazy initialization avoids initializing a value until the first time it is accessed.

Saturday, June 20, 2009

The C# preprocessor directives

Unlike the C/C++ the C# compiler does not have a separate preprocessor.
Basicaly preprocessor directives are instructions to the C# compiler to perform some action during compilation.


#if, #else, #elif and #endif - commonly used to evaluate conditional code sections:
#define DEBUG
using System;
public class MyClass
{
public static void Main()
{
#if (DEBUG)
Console.WriteLine("DEBUG is defined");
#elif (VC_V7)
Console.WriteLine("VC_V7 is defined");
#else
Console.WriteLine("DEBUG and VC_V7 are not defined");
#endif
}
}

#define lets you define a symbol, such that, by using the symbol as the expression passed to the #if directive, the expression will evaluate to true.

#undef lets you undefine a symbol, such that, by using the symbol as the expression in a #if directive, the expression will evaluate to false.

#warning/#error lets you generate a warning/error from a specific location in your code:

#define DEBUG
public class MyClass
{
public static void Main()
{
#if DEBUG
#warning DEBUG is defined
#endif
}
}

#line lets you modify the compiler's line number and (optionally) the file name output for errors and warnings.

#region lets you specify a block of code that you can expand or collapse when using the outlining feature of the Visual Studio Code Editor.

#region MyClass definition
public class MyClass
{
public static void Main()
{
}
}
#endregion

Monday, June 1, 2009

Stopwatch – a way to measure elapsed time

If you need to measure elapsed time of your function or code section you can use Stopwatch object.

According to MSDN:

A Stopwatch instance can measure elapsed time for one interval, or the total of elapsed time across multiple intervals. In a typical Stopwatch scenario, you call the Start method, then eventually call the Stop method, and then you check elapsed time using the Elapsed property.

     System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();

     watch.Start();

     // Your Implementation

     watch.Stop();

     Console.WriteLine(watch.Elapsed.ToString());

Sunday, May 31, 2009

File.ReadAllText and File.WriteAllText

If you are looking for an easy way to work with files the: File.ReadAllText and File.WriteAllText are the answer.

File.ReadAllText
Method ppens a text file, reads all lines of the file, and then closes the file.

File.WriteAllText Method creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.

Saturday, May 9, 2009

Shared Memory

Shared Memory is an efficeint way of exchanging data between programs running at the same time. One process will create an area in RAM which other processes can access.

WinAPI remarks:
After a Shared Memory object is created, the size of the file must not exceed the size of the file Shared Memory; if it does, not all of the file contents are available for sharing.
A shared file mapping object will not be destroyed until all processes that use it close their handles to it by using the CloseHandle function.

A simple example of Writer/Reader processes.
First process creates a Shared Memory; the second reads messages from it.

SharedMemoryHandler.h

#include<windows.h>


class SharedMemoryHandler

{

public:

SharedMemoryHandler(void* pObj, int length);

~SharedMemoryHandler(void);


bool Read();

bool Write();

private:

bool Load();

bool Unload();

SharedMemoryHandler(void);

SharedMemoryHandler& operator=(SharedMemoryHandler&);

private:

PVOID m_pObj;

int m_length;


PVOID m_pBuf;

HANDLE m_hMutex;

HANDLE m_hMapFile;

};


SharedMemoryHandler.cpp

#include "SharedMemoryHandler.h"

#include <tchar.h>


//___________ create unique mutex name ___________

static LPWSTR mutexName=_T("SharedMemoryHandler_Mutex");

static LPWSTR sharedMemoryName=_T("SharedMemoryHandler_SharedMemory");

SharedMemoryHandler::SharedMemoryHandler(void* pObj, int length)

:m_hMutex(0), m_hMapFile(0), m_pBuf(0), m_pObj(pObj), m_length(length)

{

Load();

}


SharedMemoryHandler::~SharedMemoryHandler(void)

{

Unload();

CloseHandle( m_hMutex );

CloseHandle( m_hMapFile );

m_length = 0;

m_hMutex = m_hMapFile = m_pBuf = m_pObj = 0;

}


bool SharedMemoryHandler::Load()

{

//__________ lock with mutex ____________

if((m_hMutex = CreateMutex(NULL, FALSE, mutexName))==0)

{

return false;

}


//_____ wait till someone unlock it ___

WaitForSingleObject( m_hMutex, INFINITE );


// _____________ create shared memory __________

m_hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, m_length, sharedMemoryName);


if (m_hMapFile == 0 || m_hMapFile == INVALID_HANDLE_VALUE)

{

//_____ unlock _____

ReleaseMutex(m_hMutex);

return false;

}


//______________ load shared memory ________________

m_pBuf = MapViewOfFile(m_hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, m_length);


if (m_pBuf == 0)

{

//_____ unlock _____

ReleaseMutex(m_hMutex);

return false;

}


//_____ unlock _____

ReleaseMutex(m_hMutex);


return true;

}


bool SharedMemoryHandler::Read()

{

//__________ lock with mutex ____________

if((m_hMutex = CreateMutex(NULL, FALSE, mutexName))==0)

{

return false;

}


//_____ wait till someone unlock it ___

WaitForSingleObject( m_hMutex, INFINITE );

ZeroMemory( m_pObj, m_length );

CopyMemory(m_pObj, m_pBuf, m_length);

//_____ unlock _____

ReleaseMutex(m_hMutex);


return true;

}


bool SharedMemoryHandler::Write()

{

//__________ lock with mutex ____________

if((m_hMutex = CreateMutex(NULL, FALSE, mutexName))==0)

{

return false;

}


//_____ wait till someone unlock it ___

WaitForSingleObject( m_hMutex, INFINITE );


ZeroMemory( m_pBuf, m_length );

CopyMemory(m_pBuf, m_pObj, m_length);


//_____ unlock _____

ReleaseMutex(m_hMutex);


return true;

}


bool SharedMemoryHandler::Unload()

{

//_______________ get mutex handler ________________


if((m_hMutex=CreateMutex(NULL, FALSE, mutexName))==0)

{

return false;

}


//____ wait till someone unlock it __

WaitForSingleObject( m_hMutex, INFINITE );


// ____ destroy shared memory ______

if (!UnmapViewOfFile(m_hMapFile))

{

//_____ unlock _____

ReleaseMutex(m_hMutex);

return false;

}


//_____ unlock _____

ReleaseMutex(m_hMutex);

return true;

}


First process:

#include "stdafx.h"

#include <conio.h>

#include "SharedMemoryHandler.h"


struct Message

{

char msg[256];

};


int _tmain()

{

Message msg = {0};

strcpy(msg.msg, "Writer process message!");


SharedMemoryHandler smh(&msg, sizeof(msg));

smh.Write();

_getch();


return 0;

}


Second process:

#include "stdafx.h"

#include "SharedMemoryHandler.h"


struct Message

{

char msg[256];

};


int _tmain()

{

Message msg = {0};

SharedMemoryHandler smh(&msg, sizeof(msg));


smh.Read();

printf("%s\n", msg.msg);


return 0;

}

How to startup your application automatically when a Window starts

One way to execute your process each time a Windows starts is to add your application's path to the registry.
When Windows starts it's executes all applications which registered at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run path.

You can create installer for your application and create relevant registry key, or you can do this from code:

Main application:

int main()

{

const wchar_t appKey[] = TEXT("My_StartUp_Application");

const wchar_t appPath[] = TEXT("D:\\StartUpApplication\\debug\\StartUpApplication.exe");


StartUpApplication startUpApp;

startUpApp.Set(appKey, appPath);


return 0;

}



StartUpApplication.h

class StartUpApplication

{

public:

StartUpApplication(void);

~StartUpApplication(void);

bool UnSet(const wchar_t* key);

bool Set(const wchar_t* key, const wchar_t* appPath);

bool GetAppPath(const wchar_t* key, wchar_t* appPath);


private:

StartUpApplication(StartUpApplication&);

StartUpApplication& operator=(StartUpApplication&);

};


StartUpApplication.cpp

#include "StartUpApplication.h"

#include <windows.h>

static const wchar_t* _startupPath = __TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");


StartUpApplication::StartUpApplication()

{

}

StartUpApplication::~StartUpApplication(void)

{

}


bool StartUpApplication::Set(const wchar_t* key, const wchar_t* appPath)

{

if(!key || !appPath)

return false;


HKEY hKey;


if(ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, _startupPath, 0, KEY_ALL_ACCESS, &hKey))

return false;


long retVal = RegSetValueEx(hKey, key, 0, REG_SZ, (BYTE*)appPath, (wcslen(appPath)+1)*sizeof(TCHAR));


return ( (ERROR_SUCCESS == retVal) && (ERROR_SUCCESS == RegCloseKey(hKey)) );

}


bool StartUpApplication::UnSet(const wchar_t* key)

{

HKEY hKey;


if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, _startupPath, 0, KEY_ALL_ACCESS, &hKey))

return false;


return ( (ERROR_SUCCESS == RegDeleteValue(hKey, (LPCWSTR)key)) && (ERROR_SUCCESS == RegCloseKey(hKey)) );

}


bool StartUpApplication::GetAppPath(const wchar_t* key, wchar_t* appPath)

{

HKEY hKey;

if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _startupPath, 0, KEY_READ, &hKey) != ERROR_SUCCESS)

return false;


DWORD dwType = REG_SZ, dwSize = MAX_PATH;

long retVal = RegQueryValueEx(hKey, (LPCWSTR)key, NULL, &dwType, (LPBYTE)appPath, &dwSize);

return ( (ERROR_SUCCESS == retVal) && (ERROR_SUCCESS == RegCloseKey(hKey)) );

}

How to receive OS notifications about windows shutdown/logoff

To create a process which must detect windows shutdown or log-off actions to perform necessary clean-up operations you can use many features.

One of them is to create Windows Service.
Another way is to subscribe to the system events notifications.

WinAPI provides a SetConsoleCtrlHandler function which able to add a callback for the calling process.

#include <windows.h>


HANDLE hEvent;


BOOL WINAPI ShutDownHandler(DWORD dwCtrlType)

{

switch( dwCtrlType )

{

case CTRL_SHUTDOWN_EVENT:


case CTRL_LOGOFF_EVENT:


case CTRL_CLOSE_EVENT:

SetEvent(hEvent);

return TRUE;


default:

return FALSE;

}

}

void main()

{

hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

SetConsoleCtrlHandler(ShutDownHandler, true);

// your implementation

WaitForSingleObject(hEvent,INFINITE);

// your clean-up


CloseHandle (hEvent);

}

Friday, May 8, 2009

Force application not to appear at taskbar

#include <windows.h>

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

{

HWND hwnd;

wchar_t pszNewWindowTitle[MAX_PATH]={0};


GetConsoleTitle(pszNewWindowTitle, sizeof(pszNewWindowTitle));

hwnd = FindWindow(NULL, pszNewWindowTitle);


if(hwnd)

ShowWindow(hwnd, SW_HIDE);


// Your Code..


return 0;

}