Search This Blog

Friday, April 12, 2013

How To Find 64-bit Operating System?

During installation of a software we copy the files based on 32-bit or 64-bit operation system.

For example,
In 64-bit OS,  we install 32-bit applications in to "C:\Program Files (x86)" folder and 64-bit into "C:\Program Files" folder by default.

Like that we load different DLLs(based on compilation method as 32 or 64 bit) based on the OS architecture to improve the speed of the process.

The following function code helps you to find whether OS installed is 32 or 64-bit Operating System.



BOOL Is64BitOS()
{
    typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO);
    PGNSI pGNSI;
    SYSTEM_INFO sysinfo;
    ZeroMemory(&sysinfo, sizeof(SYSTEM_INFO));
    pGNSI = (PGNSI) GetProcAddress(
      GetModuleHandle(TEXT("kernel32.dll")), 
      "GetNativeSystemInfo");

    if(NULL != pGNSI)
    {
      pGNSI(&sysinfo);
    //GetNativeSystemInfo(&sysinfo);
    if(PROCESSOR_ARCHITECTURE_AMD64==sysinfo.wProcessorArchitecture)
        return TRUE;
    else
        return FALSE;
    }
    else
        return FALSE;
}

Backup the MySql Database using PHP

 When we are running a website, usually people take backup of their database regularly.
For that they usually open MySql database using PhpMyAdmin and export the database in to a file.

In the below example. I am reading all the table name from  "my_db_name" DB. then  In the each table I am reading all the records. From the each records with the field name and the values, I am creating a insert query for that table.

This process is done recursively for all the table.
In the usage, I just displaying the database dumb.
You can modify it such that writing it into a file and downloading itautomatically.

I hope it would save a lot of time in doing your regular database backup activity.

<?php
define('DB_NAME','my_db_name');
class BackupDB{
    public function getTables() {
        $table_data = array();
        $sql = "SHOW TABLES FROM `" . DB_NAME. "`";
        $query = mysql_query($sql) or die(mysql_error());
        while($result = mysql_fetch_array($query))
        {
            if (isset($result['Tables_in_' . DB_NAME])) {
                    $table_data[] = $result['Tables_in_' . DB_NAME];
                }       
        }
       
        return $table_data;
    }
   
    public function backup() {
    $tables=$this->getTables();
        $output = '';

        foreach ($tables as $table) {
            $status = true;
            if ($status) {
                $output .= 'TRUNCATE TABLE `' . $table . '`;' . "\n\n";
           
                $sql = "SELECT * FROM `" . $table . "`";
                $query = mysql_query($sql) or die(mysql_error());
           
                while($result = mysql_fetch_array($query)) {
                    $fields = '';
                   
                    foreach (array_keys($result) as $value) {
                        $fields .= '`' . $value . '`, ';
                    }
                   
                    $values = '';
                   
                    foreach (array_values($result) as $value) {
                        $value = str_replace(array("\x00", "\x0a", "\x0d", "\x1a"), array('\0', '\n', '\r', '\Z'), $value);
                        $value = str_replace(array("\n", "\r", "\t"), array('\n', '\r', '\t'), $value);
                        $value = str_replace('\\', '\\\\',    $value);
                        $value = str_replace('\'', '\\\'',    $value);
                        $value = str_replace('\\\n', '\n',    $value);
                        $value = str_replace('\\\r', '\r',    $value);
                        $value = str_replace('\\\t', '\t',    $value);           
                       
                        $values .= '\'' . $value . '\', ';
                    }
                   
                    $output .= 'INSERT INTO `' . $table . '` (' . preg_replace('/, $/', '', $fields) . ') VALUES (' . preg_replace('/, $/', '', $values) . ');' . "\n";
                }
               
                $output .= "\n\n";
            }
        }
       
        return $output;   
    }
}
?>

Usage:
$objBackup    = new BackupDB ( );
echo $objBackup->backup();

How to Paste in MFC Editbox from Clipboard?

When we automating a process, sometime we need to copy some values to clipboard and paste it to a edit box from the clipboard.

In the below example, I created a edit box with the name m_edEditbox, then I am setting focus to that edit box.

Normally we use ctrl+v as the shortcut to paste in windows.

