static IMessageIn ParseMessage(JToken root) { // If `root` isn't a JSON object, throws. // If there is no such field, we get a null. var channel = (string)root["channel"]; if (channel == null) { _log.Error("Incoming message without a channel. Ignoring it."); return(null); } Func <IMessageIn> ctor; if (!_messageCtors.TryGetValue(channel, out ctor)) { _log.Error("Incoming message with unknown `channel`: '{0}'. Ignoring it.", channel); return(null); } IMessageIn msg = ctor.Invoke(); string errorcode = (string)root["errorcode"]; if (errorcode != null) { msg.Error = (ErrorCode)int.Parse(errorcode); return(msg); } // Note that data can be null. It expected for some messages. // MessageParser will throw if it doesn't like null data. JToken data = root["data"]; try { return(msg.Visit(new MessageParser(data))); } catch (Exception e) { _log.Error(e, "Unable to parse incoming message. Ignoring it."); return(null); } }
public static string FromMessage(IMessageIn msg) { return(msg.Visit(new MessageChannel())); }