private void Register_Click(object sender, RoutedEventArgs e)
        {
            // If a file was brought from resources path, fix the absolute path to point to it.
            if (filename.StartsWith("resources"))
            {
                filename = filename.Replace("/", "\\");
                filename = Path.Combine(Environment.CurrentDirectory, filename);
                filename = filename.Replace("bin\\Debug\\", "");
            }
            Image img  = Image.FromFile(filename);
            var   user = CommClient.Register(username.Text, password.Text, email.Text, img);

            if (user != default(SystemUser))
            {
                LoginWindow.user = user;
                Close();
                new MainMenuWindow(loginWindow).Show();
                // Create the invisible system messages window.
                var messagesWindow = new SystemMessageWindow();
                user.Subscribe(messagesWindow);
            }
            else
            {
                errorMessage.Text = "Could not register at the moment.";
            }
        }
        //private void getPlayer()
        //{
        //    mePlayer = CommClient.GetPlayer(this.game.gameId, playerSeatIndex);
        //}

        public void updatePlayerCards()
        {
            Dictionary <int, List <Card> > cards = CommClient.GetPlayerCards(this.game.gameId, systemUserId);
            List <Card> c;

            if (cards != null)
            {
                for (int i = 0; i < playerCards.Length; i++)
                {
                    if (cards.TryGetValue(i, out c) && c.Count == 2)
                    {
                        playerCards[i][0].Source = DrawCard(c[0].Type, c[0].Value);
                        playerCards[i][1].Source = DrawCard(c[1].Type, c[1].Value);
                    }
                    else
                    {
                        playerCards[i][0].Source = DrawCard(cardType.unknown, CARD_TYPE);
                        playerCards[i][1].Source = DrawCard(cardType.unknown, CARD_TYPE);
                    }
                }
            }

            //for (int i = 0; i < cards.Length; i++)
            //{
            //    if (cards[i] == null)
            //        playerCards[playerSeatIndex][i].Source = DrawCard(cards[i].Type, cards[i].Value);
            //    else
            //        playerCards[playerSeatIndex][i].Source = DrawCard(cardType.unknown, CARD_TYPE);
            //}
        }
        public SelectReplayWindow(Window mainMenuWindow)
        {
            InitializeComponent();
            this.mainMenuWindow = mainMenuWindow;
            var gameLogStrings = CommClient.getGameLogs();

            if (gameLogStrings == null)
            {
                MessageBox.Show("No game replays found.");
            }

            else
            {
                int i = 0;
                foreach (string[] logData in gameLogStrings)
                {
                    // Create a new game log instance.
                    var gl = new GameLog(logData);

                    // Add game log instance to game logs list.
                    gameLogs.Add(gl);

                    // Pour game log meta data into view grid list.
                    selectGameGrid.Items.Add(gl.getMetaData(i));
                    i++;
                }
            }
        }
예제 #4
0
        private void Update_Click(object sender, RoutedEventArgs e)
        {
            int money;

            if (!Int32.TryParse(MoneyDeposit.Text, out money) || money < 0)
            {
                errorMessage.Text = "Please enter a positive number";
            }
            else
            {
                bool?m = CommClient.editUserProfile(LoginWindow.user.id, username.Text, password.Text, email.Text, tempImage, money);

                if (m.HasValue && m.Value)
                {
                    Hide();
                    LoginWindow.user.name               = username.Text;
                    LoginWindow.user.password           = password.Text;
                    LoginWindow.user.email              = email.Text;
                    LoginWindow.user.money             += money;
                    LoginWindow.user.profilePicture     = tempImage;
                    LoginWindow.user.userImageByteArray = imageToByteArray(tempImage);
                    MainMenuWindow.Show();
                }
                else
                {
                    errorMessage.Text = "Could not edit user profile.";
                }
            }
        }
        // raise bet of some player
        private void BetButton_Click(object sender, RoutedEventArgs e)
        {
            int playerCoinsNum = 0, playerCoinsGambledNum, coins;

            if (game.gameOnChips)
            {
                int temp = 0;
                int.TryParse(playerChips[playerSeatIndex][3].Content.ToString(), out temp);
                playerCoinsNum += (temp * 20);
                int.TryParse(playerChips[playerSeatIndex][2].Content.ToString(), out temp);
                playerCoinsNum += (temp * 10);
                int.TryParse(playerChips[playerSeatIndex][1].Content.ToString(), out temp);
                playerCoinsNum += (temp * 5);
                int.TryParse(playerChips[playerSeatIndex][0].Content.ToString(), out temp);
                playerCoinsNum += (temp * 1);
            }
            else
            {
                int.TryParse(playerCash[playerSeatIndex].Content.ToString(), out playerCoinsNum);
            }
            int.TryParse(playerAmountGambled[playerSeatIndex].Content.ToString(), out playerCoinsGambledNum);
            //          int inserted                           put the minimal bet at least and not all in              tried to put more coins that he had
            if (!Int32.TryParse(betTextBox.Text, out coins) || coins < getMinimumBet() || playerCoinsNum < coins)
            {
                MessageBox.Show("bad bet number entered");
                return;
            }

            ReturnMessage returnMessage = CommClient.Bet(game.gameId, playerSeatIndex, coins);

            if (!returnMessage.success)
            {
                MessageBox.Show(returnMessage.description);
            }
        }
