// 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);

            channel_factory.Open();

            var ch = channel_factory.CreateChannel(new EndpointAddress("net.p2p://" + node.MeshId + "/"), conn.Address.EndpointAddress.Uri);

            ch.Closed += delegate
            {
                channel_factory.Close();
            };
            return(ch);
        }
Пример #2
0
    public static void Main()
    {
        var binding = new NetPeerTcpBinding();

        binding.Resolver.Mode           = PeerResolverMode.Custom;
        binding.Resolver.Custom.Address = new EndpointAddress("net.tcp://localhost:8086");
        var tcp = new NetTcpBinding()
        {
            TransactionFlow = false
        };

        tcp.Security.Mode = SecurityMode.None;
        binding.Resolver.Custom.Binding = tcp;

        binding.Security.Mode = SecurityMode.None;
        IFooChannel proxy = new DuplexChannelFactory <IFooChannel> (
            new Foo(),
            binding,
            new EndpointAddress("net.p2p://samplemesh/SampleService")
            ).CreateChannel();

        proxy.Open();
        proxy.SendMessage("TEST FOR ECHO");
        Console.WriteLine(proxy.SessionId);
        Console.WriteLine("type [CR] to quit");
        Console.ReadLine();
    }
Пример #3
0
        public void Connect()
        {
            if (clientProxy == null)    // create channel here
            {
                State = ConnectionState.Connecting;
                SyncServiceClientCallback callback = new SyncServiceClientCallback(window);
                // Read server address from configuration
                string serverAddress = System.Configuration.ConfigurationManager.AppSettings["SyncServiceAddress"];
#if DEBUG_ON
                Console.WriteLine("serverAddress {0}", serverAddress);
#endif
                DuplexChannelFactory <ISyncServiceClient> factory = new DuplexChannelFactory <ISyncServiceClient>(callback, new NetTcpBinding(), new EndpointAddress(serverAddress));
                factory.Open();
                clientProxy = factory.CreateChannel();
                // try sign in
                try {
                    SessionInfo info = new SessionInfo();
                    info.UserName = Environment.UserName;
                    clientProxy.SignIn(info);
                    State = ConnectionState.Connected;
                }
                catch (Exception ex) {  // unable to connect
                    clientProxy = null;
                    State       = ConnectionState.Disconnected;
                    new ErrorHandler(ex);
                }
            }
        }
Пример #4
0
        public UserServiceProxy()
        {
            var factory = new DuplexChannelFactory <IUserService>(this, new WSDualHttpBinding(), new EndpointAddress("http://localhost:888")); //creating the ChannelFactory

            factory.Open();
            proxy = factory.CreateChannel(); //creating channel to the service
        }
 public FlightHistoryProxy()
 {
     //open channel
     factory = new DuplexChannelFactory <IFlightHistoryService>(this, new WSDualHttpBinding(), new EndpointAddress("http://localhost:888"));
     factory.Open();
     proxy = factory.CreateChannel(); //creating channel to the service
 }
        /// <summary>
        /// Use this for contracts which have a callback interface.
        /// </summary>
        public static void UsingDuplex <TServiceContract>(Action <TServiceContract> action, object callbackImplementation, string endpointConfigurationName)
        {
            using (var channelFactory = new DuplexChannelFactory <TServiceContract>(callbackImplementation, endpointConfigurationName))
            {
                channelFactory.Open();
                var success = false;
                try
                {
                    var client = channelFactory.CreateChannel();
                    action(client);

                    if (channelFactory.State != CommunicationState.Faulted)
                    {
                        channelFactory.Close();
                        success = true;
                    }
                }
                finally
                {
                    if (!success)
                    {
                        channelFactory.Abort();
                    }
                }
            }
        }
Пример #7
0
        /// <summary>
        /// Gets a service channel using discovery.
        /// </summary>
        public override TChannel CreateChannel()
        {
            _channelFactory.Open();
            var channel = _channelFactory.CreateChannel(Metadata.Address);

            return(channel);
        }
        /// <summary>
        /// LogOff
        /// Logs off the user from the service
        /// and updates the GUI locally
        /// </summary>
        private void LogOff()
        {
            // Call the Service to Log Off
            DuplexChannelFactory <IChatService> cf = new DuplexChannelFactory <IChatService>(this, "NetTcpBinding_IChatService");

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

            if (proxy != null)
            {
                try
                {
                    proxy.LeaveServer(LoggedInUser.Username);

                    // Disable the GUI for Chat
                    UpdateChatGUI(false);
                } // 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("Error logging off user: "******"Cannot Create a Channel to a Proxy. Check Your Configuration Settings.", "Proxy", MessageBoxButtons.OK);
            } // end of else
        }     // end of method
