Ejemplo n.º 1
0
        /// <summary>
        /// Deserializes message contract input parameters.
        /// </summary>
        /// <param name="messageBuffer">The buffer containing the message to be deserialized.</param>
        /// <param name="proxyNamespace">The namespace of the proxy.</param>
        /// <param name="parameter">The parameter to be deserialized.</param>
        /// <returns>Deserialized input parameter.</returns>
        private static CallParameterInfo DeserializeMessageContractInputParameters(MessageBuffer messageBuffer, string proxyNamespace, ParameterInfo parameter)
        {
            Message message = messageBuffer.CreateMessage();
            TypedMessageConverter converter = TypedMessageConverter.Create(parameter.ParameterType, message.Headers.Action, proxyNamespace);
            object o;

            try
            {
                o = converter.FromMessage(message);
            }
            catch (System.Xml.XmlException)
            {
                o = Activator.CreateInstance(parameter.ParameterType);
            }
            catch (System.Runtime.Serialization.SerializationException)
            {
                o = Activator.CreateInstance(parameter.ParameterType);
            }
            catch (CommunicationException)
            {
                o = Activator.CreateInstance(parameter.ParameterType);
            }

            return(new CallParameterInfo(parameter.Name, parameter.ParameterType, FieldDirection.In, o));
        }
Ejemplo n.º 2
0
                private void HttpGetResponseThread()
                {
                    try
                    {
                        // List<IAsyncResult> results = new List<IAsyncResult>();
                        bool isEOM = false;

                        // ProcessResponseDelegate p = ProcessResponses;
                        int responseCount = 0;

                        // while (!isEOM)
                        // {
                        SessionBase.TraceSource.TraceInformation("Begin PullResponse : count {0} : clientId {1}", this.count, this.clientId);
                        BrokerResponseMessages responseMessages = this.controller.PullResponses(this.action, this.resetToBegin, this.count, this.clientId);
                        SessionBase.TraceSource.TraceInformation("End PullResponse : count {0} : isEOM {1}", responseMessages.SOAPMessage.Length, responseMessages.EOM);

                        // responseCount += responseMessages.SOAPMessage.Length;
                        responseCount = responseMessages.SOAPMessage.Length;

                        // results.Add(p.BeginInvoke(responseMessages, clientData, null, null));
                        this.ProcessResponses(responseMessages, this.clientData);
                        Interlocked.Add(ref this.responseClient.totalResponseCount, responseCount);
                        isEOM = responseMessages.EOM;

                        if (isEOM)
                        {
                            // construct endofreponses message
                            TypedMessageConverter converter      = TypedMessageConverter.Create(typeof(EndOfResponses), Constant.EndOfMessageAction);
                            EndOfResponses        endOfResponses = new EndOfResponses();
                            endOfResponses.Count  = this.responseClient.totalResponseCount;
                            endOfResponses.Reason = EndOfResponsesReason.Success;
                            Message eom = converter.ToMessage(endOfResponses, MessageVersion.Soap11);
                            eom.Headers.Add(MessageHeader.CreateHeader(Constant.ResponseCallbackIdHeaderName, Constant.ResponseCallbackIdHeaderNS, this.clientData));

                            this.callback.SendResponse(eom);
                        }
                    }
                    catch (Exception e)
                    {
                        SessionBase.TraceSource.TraceInformation("PullResponse Exception: {0}", e.ToString());

                        if (this.disposeFlag)
                        {
                            return;
                        }

                        Message exceptionMessage = Message.CreateMessage(MessageVersion.Soap11, @"http://hpc.microsoft.com/ClientSideExeption");
                        exceptionMessage.Headers.Add(MessageHeader.CreateHeader(Constant.ResponseCallbackIdHeaderName, Constant.ResponseCallbackIdHeaderNS, this.clientData));
                        exceptionMessage.Properties.Add(@"HttpClientException", e);

                        this.callback.SendResponse(exceptionMessage);
                    }
                    finally
                    {
                        if (this.Completed != null)
                        {
                            this.Completed(this, EventArgs.Empty);
                        }
                    }
                }
