public void TestOneWayCallbackConcurencyOnNamedPipe()
        {
            var address = @"net.pipe://127.0.0.1/testpipename" + MethodBase.GetCurrentMethod().Name;
            var srv = new CallbackService();
            var callback = new CallbackServiceCallback();
            using (var server = new ServiceHost(srv, new Uri(address)))
            {
                server.AddServiceEndpoint(typeof(ICallbackService), new NetNamedPipeBinding { }, address);
                server.Open();

                using (var channelFactory = new DuplexChannelFactory<ICallbackService>(new InstanceContext(callback), new NetNamedPipeBinding { }))
                {

                    var client = channelFactory.CreateChannel(new EndpointAddress(address));

                    for (int i = 0; i < 20; i++)
                        client.OneWayExecute();
                    while (callback.Count != 20)
                    {
                        Thread.Sleep(10);
                    }

                }
            }
        }
Exemple #2
0
 public RobotClient()
 {
     // Initilize communication channel
     DuplexChannelFactory = new DuplexChannelFactory<IUiPathRemoteDuplexContract>(new InstanceContext(this), "DefaultDuplexEndpoint");
     DuplexChannelFactory.Credentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
     Channel = DuplexChannelFactory.CreateChannel();
 }
Exemple #3
0
        public void CallAsync_wait_done()
        {
            var address = @"net.pipe://127.0.0.1/" + this.GetType().Name + "_" + MethodBase.GetCurrentMethod().Name;
            var binding = new NetNamedPipeBinding();

            var done = new ManualResetEvent(false);
            var srv = new AsyncService(done);
            var callback = new AsyncServiceCallback();

            using (var host = new ServiceHost(srv, new Uri(address)))
            {
                host.AddServiceEndpoint(typeof(IAsyncService), binding, address);
                host.Open();

                ThreadPool.QueueUserWorkItem(_ =>
                    {
                        using (var factory = new DuplexChannelFactory<IAsyncService>(new InstanceContext(callback), binding))
                        {
                            var client = factory.CreateChannel(new EndpointAddress(address));
                            AsyncCallback act = (x) =>
                            {
                                Assert.AreEqual(x.AsyncState, 1);
                            };
                            var result = client.BeginServiceAsyncMethod(act, 1);
                            result.AsyncWaitHandle.WaitOne();
                            Assert.AreEqual(result.AsyncState, 1);
                            client.EndServiceAsyncMethod(result);

                        }
                    });

                done.WaitOne();
            }
        }
        public MainWindow()
        {
            InitializeComponent();

            EndpointAddress endpointAddress = new EndpointAddress("http://localhost:31337/BesiegedServer/BesiegedMessage");
            DuplexChannelFactory<IBesiegedServer> duplexChannelFactory = new DuplexChannelFactory<IBesiegedServer>(m_Client, new WSDualHttpBinding(), endpointAddress);
            m_BesiegedServer = duplexChannelFactory.CreateChannel();

            // Subscribe in a separate thread to preserve the UI thread
            Task.Factory.StartNew(() =>
            {
                CommandConnect commandConnect = new CommandConnect();
                m_BesiegedServer.SendMessage(commandConnect.ToXml());
            });

            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    Command command = m_Client.MessageQueue.Take();
                    ProcessMessage(command);
                }
            }, TaskCreationOptions.LongRunning);

            GameLobbyCollection = new ObservableCollection<CommandNotifyGame>();
            DataContext = this;
        }
Exemple #5
0
        //其他成员
        private void MonitorForm_Load(object sender, EventArgs e)
        {
            string header = string.Format("{0, -13}{1, -22}{2}", "Client", "Time", "Event");
            this.listBoxExecutionProgress.Items.Add(header);
            _syncContext = SynchronizationContext.Current;
            _callbackInstance = new InstanceContext(new CalculatorCallbackService());
            _channelFactory = new DuplexChannelFactory<ICalculator>(_callbackInstance, "calculatorservice");

            EventMonitor.MonitoringNotificationSended += ReceiveMonitoringNotification;
            this.Disposed += delegate
            {
            EventMonitor.MonitoringNotificationSended -= ReceiveMonitoringNotification;
            _channelFactory.Close();
            };

            for (int i = 0; i < 2; i++)
            {
            ThreadPool.QueueUserWorkItem(state =>
            {
                int clientId = Interlocked.Increment(ref _clientId);
                EventMonitor.Send(clientId, EventType.StartCall);
                ICalculator proxy = _channelFactory.CreateChannel();
                using (OperationContextScope contextScope = new OperationContextScope(proxy as IContextChannel))
                {
                    MessageHeader<int> messageHeader = new MessageHeader<int>(clientId);
                    OperationContext.Current.OutgoingMessageHeaders.Add(messageHeader.GetUntypedHeader(EventMonitor.CientIdHeaderLocalName, EventMonitor.CientIdHeaderNamespace));
                    proxy.Add(1, 2);
                }
                EventMonitor.Send(clientId, EventType.EndCall);
            }, null);
            }
        }
Exemple #6
0
    public static void RequestResponseOverWebSocketManually_Echo_RoundTrips_Guid()
    {
        DuplexChannelFactory<IWcfDuplexService> factory = null;
        Guid guid = Guid.NewGuid();

        NetHttpBinding binding = new NetHttpBinding();
        binding.WebSocketSettings.TransportUsage = WebSocketTransportUsage.Always;

        WcfDuplexServiceCallback callbackService = new WcfDuplexServiceCallback();
        InstanceContext context = new InstanceContext(callbackService);

        try
        {
            factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, new EndpointAddress(Endpoints.NetHttpWebSocketTransport_Address));
            IWcfDuplexService duplexProxy = factory.CreateChannel();

            Task.Run(() => duplexProxy.Ping(guid));
            Guid returnedGuid = callbackService.CallbackGuid;

            Assert.True(guid == returnedGuid, string.Format("The sent GUID does not match the returned GUID. Sent '{0}', Received: '{1}'", guid, returnedGuid));
        }
        finally
        {
            if (factory != null && factory.State != CommunicationState.Closed)
            {
                factory.Abort();
            }
        }
    }
