Exemplo n.º 1
0
        private static TResult InternalSingleCall <TChannel, TResult>(ChannelFactory <TChannel> factory, Func <TChannel, TResult> func)
        {
            TChannel channel = factory.CreateChannel();
            TResult  result  = default(TResult);

            try
            {
                if (func != null)
                {
                    result = func(channel);
                }

                factory.Close();

                return(result);
            }
            catch (CommunicationException)
            {
                factory.Abort();
                throw;
            }
            catch (TimeoutException)
            {
                factory.Abort();
                throw;
            }
            catch (System.Exception)
            {
                factory.Abort();
                throw;
            }
        }
Exemplo n.º 2
0
        private static void InternalSingleCall <TChannel>(ChannelFactory <TChannel> factory, Action <TChannel> action)
        {
            TChannel channel = factory.CreateChannel();

            try
            {
                if (action != null)
                {
                    action(channel);
                }

                factory.Close();
            }
            catch (CommunicationException)
            {
                factory.Abort();
                throw;
            }
            catch (TimeoutException)
            {
                factory.Abort();
                throw;
            }
            catch (System.Exception)
            {
                factory.Abort();
                throw;
            }
        }
Exemplo n.º 3
0
 protected virtual void Dispose(bool disposing)
 {
     if (!_isDisposed)
     {
         if (disposing)
         {
             if (_channelFactory != null)
             {
                 if (_channelFactory.State != CommunicationState.Faulted)
                 {
                     try
                     {
                         _channelFactory.Close();
                     }
                     catch
                     {
                         _channelFactory.Abort();
                     }
                 }
                 else
                 {
                     _channelFactory.Abort();
                 }
             }
         }
     }
     _isDisposed = true;
 }
Exemplo n.º 4
0
        public static IAnimalService GetAnimalService(string http)
        {
            ChannelFactory <IAnimalService> channelFactory = null;

            try
            {
                // Create a binding of the type exposed by service
                BasicHttpBinding httpBinding = new BasicHttpBinding();

                // EndPoint address
                EndpointAddress endpointAddress = new EndpointAddress(http);

                // Pass Binding and EndPoint address to ChannelFactory using httpBinding
                channelFactory = new ChannelFactory <IAnimalService>(httpBinding, endpointAddress);

                // Now create the new channel as below
                IAnimalService channel = channelFactory.CreateChannel();

                return(channel);
            }
            catch (TimeoutException)
            {
                // Timeout error
                if (channelFactory != null)
                {
                    channelFactory.Abort();
                }

                throw;
            }
            catch (FaultException)
            {
                if (channelFactory != null)
                {
                    channelFactory.Abort();
                }

                throw;
            }
            catch (CommunicationException)
            {
                // Communication error
                if (channelFactory != null)
                {
                    channelFactory.Abort();
                }

                throw;
            }
            catch (Exception)
            {
                if (channelFactory != null)
                {
                    channelFactory.Abort();
                }

                throw;
            }
        }
Exemplo n.º 5
0
        private async Task ForwardMessageAsync(MqttMsgEventArgs e)
        {
            await Task.Run(() =>
            {
                ChannelFactory <IGenericOneWayContract> factory = null;
                try
                {
                    var binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
                    var se      = new ServiceEndpoint(ContractDescription.GetContract(typeof(IGenericOneWayContract)), binding, new EndpointAddress(this._configData.TesterAddress));
                    factory     = new ChannelFactory <IGenericOneWayContract>(se);
                    var channel = factory.CreateChannel();

                    using (var scope = new OperationContextScope((IContextChannel)channel))
                    {
                        var message = Message.CreateMessage(MessageVersion.Soap12WSAddressing10, "*", JsonConvert.SerializeObject(e));
                        message.Headers.Add(MessageHeader.CreateHeader(ConfigData.XName.LocalName, ConfigData.XName.NamespaceName, this._configData));
                        channel.ProcessMessage(message);

                        Trace.WriteLine("VirtualService: --- Message has been sent to tester ---");
                    }
                    factory.Close();
                }
                catch (CommunicationException ex)
                {
                    if (factory != null)
                    {
                        if (factory.State == CommunicationState.Faulted)
                        {
                            factory.Abort();
                        }
                        else if (factory.State != CommunicationState.Closed)
                        {
                            factory.Close();
                        }
                        factory = null;
                    }
                    Trace.WriteLine(ex.InnerException == null ? ex.Message : ex.InnerException.Message);
                }
                catch (Exception ex)
                {
                    if (factory != null)
                    {
                        if (factory.State == CommunicationState.Faulted)
                        {
                            factory.Abort();
                        }
                        else if (factory.State != CommunicationState.Closed)
                        {
                            factory.Close();
                        }
                        factory = null;
                    }
                    Trace.WriteLine(ex.InnerException == null ? ex.Message : ex.InnerException.Message);
                }
            });
        }
