Esempio n. 1
0
        private static bool GetRemoteEnlistmentId(EndpointAddress address, out Guid remoteEnlistmentId)
        {
            AddressHeaderCollection headers = address.Headers;

            if (headers.Count == 1)
            {
                AddressHeader header = headers.FindHeader("Enlistment", "http://schemas.microsoft.com/ws/2006/02/transactions");
                if (header != null)
                {
                    XmlDictionaryReader addressHeaderReader = header.GetAddressHeaderReader();
                    XmlDictionaryReader reader2             = addressHeaderReader;
                    try
                    {
                        ControlProtocol protocol;
                        EnlistmentHeader.ReadFrom(addressHeaderReader, out remoteEnlistmentId, out protocol);
                        return(protocol == ControlProtocol.Durable2PC);
                    }
                    catch (InvalidEnlistmentHeaderException exception)
                    {
                        Microsoft.Transactions.Bridge.DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Information);
                    }
                    finally
                    {
                        if (reader2 != null)
                        {
                            reader2.Dispose();
                        }
                    }
                }
            }
            remoteEnlistmentId = Guid.Empty;
            return(false);
        }
Esempio n. 2
0
        protected override void OnWriteStartAddressHeader(XmlDictionaryWriter writer)
        {
            XmlDictionaryReader reader = GetAddressHeaderReader();

            writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
            writer.WriteAttributes(reader, false);
            reader.Dispose();
        }
Esempio n. 3
0
 protected override void Dispose(bool isDisposing)
 {
     _message.Close();
     if (_reader != null)
     {
         _reader.Dispose();
         _reader = null;
     }
     base.Dispose(isDisposing);
 }
        public static MessageFault CreateFault(Message message, int maxBufferSize)
        {
            MessageFault fault2;

            if (message == null)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message"));
            }
            XmlDictionaryReader readerAtBodyContents = message.GetReaderAtBodyContents();
            XmlDictionaryReader reader2 = readerAtBodyContents;

            try
            {
                MessageFault    fault;
                EnvelopeVersion envelope = message.Version.Envelope;
                if (envelope == EnvelopeVersion.Soap12)
                {
                    fault = ReceivedFault.CreateFault12(readerAtBodyContents, maxBufferSize);
                }
                else if (envelope == EnvelopeVersion.Soap11)
                {
                    fault = ReceivedFault.CreateFault11(readerAtBodyContents, maxBufferSize);
                }
                else
                {
                    if (envelope != EnvelopeVersion.None)
                    {
                        throw TraceUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("EnvelopeVersionUnknown", new object[] { envelope.ToString() })), message);
                    }
                    fault = ReceivedFault.CreateFaultNone(readerAtBodyContents, maxBufferSize);
                }
                message.ReadFromBodyContentsToEnd(readerAtBodyContents);
                fault2 = fault;
            }
            catch (InvalidOperationException exception)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString("SFxErrorDeserializingFault"), exception));
            }
            catch (FormatException exception2)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString("SFxErrorDeserializingFault"), exception2));
            }
            catch (XmlException exception3)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString("SFxErrorDeserializingFault"), exception3));
            }
            finally
            {
                if (reader2 != null)
                {
                    reader2.Dispose();
                }
            }
            return(fault2);
        }
Esempio n. 5
0
        public static List <SaveMusicList> ReadMusicListData(string folder_path)
        {
            List <SaveMusicList>   objectMusic = new List <SaveMusicList>();
            FileStream             fs          = new FileStream(folder_path, FileMode.Open);
            XmlDictionaryReader    reader      = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
            DataContractSerializer ser         = new DataContractSerializer(typeof(List <SaveMusicList>));

            objectMusic = (List <SaveMusicList>)ser.ReadObject(reader, true);
            reader.Dispose();
            fs.Dispose();
            return(objectMusic);
        }
Esempio n. 6
0
        protected override void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion)
        {
            if (!IsMessageVersionSupported(messageVersion))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.MessageHeaderVersionNotSupported, GetType().FullName, messageVersion.ToString()), "version"));
            }
            XmlDictionaryReader reader = GetHeaderReader();

            writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
            writer.WriteAttributes(reader, false);
            reader.Dispose();
        }
