Пример #1
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();
            }
        }
    }
Пример #2
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);
        }
    }
        /// <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;
                }
            }
        }
        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();
        }
Пример #5
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.");
 }
    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();
            }
        }
    }
Пример #7
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;
            }
        }
Пример #8
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);
            }
        }
Пример #9
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;
            }
        }
Пример #10
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();
        }
Пример #11
0
        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);
                    }

                }
            }
        }
Пример #12
0
        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);
            }
        }
Пример #13
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();
			}
		}
Пример #14
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();
 }
        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);
            }
        }
Пример #16
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();
        }
Пример #17
0
        public void CallLocalService()
        {
            var address = @"ipc:///1/test.test/test" + MethodBase.GetCurrentMethod().Name;
            var binding = new LocalBinding();

            var data = new CallbackData { Data = "1" };
            var srv = new CallbackService(data);
            var callback = new CallbackServiceCallback();

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

                using (var factory = new DuplexChannelFactory<ICallbackService>(new InstanceContext(callback), binding))
                {
                    var client = factory.CreateChannel(new EndpointAddress(address));
                    client.Call();
                }

                callback.Wait.WaitOne();

                Assert.AreEqual(data.Data, callback.Called.Data);
            }
        }
Пример #18
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);
            }
        }
Пример #19
0
 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);
 }
Пример #20
0
        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();
            }
        }
Пример #21
0
 public ClientViewModel()
 {
     var channelFactory = new DuplexChannelFactory<IChattingService>(new ClientService(), "ChattingServiceEndPoint");
     _server = channelFactory.CreateChannel();
     This = this;
     CreateCommands();
 }
        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();
        }
Пример #23
0
        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);
            }

        }
Пример #24
0
    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);
        }
    }
Пример #25
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();
           
        }
Пример #26
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();
        }
Пример #27
0
        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;
        }
Пример #28
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();
            }
        }
Пример #29
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);
            }
        }
