File: XmlMtomWriter.cs

package info (click to toggle)
mono 6.8.0.105%2Bdfsg-3.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,284,512 kB
  • sloc: cs: 11,172,132; xml: 2,850,069; ansic: 671,653; cpp: 122,091; perl: 59,366; javascript: 30,841; asm: 22,168; makefile: 20,093; sh: 15,020; python: 4,827; pascal: 925; sql: 859; sed: 16; php: 1
file content (1303 lines) | stat: -rw-r--r-- 47,477 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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------

namespace System.Xml
{
    using System;
    using System.Xml;
    using System.Xml.XPath;
    using System.IO;
    using System.Text;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Threading;
    using System.Runtime.Serialization;

    public interface IXmlMtomWriterInitializer
    {
        void SetOutput(Stream stream, Encoding encoding, int maxSizeInBytes, string startInfo, string boundary, string startUri, bool writeMessageHeaders, bool ownsStream);
    }

    class XmlMtomWriter : XmlDictionaryWriter, IXmlMtomWriterInitializer
    {
        // Maximum number of bytes that are inlined as base64 data without being MTOM-optimized as xop:Include
        const int MaxInlinedBytes = 767;  // 768 will be the first MIMEd length

        int maxSizeInBytes;
        XmlDictionaryWriter writer;
        XmlDictionaryWriter infosetWriter;
        MimeWriter mimeWriter;
        Encoding encoding;
        bool isUTF8;
        string contentID;
        string contentType;
        string initialContentTypeForRootPart;
        string initialContentTypeForMimeMessage;
        MemoryStream contentTypeStream;
        List<MimePart> mimeParts;
        IList<MtomBinaryData> binaryDataChunks;
        int depth;
        int totalSizeOfMimeParts;
        int sizeOfBufferedBinaryData;
        char[] chars;
        byte[] bytes;
        bool isClosed;
        bool ownsStream;

        public XmlMtomWriter()
        {
        }

        public void SetOutput(Stream stream, Encoding encoding, int maxSizeInBytes, string startInfo, string boundary, string startUri, bool writeMessageHeaders, bool ownsStream)
        {
            if (encoding == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("encoding");
            if (maxSizeInBytes < 0)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxSizeInBytes", SR.GetString(SR.ValueMustBeNonNegative)));
            this.maxSizeInBytes = maxSizeInBytes;
            this.encoding = encoding;
            this.isUTF8 = IsUTF8Encoding(encoding);
            Initialize(stream, startInfo, boundary, startUri, writeMessageHeaders, ownsStream);
        }

        XmlDictionaryWriter Writer
        {
            get
            {
                if (!IsInitialized)
                {
                    Initialize();
                }
                return writer;
            }
        }

        bool IsInitialized
        {
            get { return (initialContentTypeForRootPart == null); }
        }

        void Initialize(Stream stream, string startInfo, string boundary, string startUri, bool writeMessageHeaders, bool ownsStream)
        {
            if (stream == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream");
            if (startInfo == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("startInfo");
            if (boundary == null)
                boundary = GetBoundaryString();
            if (startUri == null)
                startUri = GenerateUriForMimePart(0);
            if (!MailBnfHelper.IsValidMimeBoundary(boundary))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.MtomBoundaryInvalid, boundary), "boundary"));

            this.ownsStream = ownsStream;
            this.isClosed = false;
            this.depth = 0;
            this.totalSizeOfMimeParts = 0;
            this.sizeOfBufferedBinaryData = 0;
            this.binaryDataChunks = null;
            this.contentType = null;
            this.contentTypeStream = null;
            this.contentID = startUri;
            if (this.mimeParts != null)
                this.mimeParts.Clear();
            this.mimeWriter = new MimeWriter(stream, boundary);
            this.initialContentTypeForRootPart = GetContentTypeForRootMimePart(this.encoding, startInfo);
            if (writeMessageHeaders)
                this.initialContentTypeForMimeMessage = GetContentTypeForMimeMessage(boundary, startUri, startInfo);
        }

