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);
}

Friday, April 5, 2013

C# Utility Class To Create and Access MS Excel

This class can be used to create a Excel workbook and setting values in a particular cell.

Many times we need to save some values in excel and do some calculations programatically.
We usually automate  performance calculation and calculating percentage of improvement using the following class.

This class helps us to save your time in excel automation and performance calculation.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;

class CExcelHelper
{
    public int m_nCol;
    public int m_nRow;
    private Excel.Application m_oXL;
    private Excel._Workbook m_oWB;
    private Excel._Worksheet m_oSheet;
    private Excel.Range m_oRng;
    public void createExcel()
    {
        try
        {
            //Start Excel and get Application object.
            m_oXL = new Excel.Application();
            m_oXL.Visible = true;


            //Get a new workbook.
            m_oWB = (Excel._Workbook)(m_oXL.Workbooks.Add(Missing.Value));
            m_oSheet = (Excel._Worksheet)m_oWB.ActiveSheet;

            m_oXL.Visible = true;
            m_oXL.UserControl = true;
        }
        catch (Exception theException)
        {
            ErrMsg(ref theException);
        }
    }
    public bool SetValue(int nRow, int nCol, ref string strValue)
    {
        //Row and col should from 1S
        if (nRow < 1 || nCol < 1)
            return false;


        bool bRet = true;

        try
        {
            m_oSheet.Cells[nRow, nCol] = strValue;
        }
        catch (Exception e)
        {
            ErrMsg(ref e);
            return false;
        }
        return bRet;
    }

    public void CloseExcel()
    {
        m_oXL.Quit();
    }
    private void ErrMsg(ref Exception theException)
    {
        String errorMessage;
        errorMessage = "Error: ";
        errorMessage = String.Concat(errorMessage, theException.Message);
        errorMessage = String.Concat(errorMessage, " Line: ");
        errorMessage = String.Concat(errorMessage, theException.Source);
        MessageBox.Show(errorMessage, "Error");
    }
    public bool ApplyFormula(String strRangeStart, String strRangeEnd, string strFormula)
    {
        bool bRet = true;

        try
        {
            m_oRng = m_oSheet.get_Range(strRangeStart, strRangeEnd);
            m_oRng.Formula = strFormula;
        }
        catch (Exception e)
        {
            ErrMsg(ref e);
            return false;
        }
        return bRet;
    }
    private string RangeAddress(Excel.Range rng)
    {
        return rng.get_AddressLocal(false, false, Excel.XlReferenceStyle.xlA1);
    }
    public string CellAddress(int row, int col)
    {
        return RangeAddress(m_oSheet.Cells[row, col]);
    }
}
 
 
 
Usage:
//Excel Open
CExcelHelper objExcel = new CExcelHelper();
 objExcel.createExcel();
  string str="Sample";
 objExcel.SetValue(2, 1, ref str);

C# Code To Split String By Using Tabs As Delimmiter

We save some files as Tab delimited. In MS-Excel also have option to save the file as Tab delimited file. In that file there is a tab between each cells. We can read cell by cell using the following sample code.

Following Code snippet will split string using tab and store it in to a ArrayList.

public static void SplitTabs(string strText, ArrayList ArrTabs)
{

    int nStart = 0;
    int nPos = -1;
    int nLength = 0;
 //   strText = strText.Trim();
    nPos = strText.IndexOf("\t");
    if (nPos == -1 && strText.Length > 0)
    {
        ArrTabs.Add(strText);
    }
    while (nPos > -1)
    {
        nLength = nPos - nStart;
        string strLine = strText.Substring(nStart, nLength);
        strLine = strLine.Trim();

    //    if (strLine.Length > 0)
        {
            ArrTabs.Add(strLine);
        }
        nStart = nPos;
        nPos = strText.IndexOf("\t", nPos + 1);
        if (nPos == -1 && strText.Length > (nStart + 1)) //Last and remaining Text
        {
            strLine=strText.Substring(nStart );
            strLine = strLine.Trim();
            if (strLine.Length > 0)
            {
                ArrTabs.Add(strLine);
            }
        }
        nStart ++;

    }
}
Usage:
string strTxt = "'abc'\t'bcd'\t'xyz'";
ArrayList ArrLines= new ArrayList();
SplitTabs(strTxt, ArrLines);
 foreach (string str in ArrLines)
 {
      Console.WriteLine(str);
 }

Output:


C# Code to Split String Into Lines

In parsing some times we need to get the string line by line. We can split the line by line using the end of line character('\r\n'). We need to find its position and it can be splited suing sub-string functions and given below.