Exemplo n.º 6
0
        public void Abort()
        {
            if (_infoService == null)
            {
                return;
            }

            _infoService.Abort();
            _channelFactory.Abort();
        }
 public void Dispose()
 {
     try
     {
         channelFactory.Close();
     }
     catch (TimeoutException)
     {
         channelFactory.Abort();
     }
     catch (CommunicationException)
     {
         channelFactory.Abort();
     }
 }
Exemplo n.º 8
0
        protected virtual void ExecuteNamedPipeAction(EndpointAddress ep, Action <T> executeAction, int retryTimes, Action <string> failure)
        {
            bool   finished   = false;
            string failureMsg = "";

            while (retryTimes > 0 && !finished)
            {
                InitializeClient(ep, () =>
                {
                    try
                    {
                        executeAction(_Proxy);
                        _Factory.Close();
                        finished = true;
                    }
                    catch (CommunicationException eX)
                    {
                        eX.Exception();
                        _Factory.Abort();
                        retryTimes--;
                        failureMsg = eX.Message;
                    }
                    catch (TimeoutException eX)
                    {
                        eX.Exception();
                        _Factory.Abort();
                        retryTimes--;
                        failureMsg = eX.Message;
                    }
                    catch (Exception eX)
                    {
                        _Factory.Abort();
                        eX.Exception();
                        retryTimes--;
                        failureMsg = eX.Message;
                    }
                }, (msg) =>
                {
                    failureMsg = msg;
                    retryTimes--;
                });
            }

            if (!finished)
            {
                failure(failureMsg);
            }
        }
        public void RequestReply_TelemetryIsWritten()
        {
            TestTelemetryChannel.Clear();
            using (var host = new HostingContext <SimpleService, ISimpleService>())
            {
                host.Open();

                var            binding       = new NetTcpBinding();
                var            configuration = new TelemetryConfiguration();
                var            factory       = new ChannelFactory <ISimpleService>(binding, host.GetServiceAddress());
                ISimpleService channel       = null;
                try
                {
                    var behavior = new ClientTelemetryEndpointBehavior(configuration);
                    factory.Endpoint.EndpointBehaviors.Add(behavior);

                    channel = factory.CreateChannel();
                    channel.GetSimpleData();
                    ((IClientChannel)channel).Close();
                    factory.Close();

                    Assert.IsTrue(TestTelemetryChannel.CollectedData().Count > 0, "No telemetry events written");
                }
                catch
                {
                    if (channel != null)
                    {
                        ((IClientChannel)channel).Abort();
                    }

                    factory.Abort();
                    throw;
                }
            }
        }
Exemplo n.º 10
0
        public IList <User> GetUsersByRealName(string keyword, out int count, int pageIndex = 1, int pageSize = 50, int groupId = 0)
        {
            count = 0;
            IList <User> users = new List <User>();

            if (keyword == "")
            {
                return(null);
            }
            else
            {
                using (var factory = new ChannelFactory <IAuthenticationService>("authentication"))
                {
                    try
                    {
                        var service = factory.CreateChannel();
                        users = service.GetUsersByRealName(keyword, pageIndex, pageSize, out count);
                    }
                    finally
                    {
                        factory.Abort();
                    }
                }
                return(users);
            }
        }