        void Initialize()
        {
            if (this.isClosed)
                throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlWriterClosed)));

            if (this.initialContentTypeForRootPart != null)
            {
                if (this.initialContentTypeForMimeMessage != null)
                {
                    mimeWriter.StartPreface();
                    mimeWriter.WriteHeader(MimeGlobals.MimeVersionHeader, MimeGlobals.DefaultVersion);
                    mimeWriter.WriteHeader(MimeGlobals.ContentTypeHeader, this.initialContentTypeForMimeMessage);
                    this.initialContentTypeForMimeMessage = null;
                }

                WriteMimeHeaders(this.contentID, this.initialContentTypeForRootPart, this.isUTF8 ? MimeGlobals.Encoding8bit : MimeGlobals.EncodingBinary);

                Stream infosetContentStream = this.mimeWriter.GetContentStream();
                IXmlTextWriterInitializer initializer = writer as IXmlTextWriterInitializer;
                if (initializer == null)
                    writer = XmlDictionaryWriter.CreateTextWriter(infosetContentStream, this.encoding, this.ownsStream);
                else
                    initializer.SetOutput(infosetContentStream, this.encoding, this.ownsStream);

                this.contentID = null;
                this.initialContentTypeForRootPart = null;
            }
        }

        static string GetBoundaryString()
        {
            return MimeBoundaryGenerator.Next();
        }

        internal static bool IsUTF8Encoding(Encoding encoding)
        {
            return encoding.WebName == "utf-8";
        }

        static string GetContentTypeForMimeMessage(string boundary, string startUri, string startInfo)
        {
            StringBuilder contentTypeBuilder = new StringBuilder(
                String.Format(CultureInfo.InvariantCulture, "{0}/{1};{2}=\"{3}\";{4}=\"{5}\"",
                    MtomGlobals.MediaType, MtomGlobals.MediaSubtype,
                    MtomGlobals.TypeParam, MtomGlobals.XopType,
                    MtomGlobals.BoundaryParam, boundary));

            if (startUri != null && startUri.Length > 0)
                contentTypeBuilder.AppendFormat(CultureInfo.InvariantCulture, ";{0}=\"<{1}>\"", MtomGlobals.StartParam, startUri);

            if (startInfo != null && startInfo.Length > 0)
                contentTypeBuilder.AppendFormat(CultureInfo.InvariantCulture, ";{0}=\"{1}\"", MtomGlobals.StartInfoParam, startInfo);

            return contentTypeBuilder.ToString();
        }

        static string GetContentTypeForRootMimePart(Encoding encoding, string startInfo)
        {
            string contentType = String.Format(CultureInfo.InvariantCulture, "{0};{1}={2}", MtomGlobals.XopType, MtomGlobals.CharsetParam, CharSet(encoding));

            if (startInfo != null)
                contentType = String.Format(CultureInfo.InvariantCulture, "{0};{1}=\"{2}\"", contentType, MtomGlobals.TypeParam, startInfo);

            return contentType;
        }

        static string CharSet(Encoding enc)
        {
            string name = enc.WebName;
            if (String.Compare(name, Encoding.UTF8.WebName, StringComparison.OrdinalIgnoreCase) == 0)
                return name;
            if (String.Compare(name, Encoding.Unicode.WebName, StringComparison.OrdinalIgnoreCase) == 0)
                return "utf-16LE";
            if (String.Compare(name, Encoding.BigEndianUnicode.WebName, StringComparison.OrdinalIgnoreCase) == 0)
                return "utf-16BE";
            return name;
        }

        public override void WriteStartElement(string prefix, string localName, string ns)
        {
            WriteBase64InlineIfPresent();
            ThrowIfElementIsXOPInclude(prefix, localName, ns);
            Writer.WriteStartElement(prefix, localName, ns);
            depth++;
        }

        public override void WriteStartElement(string prefix, XmlDictionaryString localName, XmlDictionaryString ns)
        {
            if (localName == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("localName");

            WriteBase64InlineIfPresent();
            ThrowIfElementIsXOPInclude(prefix, localName.Value, ns == null ? null : ns.Value);
            Writer.WriteStartElement(prefix, localName, ns);
            depth++;
        }

        void ThrowIfElementIsXOPInclude(string prefix, string localName, string ns)
        {
            if (ns == null)
            {
                XmlBaseWriter w = this.Writer as XmlBaseWriter;
                if (w != null)
                    ns = w.LookupNamespace(prefix);
            }

            if (localName == MtomGlobals.XopIncludeLocalName && ns == MtomGlobals.XopIncludeNamespace)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomDataMustNotContainXopInclude, MtomGlobals.XopIncludeLocalName, MtomGlobals.XopIncludeNamespace)));
        }

        public override void WriteEndElement()
        {
            WriteXOPInclude();
            Writer.WriteEndElement();
            depth--;
            WriteXOPBinaryParts();
        }

        public override void WriteFullEndElement()
        {
            WriteXOPInclude();
            Writer.WriteFullEndElement();
            depth--;
            WriteXOPBinaryParts();
        }

        public override void WriteValue(IStreamProvider value)
        {
            if (value == null)
                throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value"));

            if (Writer.WriteState == WriteState.Element)
            {
                if (binaryDataChunks == null)
                {
                    binaryDataChunks = new List<MtomBinaryData>();
                    contentID = GenerateUriForMimePart((mimeParts == null) ? 1 : mimeParts.Count + 1);
                }
                binaryDataChunks.Add(new MtomBinaryData(value));
            }
            else
                Writer.WriteValue(value);
        }

        public override void WriteBase64(byte[] buffer, int index, int count)
        {
            if (Writer.WriteState == WriteState.Element)
            {
                if (buffer == null)
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("buffer"));

                // Not checking upper bound because it will be caught by "count".  This is what XmlTextWriter does.
                if (index < 0)
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("index", SR.GetString(SR.ValueMustBeNonNegative)));

                if (count < 0)
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.ValueMustBeNonNegative)));
                if (count > buffer.Length - index)
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.SizeExceedsRemainingBufferSpace, buffer.Length - index)));

                if (binaryDataChunks == null)
                {
                    binaryDataChunks = new List<MtomBinaryData>();
                    contentID = GenerateUriForMimePart((mimeParts == null) ? 1 : mimeParts.Count + 1);
                }

                int totalSize = ValidateSizeOfMessage(maxSizeInBytes, 0, totalSizeOfMimeParts);
                totalSize += ValidateSizeOfMessage(maxSizeInBytes, totalSize, sizeOfBufferedBinaryData);
                totalSize += ValidateSizeOfMessage(maxSizeInBytes, totalSize, count);
                sizeOfBufferedBinaryData += count;
                binaryDataChunks.Add(new MtomBinaryData(buffer, index, count));
            }
            else
                Writer.WriteBase64(buffer, index, count);
        }

        internal static int ValidateSizeOfMessage(int maxSize, int offset, int size)
        {
            if (size > (maxSize - offset))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomExceededMaxSizeInBytes, maxSize)));
            return size;
        }

        void WriteBase64InlineIfPresent()
        {
            if (binaryDataChunks != null)
            {
                WriteBase64Inline();
            }
        }

        void WriteBase64Inline()
        {
            foreach (MtomBinaryData data in binaryDataChunks)
            {
                if (data.type == MtomBinaryDataType.Provider)
                {
                    Writer.WriteValue(data.provider);
                }
                else
                {
                    Writer.WriteBase64(data.chunk, 0, data.chunk.Length);
                }
            }
            this.sizeOfBufferedBinaryData = 0;
            binaryDataChunks = null;
            contentType = null;
            contentID = null;
        }

        void WriteXOPInclude()
        {
            if (binaryDataChunks == null)
                return;

            bool inline = true;
            long size = 0;
            foreach (MtomBinaryData data in binaryDataChunks)
            {
                long len = data.Length;
                if (len < 0 || len > (MaxInlinedBytes - size))
                {
                    inline = false;
                    break;
                }
                size += len;
            }

            if (inline)
                WriteBase64Inline();
            else
            {
                if (mimeParts == null)
                    mimeParts = new List<MimePart>();

                MimePart mimePart = new MimePart(binaryDataChunks, contentID, contentType, MimeGlobals.EncodingBinary, sizeOfBufferedBinaryData, maxSizeInBytes);
                mimeParts.Add(mimePart);

                totalSizeOfMimeParts += ValidateSizeOfMessage(maxSizeInBytes, totalSizeOfMimeParts, mimePart.sizeInBytes);
                totalSizeOfMimeParts += ValidateSizeOfMessage(maxSizeInBytes, totalSizeOfMimeParts, mimeWriter.GetBoundarySize());

                Writer.WriteStartElement(MtomGlobals.XopIncludePrefix, MtomGlobals.XopIncludeLocalName, MtomGlobals.XopIncludeNamespace);
                Writer.WriteStartAttribute(MtomGlobals.XopIncludeHrefLocalName, MtomGlobals.XopIncludeHrefNamespace);
                Writer.WriteValue(String.Format(CultureInfo.InvariantCulture, "{0}{1}", MimeGlobals.ContentIDScheme, contentID));
                Writer.WriteEndAttribute();
                Writer.WriteEndElement();
                binaryDataChunks = null;
                sizeOfBufferedBinaryData = 0;
                contentType = null;
                contentID = null;
            }
        }

        public static string GenerateUriForMimePart(int index)
        {
            return String.Format(CultureInfo.InvariantCulture, "http://tempuri.org/{0}/{1}", index, DateTime.Now.Ticks);
        }

        void WriteXOPBinaryParts()
        {
            if (depth > 0 || mimeWriter.WriteState == MimeWriterState.Closed)
                return;

            if (Writer.WriteState != WriteState.Closed)
                Writer.Flush();

            if (mimeParts != null)
            {
                foreach (MimePart part in mimeParts)
                {
                    WriteMimeHeaders(part.contentID, part.contentType, part.contentTransferEncoding);
                    Stream s = mimeWriter.GetContentStream();
                    int blockSize = 256;
                    int bytesRead = 0;
                    byte[] block = new byte[blockSize];
                    Stream stream = null;
                    foreach (MtomBinaryData data in part.binaryData)
                    {
                        if (data.type == MtomBinaryDataType.Provider)
                        {
                            stream = data.provider.GetStream();
                            if (stream == null)
                                throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlInvalidStream)));
                            while (true)
                            {
                                bytesRead = stream.Read(block, 0, blockSize);
                                if (bytesRead > 0)
                                    s.Write(block, 0, bytesRead);
                                else
                                    break;
                                if (blockSize < 65536 && bytesRead == blockSize)
                                {
                                    blockSize = blockSize * 16;
                                    block = new byte[blockSize];
                                }
                            }

                            data.provider.ReleaseStream(stream);
                        }
                        else
                        {
                            s.Write(data.chunk, 0, data.chunk.Length);
                        }
                    }
                }
                mimeParts.Clear();
            }
            mimeWriter.Close();
        }

        void WriteMimeHeaders(string contentID, string contentType, string contentTransferEncoding)
        {
            mimeWriter.StartPart();
            if (contentID != null)
                mimeWriter.WriteHeader(MimeGlobals.ContentIDHeader, String.Format(CultureInfo.InvariantCulture, "<{0}>", contentID));
            if (contentTransferEncoding != null)
                mimeWriter.WriteHeader(MimeGlobals.ContentTransferEncodingHeader, contentTransferEncoding);
            if (contentType != null)
                mimeWriter.WriteHeader(MimeGlobals.ContentTypeHeader, contentType);
        }
