How to zip/unzip files

28 10 2013

If we search ‘How to zip/unzip files’ in any search engines, we will get lots of links to Open Source Softwares(OSS) to do it. But once you use OSS in your application, then definitely you should have to take care of OSS clearnce before you make Product release to the market. So how we can do it our own without any dependecy with OSS components?

Windows Shell library do it for free of cost.

Step 1 : Create an empty zip file

Step 2 : Add files to it using shell32 CopyHere method.


ZIP File

void CreateEmptyZipFile(CString strPath)
{
	BYTE startBuffer[] = {80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
	FILE *f = _wfopen(strPath.GetBuffer(strPath.GetLength()), _T("wb"));
	strPath.ReleaseBuffer();
	fwrite(startBuffer,sizeof(startBuffer),1,f);
	fclose(f); 
}

void ZipFile(CString strSrc, CString strDest)
{
	//Create an empty zip file
	CreateEmptyZipFile(strDest);

	BSTR bstrSource = strSrc.AllocSysString();
	BSTR bstrDest = strDest.AllocSysString();

	HRESULT hResult = S_FALSE;
	IShellDispatch *pIShellDispatch = NULL;
	Folder *pToFolder = NULL;		
	VARIANT variantDir, variantFile, variantOpt;

	CoInitialize(NULL);

	hResult = CoCreateInstance(CLSID_Shell, NULL, CLSCTX_INPROC_SERVER, 
		IID_IShellDispatch, (void **)&pIShellDispatch);

	if (SUCCEEDED(hResult))
	{
		VariantInit(&variantDir);
		variantDir.vt = VT_BSTR;
		variantDir.bstrVal = bstrDest;
		hResult = pIShellDispatch->NameSpace(variantDir, &pToFolder);

		if (SUCCEEDED(hResult))
		{
			VariantInit(&variantFile);
			variantFile.vt = VT_BSTR;
			variantFile.bstrVal = bstrSource;

			VariantInit(&variantOpt);
			variantOpt.vt = VT_I4;
			variantOpt.lVal = FOF_NO_UI;

			hResult = pToFolder->CopyHere(variantFile, variantOpt);
			Sleep(1000);
			pToFolder->Release();
		}

		pIShellDispatch->Release();
	}

	CoUninitialize();
}

UNZIP File

void UnZipFile(CString strSrc, CString strDest)
{
	BSTR source = strSrc.AllocSysString();
	BSTR dest = strDest.AllocSysString();

	HRESULT hResult = S_FALSE;
	IShellDispatch *pIShellDispatch = NULL;
	Folder *pToFolder = NULL;		
	VARIANT variantDir, variantFile, variantOpt;

	CoInitialize(NULL);

	hResult = CoCreateInstance(CLSID_Shell, NULL, CLSCTX_INPROC_SERVER, 
		IID_IShellDispatch, (void **)&pIShellDispatch);
	if (SUCCEEDED(hResult))
	{
		VariantInit(&variantDir);
		variantDir.vt = VT_BSTR;
		variantDir.bstrVal = dest;
		hResult = pIShellDispatch->NameSpace(variantDir, &pToFolder);

		if  (SUCCEEDED(hResult))
		{
			Folder *pFromFolder = NULL;
			VariantInit(&variantFile);
            variantFile.vt = VT_BSTR;
            variantFile.bstrVal = source;
			pIShellDispatch->NameSpace(variantFile, &pFromFolder);

			FolderItems *fi = NULL;
			pFromFolder->Items(&fi);

			VariantInit(&variantOpt);
            variantOpt.vt = VT_I4;
            variantOpt.lVal = FOF_NO_UI;			

			VARIANT newV;
			VariantInit(&newV);
			newV.vt = VT_DISPATCH;
			newV.pdispVal = fi;
			hResult = pToFolder->CopyHere(newV, variantOpt);
			Sleep(1000);
			pFromFolder->Release();
            pToFolder->Release();
		}
		pIShellDispatch->Release();
	}

	CoUninitialize();
}


It has been used a Folder object also in the program. Please refer MSDN for more information. Please don’t forget to include shell32.lib and Shellapi.h to your project.

Advertisements




How to use Strategy Pattern Instead of Switch-Case statements

21 05 2013


Cyclomatic complexity or conditional complexity is the term used in software module to measure the amount of decision points(logic) in our code. It would be better to keep minimum Cyclomatic complexity within the method level for better code readability and adhere to OOP principles. Incase if there is a switch-case statements in our method, corresponding to each case statement it increases the code complexity by one. So how we can avoid it.


The answer is, switch-case statements can be replaced with Strategy Design pattern.

Problem – Please see below code snippet where a Media Player object is calling differnt methods based on the file extension.

enum eMediaPlayerType
{
    WMPlayer = 0,
    RMPlayer,
    FMPlayer
};

class CMediaPlayer
{
public:
    void PlayWMFile()
    {
    }

    void PlayRMFile()
    {
    }

    void PlayFMFile()
    {
    }
};

void PlayFileBasedOnExtension()
{

    //.WMV file
    eMediaPlayerType etype = WMPlayer;
    CMediaPlayer MediaPlayer; 

    switch (etype)
    {
    case WMPlayer:
        MediaPlayer.PlayWMFile();
        break;
    case RMPlayer:
        MediaPlayer.PlayRMFile();
        break;
    case FMPlayer:
        MediaPlayer.PlayFMFile();
        break;
    }
}

Replace Switch-Case with Strategy Pattern

class IMediaPlayer
{
public:
    virtual void Play() = 0;
};

class CWindowsMediaPlayer : public IMediaPlayer
{
public:
    void Play()
    {
    }
};

class CRealMediaPlayer : public IMediaPlayer
{
public:
    void Play()
    {
    }
};

class CFlashMediaPlayer : public IMediaPlayer
{
public:
    void Play()
    {
    }
};

void ReplaceSwitchWithStrategyPattern()
{
    map<eMediaPlayerType, IMediaPlayer*> Strategies;

    IMediaPlayer* pWMPlyer = new CWindowsMediaPlayer();
    Strategies[WMPlayer] = pWMPlyer;

    IMediaPlayer* pRMPlyer = new CRealMediaPlayer();
    Strategies[RMPlayer] = pRMPlyer;

    IMediaPlayer* pFMPlyer = new CFlashMediaPlayer();
    Strategies[FMPlayer] = pFMPlyer;

    /////// Change the player based on media file extension
    eMediaPlayerType etype = WMPlayer; //.WMV file
    map<eMediaPlayerType, IMediaPlayer*>::iterator itr = Strategies.find(etype);
    itr->second->Play();
}


Even though it reduce code complexity and follow OOP principle, it will force us to add more classes.





dynamic_cast throws unhandled exception in VC++ 6.0

17 05 2013


Usually we upgrade our projects to higher versions of Visual Studio IDE for getting latest Windows libraries and making our project to be compatible with latest technologies. But recently we had to downgrade one of our DLLs to VC++ 6.0 from VS2005. As first step, we created new project in VC++ 6.0, resolved all compiler errors and successfully compiled it in VC++ 6.0 IDE. But when we integrated it with client application, it started throwing unhandled exception from wherever it used dynamic_cast. 😦


We have to explicitly enable Run-Time Type Information(RTTI) for our project in VC++ 6.0 compiler. In Visual C++ 2005, RTTI is on by default.

Enabling RTTI in VC++ 6.0 Project,

1) Open the project’s Property Page

