예제 #1
0
        public override int ReadContentAsBase64(byte[] buffer, int index, int count)
        {
            int readCount = innerReader.ReadContentAsBase64(buffer, index, count);

            if (readCount == 0)
            {
                //GetReaderFromNextChunk will wait for chunks to be queued
                //then set this.innerReader to the received message's reader
                //it will throw TimeoutException if the next chunk is not received within specified timeout
                GetReaderFromNextChunk(receiveTimeout);
                if (!isLastChunk)
                {
                    readCount = innerReader.ReadContentAsBase64(buffer,
                                                                index, count);
                    if (readCount == 0)
                    {
                        throw new CommunicationException(
                                  "Received chunk contains no data");
                    }
                    else
                    {
                        return(readCount);
                    }
                }
                else //lastChunk
                {
                    return(0);
                }
            }
            else
            {
                return(readCount);
            }
        }
        private string SelectOperationInternal(Message message)
        {
            byte[] rawBody;
            using (XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents()) {
                bodyReader.ReadStartElement("Binary");
                rawBody = bodyReader.ReadContentAsBase64();
            }

            string operation = null;

            using (var bodyReader = new JsonTextReader(new StreamReader(new MemoryStream(rawBody)))) {
                while (bodyReader.Read())
                {
                    if (bodyReader.TokenType == JsonToken.PropertyName)
                    {
                        string propertyName = (string)bodyReader.Value;
                        if (propertyName.Equals("method", StringComparison.Ordinal))
                        {
                            if (!bodyReader.Read() || bodyReader.TokenType != JsonToken.String)
                            {
                                throw new InvalidOperationException("Invalid message format.");
                            }

                            operation = (string)bodyReader.Value;
                            break;
                        }
                    }
                }
            }

            return(operation);
        }
예제 #3
0
        public void ReadXml(XmlDictionaryReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            reader.MoveToContent();
            if (!reader.IsStartElement(XmlEncryptionConstants.Elements.CipherData, XmlEncryptionConstants.Namespace))
            {
                throw DiagnosticUtility.ThrowHelperXml(reader, SR.GetString(SR.ID4188));
            }

            reader.ReadStartElement(XmlEncryptionConstants.Elements.CipherData, XmlEncryptionConstants.Namespace);
            reader.ReadStartElement(XmlEncryptionConstants.Elements.CipherValue, XmlEncryptionConstants.Namespace);

            _cipherText = reader.ReadContentAsBase64();
            _iv         = null;

            // <CipherValue>
            reader.MoveToContent();
            reader.ReadEndElement();


            // <CipherData>
            reader.MoveToContent();
            reader.ReadEndElement();
        }
        private string RawMessageToString(ref Message message)
        {
            XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();

            bodyReader.ReadStartElement("Binary");
            byte[] requestBody     = bodyReader.ReadContentAsBase64();
            string messageAsString = Encoding.UTF8.GetString(requestBody);

            MemoryStream        ms     = new MemoryStream();
            XmlDictionaryWriter writer = XmlDictionaryWriter.CreateBinaryWriter(ms);

            writer.WriteStartElement("Binary");
            writer.WriteBase64(requestBody, 0, requestBody.Length);
            writer.WriteEndElement();
            writer.Flush();

            ms.Position = 0;

            XmlDictionaryReader reader     = XmlDictionaryReader.CreateBinaryReader(ms, XmlDictionaryReaderQuotas.Max);
            Message             newMessage = Message.CreateMessage(reader, int.MaxValue, message.Version);

            newMessage.Properties.CopyProperties(message.Properties);
            message = newMessage;

            return(messageAsString);
        }