Exemplo n.º 11
0
    public static void DefaultSettings_Echo_RoundTrips_String_Streamed()
    {
        string        testString   = "Hello";
        StringBuilder errorBuilder = new StringBuilder();

        BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None);

        binding.TransferMode = TransferMode.Streamed;
        ChannelFactory <IWcfService> factory = new ChannelFactory <IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
        IWcfService serviceProxy             = factory.CreateChannel();

        try
        {
            Stream stream       = StringToStream(testString);
            var    returnStream = serviceProxy.EchoStream(stream);
            var    result       = StreamToString(returnStream);
            Assert.Equal(testString, result);
        }
        catch (System.ServiceModel.CommunicationException e)
        {
            errorBuilder.AppendLine(string.Format("Unexpected exception thrown: '{0}'", e.ToString()));
            PrintInnerExceptionsHresult(e, errorBuilder);
        }
        finally
        {
            if (factory != null && factory.State != CommunicationState.Closed)
            {
                factory.Abort();
            }
        }

        Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: DefaultSettings_Echo_RoundTrips_String_Streamed FAILED with the following errors: {0}", errorBuilder));
    }
Exemplo n.º 12
0
    public static void DefaultSettings_Echo_RoundTrips_String_Buffered()
    {
        string testString = "Hello";

        BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None);

        binding.TransferMode = TransferMode.Buffered;
        ChannelFactory <IWcfService> factory = new ChannelFactory <IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
        IWcfService serviceProxy             = factory.CreateChannel();

        try
        {
            Stream stream       = StringToStream(testString);
            var    returnStream = serviceProxy.EchoStream(stream);
            var    result       = StreamToString(returnStream);
            Assert.Equal(testString, result);
        }
        finally
        {
            if (factory != null && factory.State != CommunicationState.Closed)
            {
                factory.Abort();
            }
        }
    }
Exemplo n.º 13
0
    public static void ChannelFactory_Async_Open_Close()
    {
        ChannelFactory <IRequestChannel> factory = null;

        try
        {
            BasicHttpBinding binding = new BasicHttpBinding();

            // Create the channel factory
            factory = new ChannelFactory <IRequestChannel>(binding, new EndpointAddress(FakeAddress.HttpAddress));
            Assert.True(CommunicationState.Created == factory.State,
                        string.Format("factory.State - Expected: {0}, Actual: {1}.", CommunicationState.Created, factory.State));

            Task.Factory.FromAsync(factory.BeginOpen(null, null), factory.EndOpen).GetAwaiter().GetResult();
            Assert.True(CommunicationState.Opened == factory.State,
                        string.Format("factory.State - Expected: {0}, Actual: {1}.", CommunicationState.Opened, factory.State));

            Task.Factory.FromAsync(factory.BeginClose(null, null), factory.EndClose).GetAwaiter().GetResult();
            Assert.True(CommunicationState.Closed == factory.State,
                        string.Format("factory.State - Expected: {0}, Actual: {1}.", CommunicationState.Closed, factory.State));
        }
        finally
        {
            if (factory != null && factory.State != CommunicationState.Closed)
            {
                factory.Abort();
            }
        }
    }
Exemplo n.º 14
0
        /// <summary>
        /// Called by <see cref="DataPortal" /> to create a
        /// new business object.
        /// </summary>
        /// <param name="objectType">Type of business object to create.</param>
        /// <param name="criteria">Criteria object describing business object.</param>
        /// <param name="context">
        /// <see cref="Server.DataPortalContext" /> object passed to the server.
        /// </param>
        public DataPortalResult Create(Type objectType, object criteria, DataPortalContext context)
        {
            ChannelFactory <IWcfPortal> cf = GetChannelFactory();
            IWcfPortal  svr      = GetProxy(cf);
            WcfResponse response = null;

            try
            {
                response =
                    svr.Create(new CreateRequest(objectType, criteria, context));
                if (cf != null)
                {
                    cf.Close();
                }
            }
            catch
            {
                cf.Abort();
                throw;
            }
            object result = response.Result;

            if (result is Exception)
            {
                throw (Exception)result;
            }
            return((DataPortalResult)result);
        }
