File: WebMessageEncoderFactory.cs

package info (click to toggle)
mono 4.6.2.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (528 lines) | stat: -rw-r--r-- 25,149 bytes parent folder | download | duplicates (7)
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//----------------------------------------------------------------

namespace System.ServiceModel.Channels
{
    using System;
    using System.Globalization;
    using System.IO;
    using System.Runtime;
    using System.ServiceModel.Diagnostics;
    using System.Text;
    using System.Xml;
    using System.Diagnostics;

    class WebMessageEncoderFactory : MessageEncoderFactory
    {
        WebMessageEncoder messageEncoder;

        public WebMessageEncoderFactory(Encoding writeEncoding, int maxReadPoolSize, int maxWritePoolSize, XmlDictionaryReaderQuotas quotas, WebContentTypeMapper contentTypeMapper, bool javascriptCallbackEnabled)
        {
            messageEncoder = new WebMessageEncoder(writeEncoding, maxReadPoolSize, maxWritePoolSize, quotas, contentTypeMapper, javascriptCallbackEnabled);
        }

        public override MessageEncoder Encoder
        {
            get { return messageEncoder; }
        }

        public override MessageVersion MessageVersion
        {
            get { return messageEncoder.MessageVersion; }
        }

        internal static string GetContentType(string mediaType, Encoding encoding)
        {
            string charset = TextEncoderDefaults.EncodingToCharSet(encoding);
            if (!string.IsNullOrEmpty(charset))
            {
                return string.Format(CultureInfo.InvariantCulture, "{0}; charset={1}", mediaType, charset);
            }
            return mediaType;
        }

        class WebMessageEncoder : MessageEncoder
        {
            const string defaultMediaType = "application/xml";
            WebContentTypeMapper contentTypeMapper;
            string defaultContentType;

            // Double-checked locking pattern requires volatile for read/write synchronization
            volatile MessageEncoder jsonMessageEncoder;
            int maxReadPoolSize;
            int maxWritePoolSize;

            // Double-checked locking pattern requires volatile for read/write synchronization
            volatile MessageEncoder rawMessageEncoder;
            XmlDictionaryReaderQuotas readerQuotas;

            // Double-checked locking pattern requires volatile for read/write synchronization
            volatile MessageEncoder textMessageEncoder;
            object thisLock;
            Encoding writeEncoding;
            bool javascriptCallbackEnabled;

            public WebMessageEncoder(Encoding writeEncoding, int maxReadPoolSize, int maxWritePoolSize, XmlDictionaryReaderQuotas quotas, WebContentTypeMapper contentTypeMapper, bool javascriptCallbackEnabled)
            {
                if (writeEncoding == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writeEncoding");
                }

                this.thisLock = new object();

                TextEncoderDefaults.ValidateEncoding(writeEncoding);
                this.writeEncoding = writeEncoding;

                this.maxReadPoolSize = maxReadPoolSize;
                this.maxWritePoolSize = maxWritePoolSize;
                this.contentTypeMapper = contentTypeMapper;
                this.javascriptCallbackEnabled = javascriptCallbackEnabled;

                this.readerQuotas = new XmlDictionaryReaderQuotas();
                quotas.CopyTo(this.readerQuotas);

                this.defaultContentType = GetContentType(defaultMediaType, writeEncoding);
            }

            public override string ContentType
            {
                get { return this.defaultContentType; }
            }

            public override string MediaType
            {
                get { return defaultMediaType; }
            }

            public override MessageVersion MessageVersion
            {
                get { return MessageVersion.None; }
            }

            MessageEncoder JsonMessageEncoder
            {
                get
                {
                    if (jsonMessageEncoder == null)
                    {
                        lock (ThisLock)
                        {
                            if (jsonMessageEncoder == null)
                            {
                                jsonMessageEncoder = new JsonMessageEncoderFactory(writeEncoding, maxReadPoolSize, maxWritePoolSize, readerQuotas, javascriptCallbackEnabled).Encoder;
                            }
                        }
                    }
                    return jsonMessageEncoder;
                }
            }

            MessageEncoder RawMessageEncoder
            {
                get
                {
                    if (rawMessageEncoder == null)
                    {
                        lock (ThisLock)
                        {
                            if (rawMessageEncoder == null)
                            {
                                rawMessageEncoder = new ByteStreamMessageEncodingBindingElement(readerQuotas).CreateMessageEncoderFactory().Encoder;
                                ((IWebMessageEncoderHelper)rawMessageEncoder).EnableBodyReaderMoveToContent(); // see the comments in IWebMessageEncoderHelper for why this is done
                            }
                        }
                    }
                    return rawMessageEncoder;
                }
            }

