/// <summary> /// Copies the values from serialized json object. /// </summary> /// <param name="source">The source.</param> /// <param name="destination">The destination.</param> /// <param name="config">The config.</param> public static void CopyValuesFromJson(string source, object destination, BeetleConfig config) { if (string.IsNullOrEmpty(source)) return; var obj = (JObject)JsonConvert.DeserializeObject(source, config.JsonSerializerSettings); var type = destination.GetType(); var serializer = config.CreateSerializer(); foreach (var p in obj.Properties()) { var propType = GetPropertyType(type, p.Name); var jValue = obj[p.Name]; var value = serializer.Deserialize(jValue.CreateReader(), propType); SetPropertyValue(destination, p.Name, value); } }
/// <summary> /// Resolves the entities. /// </summary> /// <param name="bundle">The bundle.</param> /// <param name="config">The config.</param> /// <param name="unknownEntities">The unknown entities.</param> /// <returns></returns> /// <exception cref="System.InvalidOperationException">Cannot find tracker info.</exception> public static IEnumerable<EntityBag> ResolveEntities(dynamic bundle, BeetleConfig config, out IEnumerable<EntityBag> unknownEntities) { var jsonSerializer = config.CreateSerializer(); var dynEntities = (JArray)bundle.entities; var entities = new List<EntityBag>(); var unknowns = new List<EntityBag>(); bool forceUpdatePackage = bundle.forceUpdate ?? false; foreach (dynamic dynEntity in dynEntities) { // get entity tracking information var tracker = dynEntity["$t"]; if (tracker == null) throw new InvalidOperationException(Resources.CannotFindTrackerInfo); // get entity type and other information string typeName = tracker.t.ToString(); var type = Type.GetType(typeName); var state = Enum.Parse(typeof(EntityState), tracker.s.ToString()); var originalValues = new Dictionary<string, object>(); // entity's index in the client save array var index = int.Parse(tracker.i.ToString()); // read original values var ovs = tracker.o != null ? tracker.o as IEnumerable : null; if (ovs != null) { foreach (JProperty ov in ovs) { var loopType = ov.Name.Split('.').Aggregate(type, GetPropertyType); if (loopType == null) throw new BeetleException(string.Format(Resources.OriginalValuePropertyCouldNotBeFound, ov.Name)); var value = jsonSerializer.Deserialize(new JTokenReader(ov.Value), loopType); originalValues.Add(ov.Name, value); } } var forceUpdate = forceUpdatePackage || (bool)(tracker.f ?? false); // deserialize entity if (type != null) { var clientEntity = jsonSerializer.Deserialize(new JTokenReader(dynEntity), type); var entity = jsonSerializer.Deserialize(new JTokenReader(dynEntity), type); entities.Add(new EntityBag(clientEntity, entity, state, originalValues, index, forceUpdate)); } else unknowns.Add(new EntityBag(dynEntity, dynEntity, state, originalValues, index, forceUpdate)); } unknownEntities = unknowns; return entities; }