Пример #30
0
        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);
            }
        }
    // Asking for ChainTrust only should succeed if the certificate is
    // chain-trusted.
    public static void NetTcp_SecModeTrans_Duplex_Callback_Succeeds()
    {
        string          clientCertThumb = null;
        EndpointAddress endpointAddress = null;
        DuplexChannelFactory <IWcfDuplexService> factory = null;
        IWcfDuplexService serviceProxy = null;
        Guid guid = Guid.NewGuid();

        try
        {
            // *** SETUP *** \\
            NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport);
            binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Certificate;

            endpointAddress = new EndpointAddress(new Uri(
                                                      Endpoints.Tcp_Certificate_Duplex_Address));
            clientCertThumb = ServiceUtilHelper.ClientCertificate.Thumbprint;

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

            factory = new DuplexChannelFactory <IWcfDuplexService>(context, binding, endpointAddress);
            factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.ChainTrust;
            factory.Credentials.ClientCertificate.SetCertificate(
                StoreLocation.CurrentUser,
                StoreName.My,
                X509FindType.FindByThumbprint,
                clientCertThumb);

            serviceProxy = factory.CreateChannel();

            // *** EXECUTE *** \\
            // Ping on another thread.
            Task.Run(() => serviceProxy.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 *** \\
            ((ICommunicationObject)serviceProxy).Close();
            ((ICommunicationObject)factory).Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
        protected override void OnStart(string[] args)
        {
            Common.InitialiseLogFolder();

            logging.AddToLog("OnStart", true);

            InstanceContext site       = new InstanceContext(this);
            NetTcpBinding   tcpBinding = new NetTcpBinding();

            tcpBinding.TransactionFlow         = false;
            tcpBinding.ReliableSession.Ordered = true;
            tcpBinding.Security.Message.ClientCredentialType   = MessageCredentialType.None;
            tcpBinding.Security.Transport.ProtectionLevel      = System.Net.Security.ProtectionLevel.None;
            tcpBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
            tcpBinding.Security.Mode = SecurityMode.None;

            EndpointAddress myEndpoint       = new EndpointAddress("net.tcp://" + Common.DBConnection + ":8731/WCFService/");
            var             myChannelFactory = new DuplexChannelFactory <IWCFService>(site, tcpBinding);


            wcfObj = myChannelFactory.CreateChannel(myEndpoint);
            wcfObj.Subscribe();

            Common.CreateComputerObject(sourceName);

            try
            {
                logging.AddToLog("Creating Service object", true);
                OSAEObject svcobj = OSAEObjectManager.GetObjectByName("SERVICE-" + Common.ComputerName);
                if (svcobj == null)
                {
                    OSAEObjectManager.ObjectAdd("SERVICE-" + Common.ComputerName, "SERVICE-" + Common.ComputerName, "SERVICE", "", "SYSTEM", true);
                }
                OSAEObjectStateManager.ObjectStateSet("SERVICE-" + Common.ComputerName, "ON", sourceName);
            }
            catch (Exception ex)
            {
                logging.AddToLog("Error creating service object - " + ex.Message, true);
            }

            if (connectToService())
            {
                Thread loadPluginsThread = new Thread(new ThreadStart(LoadPlugins));
                loadPluginsThread.Start();
            }

            //Clock.Interval = 5000;
            //Clock.Start();
            //Clock.Elapsed += new System.Timers.ElapsedEventHandler(checkConnection);
        }
Пример #33
0
        private void Login(object sender, RoutedEventArgs e)
        {
            try
            {
                // var tcpBind = new NetTcpBinding();
                // tcpBind.MaxReceivedMessageSize = int.MaxValue;
                // tcpBind.Security.Mode = SecurityMode.Transport;
                //
                //
                // var cf = new DuplexChannelFactory<IServer>(new InstanceContext(this), tcpBind, new EndpointAddress("net.tcp://192.168.178.56:1"));
                // cf.Credentials.Windows.ClientCredential.UserName = "******";
                // cf.Credentials.Windows.ClientCredential.Password = "******";


                var tcpBind = new NetTcpBinding();
                tcpBind.MaxReceivedMessageSize = int.MaxValue;
                tcpBind.Security.Mode          = SecurityMode.TransportWithMessageCredential;
                tcpBind.Security.Transport.ClientCredentialType = TcpClientCredentialType.Certificate;



                var dual = new WSDualHttpBinding();
                dual.Security.Mode = WSDualHttpSecurityMode.Message;
                dual.Security.Message.ClientCredentialType       = MessageCredentialType.Certificate;
                dual.Security.Message.NegotiateServiceCredential = true;

                //var cf = new DuplexChannelFactory<IServer>(new InstanceContext(this), dual, new EndpointAddress("http://192.168.178.56:2"));


                EndpointIdentity identity = EndpointIdentity.CreateDnsIdentity("RootCA");
                EndpointAddress  address  = new EndpointAddress(new Uri("net.tcp://DESKTOP-MFV9PIV:3"), identity);

                var cf = new DuplexChannelFactory <IServer>(new InstanceContext(this), tcpBind, address);
                cf.Credentials.ClientCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, "db56b195af62c2e65ae9243deac64eba8a34ed73");
                cf.Credentials.Windows.ClientCredential.UserName = "******";
                cf.Credentials.Windows.ClientCredential.Password = "******";
                cf.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;


                server = cf.CreateChannel();

                server.Login(nameTb.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Fehler:{ex.Message}");
                Debugger.Break();
            }
        }
Пример #34
0
        public NebulaMasterServiceCB(string sAddr, int iPort)
        {
            NetTcpBinding hBinding = new NetTcpBinding();

            //hBinding.MaxBufferPoolSize                              = 0;
            //hBinding.MaxBufferSize                                  = 51200;
            hBinding.MaxReceivedMessageSize = 2147483647;
            hBinding.Security.Mode          = SecurityMode.None;
            EndpointAddress hAddr = new EndpointAddress($"net.tcp://{sAddr}:{iPort}/NebulaMasterService");
            DuplexChannelFactory <INebulaMasterService> hFactory = new DuplexChannelFactory <INebulaMasterService>(typeof(NebulaMasterServiceCB), hBinding, hAddr);

            Service = hFactory.CreateChannel(new InstanceContext(this));

            m_hModules = new List <INebulaModule>();

            IEnumerable <INebulaModule> hModules = from hA in Directory.GetFiles(Environment.CurrentDirectory, "*.dll").SafeSelect(hF => Assembly.UnsafeLoadFrom(hF))
                                                   from hT in hA.GetTypes()
                                                   from hI in hT.GetInterfaces()
                                                   where hI == typeof(INebulaModule)
                                                   select Activator.CreateInstance(hT) as INebulaModule;                     //Manco dante porcoddio

            foreach (INebulaModule hModule in hModules)
            {
                try
                {
                    hModule.Start(Service);
                    m_hModules.Add(hModule);
                }
                catch (Exception)
                {
                    //Skip faulted modules
                }
            }

            NebulaModuleInfo[] hModuleInfos = m_hModules.Select(x => x.ModuleInfo).ToArray();
            Service.Register(Environment.MachineName, hModuleInfos);

            foreach (INebulaModule hModule in m_hModules)
            {
                try
                {
                    hModule.RegistrationComplete();
                }
                catch (Exception)
                {
                    //Skip faulted modules
                }
            }
        }
Пример #35
0
        } // end of method

        /// <summary>
        /// GetMessageHistory
        /// Gets a list of ChatMessages to update
        /// the UI list box
        /// </summary>
        private void UpdateMessageHistoryUI()
        {
            // If User is Not Logged In
            if (!IsUserLoggedIn(userName))
            {
                return;
            }

            // Clear the List Box
            lstChatMessages.Items.Clear();

            // Temporary variable to hold the list of chat messages
            List <ChatMessage> historyChat;

            // Retrieve the New Messages
            DuplexChannelFactory <IChatService> cf = new DuplexChannelFactory <IChatService>(this, "NetTcpBinding_IChatService");

            cf.Open();
            IChatService proxy = cf.CreateChannel();

            if (proxy != null)
            {
                try
                {
                    // retrieve the chat history
                    historyChat = proxy.GetMessageHistory();

                    // Update the UI
                    foreach (ChatMessage item in historyChat)
                    {
                        lstChatMessages.Items.Add(item);
                    }

                    IsChatHistoryLoaded = true;
                }     // end of try

                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace + "." + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name);
                    MessageBox.Show(ex.Message);
                }
            }     // end of if

            else
            {
                // Cannot Connect to Server
                MessageBox.Show("Cannot Create a Channel to a Proxy. Check Your Configuration Settings.", "Proxy", MessageBoxButtons.OK);
            }     // end of else
        } // end of method
