Command Filter

The Command Filter feature in SuperSocket looks like Action Filter in ASP.NET MVC, you can use it to intercept execution of Command, the Command Filter will be invoked before or after a command execution.

Command Filter class must inherit from Attribute CommandFilterAttribute:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public abstract class CommandFilterAttribute : Attribute
{
    public abstract void OnCommandExecuting(IAppSession session, ICommand command);
 
    public abstract void OnCommandExecuted(IAppSession session, ICommand command);
}

There are two methods you should to implement for your command filter:
OnCommandExecuting: This method is called before the execution of the Command;
OnCommandExecuted: This method is called after the execution of the Command;

The following code defines a Command Filter LogTimeCommandFilterAttribute for recording the command execution time if the time is longer than 5 seconds. And the command filter is applied to the command "QUERY" by adding attribute:
public class LogTimeCommandFilterAttribute : CommandFilterAttribute
{
    public override void OnCommandExecuting(IAppSession session, ICommand command)
    {
        session.Items["StartTime"] = DateTime.Now;
    }
 
    public override void OnCommandExecuted(IAppSession session, ICommand command)
    {
        var startTime = session.Items.GetValue<DateTime>("StartTime");
        var ts = DateTime.Now.Subtract(startTime);
 
        if (ts.TotalSeconds > 5)
        {
            session.Logger.LogPerf(string.Format("A command '{0}' took {1} seconds!", command.Name, ts.ToString()));
        }
    }
}
 
[LogTimeCommandFilter]
public class QUERY : StringCommandBase<TestSession>
{
    public override void ExecuteCommand(TestSession session, StringCommandInfo commandData)
    {
        //Your code
    }
}

If you want to apply this command filter to all commands, you should add this Command Filter Attribute to your AppServer class like the following code:
[LogTimeCommandFilter]
public class TestServer : AppServer<TestSession>
{
    public TestServer()
        : base()
    {
 
    }
}

Last edited Jun 29, 2011 at 4:42 AM by kerryjiang, version 5

Comments

kerryjiang Sep 19, 2012 at 6:53 AM 
The command filter of SuperSocket 1.5 supports the feature you requested.

ShannaraAK Sep 16, 2012 at 7:50 PM 
Hmm, the edit command is missing on this site. Anyhow, I have noticed a inconsistency, perhaps?

In your second code set, is the 2nd class in that set suppose to reference the Attribute, since the LogTimeCommandFilter class doesn't exist? ie:

[LogTimeCommandFilterAttribute]
public class QUERY : StringCommandBase<TestSession>
{


Besides the above, this is awesome. Since we can execute code before the command, how do we prevent the command itself from executing if we find something with the command data itself? For instance, we need to check for sql injection, hackers sending wrong data format, etc?