Following code snippet split the string in to lines and store it in a Array list.
public static void SplitLines(string strText, ArrayList ArrLines)
{
    int nStart = 0;
    int nPos = -1;
    int nLength = 0;
    char[] szTrim = { '\r', '\n' };
    strText = strText.Trim(szTrim);
    nPos = strText.IndexOf("\r\n");
    if (nPos == -1 && strText.Length > 0)
    {
        ArrLines.Add(strText);
    }
    while (nPos > -1)
    {
        nLength = nPos - nStart;
        string strLine = strText.Substring(nStart, nLength);
        strLine = strLine.Trim(szTrim);

        if (strLine.Length > 0)
        {
            ArrLines.Add(strLine);
        }
        nStart = nPos;
        nPos = strText.IndexOf("\r\n", nPos + 1);

        if (nPos == -1 && strText.Length > (nStart + 1)) //Last and remaining Text
        {
            strLine = strText.Substring(nStart);
            strLine = strLine.Trim(szTrim);

            if (strLine.Length > 0)
            {
                ArrLines.Add(strLine);
            }
        }

        nStart++;

    }
}
 
Usage:
 string strTxt = "abc \r\nbcd \r\nxyz";
 ArrayList ArrLines= new ArrayList();
 SplitLines(strTxt,ArrLines);


 
//To print result
 foreach (string str in ArrLines)
 {
    Console.WriteLine(str);
 } 


Output screenshot:
 
 

C# Code To Get The Folder Path Of A Executable

Following Code snippet will return the folder path of the current running application.
 public static string GetExePath()
 {
     string strPath = Application.ExecutablePath;
     string strBackSlash = @"\";
     int nPos = -1;
     if ((nPos = strPath.LastIndexOf(strBackSlash)) > -1)
     {
         strPath = strPath.Substring(0, nPos + strBackSlash.Length);
     }
     return strPath;
 }
 
 
Usage:
 string strpath = GetExePath();
 MessageBox.Show(strpath);

Screenshot:

 

C# Code To Extract Only Alphabets From A String

Sometimes we may need to remove all numbers and special characters from a string.
This can be done using ASCII vaues of characters.

Following code snippet will extract only alphabets  from a string using ASCII codes.

public static string GetAlphabets(string strText)
{
    string strAlphabets="";
    for(int i=0;i<strText.Length;i++)
    {
        char chr=strText[i];
        if(chr>=65 && chr<=90)
        {
            strAlphabets=strAlphabets+chr;
        }
        else if (chr >= 97 && chr <= 122)
        {
            strAlphabets = strAlphabets + chr;
        }
       
    }
    return strAlphabets;
}
 
             
Usage:
           string strTxt = "ABCD1234!@#$abcdefgh";
            Console.WriteLine("The string is " + strTxt);
            Console.WriteLine("Output: "+  GetAlphabets(strTxt));
 


Output:

C# Code To Execute a Command line Dos Exe and display the result


Some times we may need to execute a another command line executable file and display its result as string.
You can use the following code snippet for that.


public static string ReadOutputFromCmdExection(string strFileName, string strParameter)
{
    string StrResult = "";
    ProcessStartInfo start = new ProcessStartInfo();
    start.FileName = strFileName; // Specify Executable Name.
    start.UseShellExecute = false;
    start.Arguments = strParameter;
    start.RedirectStandardOutput = true;

    using (Process process = Process.Start(start))
    {
        //
        // Read in all the text from the process with the StreamReader.
        //
        using (StreamReader reader = process.StandardOutput)
        {
            StrResult = reader.ReadToEnd();
        }
    }
    return StrResult;
}
Usage:
 string strTxt = ReadOutputFromCmdExection(@"c:\windows\system32\ipconfig.exe","" );

Console.WriteLine(strTxt);





This helps to get the out put as string, so that we can parse it and use as we require.

Thursday, April 4, 2013

C# Code Excel Get Column Name Using Column Number

We use row and column number to access the values in Ms Excel cells.

In program we use  row and col as number. but When we open Excel Column is represented as alphabets as A, B, C......AA, AB, AC....



Following is the code to convert column number into Column name.


 

private string GetExcelColumnName(int columnNumber)
{
    int dividend = columnNumber;
    string columnName = String.Empty;
    int modulo;

    while (dividend > 0)
    {
    modulo = (dividend - 1) % 26;
    columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
    dividend = (int)((dividend - modulo) / 26);
    }

    return columnName;
}