public virtual void OneWayAttachment(OneWayAttachmentRequest req)
        {
            // Create request header
            String action;

            action = "http://schemas.example.org/AttachmentService/OneWayAttachment";
            WsWsaHeader header;

            header = new WsWsaHeader(action, null, EndpointAddress, m_version.AnonymousUri, null, null);
            WsMessage request = new WsMessage(header, req, WsPrefix.None);

            // Create request serializer
            OneWayAttachmentRequestDataContractSerializer reqDcs;

            reqDcs             = new OneWayAttachmentRequestDataContractSerializer("OneWayAttachmentRequest", "http://schemas.example.org/AttachmentService");
            request.Serializer = reqDcs;
            request.Method     = "OneWayAttachment";


            // Indicate that this message will use Mtom encoding
            request.BodyParts = new WsMtomBodyParts();

            // Send service request
            m_requestChannel.Open();
            m_requestChannel.RequestOneWay(request);
            m_requestChannel.Close();
        }
Example #2
0
        public Message ProcessMessaage(Message request)
        {
            ModuleProc      PROC    = new ModuleProc(this.DYN_MODULE_NAME, "ProcessMessage");
            Message         result  = default(Message);
            IRequestChannel channel = null;

            try
            {
                channel = _factory.CreateChannel(this.TargetFinder.GetAddress(request));
                channel.Open();
                result = channel.Request(request);
            }
            catch (Exception ex)
            {
                Log.Exception(PROC, ex);
            }
            finally
            {
                if (channel != null && channel.State == CommunicationState.Opened)
                {
                    channel.Close();
                }
            }

            return(result);
        }
Example #3
0
 static void Main(string[] args)
 {
     try
     {        //使用说明先启动input,然后在启动启动output。
         //记得使用管理员启动VS,我在程序清单中添加了管理员权限。
         //创建自定义通道
         BindingElement[] bindingElements = new BindingElement[2];
         bindingElements[0] = new TextMessageEncodingBindingElement(); //文本编码
         bindingElements[1] = new HttpTransportBindingElement();       //Htp传输
         CustomBinding binding = new CustomBinding(bindingElements);
         using (Message message = Message.CreateMessage(binding.MessageVersion, "sendMessage", "Message Body"))
         {
             //创建ChannelFactory request 请求 reply回复
             IChannelFactory <IRequestChannel> factory = binding.BuildChannelFactory <IRequestChannel>(new BindingParameterCollection());
             factory.Open();        //打开ChannelFactory
                                    //这里创建IRequestChannel
             IRequestChannel requestChannel = factory.CreateChannel(new System.ServiceModel.EndpointAddress("http://localhost:9090/RequestReplyService"));
             requestChannel.Open(); //打开通道
             Message response = requestChannel.Request(message);
             //发送消息
             Console.WriteLine("已经成功发送消息!");
             //查看返回消息
             Console.WriteLine($"接收到一条返回消息,action为:{response.Headers.Action},body为{response.GetBody<String>()}");
             requestChannel.Close(); //关闭通道
             factory.Close();        //关闭工厂
         }
     }
     catch (Exception ex)
     { Console.WriteLine(ex.ToString()); }
     finally
     {
         Console.Read();
     }
 }
Example #4
0
    public static void Main()
    {
        HttpTransportBindingElement el =
            new HttpTransportBindingElement();
        IChannelFactory <IRequestChannel> factory =
            el.BuildChannelFactory <IRequestChannel> (
                new BindingContext(new CustomBinding(),
                                   new BindingParameterCollection()));

        factory.Open();

        IRequestChannel request = factory.CreateChannel(
            new EndpointAddress("http://localhost:37564"));

        request.Open();

        using (XmlWriter w = XmlWriter.Create(Console.Out)) {
            Message.CreateMessage(MessageVersion.Default, "Echo")
            .WriteMessage(w);
        }
        Console.WriteLine();

        Message msg = request.Request(
            Message.CreateMessage(MessageVersion.Default, "Echo"),
            TimeSpan.FromSeconds(15));

        using (XmlWriter w = XmlWriter.Create(Console.Out)) {
            msg.WriteMessage(w);
        }
    }
    [Issue(1398, OS = OSID.AnyOSX)] // Cert installation on OSX does not work yet
    public static void IRequestChannel_Https_NetHttpsBinding()
    {
#if FULLXUNIT_NOTSUPPORTED
        bool root_Certificate_Installed = Root_Certificate_Installed();
        bool ssl_Available = SSL_Available();

        if (!root_Certificate_Installed ||
            !ssl_Available)
        {
            Console.WriteLine("---- Test SKIPPED --------------");
            Console.WriteLine("Attempting to run the test in ToF, a ConditionalFact evaluated as FALSE.");
            Console.WriteLine("Root_Certificate_Installed evaluated as {0}", root_Certificate_Installed);
            Console.WriteLine("SSL_Available evaluated as {0}", ssl_Available);
            return;
        }
#endif
        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));
            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);
        }
    }