Esempio n. 7
0
        protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
        {
            XmlDictionaryReader reader = GetHeaderReader();

            reader.ReadStartElement();
            while (reader.NodeType != XmlNodeType.EndElement)
            {
                writer.WriteNode(reader, false);
            }
            reader.ReadEndElement();
            reader.Dispose();
        }
Esempio n. 8
0
        /// <summary>
        /// Extracts the img values from the JSON string
        /// </summary>
        /// <param name="jsonResponse">JSON string</param>
        /// <returns></returns>
        public static Dictionary <string, string> GetQRimage(string jsonResponse)
        {
            Dictionary <string, string> imgs   = new Dictionary <string, string>();
            XmlDictionaryReader         reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.ASCII.GetBytes(jsonResponse), new XmlDictionaryReaderQuotas());
            XDocument xml = XDocument.Load(reader);

            reader.Dispose();
            foreach (XElement element in xml.Descendants("img"))
            {
                imgs.Add(element.Parent.Name.ToString(), element.Value);
            }
            return(imgs);
        }
Esempio n. 9
0
        bool InferHasDetail(XmlBuffer detail)
        {
            bool hasDetail = false;

            if (detail != null)
            {
                XmlDictionaryReader reader = detail.GetReader(0);
                if (!reader.IsEmptyElement && reader.Read()) // check if the detail element contains data
                {
                    hasDetail = (reader.MoveToContent() != XmlNodeType.EndElement);
                }
                reader.Dispose();
            }
            return(hasDetail);
        }
Esempio n. 10
0
        /// <summary>
        /// Deserialize an object from JSON file.
        /// </summary>
        /// <param name="file">Path of the file to deserialize.</param>
        /// <returns>Object fill with file informations.</returns>
        public static T JsonDeserialize(string file)
        {
            FileStream             fs     = new FileStream(file, FileMode.Open);
            XmlDictionaryReader    reader = JsonReaderWriterFactory.CreateJsonReader(fs, new XmlDictionaryReaderQuotas());
            DataContractSerializer ser    = new DataContractSerializer(typeof(T));

            // Deserialize the data and read it from the instance.
            T result = ser.ReadObject(reader, true) as T;

            reader.Close();
            reader.Dispose();
            fs.Close();
            fs.Dispose();

            return(result);
        }
Esempio n. 11
0
        public void WriteTo(int sectionIndex, XmlWriter writer)
        {
            if (_bufferState != BufferState.Reading)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateInvalidStateException());
            }
            XmlDictionaryReader reader = GetReader(sectionIndex);

            try
            {
                writer.WriteNode(reader, false);
            }
            finally
            {
                reader.Dispose();
            }
        }
        public static OleTxTransactionHeader ReadFrom(Message message)
        {
            int num;
            OleTxTransactionHeader header;

            try
            {
                num = message.Headers.FindHeader("OleTxTransaction", "http://schemas.microsoft.com/ws/2006/02/tx/oletx");
            }
            catch (MessageHeaderException exception)
            {
                DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Error);
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TransactionException(System.ServiceModel.SR.GetString("OleTxHeaderCorrupt"), exception));
            }
            if (num < 0)
            {
                return(null);
            }
            XmlDictionaryReader readerAtHeader = message.Headers.GetReaderAtHeader(num);
            XmlDictionaryReader reader2        = readerAtHeader;

            try
            {
                header = ReadFrom(readerAtHeader);
            }
            catch (XmlException exception2)
            {
                DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, TraceEventType.Error);
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TransactionException(System.ServiceModel.SR.GetString("OleTxHeaderCorrupt"), exception2));
            }
            finally
            {
                if (reader2 != null)
                {
                    reader2.Dispose();
                }
            }
            MessageHeaderInfo headerInfo = message.Headers[num];

            if (!message.Headers.UnderstoodHeaders.Contains(headerInfo))
            {
                message.Headers.UnderstoodHeaders.Add(headerInfo);
            }
            return(header);
        }
