Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Execute Console Application Using ASP.NET

4.67/5 (16 votes)
4 Jan 2016CPOL4 min read 55.5K  
Execute console application using ASP.NET web application

Introduction

This article describes a simple way to modify .NET EXE configuration and execute the console application using ASP.NET web application in the same server.

Background

Sometimes, we need to use console application to do a task (maybe console application to do reporting jobs), but we need to execute it using a web application. This article describes how to execute .NET console application using some parameters and a button to modify app.config and execute the application respectively.

Using the Code

Here, we will do these steps:

  1. Create a simple console application.
  2. Create a very simple ASP.NET web application (from empty project).
  3. Create two methods to modify app.config and execute console application by clicking a button.

1. Create a Simple Console Application

Okay, we start from the first step. In this step, we will create a simple console application using C# (I use Visual Studio 2012), we create a force killer application (name it ProcessKiller), with this application, we can kill application in background process, let's say Excel, Calculator, or whatever we want. This is just an example, you can create another console application that is suitable for your case.

The complete C# code is shown below, note that we need to include Configuration Manager (namespace System.Configuration) and Diagnostics (namespace System.Diagnostics) reference in our project, so do not miss it.

C#
using System;
using System.Collections;
using System.Configuration;
using System.Diagnostics;

namespace ProcessKiller
{
    class Program
    {
        static void Main(string[] args)
        {
            string ApplicationName = 
                   ConfigurationManager.AppSettings["ApplicationName"].ToString();

            Process[] Processes = Process.GetProcessesByName(ApplicationName);

            // check to kill the right process
            foreach (Process process in Processes)
            {
                process.Kill();
            }
        }
    }
}

C# code is complete, now we can do a little stuff in the app.config, we create application configuration node in app.config (note that the app.config file is a kind of XML file, so we will use XML library in our method call in ASP.NET).

We create a key-value pair in app.config, name the key ApplicationName, and set the value (for default value) "calc". All the code is something like this:

XML
<!--?xml version="1.0" encoding="utf-8" ?-->
<configuration>
	<appsettings>
		<add key="ApplicationName" value="calc">
	    </add>
    </appsettings>
</configuration>

We've done this step. Build the project.

2. Create a Very Simple ASP.NET Empty Web Application

We create a very simple web application (name it WebKiller), create project for an empty web application template, and add Default.aspx to the project. We only need to create a textbox to change the value of key ApplicationName in our console app.config, and we create a button that will execute the console application by clicking it.

The ASP code is shown below:

ASP.NET
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
    Inherits="WebKiller.Default" %>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head  runat="server">
    <title></title>
</head>
<body>
    <form id="form1"  runat="server">
        <div>
        <asp:TextBox ID="TextBox1" runat="server"> 
        <asp:Button ID="Button1" runat="server" 
        Text="Execute" OnClick="Button1_Click" />
        </div>
    </form> 
</body> 
</html>

Try to debug it, the web app will be something like below:

Okay, we've done the ASP code, remember the control ID in ASP, we need to use this in C# code. We are ready to do some logic in code behind.

3. Create Two Methods to Modify app.config and Execute Console Application by Clicking a Button

In this step, we will create the code behind the web application. We create an event method (on click) for the button that we've created, make sure you create the empty event method from event window in Visual Studio.

Now, we create a void method to change the app.config of console application, remember the key-value in app.config. We will call this method later in our button event method.

The method code will look like this. Name the method ChangeValueOfKeyConfig().

C#
private void ChangeValueOfKeyConfig(string ProcessName)
{
    // I locate the ProcessKiller Console Application in E drive.
    string tAppPath = @"E:\ProcessKiller\ProcessKiller\bin\Debug";

    string tProcessName = TextBox1.Text;

    string tAppPathWithConfig = @"" + tAppPath + "\\ProcessKiller.exe.config";
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(tAppPathWithConfig);

    foreach (XmlElement element in xmlDoc.DocumentElement)
    {
        if (element.Name == "appSettings")
        {
            foreach (XmlNode node in element.ChildNodes)
            {
                RenameItemConfig(node, "ApplicationName", ProcessName);
                //RenameItemConfig(node, "Other Key", "Other Value");
            }
        }
    }

    xmlDoc.Save(tAppPathWithConfig);
}

private void RenameItemConfig(XmlNode node, string Key, string value)
{
    if (node.Attributes.Item(0).Value == Key)
    {
        node.Attributes.Item(1).Value = value;
    }
}

Note that we can change the value of a key in an app.config file by using the RenameItemConfig() method. Then, we are ready to fill the button event method here. First, we need to "get" the value of a textbox that we've created, and then we need to locate the console application in path in which we want it to be executed, then we can call our ChangeValueOfKeyConfig() method in button click event method, and then again, we will open Command Prompt (CMD), and we will execute our console application via CMD with some commands. The complete code in Default.aspx.cs is shown below:

C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

namespace WebKiller
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            ChangeValueOfKeyConfig(TextBox1.Text);

            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.FileName = "cmd";
            process.StartInfo.WorkingDirectory = @"E:\ProcessKiller\ProcessKiller\bin\Debug";

            process.StartInfo.Arguments = "/c \"" + "ProcessKiller.exe" + "\"";
            process.Start();
        }

        private void ChangeValueOfKeyConfig(string ProcessName)
        {
            // I locate the ProcessKiller Console Application in E drive.
            string tAppPath = @"E:\ProcessKiller\ProcessKiller\bin\Debug";

            string tProcessName = TextBox1.Text;

            string tAppPathWithConfig = @"" + tAppPath + "\\ProcessKiller.exe.config";
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(tAppPathWithConfig);

            foreach (XmlElement element in xmlDoc.DocumentElement)
            {
                if (element.Name == "appSettings")
                {
                    foreach (XmlNode node in element.ChildNodes)
                    {
                        RenameItemConfig(node, "ApplicationName", ProcessName);
                        //RenameItemConfig(node, "Other Key", "Other Value");
                    }
                }
            }

            xmlDoc.Save(tAppPathWithConfig);
        }

        private void RenameItemConfig(XmlNode node, string Key, string value)
        {
            if (node.Attributes.Item(0).Value == Key)
            {
                node.Attributes.Item(1).Value = value;
            }
        }        
    }
}

Demo

Now we can demonstrate our project, we will force kill Excel application. What we need to do: Open/run the web application in our browser, and fill the input textbox with this word "excel" (all lower case), and before we click "Execute" button, we open Microsoft Office Excel, if the Excel opens, we click the "Execute" button. The console application will do its job, it will force kill/close the excel. Now, we've done it, you can do it with some change, you can close Calculator application by filling the input textbox with "calc", or the other application that is shown in Processes tab in Task Manager.

Points of Interest

Console application can be executed using web application in the same server in a simple way. With this method, we can create a console application to generate large Excel file or anything else. You can simplify and enhance this code for your case. Actually, you do not have to use this method in your real project, this method is only useful in very rare situations, but I hope this code can help people know how to do it.

History

  • 4th January, 2016: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)