예제 #6
0
 /// <summary>
 ///
 /// </summary>
 public void CloseClient()
 {
     if (CommClient != null)
     {
         CommClient.Close();
     }
 }
예제 #7
0
        /// <summary>
        ///
        /// </summary>
        private void SetUpReceivingTask()
        {
            TcpReceivingTask = new Task(() =>
            {
                var bytes = new byte[4];

                try
                {
                    while (true)
                    {
                        var count = CommClient.Client.Receive(bytes, 4, SocketFlags.None);

                        if (count == 0)
                        {
                            throw new Exception("Remote Endpoint could be closed");
                        }

                        buffer = buffer.Concat(bytes.Take(count)).ToArray();
                        HandleBuffer();
                    }
                }
                catch (Exception ex)
                {
                    throw new CommunicationTaskException(ex);
                }
                finally
                {
                    CommClient.Close();
                    CommClient = null;
                }
            });
        }
예제 #8
0
        public SelectGameWindow(Window mainMenuWindow, string joinOperation)
        {
            InitializeComponent();
            this.mainMenuWindow = mainMenuWindow;
            actionBtn.Content   = joinOperation;
            List <TexasHoldemGame> allGames = CommClient.findAllActiveAvailableGames();

            int i = 0;

            if (allGames == null)
            {
                MessageBox.Show("No active games.");
            }

            else
            {
                foreach (TexasHoldemGame game in allGames)
                {
                    if (joinOperation.Equals("Spectate") &&
                        (game.gamePreferences.isSpectateAllowed) || (joinOperation.Equals("Join")))
                    {
                        selectGameGrid.Items.Add(new TexasHoldemGameStrings(i, game));
                        i++;
                    }
                }
            }
        }
예제 #9
0
 // CLIENT only
 public virtual bool ConnectToServer(string ip, int port, string alias)
 {
     commClient = new CommClient(ip, port, alias);
     InitializeMultiplayer();
     //ChatManager.PlayerAlias = alias;
     return(commClient.Connect());
 }
예제 #10
0
 private void Logout_Click(object sender, RoutedEventArgs e)
 {
     CommClient.Logout(LoginWindow.user.id);
     LoginWindow.user = null;
     CommClient.closeConnection();
     Close();
     loginWindow.Show();
 }
        private void CallButton_Click(object sender, RoutedEventArgs e)
        {
            ReturnMessage returnMessage = CommClient.Call(game.gameId, playerSeatIndex, getMinimumBet());

            if (!returnMessage.success)
            {
                MessageBox.Show(returnMessage.description);
            }
        }
        private void GameWindow_Closed(object sender, EventArgs e)
        {
            ReturnMessage returnMessage = CommClient.RemoveUser(game.gameId, systemUserId);

            if (!returnMessage.success)
            {
                MessageBox.Show(returnMessage.description);
            }
        }
        private void CheckButton_Click(object sender, RoutedEventArgs e)
        {
            ReturnMessage returnMessage = CommClient.Check(game.gameId, playerSeatIndex);

            //if (returnMessage.success)
            //    seatButtonToImageDictionary[seatsButtons[playerSeatIndex]].Source = new BitmapImage(new Uri("pack://application:,,,/resources/green.png"));
            if (!returnMessage.success)
            {
                MessageBox.Show(returnMessage.description);
            }
        }
