/// <summary> /// Constructor /// </summary> /// <param name="Pid">The player account ID</param> public AccountEditForm(int Pid) { InitializeComponent(); this.AccountId = Pid; // Register for Events GpcmClient.OnSuccessfulLogin += GpcmClient_OnSuccessfulLogin; GpcmClient.OnDisconnect += GpcmClient_OnDisconnect; // Fill the account information boxes using (GamespyDatabase Database = new GamespyDatabase()) { Dictionary<string, object> User = Database.GetUser(AccountId); PlayerID.Value = AccountId = Int32.Parse(User["id"].ToString()); AccountNick.Text = User["name"].ToString(); AccountEmail.Text = User["email"].ToString(); // Disable options if user is online if (GamespyEmulator.IsPlayerConnected(AccountId)) { SatusLabel.Text = "Online (IP: " + User["lastip"].ToString() + ")"; UpdateBtn.Enabled = false; DeleteBtn.Enabled = false; DisconnectBtn.Enabled = true; } else { SatusLabel.Text = "Offline"; } } }
/// <summary> /// Event fired when the Delete button is pushed /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DeleteBtn_Click(object sender, EventArgs e) { if (MessageBox.Show("Are you sure you want to delete account?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { using (GamespyDatabase Database = new GamespyDatabase()) { if (Database.DeleteUser(AccountId) == 1) Notify.Show("Account deleted successfully!", "Operation Successful", AlertType.Success); else Notify.Show("Failed to remove account from database!", "Operation failed", AlertType.Warning); } this.Close(); } }
public AccountListForm() { InitializeComponent(); SortedCol = DataTable.Columns[0]; // Try to connect to the database try { using (GamespyDatabase Driver = new GamespyDatabase()) { } } catch (DbConnectException Ex) { ExceptionForm.ShowDbConnectError(Ex); Load += (s, e) => Close(); // Close form return; } // Setting the limit will build the inital list LimitSelect.SelectedIndex = 2; }
/// <summary> /// Updates the Users Country code when sent by the client /// </summary> /// <param name="recv">Array of information sent by the server</param> private void UpdateUser(Dictionary<string, string> Recv) { // Set clients country code try { using (GamespyDatabase Conn = new GamespyDatabase()) Conn.UpdateUser(PlayerNick, Recv["countrycode"]); } catch { //Dispose(); } }
/// <summary> /// Whenever the "newuser" command is recieved, this method is called to /// add the new users information into the database /// </summary> /// <param name="Recv">Array of parms sent by the server</param> private void CreateNewUser(Dictionary<string, string> Recv) { // Make sure the user doesnt exist already try { using (GamespyDatabase Database = new GamespyDatabase()) { // Check to see if user exists if (Database.UserExists(Recv["nick"])) { Stream.SendAsync(@"\error\\err\516\fatal\\errmsg\This account name is already in use!\id\1\final\"); Disconnect(5); return; } // We need to decode the Gamespy specific encoding for the password string Password = GamespyUtils.DecodePassword(Recv["passwordenc"]); string Cc = (RemoteEndPoint.AddressFamily == AddressFamily.InterNetwork) ? Ip2nation.GetCountryCode(RemoteEndPoint.Address) : Program.Config.ASP_LocalIpCountryCode; // Attempt to create account. If Pid is 0, then we couldnt create the account if ((PlayerId = Database.CreateUser(Recv["nick"], Password, Recv["email"], Cc)) == 0) { Stream.SendAsync(@"\error\\err\516\fatal\\errmsg\Error creating account!\id\1\final\"); Disconnect(6); return; } Stream.SendAsync(@"\nur\\userid\{0}\profileid\{0}\id\1\final\", PlayerId); } } catch(Exception e) { // Check for invalid query params if (e is KeyNotFoundException) { Stream.SendAsync(@"\error\\err\0\fatal\\errmsg\Invalid Query!\id\1\final\"); } else { Stream.SendAsync(@"\error\\err\516\fatal\\errmsg\Error creating account!\id\1\final\"); GpcmServer.Log("ERROR: [Gpcm.CreateNewUser] An error occured while trying to create a new User account :: " + e.Message); } Disconnect(7); return; } }
/// <summary> /// This method verifies the login information sent by /// the client, and returns encrypted data for the client /// to verify as well /// </summary> public void ProcessLogin(Dictionary<string, string> Recv) { // Make sure we have all the required data to process this login if (!Recv.ContainsKey("uniquenick") || !Recv.ContainsKey("challenge") || !Recv.ContainsKey("response")) { Stream.SendAsync(@"\error\\err\0\fatal\\errmsg\Invalid Query!\id\1\final\"); Disconnect(2); return; } // Warp this in a try/catch, incase database is offline or something try { using (GamespyDatabase Conn = new GamespyDatabase()) { // Try and fetch the user from the database Dictionary<string, object> User = Conn.GetUser(Recv["uniquenick"]); if (User == null) { Stream.SendAsync(@"\error\\err\265\fatal\\errmsg\The uniquenick provided is incorrect!\id\1\final\"); Disconnect(2); return; } // Set player variables PlayerId = Int32.Parse(User["id"].ToString()); PlayerNick = Recv["uniquenick"]; PlayerEmail = User["email"].ToString(); PlayerCountryCode = User["country"].ToString(); PasswordHash = User["password"].ToString(); // Use the GenerateProof method to compare with the "response" value. This validates the given password if (Recv["response"] == GenerateProof(Recv["challenge"], ServerChallengeKey)) { // Password is correct, Create session key and respond SessionKey = Crc.ComputeChecksum(PlayerNick); Stream.SendAsync( @"\lc\2\sesskey\{0}\proof\{1}\userid\{2}\profileid\{2}\uniquenick\{3}\lt\{4}__\id\1\final\", SessionKey, GenerateProof(ServerChallengeKey, Recv["challenge"]), // Do this again, Params are reversed! PlayerId, PlayerNick, GenerateRandomString(22) // Generate LT whatever that is (some sort of random string, 22 chars long) ); // Log, Update database, and call event GpcmServer.Log("Client Login: {0} - {1} - {2}", PlayerNick, PlayerId, RemoteEndPoint); Conn.Execute("UPDATE accounts SET lastip=@P0, session=@P1 WHERE id=@P2", RemoteEndPoint.Address, SessionKey, PlayerId); // Update status last, and call success login Status = LoginStatus.Completed; if (OnSuccessfulLogin != null) OnSuccessfulLogin(this); } else { // The proof string failed, so the password provided was incorrect GpcmServer.Log("Failed Login Attempt: {0} - {1} - {2}", PlayerNick, PlayerId, RemoteEndPoint); Stream.SendAsync(@"\error\\err\260\fatal\\errmsg\The password provided is incorrect.\id\1\final\"); Disconnect(3); } } } catch { Disconnect(4); return; } }
/// <summary> /// Logs the client out of the game client, and closes the stream /// </summary> /// <param name="code"> /// The disconnect code. If set to 9, the OnDisconect event will not be called, the database /// will not be updated to reset everyone's session code, and the EventArgs objects will NOT /// be returned to the IO pool. You should only set to 9 for a planned server shutdown. /// </param> /// <remarks> /// Codes: /// 0 => Client sends the "logout" command /// 1 => The login timer elapsed and the client wasnt logged in or this object was disposed, forcefully disconnected /// 2 => Invalid login query, or username was incorrect /// 3 => Incorrect Password /// 4 => An error occured while trying to login the client (could be database related) /// 5 => Cant create account, username exists already /// 6 => Error Creating new account in database /// 7 => Invalid query for account creation, or an exception was thrown while trying to create account /// 8 => Remote Connection closed the Stream or was un-readchable /// 9 => Forced server shutdown [No events called, database sessions are not updated, and EventArgs are disposed] /// </remarks> public void Disconnect(int code) { // Make sure we arent disposed if (Disposed) return; // Update database session if (Status == LoginStatus.Completed && code < 9) { try { using (GamespyDatabase Database = new GamespyDatabase()) Database.Execute("UPDATE accounts SET session=0 WHERE id=" + PlayerId); } catch { // We could be shutting this server down because of DB connection issues, don't do anything here. } } // Unregister for stream events and close the connection Stream.OnDisconnect -= Stream_OnDisconnect; Stream.DataReceived -= Stream_DataReceived; Stream.Close(code == 9); // Set status and log if (code == 1 && Status == LoginStatus.Processing) GpcmServer.Log("Login Timeout: {0} - {1} - {2}", PlayerNick, PlayerId, RemoteEndPoint); else if (Status != LoginStatus.Disconnected) GpcmServer.Log("Client Logout: {0} - {1} - {2}, Code={3}", PlayerNick, PlayerId, RemoteEndPoint, code); // Preapare to be unloaded from memory Status = LoginStatus.Disconnected; Disposed = true; // Call disconnect event if (OnDisconnect != null) OnDisconnect(this); }
/// <summary> /// Event fired when the next button is clicked /// </summary> private async void NextBtn_Click(object sender, EventArgs e) { // Disable this form this.Enabled = false; string Message1 = ""; // Initiate the Task Form if (TypeSelect.SelectedIndex == 1) { TaskForm.Show(this, "Create Database", "Connecting to MySQL Database...", false); Message1 = "Successfully Connected to MySQL Database! We will attempt to create the necessary tables into the specified database. Continue?"; } else { TaskForm.Show(this, "Create Database", "Creating SQLite Database...", false); Message1 = "Successfully Created the SQLite Database! We will attempt to create the necessary tables into the specified database. Continue?"; } // Temporarily set settings if (!SetConfigSettings()) { this.Enabled = true; TaskForm.CloseForm(); return; } // Try and install the SQL try { bool PreviousInstall = true; // Run in a seperate thread, dont wanna lock up the GUI thread await Task.Run(() => { // Switch mode if (DbMode == DatabaseMode.Stats) { // Open up the database connetion using (StatsDatabase Db = new StatsDatabase()) { // We only have work to do if the tables are not installed if (!Db.TablesExist) { PreviousInstall = false; // Verify that the user wants to install DB tables DialogResult Res = MessageBox.Show(Message1, "Verify Installation", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0x40000 // Force window on top ); // If we dont want to install tables, back out! if (Res == DialogResult.No) return; // Create our tables TaskForm.Progress.Report(new TaskProgressUpdate("Creating Stats Tables")); Db.CreateSqlTables(TaskForm.Progress); } } } else // Gamespy Mode { // Open up the database connetion using (GamespyDatabase Db = new GamespyDatabase()) { // We only have work to do if the tables are not installed if (!Db.TablesExist) { PreviousInstall = false; // Verify that the user wants to install DB tables DialogResult Res = MessageBox.Show(Message1, "Verify Installation", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0x40000 // Force window on top ); // If we dont want to install tables, back out! if (Res == DialogResult.No) return; // Create our tables TaskForm.Progress.Report(new TaskProgressUpdate("Creating Gamespy Tables")); Db.CreateSqlTables(); } } } }); // No errors, so save the config file Program.Config.Save(); // Close the task form TaskForm.CloseForm(); // Show Success Form if (!PreviousInstall) MessageBox.Show("Successfully installed the database tables!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0x40000 // Force window on top ); else MessageBox.Show( "We've detected that the database was already installed here. Your database settings have been saved and no further setup is required.", "Existing Installation Found", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0x40000 // Force window on top ); // Close this form, as we are done now this.Close(); } catch (Exception Ex) { // Close the task form and re-enable this form TaskForm.CloseForm(); this.Enabled = true; // Revert the temporary config settings and show the error to the user Program.Config.Reload(); MessageBox.Show(Ex.Message, "Database Installation Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0x40000 // Force window on top ); return; } finally { if (TaskForm.IsOpen) TaskForm.CloseForm(); this.Enabled = true; } }
/// <summary> /// This method is requested by the client when logging in to fetch all the account /// names that have the specified email address and password combination /// </summary> /// <param name="recvData"></param> private void SendNicks(Dictionary<string, string> recvData) { // Make sure we have the needed data if (!recvData.ContainsKey("email") || (!recvData.ContainsKey("pass") && !recvData.ContainsKey("passenc"))) { Stream.SendAsync(@"\error\\err\0\fatal\\errmsg\Invalid Query!\id\1\final\"); return; } // Try to get user data from database try { // Get our password from the provided query string password = (recvData.ContainsKey("pass")) ? recvData["pass"] : GamespyUtils.DecodePassword(recvData["passenc"]); // Fetch accounts using (GamespyDatabase Db = new GamespyDatabase()) { var Clients = Db.GetUsersByEmailPass(recvData["email"], password.GetMD5Hash(false)); StringBuilder Response = new StringBuilder(@"\nr\" + Clients.Count); for (int i = 0; i < Clients.Count; i++) Response.AppendFormat(@"\nick\{0}\uniquenick\{0}", Clients[i]["name"]); Response.Append(@"\ndone\\final\"); Stream.SendAsync(Response.ToString()); } } catch { Stream.SendAsync(@"\error\\err\551\fatal\\errmsg\Unable to get any associated profiles.\id\1\final\"); } }
/// <summary> /// Starts the Login Server listeners, and begins accepting new connections /// </summary> public static void Start() { // Make sure we arent already running! if (bIsRunning) return; // Start the DB Connection using (GamespyDatabase Database = new GamespyDatabase()) { // First, make sure our account table exists if (!Database.TablesExist) { string message = "In order to use the Gamespy Emulation feature of this program, we need to setup a database. " + "You may choose to do this later by clicking \"Cancel\". Would you like to setup the database now?"; DialogResult R = MessageBox.Show(message, "Gamespy Database Setup", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (R == DialogResult.Yes) SetupManager.ShowDatabaseSetupForm(DatabaseMode.Gamespy, MainForm.Instance); // Call the stoOnShutdown event to Re-enable the main forms buttons Stopped(); return; } else if (Database.NeedsUpdated) { // We cannot run an outdated database DialogResult R = MessageBox.Show( String.Format( "The Gamespy database tables needs to be updated to version {0} before using this feature. Would you like to do this now?", GamespyDatabase.LatestVersion ) + Environment.NewLine.Repeat(1) + "NOTE: You should backup your gamespy account table if you are unsure as this update cannot be undone!", "Gamespy Database Update", MessageBoxButtons.YesNo, MessageBoxIcon.Question ); // If the user doesnt migrate the database tables, quit if (R != DialogResult.Yes) { // Call the stoOnShutdown event to Re-enable the main forms buttons Stopped(); return; } // Do table migrations Database.MigrateTables(); } } // Bind gpcm server on port 29900 int port = 29900; // Setup the DebugLog DebugLog.LoggingEnabled = Program.Config.GamespyServerDebug; if (Program.Config.GamespyServerDebug) DebugLog.ClearLog(); try { // Begin logging DebugLog.Write("=== Gamespy Emulator Initializing ==="); DebugLog.Write("Starting Client Manager"); // Start the client manager ClientManager = new GpcmServer(); // Begin logging DebugLog.Write("Bound to TCP port: " + port); DebugLog.Write("Starting Account Service Provider"); // Start search provider server port++; SearchProvider = new GpspServer(); // Begin logging DebugLog.Write("Bound to TCP port: " + port); DebugLog.Write("Starting Master Server"); // Start then Master Server MasterServer = new MasterServer(ref port, DebugLog); // Start CDKey Server port = 29910; DebugLog.Write("Starting Cdkey Server"); CDKeyServer = new CDKeyServer(DebugLog); // Begin logging DebugLog.Write("=== Gamespy Emulator Initialized ==="); } catch (Exception E) { Notify.Show( "Failed to Start Gamespy Servers!", "Error binding to port " + port + ": " + Environment.NewLine + E.Message, AlertType.Warning ); // Append log if (DebugLog != null) { DebugLog.Write("=== Failed to Start Emulator Servers! ==="); DebugLog.Write("Error binding to port " + port + ": " + E.Message); } // Shutdown all started servers if (ClientManager != null && ClientManager.IsListening) ClientManager.Shutdown(); if (SearchProvider != null && SearchProvider.IsListening) SearchProvider.Shutdown(); if (MasterServer != null && MasterServer.IsRunning) MasterServer.Shutdown(); // Cdkey server must have throwm the exception at this point, since it starts last // Throw excpetion to parent throw; } // Let the client know we are ready for connections bIsRunning = true; Started(); }
/// <summary> /// Event fired when the Submit button is pushed /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void UpdateBtn_Click(object sender, EventArgs e) { int Pid = (int)PlayerID.Value; using (GamespyDatabase Database = new GamespyDatabase()) { // Make sure there is no empty fields! if (AccountNick.Text.Trim().Length < 3) { MessageBox.Show("Please enter a valid account name", "Error"); return; } else if (!Validator.IsValidEmail(AccountEmail.Text)) { MessageBox.Show("Please enter a valid account email", "Error"); return; } else if (Pid != AccountId) { if (!Validator.IsValidPID(Pid.ToString())) { MessageBox.Show("Invalid PID Format. A PID must be 8 or 9 digits in length", "Error"); return; } // Make sure the PID doesnt exist! else if (Database.UserExists(Pid)) { MessageBox.Show("Battlefield 2 PID is already taken. Please try a different PID.", "Error"); return; } } Database.UpdateUser(AccountId, Pid, AccountNick.Text, AccountPass.Text, AccountEmail.Text); } this.Close(); }
/// <summary> /// Shutsdown the ClientManager server and socket /// </summary> public void Shutdown() { // Stop accepting new connections base.IgnoreNewConnections = true; // Discard the poll timer PollTimer.Stop(); PollTimer.Dispose(); // Unregister events so we dont get a shit ton of calls GpcmClient.OnSuccessfulLogin -= GpcmClient_OnSuccessfulLogin; GpcmClient.OnDisconnect -= GpcmClient_OnDisconnect; // Disconnected all connected clients Parallel.ForEach(Clients.Values, client => client.Disconnect(9)); Parallel.ForEach(Processing.Values, client => client.Disconnect(9)); // Update the database try { // Set everyone's online session to 0 using (GamespyDatabase Conn = new GamespyDatabase()) Conn.Execute("UPDATE accounts SET session=0 WHERE session != 0"); } catch (Exception e) { Program.ErrorLog.Write("WARNING: [GpcmServer.Shutdown] Failed to update client database: " + e.Message); } // Update Connected Clients in the Database Processing.Clear(); Clients.Clear(); // Shutdown the listener socket base.ShutdownSocket(); // Tell the base to dispose all free objects base.Dispose(); }
/// <summary> /// Fills the DataGridView with a list of accounts /// </summary> private void BuildList() { // Define initial variables int Limit = Int32.Parse(LimitSelect.SelectedItem.ToString()); int Start = (ListPage == 1) ? 0 : (ListPage - 1) * Limit; string Like = SearchBox.Text.Replace("'", "").Trim(); WhereClause Where = null; // Build Query using (GamespyDatabase Driver = new GamespyDatabase()) { SelectQueryBuilder Query = new SelectQueryBuilder(Driver); Query.SelectColumns("id", "name", "email", "country", "lastip", "session"); Query.SelectFromTable("accounts"); Query.AddOrderBy(SortedCol.Name, ((SortDir == ListSortDirection.Ascending) ? Sorting.Ascending : Sorting.Descending)); Query.Limit(Limit, Start); // User entered search if (!String.IsNullOrWhiteSpace(Like)) Where = Query.AddWhere("name", Comparison.Like, "%" + Like + "%"); // Online Accounts if (OnlineAccountsCheckBox.Checked) { if (Where == null) Where = Query.AddWhere("session", Comparison.NotEqualTo, 0); else Where.AddClause(LogicOperator.And, "session", Comparison.NotEqualTo, 0); } // Clear out old junk DataTable.Rows.Clear(); // Add players to data grid int RowCount = 0; foreach (Dictionary<string, object> Row in Driver.QueryReader(Query.BuildCommand())) { DataTable.Rows.Add(new string[] { Row["id"].ToString(), Row["name"].ToString(), Row["email"].ToString(), Row["country"].ToString(), (Row["session"].ToString() != "0") ? "Yes" : "No", //(Gamespy.GamespyServer.IsPlayerConnected(Int32.Parse(Row["id"].ToString())) ? "Yes" : "No"), Row["lastip"].ToString(), }); RowCount++; } // Get Filtered Rows Query = new SelectQueryBuilder(Driver); Query.SelectCount(); Query.SelectFromTable("accounts"); if (Where != null) Query.AddWhere(Where); int TotalFilteredRows = Query.ExecuteScalar<int>(); // Get Total Player Count, if the Where clause is null, this will be the same as the Filtered Row Count int TotalRows = TotalFilteredRows; if (Where != null) { Query = new SelectQueryBuilder(Driver); Query.SelectCount(); Query.SelectFromTable("accounts"); TotalRows = Query.ExecuteScalar<int>(); } // Stop Count int Stop = (ListPage == 1) ? RowCount : ((ListPage - 1) * Limit) + RowCount; // First / Previous button if (ListPage == 1) { FirstBtn.Enabled = false; PreviousBtn.Enabled = false; } else { FirstBtn.Enabled = true; PreviousBtn.Enabled = true; } // Next / Last Button LastBtn.Enabled = false; NextBtn.Enabled = false; // Get total number of pages if (TotalFilteredRows / (ListPage * Limit) > 0) { float total = float.Parse(TotalFilteredRows.ToString()) / float.Parse(Limit.ToString()); TotalPages = Int32.Parse(Math.Floor(total).ToString()); if (TotalFilteredRows % Limit != 0) TotalPages++; LastBtn.Enabled = true; NextBtn.Enabled = true; } // Set page number PageNumber.Maximum = TotalPages; PageNumber.Value = ListPage; // Update Row Count Information RowCountDesc.Text = String.Format( "Showing {0} to {1} of {2} account{3}", ++Start, Stop, TotalFilteredRows, ((TotalFilteredRows > 1) ? "s " : " ") ); // Add Total row count if (!String.IsNullOrWhiteSpace(Like)) RowCountDesc.Text += String.Format("(filtered from " + TotalRows + " total account{0})", ((TotalRows > 1) ? "s" : "")); // Update DataTable.Update(); } }
private void CreateBtn_Click(object sender, EventArgs e) { int Pid = (int)PidBox.Value; using (GamespyDatabase Database = new GamespyDatabase()) { // Make sure there is no empty fields! if (AccountName.Text.Trim().Length < 3) { MessageBox.Show("Please enter a valid account name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } else if (AccountPass.Text.Trim().Length < 3) { MessageBox.Show("Please enter a valid account password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } else if (!Validator.IsValidEmail(AccountEmail.Text)) { MessageBox.Show("Please enter a valid account email", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } // Check if PID exists (for changing PID) if (PidSelect.SelectedIndex == 1) { if (!Validator.IsValidPID(Pid.ToString())) { MessageBox.Show("Invalid PID Format. A PID must be 8 or 9 digits in length", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } else if (Database.UserExists(Pid)) { MessageBox.Show("PID is already in use. Please enter a different PID.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } } // Check if the user exists if (Database.UserExists(AccountName.Text)) { MessageBox.Show("Account name is already in use. Please select a different Account Name.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } try { // Attempt to create the account if (PidSelect.SelectedIndex == 1) Database.CreateUser(Pid, AccountName.Text, AccountPass.Text, AccountEmail.Text, "00"); else Database.CreateUser(AccountName.Text, AccountPass.Text, AccountEmail.Text, "00"); Notify.Show("Account Created Successfully!", AccountName.Text, AlertType.Success); } catch (Exception E) { MessageBox.Show(E.Message, "Account Create Error"); } } this.DialogResult = DialogResult.OK; this.Close(); }
/// <summary> /// This is the primary method for fetching an accounts BF2 PID /// </summary> /// <param name="recvData"></param> private void SendCheck(Dictionary<string, string> recvData) { // Make sure we have the needed data if (!recvData.ContainsKey("nick")) { Stream.SendAsync(@"\error\\err\0\fatal\\errmsg\Invalid Query!\id\1\final\"); return; } // Try to get user data from database try { using (GamespyDatabase Db = new GamespyDatabase()) { int pid = Db.GetPlayerId(recvData["nick"]); if(pid == 0) Stream.SendAsync(@"\error\\err\265\fatal\\errmsg\Username [{0}] doesn't exist!\id\1\final\", recvData["nick"]); else Stream.SendAsync(@"\cur\0\pid\{0}\final\", pid); } } catch { Stream.SendAsync(@"\error\\err\265\fatal\\errmsg\Database service is Offline!\id\1\final\"); } }
/// <summary> /// Starts the Login Server listeners, and begins accepting new connections /// </summary> public static void Start() { // Make sure we arent already running! if (isRunning) return; // Start the DB Connection try { Database = new GamespyDatabase(); } catch (Exception E) { Notify.Show("Failed to Start Login Server!", E.Message, AlertType.Warning); throw E; } // Bind gpcm server on port 29900 try { CmServer = new GpcmServer(); } catch (Exception E) { Notify.Show( "Failed to Start Login Server!", "Error binding to port 29900: " + Environment.NewLine + E.Message, AlertType.Warning ); throw E; } // Bind gpsp server on port 29901 try { SpServer = new GpspServer(); } catch (Exception E) { Notify.Show( "Failed to Start Login Server!", "Error binding to port 29901: " + Environment.NewLine + E.Message, AlertType.Warning ); throw E; } // Let the client know we are ready for connections isRunning = true; OnStart(); }
/// <summary> /// Delete Account menu item click event /// </summary> private void menuItemDelete_Click(object sender, System.EventArgs e) { int Id = Int32.Parse(DataTable.SelectedRows[0].Cells[0].Value.ToString()); string Name = DataTable.SelectedRows[0].Cells[1].Value.ToString(); if (MessageBox.Show("Are you sure you want to delete account \"" + Name + "\"?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { using (GamespyDatabase Database = new GamespyDatabase()) { if (Database.DeleteUser(Id) == 1) Notify.Show("Account deleted successfully!", "Operation Successful", AlertType.Success); else Notify.Show("Failed to remove account from database!", "Operation Failed", AlertType.Warning); } BuildList(); } }