Example #6
0
    public static void Main()
    {
        var b = new BasicHttpBinding();

        b.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
        b.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
        var cc = new ClientCredentials();

        cc.UserName.UserName = "******";
        IChannelFactory <IRequestChannel> cf = b.BuildChannelFactory <IRequestChannel> (cc);

        cf.Open();
        IRequestChannel req = cf.CreateChannel(
            new EndpointAddress("http://localhost:8080/"));

        Console.WriteLine(cf.GetProperty <ClientCredentials> ());
        req.Open();
        Message msg = Message.CreateMessage(MessageVersion.Soap11, "http://tempuri.org/IFoo/Echo", new EchoType("hoge"));

        //Message ret = req.Request (msg);
        IAsyncResult result = req.BeginRequest(msg, null, null);
        //return;
        Message ret = req.EndRequest(result);

        using (XmlWriter w = XmlWriter.Create(Console.Out)) {
            ret.WriteMessage(w);
        }
    }
Example #7
0
        /// <summary>
        /// Makes a WSTrust call to the STS to obtain a <see cref="SecurityToken"/> first checking if the token is available in the cache.
        /// </summary>
        /// <returns>A <see cref="GenericXmlSecurityToken"/>.</returns>
        protected override SecurityToken GetTokenCore(TimeSpan timeout)
        {
            _communicationObject.ThrowIfClosedOrNotOpen();
            WsTrustRequest  request       = CreateWsTrustRequest();
            WsTrustResponse trustResponse = GetCachedResponse(request);

            if (trustResponse is null)
            {
                using (var memeoryStream = new MemoryStream())
                {
                    var writer     = XmlDictionaryWriter.CreateTextWriter(memeoryStream, Encoding.UTF8);
                    var serializer = new WsTrustSerializer();
                    serializer.WriteRequest(writer, _requestSerializationContext.TrustVersion, request);
                    writer.Flush();
                    var             reader  = XmlDictionaryReader.CreateTextReader(memeoryStream.ToArray(), XmlDictionaryReaderQuotas.Max);
                    IRequestChannel channel = ChannelFactory.CreateChannel();
                    try
                    {
                        channel.Open();
                        Message reply = channel.Request(Message.CreateMessage(MessageVersion.Soap12WSAddressing10, _requestSerializationContext.TrustActions.IssueRequest, reader));
                        SecurityUtils.ThrowIfNegotiationFault(reply, channel.RemoteAddress);
                        trustResponse = serializer.ReadResponse(reply.GetReaderAtBodyContents());
                        CacheSecurityTokenResponse(request, trustResponse);
                    }
                    finally
                    {
                        channel.Close();
                    }
                }
            }

            return(WSTrustUtilities.CreateGenericXmlSecurityToken(request, trustResponse, _requestSerializationContext, _securityAlgorithmSuite));
        }
        public void OpenRequestNonAuthenticatable()
        {
            SymmetricSecurityBindingElement sbe =
                new SymmetricSecurityBindingElement();

            sbe.ProtectionTokenParameters =
                new UserNameSecurityTokenParameters();
            Binding binding = new CustomBinding(sbe, new HandlerTransportBindingElement(null));
            BindingParameterCollection pl =
                new BindingParameterCollection();
            ClientCredentials cred = new ClientCredentials();

            cred.UserName.UserName = "******";
            pl.Add(cred);
            IChannelFactory <IRequestChannel> f =
                binding.BuildChannelFactory <IRequestChannel> (pl);

            f.Open();
            IRequestChannel ch = f.CreateChannel(new EndpointAddress("stream:dummy"));

            try {
                ch.Open();
                Assert.Fail("NotSupportedException is expected.");
            } catch (NotSupportedException) {
            }
        }
