Search This Blog

Friday, April 5, 2013

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

Thursday, March 21, 2013

How to Print the Key and Value of PHP Array?

$data = array(
    "1"   => "One",   
    "A" => "Apple",
    "B"    => "Ball",
    "C"  => "Cat"
);

foreach ($data as $key => $value)
{
  echo $key."=".$value;
  echo "<br/>";
}

Output:


1=One
A=Apple
B=Ball
c=Cat

Wednesday, February 20, 2013

How to Automate Button OR Check box click?

We can automate command button click or check box of another running  application using the following sample code.

To automate, first we need the window handle of the application that we need to automate. We can get the handle by using FindWindow() API.


struct stUserInterFace
{
HWND handle;
LPCTSTR lpCaption;
};



BOOL CALLBACK GetAllButtons(HWND handle,LPARAM lpParam)
{
    stUserInterFace *ptrStUI=NULL;
    ptrStUI=(stUserInterFace*)lpParam;
    HWND hwndBtn=ptrStUI->handle;

    TCHAR    szClassName[128];
    GetClassName(handle,(LPSTR)&szClassName,sizeof(szClassName));

    if (_tcscmp(szClassName,_T("ThunderRT6CommandButton")) == 0 ||_tcscmp(szClassName,_T("Button")) == 0 )
    {
        TCHAR szCaption[128];
        GetWindowText(handle,(LPSTR)&szCaption,sizeof(szCaption));

        if (_tcscmp(szCaption,ptrStUI->lpCaption) == 0)
        {
            ptrStUI->handle = handle;
            return FALSE; // no more child windows
        }
    }
return TRUE;
}


BOOL ClickButton(HWND hWnd,LPCTSTR lpButtonCaption)
{
    BOOL bRet=FALSE;
    HWND    hwndBtn=NULL;

    stUserInterFace *ptrUI=new stUserInterFace;
    ptrUI->lpCaption=lpButtonCaption;
    
    EnumChildWindows(hWnd,GetAllButtons,(LPARAM)ptrUI);
    if (ptrUI->handle != NULL) 
    {
        PostMessage(ptrUI->handle,BM_CLICK,0,0);    
        bRet=TRUE;
    }
    delete ptrUI;
    return bRet;
}
BOOL CheckBox(HWND hWnd,LPCTSTR lpButtonCaption)
{
    BOOL bRet=FALSE;
    HWND    hwndBtn=NULL;

    stUserInterFace *ptrUI=new stUserInterFace;
    ptrUI->lpCaption=lpButtonCaption;
    
    EnumChildWindows(hWnd,GetAllButtons,(LPARAM)ptrUI);
    if (ptrUI->handle != NULL) 
    {
        PostMessage(ptrUI->handle,BM_SETCHECK,1,0);    
        bRet=TRUE;
    }
    delete ptrUI;
    return bRet;
}
 
Usage: 
        ShellExecute(NULL,NULL,"Test.EXE",NULL,NULL,SW_SHOW);
 Sleep(2000);
 HWND hwnd=::FindWindow(NULL,"Test");

 if(hwnd!=NULL)
 {
  ClickButton(hwnd,"TestButton");
 }