Skip to main content

Check whether a given file exists in the given path

· One min read

Using Win32 API FindFirstFile we can find whether a given file exists in the given path (szFilePath) or not. BOOL IsFileExists( LPCTSTR szFilePath) method shown below serves our purpose.

BOOL IsFileExists( LPCTSTR szFilePath) // szFilePath in | file path 
{
BOOL bFileExists;
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
hFind = FindFirstFile(szFilePath, &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
bFileExists = FALSE;
} else {
FindClose(hFind);
bFileExists = TRUE;
}

return bFileExists;
}

Hash Data using Win32 API through a CHashDataProvider class

· 3 min read

Cryptography is the use of codes to convert data so that only a specific recipient will be able to read it. Microsoft provide win32 API to Hash Data/string. The class CHashDataProvider developed to provides simple function HashData(ALG_ID algorithmID, LPCTSTR plainText, LPTSTR hashedText); which takes algorithmID and inputText to convert plainText to hashedText

ALG_ID algorithmID - Algorithm ID to be used LPCTSTR plainText - plainText that to be converted to hashedText LPTSTR hashedText - Hashed Test using the input algorithmID.

CHashDataProvider Code

HashDataProvider.h

#include <wincrypt.h>;
#define BUFFER_SIZE 256

class CHashDataProvider
{
public:
CHashDataProvider(void);
~CHashDataProvider(void);

private:
// Handle to a cryptographic service provider (CSP)
HCRYPTPROV m_hProv;

// Handle to the hash object needed to create a hash.
HCRYPTHASH m_hHash;

// Pointer to the hash.
PBYTE m_pbHash;

private:
void FreeResources();
void InitializeData();
LPTSTR FormatData(PBYTE pbHash, DWORD dwDataLen, LPTSTR hashedText);

public:
bool HashData(ALG_ID algorithmID, LPCTSTR plainText, LPTSTR hashedText);
};

HashDataProvider.cpp

#include "HashDataProvider.h"

CHashDataProvider::CHashDataProvider(void)
{
InitializeData();
}

CHashDataProvider::~CHashDataProvider(void)
{
}

//\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
// des: Hashes data based on the ALG_ID
// return: Hashing of the text is successful or not
//\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
bool
CHashDataProvider::HashData(ALG_ID algorithmID, // in | Algorithm ID (Sha1 or MD5 )
LPCTSTR plainText, // in | Original string to be hashed
LPTSTR hashedText) //out | string to store hashed text
{
InitializeData();

bool rc = true; // Default is success
DWORD dwDataLen = 0; // Length, in bytes, of the hash.

//--------------------------------------------------------------------
// Acquire a handle to the default RSA cryptographic service provider.
if (!CryptAcquireContext(
&amp;m_hProv, // handle of the CSP
NULL, // key container name
NULL, // CSP name
PROV_RSA_FULL, // provider type
CRYPT_VERIFYCONTEXT)) // no key access is requested
{
AfxMessageBox("Error in AcquireContext 0x%08x n", GetLastError());
rc = false;
FreeResources();
}

if (!CryptCreateHash(
m_hProv, // handle of the CSP
algorithmID, // hash algorithm to use
0, // hash key
0, // reserved
&amp;m_hHash)) // address of hash object handle
{
AfxMessageBox("Error in CryptCreateHash 0x%08x n", GetLastError());
rc = false;
FreeResources();
}

if (!CryptHashData(
m_hHash, // handle of the hash object
(const BYTE *) plainText, // text to be hash
_tcslen(plainText)*sizeof(TCHAR), // number of bytes of data
0)) // flags
{
AfxMessageBox("Error in CryptHashData 0x%08x n", GetLastError());
rc = false;
FreeResources();
}

if (!CryptGetHashParam(
m_hHash, // handle of the HMAC hash object
HP_HASHVAL, // query on the hash value
NULL, // pointer to the HMAC hash value
&amp;dwDataLen, // length,in bytes, of the hash
0))
{
AfxMessageBox("Error in CryptGetHashParam 0x%08x n", GetLastError());
rc = false;
FreeResources();
}

m_pbHash = (BYTE\*)malloc(dwDataLen);
if(NULL == m_pbHash)
{
AfxMessageBox("unable to allocate memoryn");
rc = false;
FreeResources();
}

if (!CryptGetHashParam(
m_hHash, // handle of the HMAC hash object
HP_HASHVAL, // query on the hash value
m_pbHash, // pointer to the HMAC hash value
&amp;dwDataLen, // length,in bytes, of the hash
0))
{
AfxMessageBox("Error in CryptGetHashParam 0x%08x n", GetLastError());
rc = false;
FreeResources();
}

hashedText = FormatData(m_pbHash, dwDataLen, hashedText);

FreeResources();

return rc;
}