Пример #9
0
        private static void joinChatroom(int port, string username)
        {
            DuplexChannelFactory <Chatroom> dupFactory = null;
            Chatroom    clientProxy = null;
            TextChatter _chatter    = new TextChatter();

            dupFactory = new DuplexChannelFactory <Chatroom>(
                _chatter, new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:" + port + "/Chat"));
            dupFactory.Open();
            clientProxy = dupFactory.CreateChannel();

            Console.WriteLine("Bienvenue dans la room {0}", username);
            clientProxy.join(username);
            string input = null;

            while (input != "exit")
            {
                input = Console.ReadLine();
                clientProxy.send(input, username);
                Console.SetCursorPosition(0, Console.CursorTop - 2);
                ClearCurrentConsoleLine();
                Console.SetCursorPosition(0, Console.CursorTop + 2);
            }

            dupFactory.Close();
        }
Пример #10
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();
			}
		}
Пример #11
0
        private void buttonLogin_Click(object sender, EventArgs e)
        {
            ServerIp   = textBoxServerIp.Text;
            ServerPort = Convert.ToInt32(numericUpDownServerPort.Value);

            IPAddress tempAddress;

            if (IPAddress.TryParse(ServerIp, out tempAddress) == false)
            {
                MessageBox.Show("Please insert proper server IP address!");
                return;
            }

            // save the setting
            Properties.Settings.Default.lastServerIp   = ServerIp;
            Properties.Settings.Default.lastServerPort = ServerPort;
            Properties.Settings.Default.Save();

            if (mUsername.CompareTo(textBoxUsername.Text) == 0 &&
                mPassword.CompareTo(textBoxPassword.Text) == 0)
            {
                FormRemoteConfigure formRemote = new FormRemoteConfigure();
                try
                {
                    InstanceContext instanceContext = new InstanceContext(formRemote);
                    EndpointAddress address         = new EndpointAddress(new Uri(string.Format("net.tcp://{0}:{1}/Service1", ServerIp, ServerPort)));

                    NetTcpBinding tcpBinding = new NetTcpBinding(SecurityMode.None);
                    tcpBinding.ReceiveTimeout         = new TimeSpan(24, 20, 31, 23);
                    tcpBinding.MaxBufferSize          = 2147483647;
                    tcpBinding.MaxReceivedMessageSize = 2147483647;

                    DuplexChannelFactory <IService1> dupFactory = new DuplexChannelFactory <IService1>(instanceContext, tcpBinding, address);
                    dupFactory.Open();

                    IService1 wcfService = dupFactory.CreateChannel();
                    wcfService.RegisterCallback();

                    formRemote.Initialize(wcfService);
                }
                catch (Exception)
                {
                    MessageBox.Show("Cant connect to specify server IP and/or port!");
                    return;
                }

                this.Hide();
                formRemote.ShowDialog();
                this.Close();
            }
            else
            {
                MessageBox.Show("Incorrect username and/or password!");
            }
        }
Пример #12
0
        public override void OnBrowserCreated(CefBrowserWrapper browser)
        {
            browsers.Add(browser);

            if (parentBrowserId == null)
            {
                parentBrowserId = browser.BrowserId;
            }

            if (ParentProcessId == null || parentBrowserId == null)
            {
                return;
            }

            var browserId = browser.IsPopup ? parentBrowserId.Value : browser.BrowserId;

            var serviceName = RenderprocessClientFactory.GetServiceName(ParentProcessId.Value, browserId);

            var binding = BrowserProcessServiceHost.CreateBinding();

            var channelFactory = new DuplexChannelFactory<IBrowserProcess>(
                this,
                binding,
                new EndpointAddress(serviceName)
            );

            channelFactory.Open();

            var browserProcess = channelFactory.CreateChannel();
            var clientChannel = ((IClientChannel)browserProcess);

            try
            {
                clientChannel.Open();
                if (!browser.IsPopup)
                {
                    browserProcess.Connect();
                }

                var javascriptObject = browserProcess.GetRegisteredJavascriptObjects();

                if (javascriptObject.MemberObjects.Count > 0)
                {
                    browser.JavascriptRootObject = javascriptObject;
                }

                browser.ChannelFactory = channelFactory;
                browser.BrowserProcess = browserProcess;
            }
            catch(Exception)
            {
            }
        }
