/// <summary>
        /// Wraps the resulting content into a JSONP callback function 
        /// extracted on the AfterReceiveReply message.
        /// </summary>
        /// <param name="reply">Outgoing response message.</param>
        /// <param name="correlationState">Correlation state returned by the AfterReceiveReply method.</param>
        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            if (correlationState == null || !(correlationState is string))
                return;

            // If we have a JSONP callback then buffer the response, wrap it with the
            // callback call and then re-create the response message
            var callback = (string)correlationState;

            var reader = reply.GetReaderAtBodyContents();
            reader.ReadStartElement();

            var content = Encoding.UTF8.GetString(reader.ReadContentAsBase64());
            content = string.Format(CultureInfo.InvariantCulture, "{0}({1});", callback, content);

            var newReply = Message.CreateMessage(MessageVersion.None, string.Empty, new JsonBodyWriter(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");
        }
Ejemplo n.º 2
0
        private void IntroduceErrorToMessage(ref Message message)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(message.GetReaderAtBodyContents());

            XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable);
            nsManager.AddNamespace("tempuri", "http://tempuri.org/");
            XmlElement xNode = doc.SelectSingleNode("//tempuri:x", nsManager) as XmlElement;
            XmlText xValue = xNode.FirstChild as XmlText;
            xValue.Value = (double.Parse(xValue.Value, CultureInfo.InvariantCulture) + 1).ToString(CultureInfo.InvariantCulture);

            MemoryStream ms = new MemoryStream();
            XmlWriterSettings writerSettings = new XmlWriterSettings
            {
                CloseOutput = false,
                OmitXmlDeclaration = true,
                Encoding = Encoding.UTF8,
            };

            XmlWriter writer = XmlWriter.Create(ms, writerSettings);
            doc.WriteTo(writer);
            writer.Close();
            ms.Position = 0;
            XmlReader reader = XmlReader.Create(ms);

            Message newMessage = Message.CreateMessage(message.Version, null, reader);
            newMessage.Headers.CopyHeadersFrom(message);
            newMessage.Properties.CopyProperties(message.Properties);
            message.Close();
            message = newMessage;
        }
        protected void DeserializeRequestInternal(Message message, object[] parameters)
        {
            var provider = ObjectBuilder.GetModelProvider();

            var serializer = ObjectBuilder.GetSerializer();

            var compressionType = GetMessageCompressionTypeOptions(message);

            CompressionProvider compressionProvider = null;
            if (compressionType != CompressionTypeOptions.None)
                compressionProvider = new CompressionProvider();

            var reader = message.GetReaderAtBodyContents();

            reader.Read();

            for (var i = 0; i < parameters.Length; i++)
            {
                var model = provider.CreateModelInfo(ParameterTypes[i].Type);

                reader.Read();

                var val = reader.Value;

                var data = BinaryConverter.FromString(val);

                if (compressionProvider != null)
                {
                    data = compressionProvider.DeCompress(data, compressionType);
                }

                object retVal;
                try
                {
                    retVal = serializer.Deserialize(data, model.MetaData, ParameterTypes[i].Type);
                }
                catch (SerializationException)
                {
                    throw FaultException.CreateFault(
                        MessageFault.CreateFault(
                        new FaultCode(Constants.SerializationFaultCode.ToString(CultureInfo.InvariantCulture)),
                                                 "Serialization failed, meta data removal is recommended."));
                }

                parameters[i] = retVal;
            }
        }
Ejemplo n.º 4
0
        //The Sum operation operates on the WCF Message object directly
        public Message Sum(Message request)
		{
			int sum = 0;
			string text = "";

            //The body of the message contains a list of numbers which will be read directly using an XmlReader
            System.Xml.XmlReader body = request.GetReaderAtBodyContents();

			while (body.Read())
			{
				text = body.ReadString().Trim();
				if (text.Length > 0)
				{
					sum += Convert.ToInt32(text,CultureInfo.InvariantCulture);
				}
			}
			body.Close();

            Message response = Message.CreateMessage(request.Version, "http://Microsoft.Samples.XmlReader/ICalculator/SumResponse", sum);
			return response;
		
		}