2) Click the C/C++ Tab

3) Select C++ Language Category

4) Select Enable Run-Time Type Information (RTTI) checkbox

RTTI


typeid operator also fail if we don’t enable RTTI in our project.





How to convert a ANSI/MB project into a UNICODE

14 05 2013

Most of the time we may need to give multiple language support for our applications. Incase if we need to support Russian or Chinese language means, definitely we have to give Unicode support for our application. So here I would like to share some tips for converting existing ANSI/MultiByte project into Unicode.

If we build our project in Multi-byte character set it will allocate 1 byte for one character. This is enough for representing all English letters. But if we build our project in Unicode character set it will allocate 2 bytes for each letters. It is required for representing Russian and Chinese letters.

Below are some suggestions for converting MBCS to Unicode project

Step 1: Create new configuration from Project Configuration Manager. Give name something like ReleaseUnicode/DebugUnicode.

Step 2: Change Character Set to Unicode from Project Settings.

Unicode

Step 3: Replace all char datatype with TCHAR. This will automatically switch to normal char or wchar_t based on it is compiled as MBCS or Unicode respectively.

Step 4: Add _T as prefix to each string text. eg: _T(“Hello World”)

Step 5: Replace LPSTR and LPCSTR with LPTSTR and LPCTSTR respectively.

Step 6: Replace following win32 APIs with corresponding Generic equivalent for same.