Exemplo n.º 15
0
        /// <summary>
        /// 根据用户uid的list获得对应的用户的list  liujingjie
        /// </summary>
        /// <param name="userIds"></param>
        /// <returns></returns>
        public IList <User> GetUsersByUserIds(IList <string> userIds)
        {
            IList <User> users = new List <User>();

            if (userIds == null || userIds.Count == 0)
            {
                return(null);
            }
            else
            {
                using (var factory = new ChannelFactory <IAuthenticationService>("authentication"))
                {
                    try
                    {
                        var service = factory.CreateChannel();
                        users = service.GetUsersByUserIds(userIds);
                    }
                    finally
                    {
                        factory.Abort();
                    }
                }
                return(users);
            }
        }
Exemplo n.º 16
0
        public static void Using <T>(Action <T> action)
        {
            BasicHttpBinding   bindnig     = new BasicHttpBinding();
            string             endpointUri = GetServiceEndpoint(typeof(T));
            ChannelFactory <T> factory     = new ChannelFactory <T>(bindnig, new EndpointAddress(new Uri(endpointUri)));

            //ChannelFactory<T> factory = new ChannelFactory<T>("*");

            T client = factory.CreateChannel();

            try
            {
                action(client);
                ((IClientChannel)client).Close();
                factory.Close();
            }
            catch (Exception ex)
            {
                IClientChannel clientInstance = ((IClientChannel)client);
                if (clientInstance.State == System.ServiceModel.CommunicationState.Faulted)

                {
                    clientInstance.Abort();
                    factory.Abort();
                }
                else if (clientInstance.State != System.ServiceModel.CommunicationState.Closed)
                {
                    clientInstance.Close();
                    factory.Close();
                }
                throw (ex);
            }
        }
Exemplo n.º 17
0
        public string RequestToBinaryConverter(string addr, int n)
        {
            string response = "";

            ChannelFactory <BinaryConverterService.IBinaryConverterService> factory = null;

            try
            {
                BasicHttpBinding binding = new BasicHttpBinding();
                //http://192.168.1.106/MyApp/BinaryConverterService.svc
                EndpointAddress address = new EndpointAddress("http://localhost:8042/MyApp/BinaryConverterService.svc");
                factory = new ChannelFactory <BinaryConverterService.IBinaryConverterService>(binding, address);
                BinaryConverterService.IBinaryConverterService channel = factory.CreateChannel();
                response = channel.GetBinary(n);
                factory.Close();
            }
            catch (Exception ex)
            {
                if (factory != null)
                {
                    factory.Abort();
                }
                response = ex.ToString();
            }
            return(response);
        }
Exemplo n.º 18
0
        public void PingStatus(string name, WebRobotManagementStatus status)
        {
            Action <string, WebRobotManagementStatus> runAction = (x, y) =>
            {
                if (status == WebRobotManagementStatus.STOPPED ||
                    status == WebRobotManagementStatus.ERROR)
                {
                    ChannelFactory <IWebManagementLog> cf = null;
                    try
                    {
                        cf = new ChannelFactory <IWebManagementLog>(new WebHttpBinding(), url);
                        cf.Endpoint.Behaviors.Add(new WebHttpBehavior());
                        var channel = cf.CreateChannel();

                        channel.PingRobotStatus(x, y);
                        cf.Close();
                    }
                    catch (Exception ex)
                    {
                        cf.Abort();
                        Console.WriteLine(ex);
                        // ignore, probably client down
                    }
                }
            };

            runAction.BeginInvoke(name, status, r => { runAction.EndInvoke(r); }, null);
        }
