Sep 26, 2007

Make your Life easy for Debugging KSH Shell Script

One of the problem that’s comes while debugging the KSH script is to use echo command to check the script health.

Well KSH Script debugging in not very easy, one may want to test the script in a test environment and before publishing the script need to remove or comment debugging lines from source code.

Following mechanism could make you life easy.

Use following lines at the beginning of the script:

if [[ -z $DEBUG ]];then
alias DEBUG='# '
else
alias DEBUG=''
fi

Where ever you put a debugging line that is only for testing, use it in the following way:

DEBUG set –x

Or echo a parameter

DEBUG echo $PATH

Or set a parameter that is valid only during the test

DEBUG export LOGFILE=/tmp

Now the trick is before executing the script, set the DEBUG variable in the KSH shell as

# export DEBUG=yes

While the execution of the script, the DEBUG lines will be executed. Now when the script is published if you happen to forget deletion of the debuging lines; they shall never disturb the script execution.

Example
#!/usr/bin/ksh
#export DEBUG=yes # if u want to include debuging line

#export DEBUG="" # if u want to remove debuging line

if [[ -z $DEBUG ]];then
alias DEBUG='# '
else
alias DEBUG=''
fi

LOG_FILE=./out/script.out
DEBUG LOG_FILE=./out/script.out

function add {
a=$1 b=$2
return $((a + b))

}

# MAIN


DEBUG echo "test execution"
DEBUG echo "$(date) script execution" >>$LOG_FILEDEBUG


echo "if you do not know it:"

add 2 2echo " 2 + 2 = $?"

Make your life easy……

Sep 21, 2007

Input String Validation

What if your validation logic just requires allowing only alphanumeric string with some special characters

Lets say it must not allow any special characters except (dollar sign $, underscore _, hyphen - , asterisk* and question mark?)

There could be many ways to implement the logic, but I love to do it using regular expressions.

So just use RegEx ValidString = new RegEx("^[-_A-Za-z0-9\?\*\*]$"); to verify the input is a valid string.

Ok job done, but what if you needs to identify the invalid character in user input.
The trick could be too just use the negative of above Regex.

RegEx InValidSplCharacter = new RegEx("[^-_A-Za-z0-9\?\*\*]");

So small way to do big things, this is what I love about Regular expression.

Sep 18, 2007

Process performance counter is disabled" exception on Process.GetProcessesByName ( )

TheLearnedOne:Here's another possibility:

http://forums.grouper.com/archive/index.php/t-134.html

Extract:

http://support.microsoft.com/default.aspx?scid=kb;en-us;Q248993

Even if you use the below procedure you shall get the same error. try it for your own.

Reenabling an Extension by Using Regedit.exe
WARNING: If you use Registry Editor incorrectly, you may cause serious problems that may require you to reinstall your operating system. Microsoft cannot guarantee that you can solve problems that result from using Registry Editor incorrectly. Use Registry Editor at your own risk.

Start Regedit.exe. (You cannot use Regedt32.exe because it does not allow searching for registry values.)
Click to select the following key
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services

Select Find from the Edit menu.
In the Find What field, type Disable Performance Counters.
Click Find Next. This will locate a Performance key that may have this Registry value set to 1.
If the Registry value is set to 1, set the value to 0 or delete the Registry value.
Press F3 to find the next occurrence of this Registry value.
Repeat the previous two steps until there are no Performance keys that have the Disable Performance Counters value set to 1.
NOTE: Often the "Disable Performance Counters" value does not appear in the registry. The value can be created and given a DWORD value of 1 to disable counters.


refer to this Microsoft article

http://support.microsoft.com/default.aspx?kbid=300956

Basically after Latest SP2 Service Pack Update - the files perfc009.dat and perfh009.dat become corrupted.

http://support.microsoft.com/default.aspx?scid=kb;EN-US;314958

make backups of the two files in \windows\system32 with a .bak extension just in case you need them later...

Here are the 2 files put into the \Windows\System32 folder and see your application running.