//Helper functions
void CHashDataProvider::FreeResources()
{
if(m_hHash)
CryptDestroyHash(m_hHash);
if(m_hProv)
CryptReleaseContext(m_hProv, 0);
if(m_pbHash)
free(m_pbHash);
}

void CHashDataProvider::InitializeData()
{
m_hProv = NULL;
m_hHash = NULL;
m_pbHash = NULL;
}

LPTSTR CHashDataProvider::FormatData(PBYTE pbHash, DWORD dwDataLen, LPTSTR hashedText)
{
TCHAR rstData[BUFFER_SIZE]= {0}; // Buffer to receive hashed result
TCHAR tmpBuffer[3] = {0};
for (DWORD i = 0 ; i &lt; dwDataLen ; i++)
{
tmpBuffer[0] = 0;
tmpBuffer[1] = 0;
tmpBuffer[2] = 0;
_stprintf_s(tmpBuffer, _T("%2.2x"), pbHash\[i\]);
_tcscat_s(rstData, tmpBuffer);
}
_tcscpy(hashedText, rstData);

return hashedText;
}

Creating an SDI/MDI application that is initially maximized

· One min read

To Creating an SDI/MDI application that is initially maximized Pass SW_SHOWMAXIMIZED as paramater to m_pMainWnd->ShowWindow() in the  in the CWinApp::InitInstance()

Code Snippet:

BOOL CWindowTitleApp::InitInstance() { 
////////////////////////////////////////////////////////////////////////////
// To Create an SDI/MDI application that is initially maximized
// /////////////////////////////////////////////////////////////////////////

m_pMainWnd->ShowWindow(SW_SHOWMAXIMIZED);
m_pMainWnd->UpdateWindow();
m_pMainWnd->DragAcceptFiles();

return TRUE;
}

Change a Window's title of an SDI/MDI Application

· One min read

Call SetWindowText method by passing required title as a string in the CWinApp::InitInstance() method after ProcessShellCommand() method. Please see the below code snippet

m_pMainWnd->SetWindowText("My New Window Title");

BOOL CWindowTitleApp::InitInstance()
{
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&amp;InitCtrls);

CWinApp::InitInstance();
SetRegistryKey(_T("Local AppWizard-Generated Applications"));
LoadStdProfileSettings(4);

CSingleDocTemplate\* pDocTemplate;
pDocTemplate = new CSingleDocTemplate(
IDR_MAINFRAME,
RUNTIME_CLASS(CWindowTitleDoc),
RUNTIME_CLASS(CMainFrame), // main SDI frame window
RUNTIME_CLASS(CWindowTitleView));
if (!pDocTemplate)
return FALSE;
AddDocTemplate(pDocTemplate);

EnableShellOpen();
RegisterShellFileTypes(TRUE);

CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);

if (!ProcessShellCommand(cmdInfo))
return FALSE;
////////////////////////////////////////////////////////////////////////////
// To Change Window Title //
////////////////////////////////////////////////////////////////////////////
m_pMainWnd-&gt;SetWindowText("My New Window Title");
////////////////////////////////////////////////////////////////////////////

m_pMainWnd-&gt;ShowWindow(SW_SHOW);
m_pMainWnd-&gt;UpdateWindow();
m_pMainWnd-&gt;DragAcceptFiles();

return TRUE;
}

How do remove 'Untitled' in main window caption

· One min read

To remove 'Untitled' in main window caption

  1. Override the PreCreateWindow() function in CMainFrame class
  2. Modify the CREATESTRUCT style by adding the below code cs.style &= ~FWS_ADDTOTITLE ;

Code snippet:

BOOL CMainFrame::PreCreateWindow(CREATESTRUCT&amp; cs)
{
if( !CFrameWnd::PreCreateWindow(cs) )
return FALSE;

////////////////////////////////////////////////////////////////////////////
// To remove 'Untitled' in main window caption //
////////////////////////////////////////////////////////////////////////////
cs.style &amp;= ~FWS\_ADDTOTITLE ;
////////////////////////////////////////////////////////////////////////////

return TRUE;
}

Steve Jobs by Walter Isaacson

· 2 min read

Bought Steve Jobs by Walter Isaacson Biography on February 14, 2012 to present it to my self through flipkart.com.

Today March 10, 2012 12.20 PM I had completed reading the book it contains 42 chapters spread over 571 pages

Reality Distortion Field: It can be done