예제 #5
0
        public object DeserializeReply(Message message, object[] parameters)
        {
            object bodyFormatProperty;

            if (!message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out bodyFormatProperty) ||
                (bodyFormatProperty as WebBodyFormatMessageProperty).Format != WebContentFormat.Raw)
            {
                throw new InvalidOperationException("Incoming messages must have a body format of Raw. Is a ContentTypeMapper set on the WebHttpBinding?");
            }

            XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();

            Newtonsoft.Json.JsonSerializer serializer = endpoint.NewtonsoftSettings().JsonSerializer;
            bodyReader.ReadStartElement("Binary");
            byte[] body = bodyReader.ReadContentAsBase64();
            try {
                using (MemoryStream ms = new MemoryStream(body)) {
                    using (StreamReader sr = new StreamReader(ms)) {
                        Type returnType = this.operation.Messages[1].Body.ReturnValue.Type;
                        var  result     = serializer.Deserialize(sr, returnType);

                        if (traceSource.Switch.ShouldTrace(TraceEventType.Information))
                        {
                            traceSource.TraceEvent(TraceEventType.Information, 1004, System.Text.Encoding.UTF8.GetString(body));
                        }

                        return(result);
                    }
                }
            } catch {
                traceSource.TraceEvent(TraceEventType.Error, 1005, System.Text.Encoding.UTF8.GetString(body));
                throw;
            }
        }
예제 #6
0
        private string ReadRawBody(ref Message message)
        {
            XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();

            bodyReader.ReadStartElement("Binary");
            byte[] bodyBytes = bodyReader.ReadContentAsBase64();
            //MemoryStream ms1 = new MemoryStream(bodyBytes);
            //StreamReader sr = new StreamReader(ms1);
            //JsonSerializer serializer = JsonHelper.GetJsonSerializer();
            //var obj = serializer.Deserialize(sr, typeof(ReturnMessage<object>));
            string messageBody = Encoding.UTF8.GetString(bodyBytes);
            // Now to recreate the message
            MemoryStream        ms     = new MemoryStream();
            XmlDictionaryWriter writer = XmlDictionaryWriter.CreateBinaryWriter(ms);

            writer.WriteStartElement("Binary");
            writer.WriteBase64(bodyBytes, 0, bodyBytes.Length);
            writer.WriteEndElement();
            writer.Flush();
            ms.Position = 0;
            XmlDictionaryReader reader     = XmlDictionaryReader.CreateBinaryReader(ms, XmlDictionaryReaderQuotas.Max);
            Message             newMessage = Message.CreateMessage(reader, int.MaxValue, message.Version);

            newMessage.Properties.CopyProperties(message.Properties);
            newMessage.Headers.CopyHeadersFrom(message);
            message = newMessage;
            return(messageBody);
        }
 public void DeserializeRequest(Message message, object[] parameters)
 {
     if (IsFormUrlEncodedMessage(message))
     {
         XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();
         bodyReader.ReadStartElement("Binary");
         byte[] bodyBytes = bodyReader.ReadContentAsBase64();
         string body      = Encoding.UTF8.GetString(bodyBytes);
         NameValueCollection         pairs  = HttpUtility.ParseQueryString(body);
         Dictionary <string, string> values = new Dictionary <string, string>();
         foreach (var key in pairs.AllKeys)
         {
             values.Add(key, pairs[key]);
         }
         foreach (var part in this.operation.Messages[0].Body.Parts)
         {
             if (values.ContainsKey(part.Name))
             {
                 string value = values[part.Name];
                 parameters[part.Index] = this.queryStringConverter.ConvertStringToValue(value, part.Type);
             }
             else
             {
                 parameters[part.Index] = GetDefaultValue(part.Type);
             }
         }
     }
     else
     {
         this.originalFormatter.DeserializeRequest(message, parameters);
     }
 }
