Archive for April, 2008

How to Execute Command in C# ?

April 30, 2008

It is normal practice to open the command prompt and execute commands. The command when executed shows the result onto the screen. There are many commands that we execute daily such as dir, find etc. C# programmers have to code in diverse satiations. A situation may arise when you want to execute a (shell) command from the C# application. Don’t Worry!!! Here is the code to do so…

In the code given below we create a process i.e. a command process and then invoke the command that we want to execute. The result of the command is stored in a string variable, which can then be used for further references. The command execution can happen in two ways, synchronously and asynchronously.  In the asynchronous command execution we just invoke the command execution using a thread that runs independently.

using System;

using System.Threading;

 

namespace ExecuteCommand

{

    public class Program

    {

        static void Main(string[] args)

        {

            string command = String.Empty;

 

            // Write to the console.

            Console.Write(“Enter the command you wish to execute: “);

 

            // Get the command you wish to execute.

            command = Console.ReadLine().Trim();

 

            // Execute the command synchronously.

            ExecuteCmd exe = new ExecuteCmd();

            exe.ExecuteCommandSync(command);

 

            // Execute the command asynchronously.

            exe.ExecuteCommandAsync(command);

 

            // Your’ done !!!

            Console.WriteLine(“\nDone !”);

            Console.ReadLine();

        }

    }

 

    public class ExecuteCmd

    {

        #region ExecuteCommand Sync and Async

        /// <summary>

        /// Executes a shell command synchronously.

        /// </summary>

        /// <param name=”command”>string command</param>

        /// <returns>string, as output of the command.</returns>

        public void ExecuteCommandSync(object command)

        {

            try

            {

                // create the ProcessStartInfo using “cmd” as the program to be run, and “/c ” as the parameters.

                // Incidentally, /c tells cmd that we want it to execute the command that follows, and then exit.

                System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo(“cmd”, “/c “ + command);

                // The following commands are needed to redirect the standard output.

                //This means that it will be redirected to the Process.StandardOutput StreamReader.

                procStartInfo.RedirectStandardOutput = true;

                procStartInfo.UseShellExecute = false;

                // Do not create the black window.

                procStartInfo.CreateNoWindow = true;

                // Now we create a process, assign its ProcessStartInfo and start it

                System.Diagnostics.Process proc = new System.Diagnostics.Process();

                proc.StartInfo = procStartInfo;

                proc.Start();

 

                // Get the output into a string

                string result = proc.StandardOutput.ReadToEnd();

 

                // Display the command output.

                Console.WriteLine(result);

            }

            catch (Exception objException)

            {

                // Log the exception

            }

        }

 

        /// <summary>

        /// Execute the command Asynchronously.

        /// </summary>

        /// <param name=”command”>string command.</param>

        public void ExecuteCommandAsync(string command)

        {

            try

            {

                //Asynchronously start the Thread to process the Execute command request.

                Thread objThread = new Thread(new ParameterizedThreadStart(ExecuteCommandSync));

                //Make the thread as background thread.

                objThread.IsBackground = true;

                //Set the Priority of the thread.

                objThread.Priority = ThreadPriority.AboveNormal;

                //Start the thread.

                objThread.Start(command);

            }

            catch (ThreadStartException objException)

            {

                // Log the exception

            }

            catch (ThreadAbortException objException)

            {

                // Log the exception

            }

            catch (Exception objException)

            {

                // Log the exception

            }

        }

        #endregion

    }

}

Advertisements

How to delete a file in C# ?

April 29, 2008

Many times a C# programmer has to delete files present on the hard drive. Deleting a file in C# is very simple, since most of the functionality is already provided by .NET framework. Here is a code that first checks if a file exists at a given path and if so, then deletes the file.


/// <summary>

/// Deletes the specified file

/// </summary>

/// <param name="fileToDelete">File (path) to be deleted.</param>wi

/// <returns>bool value indicating whether the file was deleted.</returns>

public bool DeleteFile(string fileToDelete)