예제 #14
0
        public void loginTest()
        {
            int manyUsers = 10000;

            for (int i = 0; i < manyUsers; i++)
            {
                Task.Factory.StartNew(() =>
                {
                    Console.WriteLine(Convert.ToString(i));
                    var sysUser = CommClient.Register(Convert.ToString(i), Convert.ToString(i), Convert.ToString(i), null /*Convert.ToString(i)*/);
                });
            }
        }
        private void Sit_Click(object sender, RoutedEventArgs e)
        {
            ReturnMessage returnMessage = CommClient.JoinGame(LoginWindow.user.id, this.game.gameId, seatButtonToSeatIndex[(Button)sender]);

            if (returnMessage.success)
            {
                playerSeatIndex = seatButtonToSeatIndex[(Button)sender];
            }
            else
            {
                MessageBox.Show(returnMessage.description);
            }
        }
        // send a comment
        private void CommentButton_Click(object sender, RoutedEventArgs e)
        {
            ReturnMessage returnMessage = CommClient.AddMessage(game.gameId, systemUserId, messagesTextBox.Text);

            if ((returnMessage != null) && (returnMessage.success))
            {
                messagesTextBox.Text = "";
            }
            if ((returnMessage != null) && (!returnMessage.success))
            {
                MessageBox.Show(returnMessage.description);
            }
        }
        private void Search_Click(object sender, RoutedEventArgs e)
        {
            List <TexasHoldemGame> gamesFound = new List <TexasHoldemGame>();

            if (playerNameCheckBox.IsChecked.HasValue && playerNameCheckBox.IsChecked.Value)
            {
                if (playerNameTextbox.Text.Equals(""))
                {
                    errorMessage.Text = "Wrong Input - empty player name.";
                }
                else
                {
                    gamesFound = CommClient.filterActiveGamesByPlayerName(playerNameTextbox.Text);
                }
            }
            else if (potSizeCheckBox.IsChecked.HasValue && potSizeCheckBox.IsChecked.Value)
            {
                int potSize;
                if (potSizeTextbox.Text.Equals(""))
                {
                    errorMessage.Text = "Wrong Input - empty pot size.";
                }
                else if (!Int32.TryParse(potSizeTextbox.Text, out potSize) || potSize < 0)
                {
                    errorMessage.Text = "Wrong Input - pot size should be int and positive.";
                }
                else
                {
                    gamesFound = CommClient.filterActiveGamesByPotSize(potSize);
                }
            }
            else
            {
                gamesFound = getFilteredGameByPreferences();
            }
            if (gamesFound == null || gamesFound.Count == 0)
            {
                errorMessage.Text = "Couldn't find any games try to change your criterya.";
            }
            else
            {
                int i = 0;
                foreach (TexasHoldemGame game in gamesFound)
                {
                    searchResultGrid.Items.Add(new TexasHoldemGameStrings(i, game));
                    i++;
                }
            }
        }
예제 #18
0
        public Client()
        {
            _client = new CommClient()
            {
                Configuration =
                {
                    Ssl                        = false,
                    CheckCertificateRevocation = false,
                    RequireClientCertificate   = false
                }
            };

            _client.Configuration.Protocol = new ProtocolHandler(_client, (m) =>
            {
                OnMessageRecived?.Invoke(m);
            });
        }
예제 #19
0
        public void CheckPacket(byte[] data, CommClient client)
        {
            this.pkt = new Packet();
            pkt.SetData(data);
            this.client = client;

            switch ((PacketOpcodes)pkt.Opcode)
            {
            case PacketOpcodes.SYS_ALIVE: /* TO SKIP LOGGING THIS PACKET */ break;

            case PacketOpcodes.SYS_HANDSHAKE_RES: client.SendHandShakeRes(); break;

            default:
                PacketDefinitions.LogPacketData(pkt);
                break;
            }
        }
        private void Login_Click(object sender, RoutedEventArgs e)
        {
            user = CommClient.Login(username.Text, password.Password);

            if (user == null)
            {
                MessageBox.Show("Wrong input.");
                return;
            }
            Hide();
            errorMessage.Text = "";

            // Create the invisible system messages window.
            var messagesWindow = new SystemMessageWindow();

            user.Subscribe(messagesWindow);
            new MainMenuWindow(this).Show();
        }
        private void Play_Click(object sender, RoutedEventArgs e)
        {
            ReturnMessage returnMessage = CommClient.playGame(game.gameId);

            if (returnMessage == null)
            {
                return;
            }

            if (!returnMessage.success)
            {
                MessageBox.Show(returnMessage.description);
            }
            else
            {
                playButton.IsEnabled = false;
            }
        }