예제 #8
0
        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            if (correlationState != null && correlationState is string)
            {
                //     if we have a $metadata response then buffer the response
                //     and merge it with the updated items
                if (mdataresponse == string.Empty)
                {
                    XmlDictionaryReader reader = reply.GetReaderAtBodyContents();
                    reader.ReadStartElement();
                    string content = MetadataInspector.encoding.GetString(reader.ReadContentAsBase64());

                    string filename = ((string)correlationState).Replace(@"/$", ".").Substring(1) + ".xml";
                    string fullpath = AppDomain.CurrentDomain.BaseDirectory + filename;

                    File.WriteAllText(fullpath, content);

                    mdataresponse = content;

                    //mdataresponse = MetadataConverter.Convert(content);
                }

                Message newreply = Message.CreateMessage(MessageVersion.None, "", new Writer(mdataresponse));
                newreply.Properties.CopyProperties(reply.Properties);

                reply = newreply;
            }
        }
예제 #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="message"></param>
        /// <param name="parameters"></param>
        public void DeserializeRequest(Message message, object[] parameters)
        {
            object bodyFormatProperty;

            if (!message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out bodyFormatProperty))
            {
                throw new InvalidOperationException("Incoming message cannot be null.");
            }

            WebBodyFormatMessageProperty bodyMsg = bodyFormatProperty as WebBodyFormatMessageProperty;

            if (bodyMsg == null)
            {
                throw new InvalidCastException("The type of body message must be WebBodyFormatMessageProperty.");
            }

            if (bodyMsg.Format != WebContentFormat.Raw)
            {
                throw new InvalidOperationException("The body message type must be equals to WebContentFormat.Raw.");
            }

            ////
            XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();

            bodyReader.ReadStartElement(BinaryRawBodyWriter.DefaultRootName);

            this.DecodeParameters(bodyReader.ReadContentAsBase64(), parameters);
        }
예제 #10
0
        /// <summary>
        /// Extracts the message body as a string
        /// </summary>
        /// <param name="msg">The message from which the body will be extracted</param>
        /// <param name="encoding">The encoding in which the body is expected to be</param>
        /// <returns>The message body in string representation</returns>
        public static string GetBodyAsString(Message msg, Encoding encoding)
        {
            XmlDictionaryReader xdr = msg.GetReaderAtBodyContents();

            xdr.ReadStartElement("MessageContent");
            return(encoding.GetString(xdr.ReadContentAsBase64()));
        }
예제 #11
0
        /// <summary>
        /// Reads a serialized token and converts it into a <see cref="SecurityToken"/>.
        /// </summary>
        /// <param name="reader">An XML reader positioned at the token's start element.</param>
        /// <returns>The parsed form of the token.</returns>
        public override SecurityToken ReadToken(XmlReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            XmlDictionaryReader dictionaryReader = XmlDictionaryReader.CreateDictionaryReader(reader);

            byte[] binaryData;
            string encoding = dictionaryReader.GetAttribute(EncodingType);

            if (encoding == null || encoding == Base64EncodingType)
            {
                dictionaryReader.Read();
                binaryData = dictionaryReader.ReadContentAsBase64();
            }
            else
            {
                throw new SecurityTokenException(
                          "Cannot read SecurityToken as its encoding is" + encoding + ". Expected a BinarySecurityToken with base64 encoding.");
            }

            string serializedToken = Encoding.UTF8.GetString(binaryData);

            return(ReadSecurityTokenFromString(serializedToken));
        }
예제 #12
0
            public override SecurityKeyIdentifierClause ReadClause(XmlDictionaryReader reader, byte[] derivationNonce, int derivationLength, string tokenType)
            {
                string encodingType = reader.GetAttribute(XD.SecurityJan2004Dictionary.EncodingType, null);

                if (encodingType == null)
                {
                    encodingType = DefaultEncodingType;
                }

                reader.ReadStartElement();

                byte[] bytes;
                if (encodingType == EncodingTypeValueBase64Binary)
                {
                    bytes = reader.ReadContentAsBase64();
                }
                else if (encodingType == EncodingTypeValueHexBinary)
                {
                    bytes = HexBinary.Parse(reader.ReadContentAsString()).Value;
                }
                else if (encodingType == EncodingTypeValueText)
                {
                    bytes = new UTF8Encoding().GetBytes(reader.ReadContentAsString());
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityMessageSerializationException(SR.GetString(SR.UnknownEncodingInKeyIdentifier)));
                }

                reader.ReadEndElement();

                return(CreateClause(bytes, derivationNonce, derivationLength));
            }
