File: ByteStreamMessage.cs

package info (click to toggle)
mono 6.14.1%2Bds2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,282,732 kB
  • sloc: cs: 11,182,461; xml: 2,850,281; ansic: 699,123; cpp: 122,919; perl: 58,604; javascript: 30,841; asm: 21,845; makefile: 19,602; sh: 10,973; python: 4,772; pascal: 925; sql: 859; sed: 16; php: 1
file content (727 lines) | stat: -rw-r--r-- 30,896 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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------

namespace System.ServiceModel.Channels
{
    using System;
    using System.IO;
    using System.Net.Http;
    using System.Runtime;
    using System.Threading.Tasks;
    using System.Xml;

    public static class ByteStreamMessage
    {
        public static Message CreateMessage(Stream stream)
        {
            if (stream == null)
            {
                throw FxTrace.Exception.ArgumentNull("stream");
            }
            return CreateMessage(stream, XmlDictionaryReaderQuotas.Max, true); // moveBodyReaderToContent is true, for consistency with the other implementations of Message (including the Message base class itself)
        }

        public static Message CreateMessage(ArraySegment<byte> buffer)
        {
            return CreateMessage(buffer, null);
        }

        public static Message CreateMessage(ArraySegment<byte> buffer, BufferManager bufferManager)
        {
            if (buffer.Array == null)
            {
                throw FxTrace.Exception.ArgumentNull("buffer.Array", SR.ArgumentPropertyShouldNotBeNullError("buffer.Array"));
            }

            ByteStreamBufferedMessageData data = new ByteStreamBufferedMessageData(buffer, bufferManager);
            return CreateMessage(data, XmlDictionaryReaderQuotas.Max, true); // moveBodyReaderToContent is true, for consistency with the other implementations of Message (including the Message base class itself)
        }

        internal static Message CreateMessage(Stream stream, XmlDictionaryReaderQuotas quotas, bool moveBodyReaderToContent)
        {
            return new InternalByteStreamMessage(stream, quotas, moveBodyReaderToContent);
        }

        internal static Message CreateMessage(HttpRequestMessage httpRequestMessage, XmlDictionaryReaderQuotas quotas)
        {
            return new InternalByteStreamMessage(httpRequestMessage, quotas, true); // moveBodyReaderToContent is true, for consistency with the other implementations of Message (including the Message base class itself)
        }

        internal static Message CreateMessage(HttpResponseMessage httpResponseMessage, XmlDictionaryReaderQuotas quotas)
        {
            return new InternalByteStreamMessage(httpResponseMessage, quotas, true); // moveBodyReaderToContent is true, for consistency with the other implementations of Message (including the Message base class itself)
        }

        internal static Message CreateMessage(ByteStreamBufferedMessageData bufferedMessageData, XmlDictionaryReaderQuotas quotas, bool moveBodyReaderToContent)
        {
            return new InternalByteStreamMessage(bufferedMessageData, quotas, moveBodyReaderToContent);
        }

        internal static bool IsInternalByteStreamMessage(Message message)
        {
            Fx.Assert(message != null, "message should not be null");
            return message is InternalByteStreamMessage;
        }

        class InternalByteStreamMessage : Message
        {
            BodyWriter bodyWriter;
            MessageHeaders headers;
            MessageProperties properties;
            XmlByteStreamReader reader;

