-
Notifications
You must be signed in to change notification settings - Fork 1
/
XMLObject.cs
executable file
·267 lines (227 loc) · 9.2 KB
/
XMLObject.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
/*
{*******************************************************************}
{ }
{ KS-Foundation Library }
{ Build rock solid DotNet applications }
{ on a threadsafe foundation without the hassle }
{ }
{ Copyright (c) 2014 - 2018 by Kroll-Software, }
{ Altdorf, Switzerland, All Rights Reserved }
{ www.kroll-software.ch }
{ }
{ Licensed under the MIT license }
{ Please see LICENSE.txt for details }
{ }
{*******************************************************************}
*/
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using System.Drawing;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.Reflection;
using System.Runtime.Serialization;
using System.Security.Permissions;
namespace KS.Foundation
{
public static class XmlObjectHelpers
{
public static string SerializeToXml<T>(this T obj)
{
return ToXmlString<T>(obj);
}
public static T DeserializeFromXml<T>(this string xml)
{
return FromXmlString<T>(xml);
}
public static void ToXmlStream<T>(T o, Stream stream)
{
XmlSerializer serializer = null;
try
{
serializer = typeof(T).CreateDefaultXmlSerializer();
serializer.Serialize(stream, o);
}
catch (Exception ex)
{
throw ex;
}
finally
{
}
}
public static T FromXmlStream<T>(Stream stream)
{
if (stream == null || stream.Length == 0)
return default(T);
XmlSerializer serializer = null;
try
{
if (stream.CanSeek)
stream.Seek(0, SeekOrigin.Begin);
serializer = typeof(T).CreateDefaultXmlSerializer();
return (T)serializer.Deserialize(stream);
}
catch (Exception ex)
{
throw ex;
}
finally
{
}
}
//public static string ToXmlString<T>(T o)
//{
// if (o.IsNull())
// return String.Empty;
// using (MemoryStream ms = new MemoryStream())
// using (StreamReader reader = new StreamReader(ms))
// {
// ToXmlStream<T>(o, ms);
// reader.BaseStream.Seek(0, SeekOrigin.Begin);
// return reader.ReadToEnd();
// }
//}
public static string ToXmlString<T>(T serialisableObject)
{
XmlSerializer xmlSerializer = CreateDefaultXmlSerializer(serialisableObject.GetType());
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add(String.Empty, String.Empty);
using (var ms = new MemoryStream())
{
using (var xw = XmlWriter.Create(ms,
new XmlWriterSettings()
{
Encoding = new UTF8Encoding(false),
Indent = true,
NewLineOnAttributes = true,
OmitXmlDeclaration = true,
}))
{
xmlSerializer.Serialize(xw, serialisableObject, ns);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
}
public static T FromXmlString<T>(string xml)
{
if (String.IsNullOrEmpty(xml))
{
return default(T);
}
//using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(xml)))
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
{
return FromXmlStream<T>(ms);
}
}
public static void ToXmlFile<T>(T o, string path)
{
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
{
ToXmlStream<T>(o, fs);
fs.Flush(true);
fs.Close();
}
}
public static T FromXmlFile<T>(string path)
{
if (!System.IO.File.Exists(path))
return default(T);
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
return FromXmlStream<T>(fs);
}
}
private static readonly Dictionary<Type, XmlSerializer> _xmlSerializerCache = new Dictionary<Type, XmlSerializer>();
public static XmlSerializer CreateDefaultXmlSerializer(this Type type)
{
XmlSerializer serializer;
if (_xmlSerializerCache.TryGetValue(type, out serializer))
{
return serializer;
}
else
{
var importer = new XmlReflectionImporter();
var mapping = importer.ImportTypeMapping(type, null, null);
serializer = new XmlSerializer(mapping);
return _xmlSerializerCache[type] = serializer;
}
}
}
public sealed class XmlAnything<T> : IXmlSerializable
{
public XmlAnything() { }
public XmlAnything(T t) { this.Value = t; }
public T Value { get; set; }
public void WriteXml(XmlWriter writer)
{
if (Value == null)
{
writer.WriteAttributeString("type", "null");
return;
}
Type type = this.Value.GetType();
XmlSerializer serializer = type.CreateDefaultXmlSerializer();
writer.WriteAttributeString("type", type.AssemblyQualifiedName);
serializer.Serialize(writer, this.Value);
}
private Type VersionIndependentType(string typeString)
{
string[] names = typeString.Split(new char[] { ',' }, 2);
if (names.Length != 2)
throw new ArgumentException("Invalid type string.");
string assemblyName = names[1];
string typeName = names[0];
Type typeToDeserialize = null;
AssemblyName aname = Assembly.GetExecutingAssembly().GetName();
Version assemblyVersion = aname.Version;
String assemblyTitle = aname.Name;
String searchString = assemblyTitle + ", Version=";
int searchCount = searchString.Length;
int searchIndex = assemblyName.IndexOf(searchString);
if (searchIndex != -1)
{
int versionLength = assemblyName.Substring((searchCount + searchIndex)).IndexOf(",");
assemblyName = assemblyName.Replace(assemblyName.Substring((searchCount + searchIndex), versionLength), assemblyVersion.ToString());
}
searchIndex = typeName.IndexOf(searchString);
if (searchIndex != -1)
{
int versionLength = typeName.Substring((searchCount + searchIndex)).IndexOf(",");
typeName = typeName.Replace(typeName.Substring((searchCount + searchIndex), versionLength), assemblyVersion.ToString());
}
// **************
searchString = "KS.Gantt.Gantt";
string replaceString = "KS.Gantt.GanttControl";
assemblyName = assemblyName.Replace(searchString, replaceString);
typeName = typeName.Replace(searchString, replaceString);
typeToDeserialize = Type.GetType(String.Format("{0}, {1}", typeName, assemblyName));
return typeToDeserialize;
}
public void ReadXml(XmlReader reader)
{
if (!reader.HasAttributes)
throw new FormatException("expected a type attribute!");
string type = reader.GetAttribute("type");
reader.Read(); // consume the value
if (type == "null")
return;// leave T at default value
Type tt = VersionIndependentType(type);
XmlSerializer serializer = tt.CreateDefaultXmlSerializer();
// ToDo: Check: Should work with app settings
//Type tt = typeof(T);
//XmlSerializer serializer = tt.CreateDefaultXmlSerializer();
//XmlSerializer serializer = Type.GetType(type).CreateDefaultXmlSerializer();
this.Value = (T)serializer.Deserialize(reader);
reader.ReadEndElement();
}
public XmlSchema GetSchema() { return (null); }
}
}