예제 #13
0
 public static byte[] DeserializeBody(Message message)
 {
     using (XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents()) {
         bodyReader.ReadStartElement("Binary");
         return(bodyReader.ReadContentAsBase64());
     }
 }
예제 #14
0
        public static JObject DeserializeMessage(Message message)
        {
            if (message.Properties.ContainsKey(JsonRpcConstants.JObjectMessageProperty))
            {
                return((JObject)message.Properties[JsonRpcConstants.JObjectMessageProperty]);
            }
            else
            {
                JObject json  = null;
                byte[]  bytes = null;
                using (XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents())
                {
                    bodyReader.ReadStartElement("Binary");
                    bytes = bodyReader.ReadContentAsBase64();
                }

                using (MemoryStream ms = new MemoryStream(bytes))
                {
                    using (StreamReader sr = new StreamReader(ms))
                    {
                        using (JsonTextReader jtr = new JsonTextReader(sr))
                        {
                            json = JObject.Load(jtr);
                        }
                    }
                }

                if (json == null)
                {
                    throw new ArgumentException("Message must be a JSON object");
                }

                return(json);
            }
        }
예제 #15
0
        internal static byte[] ReadContentAsBase64(XmlDictionaryReader reader, long maxBufferSize)
        {
            if (reader == null)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }
            byte[][] numArray1 = new byte[32][];
            int      length1   = 384;
            int      num1      = 0;
            int      length2   = 0;

            while (true)
            {
                byte[] buffer = new byte[length1];
                numArray1[num1++] = buffer;
                int index = 0;
                while (index < buffer.Length)
                {
                    int num2 = reader.ReadContentAsBase64(buffer, index, buffer.Length - index);
                    if (num2 != 0)
                    {
                        index += num2;
                    }
                    else
                    {
                        break;
                    }
                }
                if ((long)length2 <= maxBufferSize - (long)index)
                {
                    length2 += index;
                    if (index >= buffer.Length)
                    {
                        length1 *= 2;
                    }
                    else
                    {
                        goto label_11;
                    }
                }
                else
                {
                    break;
                }
            }
            throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError((Exception) new QuotaExceededException(SR.GetString("BufferQuotaExceededReadingBase64", new object[1] {
                (object)maxBufferSize
            })));
label_11:
            byte[] numArray2 = new byte[length2];
            int    dstOffset = 0;

            for (int index = 0; index < num1 - 1; ++index)
            {
                Buffer.BlockCopy((Array)numArray1[index], 0, (Array)numArray2, dstOffset, numArray1[index].Length);
                dstOffset += numArray1[index].Length;
            }
            Buffer.BlockCopy((Array)numArray1[num1 - 1], 0, (Array)numArray2, dstOffset, length2 - dstOffset);
            return(numArray2);
        }
예제 #16
0
파일: Drain.cs 프로젝트: tonyli71/qpid
        private static string MessageContentAsString(Message msg, AmqpProperties props)
        {
            // AmqpBinaryBinding provides message content as a single XML "Binary" element
            XmlDictionaryReader reader = msg.GetReaderAtBodyContents();

            while (!reader.HasValue)
            {
                reader.Read();
                if (reader.EOF)
                {
                    throw new InvalidDataException("empty reader for message");
                }
            }

            byte[] rawdata = reader.ReadContentAsBase64();

            string ct = props.ContentType;

            if (ct != null)
            {
                if (ct.Equals("amqp/map"))
                {
                    return("mapdata (coming soon)");
                }
            }

            return(Encoding.UTF8.GetString(rawdata));
        }