Пример #36
0
    public static void DuplexCallback_Throws_FaultException_ReturnsFaultedTask()
    {
        DuplexChannelFactory <IWcfDuplexTaskReturnService> factory = null;
        Guid          guid    = Guid.NewGuid();
        NetTcpBinding binding = null;
        DuplexTaskReturnServiceCallback callbackService = null;
        InstanceContext             context             = null;
        EndpointAddress             endpointAddress     = null;
        IWcfDuplexTaskReturnService serviceProxy        = null;

        // *** VALIDATE *** \\
        FaultException <FaultDetail> exception = Assert.Throws <FaultException <FaultDetail> >(() =>
        {
            // *** SETUP *** \\
            binding = new NetTcpBinding();
            binding.Security.Mode = SecurityMode.None;
            endpointAddress       = new EndpointAddress(Endpoints.Tcp_NoSecurity_TaskReturn_Address);
            callbackService       = new DuplexTaskReturnServiceCallback();
            context      = new InstanceContext(callbackService);
            factory      = new DuplexChannelFactory <IWcfDuplexTaskReturnService>(context, binding, endpointAddress);
            serviceProxy = factory.CreateChannel();

            // *** EXECUTE *** \\
            try
            {
                Task <Guid> task = serviceProxy.FaultPing(guid);
                if ((task as IAsyncResult).AsyncWaitHandle.WaitOne(ScenarioTestHelpers.TestTimeout))
                {
                    Guid returnedGuid = task.GetAwaiter().GetResult();
                }
                else
                {
                    throw new TimeoutException(String.Format("The call to the Service did not complete within the alloted time of: {0}", ScenarioTestHelpers.TestTimeout));
                }
            }
            finally
            {
                // *** ENSURE CLEANUP *** \\
                ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
            }
        });

        // *** ADDITIONAL VALIDATION *** \\
        string exceptionCodeName = "ServicePingFaultCallback";
        string exceptionReason   = "Reason: Testing FaultException returned from Duplex Callback";

        Assert.True(String.Equals(exceptionCodeName, exception.Code.Name), String.Format("Expected exception code name: {0}\nActual exception code name: {1}", exceptionCodeName, exception.Code.Name));
        Assert.True(String.Equals(exceptionReason, exception.Reason.GetMatchingTranslation().Text), String.Format("Expected exception reason: {0}\nActual exception reason: {1}", exceptionReason, exception.Reason.GetMatchingTranslation().Text));
    }
        private T CreateProductService <T>(string serviceName)
        {
            var binding = new NetTcpBinding()
            {
                MaxBufferPoolSize = 2147483647, MaxReceivedMessageSize = 2147483647
            };

            binding.Security.Mode = SecurityMode.None;
            var factory = new DuplexChannelFactory <T>(
                new WCFClientCallbackManager(),
                binding,
                new EndpointAddress(string.Format("net.tcp://{0}:{1}/{2}", _address, _port, serviceName)));

            return(factory.CreateChannel());
        }
