public List <string> BuildWorld(Transform cameraPivot, VoxelArray voxelArray, bool editor) { this.editor = editor; MessagePackObjectDictionary worldDict = worldObject.AsDictionary(); CheckWorldValid(worldDict); fileWriterVersion = worldDict[FileKeys.WORLD_WRITER_VERSION].AsInt32(); EntityReference.ResetEntityIds(); try { ReadWorld(worldDict, cameraPivot, voxelArray); } catch (MapReadException e) { throw e; } catch (Exception e) { throw new MapReadException("Error reading world file", e); } EntityReference.DoneLoadingEntities(); return(warnings); }
private object ConvertFromMessagePackObject(MessagePackObject msgPackObject) { if (msgPackObject.IsTypeOf(typeof(long)) ?? false) { return(msgPackObject.AsInt64()); } if (msgPackObject.IsTypeOf(typeof(double)) ?? false) { return(msgPackObject.AsDouble()); } if (msgPackObject.IsArray) { return(msgPackObject.AsEnumerable().Select(ConvertFromMessagePackObject) .ToArray()); } if (msgPackObject.IsDictionary) { var msgPackDictionary = msgPackObject.AsDictionary(); return(msgPackDictionary.ToDictionary( keyValuePair => ConvertFromMessagePackObject(keyValuePair.Key), keyValuePair => ConvertFromMessagePackObject(keyValuePair.Value))); } var obj = msgPackObject.ToObject(); if (obj is MessagePackExtendedTypeObject msgpackExtObj) { return(GetExtensionType(msgpackExtObj)); } return(obj); }
/// <summary> /// Initialize new instance with unpacked data. /// </summary> /// <param name="rpcError"> /// Metadata of error. If you specify null, <see cref="MsgPack.Rpc.RpcError.RemoteRuntimeError"/> is used. /// </param> /// <param name="unpackedException"> /// Exception data from remote MessagePack-RPC server. /// </param> /// <exception cref="SerializationException"> /// Cannot deserialize instance from <paramref name="unpackedException"/>. /// </exception> protected internal RpcException( RpcError rpcError, MessagePackObject unpackedException ) : this( rpcError, unpackedException.GetString( MessageKeyUtf8 ), unpackedException.GetString( DebugInformationKeyUtf8 ) ) { if ( unpackedException.IsDictionary ) { MessagePackObject mayBeArray; if ( unpackedException.AsDictionary().TryGetValue( _remoteExceptionsUtf8, out mayBeArray ) && mayBeArray.IsArray ) { var array = mayBeArray.AsList(); this._remoteExceptions = new RemoteExceptionInformation[ array.Count ]; for ( int i = 0; i < this._remoteExceptions.Length; i++ ) { if ( array[ i ].IsList ) { this._remoteExceptions[ i ] = new RemoteExceptionInformation( array[ i ].AsList() ); } else { // Unexpected type. Debug.WriteLine( "Unexepcted ExceptionInformation at {0}, type: {1}, value: \"{2}\".", i, array[ i ].UnderlyingType, array[ i ] ); this._remoteExceptions[ i ] = new RemoteExceptionInformation( new MessagePackObject[] { array[ i ] } ); } } } } #if !SILVERLIGHT && !MONO this.RegisterSerializeObjectStateEventHandler(); #endif }
private static void FormatMsgPackMap(MessagePackObject obj, IndentedStringBuilder builder) { var map = obj.AsDictionary(); builder.Append('{'); // Indent builder.IncreaseIndent() .AppendLine(); foreach (var item in map) { FormatMsgPackObj(item.Key, builder); builder.Append(": "); FormatMsgPackObj(item.Value, builder); builder.AppendLine(","); } // Remove the trailing new line and comma builder.TrimLastLine() .Remove(builder.Length - 1, 1); // Unindent builder.DecreaseIndent() .AppendLine(); builder.Append('}'); }
private static void Dump(MessagePackObject obj, StringBuilder buffer, int indent) { if (obj.IsNil) { buffer.Append(' ', indent * 2).Append("(null)").AppendLine(); } else if (obj.IsTypeOf <IList <MessagePackObject> >().GetValueOrDefault()) { buffer.Append(' ', indent * 2).AppendLine("("); foreach (var child in obj.AsList()) { Dump(child, buffer, indent + 1); } buffer.Append(' ', indent * 2).AppendLine(")"); } else if (obj.IsTypeOf <IDictionary <MessagePackObject, MessagePackObject> >().GetValueOrDefault()) { buffer.Append(' ', indent * 2).AppendLine("{"); foreach (var child in obj.AsDictionary()) { Dump(child.Key, buffer, indent + 1); buffer.Append(' ', (indent + 1) * 2).AppendLine("= "); Dump(child.Value, buffer, indent + 2); } buffer.Append(' ', indent * 2).AppendLine("}"); } else { buffer.Append(' ', indent * 2).Append(obj).Append(" : ").Append(obj.UnderlyingType).AppendLine(); } }
public void TestNestedMap() { var output = new MemoryStream(); Packer.Create(output).Pack( new Dictionary <string, Dictionary <int, bool> >() { { "0", new Dictionary <int, bool>() }, { "1", new Dictionary <int, bool>() { { 0, false } } }, { "2", new Dictionary <int, bool>() { { 0, false }, { 1, true } } }, } ); MessagePackObject obj = UnpackOne(output); var outer = obj.AsDictionary(); Assert.AreEqual(3, outer.Count); Assert.AreEqual(0, outer["0"].AsDictionary().Count); Assert.AreEqual(1, outer["1"].AsDictionary().Count); Assert.That(outer["1"].AsDictionary()[0].AsBoolean(), Is.False.With.TypeOf <bool>()); Assert.AreEqual(2, outer["2"].AsDictionary().Count); Assert.That(outer["2"].AsDictionary()[0].AsBoolean(), Is.False.With.TypeOf <bool>()); Assert.That(outer["2"].AsDictionary()[1].AsBoolean(), Is.True.With.TypeOf <bool>()); }
public void TestGetExceptionMessage_True_IncludesDebugInformation() { bool includesDebugInformation = true; var properties = this.GetTestArguments(); TRpcException target = NewRpcException(ConstructorKind.WithInnerException, properties); MessagePackObject result = target.GetExceptionMessage(includesDebugInformation); var asDictionary = result.AsDictionary(); Assert.That( asDictionary.Values.Any(item => item == GetRpcError(properties).ErrorCode), "Expects containing:'{0}', Actual :'{1}'", GetRpcError(properties).ErrorCode, result.ToString()); Assert.That( asDictionary.Values.Any( item => item.IsTypeOf <string>().GetValueOrDefault() && item.AsString().Contains(GetMessage(properties))), Is.True, "Expects containing:'{0}', Actual :'{1}'", GetMessage(properties), result.ToString()); Assert.That( asDictionary.Values.Any( item => item.IsTypeOf <string>().GetValueOrDefault() && item.AsString().Contains(GetDebugInformation(properties))), Is.True, "Expects containing:'{0}', Actual :'{1}'", GetDebugInformation(properties), result.ToString()); }
private static object ParseResult(MessagePackObject obj) { if (obj.IsList) { List <object> data = new List <object>(); foreach (MessagePackObject objItem in obj.AsList()) { data.Add(ParseResult(objItem)); } return(data.ToArray()); } else if (obj.IsMap) { System.Collections.Hashtable data = new System.Collections.Hashtable(); foreach (var objItem in obj.AsDictionary()) { data.Add(ParseResult(objItem.Key), ParseResult(objItem.Value)); } return(data); } else { if (obj.UnderlyingType != null && resolver.ContainsKey(obj.UnderlyingType)) { return(resolver[obj.UnderlyingType](obj)); } } return(null); }
/// <summary> /// Initialize new instance with unpacked data. /// </summary> /// <param name="rpcError"> /// Metadata of error. If you specify null, <see cref="MsgPack.Rpc.RpcError.RemoteRuntimeError"/> is used. /// </param> /// <param name="unpackedException"> /// Exception data from remote MessagePack-RPC server. /// </param> /// <exception cref="SerializationException"> /// Cannot deserialize instance from <paramref name="unpackedException"/>. /// </exception> protected internal RpcException(RpcError rpcError, MessagePackObject unpackedException) : this(rpcError, unpackedException.GetString(MessageKeyUtf8), unpackedException.GetString(DebugInformationKeyUtf8)) { if (unpackedException.IsDictionary) { MessagePackObject mayBeArray; if (unpackedException.AsDictionary().TryGetValue(_remoteExceptionsUtf8, out mayBeArray) && mayBeArray.IsArray) { var array = mayBeArray.AsList(); this._remoteExceptions = new RemoteExceptionInformation[array.Count]; for (int i = 0; i < this._remoteExceptions.Length; i++) { if (array[i].IsList) { this._remoteExceptions[i] = new RemoteExceptionInformation(array[i].AsList()); } else { // Unexpected type. Debug.WriteLine("Unexepcted ExceptionInformation at {0}, type: {1}, value: \"{2}\".", i, array[i].UnderlyingType, array[i]); this._remoteExceptions[i] = new RemoteExceptionInformation(new MessagePackObject[] { array[i] }); } } } } #if !SILVERLIGHT && !MONO this.RegisterSerializeObjectStateEventHandler(); #endif }
public static bool MsgUnPackTable(out LuaTable luatable, ref MessagePackObject pObj) { LuaTable result = new LuaTable(); luatable = result; var mPk = pObj.AsDictionary(); bool isString = false; string key; object value; foreach (var item in mPk) { //parse for key MessagePackObject mKey = item.Key; if (mKey.IsRaw) { key = mKey.AsString(); isString = true; } else if (true == mKey.IsTypeOf <double>()) { key = mKey.AsDouble().ToString(); } else { LoggerHelper.Error("key type error"); return(false); } //parse for value MessagePackObject mValue = item.Value; if (mValue.IsRaw) { value = mValue.AsString(); } else if (mValue.IsDictionary) { LuaTable luatbl; MsgUnPackTable(out luatbl, ref mValue); value = luatbl; } else if (true == mValue.IsTypeOf <bool>()) { value = mValue.AsBoolean(); } else if (true == mValue.IsTypeOf <double>()) { value = mValue.AsDouble(); } else { LoggerHelper.Error("value type error"); return(false); } result.Add(key, isString, value); isString = false; } return(true); }
private static MessagePackObjectDictionary FirstDictionary(this MessagePackObject obj) { if (obj.IsList) { return(obj.AsList().First().FirstDictionary()); } return(obj.AsDictionary()); }
public static bool MsgUnPackTable(out LuaTable luatable, ref MessagePackObject pObj) { LuaTable result = new LuaTable(); luatable = result; var mPk = pObj.AsDictionary(); bool isString = false; string key; object value; foreach (var item in mPk) { //parse for key MessagePackObject mKey = item.Key; if (mKey.IsRaw) { key = mKey.AsString(); isString = true; } else if (true == mKey.IsTypeOf<double>()) { key = mKey.AsDouble().ToString(); } else { LoggerHelper.Error("key type error"); return false; } //parse for value MessagePackObject mValue = item.Value; if (mValue.IsRaw) { value = mValue.AsString(); } else if (mValue.IsDictionary) { LuaTable luatbl; MsgUnPackTable(out luatbl, ref mValue); value = luatbl; } else if (true == mValue.IsTypeOf<bool>()) { value = mValue.AsBoolean(); } else if (true == mValue.IsTypeOf<double>()) { value = mValue.AsDouble(); } else { LoggerHelper.Error("value type error"); return false; } result.Add(key, isString, value); isString = false; } return true; }
public static bool MsgUnPackTable(out LuaTable luatable, ref MessagePackObject pObj) { LuaTable table = new LuaTable(); luatable = table; MessagePackObjectDictionary dictionary = pObj.AsDictionary(); bool isString = false; foreach (KeyValuePair <MessagePackObject, MessagePackObject> pair in dictionary) { string str; object obj2; MessagePackObject key = pair.Key; if (key.IsRaw) { str = key.AsString(); isString = true; } else if (key.IsTypeOf <double>() == true) { str = key.AsDouble().ToString(); } else { LoggerHelper.Error("key type error", true); return(false); } MessagePackObject obj4 = pair.Value; if (obj4.IsRaw) { obj2 = obj4.AsString(); } else if (obj4.IsDictionary) { LuaTable table2; MsgUnPackTable(out table2, ref obj4); obj2 = table2; } else if (obj4.IsTypeOf <bool>() == true) { obj2 = obj4.AsBoolean(); } else if (obj4.IsTypeOf <double>() == true) { obj2 = obj4.AsDouble(); } else { LoggerHelper.Error("value type error", true); return(false); } table.Add(str, isString, obj2); isString = false; } return(true); }
public void TestGetExceptionMessage_False_DoesNotIncludeDebugInformation() { bool includesDebugInformation = false; var properties = this.GetTestArguments(); TRpcException target = NewRpcException(ConstructorKind.WithInnerException, properties); MessagePackObject result = target.GetExceptionMessage(includesDebugInformation); var asDictionary = result.AsDictionary(); Assert.That(asDictionary.Values.Any(item => item == GetRpcError(properties).ErrorCode)); Assert.That( asDictionary.Values.Any( item => item.IsTypeOf <string>().GetValueOrDefault() && item.AsString() != this.DefaultMessage && item.AsString().Contains(GetMessage(properties))), Is.False, "Expects not containing:'{0}', Actual :'{1}'", GetMessage(properties), result.ToString()); Assert.That( asDictionary.Values.Any( item => item.IsTypeOf <string>().GetValueOrDefault() && item.AsString().Contains(GetRpcError(properties).DefaultMessageInvariant)), Is.True, "Expects containing:'{0}', Actual :'{1}'", GetRpcError(properties), result.ToString()); if (String.IsNullOrEmpty(GetDebugInformation(properties))) { Assert.That( asDictionary.Keys.Any( item => item.IsTypeOf <string>().GetValueOrDefault() && item.AsString().Contains("DebugInformation")), Is.False, "Expects not containing:'{0}', Actual :'{1}'", "DebugInformation", result.ToString()); } else { Assert.That( asDictionary.Values.Any( item => item.IsTypeOf <string>().GetValueOrDefault() && item.AsString().Contains(GetDebugInformation(properties))), Is.False, "Expects not containing:'{0}', Actual :'{1}'", GetDebugInformation(properties), result.ToString()); } }
public static string GetString(this MessagePackObject source, MessagePackObject key) { if (source.IsDictionary) { if (source.AsDictionary().TryGetValue(key, out var value) && value.IsTypeOf <string>().GetValueOrDefault()) { return(value.AsString()); } } return(null); }
public static TimeSpan?GetTimeSpan(this MessagePackObject source, MessagePackObject key) { if (source.IsDictionary) { if (source.AsDictionary().TryGetValue(key, out var value) && value.IsTypeOf <long>().GetValueOrDefault()) { return(new TimeSpan(value.AsInt64())); } } return(null); }
private static JToken CreateToken(MessagePackObject curObj) { if (curObj.IsDictionary) { JObject resultObj = new JObject(); Dictionary <string, MessagePackObject> curDict = curObj.AsDictionary("inputFile"); foreach (KeyValuePair <string, MessagePackObject> curProp in curDict) { resultObj[curProp.Key] = CreateToken(curProp.Value); } return(resultObj); } else if (curObj.IsArray) { JArray resultArray = new JArray(); IList <MessagePackObject> curArray = curObj.AsList(); foreach (MessagePackObject curElem in curArray) { resultArray.Add(CreateToken(curElem)); } return(resultArray); } else if (curObj.IsNil) { return(null); } else if (curObj.IsTypeOf <Int64>().HasValue&& curObj.IsTypeOf <Int64>().Value) { return(curObj.AsInt64()); } else if (curObj.IsTypeOf <double>().HasValue&& curObj.IsTypeOf <double>().Value) { return(curObj.AsDouble()); } else if (curObj.IsTypeOf <string>().HasValue&& curObj.IsTypeOf <string>().Value) { return(curObj.AsString()); } else if (curObj.IsTypeOf <bool>().HasValue&& curObj.IsTypeOf <bool>().Value) { return(curObj.AsBoolean()); } else { throw new Exception("Unknown Type!"); } }
/// <inheritdoc /> public object Unpack(MessagePackObject obj) { if (obj.IsList) { IList <MessagePackObject> list = obj.AsList(); return(this.Unpack(list)); } if (obj.IsMap) { MessagePackObjectDictionary map = obj.AsDictionary(); return(map.ToDictionary(k => k.Key.ToString(), k => Unpack(k.Value))); } return(obj.ToObject()); }
/// <summary> /// Create <see cref="RpcException"/> or dervied instance which corresponds to sepcified error information. /// </summary> /// <param name="error">Basic error information. This information will propagate to client.</param> /// <param name="errorDetail">Detailed error information, which is usally debugging purpose only, so will not propagate to client.</param> /// <returns> /// <see cref="RpcException"/> or dervied instance which corresponds to sepcified error information. /// </returns> /// <exception cref="ArgumentException"> /// <paramref name="error"/> is <see cref="MessagePackObject.IsNil">nil</see>. /// </exception> public static RpcException FromMessage( MessagePackObject error, MessagePackObject errorDetail ) { // TODO: Application specific customization // TODO: Application specific exception class if ( error.IsNil ) { throw new ArgumentException( "'error' must not be nil.", "error" ); } // Recommeded path if ( error.IsTypeOf<byte[]>().GetValueOrDefault() ) { string identifier = null; try { identifier = error.AsString(); } catch ( InvalidOperationException ) { } int? errorCode = null; if ( errorDetail.IsTypeOf<IDictionary<MessagePackObject, MessagePackObject>>().GetValueOrDefault() ) { var asDictionary = errorDetail.AsDictionary(); MessagePackObject value; if ( asDictionary.TryGetValue( _errorCodeKeyUtf8, out value ) && value.IsTypeOf<int>().GetValueOrDefault() ) { errorCode = value.AsInt32(); } } if ( identifier != null || errorCode != null ) { RpcError rpcError = RpcError.FromIdentifier( identifier, errorCode ); return rpcError.ToException( errorDetail ); } } // Other path. return new UnexpcetedRpcException( error, errorDetail ); }
private static void Dump( MessagePackObject obj, StringBuilder buffer, int indent ) { if ( obj.IsNil ) { buffer.Append( ' ', indent * 2 ).Append( "(null)" ).AppendLine(); } else if ( obj.IsTypeOf<IList<MessagePackObject>>().GetValueOrDefault() ) { buffer.Append( ' ', indent * 2 ).AppendLine( "(" ); foreach ( var child in obj.AsList() ) { Dump( child, buffer, indent + 1 ); } buffer.Append( ' ', indent * 2 ).AppendLine( ")" ); } else if ( obj.IsTypeOf<IDictionary<MessagePackObject, MessagePackObject>>().GetValueOrDefault() ) { buffer.Append( ' ', indent * 2 ).AppendLine( "{" ); foreach ( var child in obj.AsDictionary() ) { Dump( child.Key, buffer, indent + 1 ); buffer.Append( ' ', ( indent + 1 ) * 2 ).AppendLine( "= " ); Dump( child.Value, buffer, indent + 2 ); } buffer.Append( ' ', indent * 2 ).AppendLine( "}" ); } else { buffer.Append( ' ', indent * 2 ).Append( obj ).Append( " : " ).Append( obj.UnderlyingType ).AppendLine(); } }
public static object Map(Type targetType, MessagePackObject source, PropertyInfo property = null) { if (source.IsNil) { return(null); } if (targetType == typeof(string)) { return(source.AsString()); } if (targetType == typeof(int) || targetType == typeof(int?)) { return(source.AsInt32()); } if (targetType == typeof(uint) || targetType == typeof(uint?)) { return(source.AsUInt32()); } if (targetType == typeof(long) || targetType == typeof(long?)) { return(source.AsInt64()); } if (targetType == typeof(ulong) || targetType == typeof(ulong?)) { return(source.AsUInt64()); } if (targetType == typeof(float) || targetType == typeof(float?)) { return(source.AsSingle()); } if (targetType == typeof(double) || targetType == typeof(double?)) { return(source.AsDouble()); } if (targetType == typeof(bool) || targetType == typeof(bool?)) { return(source.AsBoolean()); } if (targetType == typeof(byte[])) { return(source.AsBinary()); } if (targetType == typeof(byte) || targetType == typeof(byte?)) { return(source.AsByte()); } if (targetType == typeof(sbyte) || targetType == typeof(sbyte?)) { return(source.AsSByte()); } if (targetType == typeof(char[])) { return(source.AsCharArray()); } if (targetType == typeof(short) || targetType == typeof(short?)) { return(source.AsInt16()); } if (targetType == typeof(ushort) || targetType == typeof(ushort?)) { return(source.AsUInt16()); } if (targetType == typeof(DateTime) || targetType == typeof(DateTime?)) { return(MapDateTime(property, source)); } if (targetType == typeof(IList <MessagePackObject>)) { return(source.AsList()); } if (targetType == typeof(IEnumerable <MessagePackObject>)) { return(source.AsEnumerable()); } var ti = targetType.GetTypeInfo(); if (targetType == typeof(MessagePackObject)) { return(source); } if (ti.IsGenericType && (targetType.GetGenericTypeDefinition() == typeof(List <>) || targetType.GetGenericTypeDefinition() == typeof(IList <>))) { return(MapList(targetType, source.AsList())); } if (ti.IsClass && source.IsList) { return(MapClass(targetType, source)); } if (ti.IsClass && source.IsMap) { return(MapDictionary(targetType, source.AsDictionary())); } if (ti.IsEnum) { return(MapEnum(targetType, source)); } throw new MessagePackMapperException( $"Cannot find MsgPackObject converter for type {targetType.FullName}."); }
//this is a ridiculous method Dictionary<string, object> TypifyDictionary(MessagePackObjectDictionary dict) { Dictionary<string, object> returnDictionary = new Dictionary<string, object>(); foreach (var pair in dict) { MessagePackObject obj = (MessagePackObject)pair.Value; string key = System.Text.Encoding.ASCII.GetString ((byte[])pair.Key); if (obj.UnderlyingType == null) continue; if (obj.IsRaw) { if (obj.UnderlyingType == typeof(string)) { if (pair.Key.IsRaw && pair.Key.IsTypeOf (typeof(Byte[])).Value) returnDictionary [key] = obj.AsString (); else returnDictionary [pair.Key.ToString ()] = obj.AsString (); } else if (obj.IsTypeOf (typeof(int)).Value) returnDictionary [pair.Key.ToString ()] = (int)obj.ToObject (); else if (obj.IsTypeOf (typeof(Byte[])).Value) { if (key == "payload") returnDictionary [key] = (byte[])obj; else returnDictionary [key] = System.Text.Encoding.ASCII.GetString ((Byte[])obj.ToObject ()); } else throw new Exception ("I don't know type: " + pair.Value.GetType ().Name); } else if (obj.IsArray) { List<object> arr = new List<object> (); foreach (var o in obj.ToObject() as MessagePackObject[]) { if (o.IsDictionary) arr.Add (TypifyDictionary (o.AsDictionary ())); else if (o.IsRaw) arr.Add (System.Text.Encoding.ASCII.GetString ((byte[])o)); else if (o.IsArray) { var enu = o.AsEnumerable (); List<object> array = new List<object> (); foreach (var blah in enu) array.Add (blah as object); arr.Add (array.ToArray ()); } else if (o.ToObject ().GetType () == typeof(Byte)) //this is a hack because I don't know what type you are... arr.Add (o.ToString ()); } if (pair.Key.IsRaw && pair.Key.IsTypeOf (typeof(Byte[])).Value) returnDictionary.Add (key, arr); else returnDictionary.Add (key, arr); } else if (obj.IsDictionary) { if (pair.Key.IsRaw && pair.Key.IsTypeOf(typeof(Byte[])).Value) returnDictionary [key] = TypifyDictionary (obj.AsDictionary ()); else returnDictionary [pair.Key.ToString ()] = TypifyDictionary (obj.AsDictionary ()); } else if (obj.IsTypeOf (typeof(UInt16)).Value) { if (pair.Key.IsRaw && pair.Key.IsTypeOf (typeof(Byte[])).Value) returnDictionary [key] = obj.AsUInt16 (); else returnDictionary [pair.Key.ToString ()] = obj.AsUInt16 (); } else if (obj.IsTypeOf (typeof(UInt32)).Value) { if (pair.Key.IsRaw && pair.Key.IsTypeOf (typeof(Byte[])).Value) returnDictionary [key] = obj.AsUInt32 (); else returnDictionary [pair.Key.ToString ()] = obj.AsUInt32 (); } else if (obj.IsTypeOf (typeof(bool)).Value) { if (pair.Key.IsRaw && pair.Key.IsTypeOf (typeof(Byte[])).Value) returnDictionary [key] = obj.AsBoolean (); else returnDictionary [pair.Key.ToString ()] = obj.AsBoolean (); } else throw new Exception("Don't know type: " + obj.ToObject().GetType().Name); } return returnDictionary; }
// Dirty check if obj is different from mirror, generate patches and update mirror protected static void Generate(MessagePackObject mirrorPacked, MessagePackObject objPacked, List <PatchObject> patches, List <string> path) { MessagePackObjectDictionary mirror = mirrorPacked.AsDictionary(); MessagePackObjectDictionary obj = objPacked.AsDictionary(); var newKeys = obj.Keys; var oldKeys = mirror.Keys; //var changed = false; var deleted = false; foreach (var key in oldKeys) { if (obj.ContainsKey(key) && !(!obj.ContainsKey(key) && mirror.ContainsKey(key) && !objPacked.IsArray)) { var oldVal = mirror[key]; var newVal = obj[key]; if (oldVal.IsDictionary && !oldVal.IsNil && newVal.IsDictionary && !newVal.IsNil) { List <string> deeperPath = new List <string>(path); deeperPath.Add(key.AsString()); Generate(oldVal, newVal, patches, deeperPath); } else { if (oldVal != newVal) { //changed = true; List <string> replacePath = new List <string>(path); replacePath.Add(key.AsString()); patches.Add(new PatchObject { op = "replace", path = replacePath.ToArray(), value = newVal }); } } } else { List <string> removePath = new List <string>(path); removePath.Add(key.AsString()); patches.Add(new PatchObject { op = "remove", path = removePath.ToArray() }); deleted = true; // property has been deleted } } if (!deleted && newKeys.Count == oldKeys.Count) { return; } foreach (var key in newKeys) { if (!mirror.ContainsKey(key) && obj.ContainsKey(key)) { List <string> addPath = new List <string>(path); addPath.Add(key.AsString()); patches.Add(new PatchObject { op = "add", path = addPath.ToArray(), value = obj[key] }); } } }
Dictionary <string, object> TypifyDictionary(IDictionary <MessagePackObject, MessagePackObject> dict) { Dictionary <string, object> returnDictionary = new Dictionary <string, object>(); foreach (var pair in dict) { MessagePackObject obj = (MessagePackObject)pair.Value; if (obj.UnderlyingType == null) { continue; } if (obj.IsRaw) { if (obj.IsTypeOf(typeof(string)).Value) { returnDictionary[pair.Key.AsString()] = new string(obj.AsCharArray()); } else if (obj.IsTypeOf(typeof(int)).Value) { returnDictionary[pair.Key.AsString()] = (int)obj.ToObject(); } else { throw new Exception("I don't know type: " + pair.Value.GetType().Name); } } else if (obj.IsArray) { List <object> arr = new List <object>(); //Console.WriteLine(obj.UnderlyingType.Name); foreach (var o in obj.ToObject() as MessagePackObject[]) { if (o.IsDictionary) { arr.Add(TypifyDictionary(o.AsDictionary())); } else if (o.IsRaw) { arr.Add(o.AsString()); } } returnDictionary.Add(pair.Key.AsString(), arr); } else if (obj.IsDictionary) { returnDictionary[pair.Key.AsString()] = TypifyDictionary(obj.AsDictionary() as IDictionary <MessagePackObject, MessagePackObject>); } else if (obj.IsTypeOf(typeof(UInt16)).Value) { returnDictionary[pair.Key.AsString()] = obj.AsUInt16(); } else if (obj.IsTypeOf(typeof(UInt32)).Value) { returnDictionary[pair.Key.AsString()] = obj.AsUInt32(); } else if (obj.IsTypeOf(typeof(bool)).Value) { returnDictionary[pair.Key.AsString()] = obj.AsBoolean(); } else { throw new Exception("hey what the f**k are you: " + obj.ToObject().GetType().Name); } } return(returnDictionary); }