Esempio n. 13
0
        public static WsatRegistrationHeader ReadFrom(Message message)
        {
            int num;
            WsatRegistrationHeader header;

            try
            {
                num = message.Headers.FindHeader("RegisterInfo", "http://schemas.microsoft.com/ws/2006/02/transactions");
            }
            catch (MessageHeaderException exception)
            {
                DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Warning);
                return(null);
            }
            if (num < 0)
            {
                return(null);
            }
            XmlDictionaryReader readerAtHeader = message.Headers.GetReaderAtHeader(num);
            XmlDictionaryReader reader2        = readerAtHeader;

            try
            {
                header = ReadFrom(readerAtHeader);
            }
            catch (XmlException exception2)
            {
                DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, TraceEventType.Error);
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnlistmentHeaderException(exception2.Message, exception2));
            }
            finally
            {
                if (reader2 != null)
                {
                    reader2.Dispose();
                }
            }
            MessageHeaderInfo headerInfo = message.Headers[num];

            if (!message.Headers.UnderstoodHeaders.Contains(headerInfo))
            {
                message.Headers.UnderstoodHeaders.Add(headerInfo);
            }
            return(header);
        }
Esempio n. 14
0
        /// <summary>
        /// Get JSON information from a defined node
        /// </summary>
        /// <param name="jsonResponse">JSON string</param>
        /// <param name="nodename">node name of the JSON field</param>
        /// <returns>returns the value (inner text) from the defined node</returns>
        public static string GetJsonNode(string jsonResponse, string nodename)
        {
            try
            {
                XmlDictionaryReader reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.ASCII.GetBytes(jsonResponse), new XmlDictionaryReaderQuotas());
                XDocument           xml    = XDocument.Load(reader);
                reader.Dispose();
                return(xml.Descendants(nodename).Single().Value);
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
            {
#if DEBUG
                Debug.WriteLine($"{debugPrefix} GetJsonNode() exception: {ex.Message}");
#endif
                LogEvent($"GetJsonNode() exception: {ex.Message}", EventLogEntryType.Error);
                return("");
            }
        }
Esempio n. 15
0
        public static object LoadFromFile(Type type, string filename)
        {
            object r = null;

            try
            {
                DataContractSerializer ser    = new DataContractSerializer(type);
                FileStream             stream = new FileStream(ApplicationData.Current.LocalFolder.Path + "\\" + filename, FileMode.Open);
                XmlDictionaryReader    reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas());
                r = ser.ReadObject(reader, true);
                reader.Dispose();
                stream.Dispose();
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message + "\n" + e.Source);
            }

            return(r);
        }
Esempio n. 16
0
        private void LoadFontSettings()
        {
            FileStream          fs     = null;
            XmlDictionaryReader reader = null;

            try
            {
                fs = new FileStream("settings.xml", FileMode.Open);
                XmlDictionaryReaderQuotas quotas = new XmlDictionaryReaderQuotas();
                reader = XmlDictionaryReader.CreateTextReader(fs, quotas);
                DataContractSerializer ser = new DataContractSerializer(typeof(Settings));

                Settings fontSettings =
                    (Settings)ser.ReadObject(reader, true);

                LeftListView.Font       = new Font(FontFamily.GenericSansSerif, fontSettings.FontSize);
                LeftListView.ForeColor  = fontSettings.FontColor;
                RightListView.Font      = new Font(FontFamily.GenericSansSerif, fontSettings.FontSize);
                RightListView.ForeColor = fontSettings.FontColor;
            }
            catch (System.Xml.XmlException)
            {
                MessageBox.Show("Ошибка при десериализации!");
            }
            catch (System.IO.FileNotFoundException)
            {
                MessageBox.Show("Файл не найден!");
            }
            catch (System.Runtime.Serialization.SerializationException)
            {
                MessageBox.Show("Файл поврежден и не может быть открыт!");
            }
            finally
            {
                if (reader != null)
                {
                    reader.Dispose();
                }
                fs.Close();
            }
        }