Пример #38
0
        private static void DuplexSample()
        {
            var binding = new WSDualHttpBinding();
            var address =
                new EndpointAddress("http://localhost:8733/Design_Time_Addresses/MessageService/Service1/");

            var clientCallback = new ClientCallback();
            var context        = new InstanceContext(clientCallback);

            var factory = new DuplexChannelFactory <IMyMessage>(context, binding, address);

            IMyMessage messageChannel = factory.CreateChannel();

            messageChannel.MessageToServer("From the server");
        }
Пример #39
0
 private void CreateProxy()
 {
     try
     {
         EndpointAddress endpointAddress = new EndpointAddress("net.tcp://localhost:3002/Sub");
         InstanceContext callback        = new InstanceContext(this);
         DuplexChannelFactory <ISubscription> channelFactory = new DuplexChannelFactory <ISubscription>(callback, NetTcpBindingCreator.Create(), endpointAddress);
         subscriptionProxy = channelFactory.CreateChannel();
     }
     catch (Exception e)
     {
         throw e;
         //TODO  Log error : PubSub not started
     }
 }
Пример #40
0
        /// <summary>
        /// 콜백객체를 사용할 경우의 웹서비스 프록시 반환
        /// </summary>
        /// <param name="webServiceUrl"></param>
        /// <param name="ClientCallback">
        /// IWebServiceCallback을 구현한 클라이언트 측의 객체를 래핑한 InstanceContext객체
        /// EX)
        /// WebServiceCallback callback = new WebServiceCallback();
        /// InstanceContext ctx = new InstanceContext(callback); 에서 ctx
        /// </param>
        /// <returns>
        /// 채널이 연결된 웹서비스객체
        /// </returns>
        private IWebService CallWebserviceUsingCallback(string webServiceUrl, DuplexChannelFactory <IWebService> WebServiceChannel, InstanceContext ClientCallback)
        {
            EndpointAddress epa = new EndpointAddress(
                new Uri(webServiceUrl),
                new DnsEndpointIdentity(System.IdentityModel.Claims.Claim.CreateDnsClaim("HTPSecureManager"))
                );

            IWebService webservice = WebServiceChannel.CreateChannel
                                     (
                ClientCallback,
                epa
                                     );

            return(webservice);
        }
