Welcome to mirror list, hosted at ThFree Co, Russian Federation.

BaseMessagesFormatter.cs « System.ServiceModel.Dispatcher « System.ServiceModel « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: dbe680b6e56c4a81486c81e2fad685d05b87cba2 (plain)
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
//
// DefaultMessageOperationFormatter.cs
//
// Author:
//	Atsushi Enomoto <atsushi@ximian.com>
//	Eyal Alaluf <eyala@mainsoft.com>
//
// Copyright (C) 2005-2007 Novell, Inc.  http://www.novell.com
// Copyright (C) 2008 Mainsoft Co. http://www.mainsoft.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace System.ServiceModel.Dispatcher
{
	internal abstract class BaseMessagesFormatter
		: IDispatchMessageFormatter, IClientMessageFormatter
	{
		MessageDescriptionCollection messages;
		bool isAsync;
		ParameterInfo [] requestMethodParams;
		ParameterInfo [] replyMethodParams;

		public BaseMessagesFormatter (MessageDescriptionCollection messages)
		{
			this.messages = messages;
		}

		public BaseMessagesFormatter (OperationDescription desc)
			: this (desc.Messages)
		{
			if (desc.SyncMethod != null)
			{
				isAsync = false;
				requestMethodParams = replyMethodParams = desc.SyncMethod.GetParameters ();
				return;
			}
			isAsync = true;
			ParameterInfo [] methodParams = desc.BeginMethod.GetParameters ();
			requestMethodParams = new ParameterInfo [methodParams.Length - 2];
			Array.Copy (methodParams, requestMethodParams, requestMethodParams.Length);
			methodParams = desc.EndMethod.GetParameters ();
			replyMethodParams = new ParameterInfo [methodParams.Length - 1];
			Array.Copy (methodParams, replyMethodParams, replyMethodParams.Length);
		}

		public static BaseMessagesFormatter Create (OperationDescription desc)
		{
			MethodInfo attrProvider = desc.SyncMethod ?? desc.BeginMethod;
			object [] attrs;
#if !NET_2_1
			attrs = attrProvider.GetCustomAttributes (typeof (XmlSerializerFormatAttribute), false);
			if (attrs != null && attrs.Length > 0)
				return new XmlMessagesFormatter (desc, (XmlSerializerFormatAttribute) attrs [0]);
#endif

			attrs = attrProvider.GetCustomAttributes (typeof (DataContractFormatAttribute), false);
			DataContractFormatAttribute dataAttr = null;
			if (attrs != null && attrs.Length > 0)
				dataAttr = (DataContractFormatAttribute) attrs [0];
			return new DataContractMessagesFormatter (desc, dataAttr);
		}

		protected abstract Message PartsToMessage (
			MessageDescription md, MessageVersion version, string action, object [] parts);
		protected abstract object [] MessageToParts (MessageDescription md, Message message);

		public Message SerializeRequest (
			MessageVersion version, object [] parameters)
		{
			MessageDescription md = null;
			foreach (MessageDescription mdi in messages)
				if (mdi.Direction == MessageDirection.Input)
					md = mdi;

			object [] parts = CreatePartsArray (md.Body);
			if (md.MessageType != null)
				MessageObjectToParts (md, parameters [0], parts);
			else {
				int index = 0;
				foreach (ParameterInfo pi in requestMethodParams)
					if (!pi.IsOut)
						parts [index++] = parameters [pi.Position];
			}
			return PartsToMessage (md, version, md.Action, parts);
		}

		public Message SerializeReply (
			MessageVersion version, object [] parameters, object result)
		{
			// use_response_converter

			MessageDescription md = null;
			foreach (MessageDescription mdi in messages)
				if (mdi.Direction == MessageDirection.Output)
					md = mdi;

			object [] parts = CreatePartsArray (md.Body);
			if (md.MessageType != null)
				MessageObjectToParts (md, result, parts);
			else {
				if (HasReturnValue (md.Body))
					parts [0] = result;
				int index = ParamsOffset (md.Body);
				foreach (ParameterInfo pi in replyMethodParams)
					if (pi.IsOut || pi.ParameterType.IsByRef)
						parts [index++] = parameters [pi.Position];
			}
			string action = version.Addressing == AddressingVersion.None ? null : md.Action;
			return PartsToMessage (md, version, action, parts);
		}

		public void DeserializeRequest (Message message, object [] parameters)
		{
			string action = message.Headers.Action;
			MessageDescription md = messages.Find (action);
			if (md == null)
				throw new ActionNotSupportedException (String.Format ("Action '{0}' is not supported by this operation.", action));

			object [] parts = MessageToParts (md, message);
			if (md.MessageType != null) {
#if NET_2_1
				parameters [0] = Activator.CreateInstance (md.MessageType);
#else
				parameters [0] = Activator.CreateInstance (md.MessageType, true);
#endif
				PartsToMessageObject (md, parts, parameters [0]);
			}
			else
			{
				int index = 0;
				foreach (ParameterInfo pi in requestMethodParams)
					if (!pi.IsOut)
						parameters [pi.Position] = parts [index++];
			}
		}

		public object DeserializeReply (Message message, object [] parameters)
		{
			MessageDescription md = null;
			foreach (MessageDescription mdi in messages)
				if (mdi.Direction == MessageDirection.Output)
					md = mdi;

			object [] parts = MessageToParts (md, message);
			if (md.MessageType != null) {
#if NET_2_1
				object msgObject = Activator.CreateInstance (md.MessageType);
#else
				object msgObject = Activator.CreateInstance (md.MessageType, true);
#endif
				PartsToMessageObject (md, parts, msgObject);
				return msgObject;
			}
			else {
				int index = ParamsOffset (md.Body);
				foreach (ParameterInfo pi in requestMethodParams)
					if (pi.IsOut || pi.ParameterType.IsByRef)
						parameters [pi.Position] = parts [index++];
				return HasReturnValue (md.Body) ? parts [0] : null;
			}
		}

		void PartsToMessageObject (MessageDescription md, object [] parts, object msgObject)
		{
			foreach (MessagePartDescription partDesc in md.Body.Parts)
				if (partDesc.MemberInfo is FieldInfo)
					((FieldInfo) partDesc.MemberInfo).SetValue (msgObject, parts [partDesc.Index]);
				else
					((PropertyInfo) partDesc.MemberInfo).SetValue (msgObject, parts [partDesc.Index], null);
		}

		void MessageObjectToParts (MessageDescription md, object msgObject, object [] parts)
		{
			foreach (MessagePartDescription partDesc in md.Body.Parts)
				if (partDesc.MemberInfo is FieldInfo)
					parts [partDesc.Index] = ((FieldInfo) partDesc.MemberInfo).GetValue (msgObject);
				else
					parts [partDesc.Index] = ((PropertyInfo) partDesc.MemberInfo).GetValue (msgObject, null);
		}

		internal static bool HasReturnValue (MessageBodyDescription desc)
		{
			return desc.ReturnValue != null && desc.ReturnValue.Type != typeof (void);
		}

		protected static int ParamsOffset (MessageBodyDescription desc)
		{
			return HasReturnValue (desc) ? 1 : 0;
		}

		protected static object [] CreatePartsArray (MessageBodyDescription desc)
		{
			if (HasReturnValue (desc))
				return new object [desc.Parts.Count + 1];
			return new object [desc.Parts.Count];
		}
	}

#if !NET_2_1
	class XmlMessagesFormatter : BaseMessagesFormatter
	{
		XmlSerializerFormatAttribute attr;
		Dictionary<MessageBodyDescription,XmlSerializer> bodySerializers
			= new Dictionary<MessageBodyDescription,XmlSerializer> ();

		public XmlMessagesFormatter (OperationDescription desc, XmlSerializerFormatAttribute attr)
			: base (desc)
		{
			this.attr = attr;
		}

		public XmlMessagesFormatter (MessageDescriptionCollection messages, XmlSerializerFormatAttribute attr)
			: base (messages)
		{
			this.attr = attr;
		}

		private XmlReflectionMember CreateReflectionMember (MessagePartDescription partDesc, bool isReturnValue)
		{
			XmlReflectionMember m = new XmlReflectionMember ();
			m.IsReturnValue = isReturnValue;
			m.MemberName = partDesc.Name;
			m.MemberType = partDesc.Type;
			return m;
		}

		protected override Message PartsToMessage (
			MessageDescription md, MessageVersion version, string action, object [] parts)
		{
			return Message.CreateMessage (version, action, new XmlBodyWriter (GetSerializer (md.Body), parts));
		}

		protected override object [] MessageToParts (MessageDescription md, Message message)
		{
			if (message.IsEmpty)
				return null;
				
			XmlDictionaryReader r = message.GetReaderAtBodyContents ();
			return (object []) GetSerializer (md.Body).Deserialize (r);
		}

		// FIXME: Handle ServiceKnownTypes
		XmlSerializer GetSerializer (MessageBodyDescription desc)
		{
			if (bodySerializers.ContainsKey (desc))
				return bodySerializers [desc];

			int count = desc.Parts.Count + (HasReturnValue (desc) ? 1 : 0);
			XmlReflectionMember [] members = new XmlReflectionMember [count];

			int ind = 0;
			if (HasReturnValue (desc))
				members [ind++] = CreateReflectionMember (desc.ReturnValue, true);

			foreach (MessagePartDescription partDesc in desc.Parts)
				members [ind++] = CreateReflectionMember (partDesc, false);

			// FIXME: Register known types into xmlImporter.
			XmlReflectionImporter xmlImporter = new XmlReflectionImporter ();
			XmlMembersMapping [] partsMapping = new XmlMembersMapping [1];
			partsMapping [0] = xmlImporter.ImportMembersMapping (desc.WrapperName, desc.WrapperNamespace, members, true);
			bodySerializers [desc] = XmlSerializer.FromMappings (partsMapping) [0];
			return bodySerializers [desc];
		}

		class XmlBodyWriter : BodyWriter
		{
			XmlSerializer serializer;
			object body;

			public XmlBodyWriter (XmlSerializer serializer, object parts)
				: base (false)
			{
				this.serializer = serializer;
				this.body = parts;
			}

			[MonoTODO]
			protected override BodyWriter OnCreateBufferedCopy (int maxBufferSize)
			{
				throw new NotSupportedException ();
			}

			protected override void OnWriteBodyContents (XmlDictionaryWriter writer)
			{
				serializer.Serialize (writer, body);
			}
		}
	}
#endif

	class DataContractMessagesFormatter : BaseMessagesFormatter
	{
		DataContractFormatAttribute attr;

		public DataContractMessagesFormatter (OperationDescription desc, DataContractFormatAttribute attr)
			: base (desc)
		{
			this.attr = attr;
		}

		public DataContractMessagesFormatter (MessageDescriptionCollection messages, DataContractFormatAttribute attr)
			: base (messages)
		{
			this.attr = attr;
		}

		Dictionary<MessagePartDescription, XmlObjectSerializer> serializers
			= new Dictionary<MessagePartDescription,XmlObjectSerializer> ();

		protected override Message PartsToMessage (
			MessageDescription md, MessageVersion version, string action, object [] parts)
		{
			return Message.CreateMessage (version, action, new DataContractBodyWriter (md.Body, this, parts));
		}

		protected override object [] MessageToParts (
			MessageDescription md, Message message)
		{
			if (message.IsEmpty)
				return null;

			int offset = ParamsOffset (md.Body);
			object [] parts = CreatePartsArray (md.Body);

			XmlDictionaryReader r = message.GetReaderAtBodyContents ();
			if (md.Body.WrapperName != null)
				r.ReadStartElement (md.Body.WrapperName, md.Body.WrapperNamespace);

			for (r.MoveToContent (); r.NodeType == XmlNodeType.Element; r.MoveToContent ()) {
				XmlQualifiedName key = new XmlQualifiedName (r.LocalName, r.NamespaceURI);
				MessagePartDescription rv = md.Body.ReturnValue;
				if (rv != null && rv.Name == key.Name && rv.Namespace == key.Namespace)
					parts [0] = GetSerializer (md.Body.ReturnValue).ReadObject (r);
				else if (md.Body.Parts.Contains (key)) {
					MessagePartDescription p = md.Body.Parts [key];
					parts [p.Index + offset] = GetSerializer (p).ReadObject (r);
				}
				else // Skip unknown elements
					r.Skip ();
			}

			if (md.Body.WrapperName != null && !r.EOF)
				r.ReadEndElement ();

			return parts;
		}

		// FIXME: Handle ServiceKnownTypes
		XmlObjectSerializer GetSerializer (MessagePartDescription partDesc)
		{
			if (!serializers.ContainsKey (partDesc))
				serializers [partDesc] = new DataContractSerializer (
					partDesc.Type, partDesc.Name, partDesc.Namespace);
			return serializers [partDesc];
		}

		class DataContractBodyWriter : BodyWriter
		{
			MessageBodyDescription desc;
			object [] parts;
			DataContractMessagesFormatter parent;

			public DataContractBodyWriter (MessageBodyDescription desc, DataContractMessagesFormatter parent, object [] parts)
				: base (false)
			{
				this.desc = desc;
				this.parent = parent;
				this.parts = parts;
			}

			protected override void OnWriteBodyContents (XmlDictionaryWriter writer)
			{
				int offset = HasReturnValue (desc) ? 1 : 0;
				if (desc.WrapperName != null)
					writer.WriteStartElement (desc.WrapperName, desc.WrapperNamespace);
				if (HasReturnValue (desc))
					WriteMessagePart (writer, desc, desc.ReturnValue, parts [0]);
				foreach (MessagePartDescription partDesc in desc.Parts)
					WriteMessagePart (writer, desc, partDesc, parts [partDesc.Index + offset]);
				if (desc.WrapperName != null)
					writer.WriteEndElement ();
			}

			void WriteMessagePart (
				XmlDictionaryWriter writer, MessageBodyDescription desc, MessagePartDescription partDesc, object obj)
			{
				parent.GetSerializer (partDesc).WriteObject (writer, obj);
			}
		}
	}
}