Introduction
There are different ways to manipulate commands given through the Console. I am trying to figure out a way through which, if some one wants to add more commands to an existing application, he should be able to do it in such a way that he will come up with his class and that’s it. He will not need to update anything else in the existing application except that he should create his class by deriving it from my CommandBase and having to put an attribute “[Command(“his command eg. “-delete”)].
Requirement
In my example, the use case is this:
- I have a file named Test.xml in my C:\Temp.
- I have a command named –a, and I can pass data, let’s say, “test” to this console application.
- Test.xml is an encrypted file.
- When some one enters CommandManipulation.exe -a test1 from the Console, it will load the Test.xml, decrypt the file, add test1 to a node, encrypt the file, and save the file.
Procedural-oriented way of doing this
You will have a main class and will have a function named Add, and you will parse the string command, and if it is “-a”, using a switch statement, you will call the corresponding function.
Object-oriented way of doing this
You can combine the Design patterns, Template method, and Command Factory, and using a switch-case you can do the manipulation.
The C# way of doing this
With the help of custom attributes, you can eliminate the switch–case:
Type[] aTypeArray = Assembly.GetEntryAssembly().GetTypes();
foreach(Type aType in aTypeArray)
{
object[] commandAttributeArray =
aType.GetCustomAttributes(typeof(CommandAttribute), false);
if (commandAttributeArray.Length != 0)
{
CommandAttribute anAttribute =
(CommandAttribute)commandAttributeArray[0];
if (theCommandTable.Contains(anAttribute.CommandName))
return (CommandBase)Activator.CreateInstance(aType);
}
}
How to add a new command
A new command can be plugged in simply like this:
[Command(“-m”)]
class Modify : CommandBase
{
protected override void Run(string theData)
{
}
}
No switch-case, and no code adding to the main program.