Пример #13
0
        public override void OnBrowserCreated(CefBrowserWrapper browser)
        {
            browsers.Add(browser);

            if (parentBrowserId == null)
            {
                parentBrowserId = browser.BrowserId;
            }

            if (ParentProcessId == null || parentBrowserId == null)
            {
                return;
            }

            var browserId = browser.IsPopup ? parentBrowserId.Value : browser.BrowserId;

            var serviceName = RenderprocessClientFactory.GetServiceName(ParentProcessId.Value, browserId);

            var binding = BrowserProcessServiceHost.CreateBinding();

            var channelFactory = new DuplexChannelFactory <IBrowserProcess>(
                this,
                binding,
                new EndpointAddress(serviceName)
                );

            channelFactory.Open();

            var browserProcess = channelFactory.CreateChannel();
            var clientChannel  = ((IClientChannel)browserProcess);

            try
            {
                clientChannel.Open();
                if (!browser.IsPopup)
                {
                    browserProcess.Connect();
                }

                var javascriptObject = browserProcess.GetRegisteredJavascriptObjects();

                if (javascriptObject.MemberObjects.Count > 0)
                {
                    browser.JavascriptRootObject = javascriptObject;
                }

                browser.ChannelFactory = channelFactory;
                browser.BrowserProcess = browserProcess;
            }
            catch (Exception)
            {
            }
        }
Пример #14
0
        protected void MakeProxy(string endpoindAddress, object callbackinstance)
        {
            var binding = NetSetting.GetBinding();

            EndpointAddress endpointAddress = new EndpointAddress(endpoindAddress);
            InstanceContext context         = new InstanceContext(callbackinstance);

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

            channelFactory.Endpoint.Behaviors.Add(new BusClientBehavior());
            channelFactory.Open();
            _proxy = channelFactory.CreateChannel();
        }
Пример #15
0
        public chatForm(int port, string usernme)
        {
            InitializeComponent();
            DuplexChannelFactory<Chatroom> dupFactory = null;

            TextChatter _chatter = new TextChatter(this);
            dupFactory = new DuplexChannelFactory<Chatroom>(
                _chatter, new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:" + port + "/Chat"));
            dupFactory.Open();
            clientProxy = dupFactory.CreateChannel();
            username = usernme;
            clientProxy.join(username);
        }
        }     // 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 (LoggedInUser.Username == null)
            {
                MessageBox.Show("Please Login First !");
                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
Пример #17
0
        public chatForm(int port, string usernme)
        {
            InitializeComponent();
            DuplexChannelFactory <Chatroom> dupFactory = null;

            TextChatter _chatter = new TextChatter(this);

            dupFactory = new DuplexChannelFactory <Chatroom>(
                _chatter, new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:" + port + "/Chat"));
            dupFactory.Open();
            clientProxy = dupFactory.CreateChannel();
            username    = usernme;
            clientProxy.join(username);
        }
        }     // 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
Пример #19
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);
 }
