ServiceBodyWriter.cs
9.21 KB
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Xml;
using System.Xml.Serialization;
using SoapCore.ServiceModel;
namespace SoapCore
{
internal class ServiceBodyWriter : BodyWriter
{
private readonly SoapSerializer _serializer;
private readonly OperationDescription _operation;
private readonly string _serviceNamespace;
private readonly string _envelopeName;
private readonly string _resultName;
private readonly object _result;
private readonly Dictionary<string, object> _outResults;
public ServiceBodyWriter(SoapSerializer serializer, OperationDescription operation, object result, Dictionary<string, object> outResults) : base(isBuffered: true)
{
_serializer = serializer;
_operation = operation;
_serviceNamespace = operation.Contract.Namespace;
_envelopeName = operation.Name + "Response";
_resultName = operation.ReturnName;
_result = result;
_outResults = outResults ?? new Dictionary<string, object>();
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
switch (_serializer)
{
case SoapSerializer.XmlSerializer:
OnWriteXmlSerializerBodyContents(writer);
break;
case SoapSerializer.DataContractSerializer:
OnWriteDataContractSerializerBodyContents(writer);
break;
default:
throw new NotImplementedException($"Unknown serializer {_serializer}");
}
}
private static void WriteStream(XmlDictionaryWriter writer, object value)
{
int blockSize = 256;
int bytesRead = 0;
byte[] block = new byte[blockSize];
var stream = (Stream)value;
stream.Position = 0;
while (true)
{
bytesRead = stream.Read(block, 0, blockSize);
if (bytesRead > 0)
{
writer.WriteBase64(block, 0, bytesRead);
}
else
{
break;
}
if (blockSize < 65536 && bytesRead == blockSize)
{
blockSize = blockSize * 16;
block = new byte[blockSize];
}
}
}
private void OnWriteXmlSerializerBodyContents(XmlDictionaryWriter writer)
{
Debug.Assert(_outResults != null, "Object should set empty out results");
// Do not wrap old-style single element response into additional xml element for xml serializer
var needResponseEnvelope = _result == null || (_outResults.Count > 0) || !_operation.IsMessageContractResponse;
if (needResponseEnvelope)
{
writer.WriteStartElement(_envelopeName, _serviceNamespace);
}
foreach (var outResult in _outResults)
{
string value = null;
if (outResult.Value is Guid)
{
value = outResult.Value.ToString();
}
else if (outResult.Value is bool)
{
value = outResult.Value.ToString().ToLower();
}
else if (outResult.Value is string)
{
value = System.Security.SecurityElement.Escape(outResult.Value.ToString());
}
else if (outResult.Value is Enum)
{
value = outResult.Value.ToString();
}
else if (outResult.Value == null)
{
value = null;
}
else
{
//for complex types
using (var ms = new MemoryStream())
using (var stream = new BufferedStream(ms))
{
// write element with name as outResult.Key and type information as outResultType
// i.e. <outResult.Key xsi:type="outResultType" ... />
var outResultType = outResult.Value.GetType();
var serializer = CachedXmlSerializer.GetXmlSerializer(outResultType, outResult.Key, _serviceNamespace);
lock (serializer)
{
serializer.Serialize(stream, outResult.Value);
}
//add outResultType. ugly, but working
stream.Position = 0;
XmlDocument xdoc = new XmlDocument();
xdoc.Load(stream);
var attr = xdoc.CreateAttribute("xsi", "type", "http://www.w3.org/2001/XMLSchema-instance");
attr.Value = outResultType.Name;
xdoc.DocumentElement.Attributes.Prepend(attr);
writer.WriteRaw(xdoc.DocumentElement.OuterXml);
}
}
if (value != null)
{
writer.WriteRaw(string.Format("<{0}>{1}</{0}>", outResult.Key, value));
}
}
if (_result != null)
{
// see https://referencesource.microsoft.com/System.Xml/System/Xml/Serialization/XmlSerializer.cs.html#c97688a6c07294d5
var resultType = _result.GetType();
var xmlRootAttr = resultType.GetTypeInfo().GetCustomAttributes<XmlRootAttribute>().FirstOrDefault();
var messageContractAttribute = resultType.GetTypeInfo().GetCustomAttribute<MessageContractAttribute>();
var xmlName = _operation.ReturnElementName
?? (needResponseEnvelope
? _resultName
: (string.IsNullOrWhiteSpace(xmlRootAttr?.ElementName)
? resultType.Name
: xmlRootAttr.ElementName));
var xmlNs = _operation.ReturnNamespace ?? messageContractAttribute?.WrapperNamespace
?? (string.IsNullOrWhiteSpace(xmlRootAttr?.Namespace)
? _serviceNamespace
: xmlRootAttr.Namespace);
var xmlArrayAttr = _operation.DispatchMethod.GetCustomAttribute<XmlArrayAttribute>();
if (xmlArrayAttr != null && resultType.IsArray)
{
var serializer = CachedXmlSerializer.GetXmlSerializer(resultType.GetElementType(), xmlName, xmlNs);
lock (serializer)
{
serializer.SerializeArray(writer, (object[])_result);
}
}
else
{
// This behavior is opt-in i.e. you have to explicitly have a [MessageContract(IsWrapped=false)]
// to have the message body members inlined.
var shouldInline = (messageContractAttribute != null && messageContractAttribute.IsWrapped == false) || resultType.GetMembersWithAttribute<MessageHeaderAttribute>().Any();
if (shouldInline)
{
var memberInformation = resultType.GetMembersWithAttribute<MessageBodyMemberAttribute>().Select(mi => new
{
Member = mi,
MessageBodyMemberAttribute = mi.GetCustomAttribute<MessageBodyMemberAttribute>()
}).OrderBy(x => x.MessageBodyMemberAttribute?.Order ?? 0);
if (messageContractAttribute != null && messageContractAttribute.IsWrapped)
{
writer.WriteStartElement(resultType.Name, xmlNs);
}
foreach (var memberInfo in memberInformation)
{
var memberType = memberInfo.Member.GetPropertyOrFieldType();
var memberValue = memberInfo.Member.GetPropertyOrFieldValue(_result);
var memberName = memberInfo.MessageBodyMemberAttribute?.Name ?? memberInfo.Member.Name;
var memberNamespace = memberInfo.MessageBodyMemberAttribute?.Namespace ?? _serviceNamespace;
var serializer = CachedXmlSerializer.GetXmlSerializer(memberType, memberName, memberNamespace);
lock (serializer)
{
if (memberValue is Stream)
{
writer.WriteStartElement(memberName, _serviceNamespace);
WriteStream(writer, memberValue);
writer.WriteEndElement();
}
else
{
serializer.Serialize(writer, memberValue);
}
}
}
if (messageContractAttribute != null && messageContractAttribute.IsWrapped)
{
writer.WriteEndElement();
}
}
else
{
var serializer = CachedXmlSerializer.GetXmlSerializer(resultType, xmlName, xmlNs);
lock (serializer)
{
if (_result is Stream)
{
writer.WriteStartElement(_resultName, _serviceNamespace);
WriteStream(writer, _result);
writer.WriteEndElement();
}
else
{
serializer.Serialize(writer, _result);
}
}
}
}
}
if (needResponseEnvelope)
{
writer.WriteEndElement();
}
}
private void OnWriteDataContractSerializerBodyContents(XmlDictionaryWriter writer)
{
Debug.Assert(_outResults != null, "Object should set empty out results");
writer.WriteStartElement(_envelopeName, _serviceNamespace);
foreach (var outResult in _outResults)
{
string value = null;
if (outResult.Value is Guid)
{
value = outResult.Value.ToString();
}
else if (outResult.Value is bool)
{
value = outResult.Value.ToString().ToLower();
}
else if (outResult.Value is string)
{
value = System.Security.SecurityElement.Escape(outResult.Value.ToString());
}
else if (outResult.Value is Enum)
{
value = outResult.Value.ToString();
}
else if (outResult.Value == null)
{
value = null;
}
else
{
//for complex types
using (var ms = new MemoryStream())
using (var stream = new BufferedStream(ms))
{
new DataContractSerializer(outResult.Value.GetType()).WriteObject(ms, outResult.Value);
stream.Position = 0;
using (var reader = XmlReader.Create(stream))
{
reader.MoveToContent();
value = reader.ReadInnerXml();
}
}
}
if (value != null)
{
writer.WriteRaw(string.Format("<{0}>{1}</{0}>", outResult.Key, value));
}
}
if (_result != null)
{
if (_result is Stream)
{
writer.WriteStartElement(_resultName, _serviceNamespace);
WriteStream(writer, _result);
writer.WriteEndElement();
}
else
{
var serializer = new DataContractSerializer(_result.GetType(), _resultName, _serviceNamespace);
serializer.WriteObject(writer, _result);
}
}
writer.WriteEndElement();
}
}
}