using System; using System.Collections.Generic; using System.Web.Script.Serialization; namespace ISphereWinHelper { internal static class HelperProtocol { public const string Protocol = "isphere.helper.v1"; private static readonly JavaScriptSerializer Serializer = new JavaScriptSerializer { MaxJsonLength = 16 * 1024 * 1024, RecursionLimit = 256 }; public static bool TryParseRequest(string text, out Dictionary request, out string requestId, out string op) { request = null; requestId = ""; op = ""; if (string.IsNullOrWhiteSpace(text)) { return false; } try { object decoded = Serializer.DeserializeObject(text); request = decoded as Dictionary; if (request == null) { return false; } string protocol = GetString(request, "protocol", ""); requestId = GetString(request, "request_id", ""); op = GetString(request, "op", ""); if (protocol != Protocol || string.IsNullOrWhiteSpace(op)) { return false; } return true; } catch { return false; } } public static Dictionary Success(string requestId, string op, object data) { return Envelope(requestId, op, true, data, null); } public static Dictionary Failure(string requestId, string op, string code, string message) { var error = new Dictionary { { "code", code }, { "message", message } }; return Envelope(requestId, op, false, null, error); } private static Dictionary Envelope(string requestId, string op, bool ok, object data, object error) { return new Dictionary { { "protocol", Protocol }, { "request_id", requestId ?? "" }, { "op", op ?? "" }, { "ok", ok }, { "data", data }, { "error", error }, { "warnings", new object[0] } }; } public static string ToJson(object value) { return Serializer.Serialize(value); } public static Dictionary GetObject(Dictionary source, string key) { if (source == null || !source.ContainsKey(key) || source[key] == null) { return new Dictionary(); } return source[key] as Dictionary ?? new Dictionary(); } public static string GetString(Dictionary source, string key, string defaultValue) { if (source == null || !source.ContainsKey(key) || source[key] == null) { return defaultValue; } return Convert.ToString(source[key]); } public static bool GetBool(Dictionary source, string key, bool defaultValue) { if (source == null || !source.ContainsKey(key) || source[key] == null) { return defaultValue; } try { return Convert.ToBoolean(source[key]); } catch { return defaultValue; } } public static int GetInt(Dictionary source, string key, int defaultValue) { if (source == null || !source.ContainsKey(key) || source[key] == null) { return defaultValue; } try { return Convert.ToInt32(source[key]); } catch { return defaultValue; } } } }