{

try

{

if (File.Exists(fileToDelete))

{

File.Delete(fileToDelete);

return true;

}

else

return true;

}

catch (Exception ex)

{

// Log the exception

return false;

}



}

How to Read/Write a text file in C#

April 28, 2008

Text files are used in most of the applications to store data, configuration etc. A developer often has to either read a text file or write some data to a text file. Microsoft .NET has provided easy access features that can be used for reading and writing a text file. There are three basic steps in reading or writing a text file:

1. Open a text file.

2. Read/Write the text file.

3. Close the text file.

In the step 1, we identify the text file that we want to operate on. Then we open the file using the objects of predefined classes provided by .NET. Once the file is opened, we are free to operate on it. After the completion of the operation i.e. read/write we should close the file so as to free the resources (Memory, File connection etc) occupied for performing the operation.

Below is the C# code that uses the above given principle to READ the text file and display it on the console output:

using System;

using System.IO;

namespace HowToReadATextFile

{

class FileReader

{

static void Main(string[] args)

{

// Create reader & open the file

Textreader tReader = new StreamReader(“Sample.txt”);

// Read a line of text

Console.WriteLine(tReader.ReadLine());

// Close the File Stream

tReader.Close();

}

}

}

Writing to a text file:

using System;

using System.IO;

namespace HowToWriteToATextFile

{

class FileWriter

{

static void Main(string[] args)

{

// Create a writer and open the file.

TextWriter tWriter = new StreamWriter(“Sample.txt”);

// Write a line of text to the file

tWriter.WriteLine(“Sample text inside the Sample.txt file!!”);

// Close the stream

tWriter.Close();

}

}

}

/////////////////////////////////////////////////////////////////////////////////////

How to Switch-Off the Monitor in C# ?

April 28, 2008

The desktop monitor can be switched-off programmatically using C#. We make use of Win32 API’s to switch-off the monitor. The programmatic monitor switch-off can be used to switch-off the monitor if the user is not using the computer i.e. if the computer is idle. This may help us save electric power.

As I said earlier we will be using the Win32 API SendMessage defined in user32.dll. In our C# code we will first import the user32.dll and declare the SendMessage function to be used as given below:

[DllImport(“user32.dll”)]

private static extern int SendMessage(

int hWnd, // handle to destination window
int hMsg, // message
int wParam, // first message parameter
int lParam // second message parameter
);

Parameters:

  • # hWnd (first parameter)
    Handle to the window whose window procedure will receive the message. If you don’t want to bother creating a window to send the message to, you can send the message to all top level windows (HWND_BROADCAST) or you can use GetDesktopWindow function sending the message to the desktop window.
  • # hMsg (second parameter)
    Specifies the message to be sent (i.e. WM_SYSCOMMAND).
  • # wParam(Third parameter)
    Specifies additional message-specific information (i.e. SC_MONITORPOWER).
  • # lParam (last parameter)
    * 1 – the display is going to low power.
    * 2 – the display is being shut off.
    * –1 – the display is being turned on (undocumented value).

Code to Switch-Off the monitor:

private int SC_MONITORPOWER = 0xF170;

private int WM_SYSCOMMAND = 0x0112;

[DllImport(“user32.dll”)]

private static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);

/// <summary>

/// This method will switch-iff the monitor.

/// </summary>

public void SwitchOffMonitor()

{

SendMessage(this.Handle.ToInt32(), WM_SYSCOMMAND, SC_MONITORPOWER, 2);

}

///////////////////////////////////////////////////////////////////

Participation in Microsoft Virtual TechDays!

April 24, 2008

Skyscrapr – A community for Aspiring Architects !

April 21, 2008

Good news for Aspiring Architects. Microsoft has started a new community for aspiring architects. It has many usefull content viz, articles, links, journals, case studies etc.

Visit: http://msdn2.microsoft.com/en-us/skyscrapr/default.aspx

Enjoy surfing architects !!

Nested functions in C#

April 18, 2008

