Exemplo n.º 1
0
 /// <summary>
 /// Starts the server on specified URL and checks whether error is thrown when another server is already hosted on same URL.
 /// </summary>
 /// <remarks>
 /// Implemented by the use of SignalR framework.
 /// Form more information check SignalR documentation.</remarks>
 public void StartServer(FormLogin formLogin)
 {
     try
     {
         SignalR = WebApp.Start(ServerURI);
     }
     catch (TargetInvocationException)
     {
         formLogin.labelStatusText.Invoke(new MethodInvoker(delegate { formLogin.labelStatusText.Text = "Server failed to start.\nA server is already running on " + ServerURI; }));
         return;
     }
     formLogin.StartGameWindowServer(this);  //Starts the game window for administrator.
 }
Exemplo n.º 2
0
        /// <summary>
        /// Registers new player by creating new account in dataBase which stores his credentials.
        /// </summary>
        /// <param name="userName">Name of the player who wants to create new account.</param>
        /// <param name="password">Password which is used to sign into account.</param>
        /// <param name="formLogin">Form used to display information whether registration was successfull.</param>
        /// <remarks>
        /// Returns true if client account with given user name has been created.
        /// False if client account has not been created because username is already taken.
        /// </remarks>
        /// <returns>
        /// True if client account with given user name has been created.
        /// False if client account has not been created because username is already taken.
        /// </returns>
        public bool RegisterNewPlayer(string userName, string password, FormLogin formLogin)
        {
            using (var dataBase = new DataClassesBettingParlorDataContext())
            {
                if (!formLogin.CheckIfTextBoxesAreEmpty())
                {
                    Player player = dataBase.Players.SingleOrDefault(p => p.UserName == userName);

                    if (player == null)
                    {
                        Player newPlayer = new Player()
                        {
                            UserName = userName,
                            Password = password,
                            CurrentAccountBalance = 0,
                            UserTypeID            = 1
                        };
                        dataBase.Players.InsertOnSubmit(newPlayer);
                        dataBase.SubmitChanges();

                        result = FormLogin.Result.RegistrationSuccessful;
                        formLogin.ShowResult(result);
                        return(true);
                    }
                    else
                    {
                        result = FormLogin.Result.RegistrationFailed;
                        formLogin.ShowResult(result);
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// This method is the base for client-server connection.
        /// Includes the connection process and all methods wich are run on specific response from server.
        /// Every time server sends any kind of information to client this function is responisble for receiving it and handling it properly.
        /// Contains all client methods which can be exectuded on the server asynchronously.
        /// </summary>
        /// <exception cref="HttpRequestException">Thrown when connection can't be established.</exception>
        /// <param name="formLogin">UI is passed to display status of the connection properly.</param>
        public async void ConnectToServer(FormLogin formLogin)
        {
            bool successfulConnection = true;   //parameter user to define whether connection to server was successfull or not.

            //Quering user data to pass it to server
            var queryStringData = new Dictionary <string, string>
            {
                { "username", userName }
            };

            Connection = new HubConnection(ServerURI, queryStringData);
            HubProxy   = Connection.CreateHubProxy("ClientServerConnectionsHub"); //create proxy which is used for receving responses from server.

            //Receive information from server that user tries to sign in on different forms without logging out or the  race is currently on.
            HubProxy.On <bool>("StopConnection", (raceIsOn) =>
            {
                successfulConnection = false;

                if (raceIsOn)
                {
                    formLogin.Invoke((Action)(() =>
                                              MessageBox.Show("Race is currently on. Please wait till the race ends and try to sign in again.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)));
                }
                else
                {
                    formLogin.Invoke((Action)(() =>
                                              MessageBox.Show("You are already signed in on another form. Please close all open forms and reconnect to the server.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)));
                }

                formLogin.labelStatusText.Invoke(new MethodInvoker(delegate { formLogin.labelStatusText.Text = "Log in failed due to error."; }));
                Disconnect();
            });


            //Receive notification whether the race started or not to handle buttons properly.
            HubProxy.On <string>("HandleControlsOnTheForm", (notification) =>
            {
                FormClient.Invoke((Action)(() =>
                {
                    if (notification == "race begins")
                    {
                        FormClient.EnableControlsOnRaceStart();
                    }
                    else if (notification == "disable handicap")
                    {
                        FormClient.DisableHandicapPanel();
                    }
                    else
                    {
                        return;
                    }
                }));
            });

            //Receive dog number which won the game to show the winner and prepare the GUI for next race.
            HubProxy.On <int>("ManageControlsAfterRaceHasFinished", (dogWinner) =>
                              FormClient.Invoke((Action)(() =>
                                                         FormClient.HandleControlsAfterRaceHasFinished(dogWinner))
                                                ));

            //Get response from server whether bet operation was successful or not and show aprioprate messagebox.
            HubProxy.On <bool, bool>("PlaceBetResult", (result, isStandardBet) =>
                                     FormClient.Invoke((Action)(() =>
            {
                Task.Run(() => FormClient.ShowResultBet(result));                 //run this method async to prevent block of the main UI thread.

                if (result)                                                       //check if user was able to place bet (had enough cash in his object on server)
                {
                    if (isStandardBet)                                            //check if this response is about standard bet.
                    {
                        FormClient.DisableSignOutOptionAfterPlacingStandardBet(); //only one standard bet is allowed.
                    }
                    else
                    {
                        FormClient.DisableHandicapPanel();      //only one handicap is allowed.
                    }
                }
            })));

            //Get current account balance of player and update his label on the form.
            HubProxy.On <decimal>("UpdateSaldoLabel", (saldo) =>
                                  FormClient.Invoke((Action)(() =>
                                                             FormClient.UpdateCurrentAccountBalanceLabel(saldo))
                                                    ));

            //Receive location of each dog on the server form and update them on client form.
            HubProxy.On <int, int>("MoveDogs", (dogNumber, location) =>
                                   FormClient.Invoke((Action)(() =>
                                                              FormClient.MoveDogsOnClientForm(dogNumber, location))
                                                     ));


            //Handle incoming event from server: use Invoke to write to console from SignalR's thread
            //Adds message of specific player to all connected clients chats.
            HubProxy.On <string, string>("AddMessage", (name, message) =>
                                         FormClient.Invoke((Action)(() =>
                                                                    FormClient.GetRichTextBoxConsole.AppendText(String.Format("{0}: {1}" + Environment.NewLine, name, message))
                                                                    ))
                                         );

            //Updates dataGriedView on client form to display new bets.
            HubProxy.On("UpdateBetTable", () =>
                        FormClient.Invoke((Action)(() =>
                                                   FormClient.UpdateDataGriedView())
                                          ));

            try
            {
                await Connection.Start();
            }
            catch (HttpRequestException)
            {
                formLogin.labelStatusText.Text = "Unable to connect to server: Game server is not responding.";
                return;
            }

            if (successfulConnection)                  //prevents opening client form when client wasn't able to establish connection.
            {
                formLogin.StartGameWindowClient(this); //This function is placed here because it MUST trigger after the try-catch formula is passed.
            }
        }