public static ErrorCode ReadHeader(string message, out MessageType type, out long id) { type = MessageType.unknown; id = -1; StringReader reader = new StringReader(message); string strType = reader.ReadLine(); if (string.IsNullOrEmpty(strType) || !strType.StartsWith("type: ")) { return(ErrorCode.MessageFormatInvalid); } try { strType = strType.Substring(strType.IndexOf(": ") + 2); type = (MessageType)Enum.Parse(typeof(MessageType), strType); } catch (Exception) { return(ErrorCode.MessageTypeNotSupported); } string strId = reader.ReadLine(); if (string.IsNullOrEmpty(strId) || !strId.StartsWith("id: ")) { return(ErrorCode.None); } if (!long.TryParse(strId.Substring(strId.IndexOf(": ") + 2), out id)) { return(ErrorCode.MessageFieldConversionFailed); } string strCode = reader.ReadLine(); if (string.IsNullOrEmpty(strCode) || !strCode.StartsWith("code: ")) { return(ErrorCode.None); } uint code; if (!uint.TryParse(strCode.Substring(strCode.IndexOf(": ") + 2), out code)) { return(ErrorCode.MessageFieldConversionFailed); } return((ErrorCode)code); }
public static void WriteHeader(StringWriter writer, MessageType type, long id = -1, ErrorCode?code = null) { writer.NewLine = "\n"; writer.Write("type: {0}", type); if (id != -1) { writer.WriteLine(); writer.Write("id: {0}", id); } if (code != null) { writer.WriteLine(); writer.Write("code: {0:D}", code); } }