Exemplo n.º 1
0
        public AllChatRoomForm(string userName)
        {
            InitializeComponent();
            _userName = userName;
            labelLoggedInAll.Text = $"Logged in as: {_userName}";
            _chatRoomId = 3;
            _timer = new Timer {Interval = 3000};

            try
            {
                _client = new ChatServiceClient("All");
                UpdateTexts();
                _timer.Tick += (sender, args) => UpdateTexts();
                _timer.Start();
            }
            catch (Exception)
            {
                MessageBox.Show("Not connected to the service, application will exit");
                Application.Exit();
            }
            if (richTextBoxMessageAll.TextLength == 0)
            {
                buttonSendMessageAll.Enabled = false;
            }
        }
Exemplo n.º 2
0
        //Constractor
        public BaseWindow(int width, int height)
        {
            var callback = new ClientCallback();

            Host    = new ChatServiceClient(new System.ServiceModel.InstanceContext(callback));
            _window = new Window
            {
                Width  = width,
                Height = height,
                WindowStartupLocation = WindowStartupLocation.CenterScreen,
                ResizeMode            = ResizeMode.NoResize,
                WindowStyle           = WindowStyle.None
            };
            _window.MouseLeftButtonDown += _window_MouseLeftButtonDown;
            //Grid
            _myGrid            = new Grid();
            _window.Content    = _myGrid;
            _myGrid.Background = new SolidColorBrush(Colors.BlueViolet);
            //_myGrid.ShowGridLines = true;

            RowDefinition rowDef = new RowDefinition();

            _myGrid.RowDefinitions.Add(rowDef);
            _myGrid.RowDefinitions[0].Height = new GridLength(30);

            Timer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(15)
            };
            Timer.Tick += Timer_Tick;
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            try
            {
                InstanceContext         context = new InstanceContext(new ChatProxy());
                Proxy.ChatServiceClient server  = new ChatServiceClient(context);

                Console.WriteLine("Введите логин");
                var username = Console.ReadLine();
                server.Join(username);

                Console.WriteLine();
                Console.WriteLine("Введите сообщение");
                Console.WriteLine("Для выхода нажмите Q");

                var message = Console.ReadLine();
                while (message != "Q" && message != "q")
                {
                    if (!string.IsNullOrEmpty(message))
                    {
                        server.SendMessage(message);
                    }

                    message = Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Возникла ошибка. Срочно передайте звездюлей и текст этой ошибки программисту!");
                Console.WriteLine(ex);
                throw;
            }
        }
 static void Main(string[] args)
 {
     try
     {
         Person person = new Person("John Doe");
         IChatServiceCallback callback        = new SimpleChatCallback();
         InstanceContext      instanceContext = new InstanceContext(callback);
         ChatServiceClient    serviceProxy    = new ChatServiceClient(instanceContext);
         Console.WriteLine("Endpoint:");
         Console.WriteLine("***********************************************");
         Console.WriteLine(string.Format("Address = {0}", serviceProxy.Endpoint.Address));
         Console.WriteLine(string.Format("Binding = {0}", serviceProxy.Endpoint.Binding));
         Console.WriteLine(string.Format("Contract = {0}", serviceProxy.Endpoint.Contract.Name));
         Person[] people = serviceProxy.Join(person);
         Console.WriteLine("***********************************************");
         Console.WriteLine("Connected !");
         Console.WriteLine("Online users:");
         foreach (Person p in people)
         {
             Console.WriteLine(p.Name);
         }
         Console.WriteLine("Press <ENTER> to finish...");
         Console.ReadLine();
         if (serviceProxy.State != CommunicationState.Faulted)
         {
             serviceProxy.Close();
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
Exemplo n.º 5
0
 private void UppdateMessageBox()
 {
     label2.Visible = true;
     label3.Visible = true;
     try
     {
         using (var client = new ChatServiceClient())
         {
             clientMessages = client.GetAllMessagesMadeByClient(ClientId).ToList();
         }
         label1.Text   = "My sent messages.";
         textBox1.Text = string.Empty;
         int top = 3;
         panel1.Controls.Clear();
         panel2.Controls.Clear();
         foreach (var message in clientMessages)
         {
             textBox1.Text += message.Message + "\r\n";
             AddAlterButton(top, message.Id.ToString());
             top = AddDelButton(top, message.Id.ToString());
         }
     }
     catch (FaultException <Error> fex)
     {
         var error = ErrorHelper.UnwrapFaultException(fex);
         MessageBox.Show(error.Message, "Error");
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "Error");
     }
 }
Exemplo n.º 6
0
        public MogmogConnection(string hostname, int channelId, bool saveAccessCode)
        {
            this.ChannelId      = channelId;
            this.SaveAccessCode = saveAccessCode;
            this.tokenSource    = new CancellationTokenSource();
            this.channel        = GrpcChannel.ForAddress(hostname);
            this.chatClient     = new ChatServiceClient(channel);
            var serverInfo = this.chatClient.GetChatServerInfo(new ReqChatServerInfo());
            var flags      = (ServerFlags)serverInfo.Flags;

            Mogger.Log($"Server flags for {hostname}: {flags}");
            var callOptions = new CallOptions()
                              .WithCancellationToken(this.tokenSource.Token)
                              .WithDeadline(DateTime.UtcNow.AddMinutes(1))
                              .WithWaitForReady();

            if (flags.HasFlag(ServerFlags.RequiresDiscordOAuth2))
            {
                oAuth2 = new DiscordOAuth2();
                oAuth2.Authenticate(serverInfo.ServerId);
                var headers = new Metadata
                {
                    new Entry("code", oAuth2.OAuth2Code),
                };
                callOptions = callOptions.WithHeaders(headers);
            }
            this.chatStream = this.chatClient.Chat(callOptions);
            _ = ChatLoop(this.tokenSource.Token);
        }
Exemplo n.º 7
0
        public ChatRoom(ChatServiceClient client, string roomName, User user)
        {
            DontTouchList = false;
            CurrentChats = new List<Chat>();
            InitializeComponent();
            MyClient = client;
            this.Text = roomName;
            MyUser = user;
            RoomName = roomName;
            string[] userlist = null;
            try
            {
                userlist = MyClient.GetUserList(roomName);
            }
            catch (Exception)
            {
                MessageBox.Show("The service is probably offline");
                this.Close();
                return;
            }


            if (roomName == "The Man Cave")
            {
                this.BackColor = Color.Blue;
            }
            else if (roomName == "The Kitchen")
            {
                this.BackColor = Color.HotPink;
            }
            else
            {
                this.BackColor = Color.Green;
            }


            foreach (var roomUser in userlist)
            {
                if (roomUser == MyUser.Username)
                {
                    DialogResult dialogResult = MessageBox.Show("User with the same username\nalready exists in this room.", "Username Already Exists", MessageBoxButtons.OK);
                    this.Close();
                    return;
                }
            }
            try
            {
                MyClient.AddUserNameToList(MyUser.Username, roomName);
            }
            catch (FaultException ex)
            {
                MessageBox.Show(ex.Message);
            }


            // Create a task and supply a user delegate by using a lambda expression. 
            Task RefreshTask = new Task(() => CollectNewChatInformation());
            // Start the task.
            RefreshTask.Start();
        }
Exemplo n.º 8
0
        public ActionResult GetChats(FormCollection collection)
        {
            var cookie = Request.Cookies.Get("aCookie");

            if (cookie != null)
            {
                ChatServiceClient client = new ChatServiceClient(new InstanceContext(this));
                int aCookie = Int32.Parse(cookie.Value);
                client.Online(aCookie);
                ViewBag.Chats     = client.GetChatsByName(collection["searchBy"], aCookie);
                ViewBag.SearchBy  = collection["searchBy"];
                ViewBag.ProfileId = aCookie;
                return(View());
            }
            else
            {
                return(Redirect("/Profile/Login"));
            }
            //ChatServiceClient client = new ChatServiceClient(new InstanceContext(this));
            //try
            //{
            //    var searchBy = collection["searchBy"];
            //    int profileId = Int32.Parse(collection["profileId"].ToString());
            //    client.Online(profileId);
            //    ViewBag.Chats = client.GetChatsByName(searchBy, profileId);
            //    ViewBag.SearchBy = searchBy;
            //    ViewBag.ProfileId = profileId;
            //}
            //catch (Exception)
            //{
            //    return GetChats();
            //}
            //return View();
        }
Exemplo n.º 9
0
 /// <summary>
 /// Inicia el cliente del servicio de chat
 /// </summary>
 private void InicializarClienteDeChat()
 {
     mensajes       = String.Empty;
     servicioDeChat = new ChatServiceClient(new InstanceContext(this),
                                            new NetTcpBinding(SecurityMode.None),
                                            new EndpointAddress("net.tcp://" + direccionIpDelServidor + ":8192/ChatService"));
 }
Exemplo n.º 10
0
        private void Form1_Load(object sender, EventArgs e)
        {
            var name = "user-" + Guid.NewGuid().ToString();

            chatService = new ChatServiceClient(new InstanceContext(this));
            chatService.Login(name);
        }
Exemplo n.º 11
0
        public void BroadcastChatMessage_NotFromAnotherGame()
        {
            Game game = new Game(0, 0, DateTime.Now, new List <Player>());

            game.ActiveGuidGame = "testguid";
            var callbackHandlerFrey           = new ChatCallbackHandler(game, new System.Windows.Controls.ListBox());
            ChatServiceClient chatServiceFrey = new ChatServiceClient(new InstanceContext(callbackHandlerFrey));

            chatServiceFrey.EnterChat("testguid", "Frey");
            Thread.Sleep(1000);

            Game game2 = new Game(0, 0, DateTime.Now, new List <Player>());

            game2.ActiveGuidGame = "testguid2";
            var callbackHandlerTester           = new ChatCallbackHandler(game2, new System.Windows.Controls.ListBox());
            ChatServiceClient chatServiceTester = new ChatServiceClient(new InstanceContext(callbackHandlerTester));

            chatServiceTester.EnterChat("testguid2", "Tester");
            Thread.Sleep(1000);

            chatServiceTester.BroadcastMessage("testguid2", "Tester", "Mensaje de prueba");
            Thread.Sleep(1000);
            Assert.AreEqual("Mensaje de prueba", callbackHandlerTester.LastMessageReceived);
            Assert.AreEqual(string.Empty, callbackHandlerFrey.LastMessageReceived);
        }
Exemplo n.º 12
0
        public void ConnectUser(string userName, string password, bool registrationRequired)
        {
            _serverService = new ChatServiceClient(new InstanceContext(this));

            Thread t = new Thread(delegate()
            {
                try
                {
                    CurrentUser = _serverService.LogIn(userName, password, registrationRequired);
                }
                catch (EndpointNotFoundException)
                {
                    FaultExceptionThrown?.Invoke(new FaultException("Sorry, server did not respond. Try again later."));
                }
                catch (FaultException e)
                {
                    FaultExceptionThrown?.Invoke(new FaultException(e.Message));
                }
            });

            t.Start();
            t.Join(60000);

            if (CurrentUser != null)
            {
                ContactsMessageHistory = GetFullMessageHistory();
            }
        }
Exemplo n.º 13
0
        public void Connect(string userName, string serverIp)
        {
            try
            {
                localClient      = new Client();
                localClient.Name = userName;
                var context = new InstanceContext(this);
                chatClient = new ChatServiceClient(context);

                //As the address in the configuration file is set to localhost
                //we want to change it so we can call a service in internal
                //network, or over internet
                var servicePath       = chatClient.Endpoint.ListenUri.AbsolutePath;
                var serviceListenPort = chatClient.Endpoint.Address.Uri.Port.ToString();

                chatClient.Endpoint.Address = new EndpointAddress($"net.tcp://{serverIp}:{serviceListenPort}{servicePath}");


                chatClient.Open();

                chatClient.InnerDuplexChannel.Faulted += (sender, args) => HandleProxy();
                chatClient.InnerDuplexChannel.Opened  += (sender, args) => HandleProxy();
                chatClient.InnerDuplexChannel.Closed  += (sender, args) => HandleProxy();
                chatClient.ConnectAsync(localClient);
                Connected = true;
            }
            catch (Exception exception)
            {
                ServiceMessage.AppendLine(exception.Message);
                Connected = false;
            }
        }
Exemplo n.º 14
0
        private ChatService()
        {
            _messages = Observable.Create <ChatMessage>(observer =>
            {
                try
                {
                    if (_client == null)
                    {
                        _clientCallback = new ChatServiceClientCallback(observer);
                        _client         = new ChatServiceClient(new InstanceContext(_clientCallback));
                        _client.ChannelFactory.Closed  += (s, a) => { observer.OnCompleted(); };
                        _client.ChannelFactory.Faulted += (s, a) => { observer.OnCompleted(); };

                        if (_login != null)
                        {
                            _token = _client.Connect(_login);
                        }
                    }
                }
                catch (Exception e)
                {
                    observer.OnError(e);
                }

                return(() =>
                {
                    _client.Close();
                    _client = null;
                });
            });
        }
Exemplo n.º 15
0
        private ChatService()
        {
            _messages = Observable.Create <ChatMessage>(observer =>
            {
                try
                {
                    if (_client == null)
                    {
                        _client = new ChatServiceClient("PollingHttpBinding_IChatServer");
                        _client.PushMessageReceived    += (s, a) => observer.OnNext(a.message);
                        _client.ConnectCompleted       += (s, a) => _token = a.Result;
                        _client.ChannelFactory.Closed  += (s, a) => observer.OnCompleted();
                        _client.ChannelFactory.Faulted += (s, a) => observer.OnCompleted();

                        if (_login != null)
                        {
                            _client.ConnectAsync(_login);
                        }
                    }
                }
                catch (Exception e)
                {
                    observer.OnError(e);
                }

                return(() =>
                {
                    _client.CloseAsync();
                    _client = null;
                });
            });
        }
Exemplo n.º 16
0
        public MainWindow(Room user)
        {
            InitializeComponent();
            this.user          = user;
            User_label.Content = "User: "******"http://localhost:8000/ChatProgram/ChatService/ChatHost");

            binding.ClientBaseAddress = new Uri("http://localhost:8000/myChatClient/");

            // Create Room instance to store client userName and Message
            this.localClient          = new Room();
            this.localClient.UserName = user.UserName;
            this.localClient.Message  = ChatTextBlock.Text;

            // Adding client to OnlineClients list
            OnlineClients.Add(localClient.UserName, user);

            //Construct InstanceContext to handle messages on callback interface.
            InstanceContext context = new InstanceContext(this);

            proxy = new ChatServiceClient(context);

            //Show client joined on UI
            proxy.SendMessageAsync(localClient);
            // Show timestamp on UI
            ChatTextBlock.Text = "Connected at: " + DateTime.Now;
            // To add a new line
            ChatTextBlock.Inlines.Add(new LineBreak());
            //proxy.Open();
        }
Exemplo n.º 17
0
        public void Connect(string user, string host)
        {
            User = user;

            if (!host.Contains("://"))
            {
                host = string.Format("http://{0}", host);
            }
            Host = host;

            // Validate host
            Uri uri;

            UrlExtractor.TryCreate(Host, out uri, validHostUriSchemes);
            if (uri == null)
            {
                ConnectionFailed(this, DateTime.Now, string.Format("Invalid format for host: {0}", Host));
                return;
            }
            Host = uri.ToString();

            try {
                Binding binding;
                if (uri.Scheme.Equals(Uri.UriSchemeNetPipe))
                {
                    var namedPipeBinding = new NetNamedPipeBinding();
                    namedPipeBinding.Security.Mode = NetNamedPipeSecurityMode.None;
                    binding = namedPipeBinding;
                }
                else if (uri.Scheme.Equals(Uri.UriSchemeNetTcp))
                {
                    var tcpBinding = new NetTcpBinding();
                    tcpBinding.Security.Mode = SecurityMode.None;
                    binding = tcpBinding;
                }
                else
                {
                    var httpBinding = new WSDualHttpBinding();
                    httpBinding.Security.Mode = WSDualHttpSecurityMode.None;
                    binding = httpBinding;
                }

                // Append service name
                // Note: URI creation appends any missing "/" to the host, so it's safe to just append
                if (!Host.EndsWith(serviceName) && !Host.EndsWith(string.Format("{0}/", serviceName)))
                {
                    Host = string.Format("{0}{1}", Host, serviceName);
                }

                // Create the endpoint address
                EndpointAddress endpointAddress = new EndpointAddress(Host);
                client = new ChatServiceClient(new InstanceContext(this), binding, endpointAddress);

                client.Open();
                client.Connect(user);
            } catch (Exception exception) {
                TriggerConnectionFailed(exception);
            }
        }
Exemplo n.º 18
0
        public MainWindow()
        {
            InitializeComponent();

            var instanceContext = new InstanceContext(this);

            proxy = new ChatServiceClient(instanceContext);
        }
Exemplo n.º 19
0
 public void DisconnectUser()
 {
     if (_serverService != null)
     {
         _serverService.LogOff(CurrentUser.Id);
         _serverService = null;
     }
 }
Exemplo n.º 20
0
 public MainWindow(UserDto user)
 {
     InitializeComponent();
     _chatService = new ChatServiceClient();
     _currentUser = user;
     ChattingUsersId = new List<int>();
     InitDefault();
     InitTimers();
 }
Exemplo n.º 21
0
        public IntegrationTestsFixture()
        {
            TestServer testServer = new TestServer(Program.CreateWebHostBuilder(new string[] { }).UseEnvironment("Development"));
            var        httpClient = testServer.CreateClient();

            ChatServiceClient = new ChatServiceClient(httpClient);
            MessageStore      = testServer.Host.Services.GetRequiredService <IMessageStore>();
            ConversationStore = testServer.Host.Services.GetRequiredService <IConversationStore>();
        }
Exemplo n.º 22
0
    /// <summary>
    /// Solicita al servicio de chat unirse al chat del juego
    /// </summary>
    /// <returns>True si se unio correctamente o false si no</returns>
    private Boolean UnirseAlServicioDeChat()
    {
        Boolean           SeUnioCorrectamenteAlChat;
        ChatServiceClient clienteDeChat = ChatCliente.clienteDeChat.servicioDeChat;

        ChatCliente.clienteDeChat.ReiniciarServicio();
        SeUnioCorrectamenteAlChat = clienteDeChat.Conectar(CuentaLogeada);
        return(SeUnioCorrectamenteAlChat);
    }
Exemplo n.º 23
0
 public ChatForm()
 {
     InitializeComponent();
     context            = new InstanceContext(new ChatCallback(this));
     server             = new ChatServiceClient(context);
     txtMessage.Enabled = false;
     btnSend.Enabled    = false;
     lbStatus.Text      = "Disconect";
 }
Exemplo n.º 24
0
 private void WindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
 {
     if (disconnectButton.IsEnabled)
     {
         EnableDisconnect(false);
         EnableChat(false);
         Disconnect();
     }
     _chatClient = null;
 }
Exemplo n.º 25
0
 public PersonalChatModel(ChatServiceClient proxy, string userName)
     : base(proxy, userName)
 {
     Proxy.NotifyPersonalReceived +=
         (sender, args) =>
             {
                 if (!HasError(args))
                     OnNewMessage(args.message);
             };
 }
Exemplo n.º 26
0
 public LoginForm()
 {
     _chatService = new ChatServiceClient();
     InitializeComponent();
     _chatService.Login("quangp", "123456");
     var user = _chatService.GetUser("quangp");
     var mainWindow = new MainWindow(user);
     mainWindow.Show();
     this.Close();
 }
Exemplo n.º 27
0
 void DisconnectUser()
 {
     if (isConnected)
     {
         client.Disconnect(ID);
         client = null;
         txtUserName.IsEnabled = true;
         btnConnect.Content    = "Подключиться";
         isConnected           = false;
     }
 }
        public void ConnectClient(string url, string roomName)
        {
            
            EndpointAddress address = new EndpointAddress(url);
            var binding = new WSHttpBinding();
            var client = new ChatServiceClient(binding, address);

            var newForm = new ChatRoom(client, roomName, CurrentUser);
            if(!newForm.IsDisposed)
            newForm.Show();
        }
Exemplo n.º 29
0
 private void UpdateTexts()
 {
     listViewMessageAll.Clear();
     ServiceReferenceChatUp.ChatServiceClient client = new ChatServiceClient("All");
     var result = client.GetPosts(3);
     foreach (var customPost in result)
     {
         listViewMessageAll.Items.Add($"{customPost.Submitter} {customPost.TimeSubmitted}\r\n {customPost.Comment}:");
         
     }
 }
Exemplo n.º 30
0
 void DisconnectUser()
 {
     if (isConnected)
     {
         client.Disconnect(ID);
         client = null;
         tbUserName.IsEnabled = true;
         btnConDiscon.Content = "Connect";
         isConnected          = false;
     }
 }
Exemplo n.º 31
0
 void ConnectUser()
 {
     if (!isConnected)
     {
         client = new ChatServiceClient(new System.ServiceModel.InstanceContext(this));
         ID     = client.Connect(tbUserName.Text);
         tbUserName.IsEnabled = false;
         btnConDiscon.Content = "Disconnect";
         isConnected          = true;
     }
 }
Exemplo n.º 32
0
 public void OnDisconnect(DateTime dateTime, bool result, string message)
 {
     try {
         client.Close();
     } catch {
         // Ignore any error
         client.Abort();
     } finally {
         client = null;
         Disconnected(this, result, dateTime, message);
     }
 }
        public void Initialize()
        {
            client = TestUtils.CreateTestServerAndClient();

            conversationDto1 = new AddConversationDto
            {
                Participants = new List <string> {
                    Guid.NewGuid().ToString(), Guid.NewGuid().ToString()
                }
            };
            conversationDto2 = new AddConversationDto
            {
                Participants = new List <string> {
                    conversationDto1.Participants[0], Guid.NewGuid().ToString()
                }
            };
            conversationDto3 = new AddConversationDto
            {
                Participants = new List <string> {
                    Guid.NewGuid().ToString(), Guid.NewGuid().ToString()
                }
            };
            conversationDto4 = new AddConversationDto
            {
                Participants = new List <string> {
                    conversationDto1.Participants[0], Guid.NewGuid().ToString()
                }
            };

            userProfile1 = new CreateProfileDto
            {
                Username  = conversationDto1.Participants[1],
                FirstName = Guid.NewGuid().ToString(),
                LastName  = Guid.NewGuid().ToString()
            };
            userProfile2 = new CreateProfileDto
            {
                Username  = conversationDto2.Participants[1],
                FirstName = Guid.NewGuid().ToString(),
                LastName  = Guid.NewGuid().ToString()
            };
            userProfile3 = new CreateProfileDto
            {
                Username  = conversationDto4.Participants[1],
                FirstName = Guid.NewGuid().ToString(),
                LastName  = Guid.NewGuid().ToString()
            };

            messageDto1 = new AddMessageDto("Hi!", conversationDto1.Participants[0]);
            messageDto2 = new AddMessageDto("Hello!", conversationDto1.Participants[1]);
            messageDto3 = new AddMessageDto("Hi!", "foo");
            messageDto4 = new AddMessageDto("Kifak!", conversationDto1.Participants[1]);
        }
Exemplo n.º 34
0
        private void HandleProxy()
        {
            if (chatClient == null)
            {
                return;
            }

            switch (chatClient.State)
            {
            case CommunicationState.Closed:
                chatClient = null;
                //chatListBoxMsgs.Items.Clear();
                //chatListBoxNames.Items.Clear();
                //loginLabelStatus.Content = "Disconnected";
                //ShowChat(false);
                //ShowLogin(true);
                //loginButtonConnect.IsEnabled = true;
                break;

            case CommunicationState.Closing:
                break;

            case CommunicationState.Created:
                break;

            case CommunicationState.Faulted:
                chatClient.Abort();
                chatClient = null;
                //chatListBoxMsgs.Items.Clear();
                //chatListBoxNames.Items.Clear();
                //ShowChat(false);
                //ShowLogin(true);
                //loginLabelStatus.Content = "Disconnected";
                //loginButtonConnect.IsEnabled = true;
                break;

            case CommunicationState.Opened:
                //ShowLogin(false);
                //ShowChat(true);

                //chatLabelCurrentStatus.Content = "online";
                //chatLabelCurrentUName.Content = localClient.Name;

                //Dictionary<int, Image> images = GetImages();
                //Image img = images[loginComboBoxImgs.SelectedIndex];
                //chatCurrentImage.Source = img.Source;
                break;

            case CommunicationState.Opening:
                break;
            }
        }
Exemplo n.º 35
0
    public void LogIn()
    {
      if (!Validation.IsValidUserName(this.UserName))
      {
        this._parent.DisplayError("Invalid username provided. Usernames must be between 1-20 alpha-numeric characters.", this);
        this.UserName = string.Empty;
        return;
      }

      var port = GeneratePort();

      this.Logger.Info($"LoginViewModel.LogIn - Attempting to log in \'{this.UserName}\' on port {port}.");
      
      this._eventService.Start((ushort)port);
      
      var serviceClient = new ChatServiceClient("BasicHttpBinding_IChatService");

      var responseString = serviceClient.LogIn(this.UserName, port);
      LoginResponse response;
      try
      {
        response = JsonConvert.DeserializeObject<LoginResponse>(responseString);
      }
      catch (Exception)
      {
        // TODO: Handle a malformed response received.
        throw;
      }

      switch(response.Result)
      {
        case LoginResult.Success:
          this.HandleSuccessfulLogin(response);
          break;

        case LoginResult.AccountNotRegistered:
          // TODO:
          this._parent.DisplayError("Login failed, please enter a valid username or register as a new user.", this);
          break;

        case LoginResult.InvalidPort:
          // TODO:
          break;

        case LoginResult.InvalidAccountName:
          // TODO:
          break;

        default:
          throw new ArgumentOutOfRangeException();
      }
    }
Exemplo n.º 36
0
        /// <summary>
        /// Establishes a connection with chat callback to enter to the game chat.
        /// </summary>
        /// <param name="game">Game to interact</param>
        /// <param name="player">Player who will enter to the game chat</param>
        /// <param name="chatListBox">Chat list box where the messages will be placed on</param>
        /// <param name="chatServiceClient">Instance where connection will be placed on</param>
        public static void JoinGameChat(Game game, Player player, System.Windows.Controls.ListBox chatListBox, ref ChatServiceClient chatServiceClient)
        {
            InstanceContext chatInstanceContext = new InstanceContext(new ChatCallbackHandler(game, chatListBox));

            chatServiceClient = new ChatServiceClient(chatInstanceContext);
            while (true)
            {
                if (player != null)
                {
                    chatServiceClient.EnterChat(game.ActiveGuidGame, player.Account.Username);
                    break;
                }
            }
        }
        public MainPage()
        {
            InitializeComponent();



            c = new ChatServiceClient();

            state              = (int)State.StateEnum.Out;
            c.LoginCompleted  += new EventHandler <System.ComponentModel.AsyncCompletedEventArgs>(c_LoginCompleted);
            c.UsersReceived   += new EventHandler <UsersReceivedEventArgs>(c_UsersReceived);
            c.LogoutCompleted += new EventHandler <System.ComponentModel.AsyncCompletedEventArgs>(c_LogoutCompleted);
            c.ReceiveReceived += new EventHandler <ReceiveReceivedEventArgs>(c_ReceiveReceived);
        }
Exemplo n.º 38
0
 private void buttonSendMessageAll_Click(object sender, EventArgs e)
 {
     ChatServiceClient client = new ChatServiceClient("All");
     CustomPost post = new CustomPost
     {
         Submitter = _userName,
         TimeSubmitted = DateTime.Now,
         Comment = richTextBoxMessageAll.Text,
         ChatRoomId = 3
     };
     client.SubmitPost(post);
     richTextBoxMessageAll.Clear();
     UpdateTexts();
 }
        public DeploymentTestsFixture()
        {
            string serviceUrl = Environment.GetEnvironmentVariable("ChatServiceDeploymentTestsUrl");

            if (string.IsNullOrWhiteSpace(serviceUrl))
            {
                throw new Exception("Could not find ChatServiceUrl environment variable");
            }

            ChatServiceClient = new ChatServiceClient(new System.Net.Http.HttpClient
            {
                BaseAddress = new Uri(serviceUrl)
            });
        }
Exemplo n.º 40
0
    public void Add()
    {
      if(!Validation.IsValidUserName(this.UserName))
      {
        this._parent.DisplayError("Invalid username provided. Usernames must be between 1-20 alpha-numeric characters.", this);
      }
      
      var serviceClient = new ChatServiceClient(Config.ServiceEndpointName);
      var response = serviceClient.SendFriendRequest(this._parent.MainViewModel.UserName, this.UserName);

      // TODO: Verify reponse and handle any errors.

      this._parent.MainViewModel.MessageText += $"Friend request was successfully sent to {this.UserName}!\n";
      this._parent.ShowPage(this._parent.MainViewModel, this);
    }
Exemplo n.º 41
0
 private void BtnLogin_Click(object sender, RoutedEventArgs e)
 {
     if (!ValidateUserNameNotEmpty())
     {
         TxtbUserNameRequired.Visibility = Visibility.Visible;
         return;
     }
     var serviceClient = new ChatServiceClient(
         new PollingDuplexHttpBinding { DuplexMode = PollingDuplexMode.MultipleMessagesPerPoll },
         new EndpointAddress("../ChatService.svc"));
     var model = new MainChatModel(serviceClient, TxtUserName.Text);
     var mainPageViewModel = new MainPageViewModel(model);
     var mainPage = new MainPage {DataContext = mainPageViewModel };
     var app = (App) Application.Current;
     app.RedirectTo(mainPage);
 }
Exemplo n.º 42
0
        /// <summary>
        /// 连接服务器
        /// </summary>
        private void InterChatMenuItem_Click(object sender, EventArgs e)
        {
            lbOnlineUsers.Items.Clear();
            LoginForm loginDlg = new LoginForm();
            if (loginDlg.ShowDialog() == DialogResult.OK)
            {
                userName = loginDlg.txtUserName.Text;
                loginDlg.Close();
            }

            txtChatContent.Focus();
            Application.DoEvents();
            InstanceContext site = new InstanceContext(this);//为实现服务实例的对象进行初始化
            proxy = new ChatServiceClient(site);
            IAsyncResult iar = proxy.BeginJoin(userName, new AsyncCallback(OnEndJoin), null);
            wfDlg.ShowDialog();
        }
Exemplo n.º 43
0
        static void Main(string[] args)
        {
            using(ChatServiceClient proxy = new ChatServiceClient())
            {
                Console.Write("Username: "******"[{0}]: ", name);
                String note = Console.ReadLine();
                while (note != "")
                {
                    Console.WriteLine("----------");
                    Console.WriteLine(proxy.PostNote(name, note));
                    Console.Write("[{0}]: ", name);
                    note = Console.ReadLine();
                }

            }
        }
Exemplo n.º 44
0
        /// <summary>
        /// 首页的视图模型
        /// </summary>
        public IndexViewModel()
        {
            chatClient = new ChatServiceClient(new InstanceContext(this));
            chatClient.RegisterAndGetFriendListCompleted += WriteFriendList;
            chatClient.ChangeTargetUserCompleted += WriteNewMessages;
            chatClient.GetMessagesCompleted += WriteOldMessages;
            chatClient.RegisterAndGetFriendListAsync(Username, true);

            Users = new ObservableCollection<UserInfoModel>();
            Messages = new ObservableCollection<MessageResult>();
            LogoutCommand = new UniversalCommand(new Action<object>(Logout));
            OpenTalkingWindowCommand = new UniversalCommand(new Action<object>(OpenTalkingWindow));
            ChooseWhatDoingCommand = new UniversalCommand(new Action<object>(ChooseWhatDoing));
            SendMessageCommand = new UniversalCommand(new Action<object>(SendNewMessage));
            ShowChooseIconWindowCommand = new UniversalCommand(new Action<object>(ShowChooseIconWindow));
            ShowUploadPicWindowCommand = new UniversalCommand(new Action<object>(ShowUploadPicWindow));
            KeepHeartbeat();
        }
Exemplo n.º 45
0
        public ActionResult GetMessages(string chatType)
        {
            try
            {
                ChatServiceClient client = new ChatServiceClient(chatType);
                var type = (ChatType) Enum.Parse(typeof (ChatType), chatType);
                var result = client.GetChats(type).ToList();

                return Json(new WcfResult("Recieved messages", true, result), JsonRequestBehavior.AllowGet);
            }
            catch (FaultException ex)
            {
                return Json(new WcfResult(ex.Message,false), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new WcfResult(ex.Message, false), JsonRequestBehavior.AllowGet);
            }

        }
Exemplo n.º 46
0
        public JsonResult DeleteMessage(string chatType, string messageId)
        {
            var deleteResult = false;
            try
            {
                ChatServiceClient client = new ChatServiceClient(chatType);
                 deleteResult = client.RemoveChat(new Guid(messageId));

                return Json(new WcfResult("Deleted Message",deleteResult), JsonRequestBehavior.AllowGet);
            }
            catch (FaultException ex)
            {
                return Json(new WcfResult(ex.Message ,deleteResult), JsonRequestBehavior.AllowGet);

            }
            catch (Exception ex)
            {
                return Json(new WcfResult(ex.Message,deleteResult), JsonRequestBehavior.AllowGet);
            }

        }
Exemplo n.º 47
0
    public void Send()
    {
      if (this.SelectedFriend == null)
      {
        // TODO: Display a message that no friend is selected.
        return;
      }

      if (this.SelectedFriend.Presence == PresenceStatus.Offline)
      {
        // TODO: Display a message that the person is offline.
        return;
      }

      this.Logger.Info($"MainViewModel.Send - Sending message to {this.SelectedFriend.FriendName}");
      var client = new ChatServiceClient("BasicHttpBinding_IChatService");
      client.SendMessage(this.UserId, this.SelectedFriend.FriendName, this.EntryText);

      this.MessageText += $"[To: {this.SelectedFriend.FriendName}] {this.EntryText}\n";
      this.EntryText = string.Empty;
    }
Exemplo n.º 48
0
 public JsonResult SendMessage(string username, string chatType, string message)
 {
     try
     {
         ChatServiceClient client = new ChatServiceClient(chatType);
         client.SubmitChat(new Message
         {
             Comment = message,
             ChatType = (ChatType) Enum.Parse(typeof (ChatType), chatType),
             Submitter = username
         });
         return Json(new WcfResult("Message sent", true), JsonRequestBehavior.AllowGet);
     }
     catch (FaultException ex)
     {
         return Json(new WcfResult(ex.Message, false), JsonRequestBehavior.AllowGet);
     }
     catch (Exception ex)
     {
         return Json(new WcfResult(ex.Message, false), JsonRequestBehavior.AllowGet);
     }
     
 }
Exemplo n.º 49
0
 public void CreateTracker()
 {
     Tracker = new ChatServiceClient(new InstanceContext(new MessageReceived(this)), new WSDualHttpBinding(), new EndpointAddress(_uri));
 }
Exemplo n.º 50
0
 /// <summary>
 /// 释放使用资源
 /// </summary>
 private void AbortProxyAndUpdateUI()
 {
     if (proxy != null)
     {
         proxy.Abort();
         proxy.Close();
         proxy = null;
     }
     ShowInterChatMenuItem(true);
 }
Exemplo n.º 51
0
        static void Main(string[] args)
        {
            ManualResetEventSlim mReset = new ManualResetEventSlim();
            Uri uri = null;

            Thread hosting = new Thread(() =>
                                            {
                                                #if DEBUG

                                                    Thread.CurrentThread.Name = "ServiceHost";

                                                #endif

                                                using (ServiceHost serviceHost = new ServiceHost(typeof(ChatServiceProject.ChatService)))
                                                {
                                                    // Open the ServiceHost to create listeners and start listening for messages.
                                                    serviceHost.Open();
                                                    Console.WriteLine("[SERVICE] Service is starting!");

                                                    uri =
                                                        serviceHost.Description.Endpoints.SingleOrDefault(
                                                            p => p.Contract.Name != "IMetadataExchange").Address.Uri;

                                                    mReset.Set();

                                                    lock (serviceHost)
                                                    {
                                                        try
                                                        {
                                                            Monitor.Wait(serviceHost);
                                                        }
                                                        catch (ThreadInterruptedException)
                                                        {
                                                            Console.WriteLine("[SERVICE] Service is ending!");
                                                        }
                                                    }

                                                }
                                            });

            hosting.Start();

            mReset.Wait();

            ChatServiceClient chatClient = new ChatServiceClient(new InstanceContext(new MessageCallback()), new WSDualHttpBinding(), new EndpointAddress(uri));

            Console.Write("User: "******"Sports", "pt");

            string read;
            do
            {
                Console.Write("Message: ");
                read = Console.ReadLine();

                if (read.Equals("exit"))
                    break;

                chatClient.SendMessage(read);
            } while (true);

            chatClient.Unsubscribe();
            hosting.Interrupt();
        }
Exemplo n.º 52
0
 protected ChatModelBase(ChatServiceClient proxy, string userName)
 {
     UserName = userName;
     Proxy = proxy;
 }
Exemplo n.º 53
0
        /// <summary>
        /// 初始化
        /// </summary>
        private void Initialize()
        {
            CustomerServiceList = new ObservableCollection<UserInfo>();
            CustomerServiceList.CollectionChanged += (d, e) => { OnPropertyChanged(this, "CustomerServiceList"); };
            SuperiorList = new ObservableCollection<UserInfo>();
            SuperiorList.CollectionChanged += (d, e) => { OnPropertyChanged(this, "SuperiorList"); };
            LowerList = new ObservableCollection<UserInfo>();
            LowerList.CollectionChanged += (d, e) => { OnPropertyChanged(this, "LowerList"); };

            ChatingWithList = new ObservableCollection<UserInfo>();
            CurrentMessages = new ObservableCollection<MessageResult>();

            currentUserOnlineState = UserOnlineStatus.在线;
            chatWindowIsOpen = false;
            friendListWindowIsOpen = false;
            newMessageCount = 0;
            customerServiceListIsOpen = false;
            superiorListIsOpen = false;
            lowerListIsOpen = false;
            waitSendContent = "";
            chatingWith = "";

            SendMessageCommand = new BaseCommand(SendMessage);
            AddExpressionCommand = new BaseCommand(AddExpression);
            CloseCurrentChatCommand = new BaseCommand(CloseCurrentChat);
            AddScreenShotCommand = new BaseCommand(AddScreenShot);

            Command = new BaseCommand(BeginChatToSomeone);
            SwitchChatingWithCommand = new BaseCommand(SwitchChatingWith);

            TimeToReflashCustomerServiceList = false;
            TimeToReflash2CustomerServiceList = false;

            chatClient = new ChatServiceClient(new InstanceContext(this));
            chatClient.RegisterAndGetFriendListCompleted += ChatClientRegisterAndGetFriendListCompleted;
            chatClient.RegisterAndGetFriendListAsync(CurrentUser, false);
        }
Exemplo n.º 54
0
 public MainChatModel(ChatServiceClient proxy, string userName)
     : base(proxy, userName)
 {
     Proxy.NotifyReceived += ProxyOnNotifyReceived;
     Proxy.NotifyPersonalReceived += ProxyOnNotifyPersonalReceived;
 }
Exemplo n.º 55
0
 private void FormClient_Load(object sender, EventArgs e)
 {
     ClientCallback callback = new ClientCallback();
     callback.addMessageToTextbox += new ClientCallback.UpdateTextBoxDelegate(
         AddNewMessage);
     callback.updateUsersList += new ClientCallback.UpdateListDelegate(
         UpdateUsersListbox);
     client = new ChatServiceClient(new InstanceContext(callback));
 }
Exemplo n.º 56
0
 public AddToGroupWindow(RoomControl room)
 {
     InitializeComponent();
     _currentRoom = room;
     _chatService = new ChatServiceClient();
 }
Exemplo n.º 57
0
 private List<Message> InitializeChatRoom(List<Message> messages, ChatType chatType)
 {
     client = new ChatServiceClient(chatType.ToString());
     messages = client.GetChats(chatType).ToList();
     currentChatType = chatType;
     return messages;
 }
Exemplo n.º 58
0
 public void OnDisconnect(DateTime dateTime, bool result, string message)
 {
     try {
         client.Close();
     } catch {
         // Ignore any error
         client.Abort();
     } finally {
         client = null;
         Disconnected(this, result, dateTime, message);
     }
 }
Exemplo n.º 59
0
    public override void CanClose(Action<bool> callback)
    {
      base.CanClose(callback);

      try
      {
        var client = new ChatServiceClient(Config.ServiceEndpointName);
        client.LogOff(this.UserName);
      }
      catch (Exception)
      {
        this.Logger.Warn("MainViewModel.CanClose - An error occurred while trying to log off.");
      }
    }
Exemplo n.º 60
0
        public void Connect(string user, string host)
        {
            User = user;

            if (!host.Contains("://")) {
                host = string.Format("http://{0}", host);
            }
            Host = host;

            // Validate host
            Uri uri;
            UrlExtractor.TryCreate(Host, out uri, validHostUriSchemes);
            if (uri == null) {
                ConnectionFailed(this, DateTime.Now, string.Format("Invalid format for host: {0}", Host));
                return;
            }
            Host = uri.ToString();

            try {
                Binding binding;
                if (uri.Scheme.Equals(Uri.UriSchemeNetPipe)) {
                    var namedPipeBinding = new NetNamedPipeBinding();
                    namedPipeBinding.Security.Mode = NetNamedPipeSecurityMode.None;
                    binding = namedPipeBinding;
                } else if (uri.Scheme.Equals(Uri.UriSchemeNetTcp)) {
                    var tcpBinding = new NetTcpBinding();
                    tcpBinding.Security.Mode = SecurityMode.None;
                    binding = tcpBinding;
                } else {
                    var httpBinding = new WSDualHttpBinding();
                    httpBinding.Security.Mode = WSDualHttpSecurityMode.None;
                    binding = httpBinding;
                }

                // Append service name
                // Note: URI creation appends any missing "/" to the host, so it's safe to just append
                if (!Host.EndsWith(serviceName) && !Host.EndsWith(string.Format("{0}/", serviceName))) {
                    Host = string.Format("{0}{1}", Host, serviceName);
                }

                // Create the endpoint address
                EndpointAddress endpointAddress = new EndpointAddress(Host);
                client = new ChatServiceClient(new InstanceContext(this), binding, endpointAddress);

                client.Open();
                client.Connect(user);
            } catch (Exception exception) {
                TriggerConnectionFailed(exception);
            }
        }