            /// <summary>
            /// If set to true, OnGetReaderAtBodyContents() calls MoveToContent() on the reader before returning it.
            /// If set to false, the reader is positioned on None, just before the root element of the body message.
            /// </summary>
            /// <remarks>
            /// We use this flag to preserve compatibility between .net 4.0 (or previous) and .net 4.5 (or later).
            ///
            /// In .net 4.0:
            /// - WebMessageEncodingBindingElement uses a raw encoder, different than ByteStreamMessageEncoder.
            /// - ByteStreamMessageEncodingBindingElement uses the ByteStreamMessageEncoder.
            /// - When the WebMessageEncodingBindingElement is used, the Message.GetReaderAtBodyContents() method returns 
            ///   an XmlDictionaryReader positioned initially on content (the root element of the xml); that's because MoveToContent() is called
            ///   on the reader before it's returned. 
            /// - When the ByteStreamMessageEncodingBindingElement is used, the Message.GetReaderAtBodyContents() method returns an 
            ///   XmlDictionaryReader positioned initially on None (just before the root element).
            /// 
            /// In .net 4.5:
            /// - Both WebMessageEncodingBindingElement and ByteStreamMessageEncodingBindingElement use the ByteStreamMessageEncoder.
            /// - So we need the ByteStreamMessageEncoder to call MoveToContent() when used by WebMessageEncodingBindingElement, and not do so
            ///   when used by the ByteStreamMessageEncodingBindingElement.
            /// - Preserving the compatibility with 4.0 is important especially because 4.5 is an in-place upgrade of 4.0.
            /// 
            /// See 252277 @ CSDMain for other info.
            /// </remarks>
            bool moveBodyReaderToContent;

            public InternalByteStreamMessage(ByteStreamBufferedMessageData bufferedMessageData, XmlDictionaryReaderQuotas quotas, bool moveBodyReaderToContent)
            {
                // Assign both writer and reader here so that we can CreateBufferedCopy without the need to
                // abstract between a streamed or buffered message. We're protected here by the state on Message
                // preventing both a read/write. 

                quotas = ByteStreamMessageUtility.EnsureQuotas(quotas);

                this.bodyWriter = new BufferedBodyWriter(bufferedMessageData);
                this.headers = new MessageHeaders(MessageVersion.None);
                this.properties = new MessageProperties();
                this.reader = new XmlBufferedByteStreamReader(bufferedMessageData, quotas);
                this.moveBodyReaderToContent = moveBodyReaderToContent;
            }

            public InternalByteStreamMessage(Stream stream, XmlDictionaryReaderQuotas quotas, bool moveBodyReaderToContent)
            {
                // Assign both writer and reader here so that we can CreateBufferedCopy without the need to
                // abstract between a streamed or buffered message. We're protected here by the state on Message
                // preventing both a read/write on the same stream. 

                quotas = ByteStreamMessageUtility.EnsureQuotas(quotas);

                this.bodyWriter = StreamedBodyWriter.Create(stream);
                this.headers = new MessageHeaders(MessageVersion.None);
                this.properties = new MessageProperties();
                this.reader = XmlStreamedByteStreamReader.Create(stream, quotas);
                this.moveBodyReaderToContent = moveBodyReaderToContent;
            }

            public InternalByteStreamMessage(HttpRequestMessage httpRequestMessage, XmlDictionaryReaderQuotas quotas, bool moveBodyReaderToContent)
            {
                Fx.Assert(httpRequestMessage != null, "The 'httpRequestMessage' parameter should not be null.");

                // Assign both writer and reader here so that we can CreateBufferedCopy without the need to
                // abstract between a streamed or buffered message. We're protected here by the state on Message
                // preventing both a read/write on the same stream. 

                quotas = ByteStreamMessageUtility.EnsureQuotas(quotas);

                this.bodyWriter = StreamedBodyWriter.Create(httpRequestMessage);
                this.headers = new MessageHeaders(MessageVersion.None);
                this.properties = new MessageProperties();
                this.reader = XmlStreamedByteStreamReader.Create(httpRequestMessage, quotas);
                this.moveBodyReaderToContent = moveBodyReaderToContent;
            }

            public InternalByteStreamMessage(HttpResponseMessage httpResponseMessage, XmlDictionaryReaderQuotas quotas, bool moveBodyReaderToContent)
            {
                Fx.Assert(httpResponseMessage != null, "The 'httpResponseMessage' parameter should not be null.");

                // Assign both writer and reader here so that we can CreateBufferedCopy without the need to
                // abstract between a streamed or buffered message. We're protected here by the state on Message
                // preventing both a read/write on the same stream. 

                quotas = ByteStreamMessageUtility.EnsureQuotas(quotas);

                this.bodyWriter = StreamedBodyWriter.Create(httpResponseMessage);
                this.headers = new MessageHeaders(MessageVersion.None);
                this.properties = new MessageProperties();
                this.reader = XmlStreamedByteStreamReader.Create(httpResponseMessage, quotas);
                this.moveBodyReaderToContent = moveBodyReaderToContent;
            }