#if NO
        public override bool CanSubsetElements
        {
            get { return Writer.CanSubsetElements; }
        }
#endif
        public override void Close()
        {
            if (!this.isClosed)
            {
                this.isClosed = true;
                if (IsInitialized)
                {
                    WriteXOPInclude();
                    if (Writer.WriteState == WriteState.Element ||
                        Writer.WriteState == WriteState.Attribute ||
                        Writer.WriteState == WriteState.Content)
                    {
                        Writer.WriteEndDocument();
                    }
                    Writer.Flush();
                    depth = 0;
                    WriteXOPBinaryParts();
                    Writer.Close();
                }
            }
        }

        void CheckIfStartContentTypeAttribute(string localName, string ns)
        {
            if (localName != null && localName == MtomGlobals.MimeContentTypeLocalName
                && ns != null && (ns == MtomGlobals.MimeContentTypeNamespace200406 || ns == MtomGlobals.MimeContentTypeNamespace200505))
            {
                contentTypeStream = new MemoryStream();
                this.infosetWriter = Writer;
                this.writer = XmlDictionaryWriter.CreateBinaryWriter(contentTypeStream);
                Writer.WriteStartElement("Wrapper");
                Writer.WriteStartAttribute(localName, ns);
            }
        }

        void CheckIfEndContentTypeAttribute()
        {
            if (contentTypeStream != null)
            {
                Writer.WriteEndAttribute();
                Writer.WriteEndElement();
                Writer.Flush();
                contentTypeStream.Position = 0;
                XmlReader contentTypeReader = XmlDictionaryReader.CreateBinaryReader(contentTypeStream, null, XmlDictionaryReaderQuotas.Max, null, null);
                while (contentTypeReader.Read())
                {
                    if (contentTypeReader.IsStartElement("Wrapper"))
                    {
                        contentType = contentTypeReader.GetAttribute(MtomGlobals.MimeContentTypeLocalName, MtomGlobals.MimeContentTypeNamespace200406);
                        if (contentType == null)
                        {
                            contentType = contentTypeReader.GetAttribute(MtomGlobals.MimeContentTypeLocalName, MtomGlobals.MimeContentTypeNamespace200505);
                        }
                        break;
                    }
                }
                this.writer = infosetWriter;
                this.infosetWriter = null;
                contentTypeStream = null;
                if (contentType != null)
                    Writer.WriteString(contentType);
            }
        }