Example #9
0
        public static void Snippet3()
        {
            // <Snippet3>
            CustomBinding binding = new CustomBinding();

            binding.Elements.Add(new HttpTransportBindingElement());
            Object[] bindingParams = new Object[2];

            // <Snippet30>
            IChannelFactory <IRequestChannel> factory = binding.BuildChannelFactory <IRequestChannel>(bindingParams);

            factory.Open();
            EndpointAddress address = new EndpointAddress("http://localhost:8000/ChannelApp");
            IRequestChannel channel = factory.CreateChannel(address);

            channel.Open();
            // </Snippet30>

            Message request = Message.CreateMessage(MessageVersion.Default, "hello");
            Message reply   = channel.Request(request);

            Console.Out.WriteLine(reply.Headers.Action);
            reply.Close();
            channel.Close();
            factory.Close();
            // </Snippet3>
        }
Example #10
0
        public static void Snippet33()
        {
            CustomBinding binding = new CustomBinding();

            binding.Elements.Add(new HttpTransportBindingElement());
            Object[] bindingParams = new Object[2];

            // <Snippet33>

            EndpointAddress address = new EndpointAddress("http://localhost:8000/ChannelApp");
            Uri             uri     = new Uri("http://localhost:8000/Via");

            IRequestChannel channel =
                ChannelFactory <IRequestChannel> .CreateChannel(binding, address, uri);

            channel.Open();
            // </Snippet33>

            Message request = Message.CreateMessage(MessageVersion.Default, "hello");
            Message reply   = channel.Request(request);

            Console.Out.WriteLine(reply.Headers.Action);
            reply.Close();
            channel.Close();
        }
Example #11
0
 //入口方法
 static void Main(string[] args)
 {
     try
     {
         //建立自定义的通道栈
         BindingElement[] bindingElements = new BindingElement[2];
         bindingElements[0] = new TextMessageEncodingBindingElement();
         bindingElements[1] = new HttpTransportBindingElement();
         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/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.Read();
     }
 }
        public virtual HelloWCFResponse HelloWCF(HelloWCF req)
        {
            // Create request header
            String action;

            action = "http://localhost/ServiceHelloWCF/IServiceHelloWCF/HelloWCF";
            WsWsaHeader header;

            header = new WsWsaHeader(action, null, EndpointAddress, m_version.AnonymousUri, null, null);
            WsMessage request = new WsMessage(header, req, WsPrefix.None);

            // Create request serializer
            HelloWCFDataContractSerializer reqDcs;

            reqDcs             = new HelloWCFDataContractSerializer("HelloWCF", "http://localhost/ServiceHelloWCF");
            request.Serializer = reqDcs;
            request.Method     = "HelloWCF";


            // Send service request
            m_requestChannel.Open();
            WsMessage response = m_requestChannel.Request(request);

            m_requestChannel.Close();

            // Process response
            HelloWCFResponseDataContractSerializer respDcs;

            respDcs = new HelloWCFResponseDataContractSerializer("HelloWCFResponse", "http://localhost/ServiceHelloWCF");
            HelloWCFResponse resp;

            resp = ((HelloWCFResponse)(respDcs.ReadObject(response.Reader)));
            return(resp);
        }
        public void FullRequest()
        {
            EndpointIdentity identity =
                new X509CertificateEndpointIdentity(new X509Certificate2("Test/Resources/test.pfx", "mono"));
            EndpointAddress address =
                new EndpointAddress(new Uri("stream:dummy"), identity);

            Message mreq   = Message.CreateMessage(MessageVersion.Default, "myAction");
            Message mreply = null;

            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Indent = true;

            // listener setup
            ReplyHandler replyHandler = delegate(Message rinput)
            {
                mreply = rinput;
            };
            RequestReceiver receiver = delegate()
            {
                return(mreq);
            };
            IChannelListener <IReplyChannel> listener = CreateListener(replyHandler, receiver);

            listener.Open();
            IReplyChannel reply = listener.AcceptChannel();

            reply.Open();

            RequestSender reqHandler = delegate(Message input)
            {
                try
                {
                    // sync version somehow causes an infinite loop (!?)
                    RequestContext ctx = reply.EndReceiveRequest(reply.BeginReceiveRequest(TimeSpan.FromSeconds(5), null, null));
//					RequestContext ctx = reply.ReceiveRequest (TimeSpan.FromSeconds (5));
                    Console.Error.WriteLine("Acquired RequestContext.");
                    ctx.Reply(input);
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine("ERROR during processing a request in FullRequest()");
                    Console.Error.WriteLine(ex);
                    Console.Error.Flush();
                    throw;
                }
                return(mreply);
            };
            CustomBinding b = CreateBinding(reqHandler);

            IRequestChannel ch = ChannelFactory <IRequestChannel> .CreateChannel(b, address);

            ch.Open();
            Console.Error.WriteLine("**** starting a request  ****");
            IAsyncResult async = ch.BeginRequest(mreq, null, null);

            Console.Error.WriteLine("**** request started. ****");
            Message res = ch.EndRequest(async);
        }
        public void SendRequestWithoutSignatureMessagePart()
        {
            CustomBinding b = CreateBinding();

            // without ChannelProtectionRequirements it won't be
            // signed and/or encrypted.
            IChannelFactory <IRequestChannel> f =
                b.BuildChannelFactory <IRequestChannel> (new BindingParameterCollection());

            f.Open();
            IRequestChannel ch = f.CreateChannel(CreateX509EndpointAddress("stream:dummy"));

            ch.Open();
            // MessageSecurityException : No signature message parts
            // were specified for messages with the 'myAction'
            // action.
            try
            {
                ch.Request(Message.CreateMessage(b.MessageVersion, "myAction"));
                Assert.Fail("MessageSecurityException is expected here.");
            }
            catch (MessageSecurityException)
            {
            }
        }
        /// <summary>
        /// Called by for each active event sink to send an event message to a listening client.
        /// </summary>
        /// <param name="eventMessage">Byte array containing the event message soap envelope.</param>
        /// <param name="notifyToAddress"></param>
        private void SendEvent(WsMessage eventMessage, Uri notifyToAddress)
        {
            // Parse the http transport address
            m_binding.Transport.EndpointAddress = notifyToAddress;

            m_reqChannel.Open();
            m_reqChannel.RequestOneWay(eventMessage);
            m_reqChannel.Close();
        }