Пример #20
0
        /// <summary>
        /// Creates a TV Stream Control, and connects to the specified server
        /// </summary>
        /// <param name="serverAddress">IP or hostname of the server to connect to</param>
        public TVStreamControl(string serverAddress)
        {
            ChannelScanProgress = -1;

            IPHostEntry entry = AddressLookup.GetHostEntry(serverAddress);

            _serverAddress = entry.AddressList[0].ToString();

            NetTcpBinding binding = new NetTcpBinding(SecurityMode.None, true);

            int timeout;

            //get SendTimeout from app.config
            if (Int32.TryParse(ConfigurationManager.AppSettings["GraphControlClientSendTimeout"], out timeout))
            {
                if (timeout > 0)
                {
                    binding.SendTimeout = TimeSpan.FromSeconds(timeout);
                }
            }

            //get CloseTimeout from app.config
            if (Int32.TryParse(ConfigurationManager.AppSettings["GraphControlClientCloseTimeout"], out timeout))
            {
                if (timeout > 0)
                {
                    binding.CloseTimeout = TimeSpan.FromSeconds(timeout);
                }
            }

            TVStreamControlCallback callback = new TVStreamControlCallback(this);

            _proxyFactory          = new DuplexChannelFactory <ITVStream>(callback, binding, @"net.tcp://" + ServerAddress + @":8099/TVStreamService");
            _proxyFactory.Opening += new EventHandler(Proxy_Opening);
            _proxyFactory.Opened  += new EventHandler(Proxy_Opened);
            _proxyFactory.Closing += new EventHandler(Proxy_Closing);
            _proxyFactory.Closed  += new EventHandler(Proxy_Closed);
            _proxyFactory.Faulted += new EventHandler(Proxy_Faulted);
            _proxyFactory.Open();
            _proxy = _proxyFactory.CreateChannel();

            _serverKeepAliveTimer          = new System.Timers.Timer();
            _serverKeepAliveTimer.Interval = 15000;
            _serverKeepAliveTimer.Elapsed += new System.Timers.ElapsedEventHandler(ServerKeepAliveTimer_Elapsed);
            _serverKeepAliveTimer.Enabled  = true;
        }
Пример #21
0
        public ProxyFactory(CmmClient cmmClient)
        {
            // 三坐标控制代理工厂
            NetTcpBinding cmmBinding = new NetTcpBinding(SecurityMode.None);

            cmmBinding.OpenTimeout = TimeSpan.FromSeconds(15);
            CSFeedback events = new CSFeedback(cmmClient);

            CmmControlFactory = new DuplexChannelFactory <ICmmControl>(new InstanceContext(events), cmmBinding);
            CmmControlFactory.Open();
            // 文件传输代理工厂
            NetTcpBinding fileBinding = new NetTcpBinding(SecurityMode.None);

            fileBinding.TransferMode           = TransferMode.Streamed;
            fileBinding.MaxBufferSize          = 65536;
            fileBinding.MaxReceivedMessageSize = 0x7fffffff;
            PartConfigServiceFactory           = new ChannelFactory <IPartConfigService>(fileBinding);
            PartConfigServiceFactory.Open();
        }
Пример #22
0
        /// <summary>
        /// Create the simulator service & initializes database
        /// </summary>
        public SimServiceProxy()
        {
            var serviceFactory = new DuplexChannelFactory <ISimService>(this,
                                                                        new WSDualHttpBinding(),
                                                                        new EndpointAddress("http://localhost:4767/Services/SimService.svc"));

            serviceFactory.Open();
            simService = serviceFactory.CreateChannel();

            try
            {
                InitializeDatabase();
            }
            catch (Exception e)
            {
                throw new Exception($"Database was not initialized. {e.Message}");
            }

            flightsTimers = new Dictionary <FlightDTO, Timer>();
        }
Пример #23
0
    public static void CreateChannel_EndpointAddress_Null_Throws()
    {
        WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback();
        InstanceContext context = new InstanceContext(callback);
        Binding binding = new NetTcpBinding();
        EndpointAddress remoteAddress = null;

        DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, remoteAddress);
        try {
            Assert.Throws<InvalidOperationException>(() =>
               {
                   factory.Open();
                   factory.CreateChannel();
               });
        }
        finally
        { 
            factory.Abort();
        }
    }
