[en] Server-side event filters (solved)

Topics: Technical Support
Nov 2 at 2:58 PM
Edited Nov 2 at 4:12 PM
Must server-side event filters use hardcoded comparisons? I've tried something like:
        chatProxy.Filtered += eventHandler.AddFilter((f, args) => args.Nickname == _nickname);
"_nickname" is a field with a value, and that doesn't work. However:
        chatProxy.Filtered += eventHandler.AddFilter((f, args) => args.Nickname == "Mark");
This works.

Does that mean that the value of _nickname won't serialize and the server doesn't know what to do with that? Do I need to hardcode the comparison, such as using "Mark"?
Coordinator
Nov 12 at 9:12 PM
No, they mustn't. The problem you are facing is related to LINQ expression serialization. Let me explain.

Your _nickname is a field, so the compiler embeds its value as Expression.Constant(YourClassInstance).Field("_nickname"). What happens here is that the expression includes the instance of your class, which is not what you wanted in the first place.

To overcome this, copy the field to a local variable, e.g.:
var nickname = _nickname;
chatProxy.Filtered += eventHandler.AddFilter((f, args) => args.Nickname == nickname);
And now it works. Explanation is actually simple: now the expression contains a compiler-generated closure class instance with a local copy of your _nickname field. LINQ expression now contains Expression.Constant(closure).Field("local_nickname"), and that is serializable.
Coordinator
Nov 12 at 9:17 PM
Also, there is another option.

You can create your own serializable event filter class, if your expression gets too complex.