Example #16
0
        public void MessageSecurityManualProtection()
        {
            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(),
                new HandlerTransportBindingElement(sender));

            EndpointAddress address = new EndpointAddress(
                new Uri("http://localhost:8080"),
                new X509CertificateEndpointIdentity(new X509Certificate2("Test/Resources/test.pfx", "mono")));

            ChannelProtectionRequirements reqs =
                new ChannelProtectionRequirements();

            reqs.OutgoingSignatureParts.AddParts(
                new MessagePartSpecification(new XmlQualifiedName("SampleValue", "urn:foo")), "urn:myaction");
            BindingParameterCollection parameters =
                new BindingParameterCollection();

            parameters.Add(reqs);

/*
 *                      SymmetricSecurityBindingElement innersbe =
 *                              new SymmetricSecurityBindingElement ();
 *                      innersbe.ProtectionTokenParameters =
 *                              new X509SecurityTokenParameters ();
 *                      sbe.ProtectionTokenParameters =
 *                              new SecureConversationSecurityTokenParameters (
 *                                      innersbe, false, reqs);
 */

            IChannelFactory <IRequestChannel> cf =
                binding.BuildChannelFactory <IRequestChannel> (parameters);

            cf.Open();
            IRequestChannel ch = cf.CreateChannel(address);

            ch.Open();
            try {
                ch.Request(Message.CreateMessage(MessageVersion.None, "urn:myaction", new SampleValue()));
            } finally {
                ch.Close();
            }
        }
Example #17
0
    public static void ChannelShape_TypedProxy_InvokeIRequestChannelAsync()
    {
        string        address      = Endpoints.DefaultCustomHttp_Address;
        StringBuilder errorBuilder = new StringBuilder();

        try
        {
            CustomBinding binding = new CustomBinding(new BindingElement[] {
                new TextMessageEncodingBindingElement(MessageVersion.Default, Encoding.UTF8),
                new HttpTransportBindingElement()
            });

            EndpointAddress endpointAddress = new EndpointAddress(address);

            // Create the channel factory for the request-reply message exchange pattern.
            var factory = new ChannelFactory <IRequestChannel>(binding, endpointAddress);

            // Create the channel.
            IRequestChannel channel = factory.CreateChannel();
            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.
            IAsyncResult ar           = channel.BeginRequest(requestMessage, null, null);
            Message      replyMessage = channel.EndRequest(ar);

            string replyMessageAction = replyMessage.Headers.Action;

            if (!string.Equals(replyMessageAction, action + "Response"))
            {
                errorBuilder.AppendLine(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))
            {
                errorBuilder.AppendLine(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)
        {
            errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString()));
        }

        Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: InvokeIRequestChannelViaProxyAsync FAILED with the following errors: {0}", errorBuilder));
    }