Пример #41
0
        /// <summary>
        /// Creates a service connection to the callback service behind the specified service interface.
        /// Please prefer <see cref="M:GetServiceWrapper{T}()"/> method!
        /// See documentation for further information.
        /// </summary>
        /// <remarks>Use this method only if you need to keep a connection to a service open longer than possible with <see cref="M:GetServiceWrapper{T}()"/>.
        /// When finished with the work (or it is safe to release the instance), make a call to <see cref="M:CloseServiceInstance(object)"/> to safely close and dispose the service connection.</remarks>
        /// <typeparam name="T">The service interface type.</typeparam>
        /// <param name="callbackObject">The object representing the callback to use. Must not be null.</param>
        /// <returns>A service connection to the service behind the specified service interface.</returns>
        public static T GetCallbackServiceInstance <T>(object callbackObject) where T : class, IExposedService
        {
            AssertContractTypeCorrect(typeof(T));
            Assertions.AssertNotNull(callbackObject, "callbackObject");

            Binding binding = ServiceBindingCache.GetBindingForContractType(typeof(T));
            DuplexChannelFactory <T> factory = new DuplexChannelFactory <T>(callbackObject, binding, GetEndpointAddress(typeof(T), binding));

            ApplyX509IfConfigured(factory);

            T channel = factory.CreateChannel();

            channel.Ping();
            return(channel);
        }
        static void Main(string[] args)
        {
            Console.Title = "Client";
            Console.WriteLine("Press Enter when the service is ready");
            Console.ReadLine();

            InstanceContext context = new InstanceContext(new StockCallback());
            DuplexChannelFactory <IStock> factory = new DuplexChannelFactory <IStock>(context, "StockEP");
            IStock proxy = factory.CreateChannel();

            proxy.RegisterForQuote("MSFT");

            Console.WriteLine("Waiting for stock updates. Press Enter to stop");
            Console.ReadLine();
        }
Пример #43
0
        private void MaterialFlatButton1_Click(object sender, EventArgs e)
        {
            var netTcp = new NetTcpBinding();

            netTcp.MaxReceivedMessageSize = int.MaxValue;
            netTcp.Security.Mode          = SecurityMode.Message;

            var cf = new DuplexChannelFactory <IServer>(this, netTcp, new EndpointAddress("net.tcp://192.168.2.39:1"));

            cf.Credentials.Windows.ClientCredential.UserName = "******";
            cf.Credentials.Windows.ClientCredential.Password = "******";

            server = cf.CreateChannel();
            server.Login(userNameTextBox.Text);
        }
Пример #44
0
        public static T CreateMaxItemsChannel <T>(InstanceContext callbackInstance, Binding binding, EndpointAddress endpoint)
        {
            DuplexChannelFactory <T> factory = new DuplexChannelFactory <T>(callbackInstance, binding, endpoint);

            foreach (OperationDescription op in factory.Endpoint.Contract.Operations)
            {
                var dataContractBehavior = op.Behaviors.Find <DataContractSerializerOperationBehavior>();
                if (dataContractBehavior != null)
                {
                    dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
                }
            }

            return(factory.CreateChannel());
        }
Пример #45
0
        } // END PlayLetter_Click()




        /************************
        *     HELPER METHODS    *
        ************************/

        /*
         * Purpose: Creates object that implements the callback contract.
         *          Initialization done in constructor.
         */
        public void NewGame()
        {
            //Create a Game object with WCF
            channel = new DuplexChannelFactory<IGame>(this, "GameEndPoint");
            newGame = channel.CreateChannel(); //this return IGame interface

            //Register to receive callbacks
            newGame.RegisterForCallbacks();

            // Set new word 
            wordInfo = newGame.SetNewWord();

            LoadCharFields();

        } // END NewGame()