#if NO
        public override bool ElementSubsetting
        {
            get
            {
                return Writer.ElementSubsetting;
            }
            set
            {
                Writer.ElementSubsetting = value;
            }
        }
#endif
        public override void Flush()
        {
            if (IsInitialized)
                Writer.Flush();
        }

        public override string LookupPrefix(string ns)
        {
            return Writer.LookupPrefix(ns);
        }

        public override XmlWriterSettings Settings
        {
            get
            {
                return Writer.Settings;
            }
        }

        public override void WriteAttributes(XmlReader reader, bool defattr)
        {
            Writer.WriteAttributes(reader, defattr);
        }

        public override void WriteBinHex(byte[] buffer, int index, int count)
        {
            WriteBase64InlineIfPresent();
            Writer.WriteBinHex(buffer, index, count);
        }

        public override void WriteCData(string text)
        {
            WriteBase64InlineIfPresent();
            Writer.WriteCData(text);
        }

        public override void WriteCharEntity(char ch)
        {
            WriteBase64InlineIfPresent();
            Writer.WriteCharEntity(ch);
        }

        public override void WriteChars(char[] buffer, int index, int count)
        {
            WriteBase64InlineIfPresent();
            Writer.WriteChars(buffer, index, count);
        }

        public override void WriteComment(string text)
        {
            // Don't write comments after the document element
            if (depth == 0 && mimeWriter.WriteState == MimeWriterState.Closed)
                return;

            WriteBase64InlineIfPresent();
            Writer.WriteComment(text);
        }

        public override void WriteDocType(string name, string pubid, string sysid, string subset)
        {
            WriteBase64InlineIfPresent();
            Writer.WriteDocType(name, pubid, sysid, subset);
        }
#if NO
        public override void WriteElementSubset(ArraySegment<byte> buffer)
        {
            Writer.WriteElementSubset(buffer);
        }
