Friday, September 02, 2005

Regular Expression and special characters

It is a lot of fun to work with Regular expressions. They are slick, fast, and unstable when the underlying format changes. What else a developer could ask for?

In my current project, one of our developers stores a large SQL statement in his config file. The statement is formatted for readability. But when he executes his statement, he did not want the new lines and tabs.

I suggested using Regular Expressions. Since he is new to this area, I volunteered to help him out.

At first my code looked as below:
System.IO.StreamReader myFile =new System.IO.StreamReader(@"c:\BG\a.txt");string myString = myFile.ReadToEnd();myFile.Close();textBox1.Text = myString;myString = System.Text.RegularExpressions.Regex.Replace(myString,"\t","");myString = System.Text.RegularExpressions.Regex.Replace(myString,"\r\n","");myString = System.Text.RegularExpressions.Regex.Replace (myString," ","");textBox2.Text = myString;

He was happy with the outcome. Still, I wanted a single regular expression to perform this task. After a bit of digging, I came up with the following statement:

//Regular expression to eliminate new line, carriage returns, tabs, and multiple white spaces
myString = System.Text.RegularExpressions.Regex.Replace (myString,"\t\r\n ","");

I am happy! I hope this gives you an idea of how to create sets of characters for find and replace in regular expression. I could have used other choices like concatenating the find results into a string. But, it would take more coding.

If you can suggest a better solution, I am listening. :-)

Monday, March 28, 2005

Text Box and Auto Tab

Yesterday, I have joined Bangalore .NET group out of curiosity. I want to know the happenings of Silicon Valley of India. :-) Here is a question that came up on this group today.

Q: There are three text boxes on a Win Form. The objective is to capture telephone numbers. What to do in order for the tab to move to next text box when maximum number of charecters are entered?

A: First set the MaxLength for each textbox. In our case, it would be 3 for textBox1, 3 for textBox2, and 4 for textBox3. Then in the TextChanged event of respective text boxes, add the following code:

if (textBoxX.Text.Length == textBoxX.MaxLength)
textBoxY.Focus;

If you have a better suggestion, let me know.

Tuesday, January 25, 2005

Customizing VS.Net IDE

My next cube neighbor, Larry, had issues with saving his VS.NET 2003 IDE customizations. He keeps losing his tool bar placements and updates every time he modified them. Here is a little secret.

Open blank.sln from C:\Program Files\Microsoft Visual Studio .NET 2003\Common7\IDE\SolutionTemplates (or from the drive where you installed VS.Net) and customize it any way you want. Once you save this solution, all solutions you open in the future (even if it was created before this customization) will reflect your change.

This customization is similar to modifying Normal.dot in Word to include your standard header and footer.

This process is different from Visual Studio 6 IDE. In VS6, your changes specific to a project are saved in a seperate file. VS.Net Sln's companion SUO does not save these IDE customizations anymore.

The credit goes to Larry on this one. :-)

Wednesday, December 29, 2004

Disk Space, ASP.Net, and Application Config File

One of the guys I work with is in charge of creating a website for his department. His production server has only 4 gigs in C: and 120 gigs in D: . When he compiles his ASP.Net project, the temporary files goes into "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\Temporary ASP.NET Files" folder and it runs out of space frequently. He wanted to know whether there is a way to move the temporary files to D:

A little digging into .Net framework yielded positive response. Here is a link for those who wants to learn more about your application configuration file

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/gngrfcompilationsection.asp

Cheers

Wednesday, December 08, 2004

Purposeful VS.NET

One of my colleague is in charge of removing embedded URL in our company's website. He also wants to catalog the image references against these pages. His issue on hand is time and boredom as a result of monotonous task.

My suggestion was to use a handy tool to assist in this task - VS.Net editor.
1) Open empty project in VS.Net
2) Include all the files by selecting all the folders from the destination location and adding them to project (Add an Existing Item from right click menu)
3) Find (from 'Find in Files' box on the top of IDE) "http://www.mymagiccompany.com/" in the Entire Solution
4) Copy entire output to Excel. This will serve need to catalog.
5) Find and Replace <http://www.mymagiccompany.com/> with nothing in the Entire Solution
6) Format the Excel text to anyway he wants.

Now he is happy since it saved him many hours of repetitive task. If you have a better solution to this problem, let me know.

Additional notes:

1. Remember two important words before you mess up - Back Up :-)
2. Suppose your website is located on a different server and VS.Net is on your dev box. You might want to link the file (click on the down arrow in the File Open dialog's Open button) instead of copying it locally.

Friday, December 03, 2004

Kill A Process - Part 2

Here is the feedback I received from Julie:

"The KillProcess will kill the main.exe if I use the Id but not by name. When the main app is up, I ran the procman.exe so the form comes up, I then clicked on the Get All and main app shows in the list with its Id. I put main (it has an uppercase M) in the textbox and click Kill but it doesn't kill. I put in the Id and click Kill ID and it kills main app.

So, I am going to have to get the Id of main app by using the GetProcessList in my test code and store it in a vaiable and then use that variable for the Kill procesess. I am trying to do this now.

I got the other code OK that you told me in IM. proc.KillProcess("Main"); But, like I mentioned above, it didn't kill main app so I experimented with running your procman exe and found it will only kill it when I use main app's Id. This Id is different everytime so I have to Get it."

The issue on hand is enviornment related. If your machine is running low on memory and has several proceses running, the kill operation will be delayed until it gets it priority. Since the code loops through really fast and kills all instances, it appears as if nothing is happening. Here is my second version of KillProcessesByName()

///


/// KillProcessesByName: Kills ALL processes with name that matches the parameter
/// Do not include the extension of the process. Just use the first part.
/// E.g., To kill Command prompt, call KillProcess("cmd");
///

/// Name of the process to kill
/// Boolean value to indicate whether to kill processes using their ID. This one has an immediate effect on kill operation.
/// true if the operation succeeds. False, otherwise.
public bool KillProcessesByName(string ProcName, bool ByID)
{
bool retVal = false;
string procName2 = ProcName.ToUpper();
try
{
Process[] procsToKill = Process.GetProcessesByName(ProcName);
if (ByID)
{
for (int i= 0; i < procsToKill.Length; i++)
if (procsToKill[i].ProcessName.ToUpper().CompareTo(procName2) == 0)
{
Process pc2 = Process.GetProcessById(procsToKill[i].Id);
pc2.Kill();
}
}
else
{
foreach (Process pc in procsToKill)
{
pc.Kill();
}
}
retVal = true;
}
catch (System.Exception ex)
{
throw (ex);
}
return retVal;
}

Tuesday, November 30, 2004

Kill A Process

One of my ex-Colleague from Microsoft is a testing engineer. She comes up with interesting problems and I provide her with solutions. Her issue for today is 'How would I kill a running process?' and? my solution is given below (alignment got messed up a bit).

Disclaimer: Since this is a proof of concept, I have not implemented error handling to the extent I normally would. You can extend this to no end.
------------------------------------------------------------------------------------------------

using System;
using System.Text;
using System.Diagnostics;
namespace ProcessMananger
{
///

/// Summary description for ProcMan.
///

public class ProcMan { public ProcMan() { }
///
/// Get a list of all running processes in the current machine
///

/// A string of process ID and names
public string GetProcessList()
{
Process[] procList = Process.GetProcesses();
int listCount = procList.GetLength(0);
StringBuilder sbOutput = new StringBuilder();
for (int i = 0; i < listCount; i++)
{
sbOutput.Append(procList[i].Id);
sbOutput.Append(" ");
sbOutput.Append(procList[i].ProcessName);
sbOutput.Append(Environment.NewLine);
}
return sbOutput.ToString();
}

///
/// Stars a process or app. The app or name should be fully qualified
/// or its path must be in the PATH variable
/// E.g., To run Command prompt, call StartProcess("Cmd.exe");
///
///
/// true if the call was successful; false, otherwise
public bool StartProcess(string procName)
{
bool retVal = false;
try
{
Process.Start(procName);
retVal = true;
}
catch (System.Exception ex)
{
throw(ex);
}
return retVal;
}

///
/// KillProcessesByName: Kills ALL processes with name that matches the parameter
/// Do not include the extension of the process. Just use the first part.
/// E.g., To kill Command prompt, call KillProcess("cmd");
///

/// Name of the process to kill
/// true if the call was successful; false, otherwise
public bool KillProcessesByName(string procName)
{
bool retVal = false;
try
{
Process[] procsToKill = Process.GetProcessesByName(procName);
foreach (Process pc in procsToKill)
pc.Kill();
retVal = true;
}
catch (System.Exception ex)
{
throw (ex);
}
return retVal;
}

///
/// KillProcess: Kills first process with name that matches the parameter
/// Do not include the extension of the process. Just use the first part.
/// E.g., To kill Command prompt, call KillProcess("cmd");
///

/// Name of the process to kill
/// true if the call was successful; false, otherwise
public bool KillProcess(string procName)
{
bool retVal = false;
try
{
Process[] procsToKill = Process.GetProcessesByName(procName);
if (procsToKill.Length > 0 )
procsToKill[0].Kill();
retVal = true;
}
catch (System.Exception ex)
{
throw (ex);
}
return retVal;
}

///
/// KillProcess: Kills first process with ID that matches the parameter
/// E.g., To kill a process whose ID is 1120, call KillProcess(1120);
///

/// ID of the process to kill
/// true if the call was successful; false, otherwise
public bool KillProcess(int procID)
{
bool retVal = false;
try
{
Process procToKill = Process.GetProcessById(procID);
if (procToKill != null )
procToKill.Kill();
retVal = true;
}
catch (System.Exception ex)
{
throw (ex);
}
return retVal;
}
}
}
------------------------------------------------------------------------------------------------

Let me know what you think? Also, if you have any interesting questions or coding problems, I would love to tackle.

Cheers