We all have heard of nested classes, nested namespaces. Have we ever heard of nested function??? Can we write a nested function in C#???

The answer is Yes, we can write a nested function in C# using delegates. This article deals with writing nested methods in C#. Knowledge of delegates is required. For creating nested methods, we write anonymous methods and associate delegates with them.

//Declare a delegate which will point to different anonymous methods.

public delegate long FactorialDelegate(long n);

public void FunctionInFunction()

{


// Nested function.

FactorialDelegate FactorialMethod = delegate(long number)

{

if (number < 1)

throw new ArgumentOutOfRangeException(

“n”, “Argument must be greater than 0!”);

long result = 1;

// Calculate factorial

for (int iterator = 1; iterator <= number; iterator++)

result *= iterator;

return result;

};

// Nested function with recursion.

FactorialDelegate FactorialRecursive = delegate(long number)

{

if (number < 1) throw new

ArgumentOutOfRangeException(

“n”, “Argument must be greater than 0”);

// The current method will always be at the 0th frame on the stack.

MethodBase method = new StackTrace().GetFrame(0).GetMethod();

return number > 1 ? number * (long)method.Invoke(null,

new object[] { number – 1 }) : number;

};

Console.WriteLine(“Factorial for 5 = “ + FactorialMethod(5));

Console.WriteLine(“Factorial for 10 = “ + FactorialRecursive(10));

}

In the above example we have declared a delegate and in the method FunctionInFunction we are associating that delegate with two anonymous methods we defined. The first one is a normal method and the second anonymous method is recursive in nature. In the recursive method we have used reflection to get the recursive method name i.e. invoking this method. The current method will always be on the frame 0 of the stack trace.

Some properties of anonymous methods:

· It is an error to have a jump statement, such as goto, break, or continue, inside the anonymous method block whose target is outside the block. It is also an error to have a jump statement, such as goto, break, or continue, outside the anonymous method block whose target is inside the block.

· Unlike local variables, the lifetime of the outer variable (outer variable is a variable declared local to the outside wrapper function) extends until the delegates that reference the anonymous methods are eligible for garbage collection.

· An anonymous method cannot access the ref or out parameters of an outer scope.

· No unsafe code can be accessed within the anonymous-method-block.

For more info about anonymous functions click here.

How to add a program to Windows Startup ?

April 7, 2008

Adding a program/application to Windows Startup can be accomplished in various ways such as:

  • Modifying registry settings.
  • Writing to the startup files.

A list of registry keys that can start a program when Windows boots-up and some of the file to be modified is given below. You can add the programs to the below given keys, as required. In the article I have frequently used two root keys i.e. HKEY_LOCAL_MACHINE and HKEY_CURRENT_USER.
The HKEY_LOCAL_MACHINE registry sub-tree contains information about the local computer system, including hardware and operating system data, such as bus type, system memory, device drivers, and startup control parameters.
The HKEY_CURRENT_USER registry sub-tree contains the user profile for the user who is currently logged on to the computer. The user profile includes environment variables, personal program groups, desktop settings, network connections, printers, and application preferences. The data in the user profile is similar to the data stored in the Win.ini file in Windows 3. x.

Modifying Registry Keys
When we turn on the computer the registry keys are loaded in the following order:

RunServicesOnce
This key is designed to start services when a computer boots up. These entries can also continue running even after you log on, but must be completed before the HKEY_LOCAL_MACHINE\..\..\..\RunOnce registry can start loading its programs.
Registry Keys:

•HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce

•HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce

RunServices
This key is designed to start services also. These entries can also continue running even after you log on, but must be completed before the HKEY_LOCAL_MACHINE\…\RunOnce registry can start loading its programs.
Registry Keys:

•HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServices

•HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunServices
* Logon Prompt is placed on Screen. After a user logs in the rest of the keys are loaded.