#endif
        public override void WriteEndAttribute()
        {
            CheckIfEndContentTypeAttribute();
            Writer.WriteEndAttribute();
        }

        public override void WriteEndDocument()
        {
            WriteXOPInclude();
            Writer.WriteEndDocument();
            depth = 0;
            WriteXOPBinaryParts();
        }

        public override void WriteEntityRef(string name)
        {
            WriteBase64InlineIfPresent();
            Writer.WriteEntityRef(name);
        }

        public override void WriteName(string name)
        {
            WriteBase64InlineIfPresent();
            Writer.WriteName(name);
        }

        public override void WriteNmToken(string name)
        {
            WriteBase64InlineIfPresent();
            Writer.WriteNmToken(name);
        }

        protected override void WriteTextNode(XmlDictionaryReader reader, bool attribute)
        {
            Type type = reader.ValueType;
            if (type == typeof(string))
            {
                if (reader.CanReadValueChunk)
                {
                    if (chars == null)
                    {
                        chars = new char[256];
                    }
                    int count;
                    while ((count = reader.ReadValueChunk(chars, 0, chars.Length)) > 0)
                    {
                        this.WriteChars(chars, 0, count);
                    }
                }
                else
                {
                    WriteString(reader.Value);
                }
                if (!attribute)
                {
                    reader.Read();
                }
            }
            else if (type == typeof(byte[]))
            {
                if (reader.CanReadBinaryContent)
                {
                    // Its best to read in buffers that are a multiple of 3 so we don't break base64 boundaries when converting text
                    if (bytes == null)
                    {
                        bytes = new byte[384];
                    }
                    int count;
                    while ((count = reader.ReadValueAsBase64(bytes, 0, bytes.Length)) > 0)
                    {
                        this.WriteBase64(bytes, 0, count);
                    }
                }
                else
                {
                    WriteString(reader.Value);
                }
                if (!attribute)
                {
                    reader.Read();
                }
            }
            else
            {
                base.WriteTextNode(reader, attribute);
            }
        }

        public override void WriteNode(XPathNavigator navigator, bool defattr)
        {
            WriteBase64InlineIfPresent();
            Writer.WriteNode(navigator, defattr);
        }

        public override void WriteProcessingInstruction(string name, string text)
        {
            WriteBase64InlineIfPresent();
            Writer.WriteProcessingInstruction(name, text);
        }

        public override void WriteQualifiedName(string localName, string namespaceUri)
        {
            WriteBase64InlineIfPresent();
            Writer.WriteQualifiedName(localName, namespaceUri);
        }

        public override void WriteRaw(char[] buffer, int index, int count)
        {
            WriteBase64InlineIfPresent();
            Writer.WriteRaw(buffer, index, count);
        }

        public override void WriteRaw(string data)
        {
            WriteBase64InlineIfPresent();
            Writer.WriteRaw(data);
        }

        public override void WriteStartAttribute(string prefix, string localName, string ns)
        {
            Writer.WriteStartAttribute(prefix, localName, ns);
            CheckIfStartContentTypeAttribute(localName, ns);
        }

        public override void WriteStartAttribute(string prefix, XmlDictionaryString localName, XmlDictionaryString ns)
        {
            Writer.WriteStartAttribute(prefix, localName, ns);
            if (localName != null && ns != null)
                CheckIfStartContentTypeAttribute(localName.Value, ns.Value);
        }

        public override void WriteStartDocument()
        {
            Writer.WriteStartDocument();
        }

        public override void WriteStartDocument(bool standalone)
        {
            Writer.WriteStartDocument(standalone);
        }

        public override WriteState WriteState
        {
            get
            {
                return Writer.WriteState;
            }
        }

        public override void WriteString(string text)
        {
            // Don't write whitespace after the document element
            if (depth == 0 && mimeWriter.WriteState == MimeWriterState.Closed && XmlConverter.IsWhitespace(text))
                return;

            WriteBase64InlineIfPresent();
            Writer.WriteString(text);
        }

        public override void WriteString(XmlDictionaryString value)
        {
            // Don't write whitespace after the document element
            if (depth == 0 && mimeWriter.WriteState == MimeWriterState.Closed && XmlConverter.IsWhitespace(value.Value))
                return;

            WriteBase64InlineIfPresent();
            Writer.WriteString(value);
        }

        public override void WriteSurrogateCharEntity(char lowChar, char highChar)
        {
            WriteBase64InlineIfPresent();
            Writer.WriteSurrogateCharEntity(lowChar, highChar);
        }

        public override void WriteWhitespace(string whitespace)
        {
            // Don't write whitespace after the document element
            if (depth == 0 && mimeWriter.WriteState == MimeWriterState.Closed)
                return;

            WriteBase64InlineIfPresent();
            Writer.WriteWhitespace(whitespace);
        }

        public override void WriteValue(object value)
        {
            IStreamProvider sp = value as IStreamProvider;
            if (sp != null)
            {
                WriteValue(sp);
            }
            else
            {
                WriteBase64InlineIfPresent();
                Writer.WriteValue(value);
            }
        }

        public override void WriteValue(string value)
        {
            // Don't write whitespace after the document element
            if (depth == 0 && mimeWriter.WriteState == MimeWriterState.Closed && XmlConverter.IsWhitespace(value))
                return;

            WriteBase64InlineIfPresent();
            Writer.WriteValue(value);
        }

        public override void WriteValue(bool value)
        {
            WriteBase64InlineIfPresent();
            Writer.WriteValue(value);
        }

        public override void WriteValue(DateTime value)
        {
            WriteBase64InlineIfPresent();
            Writer.WriteValue(value);
        }

        public override void WriteValue(double value)
        {
            WriteBase64InlineIfPresent();
            Writer.WriteValue(value);
        }

        public override void WriteValue(int value)
        {
            WriteBase64InlineIfPresent();
            Writer.WriteValue(value);
        }

        public override void WriteValue(long value)
        {
            WriteBase64InlineIfPresent();
            Writer.WriteValue(value);
        }