예제 #17
0
        /// <summary>
        /// Enables inspection or modification of a message after a reply message is received but prior to passing it back to the client application.
        /// </summary>
        /// <param name="reply">The message to be transformed into types and handed back to the client application.</param>
        /// <param name="correlationState">Correlation state data.</param>
        public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            HttpResponseMessageProperty property = null;

            if (reply.Properties.ContainsKey(HttpResponseMessageProperty.Name))
            {
                property = (reply.Properties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty);
            }
            if (property != null)
            {
                var errorStatus = property.Headers[NewtonsoftJsonErrorHandler.ClientHeader];
                if (errorStatus != null)
                {
                    XmlDictionaryReader            bodyReader = reply.GetReaderAtBodyContents();
                    Newtonsoft.Json.JsonSerializer serializer = endpoint.NewtonsoftSettings().JsonSerializer;
                    bodyReader.ReadStartElement("Binary");
                    byte[] body = bodyReader.ReadContentAsBase64();
                    using (MemoryStream ms = new MemoryStream(body)) {
                        using (StreamReader sr = new StreamReader(ms)) {
                            var result = (CommonFault)serializer.Deserialize(sr, typeof(CommonFault));
                            throw new FaultException <CommonFault>(result, result.Error);
                        }
                    }
                }
            }
        }
예제 #18
0
        public static string ReadRawBody(ref Message message)
        {
            XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();

            bodyReader.ReadStartElement("Binary");
            byte[] bodyBytes   = bodyReader.ReadContentAsBase64();
            string messageBody = Encoding.UTF8.GetString(bodyBytes);

            // Now to recreate the message
            MemoryStream        ms     = new MemoryStream();
            XmlDictionaryWriter writer = XmlDictionaryWriter.CreateBinaryWriter(ms);

            writer.WriteStartElement("Binary");
            writer.WriteBase64(bodyBytes, 0, bodyBytes.Length);
            writer.WriteEndElement();
            writer.Flush();
            ms.Position = 0;
            XmlDictionaryReader reader     = XmlDictionaryReader.CreateBinaryReader(ms, XmlDictionaryReaderQuotas.Max);
            Message             newMessage = Message.CreateMessage(reader, int.MaxValue, message.Version);

            newMessage.Properties.CopyProperties(message.Properties);
            message = newMessage;

            return(messageBody);
        }
        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            if (reply == null)
            {
                throw new ArgumentNullException("reply");
            }

            if (correlationState != null && correlationState is string)
            {
                // if we have a JSONP callback then buffer the response, wrap it with the callback call and then re-create the response message
                string callback = (string)correlationState;

                XmlDictionaryReader reader = reply.GetReaderAtBodyContents();
                reader.ReadStartElement();
                string content = JSONPSupportInspector.encoding.GetString(reader.ReadContentAsBase64());

                content = callback + "(" + content + ");";

                using (Message newreply = Message.CreateMessage(MessageVersion.None, "", new Writer(content)))
                {
                    newreply.Properties.CopyProperties(reply.Properties);

                    reply = newreply;

                    // change response content type to text/javascript if the JSON (only done when wrapped in a callback)
                    var replyProperties = (HttpResponseMessageProperty)reply.Properties[HttpResponseMessageProperty.Name];
                    replyProperties.Headers["Content-Type"] = replyProperties.Headers["Content-Type"].Replace("application/json", "text/javascript");
                }
            }
        }
예제 #20
0
        /// <summary>
        /// Reads the raw body.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <returns></returns>
        private string ReadRawBody(Message message)
        {
            XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();

            bodyReader.ReadStartElement("Binary");
            return(Encoding.UTF8.GetString(bodyReader.ReadContentAsBase64()));
        }
예제 #21
0
        public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName)
        {
            reader.ReadStartElement("Data");
            var data = reader.ReadContentAsBase64();

            reader.ReadEndElement();
            return(DecodeObject(data));
        }