Пример #46
0
        //
        public AgencyClient()
        {
            EndpointAddress   endpointAddress = new EndpointAddress("http://localhost:8090/Agency");
            WSDualHttpBinding binding         = new WSDualHttpBinding();

            binding.ClientBaseAddress = new Uri("http://localhost:808/WSDualOnXP/");

            DuplexChannelFactory <IAgencyService> channelFactory =
                new DuplexChannelFactory <IAgencyService>(
                    this,
                    binding,
                    endpointAddress);

            Channel = channelFactory.CreateChannel();
        }
Пример #47
0
        protected override void OnServiceStarted()
        {
            var channelFactory = new DuplexChannelFactory <TServiceInterface>(this, NetworkingExtensions.GetServiceBinding());

            TestService = channelFactory.CreateChannel(new EndpointAddress(ServiceUri));
            try
            {
                _serviceProcessId = TestService.Initialize();
            }
            catch
            {
                TestService = null;
            }
            _serviceStartedEvent.Set();
        }
Пример #48
0
        public void Start(int iNetPort, int iWebPort, string sMsAddr, int iMsPort)
        {
            MasaterServerEndPoint = new IPEndPoint(IPAddress.Parse(sMsAddr), iMsPort);

            IMasterServer hNewNode = m_hMSChannelFactory.CreateChannel(new EndpointAddress($"net.tcp://{MasaterServerEndPoint.Address}:{MasaterServerEndPoint.Port}/ElysiumMasterServer"));

            (hNewNode as ICommunicationObject).Faulted += OnMasterServerChannelClosed;
            (hNewNode as ICommunicationObject).Closed  += OnMasterServerChannelClosed;


            this.Start(iNetPort, iWebPort);

            hNewNode.Register(iNetPort);
            hNewNode.GetNodes(int.MaxValue).ToList().ForEach(x => this.Connect(x.Address.ToString(), x.Port));
        }
Пример #49
0
        public bool Call <TReturn>(Func <IContract, TReturn> f, out TReturn result)
        {
            result = default;

            try
            {
                result = f(factory.CreateChannel());
            }
            catch (Exception e)
            {
                return(false);
            }

            return(true);
        }
Пример #50
0
        public Form1()
        {
            InitializeComponent();

            InstanceContext instanceContext = new InstanceContext(new CallbackHandler(this));
            //client = new NetFilesServiceClient(instanceContext);

            NetTcpBinding binding = new NetTcpBinding(SecurityMode.None);
            DuplexChannelFactory <INetFilesService> factory = new DuplexChannelFactory <INetFilesService>(instanceContext, binding);
            Uri             adress   = new Uri("net.tcp://astrakhan.chickenkiller.com:8000/NetFilesService");
            EndpointAddress endpoint = new EndpointAddress(adress.ToString());

            //Связь с сервером не устанавливается до тех пор, пока не будет вызван метод Join
            client = factory.CreateChannel(endpoint);
        }
Пример #51
0
 private static void OpenChannel()
 {
     try
     {
         factory = new DuplexChannelFactory <IChatService>(new ChatResult(), "DuplexEP");
         proxy   = factory.CreateChannel();
         //Define an operation timeout to limit the operation time
         ((IClientChannel)proxy).OperationTimeout = TimeSpan.FromSeconds(_connectionTimeoutSeconds);
     }
     catch (Exception e)
     {
         Report.log(DeviceToReport.Client_Proxy, LogLevel.Exception, e.Message);
         throw e;
     }
 }
Пример #52
0
    public static void ServiceContract_TypedProxy_DuplexCallback()
    {
        DuplexChannelFactory <IDuplexChannelService> factory = null;
        StringBuilder errorBuilder = new StringBuilder();
        Guid          guid         = Guid.NewGuid();

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

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

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

            serviceProxy.Ping(guid);
            Guid returnedGuid = callbackService.CallbackGuid;

            if (guid != returnedGuid)
            {
                errorBuilder.AppendLine(String.Format("The sent GUID does not match the returned GUID. Sent: {0} Received: {1}", guid, returnedGuid));
            }

            factory.Close();
        }
        catch (Exception ex)
        {
            errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString()));
            for (Exception innerException = ex.InnerException; innerException != null; innerException = innerException.InnerException)
            {
                errorBuilder.AppendLine(String.Format("Inner exception: {0}", innerException.ToString()));
            }
        }
        finally
        {
            if (factory != null && factory.State != CommunicationState.Closed)
            {
                factory.Abort();
            }
        }

        if (errorBuilder.Length != 0)
        {
            Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: ServiceContract_TypedProxy_DuplexCallback FAILED with the following errors: {0}", errorBuilder));
        }
    }
