CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Working with exe in ASP.Net – Calling, Killing/Aborting an exe

By Bala Murugan
Posted On April 25,2010
Article Rating:
Be first to rate
this article.
No of Comments: 1
Category: ASP.Net
Print this article.

Working with exe in ASP.Net – Calling, Killing/Aborting an exe

 

There will be requirements where we need to start and control an exe in server using an ASP.Net application.  Since web based applications have its own limitation one can’t achieve every complex requirements using a web application. At these times, it is possible to implement these complex requirements using a batch process or an exe.

Any application requires a user intervention or an event to start its processing. For example, we can use schedule task in windows or other scheduling softwares like controlm to initiate the process based on some time and conditions.  Sometimes, these scheduling mechanisms will not be an ideal choice when we have a requirement to initiate the process (exe) whenever required.

Well, this can be done by using Process class in System. Diagnostics namespace in ASP.Net.

Moving forward, we will see how this can be implemented using ASP.Net and C#.

 

Developing your exe

1.      Since, you are considering using asp.net application to initiate an exe there are chances where multiple users can initiate the exe at the same time. Design your exe to handle this.

2.      ASP.Net can just start your exe and will return to client. Develop your exe so that it can automatically end by releasing all its resources.

 

Steps

1.      Open a new Asp.Net web application in your Visual Studio 2008.

2.      To make the configurations easier, we will keep the exe location in the appsettings in web.config so that it can be configured easily when moving the application to different environments (from dev to prod).

       <appSettings>

              <add key="EXELOC" value="F:\Articles\Working With Exe in ASP.Net\Exe\DoComplexTask\DoComplexTask\bin\Debug\"/>

       </appSettings>

 

Calling an exe from ASP.Net

To call an exe, we need to use the Process class packed in System. Diagnostics namespace. 

The below code can be used to call an exe,

protected void btnSimpleStart_Click(object sender, EventArgs e)

    {

        string locn = ConfigurationManager.AppSettings["EXELOC"];

        Process.Start(locn + "DoComplexTask.exe");

    }

 

Note

The service account in which the ASP.Net is running should have proper access to exe location and should have all the access to the resources the exe is trying to access; else the above code will not start the exe.

 

At times, it is required to specify additional settings to have a control on the exe running the server.  The ProcessStartInfo class in System. Diagnostics namespace can help us in these scenarios to achieve our goal. Refer the code below,

 

protected void btnStart_Click(object sender, EventArgs e)

    {

        string locn = ConfigurationManager.AppSettings["EXELOC"];

        Process myProcess = new Process();

 

        try

        {

            myProcess.StartInfo.UseShellExecute = false;

            myProcess.StartInfo.FileName = locn + "DoComplexTask.exe";

            myProcess.StartInfo.CreateNoWindow = true;

            myProcess.Start();           

        

        }

        catch (Exception ex)

        {

            Response.Write(ex.Message);

        }

 

    }

 

The above is self explanatory, setting UseShellExecute to false will suppress the use of OS shell to execute the exe and setting CreateNoWindow to true will not open a window or cmd in the server when the exe is initiated.

 

Calling an exe with parameters or arguments

The exe can we are calling can take inputs using command line arguments. Again, to call an exe with command line arguments we can use the property called Arguments packed in ProcessStartInfo class. Refer the code below,

 

    protected void btnStartArgs_Click(object sender, EventArgs e)

    {

        string locn = ConfigurationManager.AppSettings["EXELOC"];

        Process myProcess = new Process();

        try

        {

            myProcess.StartInfo.UseShellExecute = false;

            myProcess.StartInfo.FileName = locn + "DoComplexTask.exe";

            myProcess.StartInfo.Arguments = "Hello";

            myProcess.StartInfo.CreateNoWindow = true;

            myProcess.Start();

 

        }

        catch (Exception ex)

        {

            Response.Write(ex.Message);

        }

 

    }

 

