All files
[pithos-ms-client] / trunk / Libraries / Json40r2 / Source / Src / Newtonsoft.Json.Tests / Serialization / DynamicTests.cs
1 #if !(NET35 || NET20)
2 using System;
3 using System.Collections;
4 using System.Collections.Generic;
5 using System.Dynamic;
6 using System.Linq;
7 using System.Linq.Expressions;
8 using System.Runtime.CompilerServices;
9 using System.Runtime.Serialization.Formatters;
10 using System.Text;
11 using Newtonsoft.Json.Serialization;
12 using Newtonsoft.Json.Tests.TestObjects;
13 using Newtonsoft.Json.Utilities;
14 using NUnit.Framework;
15
16 namespace Newtonsoft.Json.Tests.Serialization
17 {
18   public class DynamicTests : TestFixtureBase
19   {
20     public class DynamicChildObject
21     {
22       public string Text { get; set; }
23       public int Integer { get; set; }
24     }
25
26     public class TestDynamicObject : DynamicObject
27     {
28       private readonly Dictionary<string, object> _members;
29
30       public int Int;
31       public DynamicChildObject ChildObject { get; set; }
32
33       internal Dictionary<string, object> Members
34       {
35         get { return _members; }
36       }
37
38       public TestDynamicObject()
39       {
40         _members = new Dictionary<string, object>();
41       }
42
43       public override IEnumerable<string> GetDynamicMemberNames()
44       {
45         return _members.Keys.Union(new[] { "Int", "ChildObject" });
46       }
47
48       public override bool TryConvert(ConvertBinder binder, out object result)
49       {
50         Type targetType = binder.Type;
51
52         if (targetType == typeof(IDictionary<string, object>) ||
53             targetType == typeof(IDictionary))
54         {
55           result = new Dictionary<string, object>(_members);
56           return true;
57         }
58         else
59         {
60           return base.TryConvert(binder, out result);
61         }
62       }
63
64       public override bool TryDeleteMember(DeleteMemberBinder binder)
65       {
66         return _members.Remove(binder.Name);
67       }
68
69       public override bool TryGetMember(GetMemberBinder binder, out object result)
70       {
71         return _members.TryGetValue(binder.Name, out result);
72       }
73
74       public override bool TrySetMember(SetMemberBinder binder, object value)
75       {
76         _members[binder.Name] = value;
77         return true;
78       }
79     }
80
81     public class ErrorSettingDynamicObject : DynamicObject
82     {
83       public override bool TrySetMember(SetMemberBinder binder, object value)
84       {
85         return false;
86       }
87     }
88
89     [Test]
90     public void SerializeDynamicObject()
91     {
92       TestDynamicObject dynamicObject = new TestDynamicObject();
93
94       dynamic d = dynamicObject;
95       d.Int = 1;
96       d.Decimal = 99.9d;
97       d.ChildObject = new DynamicChildObject();
98
99       Dictionary<string, object> values = new Dictionary<string, object>();
100
101       foreach (string memberName in dynamicObject.GetDynamicMemberNames())
102       {
103         object value;
104         dynamicObject.TryGetMember(memberName, out value);
105
106         values.Add(memberName, value);
107       }
108
109       Assert.AreEqual(d.Int, values["Int"]);
110       Assert.AreEqual(d.Decimal, values["Decimal"]);
111       Assert.AreEqual(d.ChildObject, values["ChildObject"]);
112
113       string json = JsonConvert.SerializeObject(dynamicObject, Formatting.Indented);
114       Assert.AreEqual(@"{
115   ""Decimal"": 99.9,
116   ""Int"": 1,
117   ""ChildObject"": {
118     ""Text"": null,
119     ""Integer"": 0
120   }
121 }", json);
122
123       TestDynamicObject newDynamicObject = JsonConvert.DeserializeObject<TestDynamicObject>(json);
124       d = newDynamicObject;
125
126       Assert.AreEqual(99.9, d.Decimal);
127       Assert.AreEqual(1, d.Int);
128       Assert.AreEqual(dynamicObject.ChildObject.Integer, d.ChildObject.Integer);
129       Assert.AreEqual(dynamicObject.ChildObject.Text, d.ChildObject.Text);
130     }
131
132     [Test]
133     public void sdfsdf()
134     {
135       ErrorSettingDynamicObject d = JsonConvert.DeserializeObject<ErrorSettingDynamicObject>("{'hi':5}");
136     }
137
138     [Test]
139     public void SerializeDynamicObjectWithObjectTracking()
140     {
141       dynamic o = new ExpandoObject();
142       o.Text = "Text!";
143       o.Integer = int.MaxValue;
144       o.DynamicChildObject = new DynamicChildObject
145         {
146           Integer = int.MinValue,
147           Text = "Child text!"
148         };
149
150       string json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings
151         {
152           TypeNameHandling = TypeNameHandling.All,
153           TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
154         });
155
156       Console.WriteLine(json);
157
158       string dynamicChildObjectTypeName = ReflectionUtils.GetTypeName(typeof(DynamicChildObject), FormatterAssemblyStyle.Full);
159       string expandoObjectTypeName = ReflectionUtils.GetTypeName(typeof(ExpandoObject), FormatterAssemblyStyle.Full);
160
161       Assert.AreEqual(@"{
162   ""$type"": """ + expandoObjectTypeName + @""",
163   ""Text"": ""Text!"",
164   ""Integer"": 2147483647,
165   ""DynamicChildObject"": {
166     ""$type"": """ + dynamicChildObjectTypeName + @""",
167     ""Text"": ""Child text!"",
168     ""Integer"": -2147483648
169   }
170 }", json);
171
172       dynamic n = JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
173         {
174           TypeNameHandling = TypeNameHandling.All,
175           TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
176         });
177
178       Assert.IsInstanceOfType(typeof(ExpandoObject), n);
179       Assert.AreEqual("Text!", n.Text);
180       Assert.AreEqual(int.MaxValue, n.Integer);
181
182       Assert.IsInstanceOfType(typeof(DynamicChildObject), n.DynamicChildObject);
183       Assert.AreEqual("Child text!", n.DynamicChildObject.Text);
184       Assert.AreEqual(int.MinValue, n.DynamicChildObject.Integer);
185     }
186
187     [Test]
188     [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Unable to find a default constructor to use for type System.Dynamic.DynamicObject.")]
189     public void NoPublicDefaultConstructor()
190     {
191       var settings = new JsonSerializerSettings();
192       settings.NullValueHandling = NullValueHandling.Ignore;
193       var json = @"{
194   ""contributors"": null
195 }";
196       
197       JsonConvert.DeserializeObject<DynamicObject>(json, settings);
198     }
199
200     public class DictionaryDynamicObject : DynamicObject
201     {
202       public IDictionary<string, object> Values { get; private set; }
203
204       protected DictionaryDynamicObject()
205       {
206         Values = new Dictionary<string, object>();
207       }
208
209       public override bool TrySetMember(SetMemberBinder binder, object value)
210       {
211         Values[binder.Name] = value;
212         return true;
213       }
214     }
215
216     [Test]
217     public void AllowNonPublicDefaultConstructor()
218     {
219       var settings = new JsonSerializerSettings();
220       settings.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
221
222       var json = @"{
223   ""contributors"": null,
224   ""retweeted"": false,
225   ""text"": ""Guys SX4 diesel is launched.what are your plans?catch us at #facebook http://bit.ly/dV3H1a #auto #car #maruti #india #delhi"",
226   ""in_reply_to_user_id_str"": null,
227   ""retweet_count"": 0,
228   ""geo"": null,
229   ""id_str"": ""40678260320768000"",
230   ""in_reply_to_status_id"": null,
231   ""source"": ""<a href=\""http://www.tweetdeck.com\"" rel=\""nofollow\"">TweetDeck</a>"",
232   ""created_at"": ""Thu Feb 24 07:43:47 +0000 2011"",
233   ""place"": null,
234   ""coordinates"": null,
235   ""truncated"": false,
236   ""favorited"": false,
237   ""user"": {
238     ""profile_background_image_url"": ""http://a1.twimg.com/profile_background_images/206944715/twitter_bg.jpg"",
239     ""url"": ""http://bit.ly/dcFwWC"",
240     ""screen_name"": ""marutisuzukisx4"",
241     ""verified"": false,
242     ""friends_count"": 45,
243     ""description"": ""This is the Official Maruti Suzuki SX4 Twitter ID! Men are Back - mail us on social (at) sx4bymaruti (dot) com"",
244     ""follow_request_sent"": null,
245     ""time_zone"": ""Chennai"",
246     ""profile_text_color"": ""333333"",
247     ""location"": ""India"",
248     ""notifications"": null,
249     ""profile_sidebar_fill_color"": ""efefef"",
250     ""id_str"": ""196143889"",
251     ""contributors_enabled"": false,
252     ""lang"": ""en"",
253     ""profile_background_tile"": false,
254     ""created_at"": ""Tue Sep 28 12:55:15 +0000 2010"",
255     ""followers_count"": 117,
256     ""show_all_inline_media"": true,
257     ""listed_count"": 1,
258     ""geo_enabled"": true,
259     ""profile_link_color"": ""009999"",
260     ""profile_sidebar_border_color"": ""eeeeee"",
261     ""protected"": false,
262     ""name"": ""Maruti Suzuki SX4"",
263     ""statuses_count"": 637,
264     ""following"": null,
265     ""profile_use_background_image"": true,
266     ""profile_image_url"": ""http://a3.twimg.com/profile_images/1170694644/Slide1_normal.JPG"",
267     ""id"": 196143889,
268     ""is_translator"": false,
269     ""utc_offset"": 19800,
270     ""favourites_count"": 0,
271     ""profile_background_color"": ""131516""
272   },
273   ""in_reply_to_screen_name"": null,
274   ""id"": 40678260320768000,
275   ""in_reply_to_status_id_str"": null,
276   ""in_reply_to_user_id"": null
277 }";
278
279       DictionaryDynamicObject foo = JsonConvert.DeserializeObject<DictionaryDynamicObject>(json, settings);
280
281       Assert.AreEqual(false, foo.Values["retweeted"]);
282     }
283   }
284 }
285 #endif