Пример #53
0
        public iProxy(string strIP, string strPort)
        {
            try
            {
                if (EventLibCallback.oCallBack == null)
                {
                    EventLibrary.EventLibCallback.oCallBack = new EventLibrary.EventLib();
                }


                //EndpointAddress address = new EndpointAddress("net.tcp://" + strIP + ":" + strPort + "/TestWCFService");
                EndpointAddress           address        = new EndpointAddress("net.tcp://localhost:9008/TestWCFService");
                XmlDictionaryReaderQuotas myReaderQuotas = new XmlDictionaryReaderQuotas();
                myReaderQuotas.MaxStringContentLength = Int32.MaxValue;
                myReaderQuotas.MaxArrayLength         = Int32.MaxValue;
                myReaderQuotas.MaxDepth = Int32.MaxValue;

                NetTcpBinding oBinding = new NetTcpBinding();

                oBinding.GetType().GetProperty("ReaderQuotas").SetValue(oBinding, myReaderQuotas, null);
                oBinding.ReceiveTimeout         = new TimeSpan(1, 0, 0);
                oBinding.MaxBufferSize          = Int32.MaxValue;
                oBinding.MaxReceivedMessageSize = Int32.MaxValue;
                oBinding.Security.Mode          = SecurityMode.None;

                DuplexChannelFactory <IService> oCF = new DuplexChannelFactory <IService>(EventLibrary.EventLibCallback.oCallBack, oBinding, address);
                foreach (OperationDescription op in oCF.Endpoint.Contract.Operations)
                {
                    var dataContractBehavior = op.Behaviors.Find <DataContractSerializerOperationBehavior>();
                    if (dataContractBehavior != null)
                    {
                        dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
                    }
                }

                _Service = oCF.CreateChannel();

                oCF.Opened += new EventHandler(oCF_Opened);
                oCF.Closed += new EventHandler(oCF_Closed);

                ((IContextChannel)_Service).OperationTimeout = new TimeSpan(0, 20, 0);
                Status = true;
            }
            catch (Exception ex)
            {
                Status = false;
            }
        }
Пример #54
0
        private async Task TryConnectAsync()
        {
            if (IsConnected)
            {
                await DisconnectAsync(true).ConfigureAwait(false);
            }

            if (string.IsNullOrEmpty(Username) ||
                string.IsNullOrEmpty(ServerAddress))
            {
                StatusMessage = "Could not connect, username or server address invalid";
                return;
            }

            try
            {
                StatusMessage = "Connecting...";
                var binding         = new WSDualHttpBinding();
                var endpoint        = new EndpointAddress(ServerAddress + "/Design_Time_Addresses/ALCS/HiChatService/");
                var instanceContext = new InstanceContext(this);
                var channelFactory  = new DuplexChannelFactory <IHiChatService>(instanceContext,
                                                                                binding, endpoint);
                channel = channelFactory.CreateChannel();
                var task = Task.Run(() => channel.Connect(Username));
                if (await Task.WhenAny(task, Task.Delay(15000)) != task)
                {
                    StatusMessage = "Connection timed out";
                    channel       = null;
                    return;
                }

                if (task.Result == null)
                {
                    StatusMessage = "Could not connect, server refused connection";
                    channel       = null;
                }
                else
                {
                    ConnectedUser = task.Result;
                    StatusMessage = "Connection successful";
                }
            }
            catch (Exception e)
            {
                StatusMessage = $"Could not connect, exception: {e.Message}";
                await DisconnectAsync(false).ConfigureAwait(false);
            }
        }