예제 #22
0
        /// <summary>
        /// Extracts the message body as a string
        /// </summary>
        /// <param name="msg">The message from which the body will be extracted</param>
        /// <returns>The bytes of the message body</returns>
        public static byte[] GetBodyAsBytes(Message msg)
        {
            XmlDictionaryReader xdr = msg.GetReaderAtBodyContents();

            xdr.ReadStartElement("MessageContent");

            return(xdr.ReadContentAsBase64());
        }
        public void DeserializeRequest(Message message, object[] parameters)
        {
            object bodyFormatProperty;

            if (!message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out bodyFormatProperty) ||
                (bodyFormatProperty as WebBodyFormatMessageProperty).Format != WebContentFormat.Raw)
            {
                throw new InvalidOperationException("Incoming messages must have a body format of Raw. Is a ContentTypeMapper set on the WebHttpBinding?");
            }

            XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();

            bodyReader.ReadStartElement("Binary");
            byte[]       rawBody = bodyReader.ReadContentAsBase64();
            MemoryStream ms      = new MemoryStream(rawBody);

            StreamReader sr = new StreamReader(ms);

            Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
            if (parameters.Length == 1)
            {
                // single parameter, assuming bare
                parameters[0] = serializer.Deserialize(sr, operation.Messages[0].Body.Parts[0].Type);
            }
            else
            {
                // multiple parameter, needs to be wrapped
                Newtonsoft.Json.JsonReader reader = new Newtonsoft.Json.JsonTextReader(sr);
                reader.Read();
                if (reader.TokenType != Newtonsoft.Json.JsonToken.StartObject)
                {
                    throw new InvalidOperationException("Input needs to be wrapped in an object");
                }

                reader.Read();
                while (reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName)
                {
                    string parameterName = reader.Value as string;
                    reader.Read();
                    if (this.parameterNames.ContainsKey(parameterName))
                    {
                        int parameterIndex = this.parameterNames[parameterName];
                        parameters[parameterIndex] = serializer.Deserialize(reader, this.operation.Messages[0].Body.Parts[parameterIndex].Type);
                    }
                    else
                    {
                        reader.Skip();
                    }

                    reader.Read();
                }

                reader.Close();
            }

            sr.Close();
            ms.Close();
        }
        private MockMessage PrepareMockMessage(System.ServiceModel.Channels.Message message)
        {
            byte[] msgBuffer = null;

            if (!message.IsFault)
            {
                // Handling regular content messages
                System.Diagnostics.Debug.WriteLine(
                    "Handling content response message",
                    "TransMock.Wcf.Adapter.MockAdapterInboundReply");

                XmlDictionaryReader xdr = message.GetReaderAtBodyContents();

                // Read the start element and extract its contents as a base64 encoded bytes
                if (xdr.NodeType == XmlNodeType.Element)
                {
                    // in case the content is nested in an element under the Body element
                    xdr.Read();
                }

                msgBuffer = xdr.ReadContentAsBase64();
            }
            else
            {
                // Handling faults returned by BizTalk
                System.Diagnostics.Debug.WriteLine(
                    "Handling fault response message",
                    "TransMock.Wcf.Adapter.MockAdapterInboundReply");
                using (var messageBuffer = message.CreateBufferedCopy(1024 ^ 3)) // Allowing for buffer of 1 GB
                {
                    using (var msgStream = new System.IO.MemoryStream(4096))
                    {
                        messageBuffer.WriteMessage(msgStream);

                        msgBuffer = Convert.FromBase64String(
                            Convert.ToBase64String(msgStream.ToArray()));
                    }
                }
            }

            if (msgBuffer.Length == 0)
            {
                // Message is with empty body, simply return
                System.Diagnostics.Debug.WriteLine(
                    "Response message has empty body. Exiting.",
                    "TransMock.Wcf.Adapter.MockAdapterInboundReply");

                return(null);
            }

            // Create MockMessage intance
            var mockMessage = new MockMessage(
                msgBuffer,
                this.encoding);

            return(mockMessage);
        }
