XmlReader TakeStreamedReader(Stream stream, string contentType) { if (streamedReaderPool == null) { lock (thisLock) { if (streamedReaderPool == null) { streamedReaderPool = new SynchronizedPool <XmlDictionaryReader>(maxReadPoolSize); } } } XmlDictionaryReader xmlReader = streamedReaderPool.Take(); try { if (contentType == null || IsMTOMContentType(contentType)) { if (xmlReader != null && xmlReader is IXmlMtomReaderInitializer) { ((IXmlMtomReaderInitializer)xmlReader).SetInput(stream, MtomMessageEncoderFactory.GetSupportedEncodings(), contentType, this.readerQuotas, this.maxBufferSize, onStreamedReaderClose); } else { xmlReader = XmlDictionaryReader.CreateMtomReader(stream, MtomMessageEncoderFactory.GetSupportedEncodings(), contentType, this.readerQuotas, this.maxBufferSize, onStreamedReaderClose); if (TD.ReadPoolMissIsEnabled()) { TD.ReadPoolMiss(xmlReader.GetType().Name); } } } else { if (xmlReader != null && xmlReader is IXmlTextReaderInitializer) { ((IXmlTextReaderInitializer)xmlReader).SetInput(stream, TextMessageEncoderFactory.GetEncodingFromContentType(contentType, this.contentEncodingMap), this.readerQuotas, onStreamedReaderClose); } else { xmlReader = XmlDictionaryReader.CreateTextReader(stream, TextMessageEncoderFactory.GetEncodingFromContentType(contentType, this.contentEncodingMap), this.readerQuotas, onStreamedReaderClose); if (TD.ReadPoolMissIsEnabled()) { TD.ReadPoolMiss(xmlReader.GetType().Name); } } } } catch (FormatException fe) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException( SR.GetString(SR.SFxErrorCreatingMtomReader), fe)); } catch (XmlException xe) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException( SR.GetString(SR.SFxErrorCreatingMtomReader), xe)); } return(xmlReader); }
public override Message ReadMessage(Stream stream, int maxSizeOfHeaders, string contentType) { // FIXME: create proper quotas return(Message.CreateMessage( XmlDictionaryReader.CreateMtomReader( stream, encoding, quotas), maxSizeOfHeaders, MessageVersion)); }
public override Message ReadMessage(ArraySegment <byte> buffer, BufferManager bufferManager, string contentType) { // FIXME: where should bufferManager be used? // FIXME: no way to take maxSizeOfHeaders // FIXME: create proper quotas return(Message.CreateMessage( XmlDictionaryReader.CreateMtomReader(buffer.Array, buffer.Offset, buffer.Count, encoding, quotas), int.MaxValue, MessageVersion)); }
protected override XmlDictionaryReader TakeXmlReader() { try { ArraySegment <byte> buffer = this.Buffer; XmlDictionaryReader xmlReader = readerPool.Take(); if (ContentType == null || messageEncoder.IsMTOMContentType(ContentType)) { if (xmlReader != null && xmlReader is IXmlMtomReaderInitializer) { ((IXmlMtomReaderInitializer)xmlReader).SetInput(buffer.Array, buffer.Offset, buffer.Count, MtomMessageEncoderFactory.GetSupportedEncodings(), ContentType, this.Quotas, this.messageEncoder.MaxBufferSize, onClose); } else { xmlReader = XmlDictionaryReader.CreateMtomReader(buffer.Array, buffer.Offset, buffer.Count, MtomMessageEncoderFactory.GetSupportedEncodings(), ContentType, this.Quotas, this.messageEncoder.MaxBufferSize, onClose); if (TD.ReadPoolMissIsEnabled()) { TD.ReadPoolMiss(xmlReader.GetType().Name); } } } else { if (xmlReader != null && xmlReader is IXmlTextReaderInitializer) { ((IXmlTextReaderInitializer)xmlReader).SetInput(buffer.Array, buffer.Offset, buffer.Count, TextMessageEncoderFactory.GetEncodingFromContentType(ContentType, this.messageEncoder.contentEncodingMap), this.Quotas, onClose); } else { xmlReader = XmlDictionaryReader.CreateTextReader(buffer.Array, buffer.Offset, buffer.Count, TextMessageEncoderFactory.GetEncodingFromContentType(ContentType, this.messageEncoder.contentEncodingMap), this.Quotas, onClose); if (TD.ReadPoolMissIsEnabled()) { TD.ReadPoolMiss(xmlReader.GetType().Name); } } } return(xmlReader); } catch (FormatException fe) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException( SR.GetString(SR.SFxErrorCreatingMtomReader), fe)); } catch (XmlException xe) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException( SR.GetString(SR.SFxErrorCreatingMtomReader), xe)); } }
/// <summary> /// Override the method to write the content to the xml dictionary writer. /// </summary> /// <param name="writer">Specify the output destination of the content.</param> protected override void OnWriteBodyContents(System.Xml.XmlDictionaryWriter writer) { byte[] bytes = new byte[this.stream.Length]; this.stream.Position = 0; this.stream.Read(bytes, 0, bytes.Length); string content = this.encoding.GetString(bytes); if (content.ToLowerInvariant().Contains("Content-Type: multipart/related".ToLowerInvariant())) { using (XmlDictionaryReader reader = XmlDictionaryReader.CreateMtomReader(bytes, 0, (int)bytes.Length, this.encoding, XmlDictionaryReaderQuotas.Max)) { XmlDocument msgDoc = new XmlDocument(); msgDoc.PreserveWhitespace = true; msgDoc.Load(reader); content = msgDoc.OuterXml; } } writer.WriteRaw(content); }
public DownloadFileResponse FromSOAP(byte[] soapResponse, string content_typeResponse, out FaultModel fault) { fault = null; try { var ms = new MemoryStream(soapResponse); Envelope obj = new Envelope(); DataContractSerializer dcs = new DataContractSerializer(obj.GetType()); XmlDictionaryReader reader = XmlDictionaryReader.CreateMtomReader(ms, new Encoding[] { Encoding.UTF8 }, content_typeResponse, XmlDictionaryReaderQuotas.Max); obj = (Envelope)dcs.ReadObject(reader); return(obj.Body.DownloadFileResponse); } catch (Exception ex) { throw new ServiceClientException(string.Format("Cannot deserialize {0}", typeof(DownloadFileResponse).Name), ex); } }
private ArraySegment <byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset, string startInfo, string boundary, string startUri, bool writeMessageHeaders) { if (message == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message"); } if (bufferManager == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("bufferManager"); } if (maxMessageSize < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxMessageSize", maxMessageSize, System.ServiceModel.SR.GetString("ValueMustBeNonNegative"))); } if ((messageOffset < 0) || (messageOffset > maxMessageSize)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("messageOffset", messageOffset, System.ServiceModel.SR.GetString("ValueMustBeInRange", new object[] { 0, maxMessageSize }))); } base.ThrowIfMismatchedMessageVersion(message); message.Properties.Encoder = this; MtomBufferedMessageWriter messageWriter = this.TakeBufferedWriter(); messageWriter.StartInfo = startInfo; messageWriter.Boundary = boundary; messageWriter.StartUri = startUri; messageWriter.WriteMessageHeaders = writeMessageHeaders; messageWriter.MaxSizeInBytes = maxMessageSize; ArraySegment <byte> segment = messageWriter.WriteMessage(message, bufferManager, messageOffset, maxMessageSize); this.ReturnMessageWriter(messageWriter); if (MessageLogger.LogMessagesAtTransportLevel) { string contentType = null; if (boundary != null) { contentType = this.FormatContentType(boundary, startInfo ?? this.GenerateStartInfoString()); } XmlDictionaryReader reader = XmlDictionaryReader.CreateMtomReader(segment.Array, segment.Offset, segment.Count, MtomMessageEncoderFactory.GetSupportedEncodings(), contentType, XmlDictionaryReaderQuotas.Max, 0x7fffffff, null); MessageLogger.LogMessage(ref message, reader, MessageLoggingSource.TransportSend); } return(segment); }
private XmlReader TakeStreamedReader(Stream stream, string contentType) { if (this.streamedReaderPool == null) { lock (this.thisLock) { if (this.streamedReaderPool == null) { this.streamedReaderPool = new SynchronizedPool <XmlDictionaryReader>(this.maxReadPoolSize); } } } XmlDictionaryReader reader = this.streamedReaderPool.Take(); try { if ((contentType == null) || this.IsMTOMContentType(contentType)) { if ((reader != null) && (reader is IXmlMtomReaderInitializer)) { ((IXmlMtomReaderInitializer)reader).SetInput(stream, MtomMessageEncoderFactory.GetSupportedEncodings(), contentType, this.readerQuotas, this.maxBufferSize, this.onStreamedReaderClose); return(reader); } return(XmlDictionaryReader.CreateMtomReader(stream, MtomMessageEncoderFactory.GetSupportedEncodings(), contentType, this.readerQuotas, this.maxBufferSize, this.onStreamedReaderClose)); } if ((reader != null) && (reader is IXmlTextReaderInitializer)) { ((IXmlTextReaderInitializer)reader).SetInput(stream, TextMessageEncoderFactory.GetEncodingFromContentType(contentType, this.contentEncodingMap), this.readerQuotas, this.onStreamedReaderClose); return(reader); } reader = XmlDictionaryReader.CreateTextReader(stream, TextMessageEncoderFactory.GetEncodingFromContentType(contentType, this.contentEncodingMap), this.readerQuotas, this.onStreamedReaderClose); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString("SFxErrorCreatingMtomReader"), exception)); } catch (XmlException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString("SFxErrorCreatingMtomReader"), exception2)); } return(reader); }
protected override XmlDictionaryReader TakeXmlReader() { XmlDictionaryReader reader2; try { ArraySegment <byte> buffer = base.Buffer; XmlDictionaryReader reader = this.readerPool.Take(); if ((this.ContentType == null) || this.messageEncoder.IsMTOMContentType(this.ContentType)) { if ((reader != null) && (reader is IXmlMtomReaderInitializer)) { ((IXmlMtomReaderInitializer)reader).SetInput(buffer.Array, buffer.Offset, buffer.Count, MtomMessageEncoderFactory.GetSupportedEncodings(), this.ContentType, this.messageEncoder.ReaderQuotas, this.messageEncoder.MaxBufferSize, this.onClose); } else { reader = XmlDictionaryReader.CreateMtomReader(buffer.Array, buffer.Offset, buffer.Count, MtomMessageEncoderFactory.GetSupportedEncodings(), this.ContentType, this.messageEncoder.ReaderQuotas, this.messageEncoder.MaxBufferSize, this.onClose); } } else if ((reader != null) && (reader is IXmlTextReaderInitializer)) { ((IXmlTextReaderInitializer)reader).SetInput(buffer.Array, buffer.Offset, buffer.Count, TextMessageEncoderFactory.GetEncodingFromContentType(this.ContentType, this.messageEncoder.contentEncodingMap), this.messageEncoder.ReaderQuotas, this.onClose); } else { reader = XmlDictionaryReader.CreateTextReader(buffer.Array, buffer.Offset, buffer.Count, TextMessageEncoderFactory.GetEncodingFromContentType(this.ContentType, this.messageEncoder.contentEncodingMap), this.messageEncoder.ReaderQuotas, this.onClose); } reader2 = reader; } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString("SFxErrorCreatingMtomReader"), exception)); } catch (XmlException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString("SFxErrorCreatingMtomReader"), exception2)); } return(reader2); }
public static void IXmlMtomReaderWriterInitializerTest() { DataContractSerializer serializer = new DataContractSerializer(typeof(TestData)); MemoryStream ms = new MemoryStream(); TestData td = new TestData(); XmlDictionaryWriter binaryWriter = XmlDictionaryWriter.CreateMtomWriter(ms, Encoding.UTF8, int.MaxValue, "application/soap+xml", null, null, true, false); IXmlMtomWriterInitializer writerInitializer = (IXmlMtomWriterInitializer)binaryWriter; writerInitializer.SetOutput(ms, Encoding.UTF8, int.MaxValue, "application/soap+xml", null, null, true, false); serializer.WriteObject(ms, td); binaryWriter.Flush(); byte[] xmlDoc = ms.ToArray(); binaryWriter.Close(); Encoding[] allEncodings = new Encoding[] { Encoding.Unicode, Encoding.BigEndianUnicode, Encoding.UTF8 }; XmlDictionaryReader mtomReader = XmlDictionaryReader.CreateMtomReader(xmlDoc, 0, xmlDoc.Length, allEncodings, null, XmlDictionaryReaderQuotas.Max, int.MaxValue, new OnXmlDictionaryReaderClose((XmlDictionaryReader reader) => { })); IXmlMtomReaderInitializer readerInitializer = (IXmlMtomReaderInitializer)mtomReader; readerInitializer.SetInput(xmlDoc, 0, xmlDoc.Length, allEncodings, null, XmlDictionaryReaderQuotas.Max, int.MaxValue, new OnXmlDictionaryReaderClose((XmlDictionaryReader reader) => { })); var b = mtomReader.ReadContentAsObject(); mtomReader.Close(); }
public static void Test() { MemoryStream ms; ItemOperations obj; DataContractSerializer dcs = new DataContractSerializer(typeof(ItemOperations)); string fixedMtom = MTOM.Replace( "Multipart/Related;boundary=DeltaSync91ABCB4AF5D24B8F988B77ED7A19733D?MTOM;", "Multipart/Related;boundary=\"DeltaSync91ABCB4AF5D24B8F988B77ED7A19733D?MTOM\";"); ms = new MemoryStream(Encoding.UTF8.GetBytes(fixedMtom)); XmlDictionaryReader reader = XmlDictionaryReader.CreateMtomReader(ms, Encoding.UTF8, XmlDictionaryReaderQuotas.Max); obj = (ItemOperations)dcs.ReadObject(reader); Console.WriteLine(obj.Status); Console.WriteLine(obj.Responses.Count); foreach (var resp in obj.Responses) { Console.WriteLine(" {0}", resp.ServerId); Console.WriteLine(" {0}", resp.Status); Console.WriteLine(" {0}", string.Join(" ", resp.Message.Select(b => string.Format("{0:X2}", (int)b)))); } }
public static void CreateMtomReaderWriterTest() { using (MemoryStream stream = new MemoryStream()) { string startInfo = "application/soap+xml"; using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateMtomWriter(stream, Encoding.UTF8, int.MaxValue, startInfo)) { writer.WriteElementString("localName", "the value"); writer.Flush(); byte[] bytes = stream.ToArray(); StreamReader reader = new StreamReader(stream); stream.Position = 0; string content = reader.ReadToEnd(); reader.Close(); using (XmlDictionaryReader xreader = XmlDictionaryReader.CreateMtomReader(bytes, 0, bytes.Length, Encoding.UTF8, new XmlDictionaryReaderQuotas())) { xreader.Read(); xreader.ReadOuterXml(); } } } }
ArraySegment <byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset, string startInfo, string boundary, string startUri, bool writeMessageHeaders) { if (message == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message"); } if (bufferManager == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("bufferManager"); } if (maxMessageSize < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxMessageSize", maxMessageSize, SR.GetString(SR.ValueMustBeNonNegative))); } if (messageOffset < 0 || messageOffset > maxMessageSize) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("messageOffset", messageOffset, SR.GetString(SR.ValueMustBeInRange, 0, maxMessageSize))); } ThrowIfMismatchedMessageVersion(message); EventTraceActivity eventTraceActivity = null; if (TD.MtomMessageEncodingStartIsEnabled()) { eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message); TD.MtomMessageEncodingStart(eventTraceActivity); } message.Properties.Encoder = this; MtomBufferedMessageWriter messageWriter = TakeBufferedWriter(); messageWriter.StartInfo = startInfo; messageWriter.Boundary = boundary; messageWriter.StartUri = startUri; messageWriter.WriteMessageHeaders = writeMessageHeaders; messageWriter.MaxSizeInBytes = maxMessageSize; ArraySegment <byte> messageData = messageWriter.WriteMessage(message, bufferManager, messageOffset, maxMessageSize); ReturnMessageWriter(messageWriter); if (TD.MessageWrittenByEncoderIsEnabled() && messageData != null) { TD.MessageWrittenByEncoder( eventTraceActivity ?? EventTraceActivityHelper.TryExtractActivity(message), messageData.Count, this); } if (MessageLogger.LogMessagesAtTransportLevel) { string contentType = null; if (boundary != null) { contentType = FormatContentType(boundary, startInfo ?? GenerateStartInfoString()); } XmlDictionaryReader xmlDictionaryReader = XmlDictionaryReader.CreateMtomReader(messageData.Array, messageData.Offset, messageData.Count, MtomMessageEncoderFactory.GetSupportedEncodings(), contentType, XmlDictionaryReaderQuotas.Max, int.MaxValue, null); MessageLogger.LogMessage(ref message, xmlDictionaryReader, MessageLoggingSource.TransportSend); } return(messageData); }
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel) { string startInfo = "application/soap+xml"; string boundary = string.Format("uuid:{0}+id=1", Guid.NewGuid()); string startUri = "http://tempuri.org/0"; // Set message ID UniqueId messageId = new UniqueId(); soapMessages.SoapRequestMessageId = messageId.ToString(); // Modify MessageId and From headers request.Headers.MessageId = messageId; request.Headers.From = new EndpointAddress("http://www.w3.org/2005/08/addressing/anonymous"); request.Headers.To = new Uri("http://www.w3.org/2005/08/addressing/anonymous"); // Create message buffer (Message needs to be recreated multiple times) MessageBuffer msgBuffer = request.CreateBufferedCopy(int.MaxValue); // Get assembled soap request and sign var messageToSign = msgBuffer.CreateMessage(); var bigXml = ConvertMessageToString(messageToSign); var signedBigXml = Encoding.UTF8.GetString(SoapSignatureUtility.SignBodyAndAddressingHeaders(Encoding.UTF8.GetBytes(bigXml), signingCertificate)); soapMessages.SoapRequest = signedBigXml; // Encoding message into MTOM format using MTOM writer request = msgBuffer.CreateMessage(); var initialMs = new MemoryStream(); var initialWriter = XmlDictionaryWriter.CreateMtomWriter(initialMs, Encoding.UTF8, int.MaxValue, startInfo, boundary, startUri, true, true); request.WriteMessage(initialWriter); initialWriter.Flush(); var originalMessageSize = (int)initialMs.Length; // Copy MTOM message into buffer byte[] bufferUnsigned = new byte[originalMessageSize]; Array.Copy(initialMs.GetBuffer(), 0, bufferUnsigned, 0, (int)initialMs.Position); string mtomString = Encoding.UTF8.GetString(bufferUnsigned); // Get SOAP XML from MTOM message, with start and end index int startSoapIndex; var unsignedXml = GetSoapFromString(mtomString, out startSoapIndex); int endSoapIndex = startSoapIndex + unsignedXml.Length; // If binary MIME parts are found in MTOM message, then replace out base64 content with MTOM include statement string signedFinalXml = signedBigXml; var partHeaderMatches = Regex.Matches(mtomString, @"((Content-ID: <.*>\s+)|(Content-Transfer-Encoding: binary\s+)|(Content-Type: application/octet-stream\s+)){3}", RegexOptions.IgnoreCase); if (partHeaderMatches.Count > 0) { for (int x = 0; x < partHeaderMatches.Count; x++) { var contentId = Regex.Match(partHeaderMatches[x].Value, "Content-ID: <(.*?)>"); var encodedContentId = HttpUtility.UrlEncode(contentId.Groups[1].Value).Replace(".", @"\."); var unencodedContentId = contentId.Groups[1].Value.Replace(".", @"\."); // var xopIncludeMatch = Regex.Match(unsignedXml, "(<[^>]+?>)(<([^>]+?:)?Include href=\"cid:(" + encodedContentId + ")\"[^>]*?/>)(</[^>]+?>)", RegexOptions.IgnoreCase); var xopIncludeMatch = Regex.Match(unsignedXml, "(<[^>]+?>)(<([^>]+?:)?Include href=\"cid:(" + encodedContentId + "|" + unencodedContentId + ")\"[^>]*?/>)(</[^>]+?>)", RegexOptions.IgnoreCase); signedFinalXml = Regex.Replace(signedFinalXml, xopIncludeMatch.Groups[1] + "[^<]*?" + xopIncludeMatch.Groups[5], xopIncludeMatch.Groups[0].Value); } } else { signedFinalXml = signedBigXml; } // Get difference in message length between unsigned and signed SOAP messages int diff = Encoding.UTF8.GetBytes(signedFinalXml).Length - Encoding.UTF8.GetBytes(unsignedXml).Length; // Create buffer large enough to contain MTOM message with signed SOAP XML byte[] bufferSigned = new byte[bufferUnsigned.Length + diff]; // Copy MIME start content (everything before SOAP XML) from unsigned buffer to signed buffer Array.Copy(bufferUnsigned, bufferSigned, startSoapIndex); // Copy signed SOAP XML into signed buffer after MIME start content var signedXmlArray = Encoding.UTF8.GetBytes(signedFinalXml); Array.Copy(signedXmlArray, 0, bufferSigned, startSoapIndex, signedXmlArray.Length); // Copy MIME end content to after signed SOAP XML Array.Copy(bufferUnsigned, endSoapIndex, bufferSigned, startSoapIndex + signedXmlArray.Length, bufferUnsigned.Length - (endSoapIndex + 1)); var mimeContent = new ArraySegment <byte>(bufferSigned, 0, originalMessageSize + diff).Array; soapMessages.MtomRequest = mimeContent; // Recreate request (Message) using MTOM reader var outputReader = XmlDictionaryReader.CreateMtomReader(mimeContent, 0, mimeContent.Length, Encoding.UTF8, new XmlDictionaryReaderQuotas()); request = Message.CreateMessage(outputReader, int.MaxValue, request.Version); // Dispose things msgBuffer.Close(); return(null); }