Exemple #7
0
        private  void StartP2PClient( )
        {
            string s = ConfigurationManager.AppSettings["IsSupportGroup"];
            if (s.Equals("no", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }
            InstanceContext context = new InstanceContext(new P2PChatService());
            DuplexChannelFactory<IP2PChatService> factory = new DuplexChannelFactory<IP2PChatService>(context,"p2p", new EndpointAddress("net.p2p://" + groupId));


            channel = factory.CreateChannel();
            clients.Add(groupId, this);
           

           
            new Thread(new ThreadStart(() =>
            {
                try
                {
                    channel.Join();
                }
                catch (Exception ex)
                {
                    MyLogger.Logger.Error("进入群组聊天室时出错",ex);
                }
            })).Start();
           
        }
        public MainWindow(string s) {
            InitializeComponent();
            //initialize the connections 
            try {
                DuplexChannelFactory<IDealer> channel = new DuplexChannelFactory<IDealer>(this, "DealerEndPoint");

                //activate the dealer object.
                dealer = channel.CreateChannel();  //does this in turn call the dealer constructor??
                myCallbackKey = dealer.PlayerJoin(s);
                lblMoney.Content = 2000;
                cmboNumber.ItemsSource = dealer.RouletteWheel;
                cmboNumber.DisplayMemberPath = "Key";

                cmboRange.Items.Add("1-12");
                cmboRange.Items.Add("13-24");
                cmboRange.Items.Add("25-36");

                cmboColor.Items.Add("Red");
                cmboColor.Items.Add("Black");

                cmboOddEven.Items.Add("Odd");
                cmboOddEven.Items.Add("Even");
            }
            catch (Exception ex) {
                MessageBox.Show("Error starting the service: " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }
 public ClientViewModel()
 {
     var channelFactory = new DuplexChannelFactory<IChattingService>(new ClientService(), "ChattingServiceEndPoint");
     _server = channelFactory.CreateChannel();
     This = this;
     CreateCommands();
 }
Exemple #10
0
        public bool Connect(ClientCrawlerInfo clientCrawlerInfo)
        {
            try
            {
                var site = new InstanceContext(this);

                var binding = new NetTcpBinding(SecurityMode.None);
                //var address = new EndpointAddress("net.tcp://localhost:22222/chatservice/");

                var address = new EndpointAddress("net.tcp://193.124.113.235:22222/chatservice/");
                var factory = new DuplexChannelFactory<IRemoteCrawler>(site, binding, address);

                proxy = factory.CreateChannel();
                ((IContextChannel)proxy).OperationTimeout = new TimeSpan(1, 0, 10);

                clientCrawlerInfo.ClientIdentifier = _singletoneId;
                proxy.Join(clientCrawlerInfo);

                return true;
            }

            catch (Exception ex)
            {
                MessageBox.Show("Error happened" + ex.Message);
                return false;
            }
        }
 public RegisterViewModel()
 {
     var channelFactory = new DuplexChannelFactory<IChattingService>(new ClientService(), "ChattingServiceEndPoint");
     _server = channelFactory.CreateChannel();
     Register = new RelayCommand(OnRegister, () => !(string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(Password)));
     ClearCommand = new RelayCommand(OnClear);
 }
        public static void ConnectIpc(IServiceRemotingCallback serviceRemotingCallback)
        {
            InstanceContext instanceContext = new InstanceContext(serviceRemotingCallback);

            PipeFactory = new DuplexChannelFactory<IServiceRemoting>(instanceContext, new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/BitCollectors.PlinkService/PlinkService"));
            RemotingObject = PipeFactory.CreateChannel();
        }
Exemple #13
0
        static void Main(string[] args)
        {
            Console.Title = "Client";
            Console.WriteLine("Press any key to connect to server");
            Console.ReadKey();

            // InstanceContext - представляет метод вызываемый сервисом на клиенте.
            InstanceContext context = new InstanceContext(new Context());

            // Создаем фабрику дуплексных каналов на клиенте.
            DuplexChannelFactory<IContractService> factory = new DuplexChannelFactory<IContractService>(
                context,
                new NetTcpBinding(),
                "net.tcp://localhost:9000/MyService"
                );

            // Создаем конкретный канал.
            IContractService server = factory.CreateChannel();

            
            server.ServerMethod();

            Console.WriteLine("Connected");

            Console.ReadKey();

            

            Console.ReadKey();
        }
        static void Main(string[] args)
        {
            var fact = new ChannelFactory<IDeviceManagerService>("deviceEndpoint");

            InstanceContext callback = new InstanceContext(new ServiceCallback());

            var dup = new DuplexChannelFactory<ICardReaderEventsSubscribe>(callback, "dupSocket");

            var cardReaderSub = dup.CreateChannel();

            var cha = fact.CreateChannel();

            using (fact)
            {
                var devices = cha.GetAllDevices();
                //cha.Open(new  devices[0].FullSerialNumber );

            }
            Console.WriteLine("try a new");
            Console.ReadKey();

            Console.WriteLine("REading duplex");

            cardReaderSub.SubscribeToCardSwipeByhost("Local");

            Console.ReadKey();

            var fact1 = new ChannelFactory<IDeviceManagerService>("deviceEndpoint");
            var cha1 = fact1.CreateChannel();

            using (fact1)
            {
                var devices = cha1.GetAllDevices();
            }
        }
        public MainWindow()
        {
            try
            {
                //Center the window on startup
                WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
                InitializeComponent();
                createGrid();
                // Configure the Endpoint details
                DuplexChannelFactory<ITileBag> channel = new DuplexChannelFactory<ITileBag>(this, "TileBag");

                // Activate a remote Bag object
                bag = channel.CreateChannel();
                // Register this client for the callback service
                bag.RegisterForCallbacks();

                lblPlayerScore.Content = 0;
                pWin = new PlayerLobby(this, bag.ClientCount);
                pWin.Show();
                this.Hide();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Initializing Window " + ex.Message);
            }
        }
Exemple #16
0
        /// <summary>
        /// Connect to game server
        /// </summary>
        /// <param name="IP"></param>
        /// <returns></returns>
        public bool Connect(String IP)
        {

            // Create a pipeFactory
            DuplexChannelFactory<IMessage> pipeFactory =
                  new DuplexChannelFactory<IMessage>(
                      new InstanceContext(this),
                      new NetTcpBinding(),
                //new EndpointAddress(String.Format("net.tcp://{0}:8000/GameServer", IP)));
                      new EndpointAddress(String.Format("net.tcp://{0}:8000/GameServer", "localhost")));
            try
            {

                // Creating the communication channel
                pipeProxy = pipeFactory.CreateChannel();
                // register for events 
                pipeProxy.Subscribe();
                // join the game 
                myID = pipeProxy.join(me.Username, me.money, me.numOfGames, me.ID);
                if (pipeProxy.runningGame())
                {
                    pipeProxy.resetGame();
                }
                return true;
            }
            catch (Exception e)
            {
                
                return false;
            }
        }
    public static void NetTcpBinding_DuplexCallback_ReturnsXmlComplexType()
    {
        DuplexChannelFactory<IWcfDuplexService_Xml> factory = null;
        NetTcpBinding binding = null;
        WcfDuplexServiceCallback callbackService = null;
        InstanceContext context = null;
        IWcfDuplexService_Xml serviceProxy = null;
        Guid guid = Guid.NewGuid();

        try
        {
            binding = new NetTcpBinding();
            binding.Security.Mode = SecurityMode.None;

            callbackService = new WcfDuplexServiceCallback();
            context = new InstanceContext(callbackService);

            factory = new DuplexChannelFactory<IWcfDuplexService_Xml>(context, binding, new EndpointAddress(Endpoints.Tcp_NoSecurity_XmlDuplexCallback_Address));
            serviceProxy = factory.CreateChannel();

            serviceProxy.Ping_Xml(guid);
            XmlCompositeTypeDuplexCallbackOnly returnedType = callbackService.XmlCallbackGuid;

            // validate response
            Assert.True((guid.ToString() == returnedType.StringValue), String.Format("The Guid to string value sent was not the same as what was returned.\nSent: {0}\nReturned: {1}", guid.ToString(), returnedType.StringValue));

            ((ICommunicationObject)serviceProxy).Close();
            factory.Close();
        }
        finally
        {
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
Exemple #18
0
 public void btnUpload_Click(object sender, EventArgs e)
 {
     MediaDto mediaInfo = proxy.UploadRequest(String.Empty);
     var tcpBinding = new NetTcpBinding
         {
             Security =
                 {
                     Mode = SecurityMode.None,
                     Transport = {ClientCredentialType = TcpClientCredentialType.Windows},
                     Message = {ClientCredentialType = MessageCredentialType.Windows}
                 },
             ReliableSession = {Enabled = true}
         };
     var tcpAddress =
         new EndpointAddress("net.tcp://" + mediaInfo.Address + ":" + mediaInfo.Port + "/MediaService");
     mediaChannelFactory =
         new DuplexChannelFactory<IMediaContract>(new InstanceContext(new MediaServiceCallBack()), tcpBinding,
                                                  tcpAddress);
     mediaChannelFactory.Closing += delegate
         {
             mediaContract = null;
             mediaChannelFactory = null;
         };
     mediaContract = mediaChannelFactory.CreateChannel();
     mediaContract.SayHello("Upload test.");
 }
Exemple #19
0
        public MainWindow()
        {
            InitializeComponent();

            try
            {
                // Configure the ABCs of using CardsLibrary
                DuplexChannelFactory<IWordList> channel = new DuplexChannelFactory<IWordList>(this, "WordFunEndPoint");

                // Activate a WordList object
                words = channel.CreateChannel();

                // Register for callbacks
                callbackId = words.RegisterForCallbacks();

                _countdownTimer = new DispatcherTimer();
                _countdownTimer.Interval = new TimeSpan(0, 0, 1);
                _countdownTimer.Tick += new EventHandler(CountdownTimerStep);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #20
0
        public ApplicationManager(IMessengerManager messenger, ITranslationManager translation, IConfigurationManager configuration, IUserManager user, 
                                  INotifyIconManager notifyIcon, IEventLogManager logger, IControllerConfigurationManager controller, IThemeManager theme)
        {
            Messenger = messenger;
            Translation = translation;
            Configuration = configuration;
            User = user;
            NotifyIcon = notifyIcon;
            Logger = logger;
            Controller = controller;
            Theme = theme;

            Logger.Initialize(Constants.SERVICE_NAME);
            Logger.Subscribe(param => Messenger.NotifyColleagues(AppMessages.NEW_LOG_MESSAGE, param.Entry));

            string a = Configuration.GetData(ConfOptions.OPTION_ACCENT);
            string t = Configuration.GetData(ConfOptions.OPTION_THEME);
            Theme.SetTheme(a, t);

            Translation.ChangeLanguage(Configuration.GetData(ConfOptions.OPTION_LANGUAGE));

            DuplexChannelFactory<ISubscribingService> pipeFactory = new DuplexChannelFactory<ISubscribingService>(new ServiceCommand(Messenger),
                new NetNamedPipeBinding(), new EndpointAddress(Constants.PIPE_ADDRESS + Constants.SERVICE_NAME));
            Service = pipeFactory.CreateChannel();
            Service.Subscribe();
        }
        private void submitButton_Click(object sender, RoutedEventArgs e)
        {
            var login = loginTextBox.Text;
            var pass = passwordTextBox.Password;

            Action<String> status = s => {
                statusLabel.Content = s;
                statusLabel.ToolTip = s;
            };

            try {
                channelFactory = new DuplexChannelFactory<IService>(new ClientImplementation(_MainWindow), "DnDServiceEndPoint");
                server = channelFactory.CreateChannel();

                if (server.Login(login, pass)) {
                    _MainWindow.InitializeServer(channelFactory, server);
                    this.DialogResult = true;
                } else {
                    statusLabel.Content = "Login lub hasło nie są poprawne!";
                    return;
                }

            } catch (Exception ex) {
                statusLabel.Content = "Nastąpił błąd! Spróbuj ponownie";
                System.IO.StreamWriter file = new System.IO.StreamWriter("log.txt");
                file.WriteLine(ex.ToString());
                file.Close();
                return;
            }
            this.Close();
        }
        public void connect(String url, IAudioServiceCallBack callback, EventHandler openedEvt = null, EventHandler faultEvt = null) //url = "net.tcp://localhost:8080/AudioService"
        {
            try
            {
                 duplex = new DuplexChannelFactory<IAudioService>(callback, new NetTcpBinding(),
                     new EndpointAddress(url));
                
                 service = duplex.CreateChannel();
                 channel = (ICommunicationObject)service;
                 IClientChannel c = (IClientChannel)channel;
                 c.OperationTimeout = TimeSpan.FromSeconds(5);
                 
                 channel.Opened += new EventHandler(delegate(object o, EventArgs e)
                    {
                        Console.WriteLine("Connection ok!");
                    });

                if(openedEvt != null)
                 channel.Opened += openedEvt;
                if(faultEvt != null)
                 channel.Faulted += faultEvt;
                 channel.Faulted += new EventHandler(delegate(object o, EventArgs e)
                    {
                        Console.WriteLine("Connection lost");
                    });

            }
            catch (Exception e)
            {
                Console.WriteLine("Connection error: " + e.Message);
            }
        }
    public static void ServiceContract_TypedProxy_AsyncTask_CallbackReturn()
    {
        DuplexChannelFactory<IWcfDuplexTaskReturnService> factory = null;
        Guid guid = Guid.NewGuid();

        NetTcpBinding binding = new NetTcpBinding();
        binding.Security.Mode = SecurityMode.None;

        DuplexTaskReturnServiceCallback callbackService = new DuplexTaskReturnServiceCallback();
        InstanceContext context = new InstanceContext(callbackService);

        try
        {
            factory = new DuplexChannelFactory<IWcfDuplexTaskReturnService>(context, binding, new EndpointAddress(Endpoints.Tcp_NoSecurity_TaskReturn_Address));
            IWcfDuplexTaskReturnService serviceProxy = factory.CreateChannel();

            Task<Guid> task = serviceProxy.Ping(guid);

            Guid returnedGuid = task.Result;

            Assert.Equal(guid, returnedGuid);

            factory.Close();
        }
        finally
        {
            if (factory != null && factory.State != CommunicationState.Closed)
            {
                factory.Abort();
            }
        }
    }
Exemple #24
0
        public static void Test()
        {
            string baseAddress = "net.tcp://" + Environment.MachineName + ":8000/Service";
            ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
            host.AddServiceEndpoint(typeof(ITest), new NetTcpBinding(SecurityMode.None), "");
            host.Open();
            Console.WriteLine("Host opened");

            AutoResetEvent evt = new AutoResetEvent(false);
            MyCallback callback = new MyCallback(evt);
            DuplexChannelFactory<ITest> factory = new DuplexChannelFactory<ITest>(
                new InstanceContext(callback),
                new NetTcpBinding(SecurityMode.None),
                new EndpointAddress(baseAddress));
            ITest proxy = factory.CreateChannel();

            Console.WriteLine(proxy.Hello("foo bar"));
            evt.WaitOne();

            ((IClientChannel)proxy).Close();
            factory.Close();

            Console.Write("Press ENTER to close the host");
            Console.ReadLine();
            host.Close();
        }
        public MainWindow()
        {
            InitializeComponent();

            //Initialization Code
            try
            {
                // Configure the Endpoint details
                DuplexChannelFactory<IPig> channel = new DuplexChannelFactory<IPig>(this, "Pig");

                // Activate a remote Shoe object
                pig = channel.CreateChannel();

                // Regsister this client for the callbacks service
                callbackId = pig.RegisterForCallbacks();

                // If they join after the game is started, this player will not be included in the game
                if( callbackId == 0 )
                {
                    MessageBox.Show("Game has already started");
                    this.Close();
                }

                this.Title = "Hello Player " + callbackId;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #26
0
		public OrationiSlave()
		{
			Binding binding = new NetTcpBinding(SecurityMode.None);
			EndpointAddress defaultEndpointAddress = new EndpointAddress("net.tcp://localhost:57344/Orationi/Master/v1/");
			EndpointAddress discoveredEndpointAddress = DiscoverMaster();
			ContractDescription contractDescription = ContractDescription.GetContract(typeof(IOrationiMasterService));
			ServiceEndpoint serviceEndpoint = new ServiceEndpoint(contractDescription, binding, discoveredEndpointAddress ?? defaultEndpointAddress);
			var channelFactory = new DuplexChannelFactory<IOrationiMasterService>(this, serviceEndpoint);

			try
			{
				channelFactory.Open();
			}
			catch (Exception ex)
			{
				channelFactory?.Abort();
			}

			try
			{
				_masterService = channelFactory.CreateChannel();
				_communicationObject = (ICommunicationObject)_masterService;
				_communicationObject.Open();
			}
			catch (Exception ex)
			{
				if (_communicationObject != null && _communicationObject.State == CommunicationState.Faulted)
					_communicationObject.Abort();
			}
		}
        public RemoteExecutorClient(string hostname)
        {
            _executorServiceCallback = new RemoteExecutorCallback();
            var context = new InstanceContext(_executorServiceCallback);

            // TODO: Process more than this single Endpoint named "NetTcpBinding_IExecutorService".
            // What about InstanceContext. Do we need another one if more than one Endpoint is parameterized.
            // Will it be usefull to offer more than one endpoint?
            // -> It will be usefull. What about offering chooseable predefined Endpoints? Eg.: NamedPipe or TCP.
            // .) NamedPipe will be used for local Executors or for the "Send a message to the Executor" Service.
            // .) TCP will be used for Executors on other machines.
            var uri = new Uri("net.tcp://" + hostname + ":9000/RExServer");
            EndpointIdentity identity = EndpointIdentity.CreateSpnIdentity("RExTheMighty");
            _channelFactory = new DuplexChannelFactory<IRemoteExecutor>(
                context, new NetTcpBinding(), new EndpointAddress(uri, identity));

            _reconnectTimer = new System.Timers.Timer(ReconnectTimeout) {AutoReset = false}; // Wait after channel failure before reconnect.
            _reconnectTimer.Elapsed += (s, e) => 
            {
                try
                {
                    if (!_isConnected)
                    {
                        Connect();
                    }
                }
                catch (Exception ex)
                {
                    Log.Trace("Failed to reconnect: "+ ex.Message);
                }
            };

            _isConnected = false;
        }
Exemple #28
0
    public static void RequestResponseOverWebSocketManually_Echo_RoundTrips_Guid()
    {
        DuplexChannelFactory<IWcfDuplexService> factory = null;
        IWcfDuplexService duplexProxy = null;
        Guid guid = Guid.NewGuid();

        try
        {
            // *** SETUP *** \\
            NetHttpBinding binding = new NetHttpBinding();
            binding.WebSocketSettings.TransportUsage = WebSocketTransportUsage.Always;

            WcfDuplexServiceCallback callbackService = new WcfDuplexServiceCallback();
            InstanceContext context = new InstanceContext(callbackService);

            factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, new EndpointAddress(Endpoints.NetHttpWebSocketTransport_Address));
            duplexProxy = factory.CreateChannel();

            // *** EXECUTE *** \\
            Task.Run(() => duplexProxy.Ping(guid));
            Guid returnedGuid = callbackService.CallbackGuid;

            // *** VALIDATE *** \\
            Assert.True(guid == returnedGuid, string.Format("The sent GUID does not match the returned GUID. Sent '{0}', Received: '{1}'", guid, returnedGuid));

            // *** CLEANUP *** \\
            factory.Close();
            ((ICommunicationObject)duplexProxy).Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)duplexProxy, factory);
        }
    }
Exemple #29
0
        static void Main(string[] args)
        {
            try
            {
                   DuplexChannelFactory<IServerWithCallback> cf =
                 new DuplexChannelFactory<IServerWithCallback>(
                     new CallbackImpl(),
                     new NetTcpBinding(),
                     new EndpointAddress("net.tcp://192.168.1.1:9078/DataService"));
                  IServerWithCallback srv = cf.CreateChannel();
                  CounterStatues cs = new CounterStatues { CounterName = "Counter eeee", CounterNumber = "ttt", CounterStatus =CounterStatues.CounterStatusEn.Lock, UserId = "yahoo", IpAddress = "192.168.50.90" };

                srv.StartDataOutput(cs);
                System.Threading.ParameterizedThreadStart pt = new System.Threading.ParameterizedThreadStart(ServerChecker);
                System.Threading.Thread checkserver = new System.Threading.Thread(pt);
                checkserver.Start(srv);
                Console.Read();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("Try again ...");
                System.Threading.Thread.Sleep(600);
                Main(null);
            }
        }
        /// <summary>
        /// 截获从Client端发送的消息转发到目标终结点并获得返回值给Client端
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public Message ProcessMessage(Message requestMessage)
        {
            //Binding binding = null;
            EndpointAddress endpointAddress = null;
            GetServiceEndpoint(requestMessage, out endpointAddress);
            IDuplexRouterCallback callback = OperationContext.Current.GetCallbackChannel<IDuplexRouterCallback>();
            NetTcpBinding tbinding = new NetTcpBinding("netTcpExpenseService_ForSupplier");
            using (DuplexChannelFactory<IRouterService> factory = new DuplexChannelFactory<IRouterService>(new InstanceContext(null, new DuplexRouterCallback(callback)), tbinding, endpointAddress))
            {

                factory.Endpoint.Behaviors.Add(new MustUnderstandBehavior(false));
                IRouterService proxy = factory.CreateChannel();

                using (proxy as IDisposable)
                {
                    // 请求消息记录
                    IClientChannel clientChannel = proxy as IClientChannel;
                    //Console.WriteLine(String.Format("Request received at {0}, to {1}\r\n\tAction: {2}", DateTime.Now, clientChannel.RemoteAddress.Uri.AbsoluteUri, requestMessage.Headers.Action));
                    if (WcfServerManage.IsDebug)
                        hostwcfMsg(DateTime.Now, String.Format("路由请求消息发送:  {0}", clientChannel.RemoteAddress.Uri.AbsoluteUri));
                    // 调用绑定的终结点的服务方法
                    Message responseMessage = proxy.ProcessMessage(requestMessage);

                    // 应答消息记录
                    //Console.WriteLine(String.Format("Reply received at {0}\r\n\tAction: {1}", DateTime.Now, responseMessage.Headers.Action));
                    //Console.WriteLine();
                    //hostwcfMsg(DateTime.Now, String.Format("应答消息: {0}", responseMessage.Headers.Action));
                    return responseMessage;
                }
            }
        }
Exemple #31
0
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            InstanceContext context = new InstanceContext(new ConsoleCallback());

            _factory = new DuplexChannelFactory <IRemoteConsole>(context, _endpointName);
            while (true)
            {
                IRemoteConsole remoteConsole = connectToServer();
                if (remoteConsole == null)
                {
                    return;
                }
                DoWork(remoteConsole);
            }
        }
Exemple #32
0
        /// <summary>
        /// 在用户登录UMP或智能客户端时 调用此方法 可更新用户在线信息
        /// </summary>
        public void Login()
        {
            try
            {
                NetTcpBinding   binding    = CommonFuncs.CreateNetTcpBinding();
                EndpointAddress myEndpoint = CommonFuncs.CreateEndPoint(session.AppServerInfo.Address, "8083");
                DuplexChannelFactory <IService16001Channel> fac = new DuplexChannelFactory <IService16001Channel>(this, binding, myEndpoint);
                iClient = fac.CreateChannel();

                iClient.LoginSystem(session);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #33
0
        public static ServiceHelper Create()
        {
            ServiceHelper helper = new ServiceHelper();

            CallbackClient  callbackClient = new CallbackClient();
            InstanceContext context        = new InstanceContext(callbackClient);

            DuplexChannelFactory <IManagementService> factory = new DuplexChannelFactory <IManagementService>(
                context,
                new NetNamedPipeBinding(),
                new EndpointAddress("net.pipe://localhost/Wingnut"));

            helper.Channel = factory.CreateChannel();

            return(helper);
        }
    // valid address, but the scheme is incorrect
    public static void CreateChannel_BasicHttpBinding_Throws_InvalidOperation()
    {
        WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback();
        InstanceContext          context  = new InstanceContext(callback);
        Binding binding = new BasicHttpBinding(BasicHttpSecurityMode.None);

        // Contract requires Duplex, but Binding 'BasicHttpBinding' doesn't support it or isn't configured properly to support it.
        var exception = Assert.Throws <InvalidOperationException>(() =>
        {
            DuplexChannelFactory <IWcfDuplexService> factory = new DuplexChannelFactory <IWcfDuplexService>(context, binding, "http://basichttp-not-duplex");
            factory.CreateChannel();
        });

        Assert.True(exception.Message.Contains("BasicHttpBinding"),
                    string.Format("InvalidOperationException exception string should contain 'BasicHttpBinding'. Actual message:\r\n" + exception.ToString()));
    }
Exemple #35
0
        /// <summary>
        /// 生成透明代理类
        /// </summary>
        /// <returns></returns>
        ImyService createClient()
        {
            //设置nettcp
            NetTcpBinding ws = new NetTcpBinding();

            ws.MaxReceivedMessageSize = 2147483647;
            ws.MaxBufferPoolSize      = 2147483647;
            ws.MaxReceivedMessageSize = 2147483647;
            ws.ReaderQuotas.MaxStringContentLength = 2147483647;
            ws.Security.Mode = SecurityMode.None;
            //通过回调函数,bingding,和address 就不用config了
            DuplexChannelFactory <ImyService> mcf =
                new DuplexChannelFactory <ImyService>(this, ws, address);

            return(mcf.CreateChannel());
        }
Exemple #36
0
        /// <summary>
        /// This method is opening channel to the NMS
        /// </summary>
        private void OpenChannel()
        {
            DuplexChannelFactory <INMSSubscriber> factory = new DuplexChannelFactory <INMSSubscriber>(
                new InstanceContext(instance),
                new NetTcpBinding(),
                new EndpointAddress("net.tcp://localhost:10010/INMSSubscriber"));

            try
            {
                proxy = factory.CreateChannel();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Exemple #37
0
        public PlayerCommunicationClient(Guid serverId)
        {
            //var factory = new DuplexChannelFactory<PlayerCommunicationServiceInterface>(new InstanceContext(this), new NetNamedPipeBinding(), new EndpointAddress($"net.pipe://localhost/LogRecorderAndPlayer/{serverId.ToString().Replace("-", "")}/{serverId.ToString().Replace("-", "")}"));
            var binding = new NetNamedPipeBinding();

            binding.Security.Mode = NetNamedPipeSecurityMode.None;
            binding.Security.Transport.ProtectionLevel = ProtectionLevel.None;
            var factory = new DuplexChannelFactory <PlayerCommunicationServiceInterface>(new InstanceContext(this), binding, new EndpointAddress($"net.pipe://localhost/{serverId.ToString().Replace("-", "")}/LRAPService{serverId.ToString().Replace("-", "")}"));

            //            var factory = new DuplexChannelFactory<INamedPipeService>(new InstanceContext(this), new NetNamedPipeBinding(), new EndpointAddress($"net.pipe://localhost/{serverId.ToString().Replace("-", "")}/LRAPService"));
            Proxy = factory.CreateChannel();

            ((IClientChannel)Proxy).Faulted += NamedPipeClient_Faulted;
            ((IClientChannel)Proxy).Opened  += NamedPipeClient_Opened;
            ((IClientChannel)Proxy).Open();
        }
Exemple #38
0
        // Connect to the service
        public void connect()
        {
            var binding        = new NetTcpBinding();
            var endpoint       = new EndpointAddress("net.tcp://localhost:9000/IGameService");
            var channelFactory = new DuplexChannelFactory <IServiceInterface>(callback, binding, endpoint);

            try
            {
                connection = channelFactory.CreateChannel();
                getCommObj().Open();
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Exception on connecting to service: " + ex);
            }
        }
Exemple #39
0
        private void Disconnect()
        {
            if (factory != null)
            {
                try
                {
                    factory.Close(TimeSpan.FromSeconds(2.0));
                }
                catch (TimeoutException)
                {
                    factory.Abort();
                }
            }

            factory = null;
        }
Exemple #40
0
        public static T Get <T>(string connectionString, object callbackImplementation, IEndpointBehavior behavior = null)
        {
            PropertyString           connectionProperties = new PropertyString(connectionString);
            bool                     isWindowsCredential;
            NetTcpBinding            binding         = getBinding(connectionProperties, out isWindowsCredential);
            EndpointAddress          endPointAddress = getEndPoint(connectionProperties, isWindowsCredential);
            InstanceContext          instanceContext = new InstanceContext(callbackImplementation);
            DuplexChannelFactory <T> factory         = new DuplexChannelFactory <T>(instanceContext, binding, endPointAddress);

            if (behavior != null)
            {
                factory.Endpoint.EndpointBehaviors.Add(behavior);
            }
            setupFactory(factory, connectionProperties, isWindowsCredential);
            return(factory.CreateChannel());
        }
Exemple #41
0
        public void ConnectToCalculationEngine()
        {
            // Capture the UI synchronization context
            _uiSyncContext = SynchronizationContext.Current;
            // The client callback interface must be hosted for the server to invoke the callback
            // Open a connection to the message service via the proxy

            factory = new DuplexChannelFactory <ICacheService>(
                new InstanceContext(this),
                new NetTcpBinding(),
                new EndpointAddress("net.tcp://localhost:10012/ICacheService"));
            proxy = factory.CreateChannel();
            proxy.Register("");

            //put a button window closing so that we can unsubscribe from ds
        }
Exemple #42
0
        public static IGinService CreateServiceClient(object context, int port)
        {
            var iContext  = new InstanceContext(context);
            var myBinding = new WSDualHttpBinding
            {
                ClientBaseAddress = new Uri(@"http://localhost:8738/GinService/ShellExtension/" + port)
            };
            var endpointIdentity = EndpointIdentity.CreateDnsIdentity("localhost");
            var myEndpoint       = new EndpointAddress(new Uri("http://localhost:8733/GinService/"), endpointIdentity);

            var myChannelFactory = new DuplexChannelFactory <IGinService>(iContext, myBinding, myEndpoint);

            var client = myChannelFactory.CreateChannel();

            return(client);
        }
Exemple #43
0
        static void Main(string[] args)
        {
            InstanceContext instanceContext = new InstanceContext(new CalculateCallback());

            using (DuplexChannelFactory <ICalculator> channelFactory = new DuplexChannelFactory <ICalculator>(instanceContext, "CalculatorService"))
            {
                ICalculator proxy = channelFactory.CreateChannel();

                using (proxy as IDisposable)
                {
                    proxy.Add(1, 2);

                    Console.Read();
                }
            }
        }
        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;

            _pexeso_Page = new Pexeso_Page(this);
            var client = new DuplexChannelFactory <IPexesoService>(instanceContext, "PexesoClient");

            _pexesoServiceClient = client.CreateChannel();

            InvitationResultCame += MainWindow_InvitationResultCame;
            _activePlayers_Page   = new ActivePlayers_Page(this);
            _frame_Main           = new Frame();
            _frame_Main.SetValue(Grid.RowProperty, 1);
            Grid_Main.Children.Add(_frame_Main);
        }
Exemple #45
0
        public MainWindow()
        {
            InitializeComponent();
            channelFactory = new DuplexChannelFactory <IMessengerService>(new ClientCallback(), "MessageServiceEndPoint");
            Server         = channelFactory.CreateChannel();
            UserName       = Environment.UserName;
            mutex          = new Mutex(true, MutexName, out createdNew);
            if (!createdNew)
            {
                // Show opened App
                MessageBox.Show("This program is already running");
                Application.Current.Shutdown(0);
            }

            Server.Login(UserName);
        }
Exemple #46
0
 private void CreateProxy()
 {
     try
     {  //***git
         NetTcpBinding   netTcpbinding   = new NetTcpBinding();
         EndpointAddress endpointAddress = new EndpointAddress("net.tcp://localhost:7002/Sub");
         InstanceContext callback        = new InstanceContext(this);
         DuplexChannelFactory <ISubscription> channelFactory = new DuplexChannelFactory <ISubscription>(callback, netTcpbinding, endpointAddress);
         subscriptionProxy = channelFactory.CreateChannel();
     }
     catch (Exception e)
     {
         throw e;
         //TODO  Log error : PubSub not started
     }
 }
Exemple #47
0
        // DuplexChannelBase

        IPeerConnectorClient CreateInnerClient(RemotePeerConnection conn)
        {
            conn.Instance = new LocalPeerReceiver(this);
            conn.Instance.WelcomeReceived += delegate(WelcomeInfo welcome) {
                conn.NodeId = welcome.NodeId;
                // FIXME: handle referrals
            };

            // FIXME: pass more setup parameters
            var binding = new NetTcpBinding();

            binding.Security.Mode = SecurityMode.None;
            var channel_factory = new DuplexChannelFactory <IPeerConnectorClient> (conn.Instance, binding);

            return(channel_factory.CreateChannel(new EndpointAddress("net.p2p://" + node.MeshId + "/"), conn.Address.EndpointAddress.Uri));
        }
        public MainWindow()
        {
            InitializeComponent();

            _channelfactory = new DuplexChannelFactory <IChattingService>(new ClientCallback(), "ChattingServiceEndPoint");

            Server = _channelfactory.CreateChannel();

            btn_Send.Click   += btn_Send_Click;
            btn_Login.Click  += btn_Login_Click;
            btn_Logout.Click += btn_Logout_Click;
            btn_Update.Click += btn_Update_Click;

            this.Closed     += MainWindow_Closed;
            this.DataContext = this;
        }
Exemple #49
0
        protected override void OnServiceStarted()
        {
            var channelFactory = new DuplexChannelFactory <TServiceInterface>(this, NetworkingExtensions.GetServiceBinding(_protocol));

            TestService = channelFactory.CreateChannel(new EndpointAddress(ServiceUri));
            try
            {
                _serviceProcessId = TestService.Initialize();
            }
            catch (Exception e)
            {
                _failReason = new SerializableException(e);
                TestService = null;
            }
            _serviceStartedEvent.Set();
        }
        private void StartClient()
        {
            var group = GetServiceModelSectionGroup();

            if (group != null)
            {
                var pipeFactory = new DuplexChannelFactory <IReplicatorService>(ReplicatorServiceCallback, group.Client.Endpoints[0].Name);
                _pipeProxy = pipeFactory.CreateChannel();
                ((IClientChannel)_pipeProxy).Open();
                _pipeProxy.RegisterForUpdates();
            }
            else
            {
                throw new ConfigurationErrorsException("Нет необходомой конфигурации system.serviceModel");
            }
        }
Exemple #51
0
        public static IReadService CreateChannelTools()
        {
            lock (mutexCreateChannel)
            {
                try
                {
                    if (Channelclient != null)
                    {
                        return(Channelclient);
                    }
                    InstanceContext ic = null;
                    HOST = $"{Registry.GetValue("HKEY_CURRENT_USER\\Software\\FormConfiguration", "IPAddress", null)}";
                    if (Registry.GetValue("HKEY_CURRENT_USER\\Software\\FormConfiguration", "Port", null) == null)
                    {
                        return(null);
                    }
                    PORT = ushort.Parse(
                        $"{Registry.GetValue("HKEY_CURRENT_USER\\Software\\FormConfiguration", "Port", null)}");

                    ic = new InstanceContext(new ReadServiceCallbackClient());
                    // Create a channel factory.
                    var b = new NetTcpBinding();
                    b.Security.Mode = SecurityMode.Transport;
                    b.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows;
                    b.Security.Transport.ProtectionLevel      = ProtectionLevel.EncryptAndSign;

                    b.MaxBufferSize          = 1000000;
                    b.MaxBufferPoolSize      = 1000000;
                    b.MaxReceivedMessageSize = 1000000;
                    b.OpenTimeout            = TimeSpan.FromMinutes(2);
                    b.SendTimeout            = TimeSpan.FromMinutes(2);
                    b.ReceiveTimeout         = TimeSpan.FromMinutes(10);

                    var endPoint =
                        new EndpointAddress(
                            new Uri($"net.Tcp://{HOST}:{PORT}/AdvancedScada/{CHANNEL}"));
                    var factory = new DuplexChannelFactory <IReadService>(ic, b, endPoint);
                    Channelclient = factory.CreateChannel();
                }
                catch (CommunicationException ex)
                {
                    var err = new HMIException.ScadaException("ServiceBaseClient", ex.Message);
                }
            }

            return(Channelclient);
        }
Exemple #52
0
        private void MakeTraceProxy(object callbackinstance, string endpointConfigurationName)
        {
            InstanceContext context = new InstanceContext(callbackinstance);

            context.SynchronizationContext = new SubContext();

            // if no endpoint configuratino passed, it will default to the enpointname in SubscriptionServiceClientEndpoint setting

            if (!string.IsNullOrEmpty(endpointConfigurationName))
            {
                //Use endpoint specified in SubscriptionServiceClientEndpoint setting
                m_endpointName   = endpointConfigurationName;
                m_ChannelFactory = new DuplexChannelFactory <ISubscriptionService>(context, m_endpointName);
            }
            else
            {
                //Use endpoint with the ISubscriptionService contract
                lock (locked)
                {
                    if (string.IsNullOrEmpty(m_endpointName))
                    {
                        ClientSection sectionGroup = ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;

                        foreach (ChannelEndpointElement endpoint in sectionGroup.Endpoints)
                        {
                            if (endpoint.Contract.EndsWith(".ISubscriptionService"))
                            {
                                //m_subEndpoint = endpoint;
                                m_endpointName = endpoint.Name;
                                break;
                            }
                        }
                        if (string.IsNullOrEmpty(m_endpointName))
                        {
                            throw new Exception("Unable to find endpoint configured for the ISubscriptionService contract.");
                        }
                    }
                }
                m_ChannelFactory = new DuplexChannelFactory <ISubscriptionService>(context, m_endpointName);
            }

            m_ChannelFactory.Faulted += new EventHandler(ChannelFactory_Faulted);


            m_Client = m_ChannelFactory.CreateChannel();
            ((ICommunicationObject)m_Client).Faulted += new EventHandler(ClientChannel_Faulted);
        }
Exemple #53
0
 private void BuildListenClientService()
 {
     if (listenServiceFactory == null)
     {
         if (string.IsNullOrEmpty(serviceHostAddr))
         {
             serviceHostAddr = System.Configuration.ConfigurationManager.AppSettings["ServiceHostAddr"];
         }
         InstanceContext instanceContext = new InstanceContext(instance);
         NetTcpBinding   binding         = new NetTcpBinding();
         binding.ReceiveTimeout = new TimeSpan(0, 5, 0);
         binding.SendTimeout    = new TimeSpan(0, 5, 0);
         Uri baseAddress = new Uri(string.Format("net.tcp://{0}/ListenService", serviceHostAddr));
         listenServiceFactory = new DuplexChannelFactory <IListenService>(instanceContext, binding, new EndpointAddress(baseAddress));
     }
     proxyListenService = listenServiceFactory.CreateChannel();
 }
Exemple #54
0
        public void InitializeNotify()
        {
            try
            {
                //将回调类型的实例传递给通道
                DuplexChannelFactory <IPushService> channel = new DuplexChannelFactory <IPushService>(new InstanceContext(this), "push");
                _pushProxy = channel.CreateChannel();
                _pushProxy.Regist(_id);

                Rectangle rct = Screen.AllScreens[0].WorkingArea;
                this.Left = rct.Width - this.Width - 5;
                this.Top  = rct.Height;
            }
            catch
            {
            }
        }
Exemple #55
0
        /// <summary>
        /// Create a connection to a musicplayer server.
        /// </summary>
        /// <param name="player">The musicplayer.</param>
        /// <param name="address">The server ip address.</param>
        /// <param name="port">The server port.</param>
        public ClientConnection(IMusicPlayer player, IPAddress address, int port) : base(player)
        {
            _client = new WCFServerClient(this);
            var serviceAddress = $"net.tcp://{address}:{port}/";
            var binding        = new NetTcpContextBinding(SecurityMode.None)
            {
                CloseTimeout           = new TimeSpan(0, 1, 0),
                ReceiveTimeout         = new TimeSpan(1, 0, 0),
                SendTimeout            = new TimeSpan(0, 1, 0),
                MaxReceivedMessageSize = 100000000
            };

            // 100Mb
            _factory = new DuplexChannelFactory <IServerContract>(new InstanceContext(_client), binding, serviceAddress);
            _server  = _factory.CreateChannel();
            _server.Anounce();
        }
Exemple #56
0
        public void CallAsync_noServer_done()
        {
            var address = @"net.pipe://127.0.0.1/" + this.GetType().Name + "_" + MethodBase.GetCurrentMethod().Name;
            var binding = new NetNamedPipeBinding();

            var callback = new AsyncServiceCallback();


            using (var factory = new DuplexChannelFactory <IAsyncService>(new InstanceContext(callback), binding))
            {
                var           client = factory.CreateChannel(new EndpointAddress(address));
                AsyncCallback act    = x => Assert.AreEqual(x.AsyncState, 1);
                IAsyncResult  result = client.BeginServiceAsyncMethod(act, 1);
                result.AsyncWaitHandle.WaitOne();
                Assert.AreEqual(result.AsyncState, 1);
            }
        }
Exemple #57
0
        private static void StartClient2(string address)
        {
            Console.WriteLine("Server address = " + address);
            var clb = new CallbackServiceCallback();

            Console.WriteLine("Client started");
            var factory = new DuplexChannelFactory <ICallbackService2>(new InstanceContext(clb),
                                                                       _binding);
            var client = factory.CreateChannel(new EndpointAddress(address));

            for (int i = 0; i < 6; i++)
            {
                client.CallOneWay(new CallData());
                client.Call();
                Thread.Sleep(new Random((int)DateTime.Now.Ticks).Next(2000, 3000));
            }
        }
Exemple #58
0
    public static void CreateChannel_Using_Http_NoSecurity()
    {
        WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback();
        InstanceContext          context  = new InstanceContext(callback);
        Binding         binding           = new NetHttpBinding(BasicHttpSecurityMode.None);
        EndpointAddress endpoint          = new EndpointAddress(FakeAddress.HttpAddress);
        DuplexChannelFactory <IWcfDuplexService> factory = new DuplexChannelFactory <IWcfDuplexService>(context, binding, endpoint);

        // Can't cast to IDuplexSessionChannel to IRequestChannel on http
        var exception = Assert.Throws <InvalidCastException>(() =>
        {
            factory.CreateChannel();
        });

        // Can't check that the InvalidCastException message as .NET Native only reports this message for all InvalidCastExceptions:
        // "System.InvalidCastException: Arg_InvalidCastException"
    }
Exemple #59
0
        static void Main(string[] args)
        {
            var ctx = new InstanceContext(new ChatCallback());
            //var chatClient = new ConsoleModeChatClient.ChatClient.ChatSvcClient(ctx);
            var chatClient = new DuplexChannelFactory <ChatClient.IChat>(ctx, "netTcpBinding.ChatSvc").CreateChannel();
            var name       = args.Count() == 0 ? "Mr Nobody" : args[0];

            chatClient.join(name);
            string what = ReadAndPrompt(name);

            while (what != null)
            {
                chatClient.send(what);
                what = ReadAndPrompt(name);
            }
            chatClient.leave();
        }
Exemple #60
0
 private void Close()
 {
     m_working = false;
     try
     {
         if (null != m_clientChannel)
         {
             ((ICommunicationObject)m_clientChannel).Close();
         }
     }
     catch (CommunicationException commEx)
     {
         Error(string.Format("Communication when closing channel: {0}", commEx.Message));
         ((ICommunicationObject)m_clientChannel).Abort();
     }
     catch (Exception ex)
     {
         Error(string.Format("Exception when closing channel: {0}", ex.Message));
         ((ICommunicationObject)m_clientChannel).Abort();
     }
     finally
     {
         m_clientChannel = null;
     }
     try
     {
         if (null != m_factory)
         {
             m_factory.Close();
         }
     }
     catch (CommunicationException commEx)
     {
         Error(string.Format("Communication when closing factory: {0}", commEx.Message));
         m_factory.Abort();
     }
     catch (Exception ex)
     {
         Error(string.Format("Exception when closing factory: {0}", ex.Message));
         m_factory.Abort();
     }
     finally
     {
         m_factory = null;
     }
 }