            InternalByteStreamMessage(ByteStreamBufferedMessageData messageData, MessageHeaders headers, MessageProperties properties, XmlDictionaryReaderQuotas quotas, bool moveBodyReaderToContent)
            {
                this.headers = new MessageHeaders(headers);
                this.properties = new MessageProperties(properties);
                this.bodyWriter = new BufferedBodyWriter(messageData);
                this.reader = new XmlBufferedByteStreamReader(messageData, quotas);
                this.moveBodyReaderToContent = moveBodyReaderToContent;
            }

            public override MessageHeaders Headers
            {
                get
                {
                    if (this.IsDisposed)
                    {
                        throw FxTrace.Exception.ObjectDisposed(SR.ObjectDisposed("message"));
                    }
                    return this.headers;
                }
            }

            public override bool IsEmpty
            {
                get
                {
                    if (this.IsDisposed)
                    {
                        throw FxTrace.Exception.ObjectDisposed(SR.ObjectDisposed("message"));
                    }
                    return false;
                }
            }

            public override bool IsFault
            {
                get
                {
                    if (this.IsDisposed)
                    {
                        throw FxTrace.Exception.ObjectDisposed(SR.ObjectDisposed("message"));
                    }
                    return false;
                }
            }

            public override MessageProperties Properties
            {
                get
                {
                    if (this.IsDisposed)
                    {
                        throw FxTrace.Exception.ObjectDisposed(SR.ObjectDisposed("message"));
                    }
                    return this.properties;
                }
            }

            public override MessageVersion Version
            {
                get
                {
                    if (this.IsDisposed)
                    {
                        throw FxTrace.Exception.ObjectDisposed(SR.ObjectDisposed("message"));
                    }
                    return MessageVersion.None;
                }
            }

            protected override void OnBodyToString(XmlDictionaryWriter writer)
            {
                if (this.bodyWriter.IsBuffered)
                {
                    bodyWriter.WriteBodyContents(writer);
                }
                else
                {
                    writer.WriteString(SR.MessageBodyIsStream);
                }
            }

            protected override void OnClose()
            {
                Exception ex = null;
                try
                {
                    base.OnClose();
                }
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                    {
                        throw;
                    }
                    ex = e;
                }

                try
                {
                    if (properties != null)
                    {
                        properties.Dispose();
                    }
                }
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                    {
                        throw;
                    }
                    if (ex == null)
                    {
                        ex = e;
                    }
                }

