Ooui-tws-port/Ooui/Message.cs

75 lines
2.0 KiB
C#
Raw Normal View History

2017-06-12 20:19:18 +00:00
using System;
2017-06-13 03:31:47 +00:00
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
2017-06-12 20:19:18 +00:00
namespace Ooui
{
public class Message
{
2017-06-13 03:31:47 +00:00
[JsonProperty("t")]
[JsonConverter (typeof (MillisecondEpochConverter))]
2017-06-12 20:19:18 +00:00
public DateTime CreatedTime = DateTime.UtcNow;
2017-06-13 03:31:47 +00:00
[JsonProperty("m")]
[JsonConverter (typeof (StringEnumConverter))]
2017-06-12 20:19:18 +00:00
public MessageType MessageType = MessageType.Nop;
2017-06-13 03:31:47 +00:00
[JsonProperty("id")]
2017-06-12 20:19:18 +00:00
public string TargetId = "";
2017-06-13 03:31:47 +00:00
[JsonProperty("k")]
public string Key = "";
[JsonProperty("v")]
2017-06-12 20:19:18 +00:00
public string Value = "";
public void SetValue (object value)
{
switch (value) {
case null:
Value = "null";
break;
case String s:
Value = EncodeString (s);
break;
default:
2017-06-13 03:31:47 +00:00
Value = JsonConvert.SerializeObject (value);
2017-06-12 20:19:18 +00:00
break;
}
}
public static string EncodeString (string s)
{
return s;
}
public static string DecodeString (string s)
{
return s;
}
}
public enum MessageType
{
Nop,
Create,
2017-06-12 20:45:27 +00:00
Set,
Call,
2017-06-12 20:19:18 +00:00
}
2017-06-13 03:31:47 +00:00
class MillisecondEpochConverter : DateTimeConverterBase
{
private static readonly DateTime epoch = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteRawValue (((DateTime)value - epoch).TotalMilliseconds.ToString (System.Globalization.CultureInfo.InvariantCulture));
}
public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.Value == null) return null;
return epoch.AddMilliseconds ((double)reader.Value);
}
}
2017-06-12 20:19:18 +00:00
}