Esempio n. 17
0
 protected override void ReturnXmlReader(XmlDictionaryReader xmlReader)
 {
     Contract.Assert(xmlReader != null, "xmlReader MUST NOT be null");
     xmlReader.Dispose();
 }
        protected override void GetHeadersFromMessage(Message message, MessageDescription messageDescription, object[] parameters, bool isRequest)
        {
            MessageInfo messageInfo = isRequest ? requestMessageInfo : replyMessageInfo;

            if (!messageInfo.AnyHeaders)
            {
                return;
            }

            MessageHeaders headers = message.Headers;

            KeyValuePair <Type, ArrayList>[] multipleHeaderValues = null;
            ArrayList elementList = null;

            if (messageInfo.UnknownHeaderDescription != null)
            {
                elementList = new ArrayList();
            }

            for (int i = 0; i < headers.Count; i++)
            {
                MessageHeaderInfo        header            = headers[i];
                MessageHeaderDescription headerDescription = messageInfo.HeaderDescriptionTable.Get(header.Name, header.Namespace);
                if (headerDescription != null)
                {
                    if (header.MustUnderstand)
                    {
                        headers.UnderstoodHeaders.Add(header);
                    }

                    object item = null;
                    XmlDictionaryReader headerReader = headers.GetReaderAtHeader(i);
                    try
                    {
                        object dataValue = DeserializeHeaderContents(headerReader, messageDescription, headerDescription);
                        if (headerDescription.TypedHeader)
                        {
                            item = TypedHeaderManager.Create(headerDescription.Type, dataValue, headers[i].MustUnderstand, headers[i].Relay, headers[i].Actor);
                        }
                        else
                        {
                            item = dataValue;
                        }
                    }
                    finally
                    {
                        headerReader.Dispose();
                    }

                    if (headerDescription.Multiple)
                    {
                        if (multipleHeaderValues == null)
                        {
                            multipleHeaderValues = new KeyValuePair <Type, ArrayList> [parameters.Length];
                        }

                        if (multipleHeaderValues[headerDescription.Index].Key == null)
                        {
                            multipleHeaderValues[headerDescription.Index] = new KeyValuePair <System.Type, System.Collections.ArrayList>(headerDescription.TypedHeader ? TypedHeaderManager.GetMessageHeaderType(headerDescription.Type) : headerDescription.Type, new ArrayList());
                        }
                        multipleHeaderValues[headerDescription.Index].Value.Add(item);
                    }
                    else
                    {
                        parameters[headerDescription.Index] = item;
                    }
                }
                else if (messageInfo.UnknownHeaderDescription != null)
                {
                    MessageHeaderDescription unknownHeaderDescription = messageInfo.UnknownHeaderDescription;
                    XmlDictionaryReader      headerReader             = headers.GetReaderAtHeader(i);
                    try
                    {
                        XmlDocument doc       = new XmlDocument();
                        object      dataValue = doc.ReadNode(headerReader);
                        if (dataValue != null && unknownHeaderDescription.TypedHeader)
                        {
                            dataValue = TypedHeaderManager.Create(unknownHeaderDescription.Type, dataValue, headers[i].MustUnderstand, headers[i].Relay, headers[i].Actor);
                        }

                        elementList.Add(dataValue);
                    }
                    finally
                    {
                        headerReader.Dispose();
                    }
                }
            }
            if (multipleHeaderValues != null)
            {
                for (int i = 0; i < parameters.Length; i++)
                {
                    if (multipleHeaderValues[i].Key != null)
                    {
                        parameters[i] = multipleHeaderValues[i].Value.ToArray(multipleHeaderValues[i].Key);
                    }
                }
            }
            if (messageInfo.UnknownHeaderDescription != null)
            {
                parameters[messageInfo.UnknownHeaderDescription.Index] = elementList.ToArray(messageInfo.UnknownHeaderDescription.TypedHeader ? typeof(MessageHeader <XmlElement>) : typeof(XmlElement));
            }
        }
        private async Task ProcessOperation(HttpContext httpContext, IServiceProvider serviceProvider)
        {
            Message responseMessage;

            //Reload the body to ensure we have the full message
            var memoryStream = new MemoryStream((int)httpContext.Request.ContentLength.GetValueOrDefault(1024));
            await httpContext.Request.Body.CopyToAsync(memoryStream).ConfigureAwait(false);

            memoryStream.Seek(0, SeekOrigin.Begin);
            httpContext.Request.Body = memoryStream;

            //Return metadata if no request, provided this is a GET request
            if (httpContext.Request.Body.Length == 0 && httpContext.Request.Method?.ToLower() == "get")
            {
                if (_options.WsdlFileOptions != null)
                {
                    await ProcessMetaFromFile(httpContext);
                }
                else
                {
                    await ProcessMeta(httpContext);
                }

                return;
            }

            // Get the encoder based on Content Type
            var messageEncoder = _messageEncoders[0];

            foreach (var encoder in _messageEncoders)
            {
                if (encoder.IsContentTypeSupported(httpContext.Request.ContentType))
                {
                    messageEncoder = encoder;
                    break;
                }
            }

            Message requestMessage;

            //Get the message
            try
            {
                requestMessage = await ReadMessageAsync(httpContext, messageEncoder);
            }
            catch (Exception ex)
            {
                await WriteErrorResponseMessage(ex, StatusCodes.Status500InternalServerError, serviceProvider, null, messageEncoder, httpContext);

                return;
            }

            var messageFilters      = serviceProvider.GetServices <IMessageFilter>().ToArray();
            var asyncMessageFilters = serviceProvider.GetServices <IAsyncMessageFilter>().ToArray();

            //Execute request message filters
            try
            {
                foreach (var messageFilter in messageFilters)
                {
                    messageFilter.OnRequestExecuting(requestMessage);
                }

                foreach (var messageFilter in asyncMessageFilters)
                {
                    await messageFilter.OnRequestExecuting(requestMessage);
                }
            }
            catch (Exception ex)
            {
                await WriteErrorResponseMessage(ex, StatusCodes.Status500InternalServerError, serviceProvider, requestMessage, messageEncoder, httpContext);

                return;
            }

            var    messageInspector = serviceProvider.GetService <IMessageInspector>();
            object correlationObject;

            try
            {
                correlationObject = messageInspector?.AfterReceiveRequest(ref requestMessage);
            }
            catch (Exception ex)
            {
                await WriteErrorResponseMessage(ex, StatusCodes.Status500InternalServerError, serviceProvider, requestMessage, messageEncoder, httpContext);

                return;
            }

            var messageInspector2s  = serviceProvider.GetServices <IMessageInspector2>();
            var correlationObjects2 = default(List <(IMessageInspector2 inspector, object correlationObject)>);

            try
            {
                correlationObjects2 = messageInspector2s.Select(mi => (inspector: mi, correlationObject: mi.AfterReceiveRequest(ref requestMessage, _service))).ToList();
            }
            catch (Exception ex)
            {
                await WriteErrorResponseMessage(ex, StatusCodes.Status500InternalServerError, serviceProvider, requestMessage, messageEncoder, httpContext);

                return;
            }

            // for getting soapaction and parameters in (optional) body
            // GetReaderAtBodyContents must not be called twice in one request
            XmlDictionaryReader reader = null;

            if (!requestMessage.IsEmpty)
            {
                reader = requestMessage.GetReaderAtBodyContents();
            }

            try
            {
                var soapAction = HeadersHelper.GetSoapAction(httpContext, reader);
                requestMessage.Headers.Action = soapAction;
                var operation = _service.Operations.FirstOrDefault(o => o.SoapAction.Equals(soapAction, StringComparison.Ordinal) || o.Name.Equals(HeadersHelper.GetTrimmedSoapAction(soapAction), StringComparison.Ordinal));
                if (operation == null)
                {
                    var ex = new InvalidOperationException($"No operation found for specified action: {requestMessage.Headers.Action}");
                    await WriteErrorResponseMessage(ex, StatusCodes.Status500InternalServerError, serviceProvider, requestMessage, messageEncoder, httpContext);

                    return;
                }

                _logger.LogInformation($"Request for operation {operation.Contract.Name}.{operation.Name} received");

                try
                {
                    //Create an instance of the service class
                    var serviceInstance = serviceProvider.GetRequiredService(_service.ServiceType);

                    SetMessageHeadersToProperty(requestMessage, serviceInstance);

                    // Get operation arguments from message
                    var arguments = GetRequestArguments(requestMessage, reader, operation, httpContext);

                    ExecuteFiltersAndTune(httpContext, serviceProvider, operation, arguments, serviceInstance);

                    var invoker        = serviceProvider.GetService <IOperationInvoker>() ?? new DefaultOperationInvoker();
                    var responseObject = await invoker.InvokeAsync(operation.DispatchMethod, serviceInstance, arguments);

                    if (operation.IsOneWay)
                    {
                        httpContext.Response.StatusCode = (int)HttpStatusCode.Accepted;
                        return;
                    }

                    var resultOutDictionary = new Dictionary <string, object>();
                    foreach (var parameterInfo in operation.OutParameters)
                    {
                        resultOutDictionary[parameterInfo.Name] = arguments[parameterInfo.Index];
                    }

                    responseMessage = CreateResponseMessage(
                        operation, responseObject, resultOutDictionary, soapAction, requestMessage, messageEncoder);

                    httpContext.Response.ContentType           = httpContext.Request.ContentType;
                    httpContext.Response.Headers["SOAPAction"] = responseMessage.Headers.Action;

                    correlationObjects2.ForEach(mi => mi.inspector.BeforeSendReply(ref responseMessage, _service, mi.correlationObject));

                    messageInspector?.BeforeSendReply(ref responseMessage, correlationObject);

                    SetHttpResponse(httpContext, responseMessage);

                    await WriteMessageAsync(messageEncoder, responseMessage, httpContext);
                }
                catch (Exception exception)
                {
                    if (exception is TargetInvocationException targetInvocationException)
                    {
                        exception = targetInvocationException.InnerException;
                    }

                    _logger.LogError(0, exception, exception?.Message);
                    responseMessage = await WriteErrorResponseMessage(exception, StatusCodes.Status500InternalServerError, serviceProvider, requestMessage, messageEncoder, httpContext);
                }
            }
            finally
            {
                reader?.Dispose();
            }

            // Execute response message filters
            try
            {
                foreach (var messageFilter in messageFilters)
                {
                    messageFilter.OnResponseExecuting(responseMessage);
                }

                foreach (var messageFilter in asyncMessageFilters.Reverse())
                {
                    await messageFilter.OnResponseExecuting(responseMessage);
                }
            }
            catch (Exception ex)
            {
                responseMessage = await WriteErrorResponseMessage(ex, StatusCodes.Status500InternalServerError, serviceProvider, requestMessage, messageEncoder, httpContext);
            }
        }