Ejemplo n.º 5
0
			public virtual object DeserializeReply (Message message, object [] parameters)
			{
				if (parameters == null)
					throw new ArgumentNullException ("parameters");
				CheckMessageVersion (message.Version);

				string pname = WebBodyFormatMessageProperty.Name;
				if (!message.Properties.ContainsKey (pname))
					throw new SystemException ("INTERNAL ERROR: it expects WebBodyFormatMessageProperty existence");
				var wp = (WebBodyFormatMessageProperty) message.Properties [pname];

				var serializer = GetSerializer (wp.Format);

				// FIXME: handle ref/out parameters

				var md = GetMessageDescription (MessageDirection.Output);

				var reader = message.GetReaderAtBodyContents ();

				if (IsResponseBodyWrapped) {
					if (wp.Format == WebContentFormat.Json)
						reader.ReadStartElement ("root", String.Empty); // note that the wrapper name is passed to the serializer.
					else
						reader.ReadStartElement (md.Body.WrapperName, md.Body.WrapperNamespace);
				}

#if NET_2_1
				var ret = (serializer is DataContractJsonSerializer) ?
					((DataContractJsonSerializer) serializer).ReadObject (reader) :
					((DataContractSerializer) serializer).ReadObject (reader, true);
#else
				var ret = serializer.ReadObject (reader, true);
#endif

				if (IsResponseBodyWrapped)
					reader.ReadEndElement ();

				return ret;
			}