Books That Inspired Steve Jobs

  1. 'Autobiography of a Yogi' by Paramahansa Yogananda Jobs read and re-read many times during his life. Jobs had first read as a teenager," Isaacson writes, "then re-read in India and had read once a year ever since.

  2. 'Be Here Now' by Ram Dass

  3. Zen Mind, Beginner's Mind by Shunryu Suzuki

  4. 'The Innovator's Dilemma' by Clayton Christensen

  5. 'The Whole Earth Catalog' periodicals

  6. Herman Melville's Moby Dick

  7. Shakespeare's King Lear

  8. Poems of Dylan Thomas

  9. 'Diet For A Small Planet' by Frances Lapp

  10. 'Mucusless Diet Healing System' by Arnold Ehret

  11. Chogyam Trungpa's "Cutting Through Spiritual Materialism"

Articles

  1. "Secrets of the Little Blue Box,"

The Music That Inspired Steve Jobs

  1. Bob Dylan - bootlegs
  2. Beatles
  3. Stones
  4. Joan Baez - Love Is A Four Letter Word song
  5. Joni Mitchell - Both Sides Now song
  6. "Uncle John's Band" by the Grateful Dead
  7. Glenn Gould

Quotes From His Biography

"If you don't cannibalize yourself, someone else will."

"People don’t know what they want until you show it to them."

"I hate it when people call themselves 'entrepreneurs' when what they’re really trying to do is launch a startup and then sell or go public, so they can cash in and move on."

Get back the Recent Documents Menu in Windows 7

· One min read

Here is how I got it back:

  1. Right click the Start/Win button, select Properties
  2. Click the Start Menu tab (it should be select as default)
  3. Click the Customize button
  4. Scroll down and check the Recent Items check box
  5. Click Ok
  6. Click Apply
  7. Click Ok
  8. Check "Recent" option in the start menu.

Sending SMS using C

· 2 min read

Step 1: Create a new project in Microsoft Visual Studio 2008 (File -> New -> Project -> Visual C# -> Console Application). Give SMS_Sender name and also specify the location where to store the project.

Step 2: Now add a new item to the project we just created (Project -> Add New Item -> Class). Specify a name to the class as ‘SMSHelper’. The code now looks like as follows. The namespace used is

using System.IO; 
using System.Net;

SMSHelper.cs

 public class SMSHelper { 
private WebResponse myResponse = null;
private string result = string.Empty;
private string formatUrl(string ToMobileNo, string Message) {
DateTime mydate = System.DateTime.Now;
string url = ""; url += "method=sendMessage";
url += "&userid=2000053959"; // your loginId - 1
url += "&password=Gdgek2yiY";//password - 2
url += "&msg=" + mydate.ToString();
url += Message;
url += "&send_to="; // a valid 10 digit phone no.
url += ToMobileNo; url += "&v=1.1";
url += "&msg_type=TEXT"; // Can be "FLASH" or "UNICODE\_TEXT" or "BINARY"
url += "&auth_scheme=PLAIN";
return url;
}

public string SendSms(string ToMobileNo , string Message)
{
try
{
string finalUrl = "http://enterprise.smsgupshup.com/GatewayAPI/rest?" + formatUrl(ToMobileNo, Message);
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(finalUrl);
myResponse = myRequest.GetResponse();
Stream st = myResponse.GetResponseStream();

Encoding ec = System.Text.Encoding.GetEncoding("utf-8");
StreamReader reader = new System.IO.StreamReader(st, ec);

result = reader.ReadToEnd();

reader.Close();
st.Close();
return result;
}
catch (Exception exp)
{
return result;
}
finally
{
if (myResponse != null) myResponse.Close();
}
}
}

Step 3: Open Program.cs and in Main write the following lines to send the SMS

 class Program { 
static void Main(string[] args) {
SMSHelper smsObj = new SMSHelper();
string Text = smsObj.SendSms("1234567890", "HelloWorld");
Console.WriteLine(Text);
}
}

Message Map vs Virtual Functions

· One min read

Message Map is a logical table that maps the windows messages to the member functions of the class. Message map is preferred than virtual functions due  to avoid following drawbacks:

  1. Most windows only process a small number of messages, yet each window require to giant virtual function table with the entries of each message.

  2. More efficient and use less space then virtual functions.

  3. Virtual functions don't handle user defined messages and other custom cases.

All About Design Patterns

· One min read

Definition

Design Patterns represent solutions to problems that arise when developing software within a particular context. Patterns help you learn from other's successes, instead of your own failures. Mark Johnson (cited by Bruce Eckel)

Types of Design Patterns

There are three types of design patterns

  1. Creational Patterns: Creational Patterns deals with initializing and configuring classes and objects
  2. Structural Patterns: Structural Patterns deals with decoupling the interface and implementation of classes and objects
  3. Behavioral Patterns: Behavioral Patterns deals with dynamic interactions among societies of classes and objects

These three design patters are divided in to 22 different kinds of patterns as shown below.