Пример #55
0
        private void login(object sender, RoutedEventArgs e)
        {
            try
            {
                DuplexChannelFactory <IFishService> channel;
                string hostName = Dns.GetHostName();
                string myIP     = Dns.GetHostByName(hostName).AddressList[0].ToString();
                if (endpoint_box.Text != "")
                {
                    myIP = endpoint_box.Text;
                }
                string endpointStr = "net.tcp://" + myIP + ":13200/CardsLibrary/FishService";
                //channel = new DuplexChannelFactory<IFishService>(this, "FishService", new EndpointAddress( endpointStr));
                //channel.Endpoint.ListenUri = new Uri(endpointStr);
                NetTcpBinding binding = new NetTcpBinding();
                binding.Security.Mode = SecurityMode.None;
                binding.Name          = "FishService";

                channel = new DuplexChannelFactory <IFishService>(this, binding,
                                                                  new EndpointAddress(endpointStr));
                // Activate a MessageBoard object
                fishService = channel.CreateChannel();
            }
            catch (Exception ex)
            {
                ErrorWindow win2 = new ErrorWindow(ex.Message);
                win2.Show();
            }
            try
            {
                if (fishService.AddPlayer(login_box.Text))
                {
                    ViewGameList();

                    user.Username = login_box.Text;
                }
                else
                {
                    ErrorWindow win2 = new ErrorWindow("The username selected is allready in use. Please select another username");
                    win2.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                ErrorWindow win2 = new ErrorWindow(ex.Message);
                win2.Show();
            }
        }
        }     // end of method

        private void UpdateOnlineUsersListboxUI()
        {
            // If User is Not Logged In
            if (LoggedInUser.Username == null)
            {
                MessageBox.Show("Please Login First !");
                return;
            }

            // Clear the List Box
            lbOnlineUsers.Items.Clear();

            // Temporary variable to hold the list of chat messages
            List <string> receivedOnlineUsers;

            // Retrieve the New Messages
            DuplexChannelFactory <IOneToOneChatService> cf = new DuplexChannelFactory <IOneToOneChatService>(this, "NetTcpBinding_IOneToOneChatService");

            cf.Open();
            IOneToOneChatService proxy = cf.CreateChannel();

            if (proxy != null)
            {
                try
                {
                    // retrieve the online username from the server
                    receivedOnlineUsers = proxy.GetAllOnlineUsers(LoggedInUser.Username);

                    // Update the UI
                    foreach (string item in receivedOnlineUsers)
                    {
                        lbOnlineUsers.Items.Add(item);
                    }
                } // end of try

                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace + "." + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name);
                    MessageBox.Show(ex.Message);
                }
            } // end of if

            else
            {
                // Cannot Connect to Server
                MessageBox.Show("Cannot Create a Channel to a Proxy. Check Your Configuration Settings.", "Proxy", MessageBoxButtons.OK);
            } // end of else
        }     // end of method
Пример #57
0
 public ICharacterFeedChannel CreateChannel()
 {
     try
     {
         DuplexChannelFactory <ICharacterFeedChannel> factory = new DuplexChannelFactory <ICharacterFeedChannel>(
             new InstanceContext(this),
             "CharacterFeedEndpoint");
         factory.Open();
         return(factory.CreateChannel());
     }
     catch (Exception ex)
     {
         Debug.WriteLine(ex.Message + "|" + ex.StackTrace);
     }
     return(null);
 }
Пример #58
0
    // 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()));
    }
Пример #59
0
 public OperationResult <UserExt> Connect()
 {
     try
     {
         context          = new InstanceContext(relationsCallback);
         factory          = new DuplexChannelFactory <IRelations>(context, connectionString);
         factory.Faulted += Factory_Faulted;
         channel          = factory.CreateChannel();
         var res = channel.Authentication(token);
         return(res);
     }
     catch (CommunicationException ex)
     {
         return(new OperationResult <UserExt>(null, false, "Connection error"));
     }
 }
Пример #60
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);
            }
        }