RunOnce Local Machine Key
These keys are normally used by Setup programs. Entries in these keys are started once and then are deleted from the key (registry). If there an exclamation point preceding the value of the key, the entry will not be deleted until after the program completes, otherwise it will be deleted before the program runs. This is important, because if the exclamation point is not used, and the program referenced in this key fails to complete, it will not run again as it will have already been deleted. All entries in this key are started synchronously in an undefined order. The RunOnce keys are ignored under Windows 2000 and Windows XP in Safe Mode.
Registry Keys:

•HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce

•HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnceEx

Run
These are the most common startup locations for programs to install auto start from. By default these keys are not executed in Safe mode. If you want to run these keys in safe mode, then prefix asterisk (*) to the value of the key.
Registry Keys:

•HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run registry key

•HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run registry key

All Users Startup Folder
For Windows XP, 2000, and NT, this folder is used for programs that should be auto started for all users who will login to this computer. It is generally found at:

Windows XP C:\Documents and Settings\All Users\Start Menu\Programs\Startup

Windows NT C:\wont\Profiles\All Users\Start Menu\Programs\Startup

Windows 2000 C:\Documents and Settings\All Users\Start Menu\Programs\StartupUser Profile Startup Folder – This folder will be executed for the particular user who logs in. This folder is usually found in:

Win 9X, ME c:\windows\start menu\programs\startup

Windows XP C:\Documents and Settings\LoginName\Start Menu\Programs\Startup

RunOnce Current User Key
These keys are designed to be used primarily by Setup programs. Entries in these keys are started once and then are deleted from the key. If there a exclamation point preceding the value of the key, the entry will not be deleted until after the program completes, otherwise it will be deleted before the program runs. This is important, because if the exclamation point is not use, and the program referenced in this key fails to complete, it will not run again as it will have already been deleted. The RunOnce keys are ignored under Windows 2000 and Windows XP in Safe Mode. The RunOnce keys are not supported by Windows NT 3.51.
Registry Keys:

•HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce

Explorer Run
These keys is normally used to load programs as part of a policy set in place on the computer or user.
Registry Keys:

•HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run

•HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run

UserInit Key
This key specifies the program to be launched after a user logs into Windows. For example: HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\Userinit = C:\windows\system32\userinit.exe,c:\windows\badprogram.exe. If you observer carefully we have two comma separated programs listed above. The userinit.exe is a default program that loads users profile and should always be present in this key. You can add your own programs by separating them using comma.
Registry Keys:

•HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\Userinit

Notify
This key is used to add a program that will run when a particular event occurs. Events include logon, logoff, startup, shutdown, startscreensaver, and stopscreensaver. When Winlogon.exe generates an event such as the ones listed, Windows will look in the Notify registry key for a DLL that will handle this event. Malware has been known to use this method to load itself when a user logs on to their computer. Loading in such a way allows the malware program to load in such a way that it is not easy to stop.
Registry Keys:
•HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Notify

SharedTaskScheduler
This section corresponds to files being loaded through the SharedTaskScheduler registry value for XP, NT, 2000 machines.The entries in this registry run automatically when you start windows.
Registry Keys:

•HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\SharedTaskScheduler

You can also modify the below given files to add your programs to start-up:
c:\autoexec.bat
c:\config.sys
windir\winstart.bat
windir\win.ini – [windows] “load”
windir\win.ini – [windows] “run”
windir\system.ini – [boot] “shell”

Java Language Conversion Assistant (JLCA)

April 7, 2008

The Java Language Conversion Assistant (JLCA) is a tool that automatically converts existing Java-language code into C#. This tool accepts Java files and converts them to equivalent C# files. It creates its own project for doing so. Also TODO’s are inserted into your C# code wherein the JLCA converter fails to find the equivalent C# code. Version 1.0 of this tool ships with Visual Studio .NET 2003 and can be installed during Setup. This tool is also available with VS 2005. Now it becomes very easy for the developers to migrate their existing Java application to Microsoft .NET framework.
More information on this tool can be obtained from: http://msdn.microsoft.com/vstudio/java/migrate/jlca/default.aspx