root / trunk / hammock / src / net35 / ICSharpCode.SharpZipLib.Silverlight / Serialization / XmlFormatter.Deserialize.cs @ 0eea575a
History | View | Annotate | Download (2.7 kB)
1 |
using System; |
---|---|
2 |
using System.Collections.Generic; |
3 |
using System.IO; |
4 |
using System.Reflection; |
5 |
using System.Xml; |
6 |
using System.Xml.Linq; |
7 |
|
8 |
namespace ICSharpCode.SharpZipLib.Silverlight.Serialization |
9 |
{ |
10 |
/// <summary> |
11 |
/// Code originally authored by Rockford Lhotka: |
12 |
/// http://www.lhotka.net/weblog/SilverlightSerialization.aspx, |
13 |
/// presented here with minor naming and code changes. |
14 |
/// </summary> |
15 |
public sealed partial class XmlFormatter |
16 |
{ |
17 |
private readonly Dictionary<ISerializable, SerializationInfo> _serializationReferences = |
18 |
new Dictionary<ISerializable, SerializationInfo>(); |
19 |
|
20 |
public void Serialize(Stream serializationStream, object graph) |
21 |
{ |
22 |
var writer = XmlWriter.Create(serializationStream); |
23 |
Serialize(writer, graph); |
24 |
if (writer != null) |
25 |
{ |
26 |
writer.Flush(); |
27 |
} |
28 |
} |
29 |
|
30 |
public void Serialize(TextWriter textWriter, object graph) |
31 |
{ |
32 |
var writer = XmlWriter.Create(textWriter); |
33 |
Serialize(writer, graph); |
34 |
if (writer != null) |
35 |
{ |
36 |
writer.Flush(); |
37 |
} |
38 |
} |
39 |
|
40 |
public void Serialize(XmlWriter writer, object graph) |
41 |
{ |
42 |
_serializationReferences.Clear(); |
43 |
|
44 |
var document = new XDocument(); |
45 |
SerializeObject(graph); |
46 |
var root = new XElement("g"); |
47 |
foreach (var item in _serializationReferences) |
48 |
{ |
49 |
root.Add(item.Value.ToXElement()); |
50 |
} |
51 |
document.Add(root); |
52 |
document.Save(writer); |
53 |
} |
54 |
|
55 |
internal SerializationInfo SerializeObject(object obj) |
56 |
{ |
57 |
var thisType = obj.GetType(); |
58 |
if (!IsSerializable(thisType)) |
59 |
{ |
60 |
throw new InvalidOperationException("Object not serializable"); |
61 |
} |
62 |
var mobile = obj as ISerializable; |
63 |
if (mobile == null) |
64 |
{ |
65 |
throw new InvalidOperationException( |
66 |
string.Format("Type {0} must implement ISerializable", |
67 |
thisType.Name)); |
68 |
} |
69 |
|
70 |
SerializationInfo info; |
71 |
if (!_serializationReferences.TryGetValue(mobile, out info)) |
72 |
{ |
73 |
info = new SerializationInfo(_serializationReferences.Count + 1); |
74 |
_serializationReferences.Add(mobile, info); |
75 |
mobile.Serialize(info, this); |
76 |
} |
77 |
return info; |
78 |
} |
79 |
|
80 |
private static bool IsSerializable(ICustomAttributeProvider objectType) |
81 |
{ |
82 |
var a = objectType.GetCustomAttributes(typeof (SerializableAttribute), false); |
83 |
return a.Length > 0; |
84 |
} |
85 |
} |
86 |
} |