Ejemplo n.º 6
0
		protected object DeserializeObject (XmlObjectSerializer serializer, Message message, MessageDescription md, bool isWrapped, WebContentFormat fmt)
		{
			// FIXME: handle ref/out parameters

			var reader = message.GetReaderAtBodyContents ();
			reader.MoveToContent ();

			bool wasEmptyElement = reader.IsEmptyElement;

			if (isWrapped) {
				if (fmt == WebContentFormat.Json)
					reader.ReadStartElement ("root", String.Empty); // note that the wrapper name is passed to the serializer.
				else
					reader.ReadStartElement (md.Body.WrapperName, md.Body.WrapperNamespace);
			}

			var ret = (serializer == null) ? null : ReadObjectBody (serializer, reader);

			if (isWrapped && !wasEmptyElement)
				reader.ReadEndElement ();

			return ret;
		}
        protected object DeserializeReplyInternal(Message message, object[] parameters)
        {
            var retParamInfo = ParameterTypes.FirstOrDefault(x => x.ParamType == ParamType.Return);

            if (retParamInfo == null)
                return null;

            var store = ObjectBuilder.GetModelStore();

            var serializer = ObjectBuilder.GetSerializer();
            
            var reader = message.GetReaderAtBodyContents();

            reader.Read();

            var model = store.GetModel(retParamInfo.Type);

            if (model == null)
                throw new InvalidOperationException("The model cannot be null, meta data fetch failed. Type: " + retParamInfo.Type.FullName);

            reader.Read();

            var val = reader.Value;

            var data = BinaryConverter.FromString(val);

            var compressionType = GetMessageCompressionTypeOptions(message);

            if (compressionType != CompressionTypeOptions.None)
            {
                var compressionProvider = new CompressionProvider();

                data = compressionProvider.DeCompress(data, compressionType);
            }

            object retVal;
            try
            {
                retVal = serializer.Deserialize(data, model.MetaData, retParamInfo.Type);
            }
            catch (SerializationException)
            {
                store.RemoveModel(retParamInfo.Type);

                throw;
            }
            return retVal;
        }
 public override void AfterReceiveReply(ref Message reply, object correlationState)
 {
     bool callBase = true;
     if (reply != null)
     {
         object responseProperty = reply.Properties[HttpResponseMessageProperty.Name];
         if (responseProperty != null)
         {
             if (((HttpResponseMessageProperty)responseProperty).Headers[JsonGlobals.jsonerrorString] == JsonGlobals.trueString)
             {
                 callBase = false;
                 XmlDictionaryReader reader = reply.GetReaderAtBodyContents();
                 JsonFaultDetail faultDetail = jsonFaultSerializer.ReadObject(reader) as JsonFaultDetail;
                 FaultCode faultCode = new FaultCode(FaultCodeConstants.Codes.InternalServiceFault, FaultCodeConstants.Namespaces.NetDispatch);
                 faultCode = FaultCode.CreateReceiverFaultCode(faultCode);
                 if (faultDetail != null)
                 {
                     if (faultDetail.ExceptionDetail != null)
                     {
                         throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                             new FaultException<ExceptionDetail>(faultDetail.ExceptionDetail, faultDetail.Message, faultCode));
                     }
                     else
                     {
                         throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                             new FaultException(MessageFault.CreateFault(faultCode, faultDetail.Message)));
                     }
                 }
                 else
                 {
                     throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                         new FaultException(MessageFault.CreateFault(faultCode,
                         System.ServiceModel.SR.GetString(System.ServiceModel.SR.SFxInternalServerError))));
                 }
             }
         }
     }
     if (callBase)
     {
         base.AfterReceiveReply(ref reply, correlationState);
     }
 }
        /// <summary>
        /// Extracts the service query and original message body from <paramref name="message"/> .
        /// May create a new message with the original body contents.
        /// </summary>
        /// <param name="message">The message to use for deserialization.</param>
        /// <returns>The extracted service query.</returns>
        /// <remarks>The message passed in will not be disposed. This message belongs to the
        /// caller.</remarks>
        internal static ServiceQuery GetServiceQuery(ref Message message)
        {
            ServiceQuery serviceQuery = null;
            if (!message.IsEmpty)
            {
                XmlDictionaryReader reader = message.GetReaderAtBodyContents();
                // If the message root is not <MessageRoot> then the message does not contain QueryOptions.
                // So re-write the stream back to a message.
                if (reader.IsStartElement(MessageUtility.MessageRootElementName))
                {
                    // Go to the <QueryOptions> node.
                    reader.Read();                                                              // <MessageRoot>
                    reader.ReadStartElement(MessageUtility.QueryOptionsListElementName);        // <QueryOptions>
                    serviceQuery = MessageUtility.ReadServiceQuery(reader);                     // <QueryOption></QueryOption>
                    // Go to the starting node of the original message.
                    reader.ReadEndElement();                                                    // </QueryOptions>
                    reader = XmlDictionaryReader.CreateDictionaryReader(reader.ReadSubtree());  // Remainder of the message
                }

                // Note: we must use this overload to get a streamed message. This incurs the least
                // cost on GetReaderAtBodyContents which is the most expensive call in this path.
                // Note: We do not care about the new message enforcing the max size of headers
                // since it has already been enforced with the old message.
                Message newMessage = Message.CreateMessage(reader, Int32.MaxValue, message.Version);
                newMessage.Headers.CopyHeadersFrom(message);
                newMessage.Properties.CopyProperties(message.Properties);
                message = newMessage;
            }
            return serviceQuery;
        }
            internal Message MarshalMessage(Message source, Uri to, MessageVersion targetVersion)
            {
                Message result;
                MessageHeaders sourceHeaders = source.Headers;
                MessageVersion sourceVersion = source.Version;
                UnderstoodHeaders understoodHeaders = sourceHeaders.UnderstoodHeaders;
                HashSet<string> understoodHeadersSet = CreateKeys(understoodHeaders);

#if DEBUG_MARSHALING
                System.Text.StringBuilder details = new System.Text.StringBuilder();
                details.AppendFormat("Original Message:\r\n{0}\r\n", source);
                details.AppendLine("Understood Headers:");
                foreach (MessageHeaderInfo understoodHeader in understoodHeaders)
                {
                    details.AppendFormat("\t{0}\t({1})\r\n", understoodHeader.Name, understoodHeader.Namespace);
                }
                details.AppendLine("Properties:");
                foreach (KeyValuePair<string, object> item in source.Properties)
                {
                    details.AppendFormat("\t{0}\t({1})\r\n", item.Key, item.Value);
                }
#endif //DEBUG_MARSHALING


                //if we've understood and verified the security of the message, we need to create a new message
                if (sourceVersion == targetVersion && !RoutingUtilities.IsMessageUsingWSSecurity(understoodHeaders))
                {
                    FilterHeaders(sourceHeaders, understoodHeadersSet);
                    FilterProperties(source.Properties);
                    result = source;
                }
                else
                {
                    if (source.IsFault)
                    {
                        MessageFault messageFault = MessageFault.CreateFault(source, int.MaxValue);
                        string action = sourceHeaders.Action;
                        if (string.Equals(action, sourceVersion.Addressing.DefaultFaultAction, StringComparison.Ordinal))
                        {
                            //The action was the default for the sourceVersion set it to the default for the targetVersion.
                            action = targetVersion.Addressing.DefaultFaultAction;
                        }
                        result = Message.CreateMessage(targetVersion, messageFault, action);
                    }
                    else if (source.IsEmpty)
                    {
                        result = Message.CreateMessage(targetVersion, sourceHeaders.Action);
                    }
                    else
                    {
                        XmlDictionaryReader bodyReader = source.GetReaderAtBodyContents();
                        result = Message.CreateMessage(targetVersion, sourceHeaders.Action, bodyReader);
                    }

                    CloneHeaders(result.Headers, sourceHeaders, to, understoodHeadersSet);
                    CloneProperties(result.Properties, source.Properties);
                }

#if DEBUG_MARSHALING
                details.AppendFormat("\r\nMarshaled Message:\r\n{0}\r\n", result);
                details.AppendLine("Properties:");
                foreach (KeyValuePair<string, object> item in result.Properties)
                {
                    details.AppendFormat("\t{0}\t({1})\r\n", item.Key, item.Value);
                }
                System.Diagnostics.Trace.WriteLine(details);
                TD.RoutingServiceDisplayConfig(details.ToString(), "");
#endif //DEBUG_MARSHALING

                return result;
            }