The Main Method – Part 2

Today I am going to continue the series of posts about the Main method, in this post we will see how to develop an application to copy or move a file (the back-end) and an application with a user interface to use it (the front-end) as I mentioned last post, we will learn how to call an application from another, pass arguments to it and retrieve its return value. Note that this post is not intended to be a tutorial step-by-step on how to create a Windows Forms Application, but the source itself is somehow self-explanatory.

First of all I created a solution with two projects, a Windows Forms Application (front-end) and a Console Application (back-end) as you can see in Figure 1.

A solution with two projects

Figure 1

In the Windows Forms Application I created a form with some controls, as you can see in Figure 2.

Form with some controls.

Figure 2

Below is the source code from the main form:

using System;
using System.Diagnostics;
using System.Windows.Forms;

namespace Front_End
{
	public enum OperationType : byte
	{
		Copy,
		Move
	}

	public enum FileType : byte
	{
		Source,
		Dest
	}

	public enum ResultType : byte
	{
		Success,
		Failure
	}

	public partial class MainForm : Form
	{
		public MainForm()
		{
			InitializeComponent();
		}

		private void chooseFile_Click(object sender, EventArgs e)
		{
			Button button = sender as Button;

			FileType fileType = (FileType)Convert.ToByte(button.Tag);

			openFileDialog.CheckFileExists = fileType == FileType.Source;

			if (openFileDialog.ShowDialog() == DialogResult.OK)
			{
				switch (fileType)
				{
					case FileType.Source:
						sourceFileTextBox.Text = openFileDialog.FileName;
						break;
					case FileType.Dest:
						destFileTextBox.Text = openFileDialog.FileName;
						break;
				}
			}
		}

		private void executeOperationButton_Click(object sender, EventArgs e)
		{
			OperationType operationType = copyFileRadioButton.Checked ? OperationType.Copy : OperationType.Move;

			string operationTypeString = operationType == OperationType.Copy ? "copy" : "move";

			//prepare the arguments to send.
			string arguments =
				string.Format("operation=\"{0}\" sourceFile=\"{1}\" destFile=\"{2}\"",
				operationTypeString,
				sourceFileTextBox.Text,
				destFileTextBox.Text);

			//configure the back-end application to be executed.
			ProcessStartInfo processStartInfo = new ProcessStartInfo("Back-End.exe");
			processStartInfo.Arguments = arguments;
			processStartInfo.WorkingDirectory = Application.StartupPath;
			processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;

			Process process = new Process();
			process.StartInfo = processStartInfo;

			try
			{
				//starts the back-end application and waits until its termination.
				process.Start();
				process.WaitForExit();

				//takes the result from the back-end application and converts to an enum type.
				ResultType resultType = (ResultType)process.ExitCode;

				//in this case 0 stands for success and 1 failure.
				switch (resultType)
				{
					case ResultType.Success:
						//here the file should be copied or moved.
						MessageBox.Show("The operation succeeded!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
						break;
					case ResultType.Failure:
						MessageBox.Show("The operation failed!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
						break;
				}
			}
			catch (Exception exception)
			{
				MessageBox.Show("An error ocurred while trying to start the back-end application:\n" + exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
	}
}

Note that the definition used in the main method, the one that accepts an array of strings and a return value of int type. Below is the code from the back-end application, note that in order to work both applications the front and back-end must be in the same directory:

using System;
using System.IO;

namespace Back_End
{
	class Program
	{
		//return of 0 indicate success 1 failure.
		static int Main(string[] arguments)
		{
			string sourceFile = null;
			string destFile = null;
			string operationType = null;

			if (arguments.Length < 3)
			{
				//Not all arguments were suplied.
				return 1;
			}
			else
			{
				foreach (var argument in arguments)
				{
					if (argument.Contains("operation"))
					{
						if (string.IsNullOrEmpty(operationType))
							operationType = ExtractValueFromArgument(argument);
						else
							//Duplicated argument;
							return 1;
					}
					else if (argument.Contains("sourceFile"))
					{
						if (string.IsNullOrEmpty(sourceFile))
							sourceFile = ExtractValueFromArgument(argument);
						else
							//Duplicated argument;
							return 1;
					}
					else if (argument.Contains("destFile"))
					{
						if (string.IsNullOrEmpty(destFile))
							destFile = ExtractValueFromArgument(argument);
						else
							//Duplicated argument;
							return 1;
					}
					else
					{
						//Invalid argument;
						return 1;
					}
				}

				try
				{
					if (File.Exists(sourceFile) && Directory.Exists(Path.GetDirectoryName(destFile)))
					{
						switch (operationType)
						{
							case "copy":
								File.Copy(sourceFile, destFile);
								break;
							case "move":
								File.Move(sourceFile, destFile);
								break;
						}

						return 0;
					}
				}
				catch (Exception)
				{
					return 1;
				}

				//Just to satisfy definite assignment (C# Language Specification Version 3.0, September 2007, Section 5.3).
				return 1;
			}
		}

		static string ExtractValueFromArgument(string argument)
		{
			int index = argument.IndexOf("=");

			return argument.Substring(index + 1, argument.Length - index - 1);
		}
	}
}

Now you should be able to copy or move files by using these two applications that uses front-end/back-end concept and understand how important the Main method is for any application, many applications uses the Main method for receiving and returning values like zip compression tools that you can use a friendly user interface or a command prompt, image conversion tools like http://www.imagemagick.org/.

Hope you enjoyed the post.

See you.

Advertisements

About xcap2000

I'm just a developer who's interested in C# and Microsoft Technologies.
This entry was posted in C#. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s