コード例 #1
0
        private async void Connect_btn_Click(object sender, RoutedEventArgs e)
        {
            if (this.UserNameBox.Text != String.Empty && (this.AdressBox.SelectedItem != null || this.AdressBox.Text != String.Empty))
            {
                _name = this.UserNameBox.Text;
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("Some fields are empty");
                return;
            }
            string local_machine = (this.AdressBox.SelectedItem != null)? this.AdressBox.SelectedItem.ToString(): this.AdressBox.Text;

            if (local_machine != null)
            {
                try
                {
                    this.ConnectionLabel.Content = String.Format("Connecting to {0}", local_machine);
                    InstanceContext context = new InstanceContext(this);
                    chat_service = new ChatProviderClient(context, "NetTcpBinding_IChatProvider", String.Format("net.tcp://{0}:8733/ChatProvider/", local_machine));

                    await chat_service.RegisterNewUserAsync(_name);

                    this.UserNameLabel.Content = _name + ":";

                    this.ConnectionLabel.Content = "Getting users list";

                    var users = await chat_service.GetUsersListAsync();

                    users.ForEach(user => this.UsersList.Items.Add(user));

                    this.ConnectionLabel.Content = String.Format("Connected to {0}", local_machine);
                }
                catch (EndpointNotFoundException)
                {
                    System.Windows.Forms.MessageBox.Show(string.Format("It seems that {0} doesn't host ChatServer", local_machine));
                    chat_service = null;
                    this.ConnectionLabel.Content = "Disconnected";
                }
                catch (FaultException <ExceptionType> fault)
                {
                    chat_service = null;
                    var error_type = fault.Detail;
                    if (error_type == ExceptionType.UserAlreadyRegisterd)
                    {
                        System.Windows.Forms.MessageBox.Show(String.Format("User with name {0} already registered.\nTry Another name", _name));
                    }
                    this.ConnectionLabel.Content = "Disconnected";
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.Message);
                    chat_service = null;
                    this.ConnectionLabel.Content = "Disconnected";
                }
            }
        }