Example #18
0
        private GenericXmlSecurityToken DoOperation(SecuritySessionOperation operation, EndpointAddress target, Uri via, SecurityToken currentToken, TimeSpan timeout)
        {
            GenericXmlSecurityToken token2;

            if (target == null)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("target");
            }
            if ((operation == SecuritySessionOperation.Renew) && (currentToken == null))
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("currentToken");
            }
            IRequestChannel channel = null;

            try
            {
                object obj2;
                GenericXmlSecurityToken token;
                SecurityTraceRecordHelper.TraceBeginSecuritySessionOperation(operation, target, currentToken);
                channel = this.CreateChannel(operation, target, via);
                TimeoutHelper helper = new TimeoutHelper(timeout);
                channel.Open(helper.RemainingTime());
                using (Message message = this.CreateRequest(operation, target, currentToken, out obj2))
                {
                    TraceUtility.ProcessOutgoingMessage(message);
                    using (Message message2 = channel.Request(message, helper.RemainingTime()))
                    {
                        if (message2 == null)
                        {
                            throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString("FailToRecieveReplyFromNegotiation")));
                        }
                        TraceUtility.ProcessIncomingMessage(message2);
                        ThrowIfFault(message2, this.targetAddress);
                        token = this.ProcessReply(message2, operation, obj2);
                        this.ValidateKeySize(token);
                    }
                }
                channel.Close(helper.RemainingTime());
                this.OnOperationSuccess(operation, target, token, currentToken);
                token2 = token;
            }
            catch (Exception exception)
            {
                if (Fx.IsFatal(exception))
                {
                    throw;
                }
                if (exception is TimeoutException)
                {
                    exception = new TimeoutException(System.ServiceModel.SR.GetString("ClientSecuritySessionRequestTimeout", new object[] { timeout }), exception);
                }
                this.OnOperationFailure(operation, target, currentToken, exception, channel);
                throw;
            }
            return(token2);
        }
    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 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);
        }
        public void OpenRequestWithDefaultServiceCertificate()
        {
            IChannelFactory <IRequestChannel> f =
                CreateDefaultServiceCertFactory();

            f.Open();
            // This EndpointAddress does not contain X509 identity
            IRequestChannel ch = f.CreateChannel(new EndpointAddress("stream:dummy"));

            ch.Open();
            // stop here.
        }
    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);
        }
    }
        //  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();
            }
        }
        [Category("NotWorking")]          // it depends on Kerberos
        public void OpenRequestWithoutServiceCertificateForNonX509()
        {
            CustomBinding b = CreateBinding(new MyOwnSecurityTokenParameters());

            IChannelFactory <IRequestChannel> f =
                b.BuildChannelFactory <IRequestChannel> (new BindingParameterCollection());

            f.Open();
            // This EndpointAddress does not contain X509 identity
            IRequestChannel ch = f.CreateChannel(new EndpointAddress("stream:dummy"));

            ch.Open();
        }
        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"));
        }
Example #26
0
        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;
        }
Example #27
0
        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);
        }
Example #28
0
        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 void OneWay(OneWayRequest req)
        {
            // Create request header
            String action;

            action = "http://schemas.example.org/SimpleService/OneWay";
            WsWsaHeader header;

            header = new WsWsaHeader(action, null, EndpointAddress, m_version.AnonymousUri, null, null);
            WsMessage request = new WsMessage(header, req, WsPrefix.None);

            // Create request serializer
            OneWayRequestDataContractSerializer reqDcs;

            reqDcs             = new OneWayRequestDataContractSerializer("OneWayRequest", "http://schemas.example.org/SimpleService");
            request.Serializer = reqDcs;
            request.Method     = "OneWay";


            // Send service request
            m_requestChannel.Open();
            m_requestChannel.RequestOneWay(request);
            m_requestChannel.Close();
        }
    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);
        }
    }