Ejemplo n.º 3
0
        // It is imported from samples/typed-message-converter.
        public void StandardToMessage()
        {
            TypedMessageConverter c = TypedMessageConverter.Create(
                typeof(Test1), "http://tempuri.org/MyTest");
            Message msg = c.ToMessage(new Test1());

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(msg.ToString());

            XmlNamespaceManager nss = new XmlNamespaceManager(doc.NameTable);

            nss.AddNamespace("s", "http://www.w3.org/2003/05/soap-envelope");
            nss.AddNamespace("t", "http://tempuri.org/");
            nss.AddNamespace("v", "space");
            nss.AddNamespace("w", "yy1");
            XmlElement el = doc.SelectSingleNode("/s:Envelope/s:Body/v:MyName", nss) as XmlElement;

            Assert.IsNotNull(el, "#1");
            XmlNode part = el.SelectSingleNode("t:body2", nss);

            Assert.IsNotNull(part, "#2");
            Assert.AreEqual("TEST body", part.InnerText, "#3");
            Assert.IsNotNull(el.SelectSingleNode("w:xx1", nss), "#4");
            part = el.SelectSingleNode("w:xx1/v:msg", nss);
            Assert.IsNotNull(part, "#5");
            Assert.AreEqual("default", part.InnerText, "#6");
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Initializes a new instance of the BrokerResponse class
 /// </summary>
 /// <param name="typedMessageConverter">Converts response message to its type</param>
 /// <param name="messageBuffer">Response message's buffer</param>
 /// <param name="faultCollection">indicating the fault collection</param>
 /// <param name="requestMessageId">indicating the request message id</param>
 internal BrokerResponse(TypedMessageConverter typedMessageConverter, MessageBuffer messageBuffer, FaultDescriptionCollection faultCollection, UniqueId requestMessageId)
     : this(requestMessageId)
 {
     this.typedMessageConverter = typedMessageConverter;
     this.messageBuffer         = messageBuffer;
     this.faultCollection       = faultCollection;
 }
Ejemplo n.º 5
0
        public Message Get(Message request)
        {
            MetadataMessage       metadataMessage = new MetadataMessage(this.Metadata);
            string                action          = "http://schemas.xmlsoap.org/ws/2004/09/transfer/GetResponse";
            TypedMessageConverter converter       = TypedMessageConverter.Create(typeof(MetadataMessage), action);

            return(converter.ToMessage(metadataMessage, request.Version));
        }
Ejemplo n.º 6
0
 static void Main(string[] args)
 {
     string                action     = null;
     XmlReader             bodyReader = XmlReader.Create(new StringReader("<Example xmlns=\"http://tempuri.org/\"><Gold>109</Gold><Message>StackOverflow</Message></Example>"));
     Message               msg        = Message.CreateMessage(MessageVersion.Default, action, bodyReader);
     TypedMessageConverter converter  = TypedMessageConverter.Create(typeof(Example), "http://tempuri.org/IFoo/BarOperation");
     Example               example    = (Example)converter.FromMessage(msg);
 }
Ejemplo n.º 7
0
        public static void GenerateMessage <T>(T typedMessage, string action, string ns, string filename)
        {
            TypedMessageConverter converter = TypedMessageConverter.Create(typeof(T), action, ns);

            using (Message message = converter.ToMessage(typedMessage)) {
                using (XmlWriter writer = new XmlTextWriter(filename, Encoding.UTF8))
                {
                    message.WriteMessage(writer);
                }
            }
        }
Ejemplo n.º 8
0
    public static void Main()
    {
        TypedMessageConverter c = TypedMessageConverter.Create(
            typeof(Test), "http://tempuri.org/MyTest");
        Message       msg = c.ToMessage(new Test());
        MessageBuffer mb  = msg.CreateBufferedCopy(10);

        using (XmlWriter w = XmlWriter.Create(Console.Out)) {
            mb.CreateMessage().WriteMessage(w);
        }
        Test t = (Test)c.FromMessage(mb.CreateMessage());
    }
Ejemplo n.º 9
0
    public static void Test()
    {
        TypedMessageConverter tmc = TypedMessageConverter.Create(typeof(MyMC), "Action");
        Message msg = tmc.ToMessage(new MyMC {
            MyMessage = "some string"
        }, MessageVersion.Soap11);

        Console.WriteLine(msg);     // message with the <MyMessage> element
        Console.WriteLine();
        msg = Message.CreateMessage(MessageVersion.Soap11, "Action", new MyBodyWriter());
        Console.WriteLine(msg);     // message without the <MyMessage> element
    }
Ejemplo n.º 10
0
        /// <summary>
        /// Use XmlSerializerUtils to serialize the request into XML.
        /// </summary>
        /// <param name="message">SoapMessage to serialize.</param>
        public static void SerializeRequest(SoapMessage message)
        {
            if (message.RequestBodyPayload == null)
            {
                message.RequestBodyPayloadText = string.Empty;
                return;
            }

            if (message.RequestBodyPayload is string)
            {
                message.RequestBodyPayloadText = message.RequestBodyPayload.ToString();
                return;
            }

            try
            {
                TypedMessageConverter converter = null;

                try
                {
                    //Serialize Tourico request type using TypedMessageConverter to get exactly the same XML format to POST
                    converter =
                        TypedMessageConverter.Create
                        (
                            message.RequestBodyPayload.GetType(),
                            null,                                               //Dont specify Action name here - Action would part of POST header
                            new XmlSerializerFormatAttribute()
                        );
                }
                catch (ArgumentException)
                {
                    Logger.Instance.Warn("TouricoMessageHelper", "SerializeRequest", "Unable to Serialize using TypedMessageConverter");
                }

                //Convert to XML representation
                string payloadString
                    = converter.ToMessage(message.RequestBodyPayload, MessageVersion.Soap11).ToString();

                //Parse payload
                var doc    = XDocument.Parse(payloadString);
                var result = doc.ToString();

                message.RequestBodyPayloadText = result;
            }
            catch (Exception ex)
            {
                Logger.Instance.Error("TouricoMessageHelper", "SerializeRequest", ex, "Unable to serialize request body.");
                throw;
            }
        }
Ejemplo n.º 11
0
        public void StandardRoundtrip()
        {
            TypedMessageConverter c = TypedMessageConverter.Create(
                typeof(Test1), "http://tempuri.org/MyTest");
            Test1 t1 = new Test1();

            t1.echo.msg = "test";
            t1.body2    = "testtest";
            Message msg = c.ToMessage(t1);
            Test1   t2  = (Test1)c.FromMessage(msg);

            Assert.AreEqual("test", t2.echo.msg, "#01");
            Assert.AreEqual("testtest", t2.body2, "#02");
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Initializes a new instance of the BrokerResponseEnumerator class
        /// </summary>
        /// <param name="responseService">Client the broker's response service</param>
        /// <param name="callbackManager">Manages all callbacks for the session</param>
        /// <param name="typedMessageConverter">Typed message convertor</param>
        /// <param name="newResponsesTimeout">Timeout waiting for responses</param>
        /// <param name="action">Action of the response messages</param>
        /// <param name="clientId">client id</param>
        internal BrokerResponseEnumerator(
            SessionBase session,
            IResponseService responseServiceClient,
            CallbackManager callbackManager,
            TimeSpan newResponsesTimeout,
            BrokerClientBase brokerClient,
            string clientId,
            string action,
            string replyAction)
        {
            Type responseType = typeof(TMessage);

            this.newResponsesTimeout     = newResponsesTimeout;
            this.callbackManager         = callbackManager;
            this.callbackManagerId       = this.callbackManager.Register(this);
            this.endOfResponsesConverter = TypedMessageConverter.Create(typeof(EndOfResponses), Constant.EndOfMessageAction);
            this.brokerClient            = brokerClient;
            this.clientId = clientId;
            this.session  = session;

            // If caller specified a responseType or both actions, make sure the type or the actions are valid before starting the enum by getting
            //  the deserialization objects now. Else the deseralization objects are retrieved dynamically based on response messages
            if ((typeof(TMessage) != typeof(object)) || (!string.IsNullOrEmpty(action) && !string.IsNullOrEmpty(replyAction)))
            {
                string errorMessage;

                // If replyAction isnt known, GetResponseMessageInfo will return it. This is used to track which response deserialization is currently cached in the enumerator
                if (!this.brokerClient.GetResponseMessageInfo(ref action, ref replyAction, ref responseType, out this.typedMessageConverter, out this.faultCollection, out errorMessage))
                {
                    throw new InvalidOperationException(errorMessage);
                }
            }

            this.action                     = action;
            this.replyAction                = replyAction;
            this.responseType               = responseType;
            this.responseServiceClient      = responseServiceClient;
            this.responseServiceAsyncClient = responseServiceClient as IResponseServiceAsync;
            this.flushResponsesTimer        = new Timer(this.FlushResponseTimerCallback, null, Timeout.Infinite, Timeout.Infinite);

            if (this.session.Info is SessionInfo && (this.session.Info as SessionInfo).UseAzureQueue == true)
            {
                this.GetMoreResponses(true, Constant.GetResponse_All);
            }
            else
            {
                this.GetMoreResponses(true, ResponseWindowSize * 2);
            }
        }
Ejemplo n.º 13
0
        T FromMessage <T> (Message input, bool isXml)
        {
            TypedMessageConverter tm;

            if (isXml)
            {
                tm = TypedMessageConverter.Create(typeof(T), input.Headers.Action,
                                                  new XmlSerializerFormatAttribute());
            }
            else
            {
                tm = TypedMessageConverter.Create(typeof(T), input.Headers.Action);
            }
            return((T)tm.FromMessage(input));
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Deserializes bare input parameters using the <see cref="XmlSerializer"/>.
        /// </summary>
        /// <param name="messageBuffer">The buffer containing the message to be deserialized.</param>
        /// <param name="proxyNamespace">The namespace of the proxy.</param>
        /// <param name="parameters">The parameters to be deserialized.</param>
        /// <returns>Deserialized input parameters.</returns>
        private static CallParameterInfo[] DeserializeXmlSerializerWithBareInputParameter(MessageBuffer messageBuffer, string proxyNamespace, ParameterInfo[] parameters)
        {
            Debug.Assert(parameters.Length == 1, "Expect only one parameter for bare XmlSerializer parameter");
            List <CallParameterInfo> ans = new List <CallParameterInfo>();

            Message message = messageBuffer.CreateMessage();

            foreach (ParameterInfo parameter in parameters)
            {
                TypedMessageConverter converter = TypedMessageConverter.Create(parameter.ParameterType, message.Headers.Action, proxyNamespace, new XmlSerializerFormatAttribute());
                object o = converter.FromMessage(message);
                ans.Add(new CallParameterInfo(parameter.Name, parameter.ParameterType, FieldDirection.In, o));
            }

            return(ans.ToArray());
        }
Ejemplo n.º 15
0
        Message ToMessage <T> (Message input, bool isXml, T val)
        {
            TypedMessageConverter tm;

            if (isXml)
            {
                tm = TypedMessageConverter.Create(typeof(T),
                                                  input.Headers.Action + "Response", new XmlSerializerFormatAttribute());
            }
            else
            {
                tm = TypedMessageConverter.Create(typeof(T),
                                                  input.Headers.Action + "Response");
            }
            return(tm.ToMessage(val, input.Version));
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Parses the response, parses body elements.
        /// </summary>
        /// <typeparam name="TRes"></typeparam>
        /// <param name="message"></param>
        public static void ParseResponse <TRes>(SoapMessage message)
        {
            Logger.Instance.LogFunctionEntry("TouricoMessageHelper", "ParseResponse");

            var touricoMessage = message as TouricoMessage;

            if (touricoMessage == null)
            {
                throw new InvalidCastException("Expected SabreMessage");
            }

            var doc = new XmlDocument();

            doc.LoadXml(message.RawResponseText);
            var nsMgr = new XmlNamespaceManager(doc.NameTable);

            nsMgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");

            //Body
            var bodyNode = doc.SelectSingleNode("//soap:Body", nsMgr);

            if (bodyNode != null)
            {
                //Try catch here to know if body is actual response or Fault
                XmlReader bodyReader = XmlReader.Create(new StringReader(bodyNode.InnerXml));
                Message   msg        = Message.CreateMessage(MessageVersion.Soap11, null, bodyReader);
                var       converter  = TypedMessageConverter.Create(typeof(TRes), null, new XmlSerializerFormatAttribute());
                touricoMessage.ResponseBodyPayload = (TRes)converter.FromMessage(msg);

                touricoMessage.ResponseBodyText = bodyNode.InnerXml;


                if (touricoMessage.ResponseBodyPayload == null)
                {
                    var fault = XmlSerializerUtil <WSFault> .Deserialize(touricoMessage.ResponseBodyText);

                    if (fault != null)
                    {
                        throw new TouricoProviderException(fault);
                    }

                    throw new Exception("ResponseBodyPayload is null.");
                }
            }
            Logger.Instance.LogFunctionExit("TouricoMessageHelper", "ParseResponse");
        }
        protected override Message ToMessageCore(MessageDelivery delivery)
        {
            if (!_converterHash.ContainsKey(delivery.Action))
            {
                throw new InvalidOperationException("Unsupported action");
            }

            TypedMessageConverter converter = getCachedConverter(delivery.Action);

            if (converter != null)
            {
                return(converter.ToMessage(delivery.Message));
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 18
0
        public void StandardRoundtrip2()
        {
            TypedMessageConverter c = TypedMessageConverter.Create(
                typeof(Test2), "http://tempuri.org/MyTest");
            var t1 = new Test2();

            t1.Body = new Echo()
            {
                msg = "test"
            };
            var uid = Guid.NewGuid();

            t1.Id = uid;
            Message msg = c.ToMessage(t1);
            var     t2  = (Test2)c.FromMessage(msg);

            Assert.AreEqual("test", t2.Body.msg, "#01");
            Assert.AreEqual(uid, t2.Id, "#02");
        }
Ejemplo n.º 19
0
        /// <summary>
        /// reply the end of message to the client.
        /// </summary>
        /// <param name="callback">the response service callback.</param>
        /// <param name="clientData">the client data.</param>
        /// <param name="clientPurged">indicating the client purged flag</param>
        private void ReplyEndOfMessage(IResponseServiceCallback callback, string clientData, EndOfResponsesReason reason)
        {
            if (this.callbackChannelDisposed)
            {
                return;
            }

            BrokerTracing.TraceInfo("[GetResponsesHandler] Client {0}: Send end of response, clientPurged = {1}", this.clientId, reason);
            this.ResetTimeout();
            TypedMessageConverter converter      = TypedMessageConverter.Create(typeof(EndOfResponses), Constant.EndOfMessageAction);
            EndOfResponses        endOfResponses = new EndOfResponses();

            endOfResponses.Count  = this.ResponsesCount;
            endOfResponses.Reason = reason;
            Message eom = converter.ToMessage(endOfResponses, this.Version);

            eom.Headers.Add(MessageHeader.CreateHeader(Constant.ResponseCallbackIdHeaderName, Constant.ResponseCallbackIdHeaderNS, clientData));
            this.eorReplied = true;
            try
            {
                if (callback is AzureQueueProxy)
                {
                    callback.SendResponse(eom, clientData);
                }
                else
                {
                    callback.SendResponse(eom);
                }
            }
            catch (ObjectDisposedException)
            {
                BrokerTracing.TraceEvent(System.Diagnostics.TraceEventType.Error, 0, "[BrokerClient] Client {0}: Send end of response error: communication object is disposed.", this.clientId);
                this.callbackChannelDisposed = true;
                this.Queue.ResetResponsesCallback();
            }
            catch (Exception ce)
            {
                BrokerTracing.TraceEvent(System.Diagnostics.TraceEventType.Error, 0, "[BrokerClient] Client {0}: Send end of response error: {1}", this.clientId, ce);

                // Swallow exception
            }
        }
Ejemplo n.º 20
0
        public void XmlSerializerdWithXmlAttribute()
        {
            TypedMessageConverter c = TypedMessageConverter.Create(
                typeof(Test3), "http://tempuri.org/MyTest",
                new XmlSerializerFormatAttribute());


            string xmlMessage = @"<s:Envelope xmlns:s='http://www.w3.org/2003/05/soap-envelope'
									xmlns:a='http://www.w3.org/2005/08/addressing'>
				<s:Header><a:Action s:mustUnderstand='1'>http://tempuri.org/MyTest</a:Action></s:Header>
				<s:Body xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
					<test xmlns='urn:foo'>
						<Id>OneID</Id>
						<Element>
							<Prop1 xmlns='urn:bar'>foo</Prop1>
							<Prop2 xmlns='urn:bar'>2</Prop2>
						</Element>
						<Element>
							<Prop1 xmlns='urn:bar'>bar</Prop1>
							<Prop2 xmlns='urn:bar'>3</Prop2>
						</Element>
					</test>
				</s:Body>
				</s:Envelope>"                ;

            byte[] buffer = Encoding.UTF8.GetBytes(xmlMessage);
            using (XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(buffer, XmlDictionaryReaderQuotas.Max))
            {
                Message messagedisk = Message.CreateMessage(reader, int.MaxValue, MessageVersion.Soap12);
                Test3   obj         = c.FromMessage(messagedisk) as Test3;
                Assert.IsNotNull(obj);
                Assert.AreEqual("OneID", obj.Id);
                Assert.IsNotNull(obj.ArrayOfElement);
                Assert.AreEqual(2, obj.ArrayOfElement.Length);
                Assert.AreEqual("foo", obj.ArrayOfElement[0].Prop1);
                Assert.AreEqual(3, obj.ArrayOfElement[1].Prop2);
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Dynamically creates objects needed to deserialize a response message. Keeps last deserializer since its likely it will be reused
        /// </summary>
        /// <param name="actionFromResponse">indicating the action from the response header</param>
        /// <param name="replyAction">indicating the reply action</param>
        /// <param name="messageBuffer">indicating the message buffer</param>
        /// <param name="relatesTo">indicating the relatesTo header</param>
        /// <returns>returns the created instance of BrokerResponse class</returns>
        private BrokerResponse <TMessage> CreateResponse(string actionFromResponse, string replyAction, MessageBuffer messageBuffer, UniqueId relatesTo)
        {
            TypedMessageConverter      typedMessageConverter = null;
            FaultDescriptionCollection faultCollection       = null;
            Type responseType = null;

            // If the actionFromResponse is empty, this is a broker fault. BrokerResponse can handle this with no app service specific information
            if (!String.IsNullOrEmpty(actionFromResponse))
            {
                // Check if we already have a response message converter & fault collection for this action. If not get it from the BrokerClient
                if (this.typedMessageConverter != null && this.replyAction == replyAction)
                {
                    typedMessageConverter = this.typedMessageConverter;
                    faultCollection       = this.faultCollection;
                    responseType          = this.responseType;
                }
                else
                {
                    string errorMessage = null;

                    // Get the deserialization objects from the BrokerClient
                    if (!this.brokerClient.GetResponseMessageInfo(ref actionFromResponse, ref replyAction, ref responseType,
                                                                  out typedMessageConverter, out faultCollection, out errorMessage))
                    {
                        throw new InvalidOperationException(errorMessage);
                    }

                    this.action                = actionFromResponse;
                    this.replyAction           = replyAction;
                    this.typedMessageConverter = typedMessageConverter;
                    this.faultCollection       = faultCollection;
                    this.responseType          = responseType;
                }
            }

            return(new BrokerResponse <TMessage>(this.typedMessageConverter, messageBuffer, this.faultCollection, relatesTo));
        }
        public void Bug666333()
        {
            // xml : original xml in the test
            // xml2 : when it is *appropriately* serialized
            // xml3 : mixed, d4p1:activeuser comes first
            // xml4 : mixed, d4p1:activeuser comes second
            // (Note that d4p1:activeuser is the actual element to be deserialized which takes precedence over urn:foo activeuser.)

            string xml = @"
				<CheckLoginResponse xmlns='http://tempuri.org/'>
					<playeractiveuser>
						<activeuser>
							<id>id</id>
							<hkey>hkey</hkey>
							<email>[email protected]</email>
							<lastcheck>2011-01-21T22:50:52.02</lastcheck>
						</activeuser>
						<response>
							<responsemessage>Acceso correcto, creado nuevo hkey!</responsemessage>
							<responsecode>1</responsecode>
							<langId>6</langId>
						</response>
					</playeractiveuser>
				</CheckLoginResponse>
				"                ;

            string xml2 = @"
<CheckLoginResponse xmlns='http://tempuri.org/'>
  <playeractiveuser xmlns:d4p1='http://schemas.datacontract.org/2004/07/' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>
    <d4p1:activeuser>
      <d4p1:email i:nil='true' />
      <d4p1:hkey i:nil='true' />
      <d4p1:id>idd</d4p1:id>
      <d4p1:lastcheck i:nil='true' />
    </d4p1:activeuser>
    <d4p1:response>
      <d4p1:langId i:nil='true' />
      <d4p1:responsecode>100</d4p1:responsecode>
      <d4p1:responsemessage i:nil='true' />
    </d4p1:response>
  </playeractiveuser>
</CheckLoginResponse>";

            string xml3 = @"
<CheckLoginResponse xmlns='http://tempuri.org/'>
  <playeractiveuser xmlns:d4p1='http://schemas.datacontract.org/2004/07/' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>
    <d4p1:activeuser>
      <d4p1:email i:nil='true' />
      <d4p1:hkey i:nil='true' />
      <d4p1:id>iddd</d4p1:id>
      <d4p1:lastcheck i:nil='true' />
    </d4p1:activeuser>
    <activeuser xmlns='urn:foo'>
      <email i:nil='true' />
      <hkey i:nil='true' />
      <id>idd</id>
      <lastcheck i:nil='true' />
    </activeuser>
    <response xmlns='urn:foo'>
      <langId i:nil='true' />
      <responsecode>200</responsecode>
      <responsemessage i:nil='true' />
    </response>
  </playeractiveuser>
</CheckLoginResponse>";

            string xml4 = @"
<CheckLoginResponse xmlns='http://tempuri.org/'>
  <playeractiveuser xmlns:d4p1='http://schemas.datacontract.org/2004/07/' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>
    <activeuser xmlns='urn:foo'>
      <email i:nil='true' />
      <hkey i:nil='true' />
      <id>idd</id>
      <lastcheck i:nil='true' />
    </activeuser>
    <d4p1:activeuser>
      <d4p1:email i:nil='true' />
      <d4p1:hkey i:nil='true' />
      <d4p1:id>iddd</d4p1:id>
      <d4p1:lastcheck i:nil='true' />
    </d4p1:activeuser>
    <response xmlns='urn:foo'>
      <langId i:nil='true' />
      <responsecode>200</responsecode>
      <responsemessage i:nil='true' />
    </response>
  </playeractiveuser>
</CheckLoginResponse>";

            var tm = TypedMessageConverter.Create(typeof(CheckLoginResponse), "urn:foo");
            var m  = Message.CreateMessage(MessageVersion.Default, "urn:foo", XmlReader.Create(new StringReader(xml)));

            m = Message.CreateMessage(MessageVersion.Default, "urn:foo", XmlReader.Create(new StringReader(xml2)));
            m = Message.CreateMessage(MessageVersion.Default, "urn:foo", XmlReader.Create(new StringReader(xml3)));
            var clr = (CheckLoginResponse)tm.FromMessage(m);

            Assert.IsNotNull(clr.playeractiveuser, "#1");
            Assert.IsNotNull(clr.playeractiveuser.activeuser, "#2");
            Assert.AreEqual("iddd", clr.playeractiveuser.activeuser.id, "#3");

            m = Message.CreateMessage(MessageVersion.Default, "urn:foo", XmlReader.Create(new StringReader(xml4)));
            Assert.AreEqual("iddd", clr.playeractiveuser.activeuser.id, "#4");
        }
Ejemplo n.º 23
0
                /// <summary>
                /// Parsing response stream and fetch response mesage from it
                /// </summary>
                private void ParsingResponseThreadProc()
                {
                    try
                    {
                        using (WebResponse response = this.request.GetResponse())
                            using (Stream responseStream = response.GetResponseStream())
                                using (XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(responseStream, DefaultReaderQuotas))
                                {
                                    reader.ReadStartElement();

                                    // this.disposeFlag is marked volatile so that the compiler
                                    // won't cache the value here
                                    while (!this.disposeFlag)
                                    {
                                        // In case of network failure and hang,
                                        // this call should eventually timed out
                                        Message m = ReadMessage(reader);
                                        if (m == null)
                                        {
                                            return;
                                        }

                                        if (m.Headers.Action.Equals(BrokerInstanceUnavailable.Action, StringComparison.InvariantCultureIgnoreCase))
                                        {
                                            TypedMessageConverter     converter = TypedMessageConverter.Create(typeof(BrokerInstanceUnavailable), BrokerInstanceUnavailable.Action);
                                            BrokerInstanceUnavailable biu       = (BrokerInstanceUnavailable)converter.FromMessage(m);
                                            SessionBase.TraceSource.TraceEvent(System.Diagnostics.TraceEventType.Error, 0, "[WebResponseHandler] Received broker unavailable message, BrokerLauncherEpr = {0}, BrokerNodeDown= {1}", biu.BrokerLauncherEpr, biu.IsBrokerNodeDown);
                                            this.callback.SendBrokerDownSignal(biu.IsBrokerNodeDown);
                                            break;
                                        }
                                        else
                                        {
                                            SessionBase.TraceSource.TraceEvent(System.Diagnostics.TraceEventType.Verbose, 0, "[WebResponseHandler] Received response message:  MessageId = {0}, Action = {1}", m.Headers.MessageId, m.Headers.Action);
                                            this.callback.SendResponse(m);
                                        }
                                    }
                                }
                    }
                    catch (Exception e)
                    {
                        SessionBase.TraceSource.TraceEvent(System.Diagnostics.TraceEventType.Error, 0, "[WebBrokerFrontendForGetResponse] Failed to read response from the response stream: {0}", e);
                        if (this.disposeFlag)
                        {
                            // If it has already been disposed, do not
                            // pass the exception to the enumerator
                            return;
                        }

                        Exception    exceptionToThrow = e;
                        WebException we = e as WebException;
                        if (we != null)
                        {
                            exceptionToThrow = WebAPIUtility.ConvertWebException(we);
                            FaultException <SessionFault> faultException = exceptionToThrow as FaultException <SessionFault>;
                            if (faultException != null)
                            {
                                exceptionToThrow = Utility.TranslateFaultException(faultException);
                            }
                        }

                        //Bug #15946: throw exception instead of signaling broker down.
                        //Note: To pass the exception to AsyncResponseCallback, wrap it as a response message with special action field.
                        Message exceptionMessage = Message.CreateMessage(MessageVersion.Default, Constant.WebAPI_ClientSideException);
                        exceptionMessage.Headers.Add(MessageHeader.CreateHeader(Constant.ResponseCallbackIdHeaderName, Constant.ResponseCallbackIdHeaderNS, clientData));
                        exceptionMessage.Properties.Add(Constant.WebAPI_ClientSideException, exceptionToThrow);

                        this.callback.SendResponse(exceptionMessage);
                    }
                    finally
                    {
                        // Two threads are involved here:
                        // first thread: it is disposing BrokerClient, and now it is at WebBrokerFrontendForGetResponse.Dispose
                        // second thread: it is "ParsingResponseThreadProc" worker thread

                        // The first thread holds a lock "lockObjectToProtectHandlers" and calls WebResponseHandler.Dispose method,
                        // which attempts to abort second thread. But the second thread is in finally block here, it indefinitely
                        // delays the abort. So the first thread is blocked at "this.parsingResponseThread.Abort()".

                        // The second thread calls following "this.Completed" method, which waits for the same lock "lockObjectToProtectHandlers".
                        // So the second thread is blocked on that lock.

                        // In order to avoid deadlock, change the first thread. It should not hold a lock when aborts the second thread.

                        if (this.Completed != null)
                        {
                            this.Completed(this, EventArgs.Empty);
                        }
                    }
                }
Ejemplo n.º 24
0
        /// <summary>
        /// Returns the TypedMessageConverter and operation faults for the specified action and reply action
        /// </summary>
        /// <returns></returns>
        internal bool GetResponseMessageInfo(ref string action, ref string replyAction, ref Type responseType,
                                             out TypedMessageConverter typedMessageConverter, out FaultDescriptionCollection faultCollection, out string errorMessage)
        {
            int operationIndex        = 0;
            int operationMatchIndex   = -1;
            int actionMatchIndex      = -1;
            int replyActionMatchIndex = -1;
            int operationQueryID      = -1;

            typedMessageConverter = null;
            faultCollection       = null;
            errorMessage          = "Unexpected error";

            // If caller explicitly passes action and replyAction to GetResponses or AddResponseHandler, look for both
            if (!String.IsNullOrEmpty(action) && !String.IsNullOrEmpty(replyAction))
            {
                operationQueryID = 0;
            }

            // If the caller passes just a response message type to GetResponses or AddResponseHandler, look for response type
            else if (responseType != null)
            {
                operationQueryID = 1;
            }

            // If the caller is using a typeless GetResponses or AddResponseHander, look for action
            else if (!String.IsNullOrEmpty(action))
            {
                operationQueryID = 2;
            }

            // Otherwise we have unexecpted input
            else
            {
                return(false);
            }

            // Loop through all the message descriptions of all the operations and look for matches
            foreach (OperationDescription operationDescription in this.operations)
            {
                bool actionMatch            = false;
                bool replyActionMatch       = false;
                int  actionIndex            = -1;
                int  replyActionIndex       = -1;
                int  messageDescriptonIndex = 0;

                foreach (MessageDescription messageDescription in operationDescription.Messages)
                {
                    if (messageDescription.Direction == MessageDirection.Input)
                    {
                        if (messageDescription.Action == action)
                        {
                            actionMatch = true;
                        }

                        actionIndex = messageDescriptonIndex;
                    }
                    else if (messageDescription.Direction == MessageDirection.Output)
                    {
                        if (messageDescription.Action == replyAction || messageDescription.MessageType == responseType)
                        {
                            replyActionMatch = true;
                        }

                        replyActionIndex = messageDescriptonIndex;
                    }

                    messageDescriptonIndex++;
                }

                // If we are looking for an exact match AND found matching action and reply actions
                //      OR we are looking for a replyAction match AND found a matching reply action
                //      OR we are looking for a action match AND found a matching action
                if ((operationQueryID == 0 && actionMatch && replyActionMatch) ||
                    (operationQueryID == 1 && replyActionMatch) ||
                    (operationQueryID == 2 && actionMatch))
                {
                    // If a previous operation was already matched, return ambiguous error
                    if (operationMatchIndex != -1)
                    {
                        errorMessage = SR.AmbiguousOperation;
                        return(false);
                    }

                    // Else save the operation and its reply message description
                    operationMatchIndex   = operationIndex;
                    actionMatchIndex      = actionIndex;
                    replyActionMatchIndex = replyActionIndex;
                }

                operationIndex++;
            }

            // If no matching operation was found, return operation not found
            if (operationMatchIndex == -1)
            {
                errorMessage = "Operation not found for specified actions";
                return(false);
            }

            // Create typedMessageCoverter and get fault collection
            OperationDescription operation = this.operations[operationMatchIndex];
            MessageDescription   requestMessageDescription = operation.Messages[actionMatchIndex];
            MessageDescription   replyMessageDescription   = operation.Messages[replyActionMatchIndex];

            typedMessageConverter = TypedMessageConverter.Create(replyMessageDescription.MessageType, replyMessageDescription.Action);
            action          = requestMessageDescription.Action;
            replyAction     = replyMessageDescription.Action;
            responseType    = replyMessageDescription.MessageType;
            faultCollection = operation.Faults;

            Debug.Assert(responseType != typeof(object) ? responseType == replyMessageDescription.MessageType : true, "Unexpected action/response type match!");

            return(true);
        }
Ejemplo n.º 25
0
 public void InvalidArgumentType()
 {
     TypedMessageConverter.Create(
         typeof(int), "http://tempuri.org/MyTest");
 }
 void cacheConverter(string action, Type messageType)
 {
     if (!_converterHash.ContainsKey(action))
     {
         _converterHash.Add(action, messageType == null ? null : (TypedMessageConverter)TypedMessageConverter.Create(messageType, action));
     }
 }
Ejemplo n.º 27
0
        /// <summary>
        /// Receives response messages from broker's response service
        /// </summary>
        /// <param name="message">Response message</param>
        public void SendResponse(Message message)
        {
            try
            {
                int currentResponseCount = 0;

                // Reset the heartbeat since operation just succeeded
                this.session.ResetHeartbeat();

                // Reset timeout timer since a response was received
                if (this.responseHandlerTimeoutTimer != null)
                {
                    this.responseHandlerTimeoutTimer.Change(this.responseHanderTimeout, 0);
                }

                // Bug #15946: handling client side exception thrown from WebResponseHandler(when talking to rest service)
                if (string.Equals(message.Headers.Action, Constant.WebAPI_ClientSideException, StringComparison.Ordinal))
                {
                    Exception e = message.Properties[Constant.WebAPI_ClientSideException] as Exception;
                    this.InvokeCallback(new BrokerResponse <TMessage>(e, message.Headers.RelatesTo));
                    return;
                }

                // TODO: Consider whether user callback should get an EOM message
                if (!Utility.IsEOM(message))
                {
                    // If the handler is closed, timed out, closed or broker heartbeat signaled, dont forward any more requests to the user.
                    // NOTE: If some responses already slipped through its OK because we prefer that over adding a lock here
                    if (this.shuttingDown)
                    {
                        return;
                    }

                    // Create a BrokerResponse object wrapper for the message object. A copy of the message must be created
                    MessageBuffer messageBuffer = null;
                    try
                    {
                        messageBuffer = message.CreateBufferedCopy(Constant.MaxBufferSize);
                    }
                    catch (Exception e)
                    {
                        Utility.LogError("AsyncResponseCallback.SendResponse received exception - {0}", e);
                        this.InvokeCallback(new BrokerResponse <TMessage>(e, message.Headers.RelatesTo));
                        return;
                    }

                    BrokerResponse <TMessage> brokerResponse = this.CreateResponse(BrokerClientBase.GetActionFromResponseMessage(message),
                                                                                   !message.IsFault ? message.Headers.Action : String.Empty,
                                                                                   messageBuffer,
                                                                                   message.Headers.RelatesTo == null ? SoaHelper.GetMessageId(message) : message.Headers.RelatesTo);

                    BrokerResponse <TMessage> lastResponse = null;

                    if (this.ignoreIsLastResponseProperty)
                    {
                        lastResponse = brokerResponse;
                    }
                    else
                    {
                        // Atomically swap out the last response.
                        lastResponse = Interlocked.Exchange <BrokerResponse <TMessage> >(ref this.lastBrokerResponse, brokerResponse);
                    }

                    // If there was a previous last response
                    if (lastResponse != null)
                    {
                        // Send it to the callback
                        this.InvokeCallback(lastResponse);

                        // Increment response count
                        currentResponseCount = Interlocked.Increment(ref this.currentResponseCount);
                    }

                    // If the caller wants all messages at once, do so.
                    // Else we always request ResponseWindowSize * 2 messages. If we get to
                    // the end of a window, request another
                    if (this.responseWindowSize != Constant.GetResponse_All && currentResponseCount != 0 &&
                        (currentResponseCount + 1) % this.responseWindowSize == 0)
                    {
                        // Call async version and block on completion in order to workaround System.Net.Socket bug #750028
                        try
                        {
                            SessionBase.TraceSource.TraceInformation("GetResponse : currentResponseCount {0} : clientId {1}", currentResponseCount, this.clientId);
                            this.responseService.GetResponses(
                                this.action,
                                this.callbackManagerId,
                                GetResponsePosition.Current,
                                this.responseWindowSize,
                                this.clientId);
                        }
                        catch (FaultException <SessionFault> e)
                        {
                            throw Utility.TranslateFaultException(e);
                        }
                    }
                }

                // If this is a client purged fault, return that exception in a BrokerResponse
                else
                {
                    TypedMessageConverter endOfResponsesConverter = TypedMessageConverter.Create(typeof(EndOfResponses), Constant.EndOfMessageAction);
                    EndOfResponses        endOfResponses          = (EndOfResponses)endOfResponsesConverter.FromMessage(message);

                    switch (endOfResponses.Reason)
                    {
                    case EndOfResponsesReason.ClientPurged:
                        this.InvokeCallback(new BrokerResponse <TMessage>(SessionBase.ClientPurgedException, new UniqueId(Guid.Empty)));
                        break;

                    case EndOfResponsesReason.ClientTimeout:
                        this.InvokeCallback(new BrokerResponse <TMessage>(SessionBase.ClientTimeoutException, new UniqueId(Guid.Empty)));
                        break;

                    default:
                        // Save how many responses are expected (minus 1 for the last response)
                        System.Diagnostics.Debug.Assert(endOfResponses.Count > 0, "Response count should also be positive number");
                        this.expectedResponseCount = endOfResponses.Count - 1;
                        break;
                    }
                }

                if (!this.ignoreIsLastResponseProperty)
                {
                    // Check to see if we receive the EOM message and all the responses.
                    // If so pass last response to callback marked as such. Also make
                    // sure this isnt called again with a lock.
                    if (this.expectedResponseCount == this.currentResponseCount)
                    {
                        lock (this.lastResponseLock)
                        {
                            if (this.expectedResponseCount == this.currentResponseCount)
                            {
                                // Mark the response as the last one
                                this.lastBrokerResponse.isLastResponse = true;

                                // Send last response to callback. Note since currentResponseCount
                                // is incremented after responses are sent to the callback, the
                                // callback will not be processing any other responses at this time.
                                this.InvokeCallback(this.lastBrokerResponse);

                                this.expectedResponseCount = -1;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                // Log and eat unhandled user exceptions from their calback
                Utility.LogError("Unhandled exception processing response - {0}", e);
            }
        }
        protected override object GetMessageObject(Message message)
        {
            TypedMessageConverter converter = getCachedConverter(message.Headers.Action);

            return(converter.FromMessage(message));
        }
Ejemplo n.º 29
0
 static RelayedConnectMessage()
 {
     RelayedConnectMessage.MessageConverter = TypedMessageConverter.Create(typeof(RelayedConnectMessage), "http://schemas.microsoft.com/netservices/2009/05/servicebus/relayedconnect/RelayedConnect");
 }
Ejemplo n.º 30
0
    public static void Default_Create()
    {
        var typedMessageConverter = TypedMessageConverter.Create(typeof(TestMessage), "http://TestMessage/Action");

        Assert.NotNull(typedMessageConverter);
    }