示例#1
0
        public static void Subscribe()
        {
            // Subscribe examples showing use of Raw XML Client vs the Message Contract based Client.
            // Regardless of client, the service is unafected.
            if (false)
            {
                var reader  = new StringReader("<wse:Subscribe xmlns:wse='http://schemas.xmlsoap.org/ws/2004/08/eventing'><wse:Delivery><wse:NotifyTo><Address xmlns='http://schemas.xmlsoap.org/ws/2004/08/addressing'>" + EventSinkUri + "</Address></wse:NotifyTo></wse:Delivery></wse:Subscribe>");
                var content = XmlReader.Create(reader);
                var request = Message.CreateMessage(MessageVersion.Soap11, Constants.WsEventing.Actions.Subscribe, content);
                var channel = ChannelFactory <IEventSourceRaw> .CreateChannel(new BasicHttpBinding(), new EndpointAddress("http://localhost:8080/eventsource"));

                var response = channel.Subscribe(request);
                var xml      = response.GetReaderAtBodyContents().ReadOuterXml();
                if (response.IsFault)
                {
                    throw new Exception(xml);
                }
            }
            else
            {
                var request = new SubscribeRequestMessage(EventSinkUri);
                var channel = ChannelFactory <IEventSource> .CreateChannel(new BasicHttpBinding(), new EndpointAddress("http://localhost:8080/eventsource"));

                channel.Subscribe(request);
            }

            Console.WriteLine("Event subscribed!");
        }