Пример #24
0
        /// <summary>
        /// Handle our open button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpen_Click(object sender, EventArgs e)
        {
            NetTcpBinding tcpBinding = MM_Binding_Configuration.CreateBinding();

            ClientFactory = new DuplexChannelFactory <IMM_WCF_Interface>(new MM_Server_Callback_Handler(), tcpBinding, txtServer.Text);
            ClientFactory.Open();
            Client = ClientFactory.CreateChannel();
            frmWindowsSecurityDialog SecurityDialog = new frmWindowsSecurityDialog();

            SecurityDialog.CaptionText = Application.ProductName + " " + Application.ProductVersion;
            SecurityDialog.MessageText = "Enter the credentials to log into Macomber Map Server";
            string    Username, Password, Domain;
            Exception LoginError;

            if (SecurityDialog.ShowLoginDialog(out Username, out Password, out Domain))
            {
                Client.HandleUserLogin(Username, Password);
                MessageBox.Show(this, "Connected.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Пример #25
0
    public static void CreateChannel_EndpointAddress_Null_Throws()
    {
        WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback();
        InstanceContext          context  = new InstanceContext(callback);
        Binding         binding           = new NetTcpBinding();
        EndpointAddress remoteAddress     = null;

        DuplexChannelFactory <IWcfDuplexService> factory = new DuplexChannelFactory <IWcfDuplexService>(context, binding, remoteAddress);

        try {
            Assert.Throws <InvalidOperationException>(() =>
            {
                factory.Open();
                factory.CreateChannel();
            });
        }
        finally
        {
            factory.Abort();
        }
    }
Пример #26
0
	public static void Main ()
	{
		var binding = new NetPeerTcpBinding ();
		binding.Resolver.Mode = PeerResolverMode.Custom;
		binding.Resolver.Custom.Address = new EndpointAddress ("net.tcp://localhost:8086");
		var tcp = new NetTcpBinding () { TransactionFlow = false };
		tcp.Security.Mode = SecurityMode.None;
		binding.Resolver.Custom.Binding = tcp;

		binding.Security.Mode = SecurityMode.None;
		IFooChannel proxy = new DuplexChannelFactory<IFooChannel> (
			new Foo (),
			binding,
			new EndpointAddress ("net.p2p://samplemesh/SampleService")
			).CreateChannel ();
		proxy.Open ();
		proxy.SendMessage ("TEST FOR ECHO");
		Console.WriteLine (proxy.SessionId);
		Console.WriteLine ("type [CR] to quit");
		Console.ReadLine ();
	}
Пример #27
0
        } // end of method

        /// <summary>
        /// Login
        /// Tries to login this client's username to the service
        /// </summary>
        /// <returns>true if successful, false otherwise</returns>
        private bool Login()
        {
            DuplexChannelFactory <IChatService> cf = new DuplexChannelFactory <IChatService>(this, "NetTcpBinding_IChatService");

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

            if (proxy != null)
            {
                try
                {
                    proxy.Login(userName);

                    // Change the Login State
                    LoggedIn = true;

                    return(true);
                }     // end of try

                catch (FaultException <DuplicateUserFault> ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Detail.Reason, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace + "." + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name);
                    MessageBox.Show(ex.Detail.Reason);
                    return(false);
                }
                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("Error logging in user: "******"Cannot Create a Channel to a Proxy. Check Your Configuration Settings.", "Proxy", MessageBoxButtons.OK);
                return(false);
            }     // end of else
        } // end of method
        } // end of method

        #endregion IChatServiceCallback Implementation


        /// <summary>
        /// btnSendMessage_Click
        /// Implements the Send Message Button Click
        /// </summary>
        /// <param name="sender">not used</param>
        /// <param name="e">not used</param>
        private void btnSendMessage_Click(object sender, EventArgs e)
        {
            // Validate User LoggedIn
            if (txtMyMessage.Enabled == false || LoggedInUser.Username == null)
            {
                // User needs to login!
                MessageBox.Show("Please login before sending a message.", "Login Required", MessageBoxButtons.OK);
            }
            else
            {
                // Send Message to Service
                // Retrieve the New Messages
                using (DuplexChannelFactory <IChatService> cf = new DuplexChannelFactory <IChatService>(this, "NetTcpBinding_IChatService"))
                {
                    cf.Open();
                    IChatService proxy = cf.CreateChannel();

                    if (proxy != null)
                    {
                        try
                        {
                            // It is ok to send empty messages, I don't care lol
                            proxy.SendMessage(LoggedInUser.Username, txtMyMessage.Text);
                        } // 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 catch
                    }     // 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 using
            }         // end of if
        }             // end of method
Пример #29
0
        public bool Initialize(IService1Callback callbackHandler)
        {
            try
            {
                this.callbackHandler = callbackHandler;
                InstanceContext instanceContext = new InstanceContext(callbackHandler);
                EndpointAddress address         = new EndpointAddress(new Uri(Properties.Settings.Default.RemoteIP));

                NetTcpBinding tcpBinding = new NetTcpBinding(SecurityMode.None);
                ReliableSessionBindingElement reliableBe = new ReliableSessionBindingElement();
                reliableBe.Ordered                = true;
                tcpBinding.OpenTimeout            = new TimeSpan(24, 20, 31, 23);
                tcpBinding.CloseTimeout           = new TimeSpan(24, 20, 31, 23);
                tcpBinding.ReceiveTimeout         = new TimeSpan(24, 20, 31, 23);
                tcpBinding.SendTimeout            = new TimeSpan(24, 20, 31, 23);
                tcpBinding.MaxBufferSize          = 2147483647;
                tcpBinding.MaxReceivedMessageSize = 2147483647;

                OptionalReliableSession reliableSession = new OptionalReliableSession(reliableBe);
                tcpBinding.ReliableSession = reliableSession;
                tcpBinding.ReceiveTimeout  = new TimeSpan(24, 20, 31, 23);

                dupFactory = new DuplexChannelFactory <IService1>(instanceContext, tcpBinding, address);
                dupFactory.Open();

                wcfService = dupFactory.CreateChannel();
                wcfService.RegisterCallback();

                Thread workerThread = new Thread(DoWork);
                _shouldStop = true;
                workerThread.Start();
            }
            catch (Exception)
            {
                return(false);
            }

            return(true);
        }
Пример #30
0
        internal bool Connect(IGameHost gameHost, out IRemoteGameUI ui)
        {
            try
            {
                factory = new DuplexChannelFactory <IRemoteGameUI>(new InstanceContext(gameHost), GetBinding(), new EndpointAddress(string.Format("net.tcp://{1}:{0}/simulator", SettingsViewModel.Model.HttpPort, SettingsViewModel.Model.RemotePCName)));
                factory.Open();
                ui = factory.CreateChannel();

                ui.UpdateSettings(SettingsViewModel.SIUISettings.Model);                 // Проверим соединение заодно

                ((IChannel)ui).Closed  += GameEngine_Closed;
                ((IChannel)ui).Faulted += GameEngine_Closed;

                return(true);
            }
            catch (Exception exc)
            {
                ui = null;
                ShowError(exc.Message);
                return(false);
            }
        }
Пример #31
0
 private static void KillExistingServiceIfNeeded(string serviceName)
 {
     // It might be that there is an existing process already bound to this port. We must get rid of that one, so that the
     // endpoint address gets available for us to use.
     try
     {
         var channelFactory = new DuplexChannelFactory <ISubProcessProxy>(
             new DummyCallback(),
             new NetNamedPipeBinding(),
             new EndpointAddress(serviceName)
             );
         channelFactory.Open(TimeSpan.FromSeconds(1));
         var javascriptProxy = channelFactory.CreateChannel();
         javascriptProxy.Terminate();
     }
     // ReSharper disable once EmptyGeneralCatchClause
     catch
     {
         // We assume errors at this point are caused by things like the endpoint not being present (which will happen in
         // the first render subprocess instance).
     }
 }
Пример #32
0
        /// <summary>
        /// Creates a new instance
        /// </summary>
        /// <param name="serverAddress">server hostname or ip address</param>
        /// <param name="recordCallback">the <see cref="T:IRecordCallback"/> you want to use</param>
        public RecordClient(string serverAddress, IRecordCallback recordCallback)
        {
            IPHostEntry entry = AddressLookup.GetHostEntry(serverAddress);

            _serverAddress = entry.AddressList[0].ToString();

            NetTcpBinding binding = new NetTcpBinding(SecurityMode.None, true);

            //  binding.SendTimeout = TimeSpan.FromSeconds(Convert.ToInt32(ConfigurationManager.AppSettings["GraphControlClientSendTimeout"]));
            _proxyFactory          = new DuplexChannelFactory <IRecord>(recordCallback, binding, @"net.tcp://" + ServerAddress + @":8099/RecordService");
            _proxyFactory.Opening += new EventHandler(Proxy_Opening);
            _proxyFactory.Opened  += new EventHandler(Proxy_Opened);
            _proxyFactory.Closing += new EventHandler(Proxy_Closing);
            _proxyFactory.Closed  += new EventHandler(Proxy_Closed);
            _proxyFactory.Faulted += new EventHandler(Proxy_Faulted);
            _proxyFactory.Open();
            _proxy = _proxyFactory.CreateChannel();
            _serverKeepAliveTimer          = new System.Timers.Timer();
            _serverKeepAliveTimer.Interval = 15000;
            _serverKeepAliveTimer.Elapsed += new System.Timers.ElapsedEventHandler(ServerKeepAliveTimer_Elapsed);
            _serverKeepAliveTimer.Enabled  = true;
        }
        private void JoinServer(string username)
        {
            // Check State on Service
            // Make a ChannelFactory Proxy to the Service
            DuplexChannelFactory <IChatService> cf = new DuplexChannelFactory <IChatService>(this, "NetTcpBinding_IChatService");

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

            if (proxy != null)
            {
                try
                {
                    proxy.AddMeToServer(username);
                    Console.WriteLine("Inside join server");
                    // Disable the GUI for Chat
                    UpdateChatGUI(true);
                } // end of try

                catch (FaultException <DuplicateUserFault> ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Detail.Reason, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace + "." + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name);
                    MessageBox.Show(ex.Detail.Reason);
                }

                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("Error logging off user: "******"Cannot Create a Channel to a Proxy. Check Your Configuration Settings.", "Proxy", MessageBoxButtons.OK);
            } // end of else
        }