Calling an exe with multiple parameters or arguments

We can provide multiple parameters by separating the values with space and setting it in Arguments property. Refer below,

    protected void btnStartArgs_Click(object sender, EventArgs e)

    {

        string locn = ConfigurationManager.AppSettings["EXELOC"];

        Process myProcess = new Process();

        try

        {

            myProcess.StartInfo.UseShellExecute = false;

            myProcess.StartInfo.FileName = locn + "DoComplexTask.exe";

            myProcess.StartInfo.Arguments = "100 false";

            myProcess.StartInfo.CreateNoWindow = true;

            myProcess.Start();

 

        }

        catch (Exception ex)

        {

            Response.Write(ex.Message);

        }

 

    }

 

Checking if an exe is already running

The process class has some static methods like GetCurrentProcess() and GetProcessesByName() which can be used to get the current running process on the server. We can use these methods to find if the exe we are interested is currently running. The below code uses GetProcessesByName() method to find if an exe is already running in the server.

    protected void btnIsexeRunning_Click(object sender, EventArgs e)

    {

      

        if (Process.GetProcessesByName("DoComplexTask").Length > 0)

        {

            Response.Write("Exe already running!!");

        }

        else

        {

            Response.Write("Exe is not running!!");

        }

    }

 




If you don’t want multiple instances of exe running at the same time then you can check if the exe is already running using the above code and it can be initiated accordingly.

 

Killing or Aborting an exe

The Process class has a method called Kill() which can be used to kill or abort an exe which is already running in the server. The below code does that,

  public bool CheckIfProcessAlreadyRunning()

    {

        if (Process.GetProcessesByName("DoComplexTask").Length > 0)

        {

            return true;

        }

        return false;

    }

    protected void btnAbort_Click(object sender, EventArgs e)

    {

        string locn = ConfigurationManager.AppSettings["EXELOC"];

        if (CheckIfProcessAlreadyRunning())

        {

            foreach(Process proc in Process.GetProcessesByName("DoComplexTask"))

            {

                proc.Kill();

            }

        }

    }

 

Before calling the Kill() method, you need to ensure if the exe is currently running in the server else it will throw an Win32Exception exception.

 

The other thing to notice is, the Process.Kill() is an asynchronous method, meaning, it will just order for killing and it does not wait till the exe is fully aborted. The exe may take sometime to fully abort if it uses more resources or if it has some dependent process. Hence, if in case you need to do something just after killing the exe then you can call Process.WaitForExit() method to wait till it completes its exit. But remember, it will make your application to wait indefinitely till the exe is aborted. You can also check a property called HasExited to check if the process is completed.

 

Downloads

Download Source 

Steps to execute the attached code

1.      The sample code has a sample console application that puts an entry in a text file when started.

2.      Configure the logfile variable with a location on your machine.

       string logfile = @"F:\Articles\Working With Exe in ASP.Net\Exe\log.txt";

3.      Compile the console application.

4.      In the website project, configure the appsetting in the source to point to the right location of the exe. Set the website as start-up project and press F5.

5.      You can see an entry in log.txt whenever you call the exe.

 

Conclusion

Thus, we have seen how to call an exe from asp.net application. As we all know, ASP.Net or any web application will have some limitations when dealing with exe’s.  Hence, everything cannot be achieved with this; the exe should be designed and developed with care so that there is no adverse effect.

Download the code attached with this article and see it in action!

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Query
Hi,

everything works fine when I run my sample application from Visual Studio. after deploying the page on IIS 7, the code is executed without any error but it does run the exe as well.

do I need to take care of any other IIS setting?

Process myProcess = new Process();

try
{

myProcess.StartInfo.UseShellExecute = false;

myProcess.StartInfo.FileName = @"E:\Smart.exe"; ";

myProcess.StartInfo.CreateNoWindow = true;

myProcess.Start();

}

catch (Exception ex)
{

Response.Write(ex.Message);

}