Esempio n. 20
0
        protected override void GetHeadersFromMessage(Message message, MessageDescription messageDescription, object[] parameters, bool isRequest)
        {
            try
            {
                XmlSerializer serializer;
                MessageHeaderDescriptionTable headerDescriptionTable;
                MessageHeaderDescription      unknownHeaderDescription;
                if (isRequest)
                {
                    serializer               = _requestMessageInfo.HeaderSerializer;
                    headerDescriptionTable   = _requestMessageInfo.HeaderDescriptionTable;
                    unknownHeaderDescription = _requestMessageInfo.UnknownHeaderDescription;
                }
                else
                {
                    serializer               = _replyMessageInfo.HeaderSerializer;
                    headerDescriptionTable   = _replyMessageInfo.HeaderDescriptionTable;
                    unknownHeaderDescription = _replyMessageInfo.UnknownHeaderDescription;
                }
                MessageHeaders headers        = message.Headers;
                ArrayList      unknownHeaders = null;
                XmlDocument    xmlDoc         = null;
                if (unknownHeaderDescription != null)
                {
                    unknownHeaders = new ArrayList();
                    xmlDoc         = new XmlDocument();
                }
                if (serializer == null)
                {
                    if (unknownHeaderDescription != null)
                    {
                        for (int headerIndex = 0; headerIndex < headers.Count; headerIndex++)
                        {
                            AddUnknownHeader(unknownHeaderDescription, unknownHeaders, xmlDoc, null /*bufferWriter*/, headers[headerIndex], headers.GetReaderAtHeader(headerIndex));
                        }

                        parameters[unknownHeaderDescription.Index] = unknownHeaders.ToArray(unknownHeaderDescription.TypedHeader ? typeof(MessageHeader <XmlElement>) : typeof(XmlElement));
                    }
                    return;
                }


                MemoryStream        memoryStream = new MemoryStream();
                XmlDictionaryWriter bufferWriter = XmlDictionaryWriter.CreateTextWriter(memoryStream);
                message.WriteStartEnvelope(bufferWriter);
                message.WriteStartHeaders(bufferWriter);
                MessageHeaderOfTHelper messageHeaderOfTHelper = null;
                for (int headerIndex = 0; headerIndex < headers.Count; headerIndex++)
                {
                    MessageHeaderInfo        header       = headers[headerIndex];
                    XmlDictionaryReader      headerReader = headers.GetReaderAtHeader(headerIndex);
                    MessageHeaderDescription matchingHeaderDescription = headerDescriptionTable.Get(header.Name, header.Namespace);
                    if (matchingHeaderDescription != null)
                    {
                        if (header.MustUnderstand)
                        {
                            headers.UnderstoodHeaders.Add(header);
                        }

                        if (matchingHeaderDescription.TypedHeader)
                        {
                            if (messageHeaderOfTHelper == null)
                            {
                                messageHeaderOfTHelper = new MessageHeaderOfTHelper(parameters.Length);
                            }

                            messageHeaderOfTHelper.SetHeaderAttributes(matchingHeaderDescription, header.MustUnderstand, header.Relay, header.Actor);
                        }
                    }
                    if (matchingHeaderDescription == null && unknownHeaderDescription != null)
                    {
                        AddUnknownHeader(unknownHeaderDescription, unknownHeaders, xmlDoc, bufferWriter, header, headerReader);
                    }
                    else
                    {
                        bufferWriter.WriteNode(headerReader, false);
                    }

                    headerReader.Dispose();
                }
                bufferWriter.WriteEndElement();
                bufferWriter.WriteEndElement();
                bufferWriter.Flush();

                /*
                 * XmlDocument doc = new XmlDocument();
                 * memoryStream.Position = 0;
                 * doc.Load(memoryStream);
                 * doc.Save(Console.Out);
                 */

                memoryStream.Position = 0;
                ArraySegment <byte> memoryBuffer;
                memoryStream.TryGetBuffer(out memoryBuffer);
                XmlDictionaryReader bufferReader = XmlDictionaryReader.CreateTextReader(memoryBuffer.Array, 0, (int)memoryStream.Length, XmlDictionaryReaderQuotas.Max);

                bufferReader.ReadStartElement();
                bufferReader.MoveToContent();
                if (!bufferReader.IsEmptyElement)
                {
                    bufferReader.ReadStartElement();
                    object[] headerValues = (object[])serializer.Deserialize(bufferReader, _isEncoded ? GetEncoding(message.Version.Envelope) : null);
                    int      headerIndex  = 0;
                    foreach (MessageHeaderDescription headerDescription in messageDescription.Headers)
                    {
                        if (!headerDescription.IsUnknownHeaderCollection)
                        {
                            object parameterValue = headerValues[headerIndex++];
                            if (headerDescription.TypedHeader && parameterValue != null)
                            {
                                parameterValue = messageHeaderOfTHelper.CreateMessageHeader(headerDescription, parameterValue);
                            }

                            parameters[headerDescription.Index] = parameterValue;
                        }
                    }
                    bufferReader.Dispose();
                }
                if (unknownHeaderDescription != null)
                {
                    parameters[unknownHeaderDescription.Index] = unknownHeaders.ToArray(unknownHeaderDescription.TypedHeader ? typeof(MessageHeader <XmlElement>) : typeof(XmlElement));
                }
            }
            catch (InvalidOperationException e)
            {
                // all exceptions from XmlSerializer get wrapped in InvalidOperationException,
                // so we must be conservative and never turn this into a fault
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(
                                                                              SR.Format(SR.SFxErrorDeserializingHeader, messageDescription.MessageName), e));
            }
        }