Exemplo n.º 19
0
        private void InvokeService <T>(Action <T> work, bool throwIfError = true)
        {
            ChannelFactory <T> cf = null;

            try
            {
                cf = WCFHandler <T> .ChannelFactory(DemoServerSvcUrl);


                if (cf.State != CommunicationState.Opened)
                {
                    cf.Open();
                }
                T chn = cf.CreateChannel();

                work(chn);
                (chn as IClientChannel).Close();
                cf.Close();
            }
            catch (Exception e)
            {
                cf.Abort();
                if (throwIfError)
                {
                    throw;
                }
            }
        }
        public void BehaviorAddsCustomBinding()
        {
            using (var host = new HostingContext <SimpleService, ISimpleService>())
            {
                var            binding       = new NetTcpBinding();
                var            configuration = new TelemetryConfiguration();
                var            factory       = new ChannelFactory <ISimpleService>(binding, host.GetServiceAddress());
                ISimpleService channel       = null;
                try
                {
                    var behavior = new ClientTelemetryEndpointBehavior(configuration);
                    factory.Endpoint.EndpointBehaviors.Add(behavior);

                    channel = factory.CreateChannel();
                    var innerChannel = GetInnerChannel(channel);
                    ((IClientChannel)channel).Close();
                    factory.Close();

                    Assert.IsInstanceOfType(innerChannel, typeof(ClientTelemetryChannelBase), "Telemetry channel is missing");
                }
                catch
                {
                    factory.Abort();
                    if (channel != null)
                    {
                        ((IClientChannel)channel).Abort();
                    }

                    throw;
                }
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// 获取单个用户信息
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public DeptUser GetUserInfo(string userName)
        {
            if (string.IsNullOrEmpty(userName))
            {
                return(null);
            }
            var fac = new ChannelFactory <IAuthenticationService>("authentication");

            try
            {
                var            ser       = fac.CreateChannel();
                IList <string> userNames = new List <string>();
                userNames.Add(userName);
                var users = ser.GetDeptUsersByUserNames(userNames);
                if (users == null || users.Count() == 0)
                {
                    return(null);
                }
                return(users[0]);
            }
            finally
            {
                fac.Abort();
            }
        }
        /// <summary>
        /// Callback function will be used when fault happened using the channel factory.
        /// </summary>
        /// <param name="sender">Specify the callback event sender.</param>
        /// <param name="e">Specify the event argument.</param>
        private void ChannelFactory_Faulted(object sender, EventArgs e)
        {
            ChannelFactory factory = (ChannelFactory)sender;

            // No matter anything happened, abort this.
            factory.Abort();

            lock (lockObject)
            {
                SharedContext key = null;
                foreach (KeyValuePair <SharedContext, ChannelFactory> pair in this.cached)
                {
                    if (pair.Value == factory)
                    {
                        key = pair.Key;
                        break;
                    }
                }

                if (key != null)
                {
                    this.cached.Remove(key);
                }
            }
        }
Exemplo n.º 23
0
        public void WriteLog(WebRobotStreamLogLine[] lines)
        {
            Action <WebRobotStreamLogLine[]> runAction = x =>
            {
                ChannelFactory <IWebManagementLog> cf = null;
                try
                {
                    cf = new ChannelFactory <IWebManagementLog>(new WebHttpBinding(), url);
                    cf.Endpoint.Behaviors.Add(new WebHttpBehavior());
                    var channel = cf.CreateChannel();


                    channel.WriteLog(new WebRobotStreamLog
                    {
                        Lines = x
                    });

                    cf.Close();
                }
                catch (Exception ex)
                {
                    cf.Abort();
                    Console.WriteLine(ex);
                    // ignore, probably client down
                }
            };

            runAction.BeginInvoke(lines, r => { runAction.EndInvoke(r); }, null);
        }
Exemplo n.º 24
0
        private void Cleanup()
        {
            Channel = default(T);

            try
            {
                if (_factory != null)
                {
                    _factory.Close();
                }
            }
            catch
            {
                /* nom */
            }

            try
            {
                if (_factory != null)
                {
                    _factory.Abort();
                }
            }
            catch
            {
                /* nom */
            }

            _factory = null;
        }
Exemplo n.º 25
0
	public static bool IsAliveHttp(string endpointUrl) {
		bool response = false;

		ChannelFactory <ISoaService> channelFactory = null;
		try {
			channelFactory = new ChannelFactory <ISoaService> (new BasicHttpBinding(BasicHttpSecurityMode.None), new EndpointAddress(endpointUrl));

			ISoaService soaService = channelFactory.CreateChannel();

			if (soaService != null) {
				response = soaService.IsAlive();
			}
			channelFactory.Close();
		} catch (Exception exception) {
			//TODO:
		} finally {
			if (channelFactory != null) channelFactory.Abort();
		}

		return response;

	}
Exemplo n.º 26
0
    [ActiveIssue(4077)]//CoreFX
    public static void DefaultSettings_Echo_RoundTrips_String_StreamedRequest()
    {
        string testString = "Hello";

        BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
        binding.TransferMode = TransferMode.StreamedRequest;
        ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
        IWcfService serviceProxy = factory.CreateChannel();

        try
        {
            Stream stream = StringToStream(testString);
            var result = serviceProxy.GetStringFromStream(stream);
            Assert.Equal(testString, result);
        }
        finally
        {
            if (factory != null && factory.State != CommunicationState.Closed)
            {
                factory.Abort();
            }
        }
    }
Exemplo n.º 27
0
    public static void CustomChannel_Factory_Abort_Aborts_Channel()
    {
        MockChannelFactory<IRequestChannel> mockChannelFactory = null;
        MockRequestChannel mockRequestChannel = null;
        List<string> channelOpenMethodsCalled = new List<string>();
        List<string> channelCloseMethodsCalled = new List<string>();
        List<string> factoryOpenMethodsCalled = new List<string>();
        List<string> factoryCloseMethodsCalled = new List<string>();
        string testMessageBody = "CustomChannelTest_Sync";
        Message inputMessage = Message.CreateMessage(MessageVersion.Default, action: "Test", body: testMessageBody);

        // *** SETUP *** \\
        // Intercept the creation of the factory so we can intercept creation of the channel
        Func<Type, BindingContext, IChannelFactory> buildFactoryAction = (Type type, BindingContext context) =>
        {
            // Create the channel factory and intercept all open and close method calls
            mockChannelFactory = new MockChannelFactory<IRequestChannel>(context, new TextMessageEncodingBindingElement().CreateMessageEncoderFactory());
            MockCommunicationObject.InterceptAllOpenMethods(mockChannelFactory, factoryOpenMethodsCalled);
            MockCommunicationObject.InterceptAllCloseMethods(mockChannelFactory, factoryCloseMethodsCalled);

            // Override the OnCreateChannel call so we get the mock channel created by the factory
            mockChannelFactory.OnCreateChannelOverride = (EndpointAddress endpoint, Uri via) =>
            {
                // Create the mock channel and intercept all its open and close method calls
                mockRequestChannel = (MockRequestChannel)mockChannelFactory.DefaultOnCreateChannel(endpoint, via);
                MockCommunicationObject.InterceptAllOpenMethods(mockRequestChannel, channelOpenMethodsCalled);
                MockCommunicationObject.InterceptAllCloseMethods(mockRequestChannel, channelCloseMethodsCalled);
                return mockRequestChannel;
            };
            return mockChannelFactory;
        };

        MockTransportBindingElement mockBindingElement = new MockTransportBindingElement();
        mockBindingElement.BuildChannelFactoryOverride = buildFactoryAction;

        CustomBinding binding = new CustomBinding(mockBindingElement);
        EndpointAddress address = new EndpointAddress("myprotocol://localhost:5000");
        var factory = new ChannelFactory<ICustomChannelServiceInterface>(binding, address);

        // We rely on the implicit open of the channel to be synchronous.
        // This is true for both the full framework and this NET Core version.
        ICustomChannelServiceInterface channel = factory.CreateChannel();

        // *** EXECUTE *** \\
        Message outputMessage = channel.Process(inputMessage);

        // The mock's default behavior is just to loopback what we sent.
        var result = outputMessage.GetBody<string>();

        // Abort the factory and expect both factory and channel to be aborted.
        factory.Abort();

        // *** VALIDATE *** \\
        Assert.True(String.Equals(testMessageBody, result),
                    String.Format("Expected body to be '{0}' but actual was '{1}'", testMessageBody, result));

        string expectedOpens = "OnOpening,OnOpen,OnOpened";
        string expectedCloses = "OnClosing,OnAbort,OnClosed";

        string actualOpens = String.Join(",", channelOpenMethodsCalled);
        Assert.True(String.Equals(expectedOpens, actualOpens, StringComparison.Ordinal),
               String.Format("Expected channel open methods to be '{0}' but actual was '{1}'.",
                             expectedOpens, actualOpens));

        string actualCloses = String.Join(",", channelCloseMethodsCalled);
        Assert.True(String.Equals(expectedCloses, actualCloses, StringComparison.Ordinal),
               String.Format("Expected channel close methods to be '{0}' but actual was '{1}'.",
                             expectedCloses, actualCloses));

        actualOpens = String.Join(",", factoryOpenMethodsCalled);
        Assert.True(String.Equals(expectedOpens, actualOpens, StringComparison.Ordinal),
               String.Format("Expected factory open methods to be '{0}' but actual was '{1}'.",
                             expectedOpens, actualOpens));

        actualCloses = String.Join(",", factoryCloseMethodsCalled);
        Assert.True(String.Equals(expectedCloses, actualCloses, StringComparison.Ordinal),
               String.Format("Expected factory close methods to be '{0}' but actual was '{1}'.",
                             expectedCloses, actualCloses));

        Assert.True(factory.State == CommunicationState.Closed,
                    String.Format("Expected factory's final state to be Closed but was '{0}'", factory.State));

        Assert.True(((ICommunicationObject)channel).State == CommunicationState.Closed,
            String.Format("Expected channel's final state to be Closed but was '{0}'", ((ICommunicationObject)channel).State));
    }
Exemplo n.º 28
0
    public static void ChannelFactory_Verify_CommunicationStates()
    {
        ChannelFactory<IRequestChannel> factory = null;
        IRequestChannel channel = null;

        try
        {
            BasicHttpBinding binding = new BasicHttpBinding();

            EndpointAddress endpointAddress = new EndpointAddress(BaseAddress.HttpBaseAddress);

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

            Assert.Equal(CommunicationState.Created, factory.State);

            // Create the channel.
            channel = factory.CreateChannel();
            Assert.True(typeof(IRequestChannel).GetTypeInfo().IsAssignableFrom(channel.GetType().GetTypeInfo()),
                String.Format("Channel type '{0}' was not assignable to '{1}'", channel.GetType(), typeof(IRequestChannel)));
            Assert.Equal(CommunicationState.Opened, factory.State);

            // Validate ToString()
            string toStringResult = channel.ToString();
            string toStringExpected = "System.ServiceModel.Channels.IRequestChannel";
            Assert.Equal<string>(toStringExpected, toStringResult);

            factory.Close();
            Assert.Equal(CommunicationState.Closed, factory.State);
        }
        finally
        {
            if (factory != null)
            {
                // check that there are no effects after calling Abort after Close
                factory.Abort();
                Assert.Equal(CommunicationState.Closed, factory.State);

                // check that there are no effects after calling Close again
                factory.Close();
                Assert.Equal(CommunicationState.Closed, factory.State);
            }
        }
    }
Exemplo n.º 29
0
    public static void ChannelFactory_Async_Open_Close()
    {
        ChannelFactory<IRequestChannel> factory = null;
        try
        {
            BasicHttpBinding binding = new BasicHttpBinding();

            // Create the channel factory
            factory = new ChannelFactory<IRequestChannel>(binding, new EndpointAddress(FakeAddress.HttpAddress));
            Assert.True(CommunicationState.Created == factory.State,
                string.Format("factory.State - Expected: {0}, Actual: {1}.", CommunicationState.Created, factory.State));

            Task.Factory.FromAsync(factory.BeginOpen(null, null), factory.EndOpen).GetAwaiter().GetResult();
            Assert.True(CommunicationState.Opened == factory.State,
                string.Format("factory.State - Expected: {0}, Actual: {1}.", CommunicationState.Opened, factory.State));

            Task.Factory.FromAsync(factory.BeginClose(null, null), factory.EndClose).GetAwaiter().GetResult();
            Assert.True(CommunicationState.Closed == factory.State,
                string.Format("factory.State - Expected: {0}, Actual: {1}.", CommunicationState.Closed, factory.State));
        }
        finally
        {
            if (factory != null && factory.State != CommunicationState.Closed)
            {
                factory.Abort();
            }
        }
    }
Exemplo n.º 30
0
    public static void BasicHttp_Abort_ChannelFactory_Operations_Active()
    {
        // Test creates 2 channels from a single channel factory and
        // aborts the channel factory while both channels are executing
        // operations.  This verifies the operations are cancelled and
        // the channel factory is in the correct state.
        BasicHttpBinding binding = null;
        TimeSpan delayOperation = TimeSpan.FromSeconds(3);
        ChannelFactory<IWcfService> factory = null;
        IWcfService serviceProxy1 = null;
        IWcfService serviceProxy2 = null;
        string expectedEcho1 = "first";
        string expectedEcho2 = "second";

        try
        {
            // *** SETUP *** \\
            binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
            binding.CloseTimeout = ScenarioTestHelpers.TestTimeout;
            binding.SendTimeout = ScenarioTestHelpers.TestTimeout;
            factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
            serviceProxy1 = factory.CreateChannel();
            serviceProxy2 = factory.CreateChannel();

            // *** EXECUTE *** \\
            Task<string> t1 = serviceProxy1.EchoWithTimeoutAsync("first", delayOperation);
            Task<string> t2 = serviceProxy2.EchoWithTimeoutAsync("second", delayOperation);
            factory.Abort();

            // *** VALIDATE *** \\
            Assert.True(factory.State == CommunicationState.Closed,
                        String.Format("Expected factory state 'Closed', actual was '{0}'", factory.State));

            Exception exception1 = null;
            Exception exception2 = null;
            string actualEcho1 = null;
            string actualEcho2 = null;

            // Verification is slightly more complex for the close with active operations because
            // we don't know which might have completed first and whether the channel factory
            // was able to close and dispose either channel before it completed.  So we just
            // ensure the Tasks complete with an exception or a successful return and have
            // been closed by the factory.
            try
            {
                actualEcho1 = t1.GetAwaiter().GetResult();
            }
            catch (Exception e)
            {
                exception1 = e;
            }

            try
            {
                actualEcho2 = t2.GetAwaiter().GetResult();
            }
            catch (Exception e)
            {
                exception2 = e;
            }

            Assert.True(exception1 != null || actualEcho1 != null, "First operation should have thrown Exception or returned an echo");
            Assert.True(exception2 != null || actualEcho2 != null, "Second operation should have thrown Exception or returned an echo");

            Assert.True(actualEcho1 == null || String.Equals(expectedEcho1, actualEcho1),
                        String.Format("First operation returned '{0}' but expected '{1}'.", expectedEcho1, actualEcho1));

            Assert.True(actualEcho2 == null || String.Equals(expectedEcho2, actualEcho2),
            String.Format("Second operation returned '{0}' but expected '{1}'.", expectedEcho2, actualEcho2));

            Assert.True(((ICommunicationObject)serviceProxy1).State == CommunicationState.Closed,
                            String.Format("Expected channel 1 state 'Closed', actual was '{0}'", ((ICommunicationObject)serviceProxy1).State));
            Assert.True(((ICommunicationObject)serviceProxy2).State == CommunicationState.Closed,
                String.Format("Expected channel 2 state 'Closed', actual was '{0}'", ((ICommunicationObject)serviceProxy2).State));

            // *** CLEANUP *** \\
            ((ICommunicationObject)serviceProxy1).Abort();
            ((ICommunicationObject)serviceProxy2).Abort();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy1,
                                                          (ICommunicationObject)serviceProxy2, 
                                                          factory);
        }
    }
Exemplo n.º 31
0
    [ActiveIssue(4077)]//CoreFX
    public static void DefaultSettings_Echo_RoundTrips_String_Streamed()
    {
        string testString = "Hello";
        StringBuilder errorBuilder = new StringBuilder();

        BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
        binding.TransferMode = TransferMode.Streamed;
        ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
        IWcfService serviceProxy = factory.CreateChannel();

        try
        {
            Stream stream = StringToStream(testString);
            var returnStream = serviceProxy.EchoStream(stream);
            var result = StreamToString(returnStream);
            Assert.Equal(testString, result);
        }
        catch (System.ServiceModel.CommunicationException e)
        {
            errorBuilder.AppendLine(string.Format("Unexpected exception thrown: '{0}'", e.ToString()));
            PrintInnerExceptionsHresult(e, errorBuilder);
        }
        finally
        {
            if (factory != null && factory.State != CommunicationState.Closed)
            {
                factory.Abort();
            }
        }

        Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: DefaultSettings_Echo_RoundTrips_String_Streamed FAILED with the following errors: {0}", errorBuilder));
    }