예제 #22
0
        private void action_Click(object sender, RoutedEventArgs e)
        {
            errorMessage.Text = "";
            int gameId;

            if (actionBtn.Content.Equals("Spectate"))
            {
                DataGridCellInfo cellValue = (selectGameGrid.SelectedCells.ElementAt(1));
                gameId = Int32.Parse(((TexasHoldemGameStrings)cellValue.Item).gameId);
                var game = CommClient.spectateActiveGame(LoginWindow.user.id, gameId);
                if (game != default(TexasHoldemGame))
                {
                    Close();
                    mainMenuWindow.Show();
                    var gw = new GameWindow(game, LoginWindow.user.id, true);
                    game.Subscribe(gw);
                    gw.Show();
                }
                else
                {
                    errorMessage.Text = "Could not spectate chosen game.";
                }
            }
            else
            {
                DataGridCellInfo cellValue = (selectGameGrid.SelectedCells.ElementAt(1));
                gameId = int.Parse(((TexasHoldemGameStrings)cellValue.Item).gameId);
                var game = CommClient.GetGameInstance(gameId, LoginWindow.user.id);

                if (game != default(TexasHoldemGame))
                {
                    Close();
                    mainMenuWindow.Show();
                    var gameWindow = new GameWindow(game, LoginWindow.user.id, false);
                    game.Subscribe(gameWindow);
                    gameWindow.Show();
                }
                else
                {
                    errorMessage.Text = "Could not join chosen game.";
                }
            }
        }
        private void Spectate_Game_Click(object sender, RoutedEventArgs e)
        {
            int gameId;
            DataGridCellInfo cellValue = (searchResultGrid.SelectedCells.ElementAt(1));

            gameId = Int32.Parse(((TexasHoldemGameStrings)cellValue.Item).gameId);
            var game = CommClient.spectateActiveGame(LoginWindow.user.id, gameId);

            if (game != default(TexasHoldemGame))
            {
                this.Close();
                mainMenuWindow.Show();
                new GameWindow(game, LoginWindow.user.id, true).Show();
            }
            else
            {
                errorMessage.Text = "Could not spectate chosen game.";
            }
        }
        private void Join_Game_Click(object sender, RoutedEventArgs e)
        {
            errorMessage.Text = "";
            int gameId;
            DataGridCellInfo cellValue = (searchResultGrid.SelectedCells.ElementAt(1));

            gameId = Int32.Parse(((TexasHoldemGameStrings)cellValue.Item).gameId);
            var game = CommClient.GetGameInstance(gameId, LoginWindow.user.id);

            if (game != default(TexasHoldemGame))
            {
                Close();
                mainMenuWindow.Show();
                new GameWindow(game, LoginWindow.user.id, false).Show();
            }
            else
            {
                errorMessage.Text = "Could not join chosen game.";
            }
        }
예제 #25
0
        public void CheckPacket(byte[] data, CommClient client)
        {
            this.pkt = new Packet();
            pkt.SetData(data);
            this.client = client;

            switch ((PacketOpcodes)pkt.Opcode)
            {
            case PacketOpcodes.SYS_ALIVE: /* TO SKIP LOGGING THIS PACKET */ break;

            case PacketOpcodes.SYS_HANDSHAKE_RES: client.SendHandShakeRes(); break;

            case PacketOpcodes.UT_CHAT_MESSAGE_SAY: client.ChatSendMessageSay(data); break;

            //case PacketOpcodes.UT_GUILD_LEAVE_REQ:
            default:
                PacketDefinitions.LogPacketData(pkt);
                break;
            }
        }
예제 #26
0
        /// <summary>
        ///
        /// </summary>
        public async Task StartServer(CancellationToken token)
        {
            bool accepted       = false;
            bool listenerReturn = false;

            try
            {
                var commEndPoint = new IPEndPoint(IPAddress.Any, 10080);
                Listener        = new TcpListener(commEndPoint);
                BroadcastSender = new UdpClient();

                Listener.Start();

                var taskAccept = Task.Run(() =>
                {
                    try
                    {
                        CommClient = Listener.AcceptTcpClient();
                        accepted   = true;
                    }
                    finally
                    {
                        listenerReturn = true;
                    }
                });

                var taskBroadcast = Task.Run(async() =>
                {
                    while (true)
                    {
                        if (listenerReturn)
                        {
                            break;
                        }

                        try
                        {
                            var remoteEndPoint = new IPEndPoint(IPAddress.Broadcast, 10080);
                            BroadcastSender.Send(new byte[] { 0xcc, 0xdd }, 2, remoteEndPoint);
                        }
                        catch { }

                        await Task.Delay(2000);
                    }
                });

                var cancellationCheck = Task.Run(async() =>
                {
                    try
                    {
                        while (true)
                        {
                            await Task.Delay(500);

                            if (token.IsCancellationRequested)
                            {
                                if (!accepted)
                                {
                                    Listener.Stop();
                                }

                                break;
                            }

                            if (listenerReturn)
                            {
                                break;
                            }
                        }
                    }
                    catch { }
                });

                await taskAccept;
            }
            catch
            {
                throw;
            }
            finally
            {
                Listener.Stop();
                BroadcastSender.Close();

                if ((!accepted) && (CommClient != null))
                {
                    CommClient.Close();
                    CommClient = null;
                }

                if (accepted)
                {
                    SetUpReceivingTask();
                    CommunicationEstablished?.Invoke(true);
                }
            }
        }
