- OrchardCommand attribute for command aliases and unit test.

--HG--
branch : dev
This commit is contained in:
Suha Can
2010-04-05 17:31:34 -07:00
parent f589720049
commit 5533fa1caf
4 changed files with 44 additions and 6 deletions

View File

@@ -24,11 +24,23 @@ namespace Orchard.Tests.Commands {
CommandContext commandContext = new CommandContext { Command = "NoSuchCommand" };
Assert.Throws<InvalidOperationException>(() => _handler.Execute(commandContext));
}
[Test]
public void TestCommandWithCustomAlias() {
CommandContext commandContext = new CommandContext { Command = "bar" };
_handler.Execute(commandContext);
Assert.That(commandContext.Output, Is.EqualTo("Hello World!"));
}
}
public class StubCommandHandler : DefaultOrchardCommandHandler {
public string Foo() {
return "Command Foo Executed";
}
[OrchardCommand("bar")]
public string Hello() {
return "Hello World!";
}
}
}

View File

@@ -0,0 +1,17 @@
using System;
namespace Orchard.Commands {
[AttributeUsage(AttributeTargets.Method)]
public class OrchardCommandAttribute : Attribute {
private readonly string _commandAlias;
public OrchardCommandAttribute(string commandAlias) {
_commandAlias = commandAlias;
}
public string Command {
get { return _commandAlias; }
}
}
}

View File

@@ -13,13 +13,21 @@ namespace Orchard.Commands {
#region Implementation of ICommandHandler
public void Execute(CommandContext context) {
MethodInfo methodInfo = GetType().GetMethod(context.Command);
if (methodInfo != null) {
context.Output = (string) methodInfo.Invoke(this, null);
}
else {
throw new InvalidOperationException(T("Command : ") + context.Command + T(" was not found"));
foreach (MethodInfo methodInfo in GetType().GetMethods()) {
if (String.Equals(methodInfo.Name, context.Command, StringComparison.OrdinalIgnoreCase)) {
context.Output = (string)methodInfo.Invoke(this, null);
return;
}
foreach (OrchardCommandAttribute commandAttribute in methodInfo.GetCustomAttributes(typeof(OrchardCommandAttribute), false)) {
if (String.Equals(commandAttribute.Command, context.Command, StringComparison.OrdinalIgnoreCase)) {
context.Output = (string)methodInfo.Invoke(this, null);
return;
}
}
}
throw new InvalidOperationException(T("Command : ") + context.Command + T(" was not found"));
}
#endregion

View File

@@ -129,6 +129,7 @@
<Compile Include="Validation\Argument.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="Commands\CommandAttribute.cs" />
<Compile Include="Commands\CommandContext.cs" />
<Compile Include="Commands\DefaultOrchardCommandHandler.cs" />
<Compile Include="Commands\ICommandHandler.cs" />