예제 #25
0
        public static ClaimSet DeserializeClaimSet(XmlDictionaryReader reader, SctClaimDictionary dictionary, XmlObjectSerializer serializer, XmlObjectSerializer claimSerializer)
        {
            if (reader.IsStartElement(dictionary.NullValue, dictionary.EmptyString))
            {
                reader.ReadElementString();
                return(null);
            }
            else if (reader.IsStartElement(dictionary.X509CertificateClaimSet, dictionary.EmptyString))
            {
                reader.ReadStartElement();
                byte[] rawData = reader.ReadContentAsBase64();
                reader.ReadEndElement();
                return(new X509CertificateClaimSet(new X509Certificate2(rawData), false));
            }
            else if (reader.IsStartElement(dictionary.SystemClaimSet, dictionary.EmptyString))
            {
                reader.ReadElementString();
                return(ClaimSet.System);
            }
            else if (reader.IsStartElement(dictionary.WindowsClaimSet, dictionary.EmptyString))
            {
                reader.ReadElementString();
                return(ClaimSet.Windows);
            }
            else if (reader.IsStartElement(dictionary.AnonymousClaimSet, dictionary.EmptyString))
            {
                reader.ReadElementString();
                return(ClaimSet.Anonymous);
            }
            else if (reader.IsStartElement(dictionary.ClaimSet, dictionary.EmptyString))
            {
                ClaimSet     issuer = null;
                List <Claim> claims = new List <Claim>();
                reader.ReadStartElement();

                if (reader.IsStartElement(dictionary.PrimaryIssuer, dictionary.EmptyString))
                {
                    reader.ReadStartElement();
                    issuer = DeserializeClaimSet(reader, dictionary, serializer, claimSerializer);
                    reader.ReadEndElement();
                }

                while (reader.IsStartElement())
                {
                    reader.ReadStartElement();
                    claims.Add(DeserializeClaim(reader, dictionary, claimSerializer));
                    reader.ReadEndElement();
                }

                reader.ReadEndElement();
                return(issuer != null ? new DefaultClaimSet(issuer, claims) : new DefaultClaimSet(claims));
            }
            else
            {
                return((ClaimSet)serializer.ReadObject(reader));
            }
        }
    // This is the method to action after receiving a response from Sabre
    public void AfterReceiveReply(ref Message reply, object correlationState)
    {
        try
        {
            // Get compressed response from reply and load that into a byte array.
            XmlDictionaryReader bodyReader = reply.GetReaderAtBodyContents();
            bodyReader.ReadStartElement("CompressedResponse");
            byte[] bodyByteArray = bodyReader.ReadContentAsBase64();

            // Create some helper variables
            StringBuilder uncompressed = new StringBuilder();
            String        xmlString    = "";
            XmlDocument   xmlPayload   = new XmlDocument();

            // Load the byte array into memory
            using (MemoryStream memoryStream = new MemoryStream(bodyByteArray))
            {
                // Unzip the Stream
                using (GZipStream gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
                {
                    byte[] buffer = new byte[1024];
                    int    readBytes;

                    // Unzips character by character
                    while ((readBytes = gZipStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        for (int i = 0; i < readBytes; i++)
                        {
                            // Append all characters to build the response
                            uncompressed.Append((char)buffer[i]);
                        }
                    }
                }

                xmlString = uncompressed.ToString();
                xmlString = xmlString.Replace("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>", "");
            }

            // Convert the string into an XML
            xmlPayload.LoadXml(xmlString);

            // Create a new Message, which is what will substitute what was returned by Sabre
            Message tempMessage = Message.CreateMessage(reply.Version, null, xmlPayload.ChildNodes[0]);

            tempMessage.Headers.CopyHeadersFrom(reply.Headers);
            tempMessage.Properties.CopyProperties(reply.Properties);

            MessageBuffer bufferOfFault = tempMessage.CreateBufferedCopy(Int32.MaxValue);

            // Replace the reply with the new Message
            reply = bufferOfFault.CreateMessage();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            if (correlationState != null)
            {
                MessageInfo messageInfo = correlationState as MessageInfo;
                if (messageInfo != null)
                {
                    messageInfo.ServerEndTimeStamp = DateTime.Now;

                    MessageBuffer mb          = reply.CreateBufferedCopy(int.MaxValue);
                    Message       responseMsg = mb.CreateMessage();
                    reply = mb.CreateMessage();

                    XmlDictionaryReader bodyReader = responseMsg.GetReaderAtBodyContents();
                    if (bodyReader.IsStartElement("Binary"))
                    {
                        bodyReader.ReadStartElement("Binary");
                        byte[] bodyBytes = bodyReader.ReadContentAsBase64();
                        messageInfo.Response = Encoding.UTF8.GetString(bodyBytes);
                    }
                    else
                    {
                        messageInfo.Response = bodyReader.ReadOuterXml();
                    }

                    if (reply.IsFault)
                    {
                        messageInfo.IsError = true;
                    }

                    if (messageInfo.Response.Contains("<Binary>"))
                    {
                    }

                    string message = String.Format("Response => {0} {1}", messageInfo.ServerEndTimeStamp.ToString(CultureInfo.InvariantCulture), messageInfo.Response);
                    if (IsDisplayConsole)
                    {
                        Console.WriteLine(message);
                    }

                    if (IsLogFile)
                    {
                        _logger.Log(LogLevel.Info, message);
                    }
                }

                if (OnMessage != null)
                {
                    OnMessage(this, new MessageInspectorArgs
                    {
                        MessageInspectionType = MessageInspectionType.Response,
                        Message = messageInfo
                    });
                }
            }
        }
예제 #28
0
        /// <summary>
        /// Extracts the message body as a string
        /// </summary>
        /// <param name="msg">The message from which the body will be extracted</param>
        /// <param name="encoding">The encoding in which the body is expected to be</param>
        /// <returns>The message body in string representation</returns>
        public static string GetResponseBodyAsString(Message msg, Encoding encoding)
        {
            XmlDictionaryReader xdr = msg.GetReaderAtBodyContents();

            xdr.ReadStartElement("MessageContent");

            byte[] bodyBytes = xdr.ReadContentAsBase64();

            return(encoding.GetString(bodyBytes, 0, bodyBytes.Length - 2));
        }
예제 #29
0
        public byte[] GetBytes(Message message, byte[] recyclableBuffer)
        {
            XmlDictionaryReader reader = message.GetReaderAtBodyContents();
            int length;

            while (!reader.HasValue)
            {
                reader.Read();
                if (reader.EOF)
                {
                    throw new InvalidDataException("empty XmlDictionaryReader");
                }
            }

            if (reader.TryGetBase64ContentLength(out length))
            {
                byte[] bytes = null;
                if (recyclableBuffer != null)
                {
                    if (recyclableBuffer.Length == length)
                    {
                        // reuse
                        bytes = recyclableBuffer;
                    }
                }

                if (bytes == null)
                {
                    bytes = new byte[length];
                }

                // this is the single copy mechanism from native to managed space with no intervening
                // buffers.  One could also write a method GetBytes(msg, myBuf, offset)...
                reader.ReadContentAsBase64(bytes, 0, length);
                reader.Close();
                return(bytes);
            }
            else
            {
                // uses whatever default buffering mechanism is used by the base XmlDictionaryReader class
                return(reader.ReadContentAsBase64());
            }
        }
 public BinaryBodyReader(XmlDictionaryReader reader)
 {
     reader.ReadStartElement(BinaryElementName);
     _data = reader.ReadContentAsBase64();
     if (reader.NodeType == XmlNodeType.Text)
     {
         reader.Read();
     }
     reader.ReadEndElement();
 }