public Message Request(Message message, TimeSpan timeout) { var signatureCaseMessageTransformer = new OioWsTrustMessageTransformer(); signatureCaseMessageTransformer.ModifyMessageAccordingToStsNeeds(ref message, _channelManager.ClientCertificate); var respsonse = _innerChannel.Request(message, timeout); signatureCaseMessageTransformer.ModifyMessageAccordingToWsTrust(ref respsonse, _channelManager.StsCertificate); return(respsonse); }
public static void IRequestChannel_Http_CustomBinding() { try { BindingElement[] bindingElements = new BindingElement[2]; bindingElements[0] = new TextMessageEncodingBindingElement(); bindingElements[1] = new HttpTransportBindingElement(); CustomBinding binding = new CustomBinding(bindingElements); // Create the channel factory for the request-reply message exchange pattern. IChannelFactory <IRequestChannel> factory = binding.BuildChannelFactory <IRequestChannel>( new BindingParameterCollection()); factory.Open(); // Create the channel. IRequestChannel channel = factory.CreateChannel( new EndpointAddress(BaseAddress.HttpBaseAddress)); channel.Open(); // Create the Message object to send to the service. Message requestMessage = Message.CreateMessage( binding.MessageVersion, action, new CustomBodyWriter(clientMessage)); // Send the Message and receive the Response. Message replyMessage = channel.Request(requestMessage); string replyMessageAction = replyMessage.Headers.Action; if (!string.Equals(replyMessageAction, action + "Response")) { Assert.True(false, String.Format("A response was received from the Service but it was not the expected Action, expected: {0} actual: {1}", action + "Response", replyMessageAction)); } var replyReader = replyMessage.GetReaderAtBodyContents(); string actualResponse = replyReader.ReadElementContentAsString(); string expectedResponse = "[client] This is my request.[service] Request received, this is my Reply."; if (!string.Equals(actualResponse, expectedResponse)) { Assert.True(false, String.Format("Actual MessageBodyContent from service did not match the expected MessageBodyContent, expected: {0} actual: {1}", expectedResponse, actualResponse)); } replyMessage.Close(); channel.Close(); factory.Close(); } catch (Exception ex) { Assert.True(false, String.Format("Unexpected exception was caught: {0}", ex.ToString())); } }
public Message Request(Message request, TimeSpan timeout) { Message reply = null; if (request != null) { reply = innerChannel.Request(request, timeout); } return(reply); }
public virtual GetDataResponse GetData(GetData req) { // Create request header String action; action = "http://tempuri.org/IDataAccessService/GetData"; WsWsaHeader header; header = new WsWsaHeader(action, null, EndpointAddress, m_version.AnonymousUri, null, null); WsMessage request = new WsMessage(header, req, WsPrefix.None); // Create request serializer GetDataDataContractSerializer reqDcs; reqDcs = new GetDataDataContractSerializer("GetData", "http://tempuri.org/"); request.Serializer = reqDcs; request.Method = "GetData"; // Indicate that this message will use Mtom encoding request.BodyParts = new WsMtomBodyParts(); // Send service request m_requestChannel.Open(); WsMessage response = m_requestChannel.Request(request); m_requestChannel.Close(); // Process response GetDataResponseDataContractSerializer respDcs; respDcs = new GetDataResponseDataContractSerializer("GetDataResponse", "http://tempuri.org/"); respDcs.BodyParts = response.BodyParts; GetDataResponse resp; resp = ((GetDataResponse)(respDcs.ReadObject(response.Reader))); response.Reader.Dispose(); response.Reader = null; return(resp); }
// Envelope Version 'EnvelopeNone (http://schemas.microsoft.com/ws/2005/05/envelope/none)' // does not support adding Message Headers. public void MessageSecurityPOX() { SymmetricSecurityBindingElement sbe = new SymmetricSecurityBindingElement(); sbe.ProtectionTokenParameters = new X509SecurityTokenParameters(); RequestSender sender = delegate(Message input) { MessageBuffer buf = input.CreateBufferedCopy(0x10000); using (XmlWriter w = XmlWriter.Create(Console.Error)) { buf.CreateMessage().WriteMessage(w); } return(buf.CreateMessage()); }; CustomBinding binding = new CustomBinding( sbe, new TextMessageEncodingBindingElement( MessageVersion.None, Encoding.UTF8), new HandlerTransportBindingElement(sender)); EndpointAddress address = new EndpointAddress( new Uri("http://localhost:37564"), new X509CertificateEndpointIdentity(new X509Certificate2("Test/Resources/test.pfx", "mono"))); ChannelFactory <IRequestChannel> cf = new ChannelFactory <IRequestChannel> (binding, address); IRequestChannel ch = cf.CreateChannel(); /* * // neither of Endpoint, Contract nor its Operation seems * // to have applicable behaviors (except for * // ClientCredentials) * Assert.AreEqual (1, cf.Endpoint.Behaviors.Count, "EndpointBehavior"); * Assert.AreEqual (0, cf.Endpoint.Contract.Behaviors.Count, "ContractBehavior"); * Assert.AreEqual (1, cf.Endpoint.Contract.Operations.Count, "Operations"); * OperationDescription od = cf.Endpoint.Contract.Operations [0]; * Assert.AreEqual (0, od.Behaviors.Count, "OperationBehavior"); */ ch.Open(); try { ch.Request(Message.CreateMessage(MessageVersion.None, "urn:myaction")); } finally { ch.Close(); } }
public static void IRequestChannel_Http_CustomBinding() { IChannelFactory <IRequestChannel> factory = null; IRequestChannel channel = null; Message replyMessage = null; try { // *** SETUP *** \\ BindingElement[] bindingElements = new BindingElement[2]; bindingElements[0] = new TextMessageEncodingBindingElement(); bindingElements[1] = new HttpTransportBindingElement(); CustomBinding binding = new CustomBinding(bindingElements); // Create the channel factory for the request-reply message exchange pattern. factory = binding.BuildChannelFactory <IRequestChannel>(new BindingParameterCollection()); factory.Open(); // Create the channel. channel = factory.CreateChannel(new EndpointAddress(Endpoints.DefaultCustomHttp_Address)); channel.Open(); // Create the Message object to send to the service. Message requestMessage = Message.CreateMessage( binding.MessageVersion, action, new CustomBodyWriter(clientMessage)); // *** EXECUTE *** \\ // Send the Message and receive the Response. replyMessage = channel.Request(requestMessage); // *** VALIDATE *** \\ string replyMessageAction = replyMessage.Headers.Action; Assert.Equal(action + "Response", replyMessageAction); var replyReader = replyMessage.GetReaderAtBodyContents(); string actualResponse = replyReader.ReadElementContentAsString(); string expectedResponse = "[client] This is my request.[service] Request received, this is my Reply."; Assert.Equal(expectedResponse, actualResponse); // *** CLEANUP *** \\ replyMessage.Close(); channel.Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects(channel, factory); } }
public void RequestWithDefaultServiceCertificateWithDns() { IChannelFactory <IRequestChannel> f = CreateDefaultServiceCertFactory(); f.Open(); // This EndpointAddress does not contain X509 identity IRequestChannel ch = f.CreateChannel(new EndpointAddress(new Uri("stream:dummy"), new DnsEndpointIdentity("Poupou's-Software-Factory"))); ch.Open(); // -> MessageSecurityException (IdentityVerifier complains DNS claim) ch.Request(Message.CreateMessage(MessageVersion.Default, "http://tempuri.org/MyAction")); }
public override Message Request(Message req, TimeSpan timeout) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; MessageBuffer buf = req.CreateBufferedCopy(0x10000); using (XmlWriter w = XmlWriter.Create(Console.Error, settings)) { buf.CreateMessage().WriteMessage(w); } Console.Error.WriteLine("******************** Debug Request() ********************"); Console.Error.Flush(); return(inner.Request(buf.CreateMessage(), timeout)); }
private void sendButton_Click(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; // Creating the message to send TransmittedObject to = new TransmittedObject(); to.str = "Hello"; to.i = 5; XmlSerializerWrapper wrapper = new XmlSerializerWrapper(typeof(TransmittedObject)); Message m = Message.CreateMessage (MessageVersion.Soap11, "urn:test", to, wrapper); // Creating the channel to send the message BasicHttpBinding binding = new BasicHttpBinding(); BindingParameterCollection parameters = new BindingParameterCollection(); IChannelFactory <IRequestChannel> channelFactory = binding.BuildChannelFactory <IRequestChannel>(parameters); channelFactory.Open(); // Opening the channel IRequestChannel outChannel = channelFactory.CreateChannel (new EndpointAddress (new Uri("http://<<ServerAddress>>:<<PortNumber>>"))); outChannel.Open(TimeSpan.MaxValue); // Sending the Message and waiting for the reply Message reply = outChannel.Request(m, TimeSpan.MaxValue); // Deserializing and using the Message TransmittedObject to1 = reply.GetBody <TransmittedObject> (new XmlSerializerWrapper(typeof(TransmittedObject))); MessageBox.Show(to1.str + " " + to1.i.ToString()); // Cleaning up outChannel.Close(); channelFactory.Close(); Cursor.Current = Cursors.Default; }
public virtual GetMeasurementsResponse GetMeasurements(GetMeasurements req) { // Create request header String action; action = "http://tempuri.org/ISmartService/GetMeasurements"; WsWsaHeader header; header = new WsWsaHeader(action, null, EndpointAddress, m_version.AnonymousUri, null, null); WsMessage request = new WsMessage(header, req, WsPrefix.None); // Create request serializer GetMeasurementsDataContractSerializer reqDcs; reqDcs = new GetMeasurementsDataContractSerializer("GetMeasurements", "http://tempuri.org/"); request.Serializer = reqDcs; request.Method = "GetMeasurements"; // Send service request m_requestChannel.Open(); WsMessage response = m_requestChannel.Request(request); m_requestChannel.Close(); // Process response GetMeasurementsResponseDataContractSerializer respDcs; respDcs = new GetMeasurementsResponseDataContractSerializer("GetMeasurementsResponse", "http://tempuri.org/"); GetMeasurementsResponse resp; resp = ((GetMeasurementsResponse)(respDcs.ReadObject(response.Reader))); response.Reader.Dispose(); response.Reader = null; return(resp); }
public virtual getServerAddressWithPortResponse getServerAddressWithPort(getServerAddressWithPort req) { // Create request header String action; action = "http://tempuri.org/IService1/getServerAddressWithPort"; WsWsaHeader header; header = new WsWsaHeader(action, null, EndpointAddress, m_version.AnonymousUri, null, null); WsMessage request = new WsMessage(header, req, WsPrefix.None); // Create request serializer getServerAddressWithPortDataContractSerializer reqDcs; reqDcs = new getServerAddressWithPortDataContractSerializer("getServerAddressWithPort", "http://tempuri.org/"); request.Serializer = reqDcs; request.Method = "getServerAddressWithPort"; // Send service request m_requestChannel.Open(); WsMessage response = m_requestChannel.Request(request); m_requestChannel.Close(); // Process response getServerAddressWithPortResponseDataContractSerializer respDcs; respDcs = new getServerAddressWithPortResponseDataContractSerializer("getServerAddressWithPortResponse", "http://tempuri.org/"); getServerAddressWithPortResponse resp; resp = ((getServerAddressWithPortResponse)(respDcs.ReadObject(response.Reader))); response.Reader.Dispose(); response.Reader = null; return(resp); }
public virtual TwoWayResponse TwoWay(TwoWayRequest req) { // Create request header String action; action = "http://schemas.example.org/SimpleService/TwoWay"; WsWsaHeader header; header = new WsWsaHeader(action, null, EndpointAddress, m_version.AnonymousUri, null, null); WsMessage request = new WsMessage(header, req, WsPrefix.None); // Create request serializer TwoWayRequestDataContractSerializer reqDcs; reqDcs = new TwoWayRequestDataContractSerializer("TwoWayRequest", "http://schemas.example.org/SimpleService"); request.Serializer = reqDcs; request.Method = "TwoWay"; // Send service request m_requestChannel.Open(); WsMessage response = m_requestChannel.Request(request); m_requestChannel.Close(); // Process response TwoWayResponseDataContractSerializer respDcs; respDcs = new TwoWayResponseDataContractSerializer("TwoWayResponse", "http://schemas.example.org/SimpleService"); TwoWayResponse resp; resp = ((TwoWayResponse)(respDcs.ReadObject(response.Reader))); response.Reader.Dispose(); response.Reader = null; return(resp); }
public static void IRequestChannel_Http_BasicHttpBinding() { IChannelFactory <IRequestChannel> factory = null; IRequestChannel channel = null; Message replyMessage = null; try { // *** SETUP *** \\ BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None); // Create the channel factory factory = binding.BuildChannelFactory <IRequestChannel>(new BindingParameterCollection()); factory.Open(); // Create the channel. channel = factory.CreateChannel(new EndpointAddress(Endpoints.HttpBaseAddress_Basic)); channel.Open(); // Create the Message object to send to the service. Message requestMessage = Message.CreateMessage( binding.MessageVersion, action, new CustomBodyWriter(clientMessage)); // *** EXECUTE *** \\ // Send the Message and receive the Response. replyMessage = channel.Request(requestMessage); // *** VALIDATE *** \\ // BasicHttpBinding uses SOAP1.1 which doesn't return the Headers.Action property in the Response // Therefore not validating this property as we do in the test "InvokeIRequestChannelCreatedViaBinding" var replyReader = replyMessage.GetReaderAtBodyContents(); string actualResponse = replyReader.ReadElementContentAsString(); string expectedResponse = "[client] This is my request.[service] Request received, this is my Reply."; Assert.Equal(expectedResponse, actualResponse); // *** CLEANUP *** \\ replyMessage.Close(); channel.Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects(channel, factory); } }
public void SendRequestWithoutOpen() { CustomBinding b = CreateBinding(); IChannelFactory <IRequestChannel> f = b.BuildChannelFactory <IRequestChannel> (new BindingParameterCollection()); f.Open(); IRequestChannel ch = f.CreateChannel(CreateX509EndpointAddress("stream:dummy")); try { ch.Request(Message.CreateMessage(MessageVersion.Default, "myAction")); Assert.Fail("expected InvalidOperationException here."); } catch (InvalidOperationException) { } }
public static void IRequestChannel_Http_BasicHttpBinding() { try { BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None); // Create the channel factory IChannelFactory <IRequestChannel> factory = binding.BuildChannelFactory <IRequestChannel>( new BindingParameterCollection()); factory.Open(); // Create the channel. IRequestChannel channel = factory.CreateChannel( new EndpointAddress(Endpoints.HttpBaseAddress_Basic)); channel.Open(); // Create the Message object to send to the service. Message requestMessage = Message.CreateMessage( binding.MessageVersion, action, new CustomBodyWriter(clientMessage)); // Send the Message and receive the Response. Message replyMessage = channel.Request(requestMessage); // BasicHttpBinding uses SOAP1.1 which doesn't return the Headers.Action property in the Response // Therefore not validating this property as we do in the test "InvokeIRequestChannelCreatedViaBinding" var replyReader = replyMessage.GetReaderAtBodyContents(); string actualResponse = replyReader.ReadElementContentAsString(); string expectedResponse = "[client] This is my request.[service] Request received, this is my Reply."; if (!string.Equals(actualResponse, expectedResponse)) { Assert.True(false, String.Format("Actual MessageBodyContent from service did not match the expected MessageBodyContent, expected: {0} actual: {1}", expectedResponse, actualResponse)); } replyMessage.Close(); channel.Close(); factory.Close(); } catch (Exception ex) { Assert.True(false, String.Format("Unexpected exception was caught: {0}", ex.ToString())); } }
/// <summary> /// Gets a response from the IdP based on a message. /// </summary> /// <param name="endpoint">The IdP endpoint.</param> /// <param name="message">The message.</param> /// <param name="basicAuth">Basic auth settings.</param> /// <returns></returns> public Stream GetResponse(string endpoint, string message, HttpBasicAuthElement basicAuth) { Binding binding = CreateSslBinding(); Message request = Message.CreateMessage(binding.MessageVersion, HttpArtifactBindingConstants.SOAPAction, new SimpleBodyWriter(message)); request.Headers.To = new Uri(endpoint); HttpRequestMessageProperty property = new HttpRequestMessageProperty(); property.Method = "POST"; property.Headers.Add(HttpRequestHeader.ContentType, "text/xml; charset=utf-8"); //We are using Basic http auth over ssl if (basicAuth != null && basicAuth.Enabled) { string basicAuthzHeader = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(basicAuth.Username + ":" + basicAuth.Password)); property.Headers.Add(HttpRequestHeader.Authorization, basicAuthzHeader); } request.Properties.Add(HttpRequestMessageProperty.Name, property); if (_context.Request.Params["relayState"] != null) { request.Properties.Add("relayState", _context.Request.Params["relayState"]); } EndpointAddress epa = new EndpointAddress(endpoint); ChannelFactory <IRequestChannel> factory = new ChannelFactory <IRequestChannel>(binding, epa); IRequestChannel reqChannel = factory.CreateChannel(); reqChannel.Open(); Message response = reqChannel.Request(request); Console.WriteLine(response); reqChannel.Close(); XmlDocument xDoc = new XmlDocument(); xDoc.XmlResolver = null; xDoc.PreserveWhitespace = true; xDoc.Load(response.GetReaderAtBodyContents()); string outerXml = xDoc.DocumentElement.OuterXml; MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(outerXml)); return(memStream); }
public static void IRequestChannel_Https_NetHttpsBinding() { IChannelFactory <IRequestChannel> factory = null; IRequestChannel channel = null; Message replyMessage = null; try { // *** SETUP *** \\ NetHttpsBinding binding = new NetHttpsBinding(BasicHttpsSecurityMode.Transport); // Create the channel factory factory = binding.BuildChannelFactory <IRequestChannel>(new BindingParameterCollection()); factory.Open(); // Create the channel. channel = factory.CreateChannel(new EndpointAddress(Endpoints.HttpBaseAddress_NetHttps_Binary)); channel.Open(); // Create the Message object to send to the service. Message requestMessage = Message.CreateMessage( binding.MessageVersion, action, new CustomBodyWriter(clientMessage)); // *** EXECUTE *** \\ // Send the Message and receive the Response. replyMessage = channel.Request(requestMessage); // *** VALIDATE *** \\ var replyReader = replyMessage.GetReaderAtBodyContents(); string actualResponse = replyReader.ReadElementContentAsString(); string expectedResponse = "[client] This is my request.[service] Request received, this is my Reply."; Assert.Equal(expectedResponse, actualResponse); // *** CLEANUP *** \\ replyMessage.Close(); channel.Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects(channel, factory); } }
public void CustomTransportDoesNotRequireMessageEncoding() { ReplyHandler replier = delegate(Message msg) { resmsg = msg; }; RequestReceiver receiver = delegate() { return(reqmsg); }; RequestSender sender = delegate(Message msg) { reqmsg = msg; CustomBinding br = new CustomBinding( new HandlerTransportBindingElement(replier, receiver)); IChannelListener <IReplyChannel> l = br.BuildChannelListener <IReplyChannel> ( new BindingParameterCollection()); l.Open(); IReplyChannel rch = l.AcceptChannel(); rch.Open(); Message res = Message.CreateMessage(MessageVersion.Default, "urn:succeeded"); rch.ReceiveRequest().Reply(res); rch.Close(); l.Close(); return(resmsg); }; CustomBinding bs = new CustomBinding( new HandlerTransportBindingElement(sender)); IChannelFactory <IRequestChannel> f = bs.BuildChannelFactory <IRequestChannel> ( new BindingParameterCollection()); f.Open(); IRequestChannel ch = f.CreateChannel(new EndpointAddress("urn:dummy")); ch.Open(); Message result = ch.Request(Message.CreateMessage(MessageVersion.Default, "urn:request")); }
static void Main(string[] args) { Uri listenUri = new Uri("http://127.0.0.1:3721/listener"); Binding binding = new BasicHttpBinding(); IChannelFactory <IRequestChannel> channelFactory = binding.BuildChannelFactory <IRequestChannel>(); channelFactory.Open(); IRequestChannel channel = channelFactory.CreateChannel(new EndpointAddress(listenUri)); channel.Open(); Message replyMessage = channel.Request(CreateRequestMessage(binding)); Console.WriteLine(replyMessage); Console.Read(); }
static void Main(string[] args) { EndpointAddress address = new EndpointAddress("http://127.0.0.1:9999/messagingviabinding"); BasicHttpBinding binding = new BasicHttpBinding(); IChannelFactory <IRequestChannel> channelFactory = binding.BuildChannelFactory <IRequestChannel>(); channelFactory.Open(); IRequestChannel channel = channelFactory.CreateChannel(address); channel.Open(); Message requestMessage = Message.CreateMessage(MessageVersion.Soap11, "http://artech/messagingviabinding", "The is a request message manually created for the purpose of testing."); Message replyMessage = channel.Request(requestMessage); Console.WriteLine("Receive a reply message:\n{0}", replyMessage); channel.Close(); channelFactory.Close(); Console.Read(); }
static void RunClient() { //Step1: Create a binding with just HTTP. BindingElement[] bindingElements = new BindingElement[2]; bindingElements[0] = new TextMessageEncodingBindingElement(); bindingElements[1] = new HttpTransportBindingElement(); CustomBinding binding = new CustomBinding(bindingElements); //Step2: Use the binding to build the channel factory. IChannelFactory <IRequestChannel> factory = binding.BuildChannelFactory <IRequestChannel>( new BindingParameterCollection()); //Open the channel factory. factory.Open(); //Step3: Use the channel factory to create a channel. IRequestChannel channel = factory.CreateChannel( new EndpointAddress("http://localhost:8080/channelapp")); channel.Open(); //Step4: Create a message. Message requestmessage = Message.CreateMessage( binding.MessageVersion, "http://contoso.com/someaction", "This is the body data"); //Send message. Message replymessage = channel.Request(requestmessage); Console.WriteLine("Reply message received"); Console.WriteLine("Reply action: {0}", replymessage.Headers.Action); string data = replymessage.GetBody <string>(); Console.WriteLine("Reply content: {0}", data); //Step5: Do not forget to close the message. replymessage.Close(); //Do not forget to close the channel. channel.Close(); //Do not forget to close the factory. factory.Close(); }
public object Call(string op, string action, string[] varnames, object[] varvals, Type returntype) { requestChannel.Open(TimeSpan.MaxValue); //Message msg = //Message.CreateMessage(MessageVersion.<FromBinding>, // action, // new CustomBodyWriter(op, varnames, varvals, //"<ns passed in from Proxy>")); Message msg = Message.CreateMessage(this.messageVersion, action, new CustomBodyWriter(op, varnames, varvals, "<ns passed in from Proxy>")); Message reply = requestChannel.Request(msg, TimeSpan.MaxValue); System.Xml.XmlDictionaryReader reader = reply.GetReaderAtBodyContents(); reader.ReadToFollowing(op + "Result"); return(reader.ReadElementContentAs(returntype, null)); }
static void Main(string[] args) { MyBinding binding = new MyBinding(); IChannelFactory <IRequestChannel> channelFactory = binding.BuildChannelFactory <IRequestChannel>(); channelFactory.Open(); IRequestChannel channel = channelFactory.CreateChannel(new EndpointAddress("http://127.0.0.1:8888/messagingviabinding")); channel.Open(); Message requestMessage = Message.CreateMessage(MessageVersion.Soap12WSAddressing10, "http://artech.messagingviabinding", "This is a mannualy created reply message for the purpose of testing"); Message replyMessage = channel.Request(requestMessage); Console.WriteLine("Receive a reply message:\n{0}", replyMessage); channel.Close(); channelFactory.Close(); Console.Read(); }
public static void Snippet21() { // <Snippet21> BasicHttpBinding binding = new BasicHttpBinding(); EndpointAddress address = new EndpointAddress("http://localhost:8000/ChannelApp"); ChannelFactory <IRequestChannel> factory = new ChannelFactory <IRequestChannel>(binding, address); IRequestChannel channel = factory.CreateChannel(); channel.Open(); Message request = Message.CreateMessage(MessageVersion.Soap11, "hello"); Message reply = channel.Request(request); Console.Out.WriteLine(reply.Headers.Action); reply.Close(); channel.Close(); factory.Close(); }
public Message CallMethod(string methodName) { MemoryStream memoryStream = new MemoryStream(); StreamWriter streamWriter = new StreamWriter(memoryStream); streamWriter.Write(string.Format(@"<{0} xmlns=""{1}""></{0}>", methodName, targetNamespace)); streamWriter.Flush(); memoryStream.Position = 0; XmlDictionaryReader bodyReader = XmlDictionaryReader.CreateTextReader(memoryStream, new XmlDictionaryReaderQuotas()); string soapAction = string.Format("{0}{1}/{2}", targetNamespace, serviceName, methodName); serviceChannel.Open(); Message request = Message.CreateMessage(MessageVersion.Soap11, soapAction, bodyReader); Message reply = serviceChannel.Request(request); serviceChannel.Close(); return(reply); }
public void ProcessRequest(RequestContext context) { MessageHeaders headers = context.RequestMessage.Headers; //create new request channel if needed IRequestChannel requestChannel = null; if (!_Clients.TryGetValue(headers.To, out requestChannel)) { WSHttpBinding binding = CreateBinding(); IChannelFactory <IRequestChannel> factory = binding.BuildChannelFactory <IRequestChannel>(new BindingParameterCollection()); factory.Open(); requestChannel = factory.CreateChannel(new EndpointAddress(headers.To)); requestChannel.Open(); _Clients.Add(headers.To, requestChannel); } //forward request and send back response MessageContainer container = new MessageContainer(); Message incoming = CopyMessage(context.RequestMessage, container, MessageDirection.Incoming); if ((DateTime.Now - _LastReceived).TotalMilliseconds > 1750) { _Group += 1; } container.Group = _Group; _LastReceived = DateTime.Now; //add request to gui Action <int, MessageContainer> msg = new Action <int, MessageContainer>(Messages.Insert); this.Dispatcher.Invoke(msg, new object[] { 0, container }); //get response Message responseMessage = requestChannel.Request(incoming); Message outgoing = CopyMessage(responseMessage, container, MessageDirection.Outgoing); context.Reply(outgoing); }
static void Main(string[] args) { try { //建立自定义的通道栈 BindingElement[] bindingElements = new BindingElement[2]; bindingElements[0] = new TextMessageEncodingBindingElement(); //文本编码 bindingElements[1] = new HttpTransportBindingElement(); //HTTP传输 CustomBinding binding = new CustomBinding(bindingElements); using (Message message = Message.CreateMessage(binding.MessageVersion, "SendMessage", "Message Body")) { //创建ChannelFactory并打开 IChannelFactory <IRequestChannel> factory = binding.BuildChannelFactory <IRequestChannel>(new BindingParameterCollection()); factory.Open(); //创建IRequestChannel并打开 IRequestChannel requestChannel = factory.CreateChannel(new EndpointAddress("http://localhost:9090/RequestReplyService")); requestChannel.Open(); Message response = requestChannel.Request(message); //发送消息, 会阻塞线程等待服务端返回消息 Console.WriteLine("成功发送信息"); //查看返回消息 Console.WriteLine("接收到一条返回消息,action为:{0}, body为:{1}", response.Headers.Action, response.GetBody <string>()); requestChannel.Close(); //关闭通道 factory.Close(); //关闭工厂 } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { Console.WriteLine("press any key to exit..."); Console.ReadKey(); } }
/// <summary> /// 通过channel与服务端通信 /// </summary> static public void TestChannel() { BasicHttpBinding binding = new BasicHttpBinding(); CustomBinding cb = new CustomBinding(); BindingParameterCollection param = new BindingParameterCollection(); BindingContext bc = new BindingContext(cb, param); Message request = Message.CreateMessage(MessageVersion.Soap11, "http://tempuri.org/IHomeService/TestMessage", "gaofeng"); request.Headers.Add(MessageHeader.CreateHeader("ip", string.Empty, Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString())); IChannelFactory <IRequestChannel> factory = binding.BuildChannelFactory <IRequestChannel>(param); factory.Open(); IRequestChannel channel = factory.CreateChannel(new EndpointAddress("http://127.0.0.1:28200/HomeService")); channel.Open(); var res = channel.Request(request); Console.WriteLine("结果为:" + res.GetBody <int>()); channel.Close(); factory.Close(); }
public static void Custom_Message_RoundTrips() { BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None); // Create the channel factory IChannelFactory <IRequestChannel> factory = binding.BuildChannelFactory <IRequestChannel>(new BindingParameterCollection()); factory.Open(); // Create the channel. IRequestChannel channel = factory.CreateChannel(new EndpointAddress(Endpoints.HttpBaseAddress_Basic_Text)); channel.Open(); // Create the Message object to send to the service. using (Message requestMessage = Message.CreateMessage( binding.MessageVersion, action, new CustomBodyWriter(clientMessage))) { // Send the Message and receive the Response. using (Message replyMessage = channel.Request(requestMessage)) { Assert.False(replyMessage.IsFault); Assert.False(replyMessage.IsEmpty); Assert.Equal(MessageState.Created, replyMessage.State); Assert.Equal(MessageVersion.Soap11, replyMessage.Version); var replyReader = replyMessage.GetReaderAtBodyContents(); string actualResponse = replyReader.ReadElementContentAsString(); string expectedResponse = "Test Custom_Message_RoundTrips.[service] Request received, this is my Reply."; Assert.True(string.Equals(actualResponse, expectedResponse), string.Format("Actual MessageBodyContent from service did not match the expected MessageBodyContent, expected: {0} actual: {1}", expectedResponse, actualResponse)); } } channel.Close(); factory.Close(); }
static void RunClient() { //Step1: create a binding with just HTTP CustomBinding binding = new CustomBinding(); binding.Elements.Add(new HttpTransportBindingElement()); //Step2: use the binding to build the channel factory IChannelFactory <IRequestChannel> factory = binding.BuildChannelFactory <IRequestChannel>( new BindingParameterCollection()); //open the channel factory factory.Open(); //Step3: use the channel factory to create a channel IRequestChannel channel = factory.CreateChannel( new EndpointAddress("http://localhost:8080/channelapp")); channel.Open(); //Step4: create a message Message requestmessage = Message.CreateMessage( MessageVersion.Soap12WSAddressing10, "http://contoso.com/someaction", "This is the body data"); //send message Message replymessage = channel.Request(requestmessage); Console.WriteLine("Reply message received"); Console.WriteLine("Reply action: {0}", replymessage.Headers.Action); string data = replymessage.GetBody <string>(); Console.WriteLine("Reply content: {0}", data); //Step5: don't forget to close the message requestmessage.Close(); replymessage.Close(); //don't forget to close the channel channel.Close(); //don't forget to close the factory factory.Close(); }