ANSI/MB API Generic API
strstr _tcsstr
strcmp _tcscmp
sprintf_s _stprintf_s
strlen _tcslen
_stricmp _tcscmp
strcpy_s _tcscpy_s
atol _tstol
atoi _tstoi
atof _tstof
strcspn _tcscspn
fopen_s tfopen_s
strtok_s _tcstok_s
strtol _tcstol
strtoul _tcstoul




How to read INI files

8 05 2013

INI files(.INI) are simple text files with a basic structure composed of sections and properties and which is used for some configuration settings. Till Microsoft introduced registry, the INI file served as the primary mechanism to configure operating system features. Even if it is obsolete, developers may still need to use it.

Windows provides APIs for reading and writing settings from classic Windows .ini files. The following APIs are available for reading data from INI files.
GetPrivateProfileInt
GetPrivateProfileSection
GetPrivateProfileSectionNames
GetPrivateProfileString
GetPrivateProfileStruct
GetProfileInt
GetProfileSection
GetProfileString

INIReader.h

class CINIReader
{

public:
CINIReader()
{
    m_pSectionList = new CStringList();
    m_pSectionDataList = new CStringList();
}

~CINIReader()
{
    delete m_pSectionList;
    delete m_pSectionDataList;
}

    void SetInfFileName(CString p_strInfFileName);
    BOOL IsValidSection(CString p_strSectionName);
    CStringList* GetSectionNames()
    CStringList* GetSectionData(CString p_lpSectionName);

private:
    CString m_strInfFileName;
    CStringList* m_pSectionList;
    CStringList* m_pSectionDataList;	    
};

INIReader.cpp

void CINIReader::SetInfFileName(CString p_strInfFileName)
{
m_strInfFileName = p_strInfFileName;
}

BOOL CINIReader::IsValidSection(CString p_strSectionName)
{
BOOL bReturnValue = FALSE;

if (!m_strInfFileName.IsEmpty())
{
TCHAR lpszReturnBuffer[nBufferSize];

DWORD dwNoOfCharsCopied = GetPrivateProfileString(p_strSectionName, NULL,
_T(""), lpszReturnBuffer, nBufferSize, m_strInfFileName);

bReturnValue = (dwNoOfCharsCopied > 0) ? TRUE : FALSE;
}

return bReturnValue;
}

CStringList* CINIReader::GetSectionNames()
{
if (m_pSectionList)
{
m_pSectionList->RemoveAll();
TCHAR lpszReturnBuffer[nBufferSize];
GetPrivateProfileSectionNames(lpszReturnBuffer, nBufferSize, m_strInfFileName);
TCHAR* pNextSection = NULL;
pNextSection = lpszReturnBuffer;
m_pSectionList->InsertAfter(m_pSectionList->GetTailPosition(), pNextSection);
while (*pNextSection != 0x00)
{
pNextSection = pNextSection + strlen(pNextSection) + 1;
if(*pNextSection != 0x00)
{
m_pSectionList->InsertAfter(m_pSectionList->GetTailPosition(), pNextSection);
}
}
}

return m_pSectionList;
}

CStringList* CINIReader::GetSectionData(CString p_lpSectionName)
{
if (m_pSectionDataList)
{
m_pSectionDataList->RemoveAll();
TCHAR lpszReturnBuffer[nBufferSize];
GetPrivateProfileSection(p_lpSectionName, lpszReturnBuffer, nBufferSize, m_strInfFileName);
TCHAR* pNextSection = NULL;
pNextSection = lpszReturnBuffer;
m_pSectionDataList->InsertAfter(m_pSectionDataList->GetTailPosition(), pNextSection);
while (*pNextSection != 0x00)
{
pNextSection = pNextSection + strlen(pNextSection) + 1;
if(*pNextSection != 0x00)
{
m_pSectionDataList->InsertAfter(m_pSectionDataList->GetTailPosition(), pNextSection);
}
}
}

return m_pSectionDataList;
}

We can discuss about INI writer in our next post.





How to register a vectored exception handler

2 05 2013