示例#2
0
        // It is returned for ServiceDebugBehavior.Http(s)HelpPageUrl.
        // They may be empty, and for such case the help page URL is
        // simply the service endpoint URL (foobar.svc).
        //
        // Note that if there is also ServiceMetadataBehavior that
        // lacks Http(s)GetUrl, then it is also mapped to the same
        // URL, but it requires "?wsdl" parameter and .NET somehow
        // differentiates those requests.
        //
        // If both Http(s)HelpPageUrl and Http(s)GetUrl exist, then
        // requests to the service endpoint URL (foobar.svc) results
        // in an xml output with empty string (non-WF XML error).

        SMMessage CreateHelpPage(SMMessage request)
        {
            var helpBody = ext.Owner.Description.Behaviors.Find <ServiceMetadataBehavior> () != null?
                           String.Format(@"
<p>To create client proxy source, run:</p>
<p><code>svcutil <a href='{0}'>{0}</a></code></p>
<!-- FIXME: add client proxy usage (that required decent ServiceContractGenerator implementation, so I leave it yet.) -->
", new Uri (WsdlUrl.ToString() + "?wsdl")) :  // this Uri.ctor() is nasty, but there is no other way to add "?wsdl" (!!)
                               String.Format(@"
<p>Service metadata publishing for {0} is not enabled. Service administrators can enable it by adding &lt;serviceMetadata&gt; element in the host configuration (web.config in ASP.NET), or ServiceMetadataBehavior object to the Behaviors collection of the service host's ServiceDescription.</p>", ext.Owner.Description.Name);

            var html = String.Format(@"
<html>
<head>
<title>Service {0}</title>
</head>
<body>
{1}
</body>
</html>", ext.Owner.Description.Name, helpBody);

            var m  = SMMessage.CreateMessage(MessageVersion.None, "", XmlReader.Create(new StringReader(html)));
            var rp = new HttpResponseMessageProperty();

            rp.Headers ["Content-Type"] = "text/html";
            m.Properties.Add(HttpResponseMessageProperty.Name, rp);
            return(m);
        }
示例#3
0
        internal MetadataSet GetMetadataInternal(EndpointAddress address, MetadataExchangeClientMode mode)
        {
            if (binding == null)
            {
                binding = MetadataExchangeBindings.CreateMexHttpBinding();
            }

            MetadataProxy proxy = new MetadataProxy(binding, address);

            proxy.Open();

            SMMessage msg = SMMessage.CreateMessage(
                MessageVersion.Soap12WSAddressing10,
                "http://schemas.xmlsoap.org/ws/2004/09/transfer/Get");

            msg.Headers.ReplyTo = new EndpointAddress(
                "http://www.w3.org/2005/08/addressing/anonymous");
            //msg.Headers.From = new EndpointAddress ("http://localhost");
            msg.Headers.To        = address.Uri;
            msg.Headers.MessageId = new UniqueId();

            SMMessage ret;

            try {
                ret = proxy.Get(msg);
            } catch (Exception e) {
                throw new InvalidOperationException(
                          "Metadata contains a reference that cannot be resolved : " + address.Uri.AbsoluteUri, e);
            }

            return(MetadataSet.ReadFrom(ret.GetReaderAtBodyContents()));
        }
        public void Can_Deserialize_Message_from_GetBody()
        {
            var msg = Message.CreateMessage(MessageVersion.Default, "Reverse", request);
            //Console.WriteLine("BODY: " + msg.GetReaderAtBodyContents().ReadOuterXml());

            var fromRequest = msg.GetBody <Reverse>(new System.Runtime.Serialization.DataContractSerializer(typeof(Reverse)));

            Assert.That(fromRequest.Value, Is.EqualTo(request.Value));
        }
示例#5
0
        SMMessage CreateWsdlMessage(WSServiceDescription wsdl)
        {
            MemoryStream ms = new MemoryStream();
            XmlWriter    xw = XmlWriter.Create(ms);

            WSServiceDescription.Serializer.Serialize(xw, wsdl);
            ms.Seek(0, SeekOrigin.Begin);
            return(SMMessage.CreateMessage(MessageVersion.None, "", XmlReader.Create(ms)));
        }
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            if (fault == null)
            {
                var faultException = new FaultException("Произошла ошибка. Попробуйте повторить операцию позднее.");

                var message = Message.CreateMessage(version, faultException.CreateMessageFault(), faultException.Action);
                fault = message;
            }
        }
示例#7
0
        public SMMessage Get(SMMessage req)
        {
            EnsureMetadata();

            HttpRequestMessageProperty prop = (HttpRequestMessageProperty)req.Properties [HttpRequestMessageProperty.Name];

            NameValueCollection query_string = CreateQueryString(prop.QueryString);

            if (query_string == null || query_string.AllKeys.Length != 1)
            {
                if (HelpUrl != null && Uri.Compare(req.Headers.To, HelpUrl, UriComponents.HttpRequestUrl ^ UriComponents.Query, UriFormat.UriEscaped, StringComparison.Ordinal) == 0)
                {
                    return(CreateHelpPage(req));
                }
                WSServiceDescription w = GetWsdl("wsdl");
                if (w != null)
                {
                    return(CreateWsdlMessage(w));
                }
            }

            if (query_string [null] == "wsdl")
            {
                WSServiceDescription wsdl = GetWsdl("wsdl");
                if (wsdl != null)
                {
                    return(CreateWsdlMessage(wsdl));
                }
            }
            else if (query_string ["wsdl"] != null)
            {
                WSServiceDescription wsdl = GetWsdl(query_string ["wsdl"]);
                if (wsdl != null)
                {
                    return(CreateWsdlMessage(wsdl));
                }
            }
            else if (query_string ["xsd"] != null)
            {
                XmlSchema schema = GetXmlSchema(query_string ["xsd"]);
                if (schema != null)
                {
                    //FIXME: Is this the correct way?
                    MemoryStream ms = new MemoryStream();

                    schema.Write(ms);
                    ms.Seek(0, SeekOrigin.Begin);
                    SMMessage ret = SMMessage.CreateMessage(MessageVersion.None, "", XmlReader.Create(ms));

                    return(ret);
                }
            }

            return(CreateHelpPage(req));
        }
        public void Can_Deserialize_Message_from_GetReaderAtBodyContents()
        {
            var msg = Message.CreateMessage(MessageVersion.Default, "Reverse", request);

            using (var reader = msg.GetReaderAtBodyContents())
            {
                var requestXml  = reader.ReadOuterXml();
                var fromRequest = (Reverse)DataContractSerializer.Instance.DeserializeFromString(requestXml, typeof(Reverse));
                Assert.That(fromRequest.Value, Is.EqualTo(request.Value));
            }
        }
        protected static Message GetRequestMessage(string requestXml)
        {
            var doc = new XmlDocument();

            doc.LoadXml(requestXml);

            var msg = Message.CreateMessage(new XmlNodeReader(doc), int.MaxValue,
                                            MessageVersion.Soap11WSAddressingAugust2004);

            //var msg = Message.CreateMessage(MessageVersion.Soap12WSAddressingAugust2004,
            //    "*", new XmlBodyWriter(requestXml));

            return(msg);
        }
        public void What_do_the_different_soap_payloads_look_like()
        {
            var doc = new XmlDocument();

            doc.LoadXml(msgXml);

            //var action = "Request";
            string action = null;
            var    soap12 = Message.CreateMessage(MessageVersion.Soap12, action, request);
            var    soap12WSAddressing10         = Message.CreateMessage(MessageVersion.Soap12WSAddressing10, action, request);
            var    soap12WSAddressingAugust2004 = Message.CreateMessage(MessageVersion.Soap12WSAddressingAugust2004, action, request);

            Console.WriteLine("Soap12: " + GetMessageEnvelope(soap12));
            Console.WriteLine("Soap12WSAddressing10: " + GetMessageEnvelope(soap12WSAddressing10));
            Console.WriteLine("Soap12WSAddressingAugust2004: " + GetMessageEnvelope(soap12WSAddressingAugust2004));
        }
        internal MetadataSet GetMetadataInternal(EndpointAddress address, MetadataExchangeClientMode mode)
        {
            // FIXME: give dialect and identifier
            var cf = GetChannelFactory(address, null, null);

            cf.Open();
            var proxy           = cf.CreateChannel();
            var asClientChannel = proxy as IClientChannel;

            if (asClientChannel == null)
            {
                throw new InvalidOperationException("The channel factory must return an IClientChannel implementation");
            }
            asClientChannel.OperationTimeout = OperationTimeout;
            asClientChannel.Open();

            SMMessage msg = SMMessage.CreateMessage(
                MessageVersion.Soap12WSAddressing10,
                "http://schemas.xmlsoap.org/ws/2004/09/transfer/Get");

            msg.Headers.ReplyTo = new EndpointAddress(
                "http://www.w3.org/2005/08/addressing/anonymous");
            //msg.Headers.From = new EndpointAddress ("http://localhost");
            msg.Headers.To        = address.Uri;
            msg.Headers.MessageId = new UniqueId();

            SMMessage ret;

            try
            {
                ret = proxy.Get(msg);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException(
                          "Metadata contains a reference that cannot be resolved : " + address.Uri.AbsoluteUri, e);
            }

            return(MetadataSet.ReadFrom(ret.GetReaderAtBodyContents()));
        }
        public void Can_create_entire_message_from_xml()
        {
            //var msg = Message.CreateMessage(MessageVersion.Default,
            //    "Reverse", new SimpleBodyWriter(msgXml));

            var doc = new XmlDocument();

            doc.LoadXml(msgXml);

            using (var xnr = new XmlNodeReader(doc))
            {
                var msg = Message.CreateMessage(xnr, msgXml.Length, MessageVersion.Soap12WSAddressingAugust2004);

                var xml = msg.GetReaderAtBodyContents().ReadOuterXml();
                Console.WriteLine("BODY: " + DataContractSerializer.Instance.SerializeToString(request));
                Console.WriteLine("EXPECTED BODY: " + xml);

                var fromRequest = (Reverse)DataContractSerializer.Instance.DeserializeFromString(xml, typeof(Reverse));
                Assert.That(fromRequest.Value, Is.EqualTo(request.Value));
            }

            //var fromRequest = msg.GetBody<Request>(new DataContractSerializer(typeof(Request)));
        }
示例#13
0
        void GotResponse(IAsyncResult result)
        {
            HttpChannelRequestAsyncResult channelResult = (HttpChannelRequestAsyncResult)result.AsyncState;

            channelResult.CompletedSynchronously &= result.CompletedSynchronously;

            WebResponse res;
            Stream      resstr;

            try {
                res    = channelResult.WebRequest.EndGetResponse(result);
                resstr = res.GetResponseStream();
            } catch (WebException we) {
                res = we.Response;
                if (res == null)
                {
                    channelResult.Complete(we);
                    return;
                }


                var hrr2 = (HttpWebResponse)res;

                if ((int)hrr2.StatusCode >= 400 && (int)hrr2.StatusCode < 500)
                {
                    Exception exception = new WebException(
                        String.Format("There was an error on processing web request: Status code {0}({1}): {2}",
                                      (int)hrr2.StatusCode, hrr2.StatusCode, hrr2.StatusDescription), null,
                        WebExceptionStatus.ProtocolError, hrr2);

                    if ((int)hrr2.StatusCode == 404)
                    {
                        // Throw the same exception .NET does
                        exception = new EndpointNotFoundException(
                            "There was no endpoint listening at {0} that could accept the message. This is often caused by an incorrect address " +
                            "or SOAP action. See InnerException, if present, for more details.",
                            exception);
                    }

                    channelResult.Complete(exception);
                    return;
                }


                try {
                    // The response might contain SOAP fault. It might not.
                    resstr = res.GetResponseStream();
                } catch (WebException we2) {
                    channelResult.Complete(we2);
                    return;
                }
            }

            var hrr = (HttpWebResponse)res;

            if ((int)hrr.StatusCode >= 400 && (int)hrr.StatusCode < 500)
            {
                channelResult.Complete(new WebException(String.Format("There was an error on processing web request: Status code {0}({1}): {2}", (int)hrr.StatusCode, hrr.StatusCode, hrr.StatusDescription)));
            }

            try {
                Message ret;

                // TODO: unit test to make sure an empty response never throws
                // an exception at this level
                if (hrr.ContentLength == 0)
                {
                    ret = Message.CreateMessage(Encoder.MessageVersion, String.Empty);
                }
                else
                {
                    using (var responseStream = resstr) {
                        MemoryStream ms = new MemoryStream();
                        byte []      b  = new byte [65536];
                        int          n  = 0;

                        while (true)
                        {
                            n = responseStream.Read(b, 0, 65536);
                            if (n == 0)
                            {
                                break;
                            }
                            ms.Write(b, 0, n);
                        }
                        ms.Seek(0, SeekOrigin.Begin);

                        ret = Encoder.ReadMessage(
                            ms, (int)source.Transport.MaxReceivedMessageSize, res.ContentType);
                    }
                }

                var rp = new HttpResponseMessageProperty()
                {
                    StatusCode = hrr.StatusCode, StatusDescription = hrr.StatusDescription
                };
                foreach (var key in hrr.Headers.AllKeys)
                {
                    rp.Headers [key] = hrr.Headers [key];
                }
                ret.Properties.Add(HttpResponseMessageProperty.Name, rp);

                channelResult.Response = ret;
                channelResult.Complete();
            } catch (Exception ex) {
                channelResult.Complete(ex);
            } finally {
                res.Close();
            }
        }
示例#14
0
        void GotResponse(IAsyncResult result)
        {
            HttpChannelRequestAsyncResult channelResult = (HttpChannelRequestAsyncResult)result.AsyncState;

            channelResult.CompletedSynchronously &= result.CompletedSynchronously;

            WebResponse res;
            Stream      resstr;

            try {
                res    = channelResult.WebRequest.EndGetResponse(result);
                resstr = res.GetResponseStream();
            } catch (WebException we) {
                res = we.Response;
                if (res == null)
                {
                    channelResult.Complete(we);
                    return;
                }
                try {
                    // The response might contain SOAP fault. It might not.
                    resstr = res.GetResponseStream();
                } catch (WebException we2) {
                    channelResult.Complete(we2);
                    return;
                }
            }

            var hrr = (HttpWebResponse)res;

            if ((int)hrr.StatusCode >= 400 && (int)hrr.StatusCode < 500)
            {
                channelResult.Complete(new WebException(String.Format("There was an error on processing web request: Status code {0}({1}): {2}", (int)hrr.StatusCode, hrr.StatusCode, hrr.StatusDescription)));
            }

            try {
                Message ret;

                // TODO: unit test to make sure an empty response never throws
                // an exception at this level
                if (hrr.ContentLength == 0)
                {
                    ret = Message.CreateMessage(Encoder.MessageVersion, String.Empty);
                }
                else
                {
                    using (var responseStream = resstr) {
                        MemoryStream ms = new MemoryStream();
                        byte []      b  = new byte [65536];
                        int          n  = 0;

                        while (true)
                        {
                            n = responseStream.Read(b, 0, 65536);
                            if (n == 0)
                            {
                                break;
                            }
                            ms.Write(b, 0, n);
                        }
                        ms.Seek(0, SeekOrigin.Begin);

                        ret = Encoder.ReadMessage(
                            ms, (int)source.Transport.MaxReceivedMessageSize, res.ContentType);
                    }
                }

                var rp = new HttpResponseMessageProperty()
                {
                    StatusCode = hrr.StatusCode, StatusDescription = hrr.StatusDescription
                };
#if MOONLIGHT
                if (hrr.SupportsHeaders)
                {
                    foreach (string key in hrr.Headers)
                    {
                        rp.Headers [key] = hrr.Headers [key];
                    }
                }
#else
                foreach (var key in hrr.Headers.AllKeys)
                {
                    rp.Headers [key] = hrr.Headers [key];
                }
#endif
                ret.Properties.Add(HttpResponseMessageProperty.Name, rp);

                channelResult.Response = ret;
                channelResult.Complete();
            } catch (Exception ex) {
                channelResult.Complete(ex);
            } finally {
                res.Close();
            }
        }
示例#15
0
        internal static Message DecodeIntegrationDatagram(MsmqIntegrationChannelListener listener, MsmqReceiveHelper receiver, MsmqIntegrationInputMessage msmqMessage, MsmqMessageProperty messageProperty)
        {
            using (MsmqDiagnostics.BoundReceiveBytesOperation())
            {
                Message message      = Message.CreateMessage(MessageVersion.None, (string)null);
                bool    closeMessage = true;

                try
                {
                    SecurityMessageProperty securityProperty = listener.ValidateSecurity(msmqMessage);
                    if (null != securityProperty)
                    {
                        message.Properties.Security = securityProperty;
                    }

                    MsmqIntegrationMessageProperty integrationProperty = new MsmqIntegrationMessageProperty();
                    msmqMessage.SetMessageProperties(integrationProperty);

                    int size = msmqMessage.BodyLength.Value;

                    if (size > listener.MaxReceivedMessageSize)
                    {
                        receiver.FinalDisposition(messageProperty);
                        throw listener.NormalizePoisonException(messageProperty.LookupId, MaxMessageSizeStream.CreateMaxReceivedMessageSizeExceededException(listener.MaxReceivedMessageSize));
                    }

                    byte[] bodyBytes = msmqMessage.Body.GetBufferCopy(size);

                    MemoryStream bodyStream = new MemoryStream(bodyBytes, 0, bodyBytes.Length, false);

                    object body = null;
                    using (MsmqDiagnostics.BoundDecodeOperation())
                    {
                        try
                        {
                            body = DeserializeForIntegration(listener, bodyStream, integrationProperty, messageProperty.LookupId);
                        }
                        catch (SerializationException e)
                        {
                            receiver.FinalDisposition(messageProperty);
                            throw listener.NormalizePoisonException(messageProperty.LookupId, new ProtocolException(SR.GetString(SR.MsmqDeserializationError), e));
                        }

                        integrationProperty.Body = body;
                        message.Properties[MsmqIntegrationMessageProperty.Name] = integrationProperty;
                        bodyStream.Seek(0, SeekOrigin.Begin);
                        message.Headers.To = listener.Uri;
                        closeMessage       = false;
                        MsmqDiagnostics.TransferFromTransport(message);
                    }
                    return(message);
                }
                finally
                {
                    if (closeMessage)
                    {
                        message.Close();
                    }
                }
            }
        }