perfc009.dat (http://www.calforums.com/perfc009.dat)
perfh009.dat (http://www.calforums.com/perfh009.dat)


source: http://www.experts-exchange.com/Programming/Languages/.NET/Q_21285890.html

Working with the System.Diagnostic.Process Class


Working with the System.Diagnostic.Process Class

Introduction

The System.Diagnostic.Process class is used for the starting and stopping of processes; and controlling and monitoring application. With this powerful class you can gain access to information and use it to create an instance of an application or stop a running process. This FAQ will cover how to get a list of running process and how to start a new process by calling an executable or a register file extension (like .doc).



Why would you want to use the Process class? This class is the "Successor" to the Shell command in VB6. If you need to start an application with parameters, or get notified when it exits, this class provides the power and information you need.



Note: All code provide assumes that you have the Imported the System.Diagnostics namespace. The simplest way to do this is to add the following line of code at the top of your file. Also, for the code posted in this FAQ output is dumped to the Output window using the Debug.WriteLine method.


Code:
Imports System.Diagnostics


Getting Information

Getting information from the current process.

It's important to find out what information we can obtain from a Process, so let's take a look at the information available. This example will be using the GetCurrentProcess to retrieve a reference to the applications process component. To do this we will declare a variable and use the shared GetCurrentProcess method to retrieve the object reference. All further code in the section will build on this declaration.


Code:
Dim proc As Process = Process.GetCurrentProcess


Now that we have a reference to our Process, let's find out what information it can tell us. There is a lot of information you can retrieve from a Process Object. Here are just a few of them.


Code:
' Unique identifier for this process.

Debug.WriteLine(proc.Id.ToString)

' Name of the process.

Debug.WriteLine(proc.ProcessName)

' This process's native handle.

Debug.WriteLine(proc.Handle.ToString)

' Caption of the main window.

Debug.WriteLine(proc.MainWindowTitle)

' Window handle of the main window

Debug.WriteLine(proc.MainWindowHandle)

' Base Priority Information.

Debug.WriteLine(proc.BasePriority.ToString)

' Overall priority category

Debug.WriteLine(proc.PriorityClass.ToString)

' Number of handles this process has opened.

Debug.WriteLine(proc.HandleCount.ToString)

' Indicates whether the user interface of this process is responding.

Debug.WriteLine(proc.Responding.ToString)



There are more properties available including information on Processor and Memory usage.



Getting a list of the Current Processes

Getting a list of the current processes running on your system is an easy task. We can use the shared method GetProcesses() to retrieve this information. The GetProcesses() method returns an Array of Process components that we can further query to learn more about any given process.


Code:
' Declare a Process class.

Dim proc As Process

' Loop through the Processes and write the name of the Process to the output window.

For each proc In Process.GetProcesses

Debug.Writeline(proc.ProcessName)

Next


Starting a Process

Starting a Process with the Shared Start method.

Starting a Process is a manner of knowing what the path to the executable (or other object that can be started through the run command). The simplest way to do this is to use the Shared Start method of the Process class. This example will be using notepad.exe and a text file named info.txt.


Code:
' Start an instance of Notepad.

Process.Start("notepad.exe")

' Start an instance of Notepad and open the info.txt file.

Process.Start("notepad.exe", "c:\info.txt")

' Start an instance of the application that is registered to txt files.

' Just like you would double-click a file in Windows Explorer.

Process.Start("c:\info.txt")


On most systems, the "txt" extension is registered to the Notepad application. This will start a new instance of Notepad and open the info.txt file.



These shared methods offer a way to create a process, but if we need more control over the process we need to create an instance of the Process class itself and use the StartInfo object. Also the shared method will throw an error if we pass a file that is not registered with the system.



Starting a Process using the Process Class and the StartInfo object.

Starting a process using the StartInfo object is relatively easy. The only required property is StartInfo.FileName which is a string specifying what to start. So why would you use it. Simple, you can provide error handling if a file is not registered and specify the WindowStyle. Also creating an instance of the Process Class allows for notification when the process has exited through events. Below we will start notepad again and pass it the argument of "C:\info.txt"


Code:
' Create an Instance of the Process Class

Dim proc As New Process

' Provide the name of the application or file.

proc.StartInfo.FileName = "notepad.exe"

' Specify the arguments.

proc.StartInfo.Arguments = "c:\info.txt"

' Start the process.

proc.Start


Simple, right? Good.



Using Events to find out when a process has Exited.

The process class exposes two events; Disposed and Exited. Disposed is inherited from Component, Exited occurs when the process exits. First we need to create an event handler that will execute when the process exits. In our event handler, we will write the ExitCode and ExitTime properties to the output window.


Code:
Private Sub OnProcessExit(ByVal sender As Object, ByVal e As EventArgs)

' Avoid late binding and Cast the Object to a Process.

Dim proc As Process = CType(sender, Process)

' Write the ExitCode

Debug.WriteLine(proc.ExitCode)

' Write the ExitTime

Debug.WriteLine(proc.ExitTime.ToString)

End Sub


So now we have an event handler, but how do we get the event handler to fire? To do this we must add two lines of code before we start our process. We need to set EnableRaisingEvents to True in order for the events to fire. We must also add an event handler to trap the Exited event and run our OnProcessExit method.


Code:
Dim proc As New Process

' Provide the name of the application or file.

proc.StartInfo.FileName = "notepad.exe"

' Specify the arguments.

proc.StartInfo.Arguments = "c:\info.txt"

' This will allow the Exited event to fire.

proc.EnableRaisingEvents = True

' Add an event handler for this process.

' Run the OnProcessExit sub when this process exits.

AddHandler proc.Exited, AddressOf OnProcessExit

' Start the process.

proc.Start()


Now when the process exits, the Exited Event will be raised and our OnProcessExit method will be called.



Providing Error Handling

Providing error handling is a crucial part of any application. With the process method you will want to catch any error that is raised. The most common error is a file not found, the second most common error is dealing with files that are not registered to any particular application.



You can proactively avoid "file not found" errors by using the Shared Exists method of the System.IO.File class. We will use this later when we put everything together to create our StartProcess Method.


Code:
If System.IO.File.Exists(path) = False Then

Exit Sub

End If


Dealing with files that are not registered in the system is a little different. When you use Windows Explorer and try to open a file that is not registered, you are prompted with the "Open With" dialog and can then choose the application to open the file with. This functionality is provided by the Process class by setting the ErrorDialog Property in the StartInfo object to True.


Code:
proc.StartInfo.ErrorDialog = True


Putting it all together

Now that we have an understanding of the Process component and some of the things we can do, I am going to share two methods that I use for starting a Process.


Code:
' Method to Start a Process with Error Handling.

Private Sub StartProcess(ByVal Path As String)

' Declare the Process variable.

Dim proc As Process

' Ensure that the file exists

If System.IO.File.Exists(Path) = False Then

Exit Sub

End If

' Create the Process component.

proc = New Process

' Set EnableRaisingEvents to True.

proc.EnableRaisingEvents = True

' Add an event handler to trap the Exited event.

AddHandler proc.Exited, AddressOf OnProcessExit

' Build the StartInfo object.

' Set the FileName property to the argument that was passed.

proc.StartInfo.FileName = Path

' Enable the ErrorDialog.

proc.StartInfo.ErrorDialog = True

' Start the Process

proc.Start()

End Sub



' Event Handler for Process.Exited Event

Private Sub OnProcessExit(ByVal sender As Object, ByVal e As EventArgs)

' Avoid late binding and cast the Object to a specific Process component.

Dim proc As Process = CType(sender, Process)

' Write out the Exit information.

Debug.WriteLine(proc.ExitCode)

Debug.WriteLine(proc.ExitTime)

' Dispose and Clear the object.

proc.Dispose()

proc = Nothing

End Sub







source: http://vbcity.com/forums/topic.asp?tid=29605