예제 #27
0
 public Window1()
 {
     InitializeComponent();
     client = new CommClient();
 }
 private void Exit_Click(object sender, RoutedEventArgs e)
 {
     Application.Current.Shutdown();
     CommClient.closeConnection();
 }
예제 #29
0
        private static void InitiateCore(Boolean databaseOnly)
        {
            // Set the failed handler in order to catch also AlreadyRunning exceptions
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            OnKernelFailed += Kernel_OnKernelFailed;
            // At first we need to check if other beremote instances are running, if so we do some stuff...
            //var exists = ExistsMultipleBeremoteInstances();
            //if (exists)
            //{
            //    var client = new CommClient();
            //    client.ShowNotification("beRemote is already running. Trying to focus it now...");
            //    client.FocusMainWindow();

            //    throw new ApplicationAlreadyRunningException();
            //}

            // Starting the logging facility
            InitiateLogger();

            // Starting the inter communication wcf service for communication accross multiple beremote instances (cli support only)
            try
            {
                InterCommServer = new CommServer(KernelInstanceGuid);
                InterCommServer.Start();
            }
            catch (System.ServiceModel.AddressAlreadyInUseException ex)
            {
                var client = new CommClient();
                client.ShowNotification("beRemote is already running. Trying to focus it now...");
                client.FocusMainWindow();

                //TriggerNewConnection();

                var exc = new ApplicationAlreadyRunningException();

                OnKernelFailed(null, new KernelFailedEventArgs(exc));

                return;
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString(), 0);
            }


            try
            {
                //TODO: Remove this after update releases. Only for compatiblity purposes while old versions are in use
                var databasePath    = System.Environment.ExpandEnvironmentVariables(Helper.GetApplicationConfiguration().GetValue("database", "dbpath"));
                var newDbPath       = new FileInfo(databasePath);
                var compatOldDbPath = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "\\" + newDbPath.Name);

                if (compatOldDbPath.Exists && false == newDbPath.Exists)
                {
                    Logger.Warning("Database was present in executable folder. Copying it over to config file target.");

                    compatOldDbPath.CopyTo(newDbPath.FullName);
                }

                // possible override of database
                if (ParsedOptions != null)
                {
                    if (ParsedOptions.ContainsParameter("db-interface"))
                    {
                        var option = ParsedOptions.GetParameter("db-interface");

                        var localConfig = Helper.GetApplicationConfiguration();

                        Logger.Info("Overriding default database interface");

                        localConfig.SetValue("database", "dbinterface", option.Value, true);
                    }

                    if (ParsedOptions.ContainsParameter("db-path"))
                    {
                        var option = ParsedOptions.GetParameter("db-path");

                        var localConfig = Helper.GetApplicationConfiguration();

                        Logger.Info("Overriding default database path, now using: " + option.Value);

                        localConfig.SetValue("database", "dbpath", option.Value, true);
                    }
                }

                StorageCore.Core.InitDatabaseGuid(false);
            }
            catch { }

            // Deleting tmp folder
            try
            {
                var tmp = new DirectoryInfo(Environment.ExpandEnvironmentVariables("%appdata%\\beRemote\\tmp"));

                if (tmp.Exists)
                {
                    tmp.Delete(true);
                }
            }
            catch (Exception ex)
            {
                new beRemoteException(beRemoteExInfoPackage.MajorInformationPackage,
                                      "Problem removing tmp folder of previous instances.", ex);
            }


            if (true == databaseOnly)
            {
                Logger.Log(LogEntryType.Warning, "Kernel initiation is skipped due to database only flag!");

                if (OnKernelReady != null)
                {
                    OnKernelReady(new StackTrace(), new KernelReadyEventArgs());
                }

                return;
            }
            else
            {
                Logger.Log(LogEntryType.Debug, "Initiating beRemote ProtocolSystem thread", LoggerContext);

                AllPluginSystemCaller();


                Logger.Log(LogEntryType.Debug, "... all beRemote System threads are running!", LoggerContext);

                if (OnKernelReady != null)
                {
                    OnKernelReady(new StackTrace(), new KernelReadyEventArgs());
                }
            }
        }
예제 #30
0
 private void Exit_Click(object sender, RoutedEventArgs e)
 {
     CommClient.Logout(LoginWindow.user.id);
     Application.Current.Shutdown();
 }