            MessageEncoder TextMessageEncoder
            {
                get
                {
                    if (textMessageEncoder == null)
                    {
                        lock (ThisLock)
                        {
                            if (textMessageEncoder == null)
                            {
                                textMessageEncoder = new TextMessageEncoderFactory(MessageVersion.None, writeEncoding, maxReadPoolSize, maxWritePoolSize, readerQuotas).Encoder;
                            }
                        }
                    }
                    return textMessageEncoder;
                }
            }

            object ThisLock
            {
                get { return thisLock; }
            }

            public override bool IsContentTypeSupported(string contentType)
            {
                if (contentType == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contentType");
                }

                WebContentFormat messageFormat;
                if (TryGetContentTypeMapping(contentType, out messageFormat) &&
                    (messageFormat != WebContentFormat.Default))
                {
                    return true;
                }

                return RawMessageEncoder.IsContentTypeSupported(contentType) || JsonMessageEncoder.IsContentTypeSupported(contentType) || TextMessageEncoder.IsContentTypeSupported(contentType);
            }

            public override Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType)
            {
                if (bufferManager == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("bufferManager"));
                }

                WebContentFormat format = GetFormatForContentType(contentType);
                Message message;

                switch (format)
                {
                    case WebContentFormat.Json:
                        message = JsonMessageEncoder.ReadMessage(buffer, bufferManager, contentType);
                        message.Properties.Add(WebBodyFormatMessageProperty.Name, WebBodyFormatMessageProperty.JsonProperty);
                        break;
                    case WebContentFormat.Xml:
                        message = TextMessageEncoder.ReadMessage(buffer, bufferManager, contentType);
                        message.Properties.Add(WebBodyFormatMessageProperty.Name, WebBodyFormatMessageProperty.XmlProperty);
                        break;
                    case WebContentFormat.Raw:
                        message = RawMessageEncoder.ReadMessage(buffer, bufferManager, contentType);
                        message.Properties.Add(WebBodyFormatMessageProperty.Name, WebBodyFormatMessageProperty.RawProperty);
                        break;
                    default:
                        throw Fx.AssertAndThrow("This should never get hit because GetFormatForContentType shouldn't return a WebContentFormat other than Json, Xml, and Raw");
                }
                return message;
            }

            public override Message ReadMessage(Stream stream, int maxSizeOfHeaders, string contentType)
            {
                if (stream == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("stream"));
                }