                try
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                }
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                    {
                        throw;
                    }
                    if (ex == null)
                    {
                        ex = e;
                    }
                }

                if (ex != null)
                {
                    throw FxTrace.Exception.AsError(ex);
                }

                this.bodyWriter = null;
            }

            protected override MessageBuffer OnCreateBufferedCopy(int maxBufferSize)
            {
                BufferedBodyWriter bufferedBodyWriter;
                if (this.bodyWriter.IsBuffered)
                {
                    // Can hand this off in buffered case without making a new one. 
                    bufferedBodyWriter = (BufferedBodyWriter)this.bodyWriter;
                }
                else
                {
                    bufferedBodyWriter = (BufferedBodyWriter)this.bodyWriter.CreateBufferedCopy(maxBufferSize);
                }

                // Protected by Message state to be called only once. 
                this.bodyWriter = null;
                return new ByteStreamMessageBuffer(bufferedBodyWriter.MessageData, this.headers, this.properties, this.reader.Quotas, this.moveBodyReaderToContent);
            }

            protected override T OnGetBody<T>(XmlDictionaryReader reader)
            {
                Fx.Assert(reader is XmlByteStreamReader, "reader should be XmlByteStreamReader");
                if (this.IsDisposed)
                {
                    throw FxTrace.Exception.ObjectDisposed(SR.ObjectDisposed("message"));
                }

                Type typeT = typeof(T);
                if (typeof(Stream) == typeT)
                {
                    Stream stream = (reader as XmlByteStreamReader).ToStream();
                    reader.Close();
                    return (T)(object)stream;
                }
                else if (typeof(byte[]) == typeT)
                {
                    byte[] buffer = (reader as XmlByteStreamReader).ToByteArray();
                    reader.Close();
                    return (T)(object)buffer;
                }
                throw FxTrace.Exception.AsError(
                    new NotSupportedException(SR.ByteStreamMessageGetTypeNotSupported(typeT.FullName)));
            }

            protected override XmlDictionaryReader OnGetReaderAtBodyContents()
            {
                XmlDictionaryReader r = this.reader;
                this.reader = null;

                if ((r != null) && this.moveBodyReaderToContent)
                {
                    r.MoveToContent();
                }

                return r;
            }

            protected override IAsyncResult OnBeginWriteMessage(XmlDictionaryWriter writer, AsyncCallback callback, object state)
            {
                WriteMessagePreamble(writer);
                return new OnWriteMessageAsyncResult(writer, this, callback, state);
            }

            protected override void OnEndWriteMessage(IAsyncResult result)
            {
                OnWriteMessageAsyncResult.End(result);
            }

            protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
            {
                this.bodyWriter.WriteBodyContents(writer);
            }

            protected override IAsyncResult OnBeginWriteBodyContents(XmlDictionaryWriter writer, AsyncCallback callback, object state)
            {
                return this.bodyWriter.BeginWriteBodyContents(writer, callback, state);
            }

            protected override void OnEndWriteBodyContents(IAsyncResult result)
            {
                this.bodyWriter.EndWriteBodyContents(result);
            }

            class OnWriteMessageAsyncResult : AsyncResult
            {
                InternalByteStreamMessage message;
                XmlDictionaryWriter writer;

                public OnWriteMessageAsyncResult(XmlDictionaryWriter writer, InternalByteStreamMessage message, AsyncCallback callback, object state)
                    : base(callback, state)
                {
                    this.message = message;
                    this.writer = writer;

                    IAsyncResult result = this.message.OnBeginWriteBodyContents(this.writer, PrepareAsyncCompletion(HandleWriteBodyContents), this);
                    bool completeSelf = SyncContinue(result);

                    if (completeSelf)
                    {
                        this.Complete(true);
                    }
                }

                static bool HandleWriteBodyContents(IAsyncResult result)
                {
                    OnWriteMessageAsyncResult thisPtr = (OnWriteMessageAsyncResult)result.AsyncState;
                    thisPtr.message.OnEndWriteBodyContents(result);
                    thisPtr.message.WriteMessagePostamble(thisPtr.writer);
                    return true;
                }

                public static void End(IAsyncResult result)
                {
                    AsyncResult.End<OnWriteMessageAsyncResult>(result);
                }
            }
            
            class BufferedBodyWriter : BodyWriter
            {
                ByteStreamBufferedMessageData bufferedMessageData;

                public BufferedBodyWriter(ByteStreamBufferedMessageData bufferedMessageData)
                    : base(true)
                {
                    this.bufferedMessageData = bufferedMessageData;
                }

                internal ByteStreamBufferedMessageData MessageData
                {
                    get { return bufferedMessageData; }
                }

                protected override BodyWriter OnCreateBufferedCopy(int maxBufferSize)
                {
                    // Never called because when copying a Buffered message, we simply hand off the existing BodyWriter 
                    // to the new message.
                    Fx.Assert(false, "This is never called");
                    return null;
                }

                protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
                {
                    writer.WriteStartElement(ByteStreamMessageUtility.StreamElementName, string.Empty);
                    writer.WriteBase64(this.bufferedMessageData.Buffer.Array, this.bufferedMessageData.Buffer.Offset, this.bufferedMessageData.Buffer.Count);
                    writer.WriteEndElement();
                }
            }

            abstract class StreamedBodyWriter : BodyWriter
            {
                private StreamedBodyWriter()
                    : base(false)
                {
                }

                public static StreamedBodyWriter Create(Stream stream)
                {
                    return new StreamBasedStreamedBodyWriter(stream);
                }

                public static StreamedBodyWriter Create(HttpRequestMessage httpRequestMessage)
                {
                    return new HttpRequestMessageStreamedBodyWriter(httpRequestMessage);
                }

                public static StreamedBodyWriter Create(HttpResponseMessage httpResponseMessage)
                {
                    return new HttpResponseMessageStreamedBodyWriter(httpResponseMessage);
                }

                // OnCreateBufferedCopy / OnWriteBodyContents can only be called once - protected by state on Message (either copied or written once)
                protected override BodyWriter OnCreateBufferedCopy(int maxBufferSize)
                {
                    using (BufferManagerOutputStream bufferedStream = new BufferManagerOutputStream(SR.MaxReceivedMessageSizeExceeded("{0}"), maxBufferSize))
                    {
                        using (XmlDictionaryWriter writer = new XmlByteStreamWriter(bufferedStream, true))
                        {
                            OnWriteBodyContents(writer);
                            writer.Flush();
                            int size;
                            byte[] bytesArray = bufferedStream.ToArray(out size);
                            ByteStreamBufferedMessageData bufferedMessageData = new ByteStreamBufferedMessageData(new ArraySegment<byte>(bytesArray, 0, size));
                            return new BufferedBodyWriter(bufferedMessageData);
                        }
                    }
                }

                // OnCreateBufferedCopy / OnWriteBodyContents can only be called once - protected by state on Message (either copied or written once)
                protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
                {
                    writer.WriteStartElement(ByteStreamMessageUtility.StreamElementName, string.Empty);
                    writer.WriteValue(new ByteStreamStreamProvider(this.GetStream()));
                    writer.WriteEndElement();
                }

                protected override IAsyncResult OnBeginWriteBodyContents(XmlDictionaryWriter writer, AsyncCallback callback, object state)
                {
                    return new WriteBodyContentsAsyncResult(writer, this.GetStream(), callback, state);
                }

                protected override void OnEndWriteBodyContents(IAsyncResult result)
                {
                    WriteBodyContentsAsyncResult.End(result);
                }

                protected abstract Stream GetStream();

                class ByteStreamStreamProvider : IStreamProvider
                {
                    Stream stream;

                    internal ByteStreamStreamProvider(Stream stream)
                    {
                        this.stream = stream;
                    }

                    public Stream GetStream()
                    {
                        return stream;
                    }

                    public void ReleaseStream(Stream stream)
                    {
                        //Noop
                    }
                }

                class WriteBodyContentsAsyncResult : AsyncResult
                {
                    XmlDictionaryWriter writer;

                    public WriteBodyContentsAsyncResult(XmlDictionaryWriter writer, Stream stream, AsyncCallback callback, object state)
                        : base(callback, state)
                    {
                        this.writer = writer;

                        this.writer.WriteStartElement(ByteStreamMessageUtility.StreamElementName, string.Empty);
                        IAsyncResult result = this.writer.WriteValueAsync(new ByteStreamStreamProvider(stream)).AsAsyncResult(PrepareAsyncCompletion(HandleWriteBodyContents), this);
                        bool completeSelf = SyncContinue(result);

                        // Note:  The current task implementation hard codes the "IAsyncResult.CompletedSynchronously" property to false, so this fast path will never
                        // be hit, and we will always hop threads.  CSDMain #210220
                        if (completeSelf)
                        {
                            this.Complete(true);
                        }
                    }

                    static bool HandleWriteBodyContents(IAsyncResult result)
                    {
                        // If result is a task, we need to get the result so that exceptions are bubbled up in case the task is faulted.
                        Task t = result as Task;
                        if (t != null)
                        {
                            t.GetAwaiter().GetResult();
                        }

                        WriteBodyContentsAsyncResult thisPtr = (WriteBodyContentsAsyncResult)result.AsyncState;
                        thisPtr.writer.WriteEndElement();
                        return true;
                    }

                    public static void End(IAsyncResult result)
                    {
                        AsyncResult.End<WriteBodyContentsAsyncResult>(result);
                    }
                }

                class StreamBasedStreamedBodyWriter : StreamedBodyWriter
                {
                    private Stream stream;

                    public StreamBasedStreamedBodyWriter(Stream stream)
                    {

                        this.stream = stream;
                    }

                    protected override Stream GetStream()
                    {
                        return this.stream;
                    }
                }

                class HttpRequestMessageStreamedBodyWriter : StreamedBodyWriter
                {
                    private HttpRequestMessage httpRequestMessage;

                    public HttpRequestMessageStreamedBodyWriter(HttpRequestMessage httpRequestMessage)
                    {
                        Fx.Assert(httpRequestMessage != null, "The 'httpRequestMessage' parameter should not be null.");

                        this.httpRequestMessage = httpRequestMessage;
                    }

                    protected override Stream GetStream()
                    {
                        HttpContent content = this.httpRequestMessage.Content;
                        if (content != null)
                        {
                            return content.ReadAsStreamAsync().Result;
                        }

                        return new MemoryStream(EmptyArray<byte>.Instance);
                    }

                    protected override BodyWriter OnCreateBufferedCopy(int maxBufferSize)
                    {
                        HttpContent content = this.httpRequestMessage.Content;
                        if (content != null)
                        {
                            content.LoadIntoBufferAsync(maxBufferSize).Wait();
                        }

                        return base.OnCreateBufferedCopy(maxBufferSize);
                    }
                }

                class HttpResponseMessageStreamedBodyWriter : StreamedBodyWriter
                {
                    private HttpResponseMessage httpResponseMessage;

                    public HttpResponseMessageStreamedBodyWriter(HttpResponseMessage httpResponseMessage)
                    {
                        Fx.Assert(httpResponseMessage != null, "The 'httpResponseMessage' parameter should not be null.");

                        this.httpResponseMessage = httpResponseMessage;
                    }

                    protected override Stream GetStream()
                    {
                        HttpContent content = this.httpResponseMessage.Content;
                        if (content != null)
                        {
                            return content.ReadAsStreamAsync().Result;
                        }

                        return new MemoryStream(EmptyArray<byte>.Instance);
                    }

                    protected override BodyWriter OnCreateBufferedCopy(int maxBufferSize)
                    {
                        HttpContent content = this.httpResponseMessage.Content;
                        if (content != null)
                        {
                            content.LoadIntoBufferAsync(maxBufferSize).Wait();
                        }

                        return base.OnCreateBufferedCopy(maxBufferSize);
                    }
                }
            }

            class ByteStreamMessageBuffer : MessageBuffer
            {
                bool closed;
                MessageHeaders headers;
                ByteStreamBufferedMessageData messageData;
                MessageProperties properties;
                XmlDictionaryReaderQuotas quotas;
                bool moveBodyReaderToContent;
                object thisLock = new object();

                public ByteStreamMessageBuffer(ByteStreamBufferedMessageData messageData, MessageHeaders headers, MessageProperties properties, XmlDictionaryReaderQuotas quotas, bool moveBodyReaderToContent)
                    : base()
                {
                    this.messageData = messageData;
                    this.headers = new MessageHeaders(headers);
                    this.properties = new MessageProperties(properties);
                    this.quotas = new XmlDictionaryReaderQuotas();
                    quotas.CopyTo(this.quotas);
                    this.moveBodyReaderToContent = moveBodyReaderToContent;

                    this.messageData.Open();                
                }

                public override int BufferSize
                {
                    get { return this.messageData.Buffer.Count; }
                }

                object ThisLock
                {
                    get { return this.thisLock; }
                }

                public override void Close()
                {
                    lock (ThisLock)
                    {
                        if (!closed)
                        {
                            closed = true;
                            this.headers = null;
                            if (properties != null)
                            {
                                properties.Dispose();
                                properties = null;
                            }
                            this.messageData.Close();
                            this.messageData = null;
                            this.quotas = null;
                        }
                    }
                }

                public override Message CreateMessage()
                {
                    lock (ThisLock)
                    {
                        if (closed)
                        {
                            throw FxTrace.Exception.ObjectDisposed(SR.ObjectDisposed("message"));
                        }

                        return new InternalByteStreamMessage(this.messageData, this.headers, this.properties, this.quotas, this.moveBodyReaderToContent);
                    }
                }
            }
        }
    }
}