#if DECIMAL_FLOAT_API
        public override void WriteValue(decimal value)
        {
            WriteBase64InlineIfPresent();
            Writer.WriteValue(value);
        }

        public override void WriteValue(float value)
        {
            WriteBase64InlineIfPresent();
            Writer.WriteValue(value);
        }
#endif
        public override void WriteValue(XmlDictionaryString value)
        {
            // Don't write whitespace after the document element
            if (depth == 0 && mimeWriter.WriteState == MimeWriterState.Closed && XmlConverter.IsWhitespace(value.Value))
                return;

            WriteBase64InlineIfPresent();
            Writer.WriteValue(value);
        }

        public override void WriteXmlnsAttribute(string prefix, string ns)
        {
            Writer.WriteXmlnsAttribute(prefix, ns);
        }

        public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns)
        {
            Writer.WriteXmlnsAttribute(prefix, ns);
        }

        public override string XmlLang
        {
            get
            {
                return Writer.XmlLang;
            }
        }

        public override XmlSpace XmlSpace
        {
            get
            {
                return Writer.XmlSpace;
            }
        }

        static class MimeBoundaryGenerator
        {
            static long id;
            static string prefix;

            static MimeBoundaryGenerator()
            {
                prefix = string.Concat(Guid.NewGuid().ToString(), "+id=");
            }

            internal static string Next()
            {
                long nextId = Interlocked.Increment(ref id);
                return String.Format(CultureInfo.InvariantCulture, "{0}{1}", prefix, nextId);
            }
        }

        class MimePart
        {
            internal IList<MtomBinaryData> binaryData;
            internal string contentID;
            internal string contentType;
            internal string contentTransferEncoding;
            internal int sizeInBytes;

            internal MimePart(IList<MtomBinaryData> binaryData, string contentID, string contentType, string contentTransferEncoding, int sizeOfBufferedBinaryData, int maxSizeInBytes)
            {
                this.binaryData = binaryData;
                this.contentID = contentID;
                this.contentType = contentType ?? MtomGlobals.DefaultContentTypeForBinary;
                this.contentTransferEncoding = contentTransferEncoding;
                this.sizeInBytes = GetSize(contentID, contentType, contentTransferEncoding, sizeOfBufferedBinaryData, maxSizeInBytes);
            }

            static int GetSize(string contentID, string contentType, string contentTransferEncoding, int sizeOfBufferedBinaryData, int maxSizeInBytes)
            {
                int size = XmlMtomWriter.ValidateSizeOfMessage(maxSizeInBytes, 0, MimeGlobals.CRLF.Length * 3);
                if (contentTransferEncoding != null)
                    size += XmlMtomWriter.ValidateSizeOfMessage(maxSizeInBytes, size, MimeWriter.GetHeaderSize(MimeGlobals.ContentTransferEncodingHeader, contentTransferEncoding, maxSizeInBytes));
                if (contentType != null)
                    size += XmlMtomWriter.ValidateSizeOfMessage(maxSizeInBytes, size, MimeWriter.GetHeaderSize(MimeGlobals.ContentTypeHeader, contentType, maxSizeInBytes));
                if (contentID != null)
                {
                    size += XmlMtomWriter.ValidateSizeOfMessage(maxSizeInBytes, size, MimeWriter.GetHeaderSize(MimeGlobals.ContentIDHeader, contentID, maxSizeInBytes));
                    size += XmlMtomWriter.ValidateSizeOfMessage(maxSizeInBytes, size, 2); // include '<' and '>'
                }
                size += XmlMtomWriter.ValidateSizeOfMessage(maxSizeInBytes, size, sizeOfBufferedBinaryData);
                return size;
            }
        }
    }


    internal static class MtomGlobals
    {
        internal static string XopIncludeLocalName = "Include";
        internal static string XopIncludeNamespace = "http://www.w3.org/2004/08/xop/include";
        internal static string XopIncludePrefix = "xop";
        internal static string XopIncludeHrefLocalName = "href";
        internal static string XopIncludeHrefNamespace = String.Empty;
        internal static string MediaType = "multipart";
        internal static string MediaSubtype = "related";
        internal static string BoundaryParam = "boundary";
        internal static string TypeParam = "type";
        internal static string XopMediaType = "application";
        internal static string XopMediaSubtype = "xop+xml";
        internal static string XopType = "application/xop+xml";
        internal static string StartParam = "start";
        internal static string StartInfoParam = "start-info";
        internal static string ActionParam = "action";
        internal static string CharsetParam = "charset";
        internal static string MimeContentTypeLocalName = "contentType";
        internal static string MimeContentTypeNamespace200406 = "http://www.w3.org/2004/06/xmlmime";
        internal static string MimeContentTypeNamespace200505 = "http://www.w3.org/2005/05/xmlmime";
        internal static string DefaultContentTypeForBinary = "application/octet-stream";
    }

    internal static class MimeGlobals
    {
        internal static string MimeVersionHeader = "MIME-Version";
        internal static string DefaultVersion = "1.0";
        internal static string ContentIDScheme = "cid:";
        internal static string ContentIDHeader = "Content-ID";
        internal static string ContentTypeHeader = "Content-Type";
        internal static string ContentTransferEncodingHeader = "Content-Transfer-Encoding";
        internal static string EncodingBinary = "binary";
        internal static string Encoding8bit = "8bit";
        internal static byte[] COLONSPACE = new byte[] { (byte)':', (byte)' ' };
        internal static byte[] DASHDASH = new byte[] { (byte)'-', (byte)'-' };
        internal static byte[] CRLF = new byte[] { (byte)'\r', (byte)'\n' };
        // Per RFC2045, preceding CRLF sequence is part of the boundary. MIME boundary tags begin with --
        internal static byte[] BoundaryPrefix = new byte[] { (byte)'\r', (byte)'\n', (byte)'-', (byte)'-' };
    }

    enum MimeWriterState
    {
        Start,
        StartPreface,
        StartPart,
        Header,
        Content,
        Closed,
    }

    internal class MimeWriter
    {
        Stream stream;
        byte[] boundaryBytes;
        MimeWriterState state;
        BufferedWrite bufferedWrite;
        Stream contentStream;

        internal MimeWriter(Stream stream, string boundary)
        {
            if (stream == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream");
            if (boundary == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("boundary");

            this.stream = stream;
            this.boundaryBytes = MimeWriter.GetBoundaryBytes(boundary);
            this.state = MimeWriterState.Start;
            this.bufferedWrite = new BufferedWrite();
        }

        internal static int GetHeaderSize(string name, string value, int maxSizeInBytes)
        {
            if (name == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name");
            if (value == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");

            int size = XmlMtomWriter.ValidateSizeOfMessage(maxSizeInBytes, 0, MimeGlobals.COLONSPACE.Length + MimeGlobals.CRLF.Length);
            size += XmlMtomWriter.ValidateSizeOfMessage(maxSizeInBytes, size, name.Length);
            size += XmlMtomWriter.ValidateSizeOfMessage(maxSizeInBytes, size, value.Length);
            return size;
        }

        internal static byte[] GetBoundaryBytes(string boundary)
        {
            byte[] boundaryBytes = new byte[boundary.Length + MimeGlobals.BoundaryPrefix.Length];
            for (int i = 0; i < MimeGlobals.BoundaryPrefix.Length; i++)
                boundaryBytes[i] = MimeGlobals.BoundaryPrefix[i];
            Encoding.ASCII.GetBytes(boundary, 0, boundary.Length, boundaryBytes, MimeGlobals.BoundaryPrefix.Length);
            return boundaryBytes;
        }

        internal MimeWriterState WriteState
        {
            get
            {
                return state;
            }
        }

        internal int GetBoundarySize()
        {
            return this.boundaryBytes.Length;
        }

        internal void StartPreface()
        {
            if (state != MimeWriterState.Start)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MimeWriterInvalidStateForStartPreface, state.ToString())));

            state = MimeWriterState.StartPreface;
        }

        internal void StartPart()
        {
            switch (state)
            {
                case MimeWriterState.StartPart:
                case MimeWriterState.Closed:
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MimeWriterInvalidStateForStartPart, state.ToString())));
                default:
                    break;
            }

            state = MimeWriterState.StartPart;

            if (contentStream != null)
            {
                contentStream.Flush();
                contentStream = null;
            }

            bufferedWrite.Write(boundaryBytes);
            bufferedWrite.Write(MimeGlobals.CRLF);
        }

        internal void Close()
        {
            switch (state)
            {
                case MimeWriterState.Closed:
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MimeWriterInvalidStateForClose, state.ToString())));
                default:
                    break;
            }

            state = MimeWriterState.Closed;

            if (contentStream != null)
            {
                contentStream.Flush();
                contentStream = null;
            }

            bufferedWrite.Write(boundaryBytes);
            bufferedWrite.Write(MimeGlobals.DASHDASH);
            bufferedWrite.Write(MimeGlobals.CRLF);

            Flush();
        }

        void Flush()
        {
            if (bufferedWrite.Length > 0)
            {
                stream.Write(bufferedWrite.GetBuffer(), 0, bufferedWrite.Length);
                bufferedWrite.Reset();
            }
        }

        internal void WriteHeader(string name, string value)
        {
            if (name == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name");
            if (value == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");

            switch (state)
            {
                case MimeWriterState.Start:
                case MimeWriterState.Content:
                case MimeWriterState.Closed:
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MimeWriterInvalidStateForHeader, state.ToString())));
                default:
                    break;
            }

            state = MimeWriterState.Header;

            bufferedWrite.Write(name);
            bufferedWrite.Write(MimeGlobals.COLONSPACE);
            bufferedWrite.Write(value);
            bufferedWrite.Write(MimeGlobals.CRLF);
        }

        internal Stream GetContentStream()
        {
            switch (state)
            {
                case MimeWriterState.Start:
                case MimeWriterState.Content:
                case MimeWriterState.Closed:
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MimeWriterInvalidStateForContent, state.ToString())));
                default:
                    break;
            }

            state = MimeWriterState.Content;

            bufferedWrite.Write(MimeGlobals.CRLF);

            Flush();

            contentStream = stream;

            return contentStream;
        }
    }

    internal class BufferedWrite
    {
        byte[] buffer;
        int offset;

        internal BufferedWrite()
            : this(256)
        {
        }

        internal BufferedWrite(int initialSize)
        {
            buffer = new byte[initialSize];
        }

        void EnsureBuffer(int count)
        {
            int currSize = buffer.Length;
            if (count > currSize - offset)
            {
                int newSize = currSize;
                do
                {
                    if (newSize == Int32.MaxValue)
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.WriteBufferOverflow)));
                    newSize = (newSize < Int32.MaxValue / 2) ? newSize * 2 : Int32.MaxValue;
                }
                while (count > newSize - offset);
                byte[] newBuffer = new byte[newSize];
                Buffer.BlockCopy(buffer, 0, newBuffer, 0, offset);
                buffer = newBuffer;
            }
        }

        internal int Length
        {
            get
            {
                return offset;
            }
        }

        internal byte[] GetBuffer()
        {
            return buffer;
        }

        internal void Reset()
        {
            offset = 0;
        }

        internal void Write(byte[] value)
        {
            Write(value, 0, value.Length);
        }

        internal void Write(byte[] value, int index, int count)
        {
            EnsureBuffer(count);
            Buffer.BlockCopy(value, index, buffer, offset, count);
            offset += count;
        }

        internal void Write(string value)
        {
            Write(value, 0, value.Length);
        }

        internal void Write(string value, int index, int count)
        {
            EnsureBuffer(count);
            for (int i = 0; i < count; i++)
            {
                char c = value[index + i];
                if ((ushort)c > 0xFF)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.MimeHeaderInvalidCharacter, c, ((int)c).ToString("X", CultureInfo.InvariantCulture))));
                buffer[offset + i] = (byte)c;
            }
            offset += count;
        }