                WebContentFormat format = GetFormatForContentType(contentType);
                Message message;
                switch (format)
                {
                    case WebContentFormat.Json:
                        message = JsonMessageEncoder.ReadMessage(stream, maxSizeOfHeaders, contentType);
                        message.Properties.Add(WebBodyFormatMessageProperty.Name, WebBodyFormatMessageProperty.JsonProperty);
                        break;
                    case WebContentFormat.Xml:
                        message = TextMessageEncoder.ReadMessage(stream, maxSizeOfHeaders, contentType);
                        message.Properties.Add(WebBodyFormatMessageProperty.Name, WebBodyFormatMessageProperty.XmlProperty);
                        break;
                    case WebContentFormat.Raw:
                        message = RawMessageEncoder.ReadMessage(stream, maxSizeOfHeaders, contentType);
                        message.Properties.Add(WebBodyFormatMessageProperty.Name, WebBodyFormatMessageProperty.RawProperty);
                        break;
                    default:
                        throw Fx.AssertAndThrow("This should never get hit because GetFormatForContentType shouldn't return a WebContentFormat other than Json, Xml, and Raw");
                }
                return message;
            }

            public override ArraySegment<byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)
            {
                if (message == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message"));
                }
                if (bufferManager == null)
                {
                    throw TraceUtility.ThrowHelperError(new ArgumentNullException("bufferManager"), message);
                }
                if (maxMessageSize < 0)
                {
                    throw TraceUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxMessageSize", maxMessageSize,
                        SR2.GetString(SR2.ValueMustBeNonNegative)), message);
                }
                if (messageOffset < 0 || messageOffset > maxMessageSize)
                {
                    throw TraceUtility.ThrowHelperError(new ArgumentOutOfRangeException("messageOffset", messageOffset,
                        SR2.GetString(SR2.JsonValueMustBeInRange, 0, maxMessageSize)), message);
                }
                ThrowIfMismatchedMessageVersion(message);

                WebContentFormat messageFormat = ExtractFormatFromMessage(message);
                JavascriptCallbackResponseMessageProperty javascriptResponseMessageProperty;
                switch (messageFormat)
                {
                    case WebContentFormat.Json:
                        return JsonMessageEncoder.WriteMessage(message, maxMessageSize, bufferManager, messageOffset);
                    case WebContentFormat.Xml:
                        if (message.Properties.TryGetValue<JavascriptCallbackResponseMessageProperty>(JavascriptCallbackResponseMessageProperty.Name, out javascriptResponseMessageProperty) &&
                            javascriptResponseMessageProperty != null &&
                            !String.IsNullOrEmpty(javascriptResponseMessageProperty.CallbackFunctionName))
                        {
                            throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR2.JavascriptCallbackNotsupported), message);
                        }
                        return TextMessageEncoder.WriteMessage(message, maxMessageSize, bufferManager, messageOffset);
                    case WebContentFormat.Raw:
                        if (message.Properties.TryGetValue<JavascriptCallbackResponseMessageProperty>(JavascriptCallbackResponseMessageProperty.Name, out javascriptResponseMessageProperty) &&
                            javascriptResponseMessageProperty != null &&
                            !String.IsNullOrEmpty(javascriptResponseMessageProperty.CallbackFunctionName))
                        {
                            throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR2.JavascriptCallbackNotsupported), message);
                        }
                        return RawMessageEncoder.WriteMessage(message, maxMessageSize, bufferManager, messageOffset);
                    default:
                        throw Fx.AssertAndThrow("This should never get hit because GetFormatForContentType shouldn't return a WebContentFormat other than Json, Xml, and Raw");
                }
            }

            public override void WriteMessage(Message message, Stream stream)
            {
                if (message == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message"));
                }
                if (stream == null)
                {
                    throw TraceUtility.ThrowHelperError(new ArgumentNullException("stream"), message);
                }
                ThrowIfMismatchedMessageVersion(message);

                WebContentFormat messageFormat = ExtractFormatFromMessage(message);
                JavascriptCallbackResponseMessageProperty javascriptResponseMessageProperty;
                switch (messageFormat)
                {
                    case WebContentFormat.Json:
                        JsonMessageEncoder.WriteMessage(message, stream);
                        break;
                    case WebContentFormat.Xml:
                        if (message.Properties.TryGetValue<JavascriptCallbackResponseMessageProperty>(JavascriptCallbackResponseMessageProperty.Name, out javascriptResponseMessageProperty) &&
                            javascriptResponseMessageProperty != null &&
                            !String.IsNullOrEmpty(javascriptResponseMessageProperty.CallbackFunctionName))
                        {
                            throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR2.JavascriptCallbackNotsupported), message);
                        }
                        TextMessageEncoder.WriteMessage(message, stream);
                        break;
                    case WebContentFormat.Raw:
                        if (message.Properties.TryGetValue<JavascriptCallbackResponseMessageProperty>(JavascriptCallbackResponseMessageProperty.Name, out javascriptResponseMessageProperty) &&
                            javascriptResponseMessageProperty != null &&
                            !String.IsNullOrEmpty(javascriptResponseMessageProperty.CallbackFunctionName))
                        {
                            throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR2.JavascriptCallbackNotsupported), message);
                        }
                        RawMessageEncoder.WriteMessage(message, stream);
                        break;
                    default:
                        throw Fx.AssertAndThrow("This should never get hit because GetFormatForContentType shouldn't return a WebContentFormat other than Json, Xml, and Raw");
                }
            }

            public override IAsyncResult BeginWriteMessage(Message message, Stream stream, AsyncCallback callback, object state)
            {
                if (message == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message"));
                }
                if (stream == null)
                {
                    throw TraceUtility.ThrowHelperError(new ArgumentNullException("stream"), message);
                }

                ThrowIfMismatchedMessageVersion(message);

                return new WriteMessageAsyncResult(message, stream, this, callback, state);
            }

            public override void EndWriteMessage(IAsyncResult result)
            {
                WriteMessageAsyncResult.End(result);
            }

            internal override bool IsCharSetSupported(string charSet)
            {
                Encoding tmp;
                return TextEncoderDefaults.TryGetEncoding(charSet, out tmp);
            }

            WebContentFormat ExtractFormatFromMessage(Message message)
            {
                object messageFormatProperty;
                message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out messageFormatProperty);
                if (messageFormatProperty == null)
                {
                    return WebContentFormat.Xml;
                }

                WebBodyFormatMessageProperty typedMessageFormatProperty = messageFormatProperty as WebBodyFormatMessageProperty;
                if ((typedMessageFormatProperty == null) ||
                    (typedMessageFormatProperty.Format == WebContentFormat.Default))
                {
                    return WebContentFormat.Xml;
                }

                return typedMessageFormatProperty.Format;
            }

            WebContentFormat GetFormatForContentType(string contentType)
            {
                WebContentFormat messageFormat;

                if (TryGetContentTypeMapping(contentType, out messageFormat) &&
                    (messageFormat != WebContentFormat.Default))
                {
                    if (DiagnosticUtility.ShouldTraceInformation)
                    {
                        if (string.IsNullOrEmpty(contentType))
                        {
                            contentType = "<null>";
                        }
                        TraceUtility.TraceEvent(TraceEventType.Information,
                            TraceCode.RequestFormatSelectedFromContentTypeMapper,
                            SR2.GetString(SR2.TraceCodeRequestFormatSelectedFromContentTypeMapper, messageFormat.ToString(), contentType));
                    }
                    return messageFormat;
                }

                // Don't pass on null content types to IsContentTypeSupported methods -- they might throw.
                // If null content type isn't already mapped, return the default format of Raw.

                if (contentType == null)
                {
                    messageFormat = WebContentFormat.Raw;
                }
                else if (JsonMessageEncoder.IsContentTypeSupported(contentType))
                {
                    messageFormat = WebContentFormat.Json;
                }
                else if (TextMessageEncoder.IsContentTypeSupported(contentType))
                {
                    messageFormat = WebContentFormat.Xml;
                }
                else
                {
                    messageFormat = WebContentFormat.Raw;
                }

                if (DiagnosticUtility.ShouldTraceInformation)
                {
                    TraceUtility.TraceEvent(TraceEventType.Information,
                        TraceCode.RequestFormatSelectedByEncoderDefaults,
                        SR2.GetString(SR2.TraceCodeRequestFormatSelectedByEncoderDefaults, messageFormat.ToString(), contentType));
                }

                return messageFormat;
            }

            bool TryGetContentTypeMapping(string contentType, out WebContentFormat format)
            {
                if (contentTypeMapper == null)
                {
                    format = WebContentFormat.Default;
                    return false;
                }

                try
                {
                    format = contentTypeMapper.GetMessageFormatForContentType(contentType);
                    if (!WebContentFormatHelper.IsDefined(format))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR2.GetString(SR2.UnknownWebEncodingFormat, contentType, format)));
                    }
                    return true;
                }
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                    {
                        throw;
                    }

                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(
                        SR2.GetString(SR2.ErrorEncounteredInContentTypeMapper), e));
                }
            }

            class WriteMessageAsyncResult : ScheduleActionItemAsyncResult
            {
                Message message;
                Stream stream;
                MessageEncoder encoder;
                WebMessageEncoder webMessageEncoder;
                static AsyncCompletion handleEndWriteMessage;

                public WriteMessageAsyncResult(Message message, Stream stream, WebMessageEncoder webMessageEncoder, AsyncCallback callback, object state)
                    : base(callback, state)
                {
                    this.message = message;
                    this.stream = stream;
                    this.webMessageEncoder = webMessageEncoder;

                    WebContentFormat messageFormat = webMessageEncoder.ExtractFormatFromMessage(message);
                    JavascriptCallbackResponseMessageProperty javascriptResponseMessageProperty;

                    switch (messageFormat)
                    {
                        case WebContentFormat.Json:
                            this.encoder = webMessageEncoder.JsonMessageEncoder;
                            this.Schedule();
                            break;

                        case WebContentFormat.Xml:
                            if (message.Properties.TryGetValue<JavascriptCallbackResponseMessageProperty>(JavascriptCallbackResponseMessageProperty.Name, out javascriptResponseMessageProperty) &&
                                javascriptResponseMessageProperty != null &&
                                !String.IsNullOrEmpty(javascriptResponseMessageProperty.CallbackFunctionName))
                            {
                                throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR2.JavascriptCallbackNotsupported), message);
                            }
                            this.encoder = webMessageEncoder.TextMessageEncoder;
                            this.Schedule();
                            break;

                        case WebContentFormat.Raw:
                            if (message.Properties.TryGetValue<JavascriptCallbackResponseMessageProperty>(JavascriptCallbackResponseMessageProperty.Name, out javascriptResponseMessageProperty) &&
                                javascriptResponseMessageProperty != null &&
                                !String.IsNullOrEmpty(javascriptResponseMessageProperty.CallbackFunctionName))
                            {
                                throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR2.JavascriptCallbackNotsupported), message);
                            }

                            handleEndWriteMessage = new AsyncCompletion(HandleEndWriteMessage);
                            IAsyncResult result = webMessageEncoder.RawMessageEncoder.BeginWriteMessage(message, stream, PrepareAsyncCompletion(HandleEndWriteMessage), this);
                            if (SyncContinue(result))
                            {
                                this.Complete(true);
                            }
                            break;

                        default:
                            throw Fx.AssertAndThrow("This should never get hit because GetFormatForContentType shouldn't return a WebContentFormat other than Json, Xml, and Raw");
                    }
                }


                protected override void OnDoWork()
                {
                    this.encoder.WriteMessage(this.message, this.stream);
                }

                static bool HandleEndWriteMessage(IAsyncResult result)
                {
                    WriteMessageAsyncResult thisPtr = (WriteMessageAsyncResult)result.AsyncState;
                    thisPtr.webMessageEncoder.RawMessageEncoder.EndWriteMessage(result);
                    return true;
                }
            }
        }
    }
}