| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.IO; |
| | | 5 | | using System.Text; |
| | | 6 | | using System.Xml; |
| | | 7 | | |
| | | 8 | | namespace CoreWCF.Diagnostics |
| | | 9 | | { |
| | | 10 | | internal class EncodingFallbackAwareXmlTextWriter : XmlTextWriter |
| | | 11 | | { |
| | | 12 | | private readonly Encoding _encoding; |
| | | 13 | | |
| | 1 | 14 | | internal EncodingFallbackAwareXmlTextWriter(TextWriter writer) : base(writer) |
| | | 15 | | { |
| | 1 | 16 | | _encoding = writer.Encoding; |
| | 1 | 17 | | } |
| | | 18 | | |
| | | 19 | | public override void WriteString(string value) |
| | | 20 | | { |
| | 6 | 21 | | if (!string.IsNullOrEmpty(value) && |
| | 6 | 22 | | ContainsInvalidXmlChar(value)) |
| | | 23 | | { |
| | 0 | 24 | | byte[] blob = _encoding.GetBytes(value); |
| | 0 | 25 | | value = _encoding.GetString(blob); |
| | | 26 | | } |
| | | 27 | | |
| | 6 | 28 | | base.WriteString(value); |
| | 6 | 29 | | } |
| | | 30 | | |
| | | 31 | | private bool ContainsInvalidXmlChar(string value) |
| | | 32 | | { |
| | 6 | 33 | | if (string.IsNullOrEmpty(value)) |
| | | 34 | | { |
| | 0 | 35 | | return false; |
| | | 36 | | } |
| | | 37 | | |
| | 6 | 38 | | int i = 0; |
| | 6 | 39 | | int len = value.Length; |
| | | 40 | | |
| | 115 | 41 | | while (i < len) |
| | | 42 | | { |
| | 109 | 43 | | if (XmlConvert.IsXmlChar(value[i])) |
| | | 44 | | { |
| | 109 | 45 | | i++; |
| | 109 | 46 | | continue; |
| | | 47 | | } |
| | | 48 | | |
| | 0 | 49 | | if (i + 1 < len && |
| | 0 | 50 | | XmlConvert.IsXmlSurrogatePair(value[i + 1], value[i])) |
| | | 51 | | { |
| | 0 | 52 | | i += 2; |
| | 0 | 53 | | continue; |
| | | 54 | | } |
| | | 55 | | |
| | 0 | 56 | | return true; |
| | | 57 | | } |
| | | 58 | | |
| | 6 | 59 | | return false; |
| | | 60 | | } |
| | | 61 | | } |
| | | 62 | | } |