#if NO
        internal void Write(byte value)
        {
            EnsureBuffer(1);
            buffer[offset++] = value;
        }

        internal void Write(char value)
        {
            EnsureBuffer(1);
            if ((ushort)value > 0xFF)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.MimeHeaderInvalidCharacter, value, ((int)value).ToString("X", CultureInfo.InvariantCulture)))));
            buffer[offset++] = (byte)value;
        }

        internal void Write(int value)
        {
            Write(value.ToString());
        }

        internal void Write(char[] value)
        {
            Write(value, 0, value.Length);
        }

        internal void Write(char[] value, int index, int count)
        {
            EnsureBuffer(count);
            for (int i = 0; i < count; i++)
            {
                char c = value[index + i];
                if ((ushort)c > 0xFF)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.MimeHeaderInvalidCharacter, c, ((int)c).ToString("X", CultureInfo.InvariantCulture)))));
                buffer[offset + i] = (byte)c;
            }
            offset += count;
        }

#endif

    }

    enum MtomBinaryDataType { Provider, Segment }

    class MtomBinaryData
    {
        internal MtomBinaryDataType type;

        internal IStreamProvider provider;
        internal byte[] chunk;

        internal MtomBinaryData(IStreamProvider provider)
        {
            this.type = MtomBinaryDataType.Provider;
            this.provider = provider;
        }

        internal MtomBinaryData(byte[] buffer, int offset, int count)
        {
            this.type = MtomBinaryDataType.Segment;
            this.chunk = new byte[count];
            Buffer.BlockCopy(buffer, offset, this.chunk, 0, count);
        }

        internal long Length
        {
            get
            {
                if (this.type == MtomBinaryDataType.Segment)
                    return this.chunk.Length;

                return -1;
            }
        }
    }
}