I am generating the ctrl+v keyboard event programatically using the following code.
 
 

    m_edEditBox.SetFocus();
    Sleep(100);
    keybd_event( VK_CONTROL, MapVirtualKey( VK_CONTROL, 0 ), 0, 0 );
    Sleep(100);
    keybd_event( 'V', MapVirtualKey( 'V', 0 ),  0, 0 );
    Sleep(100);
    keybd_event( 'V', MapVirtualKey( 'V', 0 ), KEYEVENTF_KEYUP, 0 );
    Sleep(100);
    keybd_event( VK_CONTROL, MapVirtualKey( VK_CONTROL, 0 ), KEYEVENTF_KEYUP, 0 );
    Sleep(100);

Extract All Digits From A String

Sometimes we may need to extract only digits from a string.

For example,
When we display a phone number we display as 001-00-100-200, some thing like that.
but when we save this number is a database as integer, then we need to remove hyphen and other characters.

In such situation we can use this following function.
 
 

CString GetAllDigits(LPCSTR lpTxt)
{
    CString csDigits;
    for(;*lpTxt!='\0'; lpTxt++)
    {
        if(*lpTxt>=48 && *lpTxt <58)
        {
            csDigits += *lpTxt;
        }
    }
    return csDigits;
}

Count Digits, Alphabets, Special Characters and Total number of characters

Some software have option to find the number of digits, alphabets, special characters and total number of  characters.

This type of functions are helpful is parsing texts. This function uses the ASCII values of each characters and gives the count.  Zip code in Canada has alphabets and numbers for such type of validation, we can use this function.

This function accept a string as pointer to a character and  give the count as reference.



unsigned int CountLetters(LPCTSTR lpTxt, unsigned int &nAlphabetCount, unsigned int &nDigitCount, unsigned int &niSpecialCharCount)
{
    unsigned int nLength =0; 
    nAlphabetCount = 0;
    nDigitCount = 0;
    niSpecialCharCount =0;

    for(;*lpTxt!='\0'; lpTxt++)
    {
        if( (*lpTxt>='a'  && *lpTxt <='z') || (*lpTxt>='A'  && *lpTxt <='Z'))
        {
            nAlphabetCount++;
        }
        else if(*lpTxt>=48 && *lpTxt <58)
        {
            nDigitCount++;
        }
        else if( *lpTxt < 127 && *lpTxt>32 && *lpTxt != 160)
        {
            niSpecialCharCount++;
        }
        nLength++;
    }
    return nLength;
}

Counting Number Of Digits In C++

We validate phone numbers, Zip code, credit card numbers, etc using number of digits.

How to get the number of digits?

 When we have a number as the  string  then we can find the count by using the ASCII value.
ASCII value of '0' is 48 and '9' is 57. we have to check the ASCII of each character and if it matches the numerical range then we have increase the count.

Following function helps us to count the number of digits



unsigned int CountDigits(LPCTSTR lpTxt)
{
    unsigned int nCount =0;
    for(;*lpTxt!='\0'; lpTxt++)
    {
        if(*lpTxt>=48 && *lpTxt <58)
            nCount++;
    }
    return nCount;
}

Deleting A Directory in C++

When we delete a directory programatically we can't delete it when there is some files or folders inside the directory.  We can delete only the empty folders.

Otherwise, We usually delete  recursively search and delete all files and then we delete all folders and finally we delete the folder which we want to delete.

But the following code snippet uses shell operation and delete the directory directly without any recursive function.

It is faster than the recursive function.

 
bool DeleteDirectory(LPCTSTR lpszDir)
{
 int len = _tcslen(lpszDir);
 TCHAR *pszFrom = new TCHAR[len+2];
 _tcscpy(pszFrom, lpszDir);
 pszFrom[len] = 0;
 pszFrom[len+1] = 0;

 SHFILEOPSTRUCT fileop;
 fileop.hwnd   = NULL;    // no status display
 fileop.wFunc  = FO_DELETE;  // delete operation
 fileop.pFrom  = pszFrom;  // source file name as double null terminated string
 fileop.pTo    = NULL;    // no destination needed
 fileop.fFlags = FOF_NOCONFIRMATION|FOF_SILENT;  // do not prompt the user

 

 fileop.fAnyOperationsAborted = FALSE;
 fileop.lpszProgressTitle     = NULL;
 fileop.hNameMappings         = NULL;

 int ret = SHFileOperation(&fileop); 
 delete [] pszFrom;  
 return (ret == 0);
}