Recently just after we deployed our project in a Client machine, they reported a sporadic crash issue in their machine. :(. After analyzing the dump file, our Architect team found out that its happening from a particular COM Component. Unfortunately I was responsible for that component. 😦 😦

I tried to reproduce same issue in my development machine and was able to reproduce only in release configuratiin mode. Actually I have only the source code of my component in my machine.
So I was thinking about, how to find out this crash location in my source code. Yes, you are right some loggin mechanism. 🙂 Plus some exception handling mechanism too. 🙂 🙂

In case of exception occouered in our code, the operating system try to find out a handler which tells how to proceed now. If it fails, then we will get error message that our application is going to close!!!
In order to find such exception handler, the system has a fixed order to search.
It will start with the vectored exception handlers. So we can set a Vectored exception handler for our application using Windows API AddVectoredExceptionHandler.It registers a vectored exception handler.
The parameter of exception handler is pointer to a structure EXCEPTION_POINTERS. From this structure we get exception code and address where the exception occurred. Then using the method SymGetSymFromAddr64 from Dbghelp.dll, we can locate the symbol(function name) for that address.

char *Symbol(DWORD dwAddr)
{
    typedef struct _IMAGEHLP_SYMBOL64_L {
        DWORD   SizeOfStruct;
        DWORD64 Address;
        DWORD   Size;
        DWORD   Flags;
        DWORD   MaxNameLength;
        CHAR    Name[1];
    } IMAGEHLP_SYMBOL64_L, *PIMAGEHLP_SYMBOL64_L;

    typedef BOOL (__stdcall *pfnSymInitialize) (HANDLE hProcess,
        PCSTR UserSearchPath, BOOL fInvadeProcess);
    typedef BOOL (__stdcall *pfnSymGetSymFromAddr64) (HANDLE hProcess,
        DWORD64 qwAddr, PDWORD64 pdwDisplacement, PIMAGEHLP_SYMBOL64_L  Symbol);

    static BOOL	bSymLoad;
    static char symName[1024];
    static IMAGEHLP_SYMBOL64_L *pSym = NULL;
    static pfnSymInitialize SymInit;
    static pfnSymGetSymFromAddr64 SymName;

    if (!bSymLoad)
    {
        HMODULE hMod;			
        if ( (hMod = LoadLibrary(__T("Dbghelp.dll"))) &&
            (SymInit = (pfnSymInitialize) GetProcAddress(hMod, "SymInitialize")) &&
            (SymName = (pfnSymGetSymFromAddr64) GetProcAddress(hMod, "SymGetSymFromAddr64")))
        {
            bSymLoad = SymInit(GetCurrentProcess(), NULL, true);
            pSym = (IMAGEHLP_SYMBOL64_L *) malloc(sizeof(IMAGEHLP_SYMBOL64_L) + 2000);
        }
    }

    if (bSymLoad)
    {
        DWORD64  dwDisplacement = 0;
        pSym->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64_L);
        pSym->MaxNameLength = 2000;

        if (SymName(GetCurrentProcess(), dwAddr, &dwDisplacement, pSym))
        {
            return &pSym->Name[0];
        }
    }

    return NULL;
}

LONG CALLBACK VectoredExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)
{
    CString strMsg;
    strMsg.Format("Exception code: 0x%x (%s)", ExceptionInfo->ExceptionRecord->ExceptionCode,
		Symbol((DWORD) ExceptionInfo->ExceptionRecord->ExceptionAddress) );
	return EXCEPTION_CONTINUE_SEARCH;
}

BOOL InitInstance()
{
    AddVectoredExceptionHandler(1, VectoredExceptionHandler);
}


It uses few symbol handler functions from Dbghelp.dll, which gives applications easy and portable access to the symbolic debugging information of an executable image.





How to pass variable number of arguments to a function

30 04 2013

How to write functions which takes variable number of arguments in our program.

In C++, we can write functions with three dots(…) as parameter. This will make that function to support variable number of arguments. The va_arg, va_end, and va_start macros provide access to function arguments when the number of arguments is variable.

void LogError(TCHAR * format, ...)
{
   va_list args;
   int len;
   TCHAR *buffer;

   va_start(args, format);
   len = _vscprintf(format, args) + 1;
   buffer = (TCHAR *) _alloca( len * sizeof(TCHAR) );
   vsprintf_s( buffer, len, format, args );
   CString strErrMsg = buffer;
}

int Sum(int noOfArgs, ...)
{
    int nSum = 0;
    va_list args;
    va_start(args, noOfArgs);
    nSum = va_arg(args, int);
    for(int i = 2; i <= noOfArgs; i++) 
    {
        nSum += va_arg(args, int);
    }
    va_end(args);
    return nSum;
}

void main()
{
    int nSum = Sum(5, 1, 2, 3, 4, 5);
    LogError(_T("Failed - %s, ErrorCode - %d"), "AccessDenied", 111);
}


These macros are defined in STDARG.H file.