Пример #34
0
        private static void Main(string[] args)
        {
            Console.WriteLine("Apelido: ");
            string apelido = Console.ReadLine();

            if (string.IsNullOrEmpty(apelido))
            {
                return;
            }
            DuplexChannelFactory <IRxService> dup = null;
            IRxService   cli  = null;
            ChatCallback call = new ChatCallback();

            dup = new DuplexChannelFactory <IRxService>(call,
                                                        new NetTcpBinding(), new EndpointAddress(@"net.tcp://localhost:9999/Chat/"));
            dup.Open();
            cli = dup.CreateChannel();
            cli.Register();
            while (true)
            {
                Console.Write("Mensagem:");
                var msg = Console.ReadLine();
                if (string.IsNullOrEmpty(msg))
                {
                    break;
                }
                var message = new Message()
                {
                    From      = apelido,
                    To        = "All",
                    Timestamp = DateTime.Now,
                    Text      = msg
                };
                cli.SendMessage(message);
            }
            dup.Close();
        }
Пример #35
0
        private T CreateDuplexChannelFactory <DataContractCallBack>(Binding binding)
            where DataContractCallBack : IContractCallback, new()
        {
            DataContractCallBack _contractCall = new DataContractCallBack();
            InstanceContext      _context      = new InstanceContext(_contractCall);

            CommunicationObject = _context;
            DuplexChannelFactory <T> _channelFacotry = new DuplexChannelFactory <T>(_context, binding);

            AddEndpointBehaviors(_channelFacotry.Endpoint);

            foreach (OperationDescription op in _channelFacotry.Endpoint.Contract.Operations)
            {
                var dataContractBehavior = op.Behaviors.Find <DataContractSerializerOperationBehavior>();

                if (dataContractBehavior != null)
                {
                    dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
                }
            }

            _channelFacotry.Open();
            return(_channelFacotry.CreateChannel(new EndpointAddress(ServiceURL)));
        }
Пример #36
0
        private static void joinChatroom(int port, string username)
        {
            DuplexChannelFactory<Chatroom> dupFactory = null;
            Chatroom clientProxy = null;
            TextChatter _chatter = new TextChatter();
            dupFactory = new DuplexChannelFactory<Chatroom>(
                _chatter, new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:"+ port +"/Chat"));
            dupFactory.Open();
            clientProxy = dupFactory.CreateChannel();

            Console.WriteLine("Bienvenue dans la room {0}",username);
            clientProxy.join(username);
            string input = null;
            while (input != "exit")
            {
                input = Console.ReadLine();
                clientProxy.send(input, username);
                Console.SetCursorPosition(0, Console.CursorTop - 2);
                ClearCurrentConsoleLine();
                Console.SetCursorPosition(0, Console.CursorTop + 2);
            }

            dupFactory.Close();
        }