public void writeOwnertoSql() { SqlWrapper ms = new SqlWrapper(); ms.SqlInsert( "INSERT INTO " + this.GetSqlTablefromDynelType() + "owner VALUES (" + this.Id.ToString() + "," + this.Owner.Id.ToString() + ")"); }
// Save All Container Arrays To SQL void SaveToSQL(string tablename) { SqlWrapper sql = new SqlWrapper(); sql.SqlDelete("DELETE FROM " + tablename + " WHERE container=" + Type + " AND ID=" + Instance); for (int i = 0; i < Items.Length; i++) { if (Items[i] is ContainerEntry) { // Not instanced items first ContainerEntry ce = (ContainerEntry)Items[i]; sql.SqlInsert("INSERT INTO " + tablename + " (ID,Placement, flags, multiplecount, type,instance, lowid,highid, quality,nothing, container) VALUES (" + Instance + "," + i + "," + ce.Flags + "," + ce.Amount + ",0,0," + ce.LowID + "," + ce.HighID + "," + ce.QL + ",0," + Type + ")"); } else { // Do instanced items stuff here // insert into inventory table AND store item's stats } } }
/// <summary> /// Write uploaded nanos to database /// TODO: catch exceptions /// </summary> public void WriteUploadedNanosToSql() { lock (this.uploadedNanos) { foreach (AOUploadedNanos au in this.uploadedNanos) { SqlWrapper sqlWrapper = new SqlWrapper(); sqlWrapper.SqlInsert( "REPLACE INTO " + this.GetSqlTablefromDynelType() + "uploadednanos VALUES (" + this.Id.ToString() + "," + au.Nano.ToString() + ")"); } } }
/// <summary> /// Write waypoints to database /// TODO: catch exceptions, replace the string formats with something more convenient /// </summary> public void writeWaypointstoSql() { SqlWrapper ms = new SqlWrapper(); int count; ms.SqlDelete("DELETE FROM " + this.GetSqlTablefromDynelType() + "waypoints WHERE ID=" + this.Id.ToString()); for (count = 0; count < this.Waypoints.Count; count++) { ms.SqlInsert( "INSERT INTO " + this.GetSqlTablefromDynelType() + "waypoints VALUES (" + this.Id.ToString() + "," + this.PlayField.ToString() + "," + String.Format(CultureInfo.InvariantCulture, "'{0}'", this.Waypoints[count].x) + "," + String.Format(CultureInfo.InvariantCulture, "'{0}'", this.Waypoints[count].y) + "," + String.Format(CultureInfo.InvariantCulture, "'{0}'", this.Waypoints[count].z) + ")"); } if (this.Waypoints.Count > 0) { } }
/// <summary> /// Write socialtab contents to database /// TODO: catch exceptions /// </summary> public void SaveSocialTab() { lock (SocialTab) { // Note: Shouldermeshs still are same for left and right, subject to change in the future (as well as weaponmesh) SqlWrapper ms = new SqlWrapper(); ms.SqlInsert("REPLACE INTO socialtab VALUES (" + ID + ", " + (SocialTab.ContainsKey(0) ? SocialTab[0] : 0) + ", " + (SocialTab.ContainsKey(1) ? SocialTab[1] : 0) + ", " + (SocialTab.ContainsKey(2) ? SocialTab[2] : 0) + ", " + (SocialTab.ContainsKey(3) ? SocialTab[3] : 0) + ", " + (SocialTab.ContainsKey(4) ? SocialTab[4] : 0) + ", " + (SocialTab.ContainsKey(38) ? SocialTab[38] : 0) + ", " + (SocialTab.ContainsKey(1004) ? SocialTab[1004] : 0) + ", " + (SocialTab.ContainsKey(1005) ? SocialTab[1005] : 0) + ", " + (SocialTab.ContainsKey(64) ? SocialTab[64] : 0) + ", " + (SocialTab.ContainsKey(32) ? SocialTab[32] : 0) + ", " + (SocialTab.ContainsKey(1006) ? SocialTab[1006] : 0) + ", " + (SocialTab.ContainsKey(1007) ? SocialTab[1007] : 0) + ")"); } }
/// <summary> /// Write uploaded nanos to database /// TODO: catch exceptions /// </summary> public void writeUploadedNanostoSQL() { lock (UploadedNanos) { foreach (AOUploadedNanos au in UploadedNanos) { SqlWrapper Sql = new SqlWrapper(); Sql.SqlInsert("REPLACE INTO " + getSQLTablefromDynelType() + "uploadednanos VALUES (" + ID.ToString() + "," + au.Nano.ToString() + ")"); } } }
/// <summary> /// Write timers to database /// TODO: catch exceptions /// </summary> public void writeTimerstoSQL() { lock (Timers) { SqlWrapper ms = new SqlWrapper(); int count; // remove HP and NP tick count = Timers.Count; while (count > 0) { count--; if ((Timers[count].Strain == 0) || (Timers[count].Strain == 1)) { Timers.RemoveAt(count); } } ms.SqlDelete("DELETE FROM " + getSQLTablefromDynelType() + "timers WHERE ID=" + ID.ToString()); TimeSpan ts; DateTime n = DateTime.Now; for (count = 0; count < Timers.Count; count++) { ts = Timers[count].Timestamp - n; ms.SqlInsert("INSERT INTO " + getSQLTablefromDynelType() + "timers VALUES (" + ID.ToString() + "," + Timers[count].Strain + "," + Timers[count].Timestamp.Second.ToString() + ",X'" + Timers[count].Function.ToBlob() + "');"); } } }
public new void AddToDB() { SqlWrapper Sql = new SqlWrapper(); Sql.SqlInsert("INSERT INTO " + getSQLTablefromDynelType() + " (ID, Playfield) VALUES (" + ID.ToString() + "," + PlayField.ToString() + ")"); writeCoordinatestoSQL(); writeHeadingtoSQL(); Sql.SqlUpdate("UPDATE " + getSQLTablefromDynelType() + " SET TemplateID=" + TemplateID.ToString() + ", Hash='" + HASH + "' WHERE ID=" + ID.ToString() + " AND playfield=" + PlayField.ToString()); }
/// <summary> /// Check our tables and create/fill them if they don't exist /// </summary> public void CheckDBs() { SqlWrapper ms = new SqlWrapper(); List <string> tablelist = new List <string>(); List <string> tabletodo = new List <string>(); bool allok = true; // ToDo: check if database exists and create it if not (parsing the connection string) if (this.ismssql) { ms.SqlRead("SELECT table_name FROM INFORMATION_SCHEMA.TABLES;"); } else if (this.isnpgsql) { ms.SqlRead("SELECT table_name FROM information_schema.tables;"); } else if (this.ismysql) { ms.SqlRead("show Tables"); } if (ms.myreader.HasRows) { while (ms.myreader.Read()) { tablelist.Add(ms.myreader.GetString(0)); } } else { allok = false; } ms.sqlclose(); string[] sqlfiles = Directory.GetFiles("SQLTables"); bool isin; foreach (string s in sqlfiles) { isin = false; foreach (string table in tablelist) { if (s.ToLower() == Path.Combine("SQLTables", table + ".sql").ToLower()) { isin = true; break; } } if (!isin) { tabletodo.Add(s); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Table " + s + " doesn't exist."); allok = false; } } if (!allok) { Console.ForegroundColor = ConsoleColor.Red; Console.Write("SQL Tables are not complete. Should they be created? (Y/N) "); string answer = Console.ReadLine(); string sqlquery; if (answer.ToLower() == "y") { foreach (string todo in tabletodo) { long filesize = new FileInfo(todo).Length; Console.ForegroundColor = ConsoleColor.Green; Console.Write("Table " + todo.PadRight(67) + "[ 0%]"); if (filesize > 10000) { string[] queries = File.ReadAllLines(todo); int c = 0; sqlquery = string.Empty; string lastpercent = "0"; while (c < queries.Length) { if (queries[c].IndexOf("INSERT INTO") == -1) { sqlquery += queries[c] + "\n"; } else { c--; break; } c++; } ms.SqlInsert(sqlquery); c++; string buf1 = string.Empty; while (c < queries.Length) { if (queries[c].ToLower().Substring(0, 11) == "insert into") { break; } c++; } if (c < queries.Length) { buf1 = queries[c].Substring(0, queries[c].ToLower().IndexOf("values")); buf1 = buf1 + "VALUES "; StringBuilder Buffer = new StringBuilder(0, 1 * 1024 * 1024); while (c < queries.Length) { if (Buffer.Length == 0) { Buffer.Append(buf1); } string part = string.Empty; while (c < queries.Length) { if (queries[c].Trim() != string.Empty) { part = queries[c].Substring(queries[c].ToLower().IndexOf("values")); part = part.Substring(part.IndexOf("(")); // from '(' to end part = part.Substring(0, part.Length - 1); // Remove ';' if (Buffer.Length + 1 + part.Length > 1024 * 1000) { Buffer.Remove(Buffer.Length - 2, 2); Buffer.Append(";"); ms.SqlInsert(Buffer.ToString()); Buffer.Clear(); Buffer.Append(buf1); string lp2 = Convert.ToInt32(Math.Floor((double)c / queries.Length * 100)) .ToString(); if (lp2 != lastpercent) { Console.Write( "\rTable " + todo.PadRight(67) + "[" + lp2.PadLeft(3) + "%]"); lastpercent = lp2; } } Buffer.Append(part + ", "); } c++; } Buffer.Remove(Buffer.Length - 2, 2); Buffer.Append(";"); ms.SqlInsert(Buffer.ToString()); Buffer.Clear(); string lp = Convert.ToInt32(Math.Floor((double)c / queries.Length * 100)).ToString(); if (lp != lastpercent) { Console.Write("\rTable " + todo.PadRight(67) + "[" + lp.PadLeft(3) + "%]"); lastpercent = lp; } } } else { Console.Write("\rTable " + todo.PadRight(67) + "[100%]"); } } else { sqlquery = File.ReadAllText(todo); ms.SqlInsert(sqlquery); Console.Write("\rTable " + todo.PadRight(67) + "[100%]"); } Console.WriteLine(); } } } Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Database is fine."); }
/// <summary> /// /// </summary> /// <returns></returns> private Int32 CreateNewChar() { SqlWrapper ms = new SqlWrapper(); Int32 charID = 0; switch (this.Breed) { case 0x1: /* solitus */ this.Abis = new int[6] { 6, 6, 6, 6, 6, 6 }; break; case 0x2: /* opifex */ this.Abis = new int[6] { 3, 3, 10, 6, 6, 15 }; break; case 0x3: /* nanomage */ this.Abis = new int[6] { 3, 10, 6, 15, 3, 3 }; break; case 0x4: /* atrox */ this.Abis = new int[6] { 15, 3, 3, 3, 10, 6 }; break; default: Console.WriteLine("unknown breed: ", this.Breed); break; } /* * Note, all default values are not specified here as defaults are handled * in the CharacterStats Class for us automatically. Also minimises SQL * usage for default stats that are never changed from their default value * ~NV */ ms.SqlDelete("DELETE FROM `characters_stats` WHERE ID=" + charID); String sqlInsert = "INSERT INTO `characters` (`Username`,`Name`,`FirstName`,`LastName`,"; String sqlValues = "VALUES('" + this.AccountName + "','" + this.Name + "','','',"; sqlInsert += "`playfield`,`X`,`Y`,`Z`,`HeadingX`,`HeadingY`,`HeadingZ`,`HeadingW`)"; sqlValues += "0,0,0,0,0,0,0,0)"; sqlInsert += sqlValues; try { ms.SqlInsert(sqlInsert); } catch (Exception e) { Console.WriteLine(sqlInsert + e.Message); return 0; } try { /* select new char id */ string sqlQuery = "SELECT `ID` FROM `characters` WHERE Name = " + "'" + this.Name + "'"; DataTable dt = ms.ReadDatatable(sqlQuery); foreach (DataRow row in dt.Rows) { charID = (Int32)row[0]; } } catch (Exception e) { ms.sqlclose(); Console.WriteLine(this.Name + e.Message); return 0; } ms.SqlDelete("DELETE FROM `characters_stats` WHERE ID=" + charID); sqlInsert = "INSERT INTO `characters_stats` (`ID`, `Stat`, `Value`) VALUES "; // Flags / 0 (Player) sqlInsert += "(" + charID + ", 0, " + 20 + "),"; // Level / 54 sqlInsert += "(" + charID + ", 54, " + 1 + "),"; // HeadMesh / 64 sqlInsert += "(" + charID + ", 64, " + this.HeadMesh + "),"; // MonsterScale / 360 sqlInsert += "(" + charID + ", 360, " + this.MonsterScale + "),"; // Sex / 59 sqlInsert += "(" + charID + ", 59, " + this.Gender + "),"; // VisualSex / 369 sqlInsert += "(" + charID + ", 369, " + this.Gender + "),"; // Breed / 4 sqlInsert += "(" + charID + ", 4, " + this.Breed + "),"; // VisualBreed / 367 sqlInsert += "(" + charID + ", 367, " + this.Breed + "),"; // Profession / 60 sqlInsert += "(" + charID + ", 60, " + this.Profession + "),"; // VisualProfession / 368 sqlInsert += "(" + charID + ", 368, " + this.Profession + "),"; // Fatness / 47 sqlInsert += "(" + charID + ", 47, " + this.Fatness + "),"; // Strength / 16 sqlInsert += "(" + charID + ", 16, " + this.Abis[0] + "),"; // Psychic / 21 sqlInsert += "(" + charID + ", 21, " + this.Abis[1] + "),"; // Sense / 20 sqlInsert += "(" + charID + ", 20, " + this.Abis[2] + "),"; // Intelligence / 19 sqlInsert += "(" + charID + ", 19, " + this.Abis[3] + "),"; // Stamina / 18 sqlInsert += "(" + charID + ", 18, " + this.Abis[4] + "),"; // Agility / 17 sqlInsert += "(" + charID + ", 17, " + this.Abis[5] + "),"; // Set HP and NP auf 1 sqlInsert += "(" + charID + ",1,1),"; sqlInsert += "(" + charID + ",214,1);"; ms.SqlInsert(sqlInsert); return charID; }
public void writeWeaponpairstoSQL() { SqlWrapper Sql = new SqlWrapper(); Sql.SqlDelete("DELETE FROM " + getSQLTablefromDynelType() + "weaponpairs WHERE ID=" + ID.ToString() + " AND playfield=" + PlayField.ToString() + ";"); int c; for (c = 0; c < Weaponpairs.Count; c++) { Sql.SqlInsert("INSERT INTO " + getSQLTablefromDynelType() + "weaponpairs VALUES (" + ID.ToString() + "," + PlayField.ToString() + "," + Weaponpairs[c].value1.ToString() + "," + Weaponpairs[c].value2.ToString() + "," + Weaponpairs[c].value3.ToString() + "," + Weaponpairs[c].value4.ToString() + ");"); } }
public void writeWaypointstoSQL() { SqlWrapper ms = new SqlWrapper(); int count; ms.SqlDelete("DELETE FROM "+getSQLTablefromDynelType()+"waypoints WHERE ID="+ID.ToString()); for (count = 0; count < Waypoints.Count; count++) { ms.SqlInsert("INSERT INTO " + getSQLTablefromDynelType() + "waypoints VALUES (" + ID.ToString() + "," + PlayField.ToString() + "," + String.Format(System.Globalization.CultureInfo.InvariantCulture, "'{0}'", Waypoints[count].x) + "," + String.Format(System.Globalization.CultureInfo.InvariantCulture, "'{0}'", Waypoints[count].y) + "," + String.Format(System.Globalization.CultureInfo.InvariantCulture, "'{0}'", Waypoints[count].z) + ")"); } if (Waypoints.Count > 0) { } }
public void AddToDB() { SqlWrapper Sql = new SqlWrapper(); Sql.SqlInsert("INSERT INTO " + getSQLTablefromDynelType() + " (ID, Playfield) VALUES (" + ID.ToString() + "," + PlayField.ToString() + ")"); writeCoordinatestoSQL(); writeHeadingtoSQL(); writeMainStatstoSQL(); WriteStats(); writeInventorytoSQL(); writeNanostoSQL(); writeWaypointstoSQL(); writeWeaponpairstoSQL(); writeMeshstoSQL(); }
public void writeMeshstoSQL() { SqlWrapper Sql = new SqlWrapper(); Sql.SqlDelete("DELETE FROM " + getSQLTablefromDynelType() + "meshs WHERE ID=" + ID.ToString() + " AND playfield=" + PlayField.ToString()); int c; for (c = 0; c < Meshs.Count; c++) { Sql.SqlInsert("INSERT INTO " + getSQLTablefromDynelType() + "meshs VALUES (" + ID.ToString() + "," + PlayField.ToString() + "," + Meshs[c].Position.ToString() + "," + Meshs[c].Mesh.ToString() + "," + Meshs[c].OverrideTexture.ToString() + ")"); } }
/// <summary> /// Write newly created NPC to database /// </summary> public void AddToDB() { SqlWrapper Sql = new SqlWrapper(); Sql.SqlInsert( "INSERT INTO " + this.GetSqlTablefromDynelType() + " (ID, Playfield) VALUES (" + this.Id.ToString() + "," + this.PlayField.ToString() + ")"); this.WriteCoordinatesToSql(); this.WriteHeadingToSql(); this.writeMainStatstoSql(); this.WriteStats(); this.WriteInventoryToSql(); this.WriteNanosToSql(); this.writeWaypointstoSql(); this.WriteWeaponpairstoSql(); this.writeMeshstoSql(); }
/// <summary> /// Write bank contents to database /// TODO: catch exceptions /// </summary> public void WriteBankContentsToSql() { lock (this.bank) { SqlWrapper sqlWrapper = new SqlWrapper(); sqlWrapper.SqlDelete("DELETE FROM bank WHERE charID=" + this.Id.ToString()); foreach (AOItem item in this.bank) { string insert = "INSERT INTO bank VALUES(" + this.Id.ToString() + "," + item.Flags.ToString() + "," + item.LowID.ToString() + "," + item.HighID.ToString() + "," + item.MultipleCount.ToString() + "," + item.Quality.ToString() + "," + item.Type.ToString() + "," + item.Instance.ToString() + ",X'"; foreach (AOItemAttribute tempattr in item.Stats) { insert = insert + this.reverseString(tempattr.Stat.ToString("X8")) + this.reverseString(tempattr.Stat.ToString("X8")); } insert = insert + "');"; sqlWrapper.SqlInsert(insert); } } }
/// <summary> /// /// </summary> /// <param name="packet"></param> /// <param name="client"></param> public static void Read(byte[] packet, Client client) { PacketReader reader = new PacketReader(packet); Header header = reader.PopHeader(); reader.PopByte(); byte cmd = reader.PopByte(); Identity target = reader.PopIdentity(); int unknown = reader.PopInt(); string cmdStr = ""; byte CmdByte = 0; #region cmd args switch (cmd) { case 1: case 7: case 9: case 13: case 17: case 19: case 20: case 21: case 23: case 24: case 25: case 26: case 27: case 28: short cmdStrLen = reader.PopShort(); cmdStr = reader.PopString(cmdStrLen); break; case 10: CmdByte = reader.PopByte(); break; default: break; } reader.Finish(); #endregion SqlWrapper ms = new SqlWrapper(); DataTable dt; #region cmd handlers switch (cmd) { #region /org create <name> case 1: { // org create /* client wants to create organization * name of org is CmdStr */ string sqlQuery = "SELECT * FROM organizations WHERE Name='" + cmdStr + "'"; string guildName = null; uint orgID = 0; dt = ms.ReadDatatable(sqlQuery); if (dt.Rows.Count > 0) { guildName = (string)dt.Rows[0]["Name"]; } if (guildName == null) { client.SendChatText("You have created the guild: " + cmdStr); string currentDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); string sqlQuery2 = "INSERT INTO organizations (Name, creation, LeaderID, GovernmentForm) VALUES ('" + cmdStr + "', '" + currentDate + "', '" + client.Character.Id + "', '0')"; ms.SqlInsert(sqlQuery2); string sqlQuery3 = "SELECT * FROM organizations WHERE Name='" + cmdStr + "'"; dt = ms.ReadDatatable(sqlQuery3); if (dt.Rows.Count > 0) { orgID = (UInt32)dt.Rows[0]["ID"]; } // Make sure the order of these next two lines is not swapped -NV client.Character.Stats.ClanLevel.Set(0); client.Character.OrgId = orgID; break; } else { client.SendChatText("This guild already <font color=#DC143C>exists</font>"); break; } } #endregion #region /org ranks case 2: // org ranks //Displays Org Rank Structure. /* Select governingform from DB, Roll through display from GovForm */ if (client.Character.OrgId == 0) { client.SendChatText("You're not in an organization!"); break; } string ranksSql = "SELECT GovernmentForm FROM organizations WHERE ID = " + client.Character.OrgId; int governingForm = -1; dt = ms.ReadDatatable(ranksSql); if (dt.Rows.Count > 0) { governingForm = (Int32)dt.Rows[0]["GovernmentForm"]; } client.SendChatText("Current Rank Structure: " + GetRankList(governingForm)); break; #endregion #region /org contract case 3: // org contract break; #endregion #region unknown org command 4 case 4: Console.WriteLine("Case 4 Started"); break; #endregion #region /org info case 5: { Client tPlayer = null; if ((tPlayer = FindClient.FindClientById(target.Instance)) != null) { string orgDescription = "", orgObjective = "", orgHistory = "", orgLeaderName = ""; int orgGoverningForm = 0, orgLeaderID = 0; dt = ms.ReadDatatable("SELECT * FROM organizations WHERE ID=" + tPlayer.Character.OrgId); if (dt.Rows.Count > 0) { orgDescription = (string)dt.Rows[0]["Description"]; orgObjective = (string)dt.Rows[0]["Objective"]; orgHistory = (string)dt.Rows[0]["History"]; orgGoverningForm = (Int32)dt.Rows[0]["GovernmentForm"]; orgLeaderID = (Int32)dt.Rows[0]["LeaderID"]; } dt = ms.ReadDatatable("SELECT Name FROM characters WHERE ID=" + orgLeaderID); if (dt.Rows.Count > 0) { orgLeaderName = (string)dt.Rows[0][0]; } string textGovForm = null; if (orgGoverningForm == 0) { textGovForm = "Department"; } else if (orgGoverningForm == 1) { textGovForm = "Faction"; } else if (orgGoverningForm == 2) { textGovForm = "Republic"; } else if (orgGoverningForm == 3) { textGovForm = "Monarchy"; } else if (orgGoverningForm == 4) { textGovForm = "Anarchism"; } else if (orgGoverningForm == 5) { textGovForm = "Feudalism"; } else { textGovForm = "Department"; } string orgRank = GetRank(orgGoverningForm, tPlayer.Character.Stats.ClanLevel.StatBaseValue); PacketWriter packetWriter = new PacketWriter(); packetWriter.PushBytes(new byte[] { 0xDF, 0xDF }); packetWriter.PushShort(10); packetWriter.PushShort(1); packetWriter.PushShort(0); packetWriter.PushInt(3086); packetWriter.PushInt(client.Character.Id); packetWriter.PushInt(0x64582A07); packetWriter.PushIdentity(50000, tPlayer.Character.Id); packetWriter.PushByte(0); packetWriter.PushByte(2); // OrgServer case 0x02 (Org Info) packetWriter.PushInt(0); packetWriter.PushInt(0); packetWriter.PushInt(0xDEAA); // Type (org) packetWriter.PushUInt(tPlayer.Character.OrgId); // org ID packetWriter.PushShort((short)tPlayer.Character.OrgName.Length); packetWriter.PushBytes(Encoding.ASCII.GetBytes(tPlayer.Character.OrgName)); packetWriter.PushShort((short)orgDescription.Length); packetWriter.PushBytes(Encoding.ASCII.GetBytes(orgDescription)); packetWriter.PushShort((short)orgObjective.Length); packetWriter.PushBytes(Encoding.ASCII.GetBytes(orgObjective)); packetWriter.PushShort((short)orgHistory.Length); packetWriter.PushBytes(Encoding.ASCII.GetBytes(orgHistory)); packetWriter.PushShort((short)textGovForm.Length); packetWriter.PushBytes(Encoding.ASCII.GetBytes(textGovForm)); packetWriter.PushShort((short)orgLeaderName.Length); packetWriter.PushBytes(Encoding.ASCII.GetBytes(orgLeaderName)); packetWriter.PushShort((short)orgRank.Length); packetWriter.PushBytes(Encoding.ASCII.GetBytes(orgRank)); packetWriter.Push3F1Count(0); byte[] reply = packetWriter.Finish(); client.SendCompressed(reply); } } break; #endregion #region /org disband case 6: break; #endregion #region /org startvote <text> <duration> <entries> case 7: // org startvote <"text"> <duration(minutes)> <entries> // arguments (<text> <duration> and <entries>) are in CmdStr break; #endregion #region /org vote info case 8: // org vote info break; #endregion #region /org vote <entry> case 9: // <entry> is CmdStr break; #endregion #region /org promote case 10: { // some arg in CmdByte. No idea what it is //create the target namespace t_promote Client toPromote = null; string promoteSql = ""; int targetOldRank = -1; int targetNewRank = -1; int newPresRank = -1; int oldPresRank = 0; if ((toPromote = FindClient.FindClientById(target.Instance)) != null) { //First we check if target is in the same org as you if (toPromote.Character.OrgId != client.Character.OrgId) { //not in same org client.SendChatText("Target is not in your organization!"); break; } //Target is in same org, are you eligible to promote? Promoter Rank has to be TargetRank-2 or == 0 if ((client.Character.Stats.ClanLevel.Value == (toPromote.Character.Stats.ClanLevel.Value - 2)) || (client.Character.Stats.ClanLevel.Value == 0)) { //Promoter is eligible. Start the process //First we get the details about the org itself promoteSql = "SELECT * FROM organizations WHERE ID = " + client.Character.OrgId; dt = ms.ReadDatatable(promoteSql); int promoteGovForm = -1; string promotedToRank = ""; string demotedFromRank = ""; if (dt.Rows.Count > 0) { promoteGovForm = (Int32)dt.Rows[0]["GovernmentForm"]; } //Check if new rank == 0, if so, demote promoter if ((targetOldRank - 1) == 0) { /* This is a bit more complex. Here we need to promote new president first * then we go about demoting old president * finally we set the new leader in Sql * Reset OrgName to set changes */ // Set new President's Rank targetOldRank = toPromote.Character.Stats.ClanLevel.Value; targetNewRank = targetOldRank - 1; promotedToRank = GetRank(promoteGovForm, (uint)targetNewRank); toPromote.Character.Stats.ClanLevel.Set(targetNewRank); // Demote the old president oldPresRank = client.Character.Stats.ClanLevel.Value; newPresRank = oldPresRank + 1; demotedFromRank = GetRank(promoteGovForm, (uint)newPresRank); client.Character.Stats.ClanLevel.Set(newPresRank); //Change the leader id in Sql string newLeadSql = "UPDATE organizations SET LeaderID = " + toPromote.Character.Id + " WHERE ID = " + toPromote.Character.OrgId; ms.SqlUpdate(newLeadSql); client.SendChatText( "You've passed leadership of the organization to: " + toPromote.Character.Name); toPromote.SendChatText( "You've been promoted to the rank of " + promotedToRank + " by " + client.Character.Name); break; } else { //Just Promote targetOldRank = toPromote.Character.Stats.ClanLevel.Value; targetNewRank = targetOldRank - 1; promotedToRank = GetRank(promoteGovForm, (uint)targetNewRank); toPromote.Character.Stats.ClanLevel.Set(targetNewRank); client.SendChatText( "You've promoted " + toPromote.Character.Name + " to " + promotedToRank); toPromote.SendChatText( "You've been promoted to the rank of " + promotedToRank + " by " + client.Character.Name); } } else { //Promoter not eligible to promote client.SendChatText( "Your Rank is not high enough to promote " + toPromote.Character.Name); break; } } break; } #endregion #region /org demote case 11: // demote target player //create the target namespace t_demote Client toDemote = null; string demoteSql = ""; int targetCurRank = -1; int targetNewerRank = -1; if ((toDemote = FindClient.FindClientById(target.Instance)) != null) { //First we check if target is in the same org as you if (toDemote.Character.OrgId != client.Character.OrgId) { //not in same org client.SendChatText("Target is not in your organization!"); break; } //Target is in same org, are you eligible to demote? Promoter Rank has to be TargetRank-2 or == 0 if ((client.Character.Stats.GMLevel.Value == (toDemote.Character.Stats.ClanLevel.Value - 2)) || (client.Character.Stats.ClanLevel.Value == 0)) { //Promoter is eligible. Start the process //First we get the details about the org itself demoteSql = "SELECT GovernmentForm FROM organizations WHERE ID = " + client.Character.OrgId; dt = ms.ReadDatatable(demoteSql); int demoteGovForm = -1; string demotedToRank = ""; if (dt.Rows.Count > 0) { demoteGovForm = (Int32)dt.Rows[0]["GovernmentForm"]; } //Check whether new rank would be lower than lowest for current govform if ((targetCurRank + 1) > GetLowestRank(demoteGovForm)) { client.SendChatText("You can't demote character any lower!"); break; } targetCurRank = toDemote.Character.Stats.GMLevel.Value; targetNewerRank = targetCurRank + 1; demotedToRank = GetRank(demoteGovForm, (uint)targetNewerRank); toDemote.Character.Stats.ClanLevel.Set(targetNewerRank); client.SendChatText("You've demoted " + toDemote.Character.Name + " to " + demotedToRank); toDemote.SendChatText( "You've been demoted to the rank of " + demotedToRank + " by " + client.Character.Name); break; } else { //Promoter not eligible to promote client.SendChatText("Your Rank is not high enough to demote " + toDemote.Character.Name); break; } } break; #endregion #region unknown org command 12 case 12: Console.WriteLine("Case 12 Started"); break; #endregion #region /org kick <name> case 13: // kick <name> from org // <name> is CmdStr //create the t_player Client namespace, using CmdStr to find character id, in replacement of target.Instance uint kickedFrom = client.Character.OrgId; string kickeeSql = "SELECT * FROM characters WHERE Name = '" + cmdStr + "'"; int kickeeId = 0; dt = ms.ReadDatatable(kickeeSql); if (dt.Rows.Count > 0) { kickeeId = (Int32)dt.Rows[0]["ID"]; } Client targetPlayer = null; if ((targetPlayer = FindClient.FindClientById(kickeeId)) != null) { //Check if CmdStr is actually part of the org uint kickeeOrgId = targetPlayer.Character.OrgId; if (kickeeOrgId != client.Character.OrgId) { //Not part of Org. break out. client.SendChatText(cmdStr + "is not a member of your organization!"); break; } //They are part of the org, so begin the processing... //First we check if the player is online... string onlineSql = "SELECT online FROM characters WHERE ID = " + client.Character.Id; dt = ms.ReadDatatable(onlineSql); int onlineStatus = 0; if (dt.Rows.Count > 0) { onlineStatus = (Int32)dt.Rows[0][0]; } if (onlineStatus == 0) { //Player isn't online. Org Kicks are processed in a different method // TODO: Offline Org KICK break; } //Player is online. Start the kick. targetPlayer.Character.Stats.ClanLevel.Set(0); targetPlayer.Character.OrgId = 0; string kickedFromSql = "SELECT Name FROM organizations WHERE ID = " + client.Character.OrgId; dt = ms.ReadDatatable(kickedFromSql); string kickedFromName = ""; if (dt.Rows.Count > 0) { kickedFromName = (string)dt.Rows[0][0]; } targetPlayer.SendChatText("You've been kicked from the organization " + kickedFromName); } // TODO: Offline Org KICK break; #endregion #region /org invite case 14: { Client tPlayer = null; if ((tPlayer = FindClient.FindClientById(target.Instance)) != null) { PacketWriter writer = new PacketWriter(); writer.PushBytes(new byte[] { 0xDF, 0xDF }); writer.PushShort(10); writer.PushShort(1); writer.PushShort(0); writer.PushInt(3086); //Sender writer.PushInt(tPlayer.Character.Id); //Receiver writer.PushInt(0x64582A07); //Packet ID writer.PushIdentity(50000, tPlayer.Character.Id); //Target Identity writer.PushByte(0); writer.PushByte(5); //OrgServer Case 0x05 (Invite) writer.PushInt(0); writer.PushInt(0); writer.PushIdentity(0xDEAA, (int)client.Character.OrgId); // Type (org) writer.PushShort((short)client.Character.OrgName.Length); writer.PushBytes(Encoding.ASCII.GetBytes(client.Character.OrgName)); writer.PushInt(0); byte[] reply = writer.Finish(); tPlayer.SendCompressed(reply); } } break; #endregion #region Org Join case 15: { //target.Instance holds the OrgID of the Org wishing to be joined. int orgIdtoJoin = target.Instance; string JoinSql = "SELECT * FROM organizations WHERE ID = '" + orgIdtoJoin + "' LIMIT 1"; int gov_form = 0; dt = ms.ReadDatatable(JoinSql); if (dt.Rows.Count > 0) { gov_form = (Int32)dt.Rows[0]["GovernmentForm"]; } // Make sure the order of these next two lines is not swapped -NV client.Character.Stats.ClanLevel.Set(GetLowestRank(gov_form)); client.Character.OrgId = (uint)orgIdtoJoin; } break; #endregion #region /org leave case 16: // org leave // TODO: Disband org if it was leader that left org. -Suiv- // I don't think a Disband happens if leader leaves. I don't think leader -can- leave without passing lead to another // Something worth testing on Testlive perhaps ~Chaz // Just because something happens on TL, doesnt mean its a good idea. Really tbh id prefer it if you had to explicitly type /org disband to disband rather than /org leave doing it... -NV // Agreeing with NV. Org Leader can't leave without passing lead on. org disband requires /org disband to specifically be issued, with a Yes/No box. string LeaveSql = "SELECT * FROM organizations WHERE ID = " + client.Character.OrgId; int govern_form = 0; dt = ms.ReadDatatable(LeaveSql); if (dt.Rows.Count > 0) { govern_form = (Int32)dt.Rows[0]["GovernmentForm"]; } if ((client.Character.Stats.ClanLevel.Value == 0) && (govern_form != 4)) { client.SendChatText( "Organization Leader cannot leave organization without Disbanding or Passing Leadership!"); } else { client.Character.OrgId = 0; client.SendChatText("You left the guild"); } break; #endregion #region /org tax | /org tax <tax> case 17: // gets or sets org tax // <tax> is CmdStr // if no <tax>, then just send chat text with current tax info if (cmdStr == null) { client.SendChatText("The current organization tax rate is: "); break; } else { break; } #endregion #region /org bank case 18: { // org bank dt = ms.ReadDatatable("SELECT * FROM organizations WHERE ID=" + client.Character.OrgId); if (dt.Rows.Count > 0) { UInt64 bank_credits = (UInt64)dt.Rows[0]["Bank"]; client.SendChatText("Your bank has " + bank_credits + " credits in its account"); } } break; #endregion #region /org bank add <cash> case 19: { if (client.Character.OrgId == 0) { client.SendChatText("You are not in an organisation."); break; } // org bank add <cash> int minuscredits_fromplayer = Convert.ToInt32(cmdStr); int characters_credits = client.Character.Stats.Cash.Value; if (characters_credits < minuscredits_fromplayer) { client.SendChatText("You do not have enough Credits"); } else { int total_Creditsspent = characters_credits - minuscredits_fromplayer; client.Character.Stats.Cash.Set(total_Creditsspent); ms.SqlUpdate( "UPDATE `organizations` SET `Bank` = `Bank` + " + minuscredits_fromplayer + " WHERE `ID` = " + client.Character.OrgId); client.SendChatText("You have donated " + minuscredits_fromplayer + " to the organization"); } } break; #endregion #region /org bank remove <cash> case 20: // org bank remove <cash> // <cash> is CmdStr // player wants to take credits from org bank // only leader can do that if ((client.Character.Stats.ClanLevel.Value != 0) || (client.Character.OrgId == 0)) { client.SendChatText("You're not the leader of an Organization"); break; } int removeCredits = Convert.ToInt32(cmdStr); long orgBank = 0; dt = ms.ReadDatatable("SELECT Bank FROM organizations WHERE ID = " + client.Character.OrgId); if (dt.Rows.Count > 0) { orgBank = (Int64)dt.Rows[0][0]; } if (removeCredits > orgBank) { client.SendChatText("Not enough credits in Organization Bank!"); break; } else { long neworgbank = orgBank - removeCredits; int existingcreds = 0; existingcreds = client.Character.Stats.Cash.Value; int newcreds = existingcreds + removeCredits; ms.SqlUpdate( "UPDATE organizations SET Bank = " + neworgbank + " WHERE ID = " + client.Character.OrgId); client.Character.Stats.Cash.Set(newcreds); client.SendChatText("You've removed " + removeCredits + " credits from the organization bank"); } break; #endregion #region /org bank paymembers <cash> case 21: // <cash> is CmdStr // give <cash> credits to every org member // credits are taken from org bank // only leader can do it break; #endregion #region /org debt case 22: // send player text about how big is his/her tax debt to org break; #endregion #region /org history <text> case 23: { if (client.Character.Stats.ClanLevel.Value == 0) { // org history <history text> ms.SqlUpdate( "UPDATE organizations SET history = '" + cmdStr + "' WHERE ID = '" + client.Character.OrgId + "'"); client.SendChatText("History Updated"); } else { client.SendChatText("You must be the Organization Leader to perform this command!"); } } break; #endregion #region /org objective <text> case 24: { if (client.Character.Stats.ClanLevel.Value == 0) { // org objective <objective text> ms.SqlUpdate( "UPDATE organizations SET objective = '" + cmdStr + "' WHERE ID = '" + client.Character.OrgId + "'"); client.SendChatText("Objective Updated"); } else { client.SendChatText("You must be the Organization Leader to perform this command!"); } } break; #endregion #region /org description <text> case 25: { if (client.Character.Stats.ClanLevel.Value == 0) { // org description <description text> ms.SqlUpdate( "UPDATE organizations SET description = '" + cmdStr + "' WHERE ID = '" + client.Character.OrgId + "'"); client.SendChatText("Description Updated"); } else { client.SendChatText("You must be the Organization Leader to perform this command!"); } } break; #endregion #region /org name <text> case 26: { // org name <name> /* Renames Organization * Checks for Existing Orgs with similar name to stop crash * Chaz */ if (client.Character.Stats.ClanLevel.Value == 0) { string SqlQuery26 = "SELECT * FROM organizations WHERE Name LIKE '" + cmdStr + "' LIMIT 1"; string CurrentOrg = null; dt = ms.ReadDatatable(SqlQuery26); if (dt.Rows.Count > 0) { CurrentOrg = (string)dt.Rows[0]["Name"]; } if (CurrentOrg == null) { string SqlQuery27 = "UPDATE organizations SET Name = '" + cmdStr + "' WHERE ID = '" + client.Character.OrgId + "'"; ms.SqlUpdate(SqlQuery27); client.SendChatText("Organization Name Changed to: " + cmdStr); // Forces reloading of org name and the like // XXXX TODO: Make it reload for all other members in the org client.Character.OrgId = client.Character.OrgId; break; } else { client.SendChatText("An Organization already exists with that name"); break; } } else { client.SendChatText("You must be the organization leader to perform this command!"); } break; } #endregion #region /org governingform <text> case 27: { // org governingform <form> /* Current Governing Forms: * Department, Faction, Republic, Monarchy, Anarchism, Feudalism */ //Check on whether your President or not if (client.Character.Stats.ClanLevel.Value == 0) { //first we drop the case on the input, just to be sure. Int32 GovFormNum = -1; if (cmdStr == null) { //list gov forms client.SendChatText( "List of Accepted Governing Forms is: department, faction, republic, monarchy, anarchism, feudalism"); break; } //was correct input passed? switch (cmdStr.ToLower()) { case "department": GovFormNum = 0; break; case "faction": GovFormNum = 1; break; case "republic": GovFormNum = 2; break; case "monarchy": GovFormNum = 3; break; case "anarchism": GovFormNum = 4; break; case "feudalism": GovFormNum = 5; break; default: client.SendChatText(cmdStr + " Is an invalid Governing Form!"); client.SendChatText( "Accepted Governing Forms are: department, faction, republic, monarchy, anarchism, feudalism"); break; } if (GovFormNum != -1) { ms.SqlUpdate( "UPDATE organizations SET GovernmentForm = '" + GovFormNum + "' WHERE ID = '" + client.Character.OrgId + "'"); foreach (int currentCharId in OrgMisc.GetOrgMembers(client.Character.OrgId, true)) { client.Character.Stats.ClanLevel.Set(GetLowestRank(GovFormNum)); } client.SendChatText("Governing Form is now: " + cmdStr); break; } } else { //Haha! You're not the org leader! client.SendChatText("You must be the Org Leader to perform this command"); break; } } break; #endregion #region /org stopvote <text> case 28: // <text> is CmdStr break; #endregion #region unknown command default: break; #endregion } #endregion reader.Finish(); }
public new void AddToDB() { SqlWrapper sqlWrapper = new SqlWrapper(); // Fix from Moin, thx sqlWrapper.SqlInsert( "INSERT INTO " + this.GetSqlTablefromDynelType() + " (ID, Playfield, TemplateID, Hash) VALUES (" + this.Id.ToString() + "," + this.PlayField.ToString() + "," + this.TemplateId.ToString() + ",'" + this.Hash + "')"); this.WriteCoordinatesToSql(); this.WriteHeadingToSql(); }
/// <summary> /// Write timers to database /// TODO: catch exceptions /// </summary> public void WriteTimersToSql() { lock (this.timers) { SqlWrapper ms = new SqlWrapper(); int count; // remove HP and NP tick count = this.timers.Count; while (count > 0) { count--; if ((this.timers[count].Strain == 0) || (this.timers[count].Strain == 1)) { this.timers.RemoveAt(count); } } ms.SqlDelete("DELETE FROM " + this.GetSqlTablefromDynelType() + "timers WHERE ID=" + this.Id.ToString()); TimeSpan ts; DateTime n = DateTime.Now; for (count = 0; count < this.timers.Count; count++) { ts = this.timers[count].Timestamp - n; ms.SqlInsert( "INSERT INTO " + this.GetSqlTablefromDynelType() + "timers VALUES (" + this.Id.ToString() + "," + this.timers[count].Strain + "," + this.timers[count].Timestamp.Second.ToString() + ",X'" + this.timers[count].Function.Serialize() + "');"); } } }
/// <summary> /// Write nanos to database /// TODO: catch exceptions /// </summary> public void writeNanostoSQL() { lock (ActiveNanos) { SqlWrapper ms = new SqlWrapper(); int count; ms.SqlDelete("DELETE FROM " + getSQLTablefromDynelType() + "activenanos WHERE ID=" + ID.ToString()); for (count = 0; count < ActiveNanos.Count; count++) { ms.SqlInsert("INSERT INTO " + getSQLTablefromDynelType() + "activenanos VALUES (" + ID.ToString() + "," + ActiveNanos[count].ID.ToString() + "," + ActiveNanos[count].NanoStrain.ToString() + ")"); } } }
/// <summary> /// Check our tables and create/fill them if they don't exist /// </summary> public void CheckDBs() { SqlWrapper ms = new SqlWrapper(); List<string> tablelist = new List<string>(); List<string> tabletodo = new List<string>(); bool allok = true; // ToDo: check if database exists and create it if not (parsing the connection string) if (this.ismssql) { ms.SqlRead("SELECT table_name FROM INFORMATION_SCHEMA.TABLES;"); } else if (this.isnpgsql) { ms.SqlRead("SELECT table_name FROM information_schema.tables;"); } else if (this.ismysql) { ms.SqlRead("show Tables"); } if (ms.myreader.HasRows) { while (ms.myreader.Read()) { tablelist.Add(ms.myreader.GetString(0)); } } else { allok = false; } ms.sqlclose(); string[] sqlfiles = Directory.GetFiles("SQLTables"); bool isin; foreach (string s in sqlfiles) { isin = false; foreach (string table in tablelist) { if (s.ToLower() == Path.Combine("SQLTables", table + ".sql").ToLower()) { isin = true; break; } } if (!isin) { tabletodo.Add(s); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Table " + s + " doesn't exist."); allok = false; } } if (!allok) { Console.ForegroundColor = ConsoleColor.Red; Console.Write("SQL Tables are not complete. Should they be created? (Y/N) "); string answer = Console.ReadLine(); string sqlquery; if (answer.ToLower() == "y") { foreach (string todo in tabletodo) { long filesize = new FileInfo(todo).Length; Console.ForegroundColor = ConsoleColor.Green; Console.Write("Table " + todo.PadRight(67) + "[ 0%]"); if (filesize > 10000) { string[] queries = File.ReadAllLines(todo); int c = 0; sqlquery = string.Empty; string lastpercent = "0"; while (c < queries.Length) { if (queries[c].IndexOf("INSERT INTO") == -1) { sqlquery += queries[c] + "\n"; } else { c--; break; } c++; } ms.SqlInsert(sqlquery); c++; string buf1 = string.Empty; while (c < queries.Length) { if (queries[c].ToLower().Substring(0, 11) == "insert into") { break; } c++; } if (c < queries.Length) { buf1 = queries[c].Substring(0, queries[c].ToLower().IndexOf("values")); buf1 = buf1 + "VALUES "; StringBuilder Buffer = new StringBuilder(0, 1 * 1024 * 1024); while (c < queries.Length) { if (Buffer.Length == 0) { Buffer.Append(buf1); } string part = string.Empty; while (c < queries.Length) { if (queries[c].Trim() != string.Empty) { part = queries[c].Substring(queries[c].ToLower().IndexOf("values")); part = part.Substring(part.IndexOf("(")); // from '(' to end part = part.Substring(0, part.Length - 1); // Remove ';' if (Buffer.Length + 1 + part.Length > 1024 * 1000) { Buffer.Remove(Buffer.Length - 2, 2); Buffer.Append(";"); ms.SqlInsert(Buffer.ToString()); Buffer.Clear(); Buffer.Append(buf1); string lp2 = Convert.ToInt32(Math.Floor((double)c / queries.Length * 100)) .ToString(); if (lp2 != lastpercent) { Console.Write( "\rTable " + todo.PadRight(67) + "[" + lp2.PadLeft(3) + "%]"); lastpercent = lp2; } } Buffer.Append(part + ", "); } c++; } Buffer.Remove(Buffer.Length - 2, 2); Buffer.Append(";"); ms.SqlInsert(Buffer.ToString()); Buffer.Clear(); string lp = Convert.ToInt32(Math.Floor((double)c / queries.Length * 100)).ToString(); if (lp != lastpercent) { Console.Write("\rTable " + todo.PadRight(67) + "[" + lp.PadLeft(3) + "%]"); lastpercent = lp; } } } else { Console.Write("\rTable " + todo.PadRight(67) + "[100%]"); } } else { sqlquery = File.ReadAllText(todo); ms.SqlInsert(sqlquery); Console.Write("\rTable " + todo.PadRight(67) + "[100%]"); } Console.WriteLine(); } } } Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Database is fine."); }
/// <summary> /// Write bank contents to database /// TODO: catch exceptions /// </summary> public void writeBankContentstoSQL() { SqlWrapper ms = new SqlWrapper(); ms.SqlDelete("DELETE FROM bank WHERE charID=" + ID.ToString()); foreach (AOItem temp in Bank) { string insert = "INSERT INTO bank VALUES(" + ID.ToString() + "," + temp.flags.ToString() + "," + temp.lowID.ToString() + "," + temp.highID.ToString() + "," + temp.multiplecount.ToString() + "," + temp.Quality.ToString() + "," + temp.Type.ToString() + "," + temp.Instance.ToString() + ",X'"; foreach (AOItemAttribute tempattr in temp.Stats) { insert = insert + reverseString(tempattr.Stat.ToString("X8")) + reverseString(tempattr.Stat.ToString("X8")); } insert = insert + "');"; ms.SqlInsert(insert); } }
private static void Main(string[] args) { #region Console Texts... Console.Title = "CellAO " + AssemblyInfoclass.Title + " Console. Version: " + AssemblyInfoclass.Description + " " + AssemblyInfoclass.AssemblyVersion + " " + AssemblyInfoclass.Trademark; ConsoleText ct = new ConsoleText(); ct.TextRead("main.txt"); Console.WriteLine("Loading " + AssemblyInfoclass.Title + "..."); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("[OK]"); Console.ResetColor(); #endregion //Sying helped figure all this code out, about 5 yearts ago! :P bool processedargs = false; loginLoginServer = new LoginServer(); loginLoginServer.EnableTCP = true; loginLoginServer.EnableUDP = false; try { loginLoginServer.TcpIP = IPAddress.Parse(Config.Instance.CurrentConfig.ListenIP); } catch { ct.TextRead("ip_config_parse_error.txt"); Console.ReadKey(); return; } loginLoginServer.TcpPort = Convert.ToInt32(Config.Instance.CurrentConfig.LoginPort); #region NLog LoggingConfiguration config = new LoggingConfiguration(); ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget(); consoleTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}"; FileTarget fileTarget = new FileTarget(); config.AddTarget("file", fileTarget); fileTarget.FileName = "${basedir}/LoginEngineLog.txt"; fileTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}"; LoggingRule rule1 = new LoggingRule("*", LogLevel.Trace, consoleTarget); config.LoggingRules.Add(rule1); LoggingRule rule2 = new LoggingRule("*", LogLevel.Trace, fileTarget); config.LoggingRules.Add(rule2); LogManager.Configuration = config; #endregion #region NBug SettingsOverride.LoadCustomSettings("NBug.LoginEngine.Config"); NBug.Settings.WriteLogToDisk = true; AppDomain.CurrentDomain.UnhandledException += Handler.UnhandledException; TaskScheduler.UnobservedTaskException += Handler.UnobservedTaskException; //TODO: ADD More Handlers. #endregion loginLoginServer.MaximumPendingConnections = 100; #region Console Commands //Andyzweb: Added checks for start and stop //also added a running command to return status of the server //and added Console.Write("\nServer Command >>"); to login server string consoleCommand; ct.TextRead("login_consolecommands.txt"); while (true) { if (!processedargs) { if (args.Length == 1) { if (args[0].ToLower() == "/autostart") { ct.TextRead("autostart.txt"); ThreadMgr.Start(); loginLoginServer.Start(); } } processedargs = true; } Console.Write("\nServer Command >>"); consoleCommand = Console.ReadLine(); string temp = ""; while (temp != consoleCommand) { temp = consoleCommand; consoleCommand = consoleCommand.Replace(" ", " "); } consoleCommand = consoleCommand.Trim(); switch (consoleCommand.ToLower()) { case "start": if (loginLoginServer.Running) { Console.ForegroundColor = ConsoleColor.Red; ct.TextRead("loginisrunning.txt"); Console.ResetColor(); break; } ThreadMgr.Start(); loginLoginServer.Start(); break; case "stop": if (!loginLoginServer.Running) { Console.ForegroundColor = ConsoleColor.Red; ct.TextRead("loginisnotrunning.txt"); Console.ResetColor(); break; } ThreadMgr.Stop(); loginLoginServer.Stop(); break; case "exit": Process.GetCurrentProcess().Kill(); break; case "running": if (loginLoginServer.Running) { //Console.WriteLine("Login Server is running"); ct.TextRead("loginisrunning.txt"); break; } //Console.WriteLine("Login Server not running"); ct.TextRead("loginisnotrunning.txt"); break; #region Help Commands.... case "help": ct.TextRead("logincmdhelp.txt"); break; case "help start": ct.TextRead("helpstart.txt"); break; case "help exit": ct.TextRead("helpstop.txt"); break; case "help running": ct.TextRead("loginhelpcmdrunning.txt"); break; case "help Adduser": ct.TextRead("logincmdadduserhelp.txt"); break; case "help setpass": ct.TextRead("logincmdhelpsetpass.txt"); break; #endregion default: #region Adduser //This section handles the command for adding a user to the database if (consoleCommand.ToLower().StartsWith("adduser")) { string[] parts = consoleCommand.Split(' '); if (parts.Length < 9) { Console.WriteLine( "Invalid command syntax.\nPlease use:\nAdduser <username> <password> <number of characters> <expansion> <gm level> <email> <FirstName> <LastName>"); break; } string username = parts[1]; string password = parts[2]; int numChars = 0; try { numChars = int.Parse(parts[3]); } catch { Console.WriteLine("Error: <number of characters> must be a number (duh!)"); break; } int expansions = 0; try { expansions = int.Parse(parts[4]); } catch { Console.WriteLine("Error: <expansions> must be a number between 0 and 2047!"); break; } if (expansions < 0 || expansions > 2047) { Console.WriteLine("Error: <expansions> must be a number between 0 and 2047!"); break; } int gm = 0; try { gm = int.Parse(parts[5]); } catch { Console.WriteLine("Error: <GM Level> must be number (duh!)"); break; } string email = parts[6]; if (email == null) { email = String.Empty; } if (!TestEmailRegex(email)) { Console.WriteLine("Error: <Email> You must supply an email address for this account"); break; } string firstname = parts[7]; try { if (firstname == null) { throw new ArgumentNullException(); } } catch { Console.WriteLine("Error: <FirstName> You must supply a first name for this accout"); break; } string lastname = parts[8]; try { if (lastname == null) { throw new ArgumentNullException(); } } catch { Console.WriteLine("Error: <LastName> You must supply a last name for this account"); break; } const string FormatString = "INSERT INTO `login` (`CreationDate`, `Flags`,`AccountFlags`,`Username`,`Password`,`Allowed_Characters`,`Expansions`, `GM`, `Email`, `FirstName`, `LastName`) VALUES " + "(NOW(), '0', '0', '{0}', '{1}', {2}, {3}, {4}, '{5}', '{6}', '{7}');"; LoginEncryption le = new LoginEncryption(); string hashedPassword = le.GeneratePasswordHash(password); string sql = String.Format( FormatString, username, hashedPassword, numChars, expansions, gm, email, firstname, lastname); SqlWrapper sqlWrapper = new SqlWrapper(); try { sqlWrapper.SqlInsert(sql); } catch (MySqlException ex) { switch (ex.Number) { case 1062: //duplicate entry for key Console.WriteLine("A user account with this username already exists."); break; default: Console.WriteLine( "An error occured while trying to add a new user account:\n{0}", ex.Message); break; } break; } Console.WriteLine("User added successfully."); break; } #endregion #region Hashpass //This function just hashes the string you enter using the loginencryption method if (consoleCommand.ToLower().StartsWith("hash")) { string Syntax = "The Syntax for this command is \"hash <String to hash>\" alphanumeric no spaces"; string[] parts = consoleCommand.Split(' '); if (parts.Length != 2) { Console.WriteLine(Syntax); break; } string pass = parts[1]; LoginEncryption le = new LoginEncryption(); string hashed = le.GeneratePasswordHash(pass); Console.WriteLine(hashed); break; } #endregion #region setpass //sets the password for the given username //Added by Andyzweb //Still TODO add exception and error handling if (consoleCommand.ToLower().StartsWith("setpass")) { string Syntax = "The syntax for this command is \"setpass <account username> <newpass>\" where newpass is alpha numeric no spaces"; string[] parts = consoleCommand.Split(' '); if (parts.Length != 3) { Console.WriteLine(Syntax); break; } string username = parts[1]; string newpass = parts[2]; LoginEncryption le = new LoginEncryption(); string hashed = le.GeneratePasswordHash(newpass); string formatString; formatString = "UPDATE `login` SET Password = '******' WHERE login.Username = '******'"; string sql = String.Format(formatString, hashed, username); SqlWrapper updt = new SqlWrapper(); try { updt.SqlUpdate(sql); } //yeah this part here, some kind of exception handling for mysql errors catch { } } #endregion ct.TextRead("login_consolecmdsdefault.txt"); break; } } #endregion }
/// <summary> /// Write inventory to database /// TODO: catch exceptions /// </summary> public void writeInventorytoSQL() { lock (Inventory) { SqlWrapper ms = new SqlWrapper(); int count; ms.SqlDelete("DELETE FROM " + getSQLTablefromDynelType() + "inventory WHERE ID=" + ID.ToString() + " AND container=104;"); for (count = 0; count < Inventory.Count; count++) { if (Inventory[count].Container != -1) // dont save possible trade leftovers { ms.SqlInsert("INSERT INTO " + getSQLTablefromDynelType() + "inventory (ID,placement,flags,multiplecount,lowid,highid,quality,container) values (" + ID.ToString() + "," + Inventory[count].Placement.ToString() + ",1," + Inventory[count].Item.multiplecount.ToString() + "," + Inventory[count].Item.lowID.ToString() + "," + Inventory[count].Item.highID.ToString() + "," + Inventory[count].Item.Quality.ToString() + ",104);"); } } } }
/// <summary> /// Write nanos to database /// TODO: catch exceptions /// </summary> public void WriteNanosToSql() { lock (this.activeNanos) { SqlWrapper sqlWrapper = new SqlWrapper(); int count; sqlWrapper.SqlDelete( "DELETE FROM " + this.GetSqlTablefromDynelType() + "activenanos WHERE ID=" + this.Id.ToString()); for (count = 0; count < this.activeNanos.Count; count++) { sqlWrapper.SqlInsert( "INSERT INTO " + this.GetSqlTablefromDynelType() + "activenanos VALUES (" + this.Id.ToString() + "," + this.activeNanos[count].ID.ToString() + "," + this.activeNanos[count].NanoStrain.ToString() + ")"); } } }
/// <summary> /// Write Stat to Sql /// </summary> public void WriteStatToSql(bool doit) { if (this.DoNotDontWriteToSql) { return; } int id = this.parent.Id; SqlWrapper sql = new SqlWrapper(); if (doit) { if (this.parent is NonPlayerCharacterClass) { sql.SqlInsert( "INSERT INTO " + (this.parent).GetSqlTablefromDynelType() + "_stats (ID, Playfield, Stat, Value) VALUES (" + id + "," + this.parent.PlayField + "," + this.StatNumber + "," + ((Int32)this.StatBaseValue) + ") ON DUPLICATE KEY UPDATE Value=" + ((Int32)this.StatBaseValue) + ";"); } else { sql.SqlInsert( "INSERT INTO " + (this.parent).GetSqlTablefromDynelType() + "_stats (ID, Stat, Value) VALUES (" + id + "," + this.StatNumber + "," + ((Int32)this.StatBaseValue) + ") ON DUPLICATE KEY UPDATE Value=" + ((Int32)this.StatBaseValue) + ";"); } } }
static void Main(string[] args) { #region Console Texts... Console.Title = "CellAO " + AssemblyInfoclass.Title + " Console. Version: " + AssemblyInfoclass.Description + " " + AssemblyInfoclass.AssemblyVersion; ConsoleText ct = new ConsoleText(); ct.TextRead("main.txt"); Console.WriteLine("Loading " + AssemblyInfoclass.Title + "..."); if (ismodified()) { Console.WriteLine("Your " + AssemblyInfoclass.Title + " was compiled from modified source code."); } else if (ismixed()) { Console.WriteLine("Your " + AssemblyInfoclass.Title + " uses mixed SVN revisions."); } Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("[OK]"); Console.ResetColor(); #endregion //Sying helped figure all this code out, about 5 yearts ago! :P bool processedargs = false; LoginServer = new Server(); LoginServer.EnableTCP = true; LoginServer.EnableUDP = false; try { LoginServer.TcpIP = IPAddress.Parse(ConfigReadWrite.Instance.CurrentConfig.ListenIP); } catch { ct.TextRead("ip_config_parse_error.txt"); Console.ReadKey(); return; } LoginServer.TcpPort = Convert.ToInt32(ConfigReadWrite.Instance.CurrentConfig.LoginPort); #region NLog LoggingConfiguration config = new LoggingConfiguration(); ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget(); consoleTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}"; FileTarget fileTarget = new FileTarget(); config.AddTarget("file", fileTarget); fileTarget.FileName = "${basedir}/LoginEngineLog.txt"; fileTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}"; LoggingRule rule1 = new LoggingRule("*", LogLevel.Trace, consoleTarget); config.LoggingRules.Add(rule1); LoggingRule rule2 = new LoggingRule("*", LogLevel.Trace, fileTarget); config.LoggingRules.Add(rule2); LogManager.Configuration = config; #endregion LoginServer.MaximumPendingConnections = 100; #region Console Commands //Andyzweb: Added checks for start and stop //also added a running command to return status of the server //and added Console.Write("\nServer Command >>"); to login server string consoleCommand; ct.TextRead("login_consolecommands.txt"); while (true) { if (!processedargs) { if (args.Length == 1) { if (args[0].ToLower() == "/autostart") { ct.TextRead("autostart.txt"); ThreadMgr.Start(); LoginServer.Start(); } } processedargs = true; } Console.Write("\nServer Command >>"); consoleCommand = Console.ReadLine(); string temp = ""; while (temp != consoleCommand) { temp = consoleCommand; consoleCommand = consoleCommand.Replace(" ", " "); } consoleCommand = consoleCommand.Trim(); switch (consoleCommand.ToLower()) { case "start": if (LoginServer.Running) { Console.ForegroundColor = ConsoleColor.Red; ct.TextRead("loginisrunning.txt"); Console.ResetColor(); break; } ThreadMgr.Start(); LoginServer.Start(); break; case "stop": if (!LoginServer.Running) { Console.ForegroundColor = ConsoleColor.Red; ct.TextRead("loginisnotrunning.txt"); Console.ResetColor(); break; } ThreadMgr.Stop(); LoginServer.Stop(); break; case "exit": Process.GetCurrentProcess().Kill(); break; case "running": if (LoginServer.Running) { //Console.WriteLine("Login Server is running"); ct.TextRead("loginisrunning.txt"); break; } //Console.WriteLine("Login Server not running"); ct.TextRead("loginisnotrunning.txt"); break; #region Help Commands.... case "help": ct.TextRead("logincmdhelp.txt"); break; case "help start": ct.TextRead("helpstart.txt"); break; case "help exit": ct.TextRead("helpstop.txt"); break; case "help running": ct.TextRead("loginhelpcmdrunning.txt"); break; case "help Adduser": ct.TextRead("logincmdadduserhelp.txt"); break; case "help setpass": ct.TextRead("logincmdhelpsetpass.txt"); break; #endregion default: #region Adduser //This section handles the command for adding a user to the database if (consoleCommand.ToLower().StartsWith("adduser")) { string[] parts = consoleCommand.Split(' '); if (parts.Length < 9) { Console.WriteLine("Invalid command syntax.\nPlease use:\nAdduser <username> <password> <number of characters> <expansion> <gm level> <email> <FirstName> <LastName>"); break; } string username = parts[1]; string password = parts[2]; int numChars = 0; try { numChars = int.Parse(parts[3]); } catch { Console.WriteLine("Error: <number of characters> must be a number (duh!)"); break; } int expansions = 0; try { expansions = int.Parse(parts[4]); if (expansions < 0 || expansions > 2047) { throw new Exception(); } } catch { Console.WriteLine("Error: <expansions> must be a number between 0 and 2047!"); break; } int gm = 0; try { gm = int.Parse(parts[5]); } catch { Console.WriteLine("Error: <GM Level> must be number (duh!)"); break; } string email = parts[6].ToString(); try { if (email == null) { throw new Exception(); } } catch { Console.WriteLine("Error: <Email> You must supply an email address for this account"); break; } string firstname = parts[7].ToString(); try { if (firstname == null) { throw new Exception(); } } catch { Console.WriteLine("Error: <FirstName> You must supply a first name for this accout"); break; } string lastname = parts[8].ToString(); try { if (lastname == null) { throw new Exception(); } } catch { Console.WriteLine("Error: <LastName> You must supply a last name for this account"); break; } string formatString; formatString = "INSERT INTO `login` (`CreationDate`, `Flags`,`AccountFlags`,`Username`,`Password`,`Allowed_Characters`,`Expansions`, `GM`, `Email`, `FirstName`, `LastName`) VALUES " + "(NOW(), '0', '0', '{0}', '{1}', {2}, {3}, {4}, '{5}', '{6}', '{7}');"; LoginEncryption le = new LoginEncryption(); string hashedPassword = le.GeneratePasswordHash(password); string sql = String.Format(formatString, username, hashedPassword, numChars, expansions, gm, email, firstname, lastname); AO.Core.SqlWrapper wrp = new AO.Core.SqlWrapper(); try { wrp.SqlInsert(sql); } catch (MySql.Data.MySqlClient.MySqlException ex) { switch (ex.Number) { case 1062: //duplicate entry for key Console.WriteLine("A user account with this username already exists."); break; default: Console.WriteLine("An error occured while trying to add a new user account:\n{0}", ex.Message); break; } break; } Console.WriteLine("User added successfully."); break; } #endregion #region Hashpass //This function just hashes the string you enter using the loginencryption method if (consoleCommand.ToLower().StartsWith("hash")) { string Syntax = "The Syntax for this command is \"hash <String to hash>\" alphanumeric no spaces"; string[] parts = consoleCommand.Split(' '); if (parts.Length != 2) { Console.WriteLine(Syntax); break; } string pass = parts[1]; LoginEncryption le = new LoginEncryption(); string hashed = le.GeneratePasswordHash(pass); Console.WriteLine(hashed); break; } #endregion #region setpass //sets the password for the given username //Added by Andyzweb //Still TODO add exception and error handling if (consoleCommand.ToLower().StartsWith("setpass")) { string Syntax = "The syntax for this command is \"setpass <account username> <newpass>\" where newpass is alpha numeric no spaces"; string[] parts = consoleCommand.Split(' '); if (parts.Length != 3) { Console.WriteLine(Syntax); break; } string username = parts[1]; string newpass = parts[2]; LoginEncryption le = new LoginEncryption(); string hashed = le.GeneratePasswordHash(newpass); string formatString; formatString = "UPDATE `login` SET Password = '******' WHERE login.Username = '******'"; string sql = String.Format(formatString, hashed, username); AO.Core.SqlWrapper updt = new AO.Core.SqlWrapper(); try { updt.SqlUpdate(sql); } //yeah this part here, some kind of exception handling for mysql errors catch { } } #endregion ct.TextRead("login_consolecmdsdefault.txt"); break; } } #endregion }