Repository: mm201/pkmn-classic-framework Branch: master Commit: b7759e7a6bd3 Files: 314 Total size: 2.5 MB Directory structure: gitextract_fpvand7g/ ├── .gitignore ├── .gitmodules ├── GlobalTerminalService/ │ ├── GTServer4.cs │ ├── GTServer5.cs │ ├── GTServerBase.cs │ ├── GlobalTerminalService.csproj │ ├── Program.cs │ ├── ProjectInstaller.Designer.cs │ ├── ProjectInstaller.cs │ ├── ProjectInstaller.resx │ ├── Properties/ │ │ └── AssemblyInfo.cs │ ├── Service1.Designer.cs │ ├── Service1.cs │ ├── Service1.resx │ ├── app.config │ └── cert.pfx ├── LICENSE.md ├── MakeBaseStatTables/ │ ├── MakeBaseStatTables.csproj │ ├── Program.cs │ ├── Properties/ │ │ └── AssemblyInfo.cs │ ├── app.config │ └── packages.config ├── README.md ├── RenameImages/ │ ├── App.config │ ├── Program.cs │ ├── Properties/ │ │ └── AssemblyInfo.cs │ └── RenameImages.csproj ├── Roadmap.md ├── VeekunImport/ │ ├── Program.cs │ ├── Properties/ │ │ └── AssemblyInfo.cs │ ├── VeekunImport.csproj │ ├── app.config │ ├── countries4.txt │ ├── countries5.txt │ ├── families.txt │ ├── families_map.txt │ ├── form_abilities3.txt │ ├── form_abilities4.txt │ ├── form_abilities5.txt │ ├── form_abilities6.txt │ ├── form_stats1.txt │ ├── form_stats2.txt │ ├── form_stats3.txt │ ├── form_stats4.txt │ ├── form_stats5.txt │ ├── form_stats6.txt │ ├── form_values.txt │ ├── items3.txt │ ├── items4.txt │ ├── items5.txt │ ├── items_balls.txt │ ├── packages.config │ ├── regions.txt │ ├── ribbon_positions3.txt │ ├── ribbon_positions4.txt │ ├── ribbon_positions5.txt │ └── ribbons.txt ├── bvCrawler4/ │ ├── App.config │ ├── Program.cs │ ├── Properties/ │ │ └── AssemblyInfo.cs │ ├── bvCrawler4.csproj │ └── packages.config ├── bvCrawler5/ │ ├── App.config │ ├── Program.cs │ ├── Properties/ │ │ └── AssemblyInfo.cs │ ├── bvCrawler5.csproj │ └── packages.config ├── bvRestorer4/ │ ├── App.config │ ├── Program.cs │ ├── Properties/ │ │ └── AssemblyInfo.cs │ └── bvRestorer4.csproj ├── bvRestorer5/ │ ├── App.config │ ├── Program.cs │ ├── Properties/ │ │ └── AssemblyInfo.cs │ └── bvRestorer5.csproj ├── gfx/ │ ├── 2014 design/ │ │ ├── fGTS colour blending.psd │ │ ├── heading-backdrop.psd │ │ ├── headinglogo.psd │ │ ├── logo-colour.psd │ │ └── logov3.psd │ └── 2023 design/ │ ├── Discord Icon Pride.afdesign │ ├── Discord Icon.afdesign │ ├── Logo.afdesign │ ├── Temp placeholder background.afdesign │ └── Touch Icon.afdesign ├── gts/ │ ├── Global.asax │ ├── Global.asax.cs │ ├── Properties/ │ │ ├── AssemblyInfo.cs │ │ └── PublishProfiles/ │ │ ├── Local IIS.pubxml │ │ └── Public.pubxml │ ├── Web.Public.config │ ├── Web.config │ ├── admin/ │ │ ├── Sessions.aspx │ │ ├── Sessions.aspx.cs │ │ ├── Sessions.aspx.designer.cs │ │ ├── Web.Debug.config │ │ ├── Web.Release.config │ │ └── Web.config │ ├── gts.csproj │ ├── masters/ │ │ ├── MasterPage.master │ │ ├── MasterPage.master.cs │ │ └── MasterPage.master.designer.cs │ ├── pgl.ashx │ ├── pgl.ashx.cs │ ├── pkvldtprod.ashx │ ├── pkvldtprod.ashx.cs │ ├── pokemondpds.ashx │ ├── pokemondpds.ashx.cs │ ├── pokemondpds_web.ashx │ ├── pokemondpds_web.ashx.cs │ ├── src/ │ │ ├── AppStateHelper.cs │ │ ├── BanHelper.cs │ │ ├── FakeOpponentGenerator.cs │ │ └── IpAddressHelper.cs │ ├── syachi2ds.ashx │ └── syachi2ds.ashx.cs ├── library/ │ ├── Data/ │ │ ├── DataMysql.cs │ │ ├── DataSqlite.cs │ │ ├── Database.cs │ │ ├── DatabaseExtender.cs │ │ ├── MySqlDatabaseExtender.cs │ │ └── SqlDatabaseExtender.cs │ ├── Library.csproj │ ├── Pokedex/ │ │ ├── Ability.cs │ │ ├── Evolution.cs │ │ ├── Family.cs │ │ ├── Form.cs │ │ ├── FormAbilities.cs │ │ ├── FormStats.cs │ │ ├── Item.cs │ │ ├── Location.cs │ │ ├── Move.cs │ │ ├── Pokedex.cs │ │ ├── PokedexRecordBase.cs │ │ ├── Region.cs │ │ ├── Ribbon.cs │ │ ├── Species.cs │ │ └── Type.cs │ ├── Properties/ │ │ └── AssemblyInfo.cs │ ├── Structures/ │ │ ├── ByteStatValues.cs │ │ ├── ContestStatValues.cs │ │ ├── Enums.cs │ │ ├── Format.cs │ │ ├── IntStatValues.cs │ │ ├── IvStatValues.cs │ │ ├── MoveSlot.cs │ │ ├── Pokemon4.cs │ │ ├── Pokemon5.cs │ │ ├── PokemonBase.cs │ │ ├── PokemonParty4.cs │ │ ├── PokemonParty5.cs │ │ ├── PokemonPartyBase.cs │ │ ├── StatValues.cs │ │ ├── StatValuesBase.cs │ │ └── TrainerMemo.cs │ ├── Support/ │ │ ├── AliasTable.cs │ │ ├── AssertHelper.cs │ │ ├── BinarySerializableBase.cs │ │ ├── EncodedString4.cs │ │ ├── EncodedString5.cs │ │ ├── EncodedStringBase.cs │ │ ├── EnumerableExtender.cs │ │ ├── GameSyncUtils.cs │ │ ├── Indexer1d.cs │ │ ├── LazyKeyValuePair.cs │ │ ├── LocalizedString.cs │ │ ├── LogHelper.cs │ │ ├── StreamExtender.cs │ │ ├── StringHelper.cs │ │ ├── TrendyPhrase4.cs │ │ ├── TrendyPhrase5.cs │ │ ├── TrendyPhraseBase.cs │ │ └── ValidationSummary.cs │ ├── Wfc/ │ │ ├── BanStatus.cs │ │ ├── BattleSubwayPokemon5.cs │ │ ├── BattleSubwayProfile5.cs │ │ ├── BattleSubwayRecord5.cs │ │ ├── BattleTowerPokemon4.cs │ │ ├── BattleTowerPokemonBase.cs │ │ ├── BattleTowerProfile4.cs │ │ ├── BattleTowerProfileBase.cs │ │ ├── BattleTowerRecord4.cs │ │ ├── BattleTowerRecordBase.cs │ │ ├── BattleVideoHeader4.cs │ │ ├── BattleVideoHeader5.cs │ │ ├── BattleVideoRecord4.cs │ │ ├── BattleVideoRecord5.cs │ │ ├── BoxRecord4.cs │ │ ├── DressupRecord4.cs │ │ ├── GtsRecord4.cs │ │ ├── GtsRecord5.cs │ │ ├── GtsRecordBase.cs │ │ ├── MusicalRecord5.cs │ │ ├── PlazaQuestionnaire.cs │ │ ├── PlazaSchedule.cs │ │ ├── TrainerProfile4.cs │ │ ├── TrainerProfile5.cs │ │ ├── TrainerProfileBase.cs │ │ ├── TrainerProfilePlaza.cs │ │ ├── TrainerRankings.cs │ │ └── VipRecord.cs │ ├── app.config │ ├── database.sql │ ├── lib/ │ │ ├── SQLite.Designer.pdb │ │ ├── SQLite.Designer.xml │ │ ├── System.Data.SQLite.Linq.pdb │ │ ├── System.Data.SQLite.Linq.xml │ │ ├── System.Data.SQLite.dll.config │ │ ├── System.Data.SQLite.pdb │ │ └── System.Data.SQLite.xml │ └── packages.config ├── pkmn-classic-framework.sln ├── pokedex/ │ └── Shiny lock generations.txt ├── towerRestorer4/ │ ├── App.config │ ├── Program.cs │ ├── Properties/ │ │ └── AssemblyInfo.cs │ └── towerRestorer.csproj └── web/ ├── Default.aspx ├── Default.aspx.cs ├── Default.aspx.designer.cs ├── Global.asax ├── Global.asax.cs ├── Properties/ │ ├── AssemblyInfo.cs │ └── PublishProfiles/ │ └── Public.pubxml ├── RoomLeaders.aspx ├── RoomLeaders.aspx.cs ├── RoomLeaders.aspx.designer.cs ├── Web.Public.config ├── Web.config ├── admin/ │ ├── AddBoxes.aspx │ ├── AddBoxes.aspx.cs │ ├── AddBoxes.aspx.designer.cs │ ├── AddDressup.aspx │ ├── AddDressup.aspx.cs │ ├── AddDressup.aspx.designer.cs │ ├── AddMusical.aspx │ ├── AddMusical.aspx.cs │ ├── AddMusical.aspx.designer.cs │ ├── Web.Debug.config │ ├── Web.Release.config │ └── Web.config ├── battlevideo/ │ ├── Default.aspx │ ├── Default.aspx.cs │ └── Default.aspx.designer.cs ├── controls/ │ ├── DnsAddress.ascx │ ├── DnsAddress.ascx.cs │ ├── DnsAddress.ascx.designer.cs │ ├── ForeignLookup.ascx │ ├── ForeignLookup.ascx.cs │ ├── ForeignLookup.ascx.designer.cs │ ├── LabelTextBox.ascx │ ├── LabelTextBox.ascx.cs │ ├── LabelTextBox.ascx.designer.cs │ ├── PokemonPicker.ascx │ ├── PokemonPicker.ascx.cs │ ├── PokemonPicker.ascx.designer.cs │ ├── PokemonSource.ashx │ └── PokemonSource.ashx.cs ├── css/ │ ├── form.css │ ├── login.css │ ├── main.css │ ├── pkmnstats.css │ └── types.css ├── gts/ │ ├── Default.aspx │ ├── Default.aspx.cs │ ├── Default.aspx.designer.cs │ ├── Pokemon.aspx │ ├── Pokemon.aspx.cs │ └── Pokemon.aspx.designer.cs ├── masters/ │ ├── LeftColumn.master │ ├── LeftColumn.master.cs │ ├── LeftColumn.master.designer.cs │ ├── MasterPage.master │ ├── MasterPage.master.cs │ ├── MasterPage.master.designer.cs │ ├── ThreeColumn.master │ ├── ThreeColumn.master.cs │ └── ThreeColumn.master.designer.cs ├── packages.config ├── scripts/ │ ├── form.js │ └── retina.js ├── src/ │ ├── AppStateHelper.cs │ ├── Common.cs │ ├── DependencyNode.cs │ ├── ForeignLookupSource.cs │ ├── HeaderColour.cs │ ├── OnceTemplate.cs │ ├── RequireCss.cs │ ├── RequireLinkBase.cs │ ├── RequireScript.cs │ ├── RetinaImage.cs │ ├── RetinaImageBase.cs │ ├── WebException.cs │ └── WebFormat.cs ├── test/ │ ├── BoxUp.aspx │ ├── BoxUp.aspx.cs │ ├── BoxUp.aspx.designer.cs │ ├── Decode.aspx │ ├── Decode.aspx.cs │ ├── Decode.aspx.designer.cs │ ├── Gsid.aspx │ ├── Gsid.aspx.cs │ ├── Gsid.aspx.designer.cs │ ├── NameDecode.aspx │ ├── NameDecode.aspx.cs │ ├── NameDecode.aspx.designer.cs │ ├── NameEncode.aspx │ ├── NameEncode.aspx.cs │ ├── NameEncode.aspx.designer.cs │ ├── VideoId.aspx │ ├── VideoId.aspx.cs │ ├── VideoId.aspx.designer.cs │ └── Web.config └── web.csproj ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ [Tt]humbs.db *.suo *.csproj.user *.pubxml.user [Dd]ebug/ [Rr]elease/ [Bb]in/ [Pp]ackages/ .DS_Store ._.DS_Store ._* .vs/ ================================================ FILE: .gitmodules ================================================ [submodule "GamestatsBase"] path = GamestatsBase url = git@github.com:mm201/GamestatsBase.git branch = master ================================================ FILE: GlobalTerminalService/GTServer4.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using PkmnFoundations.Support; using PkmnFoundations.Structures; using PkmnFoundations.Data; using System.Net.Sockets; using System.Diagnostics; using PkmnFoundations.Wfc; namespace PkmnFoundations.GlobalTerminalService { public class GTServer4 : GTServerBase { public GTServer4() : base(12400, false) { Initialize(); } public GTServer4(int threads) : base(12400, false, threads) { Initialize(); } public GTServer4(int threads, int timeout) : base(12400, false, threads, timeout) { Initialize(); } private void Initialize() { } protected override byte[] ProcessRequest(byte[] data, TcpClient c) { int length = BitConverter.ToInt32(data, 0); AssertHelper.Equals(length, data.Length); RequestTypes4 requestType = (RequestTypes4)data[4]; StringBuilder logEntry = new StringBuilder(); logEntry.AppendFormat("Handling Generation IV {0} request.\nHost: {1}", requestType, c.Client.RemoteEndPoint); logEntry.AppendLine(); EventLogEntryType type = EventLogEntryType.Information; CryptMessage(data); MemoryStream response = new MemoryStream(); response.Write(new byte[] { 0x00, 0x00, 0x00, 0x00 }, 0, 4); // placeholder for length response.WriteByte((byte)requestType); response.WriteByte(data[5]); try { int pid = BitConverter.ToInt32(data, 8); byte version = data[0x0c]; byte language = data[0x0d]; logEntry.AppendFormat("pid: {0}", pid); logEntry.AppendLine(); switch (requestType) { #region Box upload case RequestTypes4.BoxUpload: { if (data.Length != 0x360) { logEntry.AppendLine("Length did not validate."); type = EventLogEntryType.FailureAudit; response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } BoxLabels4 label = (BoxLabels4)BitConverter.ToInt32(data, 0x140); byte[] boxData = new byte[0x21c]; Array.Copy(data, 0x144, boxData, 0, 0x21c); BoxRecord4 record = new BoxRecord4(pid, label, 0, boxData); ulong serial = Database.Instance.BoxUpload4(record); if (serial == 0) { logEntry.AppendLine("Uploaded box already in server."); response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } logEntry.AppendFormat("Box {0} uploaded successfully.", serial); logEntry.AppendLine(); response.Write(new byte[] { 0x00, 0x00 }, 0, 2); // result code (0 for OK) response.Write(BitConverter.GetBytes(serial), 0, 8); } break; case RequestTypes4.BoxSearch: { if (data.Length != 0x14c) { logEntry.AppendLine("Length did not validate."); type = EventLogEntryType.FailureAudit; response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } // todo: validate or log some of this? BoxLabels4 label = (BoxLabels4)BitConverter.ToInt32(data, 0x144); logEntry.AppendFormat("Searching for {0} boxes.", label); logEntry.AppendLine(); BoxRecord4[] results = Database.Instance.BoxSearch4(label, 20); response.Write(new byte[] { 0x00, 0x00 }, 0, 2); // result code (0 for OK) response.Write(BitConverter.GetBytes(results.Length), 0, 4); foreach (BoxRecord4 result in results) { response.Write(BitConverter.GetBytes(result.PID), 0, 4); response.Write(BitConverter.GetBytes((int)result.Label), 0, 4); response.Write(BitConverter.GetBytes(result.SerialNumber), 0, 8); // xxx: this may throw if there's database corruption response.Write(result.Data, 0, 0x21c); } logEntry.AppendFormat("Retrieved {0} boxes.", results.Length); logEntry.AppendLine(); } break; #endregion #region Dressup case RequestTypes4.DressupUpload: { if (data.Length != 0x220) { logEntry.AppendLine("Length did not validate."); type = EventLogEntryType.FailureAudit; response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } byte[] dressupData = new byte[0xe0]; Array.Copy(data, 0x140, dressupData, 0, 0xe0); DressupRecord4 record = new DressupRecord4(pid, 0, dressupData); ulong serial = Database.Instance.DressupUpload4(record); if (serial == 0) { logEntry.AppendLine("Uploaded dressup already in server."); response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } logEntry.AppendFormat("Dressup {0} uploaded successfully.", serial); response.Write(new byte[] { 0x00, 0x00 }, 0, 2); // result code (0 for OK) response.Write(BitConverter.GetBytes(serial), 0, 8); } break; case RequestTypes4.DressupSearch: { if (data.Length != 0x14c) { logEntry.AppendLine("Length did not validate."); type = EventLogEntryType.FailureAudit; response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } // todo: validate or log some of this? ushort species = BitConverter.ToUInt16(data, 0x144); logEntry.AppendFormat("Searching for dressups of species {0}.", species); logEntry.AppendLine(); DressupRecord4[] results = Database.Instance.DressupSearch4(species, 10); response.Write(new byte[] { 0x00, 0x00 }, 0, 2); // result code (0 for OK) response.Write(BitConverter.GetBytes(results.Length), 0, 4); foreach (DressupRecord4 result in results) { response.Write(BitConverter.GetBytes(result.PID), 0, 4); response.Write(BitConverter.GetBytes(result.SerialNumber), 0, 8); response.Write(result.Data, 0, 0xe0); } logEntry.AppendFormat("Retrieved {0} dressup results.", results.Length); logEntry.AppendLine(); } break; #endregion #region Battle videos case RequestTypes4.BattleVideoUpload: { if (data.Length != 0x1e8c) { logEntry.AppendLine("Length did not validate."); type = EventLogEntryType.FailureAudit; response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } byte[] battlevidData = new byte[0x1d4c]; Array.Copy(data, 0x140, battlevidData, 0, 0x1d4c); BattleVideoRecord4 record = new BattleVideoRecord4(pid, 0, battlevidData); ulong serial = Database.Instance.BattleVideoUpload4(record); if (serial == 0) { logEntry.AppendFormat("Uploaded battle video already in server."); response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } logEntry.AppendFormat("Battle video {0} uploaded successfully.", BattleVideoHeader4.FormatSerial(serial)); logEntry.AppendLine(); response.Write(new byte[] { 0x00, 0x00 }, 0, 2); // result code (0 for OK) response.Write(BitConverter.GetBytes(serial), 0, 8); } break; case RequestTypes4.BattleVideoSearch: { if (data.Length != 0x15c) { logEntry.AppendLine("Length did not validate."); type = EventLogEntryType.FailureAudit; response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } // todo: validate or log some of this? BattleVideoRankings4 ranking = (BattleVideoRankings4)BitConverter.ToUInt32(data, 0x140); ushort species = BitConverter.ToUInt16(data, 0x144); BattleVideoMetagames4 meta = (BattleVideoMetagames4)data[0x146]; byte country = data[0x147]; byte region = data[0x148]; logEntry.Append("Searching for "); if (ranking != BattleVideoRankings4.None) logEntry.AppendFormat("{0}", ranking); else { if (species != 0xffff) logEntry.AppendFormat("species {0}, ", species); logEntry.AppendFormat("{0}", meta); if (country != 0xff) logEntry.AppendFormat(", country {0}", country); if (region != 0xff) logEntry.AppendFormat(", region {0}", region); } logEntry.AppendLine("."); BattleVideoHeader4[] results = Database.Instance.BattleVideoSearch4(species, ranking, meta, country, region, 30); response.Write(new byte[] { 0x00, 0x00 }, 0, 2); // result code (0 for OK) response.Write(BitConverter.GetBytes(results.Length), 0, 4); foreach (BattleVideoHeader4 result in results) { response.Write(BitConverter.GetBytes(result.PID), 0, 4); response.Write(BitConverter.GetBytes(result.SerialNumber), 0, 8); response.Write(result.Data, 0, 0xe4); } logEntry.AppendFormat("Retrieved {0} battle video results.", results.Length); logEntry.AppendLine(); } break; case RequestTypes4.BattleVideoWatch: { if (data.Length != 0x14c) { logEntry.AppendLine("Length did not validate."); type = EventLogEntryType.FailureAudit; response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } ulong serial = BitConverter.ToUInt64(data, 0x140); BattleVideoRecord4 record = Database.Instance.BattleVideoGet4(serial, true); if (record == null) { response.Write(new byte[] { 0x02, 0x00 }, 0, 2); logEntry.AppendFormat("Requested battle video {0} was missing.", BattleVideoHeader4.FormatSerial(serial)); logEntry.AppendLine(); type = EventLogEntryType.FailureAudit; break; } response.Write(new byte[] { 0x00, 0x00 }, 0, 2); // result code (0 for OK) response.Write(BitConverter.GetBytes(record.PID), 0, 4); response.Write(BitConverter.GetBytes(record.SerialNumber), 0, 8); response.Write(record.Header.Data, 0, 0xe4); response.Write(record.Data, 0, 0x1c68); logEntry.AppendFormat("Retrieved battle video {0}.", BattleVideoHeader4.FormatSerial(serial)); logEntry.AppendLine(); } break; case RequestTypes4.BattleVideoSaved: { if (data.Length != 0x148) { logEntry.AppendLine("Length did not validate."); type = EventLogEntryType.FailureAudit; response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } ulong serial = BitConverter.ToUInt64(data, 0x140); if (Database.Instance.BattleVideoFlagSaved4(serial)) { response.Write(new byte[] { 0x00, 0x00 }, 0, 2); // result code (0 for OK) logEntry.AppendFormat("Battle video {0} flagged saved.", BattleVideoHeader4.FormatSerial(serial)); logEntry.AppendLine(); } else { response.Write(new byte[] { 0x02, 0x00 }, 0, 2); logEntry.AppendFormat("Requested battle video {0} was missing.", BattleVideoHeader4.FormatSerial(serial)); logEntry.AppendLine(); } } break; #endregion #region Trainer Rankings case RequestTypes4.TrainerRankingsHead: { if (data.Length != 0x140) { logEntry.AppendLine("Length did not validate."); type = EventLogEntryType.FailureAudit; response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } // AdmiralCurtiss's request: completely blank! (just the 0x140 byte header) // AdmiralCurtiss's response: // 0000: 0c000000f0550000 0128431c // Response format seems to be a list of the three record categories currently being collected. // 0x01: Hall of fame entries // 0x28: Completed GTS trades // 0x43: Facilities challenged at battle frontier // The purpose of 0x1c is unclear to me. if (Database.Instance.TrainerRankingsPerformRollover()) { logEntry.AppendLine("Leaderboard rollover."); } var recordTypes = Database.Instance.TrainerRankingsGetActiveRecordTypes(); // todo: If we can be sure the player has already sent us their up to date records, // then we can lie here about the active records and collect more complete trainer // stats for better trainer profiles response.Write(new byte[] { 0x00, 0x00 }, 0, 2); // The game will give error 10609 if the response is longer than 4 bytes. // The game will bluescreen if the response is shorter than 3 bytes. // The 4th byte is optional and I don't know what, if anything, it does. int i; for (i = 0; i < 3 && i < recordTypes.Count; i++) { response.WriteByte((byte)recordTypes[i]); } for (; i < 3; i++) { // Must be valid RecordTypes. If we pad with 0x00, it causes a bluescreen. response.WriteByte((byte)0x01); } response.WriteByte(0x1c); // todo: Find out the meaning of this 0x1c. } break; case RequestTypes4.TrainerRankingsSearch: { if (data.Length != 0x164) { logEntry.AppendLine("Length did not validate."); type = EventLogEntryType.FailureAudit; response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } // The request is important. It contains the player's records for the above three chosen categories. // It also (presumably) conveys which teams the player is a part of. // (Trainer Class, Birth Month, Favourite Pokémon) // AdmiralCurtiss's request: // 0140: 0c02050900000000 1800303b01000000 // 0150: 0100000028000000 0000000043000000 // 0160: 00000000 // Hikari's request: // Platinum EN July AceTrainerF Gallade // 0140: 0c02070bdb010000 e200350f01000000 // 0150: 0300000028000000 0800000043000000 // 0160: 28000000 // 140: Version // 141: Language // 142: Birth Month // 143: Trainer Class // 144-145: Favourite Pokémon // 146-14b: Unknown // 14c-163: Three record records // Record record contains 4 bytes of category and 4 bytes of my score in the category. // Note: Although the game gives instructions that only // your first submission will apply, I think it's more // fun if we allow you to update your results by // submitting again. In this way, you can race against // competing teams to get the highest score. var submission = new TrainerRankingsSubmission(pid, data, 0x140); Database.Instance.TrainerRankingsSubmit(submission); response.Write(new byte[] { 0x00, 0x00 }, 0, 2); // The response is biig and contains all the records for both this week and last week. // This week lacks numbers because they're still growing and to make it a surprise. // Including more than 3 RecordTypes in the response will give error 10609. TrainerRankingsReport thisWeek = Database.Instance.TrainerRankingsGetPendingReport(); thisWeek.PadResults(); TrainerRankingsReport lastWeek = Database.Instance.TrainerRankingsGetReport(DateTime.MinValue, thisWeek.StartDate.AddDays(-1), 1).FirstOrDefault(); if (lastWeek == null) lastWeek = GenerateFakeReport(thisWeek.StartDate.AddDays(-7), new TrainerRankingsRecordTypes[] { 0, 0, 0 }); else { lastWeek.PadResults(); } // Last week: foreach (var lbg in lastWeek.Leaderboards) { response.Write(BitConverter.GetBytes((int)lbg.RecordType), 0, 4); foreach (var lbe in lbg.LeaderboardTrainerClass.Entries) { response.WriteByte((byte)lbe.Team); } foreach (var lbe in lbg.LeaderboardTrainerClass.Entries) { response.Write(BitConverter.GetBytes(lbe.Score), 0, 8); } foreach (var lbe in lbg.LeaderboardBirthMonth.Entries) { response.WriteByte((byte)lbe.Team); } foreach (var lbe in lbg.LeaderboardBirthMonth.Entries) { response.Write(BitConverter.GetBytes(lbe.Score), 0, 8); } foreach (var lbe in lbg.LeaderboardFavouritePokemon.Entries) { response.Write(BitConverter.GetBytes((short)lbe.Team), 0, 2); } foreach (var lbe in lbg.LeaderboardFavouritePokemon.Entries) { response.Write(BitConverter.GetBytes(lbe.Score), 0, 8); } } // This week: foreach (var lbg in thisWeek.Leaderboards) { response.Write(BitConverter.GetBytes((int)lbg.RecordType), 0, 4); foreach (var lbe in lbg.LeaderboardTrainerClass.Entries) { response.WriteByte((byte)lbe.Team); } foreach (var lbe in lbg.LeaderboardBirthMonth.Entries) { response.WriteByte((byte)lbe.Team); } foreach (var lbe in lbg.LeaderboardFavouritePokemon.Entries) { response.Write(BitConverter.GetBytes((short)lbe.Team), 0, 2); } } } break; #endregion default: logEntry.AppendLine("Unrecognized request type."); response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } } catch (Exception ex) { logEntry.AppendFormat("Unhandled exception while handling request.\nException: {0}", ex.ToString()); logEntry.AppendLine(); type = EventLogEntryType.Error; response.Write(new byte[] { 0x02, 0x00 }, 0, 2); } response.Flush(); byte[] responseData = response.ToArray(); WriteLength(responseData); CryptMessage(responseData); LogHelper.Write(logEntry.ToString(), type); return responseData; } private void CryptMessage(byte[] message) { if (message.Length < 5) return; byte padOffset = (byte)(message[0] + message[4]); // encrypt and decrypt are the same operation... for (int x = 5; x < message.Length; x++) message[x] ^= m_pad[(x + padOffset) & 0xff]; } public override string Title { get { return "Generation IV Global Terminal"; } } private static readonly byte[] m_pad = new byte[] { 0x1F, 0x98, 0xA5, 0x46, 0x76, 0x5C, 0x3D, 0x0E, 0x93, 0x18, 0x33, 0x28, 0x0B, 0x07, 0x03, 0x82, 0x02, 0x43, 0x8A, 0x86, 0xDB, 0x38, 0x34, 0x19, 0xD6, 0xF9, 0x59, 0xB2, 0xAD, 0x6A, 0x7D, 0xBC, 0xEE, 0xE0, 0x3A, 0x3F, 0xCA, 0x4C, 0x25, 0x68, 0xF4, 0xA9, 0x5B, 0xF7, 0x22, 0x60, 0x5A, 0x6F, 0xFA, 0x1B, 0x79, 0xE9, 0x17, 0xB1, 0x00, 0x9C, 0xAA, 0x5E, 0x9D, 0xFF, 0xEA, 0xA0, 0x0D, 0x4B, 0x75, 0xF6, 0x61, 0x85, 0x5D, 0xBB, 0xDC, 0xFB, 0x64, 0x2E, 0x7A, 0xAB, 0xF1, 0xE8, 0x44, 0x0C, 0xB8, 0x8F, 0xA8, 0x0A, 0x8E, 0xBD, 0xE1, 0x3B, 0xFC, 0x3C, 0x9F, 0x1A, 0x56, 0xC5, 0xE2, 0xF5, 0x47, 0xD9, 0xD7, 0x8C, 0xCD, 0x97, 0xF0, 0x7B, 0x8B, 0xC3, 0x4F, 0x45, 0x04, 0x90, 0x81, 0x1E, 0x6B, 0xC9, 0xD3, 0x73, 0xC6, 0xE7, 0x24, 0xBA, 0x32, 0xF3, 0xC0, 0xEC, 0x57, 0xCC, 0xC4, 0xB6, 0xC1, 0xAE, 0xAF, 0x88, 0xF2, 0x84, 0xCE, 0x4A, 0x0F, 0x94, 0x41, 0xB4, 0x74, 0x2A, 0xD1, 0x70, 0x1C, 0xD4, 0xB0, 0xC2, 0x09, 0x08, 0x16, 0x9B, 0xB5, 0x8D, 0x2B, 0xD2, 0x89, 0xB7, 0x99, 0xA1, 0x30, 0x65, 0x54, 0x40, 0x96, 0x71, 0xFE, 0xBF, 0x31, 0x06, 0xE5, 0x14, 0xE6, 0xDA, 0x48, 0x26, 0xAC, 0x87, 0x9A, 0xD8, 0xA6, 0xEB, 0x92, 0xCF, 0xFD, 0x77, 0x1D, 0x21, 0x9E, 0x36, 0x35, 0x53, 0x3E, 0xD0, 0xD5, 0x62, 0x58, 0x5F, 0x63, 0x7C, 0x7E, 0x52, 0x29, 0x12, 0x2C, 0x78, 0x05, 0x91, 0x55, 0xE3, 0xA2, 0xB9, 0xF8, 0x50, 0x95, 0x13, 0x80, 0x7F, 0x11, 0x27, 0xCB, 0x37, 0x4E, 0x51, 0x15, 0xEF, 0xA7, 0x72, 0x4D, 0x83, 0x49, 0xA4, 0x69, 0xDE, 0x20, 0xA3, 0x67, 0xDF, 0x10, 0x42, 0x39, 0x6C, 0x2D, 0xC7, 0x23, 0xE4, 0xDD, 0xED, 0xBE, 0x66, 0xB3, 0x2F, 0x01, 0x6E, 0x6D, 0xC8, }; private static TrainerRankingsLeaderboardEntry[] GenerateFakeData(int entryCount, int minTeam, int teamCount, int maxScore) { Random scoreRandomizer = new Random(); return Enumerable.Range(minTeam, teamCount).Select(i => new TrainerRankingsLeaderboardEntry(i, scoreRandomizer.Next(maxScore))) .OrderBy(e => -e.Score).Take(entryCount).ToArray(); } private static TrainerRankingsReport GenerateFakeReport(DateTime startDate, TrainerRankingsRecordTypes[] recordTypes) { var leaderboards = recordTypes.Select(r => new TrainerRankingsLeaderboardGroup(r, new TrainerRankingsLeaderboard(TrainerRankingsTeamCategories.TrainerClass, GenerateFakeData(16, 0, 16, 100000)), new TrainerRankingsLeaderboard(TrainerRankingsTeamCategories.BirthMonth, GenerateFakeData(12, 1, 12, 100000)), new TrainerRankingsLeaderboard(TrainerRankingsTeamCategories.FavouritePokemon, GenerateFakeData(20, 1, 493, 100000)))).ToArray(); return new TrainerRankingsReport(startDate, startDate.AddDays(7), leaderboards); } } internal enum RequestTypes4 : byte { BoxUpload = 0x08, BoxSearch = 0x09, DressupUpload = 0x20, DressupSearch = 0x21, BattleVideoUpload = 0xd8, BattleVideoSearch = 0xd9, BattleVideoWatch = 0xda, BattleVideoSaved = 0xdb, TrainerRankingsHead = 0xf0, TrainerRankingsSearch = 0xf1 } } ================================================ FILE: GlobalTerminalService/GTServer5.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using PkmnFoundations.Support; using System.IO; using PkmnFoundations.Structures; using PkmnFoundations.Data; using System.Security.Cryptography.X509Certificates; using System.Net.Sockets; using System.Diagnostics; using PkmnFoundations.Wfc; namespace PkmnFoundations.GlobalTerminalService { public class GTServer5 : GTServerBase { public GTServer5() : base(12401, true) { Initialize(); } public GTServer5(int threads) : base(12401, true, threads) { Initialize(); } public GTServer5(int threads, int timeout) : base(12401, true, threads, timeout) { Initialize(); } public GTServer5(int threads, int timeout, X509Certificate2 certificate) : base(12401, true, threads, timeout, certificate) { Initialize(); } private void Initialize() { } protected override byte[] ProcessRequest(byte[] data, TcpClient c) { int length = BitConverter.ToInt32(data, 0); AssertHelper.Equals(length, data.Length); RequestTypes5 requestType = (RequestTypes5)data[4]; StringBuilder logEntry = new StringBuilder(); logEntry.AppendFormat("Handling Generation V {0} request.\nHost: {1}", requestType, c.Client.RemoteEndPoint); logEntry.AppendLine(); EventLogEntryType type = EventLogEntryType.Information; MemoryStream response = new MemoryStream(); response.Write(new byte[] { 0x00, 0x00, 0x00, 0x00 }, 0, 4); // placeholder for length response.WriteByte((byte)requestType); response.WriteByte(data[5]); try { int pid = BitConverter.ToInt32(data, 8); byte version = data[0x0c]; byte language = data[0x0d]; logEntry.AppendFormat("pid: {0}", pid); logEntry.AppendLine(); switch (requestType) { #region Musicals case RequestTypes5.MusicalUpload: { if (data.Length != 0x370) { logEntry.AppendLine("Length did not validate."); type = EventLogEntryType.FailureAudit; response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } byte[] musicalData = new byte[0x230]; Array.Copy(data, 0x140, musicalData, 0, 0x230); MusicalRecord5 record = new MusicalRecord5(pid, 0, musicalData); ulong serial = Database.Instance.MusicalUpload5(record); if (serial == 0) { logEntry.AppendLine("Uploaded musical already in server."); response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } logEntry.AppendFormat("Musical {0} uploaded successfully.", serial); logEntry.AppendLine(); response.Write(new byte[] { 0x00, 0x00 }, 0, 2); // result code (0 for OK) response.Write(BitConverter.GetBytes(serial), 0, 8); } break; case RequestTypes5.MusicalSearch: { if (data.Length != 0x14c) { logEntry.AppendLine("Length did not validate."); type = EventLogEntryType.FailureAudit; response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } // todo: validate or log some of this? ushort species = BitConverter.ToUInt16(data, 0x144); logEntry.AppendFormat("Searching for musical photos of species {0}.", species); logEntry.AppendLine(); MusicalRecord5[] results = Database.Instance.MusicalSearch5(species, 5); response.Write(new byte[] { 0x00, 0x00 }, 0, 2); // result code (0 for OK) response.Write(BitConverter.GetBytes(results.Length), 0, 4); foreach (MusicalRecord5 result in results) { response.Write(BitConverter.GetBytes(result.PID), 0, 4); response.Write(BitConverter.GetBytes(result.SerialNumber), 0, 8); response.Write(result.Data, 0, 0x230); } logEntry.AppendFormat("Retrieved {0} musical results.", results.Length); logEntry.AppendLine(); } break; #endregion #region Battle videos case RequestTypes5.BattleVideoUpload: { if (data.Length != 0x1ae8) { logEntry.AppendLine("Length did not validate."); type = EventLogEntryType.FailureAudit; response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } int sigLength = BitConverter.ToInt32(data, 0x19e4); if (sigLength > 0x100 || sigLength < 0x00) { response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } byte[] battlevidData = new byte[0x18a4]; Array.Copy(data, 0x140, battlevidData, 0, 0x18a4); BattleVideoRecord5 record = new BattleVideoRecord5(pid, 0, battlevidData); byte[] vldtSignature = new byte[sigLength]; Array.Copy(data, 0x19e8, vldtSignature, 0, sigLength); // todo: validate signature. ulong serial = Database.Instance.BattleVideoUpload5(record); if (serial == 0) { logEntry.AppendLine("Uploaded battle video already in server."); response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } logEntry.AppendFormat("Battle video {0} uploaded successfully.", BattleVideoHeader4.FormatSerial(serial)); logEntry.AppendLine(); response.Write(new byte[] { 0x00, 0x00 }, 0, 2); // result code (0 for OK) response.Write(BitConverter.GetBytes(serial), 0, 8); } break; case RequestTypes5.BattleVideoSearch: { if (data.Length != 0x15c) { logEntry.AppendLine("Length did not validate."); type = EventLogEntryType.FailureAudit; response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } // todo: validate or log some of this? BattleVideoRankings5 ranking = (BattleVideoRankings5)BitConverter.ToUInt32(data, 0x140); ushort species = BitConverter.ToUInt16(data, 0x144); BattleVideoMetagames5 meta = (BattleVideoMetagames5)data[0x146]; // Byte 148 contains a magic number related to the searched metagame. // If 0, disable metagame search. Metagame being 00 is insufficient // since that value could mean Battle Subway Single. if (data[0x148] == 0x00) meta = BattleVideoMetagames5.SearchNone; byte country = data[0x14a]; byte region = data[0x14b]; logEntry.Append("Searching for "); if (ranking != BattleVideoRankings5.None) logEntry.AppendFormat("{0}", ranking); else { if (species != 0xffff) logEntry.AppendFormat("species {0}, ", species); logEntry.AppendFormat("{0}", meta); if (country != 0xff) logEntry.AppendFormat(", country {0}", country); if (region != 0xff) logEntry.AppendFormat(", region {0}", region); } logEntry.AppendLine("."); BattleVideoHeader5[] results = Database.Instance.BattleVideoSearch5(species, ranking, meta, country, region, 30); response.Write(new byte[] { 0x00, 0x00 }, 0, 2); // result code (0 for OK) response.Write(BitConverter.GetBytes(results.Length), 0, 4); foreach (BattleVideoHeader5 result in results) { response.Write(BitConverter.GetBytes(result.PID), 0, 4); response.Write(BitConverter.GetBytes(result.SerialNumber), 0, 8); response.Write(result.Data, 0, 0xc4); } logEntry.AppendFormat("Retrieved {0} battle video results.", results.Length); logEntry.AppendLine(); } break; case RequestTypes5.BattleVideoWatch: { if (data.Length != 0x14c) { logEntry.AppendLine("Length did not validate."); type = EventLogEntryType.FailureAudit; response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } ulong serial = BitConverter.ToUInt64(data, 0x140); BattleVideoRecord5 record = Database.Instance.BattleVideoGet5(serial, true); if (record == null) { response.Write(new byte[] { 0x02, 0x00 }, 0, 2); logEntry.AppendFormat("Requested battle video {0} was missing.", BattleVideoHeader4.FormatSerial(serial)); logEntry.AppendLine(); type = EventLogEntryType.FailureAudit; break; } response.Write(new byte[] { 0x00, 0x00 }, 0, 2); // result code (0 for OK) response.Write(BitConverter.GetBytes(record.PID), 0, 4); response.Write(BitConverter.GetBytes(record.SerialNumber), 0, 8); response.Write(record.Header.Data, 0, 0xc4); response.Write(record.Data, 0, 0x17e0); logEntry.AppendFormat("Retrieved battle video {0}.", BattleVideoHeader4.FormatSerial(serial)); logEntry.AppendLine(); } break; case RequestTypes5.BattleVideoSaved: { if (data.Length != 0x148) { logEntry.AppendLine("Length did not validate."); type = EventLogEntryType.FailureAudit; response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } ulong serial = BitConverter.ToUInt64(data, 0x140); if (Database.Instance.BattleVideoFlagSaved5(serial)) { response.Write(new byte[] { 0x00, 0x00 }, 0, 2); // result code (0 for OK) logEntry.AppendFormat("Battle video {0} flagged saved.", BattleVideoHeader4.FormatSerial(serial)); logEntry.AppendLine(); } else { response.Write(new byte[] { 0x02, 0x00 }, 0, 2); logEntry.AppendFormat("Requested battle video {0} was missing.", BattleVideoHeader4.FormatSerial(serial)); logEntry.AppendLine(); } } break; #endregion default: logEntry.AppendLine("Unrecognized request type."); response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } } catch (Exception ex) { logEntry.AppendFormat("Unhandled exception while handling request.\nException: {0}", ex.ToString()); logEntry.AppendLine(); response.Write(new byte[] { 0x02, 0x00 }, 0, 2); } response.Flush(); byte[] responseData = response.ToArray(); WriteLength(responseData); LogHelper.Write(logEntry.ToString(), type); return responseData; } private byte Byte6(RequestTypes5 type) { switch (type) { case RequestTypes5.MusicalUpload: case RequestTypes5.MusicalSearch: return 0x52; case RequestTypes5.BattleVideoUpload: case RequestTypes5.BattleVideoSearch: case RequestTypes5.BattleVideoWatch: case RequestTypes5.BattleVideoSaved: return 0x55; default: return 0x00; } } public override string Title { get { return "Generation V Global Terminal"; } } } internal enum RequestTypes5 : byte { MusicalUpload = 0x08, MusicalSearch = 0x09, BattleVideoUpload = 0xf0, BattleVideoSearch = 0xf1, BattleVideoWatch = 0xf2, BattleVideoSaved = 0xf3 } } ================================================ FILE: GlobalTerminalService/GTServerBase.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading; using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; using System.Net.Security; using System.Net; using PkmnFoundations.Support; using System.Diagnostics; namespace PkmnFoundations.GlobalTerminalService { public abstract class GTServerBase { public GTServerBase(int port) : this(port, false, 16, 5000) { } public GTServerBase(int port, bool useSsl) : this(port, useSsl, 16, 5000) { } public GTServerBase(int port, bool useSsl, int threads) : this(port, useSsl, threads, 5000) { } // todo: It would probably be better to load a custom certificate from // app.config, but since the DS doesn't even validate it, there's no // real point in securing it. public GTServerBase(int port, bool useSsl, int threads, int timeout) : this(port, useSsl, threads, timeout, useSsl ? GetDefaultCertificate() : null) { } public GTServerBase(int port, bool useSsl, int threads, int timeout, X509Certificate2 certificate) { Threads = threads; Timeout = timeout; UseSsl = useSsl; Certificate = certificate; m_workers = new List(threads); m_listener = new TcpListener(IPAddress.Any, port); } private static X509Certificate2 GetDefaultCertificate() { X509Store store = new X509Store(StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); var cers = store.Certificates.Find(X509FindType.FindBySubjectName, "pkgdsprod.nintendo.co.jp", false) .Cast().Where(cer => cer.HasPrivateKey && cer.PrivateKey != null); // fixme: Screen any found certificates for errors like "The // credentials supplied to the package were not recognized" and use // the dummy if none are good. var cerFirst = cers.FirstOrDefault(); if (cerFirst != null) return cerFirst; LogHelper.Write("X.509 certificate not found. Please add a certificate with subject \"pkgdsprod.nintendo.co.jp\" to the store. Using dummy certificate."); return new X509Certificate2(AppDomain.CurrentDomain.BaseDirectory + Path.DirectorySeparatorChar + "cert.pfx", "letmein"); } public int Threads { get; protected set; } public int Timeout { get; protected set; } protected bool UseSsl { get; set; } protected X509Certificate Certificate { get; set; } private List m_workers; private object m_lock = new object(); private bool m_closing; private TcpListener m_listener; public void BeginPolling() { lock (m_lock) { if (m_workers.Count > 0) return; LogHelper.Write(String.Format("{0} server running on port {1} with {2} threads.", Title, ((IPEndPoint)m_listener.LocalEndpoint).Port, Threads)); m_closing = false; m_listener.Start(); for (int x = 0; x < Threads; x++) { Thread t = new Thread(MainLoop); m_workers.Add(t); t.Start(); } } } public void EndPolling() { lock (m_lock) { if (m_workers.Count == 0) return; m_closing = true; // wait for worker threads to exit while (m_workers.Count > 0) { Thread.Sleep(10); } m_listener.Stop(); } } private void MainLoop(object o) { int threadIndex = m_workers.IndexOf(Thread.CurrentThread); // This is too chatty for an event log. //LogHelper.Write(String.Format("Thread {0} begins.", threadIndex)); while (!m_closing) { try { if (!m_listener.Pending()) { Thread.Sleep(10); continue; } using (TcpClient c = AcceptClient()) { if (c == null) { Thread.Sleep(10); continue; } try { c.ReceiveTimeout = Timeout; c.SendTimeout = Timeout; Stream s = GetStream(c); BinaryReader br = new BinaryReader(s); int length = br.ReadInt32(); if (length > 7820) { LogHelper.Write(String.Format("Indicated request length is over limit.\nHost: {0}", c.Client.RemoteEndPoint), EventLogEntryType.FailureAudit); continue; } if (length < 320) { LogHelper.Write(String.Format("Indicated request length is under limit.\nHost: {0}", c.Client.RemoteEndPoint), EventLogEntryType.FailureAudit); continue; } byte[] data = new byte[length]; BitConverter.GetBytes(length).CopyTo(data, 0); int actualLength = br.ReadBlock(data, 4, length - 4); if (actualLength + 4 != length) { LogHelper.Write(String.Format("The client disconnected prematurely.\nHost: {0}", c.Client.RemoteEndPoint), EventLogEntryType.FailureAudit); continue; } byte[] response = ProcessRequest(data, c); s.Write(response, 0, response.Length); } catch (Exception ex) { LogHelper.Write(String.Format("Unhandled exception while handling request:\nHost: {0}\nException: {1}", c.Client.RemoteEndPoint, ex.Message), EventLogEntryType.Error); } } } catch (Exception ex) { LogHelper.Write(String.Format("Unhandled exception while handling request:\nException: {0}", ex.Message), EventLogEntryType.Error); } } //LogHelper.Write(String.Format("Thread {0} ends.", threadIndex)); m_workers.Remove(Thread.CurrentThread); } private TcpClient AcceptClient() { lock (m_listener) { if (!m_listener.Pending()) return null; return m_listener.AcceptTcpClient(); } } private Stream GetStream(TcpClient c) { if (UseSsl) { // todo: If we target .NET Core 3+, we can manually enable RC4 cipher suites. // https://github.com/dotnet/runtime/issues/23818 // The DS wants to use SSLv3 and one of the following ciphers: // 0x0004 TLS_RSA_WITH_RC4_128_MD5 // 0x0005 TLS_RSA_WITH_RC4_128_SHA // For now, the only functional approach is to enable these ciphers in the registry or via e.g. IISCrypto. SslStream sslClient = new SslStream(c.GetStream()); sslClient.AuthenticateAsServer(Certificate, false, System.Security.Authentication.SslProtocols.Ssl3, false); return sslClient; } else return c.GetStream(); } protected abstract byte[] ProcessRequest(byte[] data, TcpClient c); public abstract String Title { get; } protected void WriteLength(byte[] message) { byte[] data = BitConverter.GetBytes(message.Length); Array.Copy(data, 0, message, 0, 4); } } } ================================================ FILE: GlobalTerminalService/GlobalTerminalService.csproj ================================================  Debug x86 8.0.30703 2.0 {7AB1A65F-3AD1-4356-94E7-F1A669BF4CE0} Exe Properties PkmnFoundations.GlobalTerminalService GlobalTerminalService v4.0 512 AnyCPU true full false bin\Debug\ DEBUG;TRACE prompt 4 x86 pdbonly true bin\Release\ TRACE prompt 4 Component ProjectInstaller.cs Component Service1.cs {408EFC7E-C6B0-4160-8628-2679E34385CE} Library Always ProjectInstaller.cs Service1.cs ================================================ FILE: GlobalTerminalService/Program.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading; namespace PkmnFoundations.GlobalTerminalService { static class Program { /// /// The main entry point for the application. /// static void Main() { #if DEBUG Service1 myService = new Service1(); myService.Start(); while (true) { Thread.Sleep(1000); } #else ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new Service1() }; ServiceBase.Run(ServicesToRun); #endif } } } ================================================ FILE: GlobalTerminalService/ProjectInstaller.Designer.cs ================================================ namespace PkmnFoundations.GlobalTerminalService { partial class ProjectInstaller { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller(); this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller(); // // serviceProcessInstaller1 // this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.NetworkService; this.serviceProcessInstaller1.Password = null; this.serviceProcessInstaller1.Username = null; // // serviceInstaller1 // this.serviceInstaller1.Description = "Provides Global Terminal functionality to Pokémon games on the Nintendo DS."; this.serviceInstaller1.DisplayName = "Global Terminal Service"; this.serviceInstaller1.ServiceName = "GlobalTerminalService"; this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic; // // ProjectInstaller // this.Installers.AddRange(new System.Configuration.Install.Installer[] { this.serviceProcessInstaller1, this.serviceInstaller1}); } #endregion private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1; private System.ServiceProcess.ServiceInstaller serviceInstaller1; } } ================================================ FILE: GlobalTerminalService/ProjectInstaller.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration.Install; using System.Linq; namespace PkmnFoundations.GlobalTerminalService { [RunInstaller(true)] public partial class ProjectInstaller : System.Configuration.Install.Installer { public ProjectInstaller() { InitializeComponent(); } } } ================================================ FILE: GlobalTerminalService/ProjectInstaller.resx ================================================  text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 17, 17 328, 17 False ================================================ FILE: GlobalTerminalService/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("GlobalTerminalService")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GlobalTerminalService")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("47274bc4-d452-4eeb-acfb-6aedfe702a65")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: GlobalTerminalService/Service1.Designer.cs ================================================ namespace PkmnFoundations.GlobalTerminalService { partial class Service1 { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { // // Service1 // this.ServiceName = "GlobalTerminalService"; } #endregion } } ================================================ FILE: GlobalTerminalService/Service1.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; using PkmnFoundations.Support; namespace PkmnFoundations.GlobalTerminalService { public partial class Service1 : ServiceBase { public Service1() { InitializeComponent(); #if !DEBUG LogHelper.UseEventLog(this.EventLog); #endif } private GTServer4 m_server_4 = null; private GTServer5 m_server_5 = null; protected override void OnStart(string[] args) { Start(); } public void Start() { if (m_server_4 == null) m_server_4 = new GTServer4(); if (m_server_5 == null) m_server_5 = new GTServer5(); m_server_4.BeginPolling(); m_server_5.BeginPolling(); } protected override void OnStop() { if (m_server_4 != null) m_server_4.EndPolling(); // fixme: it waits for the GenIV server to stop completely before // shutting down the GenV server. Should shut them both down async. if (m_server_5 != null) m_server_5.EndPolling(); } } } ================================================ FILE: GlobalTerminalService/Service1.resx ================================================  text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 False ================================================ FILE: GlobalTerminalService/app.config ================================================ ================================================ FILE: LICENSE.md ================================================ Copyright © 2014-2023 Megan Edwards (mm201), all rights reserved You may: * Run a private instance for development purposes. * Serve it privately to a LAN for personal use among a group of people you know. * Privately make changes. * Contribute those changes back to the author's original project which, at the time of writing, is located at https://github.com/mm201/pkmn-classic-framework/ . Such contributions will be subject to the author's choice of license. Should a period of 180 consecutive days elapse where the server operated or endorsed by the author (which, at the time of writing, is located at https://pkmnclassic.net/ ) remains offline, then you may take the contents of this repository and rerelease them under the terms of the GNU Affero General Public License. The full text of this license may, at time of writing, be found at https://www.gnu.org/licenses/agpl-3.0.en.html . THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: MakeBaseStatTables/MakeBaseStatTables.csproj ================================================  Debug AnyCPU {99FCBB1C-D94F-458D-ABD2-8800FBDC65DA} Exe Properties MakeBaseStatTables MakeBaseStatTables v3.5 512 a6417236 AnyCPU true full false bin\Debug\ DEBUG;TRACE prompt 4 AnyCPU pdbonly true bin\Release\ TRACE prompt 4 False ..\packages\System.Data.SQLite.Core.1.0.94.0\lib\net20\System.Data.SQLite.dll False ..\packages\System.Data.SQLite.Linq.1.0.94.1\lib\net20\System.Data.SQLite.Linq.dll {408efc7e-c6b0-4160-8628-2679e34385ce} Library This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. ================================================ FILE: MakeBaseStatTables/Program.cs ================================================ using System; using System.Collections.Generic; using System.Data.SQLite; using System.IO; using System.Linq; using System.Text; using PkmnFoundations.Data; namespace MakeBaseStatTables { /// /// Builds some .txt data files from the Veekun data which require manual /// edits. /// class Program { static void Main(string[] args) { String veekunFilename; if (args.Length < 1) veekunFilename = "pokedex.sqlite"; else veekunFilename = args[0]; if (veekunFilename.Contains(';')) throw new NotSupportedException("The character ; in filenames is not supported."); if (veekunFilename.Contains('?')) { Console.WriteLine("Usage: MakeBaseStatTables [filename]"); Console.WriteLine("filename: Filename of Veekun sqlite database. Default: pokedex.sqlite"); return; } using (SQLiteConnection connVeekun = new SQLiteConnection("Data Source=" + veekunFilename + "; Version=3")) { connVeekun.Open(); SQLiteDataReader reader = (SQLiteDataReader)connVeekun.ExecuteReader("SELECT id, " + "(SELECT base_stat FROM pokemon_stats WHERE pokemon_id = pokemon_forms.pokemon_id AND stat_id = 1) AS base_hp, " + "(SELECT base_stat FROM pokemon_stats WHERE pokemon_id = pokemon_forms.pokemon_id AND stat_id = 2) AS base_attack, " + "(SELECT base_stat FROM pokemon_stats WHERE pokemon_id = pokemon_forms.pokemon_id AND stat_id = 3) AS base_defense, " + "(SELECT base_stat FROM pokemon_stats WHERE pokemon_id = pokemon_forms.pokemon_id AND stat_id = 4) AS base_sp_attack, " + "(SELECT base_stat FROM pokemon_stats WHERE pokemon_id = pokemon_forms.pokemon_id AND stat_id = 5) AS base_sp_defense, " + "(SELECT base_stat FROM pokemon_stats WHERE pokemon_id = pokemon_forms.pokemon_id AND stat_id = 6) AS base_speed, " + "(SELECT effort FROM pokemon_stats WHERE pokemon_id = pokemon_forms.pokemon_id AND stat_id = 1) AS reward_hp, " + "(SELECT effort FROM pokemon_stats WHERE pokemon_id = pokemon_forms.pokemon_id AND stat_id = 2) AS reward_attack, " + "(SELECT effort FROM pokemon_stats WHERE pokemon_id = pokemon_forms.pokemon_id AND stat_id = 3) AS reward_defense, " + "(SELECT effort FROM pokemon_stats WHERE pokemon_id = pokemon_forms.pokemon_id AND stat_id = 4) AS reward_sp_attack, " + "(SELECT effort FROM pokemon_stats WHERE pokemon_id = pokemon_forms.pokemon_id AND stat_id = 5) AS reward_sp_defense, " + "(SELECT effort FROM pokemon_stats WHERE pokemon_id = pokemon_forms.pokemon_id AND stat_id = 6) AS reward_speed, " + "(SELECT type_id FROM pokemon_types WHERE pokemon_id = pokemon_forms.pokemon_id AND slot = 1) AS type1, " + "(SELECT type_id FROM pokemon_types WHERE pokemon_id = pokemon_forms.pokemon_id AND slot = 2) AS type2 " + "FROM pokemon_forms ORDER BY id"); using (FileStream fs = File.Open("form_stats1.txt", FileMode.Create)) { StreamWriter sw = new StreamWriter(fs); while (reader.Read()) { sw.Write("{0:00000}\t", reader["id"]); sw.Write("{0:00}\t", reader["type1"] is DBNull ? 0 : Convert.ToInt32(reader["type1"])); sw.Write("{0:00}\t", reader["type2"] is DBNull ? 0 : Convert.ToInt32(reader["type2"])); sw.Write("{0:000}\t", Convert.ToInt32(reader["base_hp"])); sw.Write("{0:000}\t", Convert.ToInt32(reader["base_attack"])); sw.Write("{0:000}\t", Convert.ToInt32(reader["base_defense"])); sw.Write("{0:000}\t", Convert.ToInt32(reader["base_speed"])); sw.Write("{0:000}\t", Convert.ToInt32(reader["base_sp_attack"])); sw.Write("{0:000}\t", Convert.ToInt32(reader["base_sp_defense"])); sw.Write("{0:0}\t", Convert.ToByte(reader["reward_hp"])); sw.Write("{0:0}\t", Convert.ToByte(reader["reward_attack"])); sw.Write("{0:0}\t", Convert.ToByte(reader["reward_defense"])); sw.Write("{0:0}\t", Convert.ToByte(reader["reward_speed"])); sw.Write("{0:0}\t", Convert.ToByte(reader["reward_sp_attack"])); sw.WriteLine("{0:0}", Convert.ToByte(reader["reward_sp_defense"])); } sw.Close(); fs.Close(); } reader.Close(); reader = (SQLiteDataReader)connVeekun.ExecuteReader("SELECT id, " + "(SELECT ability_id FROM pokemon_abilities WHERE pokemon_id = pokemon_forms.pokemon_id AND slot = 1) AS ability1, " + "(SELECT ability_id FROM pokemon_abilities WHERE pokemon_id = pokemon_forms.pokemon_id AND slot = 2) AS ability2, " + "(SELECT ability_id FROM pokemon_abilities WHERE pokemon_id = pokemon_forms.pokemon_id AND is_hidden = 1) AS ability_hidden " + "FROM pokemon_forms ORDER BY id"); using (FileStream fs3 = File.Open("form_abilities3.txt", FileMode.Create), fs4 = File.Open("form_abilities4.txt", FileMode.Create), fs5 = File.Open("form_abilities5.txt", FileMode.Create), fs6 = File.Open("form_abilities6.txt", FileMode.Create)) { StreamWriter sw3 = new StreamWriter(fs3); StreamWriter sw4 = new StreamWriter(fs4); StreamWriter sw5 = new StreamWriter(fs5); StreamWriter sw6 = new StreamWriter(fs6); while (reader.Read()) { long id = Convert.ToInt64(reader["id"]); if ((id <= 386) || (id >= 10000 && id <= 10033)) { sw3.Write("{0:00000}\t", reader["id"]); sw3.Write("{0:000}\t", reader["ability1"] is DBNull ? 0 : Convert.ToInt32(reader["ability1"])); sw3.Write("{0:000}\t", reader["ability2"] is DBNull ? 0 : Convert.ToInt32(reader["ability2"])); sw3.WriteLine("{0:000}", 0); } else if ((id <= 493) || (id >= 10034 && id <= 10065)) { sw4.Write("{0:00000}\t", reader["id"]); sw4.Write("{0:000}\t", reader["ability1"] is DBNull ? 0 : Convert.ToInt32(reader["ability1"])); sw4.Write("{0:000}\t", reader["ability2"] is DBNull ? 0 : Convert.ToInt32(reader["ability2"])); sw4.WriteLine("{0:000}", 0); } if ((id <= 649) || (id >= 10000 && id <= 10084)) { sw5.Write("{0:00000}\t", reader["id"]); sw5.Write("{0:000}\t", reader["ability1"] is DBNull ? 0 : Convert.ToInt32(reader["ability1"])); sw5.Write("{0:000}\t", reader["ability2"] is DBNull ? 0 : Convert.ToInt32(reader["ability2"])); sw5.WriteLine("{0:000}", reader["ability_hidden"] is DBNull ? 0 : Convert.ToInt32(reader["ability_hidden"])); } else { sw6.Write("{0:00000}\t", reader["id"]); sw6.Write("{0:000}\t", reader["ability1"] is DBNull ? 0 : Convert.ToInt32(reader["ability1"])); sw6.Write("{0:000}\t", reader["ability2"] is DBNull ? 0 : Convert.ToInt32(reader["ability2"])); sw6.WriteLine("{0:000}", reader["ability_hidden"] is DBNull ? 0 : Convert.ToInt32(reader["ability_hidden"])); } } sw3.Close(); sw4.Close(); sw5.Close(); sw6.Close(); fs3.Close(); fs4.Close(); fs5.Close(); fs6.Close(); } connVeekun.Close(); } } } } ================================================ FILE: MakeBaseStatTables/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MakeBaseStatTables")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MakeBaseStatTables")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e867b07c-6746-4495-8cd8-ad05b8463a8b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: MakeBaseStatTables/app.config ================================================ 
================================================ FILE: MakeBaseStatTables/packages.config ================================================  ================================================ FILE: README.md ================================================ # Poké Classic Framework https://pkmnclassic.net/ Poké Classic Framework is a replacement server and class library for Pokémon Generations 4 and 5. Poké Classic Network is the name of the server itself. ## How to connect AltWFC is configured to automatically direct you to my servers. Follow the [instructions](https://github.com/polaris-/dwc_network_server_emulator/wiki) at their wiki to connect. ## What works * GTS * Battle Videos * Dressup (PtHGSS) * Box uploads (PtHGSS) * Musical photos (BW1/2) * Wi-Fi Battle Tower and Subway * Trainer Rankings (PtHGSS) * Wi-Fi Plaza (PtHGSS) (Surveys still in progress) Direct communications are handled by [AltWFC](https://github.com/polaris-/dwc_network_server_emulator) and are outside the scope of this project. They work at the time of writing but haven't been tested that thoroughly. ## What doesn't * Game Sync * Rating Battles / Competitions ## What's planned * A much more awesome website * Cheat detection * Stat checking in a similar manner as Pokécheck * Game Sync (I will need help with this!) ## How you can help If there's something you want to see, the best thing is to discuss it with me and prepare a pull request. You should also check for open issues marked [Help Wanted](https://github.com/mm201/pkmn-classic-framework/labels/help%20wanted). Not all of them require programming skill. The most significant way you can help is simply by using it. The GTS is nothing without users. Get on there and start trading! ## Credits * [Project Pokémon](https://projectpokemon.org/) for most of the original fake GTS reverse engineering work, file format and data structure descriptions, and many ID number tables, including items and trendy phrases. * [Pipian](http://www.pipian.net/ierukana/) for more reverse engineering help, including the Battle Tower and Wi-fi Plaza. * [Nagato](https://github.com/polaris-), for help reverse engineering the Game Sync protocol. * [Billy](https://billy.wales/) for help with GameSpy protocols and interfacing with Wiimmfi. * Nagato and other contributors to the [AltWFC](https://github.com/barronwaffles/dwc_network_server_emulator) project, which this project depends on for basic Nintendo Wi-Fi fuctionality. * [Eevee](https://veekun.com/) for her Veekun Pokédex and large sprite rips. * [Bulbapedia](https://bulbapedia.bulbagarden.net/wiki/Main_Page) for most item sprites and Generation 3 item/text conversion tables. * [kaphotics](https://twitter.com/kaphotics) for the Pokémon mini sprite rips from ORAS. * [sosnek](https://github.com/sosnek) for help with held item validation. * [msikma](https://github.com/msikma/pokesprite) and [monsanto](https://github.com/smogon/sprites) for their sprite databases. * GatorShark and Magical for their [Spinda spot documentation](https://gatorshark.webs.com/SpindaDocumentation.htm) and [Python implementation](https://github.com/magical/spinda), respectively. ================================================ FILE: RenameImages/App.config ================================================  ================================================ FILE: RenameImages/Program.cs ================================================ using PkmnFoundations.Data; using PkmnFoundations.Pokedex; using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Text; namespace RenameImages { /// /// Renames images obtained from Pokesprite. https://github.com/msikma/pokesprite /// class Program { static void Main(string[] args) { string path; char slash = Path.DirectorySeparatorChar; ConnectionStringSettings css; if (args.Length < 1) path = "." + slash + "pkmn-sm"; else path = args[0]; if (path.Contains('?')) { Console.WriteLine("h e l p"); return; } while (path.Length > 0 && (path[path.Length - 1] == '/' || path[path.Length - 1] == '\\')) { path = path.Substring(0, path.Length - 1); } path = path + slash; if (args.Length < 3) css = ConfigurationManager.ConnectionStrings["pkmnFoundationsConnectionString"]; else css = new ConnectionStringSettings("", args[1], args[2]); Database db = Database.CreateInstance(css); Pokedex pokedex = new Pokedex(db, false); foreach (var pair in pokedex.Forms) { Form form = pair.Value; Species species = form.Species; StringBuilder speciesNameBuilder = new StringBuilder(species.Name["EN"].ToLowerInvariant()); speciesNameBuilder.Replace("\'", ""); speciesNameBuilder.Replace(".", ""); speciesNameBuilder.Replace("♀", "-f"); speciesNameBuilder.Replace("♂", "-m"); speciesNameBuilder.Replace('é', 'e'); speciesNameBuilder.Replace(' ', '-'); string speciesName = speciesNameBuilder.ToString(); // fixme: This is incorrect for Vivillon, Pumpkaboo, and Gourgeist, because their suffixless form is not form 0. string oldFilename = (form.Value == 0) ? String.Format("{0}.png", speciesName) : String.Format("{0}-{1}.png", speciesName, form.Suffix); string newFilename = (form.Suffix.Trim().Length == 0) ? String.Format("{0}.png", species.NationalDex) : String.Format("{0}-{1}.png", species.NationalDex, form.Suffix); try { File.Move(path + oldFilename, path + newFilename); Console.Write("{0} {1}", oldFilename, newFilename); } catch (Exception ex) { Console.Write(ex.Message); } if (form.Value == 0 && form.Suffix.Trim().Length != 0) { try { string speciesFilename = String.Format("{0}.png", species.NationalDex); File.Copy(path + newFilename, path + speciesFilename); Console.Write(" {0}", speciesFilename); } catch (Exception ex) { Console.WriteLine(); Console.Write(ex.Message); } } Console.WriteLine(); } Console.ReadKey(); } private static string NormalizeFilename(string filename, string path) { if (filename.Length >= path.Length) { string pathPart = filename.Substring(0, path.Length); if (pathPart == path) filename = filename.Substring(path.Length); } return filename.ToLowerInvariant().Trim(); } } } ================================================ FILE: RenameImages/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("RenameImages")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RenameImages")] [assembly: AssemblyCopyright("Copyright © 2022")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d8787475-2d21-4e60-9320-13fa55c979ac")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: RenameImages/RenameImages.csproj ================================================  Debug AnyCPU {D8787475-2D21-4E60-9320-13FA55C979AC} Exe RenameImages RenameImages v4.0 512 true AnyCPU true full false bin\Debug\ DEBUG;TRACE prompt 4 AnyCPU pdbonly true bin\Release\ TRACE prompt 4 {408efc7e-c6b0-4160-8628-2679e34385ce} Library ================================================ FILE: Roadmap.md ================================================ # Roadmap This is a complete list of all the features I want the PCN server to have for me to consider it complete. ## IV and V * GTS: cheat filter, legal request filter, search, history, player history, push notifications * Battle tower: room leaders, room history, player history, player's last party used, player's highest floor reached * Battle videos: Search, history, watch * Mystery gift: monthly rotation * Player profiles: login, view, permissions * Pokédex * Friend list management? I don’t know whether to handle this at the Trainer or User level. * I guess we can show friends lists in one’s own trainer profiles after game sync has happened, and have an Add as Friend button. (Add as Dream Pal?) * Permissions: Game progress (badges, medals, pokedex, battle tower, …), Friends, GTS history, uploaded shit * Permission levels: Everyone, friends, nobody ## IV * Dressups: search * Box uploads: search * Trainer rankings: current, breakdown by week * Wifi plaza: survey results * Stat checking: check via GTS, check via battle videos * Player profiles: link via GTS ## V * Musicals: search * Stat checking: check via Game Sync * Player profiles: link via Game Sync ID * pkvldtprod: soft legality check * Game Sync: put to bed, wake up, receive items, pokemon, musicals, c-gear, pokedex wallpaper * Dream World: berry garden, pokemon feeder, house decorations * Rating battles * Battle competitions ## Stat checking * All the features of Pokecheck. * GenIV links in a Pokecheck style way: Search for Ditto lv9 and under, get a secret code from the search results. * GenV links using your PGL code. * Link in one place for both PGL and stat check. (Provide some basic PGL style functionality eg. player profiles and game selection for Gen4) In Gen4, you check a pokemon just like Pokecheck, only your request must be Ditto lv9 and under for it to happen. In Gen5, you check a box of pokemon at a time by renaming the box and using Game Sync. (possible issue: game sync limited to once a day) You can add tags to your pokemon summaries, works much the same as pokecheck boxes only multiples are allowed. * Species/shiny/DW are built-in searches. * Set individual pokemon to public/friends/private. * Delete button. (this is a 100% real delete) ## Administration * Can see full “pokecheck” pages for any pokemon in the GTS or history. * Can eject pokemon from the system. * Can see all trainer profiles * Can see all user profiles * Can ban trainers?? * Can link/unlink trainers to user profiles. * Gets some secret trainer/user info like pid. * Sees full validation summaries of all pokemon * Has access to pkvldtprod logs * Hide/delete pkgdsprod uploads * Hex view of pkm data (decrypted, unshuffled) ================================================ FILE: VeekunImport/Program.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; using PkmnFoundations.Data; using System.Data.SQLite; using System.Data; using PkmnFoundations.Structures; using PkmnFoundations.Pokedex; using PkmnFoundations.Support; using System.Threading; using System.Globalization; using System.IO; namespace VeekunImport { class Program { const int GENERATIONS = 6; static void Main(string[] args) { string veekunFilename; ConnectionStringSettings css; if (args.Length < 1) veekunFilename = "pokedex.sqlite"; else veekunFilename = args[0]; if (veekunFilename.Contains(';')) throw new NotSupportedException("The character ; in filenames is not supported."); if (veekunFilename.Contains('?')) { Console.WriteLine("Usage: VeekunImport [filename [connectionString providerName]]"); Console.WriteLine("filename: Filename of Veekun sqlite database. Default: pokedex.sqlite"); Console.WriteLine("connectionString: pkmnFoundations connection string. Default: from app.config"); Console.WriteLine("providerName: .NET classname of connection provider. Default: from app.config"); return; } if (args.Length < 3) css = ConfigurationManager.ConnectionStrings["pkmnFoundationsConnectionString"]; else css = new ConnectionStringSettings("", args[1], args[2]); Database db = Database.CreateInstance(css); using (SQLiteConnection connVeekun = new SQLiteConnection("Data Source=" + veekunFilename + "; Version=3")) { connVeekun.Open(); // General logic: // 1. run a query against veekun, populate a DataTable. // 2. foreach DataRow, instance a class from the PkmnFoundations.Pokedex namespace. // 3. call Database.AddToPokedex on that object. // todo: We need a way to rebuild specific tables // pkmncf_pokedex_pokemon_families // Obtain the families map. We will use it in a few places. Dictionary familyMap = new Dictionary(); List familyList = new List(); ProcessTSV("families_map.txt", 1, row => { // todo: allow for comments by stopping consumption of fields once one fails to parse. int[] fieldsInt = row.Fields.Select(s => Convert.ToInt32(s)).ToArray(); familyList.Add(fieldsInt); foreach (int x in fieldsInt) { // lineNumber is one-based, unlike familyList index. // species is the key, family ID is the value. // If any species is repeated in family_map.txt, this ought to fail. familyMap.Add(x, row.ValidLineNumber + 1); } }); // families from families.txt override default behaviour. List overrideFamilies = new List(); ProcessTSV("families.txt", 7, row => { string[] fields = row.Fields; overrideFamilies.Add(new Family(null, Convert.ToInt32(fields[0]), Convert.ToInt32(fields[1]), Convert.ToInt32(fields[2]), Convert.ToInt32(fields[3]), Convert.ToInt32(fields[4]), Convert.ToInt32(fields[5]), Convert.ToByte(fields[6]) )); }); // already sorted //someFamilies.Sort((f, other) => f.ID.CompareTo(other.ID)); int familyCount = familyList.Count; int nextOverrideIndex = 0; for (int familyId = 1; familyId <= familyCount; familyId++) { int basicSpeciesId = familyList[familyId - 1][0]; Family f; if (nextOverrideIndex < overrideFamilies.Count && overrideFamilies[nextOverrideIndex].ID == familyId) { // An override exists in the table; use it. f = overrideFamilies[nextOverrideIndex]; nextOverrideIndex++; } else { // No override exists so go with default: // Basic male/female are the same species which is the one listed first. // There is no baby species nor incense // (Non-incense babies are considered basic in this system anyway.) // Gender ratio comes from the basic species. byte genderRatio = (byte)Convert.ToInt32(connVeekun.ExecuteScalar("SELECT gender_rate FROM pokemon_species WHERE id = @id", new SQLiteParameter("@id", basicSpeciesId))); f = new Family(null, familyId, basicSpeciesId, basicSpeciesId, 0, 0, 0, genderRatio); } db.PokedexInsertFamily(f); string basic = (f.BasicMaleID != f.BasicFemaleID) ? String.Format(" {0}/{1}", f.BasicMaleID, f.BasicFemaleID) : String.Format(" {0}", f.BasicMaleID); string baby; if (f.BabyMaleID != f.BabyFemaleID) baby = String.Format(" {0}/{1} incense {2}", f.BabyMaleID, f.BabyFemaleID, f.IncenseID); else baby = (f.BabyMaleID == 0) ? "" : String.Format(" {0} incense {1}", f.BabyMaleID, f.IncenseID); string gender = (f.GenderRatio == 255) ? "genderless" : String.Format("{0}% female", (float)f.GenderRatio * 12.5f); Console.WriteLine("Inserted family {0}{1}{2} {3}", f.ID, basic, baby, gender); } // pkmncf_pokedex_pokemon SQLiteDataReader rdPokemon = (SQLiteDataReader)connVeekun.ExecuteReader("SELECT " + "pokemon_species.id, " + "(SELECT pokemon_species_names.name FROM pokemon_species_names WHERE pokemon_species_names.pokemon_species_id = pokemon_species.id AND local_language_id = 1) AS name_ja, " + "(SELECT pokemon_species_names.name FROM pokemon_species_names WHERE pokemon_species_names.pokemon_species_id = pokemon_species.id AND local_language_id = 9) AS name_en, " + "(SELECT pokemon_species_names.name FROM pokemon_species_names WHERE pokemon_species_names.pokemon_species_id = pokemon_species.id AND local_language_id = 5) AS name_fr, " + "(SELECT pokemon_species_names.name FROM pokemon_species_names WHERE pokemon_species_names.pokemon_species_id = pokemon_species.id AND local_language_id = 8) AS name_it, " + "(SELECT pokemon_species_names.name FROM pokemon_species_names WHERE pokemon_species_names.pokemon_species_id = pokemon_species.id AND local_language_id = 6) AS name_de, " + "(SELECT pokemon_species_names.name FROM pokemon_species_names WHERE pokemon_species_names.pokemon_species_id = pokemon_species.id AND local_language_id = 7) AS name_es, " + "(SELECT pokemon_species_names.name FROM pokemon_species_names WHERE pokemon_species_names.pokemon_species_id = pokemon_species.id AND local_language_id = 3) AS name_ko, " + "growth_rate_id, gender_rate, " + "(SELECT egg_group_id FROM pokemon_egg_groups WHERE species_id = pokemon_species.id ORDER BY egg_group_id LIMIT 1) AS egg_group_1, " + "(SELECT egg_group_id FROM pokemon_egg_groups WHERE species_id = pokemon_species.id ORDER BY egg_group_id LIMIT 1, 1) AS egg_group_2, " + "hatch_counter, has_gender_differences " + "FROM pokemon_species " + "ORDER BY pokemon_species.id"); while (rdPokemon.Read()) { int id = Convert.ToInt32(rdPokemon["id"]); byte growth_rate_id = Convert.ToByte(rdPokemon["growth_rate_id"]); int gender_rate = Convert.ToInt32(rdPokemon["gender_rate"]); byte egg_group_1 = Convert.ToByte(rdPokemon["egg_group_1"]); byte egg_group_2 = 0; if (!(rdPokemon["egg_group_2"] is DBNull)) egg_group_2 = Convert.ToByte(rdPokemon["egg_group_2"]); int hatch_counter = Convert.ToInt32(rdPokemon["hatch_counter"]); byte has_gender_differences = Convert.ToByte(rdPokemon["has_gender_differences"]); if (id == 255) has_gender_differences = 0; // Torchic doesn't have gender differences. // todo: Family ID Species s = new Species(null, id, familyMap[id], GetLocalizedString(rdPokemon, "name_"), (GrowthRates)growth_rate_id, (byte)gender_rate, (EggGroups)egg_group_1, (EggGroups)egg_group_2, (byte)hatch_counter, has_gender_differences != 0 ); db.PokedexInsertSpecies(s); Console.WriteLine("Inserted {0} {1} {2} {3} {4} {5}", s.NationalDex, s.Name.ToString(), s.GrowthRate, s.GenderRatio, s.EggSteps, s.GenderVariations); } rdPokemon.Close(); // pkmncf_pokedex_pokemon_forms Dictionary formValueMap = new Dictionary(); ProcessTSV("form_values.txt", 3, row => { string[] fields = row.Fields; formValueMap.Add(Convert.ToInt32(fields[1]), Convert.ToByte(fields[2])); }); SQLiteDataReader rdForms = (SQLiteDataReader)connVeekun.ExecuteReader("SELECT id, " + "(SELECT species_id FROM pokemon WHERE id = pokemon_id) AS NationalDex, " + "form_order - 1 AS FormValue, " + "(SELECT pokemon_form_names.form_name FROM pokemon_form_names WHERE pokemon_form_names.pokemon_form_id = pokemon_forms.id AND local_language_id = 1) AS name_ja, " + "(SELECT pokemon_form_names.form_name FROM pokemon_form_names WHERE pokemon_form_names.pokemon_form_id = pokemon_forms.id AND local_language_id = 9) AS name_en, " + "(SELECT pokemon_form_names.form_name FROM pokemon_form_names WHERE pokemon_form_names.pokemon_form_id = pokemon_forms.id AND local_language_id = 5) AS name_fr, " + "(SELECT pokemon_form_names.form_name FROM pokemon_form_names WHERE pokemon_form_names.pokemon_form_id = pokemon_forms.id AND local_language_id = 8) AS name_it, " + "(SELECT pokemon_form_names.form_name FROM pokemon_form_names WHERE pokemon_form_names.pokemon_form_id = pokemon_forms.id AND local_language_id = 6) AS name_de, " + "(SELECT pokemon_form_names.form_name FROM pokemon_form_names WHERE pokemon_form_names.pokemon_form_id = pokemon_forms.id AND local_language_id = 7) AS name_es, " + "(SELECT pokemon_form_names.form_name FROM pokemon_form_names WHERE pokemon_form_names.pokemon_form_id = pokemon_forms.id AND local_language_id = 3) AS name_ko, " + "form_identifier, " + "(SELECT height FROM pokemon WHERE id = pokemon_id) AS height, " + "(SELECT weight FROM pokemon WHERE id = pokemon_id) AS weight, " + "(SELECT base_experience FROM pokemon WHERE id = pokemon_id) AS experience " + "FROM pokemon_forms"); while (rdForms.Read()) { int id = Convert.ToInt32(rdForms["id"]); int NationalDex = Convert.ToInt32(rdForms["NationalDex"]); byte FormValue = Convert.ToByte(rdForms["FormValue"]); string form_identifier = rdForms["form_identifier"].ToString(); int height = Convert.ToInt32(rdForms["height"]); int weight = Convert.ToInt32(rdForms["weight"]); int experience = Convert.ToInt32(rdForms["experience"]); if (formValueMap.ContainsKey(id)) FormValue = formValueMap[id]; Form f = new Form(null, id, NationalDex, FormValue, GetLocalizedString(rdForms, "name_"), form_identifier, height, weight, experience ); db.PokedexInsertForm(f); Console.WriteLine("Inserted {0} {1} {2} {3} {4} {5:0.0}m {6:0.0}kg {7}", f.ID, f.SpeciesID, f.Value, f.Name.ToString(), f.Suffix, f.Height * 0.1f, f.Weight * 0.1f, f.Experience); } rdForms.Close(); // pkmncf_pokedex_pokemon_form_stats for (int generation = 1; generation <= GENERATIONS; generation++) { string filename = String.Format("form_stats{0}.txt", generation); ProcessTSV(filename, 15, row => { int[] fieldsInt = row.Fields.Select(s => Convert.ToInt32(s)).ToArray(); FormStats f = new FormStats(null, fieldsInt[0], (Generations)generation, fieldsInt[1], fieldsInt[2], new IntStatValues(fieldsInt[3], fieldsInt[4], fieldsInt[5], fieldsInt[6], fieldsInt[7], fieldsInt[8]), new ByteStatValues((byte)fieldsInt[9], (byte)fieldsInt[10], (byte)fieldsInt[11], (byte)fieldsInt[12], (byte)fieldsInt[13], (byte)fieldsInt[14]) ); db.PokedexInsertFormStats(f); Console.WriteLine("Inserted stats for {0} gen {1}", f.FormID, (int)f.MinGeneration); }); } // todo: pkmncf_pokedex_pokemon_evolutions // pkmncf_pokedex_types SQLiteDataReader rdTypes = (SQLiteDataReader)connVeekun.ExecuteReader("SELECT id, damage_class_id, " + "(SELECT name FROM type_names WHERE type_names.type_id = types.id AND local_language_id = 1) AS name_ja, " + "(SELECT name FROM type_names WHERE type_names.type_id = types.id AND local_language_id = 9) AS name_en, " + "(SELECT name FROM type_names WHERE type_names.type_id = types.id AND local_language_id = 5) AS name_fr, " + "(SELECT name FROM type_names WHERE type_names.type_id = types.id AND local_language_id = 8) AS name_it, " + "(SELECT name FROM type_names WHERE type_names.type_id = types.id AND local_language_id = 6) AS name_de, " + "(SELECT name FROM type_names WHERE type_names.type_id = types.id AND local_language_id = 7) AS name_es, " + "(SELECT name FROM type_names WHERE type_names.type_id = types.id AND local_language_id = 3) AS name_ko " + "FROM types ORDER BY id"); // http://stackoverflow.com/questions/27156585/failed-to-enable-constraints-without-dataadapter while (rdTypes.Read()) { int id = Convert.ToInt32(rdTypes["id"]); PkmnFoundations.Pokedex.Type t = new PkmnFoundations.Pokedex.Type(null, id, GetLocalizedString(rdTypes, "name_"), GetDamageClass(rdTypes)); db.PokedexInsertType(t); Console.WriteLine("Inserted type {0} {1} {2}", t.ID, t.Name.ToString(), t.DamageClass); } rdTypes.Close(); // pkmncf_pokedex_moves SQLiteDataReader rdMoves = (SQLiteDataReader)connVeekun.ExecuteReader("SELECT id, type_id, " + "(SELECT name FROM move_names WHERE move_names.move_id = moves.id AND local_language_id = 1) AS name_ja, " + "(SELECT name FROM move_names WHERE move_names.move_id = moves.id AND local_language_id = 9) AS name_en, " + "(SELECT name FROM move_names WHERE move_names.move_id = moves.id AND local_language_id = 5) AS name_fr, " + "(SELECT name FROM move_names WHERE move_names.move_id = moves.id AND local_language_id = 8) AS name_it, " + "(SELECT name FROM move_names WHERE move_names.move_id = moves.id AND local_language_id = 6) AS name_de, " + "(SELECT name FROM move_names WHERE move_names.move_id = moves.id AND local_language_id = 7) AS name_es, " + "(SELECT name FROM move_names WHERE move_names.move_id = moves.id AND local_language_id = 3) AS name_ko, " + "damage_class_id, power, pp, accuracy, priority, target_id FROM moves"); while (rdMoves.Read()) { int id = Convert.ToInt32(rdMoves["id"]); int type_id = Convert.ToInt32(rdMoves["type_id"]); int damage_class_id = Convert.ToInt32(rdMoves["damage_class_id"]); short power = DatabaseExtender.Cast(rdMoves["power"]) ?? 0; short pp = DatabaseExtender.Cast(rdMoves["pp"]) ?? 0; short accuracy = DatabaseExtender.Cast(rdMoves["accuracy"]) ?? 0; short priority = Convert.ToInt16(rdMoves["priority"]); int target_id = Convert.ToInt32(rdMoves["target_id"]); Move m = new Move(null, id, type_id, GetLocalizedString(rdMoves, "name_"), (DamageClass)damage_class_id, power, pp, accuracy, priority, (BattleTargets)target_id ); db.PokedexInsertMove(m); Console.WriteLine("Inserted move {0} {1}", m.ID, m.Name.ToString()); } // pkmncf_pokedex_abilities SQLiteDataReader rdAbilities = (SQLiteDataReader)connVeekun.ExecuteReader("SELECT id, " + "(SELECT name FROM ability_names WHERE ability_names.ability_id = abilities.id AND local_language_id = 1) AS name_ja, " + "(SELECT name FROM ability_names WHERE ability_names.ability_id = abilities.id AND local_language_id = 9) AS name_en, " + "(SELECT name FROM ability_names WHERE ability_names.ability_id = abilities.id AND local_language_id = 5) AS name_fr, " + "(SELECT name FROM ability_names WHERE ability_names.ability_id = abilities.id AND local_language_id = 8) AS name_it, " + "(SELECT name FROM ability_names WHERE ability_names.ability_id = abilities.id AND local_language_id = 6) AS name_de, " + "(SELECT name FROM ability_names WHERE ability_names.ability_id = abilities.id AND local_language_id = 7) AS name_es, " + "(SELECT name FROM ability_names WHERE ability_names.ability_id = abilities.id AND local_language_id = 3) AS name_ko " + "FROM abilities WHERE is_main_series = 1"); while (rdAbilities.Read()) { int id = Convert.ToInt32(rdAbilities["id"]); Ability a = new Ability(null, id, GetLocalizedString(rdAbilities, "name_") ); db.PokedexInsertAbility(a); Console.WriteLine("Inserted ability {0} {1}", a.Value, a.Name.ToString()); } rdAbilities.Close(); // pkmncf_pokedex_pokemon_form_abilities for (int generation = 3; generation <= GENERATIONS; generation++) { string filename = String.Format("form_abilities{0}.txt", generation); ProcessTSV(filename, 4, row => { int[] fieldsInt = row.Fields.Select(s => Convert.ToInt32(s)).ToArray(); FormAbilities f = new FormAbilities(null, fieldsInt[0], (Generations)generation, fieldsInt[1], fieldsInt[2], fieldsInt[3] ); db.PokedexInsertFormAbilities(f); Console.WriteLine("Inserted abilities for {0} gen {1}", f.FormID, (int)f.MinGeneration); }); } // pkmncf_pokedex_items Dictionary items = new Dictionary(); for (int generation = 3; generation <= GENERATIONS; generation++) { string filename = String.Format("items{0}.txt", generation); ProcessTSV(filename, 3, row => { string[] fields = row.Fields; int id, thisGenId; string name = fields[1]; if (!Int32.TryParse(fields[0], out thisGenId) || !Int32.TryParse(fields[2], out id)) { Console.WriteLine("{0} line {1} has bad format, skipped.", filename, row.LineNumber); return; } ItemLoading theItem = null; if (!items.ContainsKey(id)) { theItem = new ItemLoading(id, name); items.Add(id, theItem); } theItem = theItem ?? items[id]; theItem.Name = name; // prefer newer names where available theItem.SetGenerationValue(thisGenId, generation); }); } // Pokeball IDs: ProcessTSV("items_balls.txt", 3, row => { string[] fields = row.Fields; int id, ballId; string name = fields[1]; if (!Int32.TryParse(fields[0], out ballId) || !Int32.TryParse(fields[2], out id)) { Console.WriteLine("{0} line {1} has bad format, skipped.", "items_balls.txt", row.LineNumber); return; } ItemLoading theItem = null; if (!items.ContainsKey(id)) { theItem = new ItemLoading(id, name); items.Add(id, theItem); } theItem = theItem ?? items[id]; if (theItem.Name == null) theItem.Name = name; theItem.PokeballValue = ballId; }); // lookup Veekun ID number against some generation or another. Dictionary items3 = items .Where(i => i.Value.Value3 != null && i.Value.NameLocalized == null) .ToDictionary(i => (int)i.Value.Value3, i => i.Value); Dictionary items4 = items .Where(i => i.Value.Value4 != null && i.Value.NameLocalized == null) .ToDictionary(i => (int)i.Value.Value4, i => i.Value); Dictionary items5 = items .Where(i => i.Value.Value5 != null && i.Value.NameLocalized == null) .ToDictionary(i => (int)i.Value.Value5, i => i.Value); Dictionary items6 = items .Where(i => i.Value.Value6 != null && i.Value.NameLocalized == null) .ToDictionary(i => (int)i.Value.Value6, i => i.Value); // veekun has incorrect Gen3 indices for Helix/Dome fossil. // (Or they disagree with Bulbapedia which is my primary source) SQLiteDataReader rdItems = (SQLiteDataReader)connVeekun.ExecuteReader("SELECT id, cost, " + "(SELECT game_index FROM item_game_indices WHERE item_id = items.id AND generation_id = 3 AND NOT item_id IN (101, 102)) AS value3, " + "(SELECT game_index FROM item_game_indices WHERE item_id = items.id AND generation_id = 4) AS value4, " + "(SELECT game_index FROM item_game_indices WHERE item_id = items.id AND generation_id = 5) AS value5, " + "(SELECT game_index FROM item_game_indices WHERE item_id = items.id AND generation_id = 6) AS value6, " + "(SELECT name FROM item_names WHERE item_names.item_id = items.id AND local_language_id = 1) AS name_ja, " + "(SELECT name FROM item_names WHERE item_names.item_id = items.id AND local_language_id = 9) AS name_en, " + "(SELECT name FROM item_names WHERE item_names.item_id = items.id AND local_language_id = 5) AS name_fr, " + "(SELECT name FROM item_names WHERE item_names.item_id = items.id AND local_language_id = 8) AS name_it, " + "(SELECT name FROM item_names WHERE item_names.item_id = items.id AND local_language_id = 6) AS name_de, " + "(SELECT name FROM item_names WHERE item_names.item_id = items.id AND local_language_id = 7) AS name_es, " + "(SELECT name FROM item_names WHERE item_names.item_id = items.id AND local_language_id = 3) AS name_ko " + "FROM items"); Dictionary[] itemsGeneration = new Dictionary[] { null, null, items3, items4, items5, items6 }; while (rdItems.Read()) { List toProcess = new List(4); for (int generation = 3; generation <= GENERATIONS; generation++) { string col = String.Format("value{0}", generation); if (!(rdItems[col] is DBNull)) { Dictionary dict = itemsGeneration[generation - 1]; int value = Convert.ToInt32(rdItems[col]); if (dict.ContainsKey(value)) { ItemLoading il = dict[value]; il.NameLocalized = GetLocalizedString(rdItems, "name_"); il.Price = Convert.ToInt32(rdItems["cost"]); } } } } rdItems.Close(); foreach (ItemLoading il in items.Values) { LocalizedString name = il.NameLocalized; if (name == null) { name = new LocalizedString() { { "EN", il.Name } }; Console.WriteLine("Veekun database missing item {0} {1}. Non-English translations will be missing.", il.ID, name); } Item i = new Item(null, il.ID, il.Value3, il.Value4, il.Value5, il.Value6, il.PokeballValue, il.Price, name); db.PokedexInsertItem(i); Console.WriteLine("Inserted item {0} {1}", i.ID, i.Name.ToString()); } // pkmncf_pokedex_ribbons Dictionary ribbons = new Dictionary(); if (!ProcessTSV("ribbons.txt", 3, row => { string[] fields = row.Fields; int id = Convert.ToInt32(fields[0]); ribbons.Add(id, new RibbonLoading(id, fields[1], fields[2])); })) Console.WriteLine("ribbons.txt not found. Not inserting any ribbons."); else { for (int generation = 3; generation <= GENERATIONS; generation++) { string filename = String.Format("ribbon_positions{0}.txt", generation); ProcessTSV(filename, 2, row => { string[] fields = row.Fields; int id = Convert.ToInt32(fields[0]); int position = Convert.ToInt32(fields[1]); if (!ribbons.ContainsKey(id)) { Console.WriteLine("Error: Ribbon ID {0} contained in {1} but not in ribbons.txt!", id, filename); return; } RibbonLoading r = ribbons[id]; r.SetGenerationPosition(position, generation); }); } foreach (KeyValuePair pair in ribbons) { RibbonLoading r = pair.Value; db.PokedexInsertRibbon(new Ribbon(null, r.ID, new LocalizedString() { { "EN", r.Name } }, new LocalizedString() { { "EN", r.Description } }, r.Position3, r.Position4, r.Position5, r.Position6, null, null, null, null )); Console.WriteLine("Inserted ribbon {0} {1}", r.ID, r.Name); } } // pkmncf_pokedex_regions ProcessTSV("regions.txt", 2, row => { string[] fields = row.Fields; int id = Convert.ToInt32(fields[0]); Region r = new Region(null, id, new LocalizedString() { { "EN", fields[1] } }); db.PokedexInsertRegion(r); Console.WriteLine("Inserted region {0} {1}", r.ID, r.Name); }); // pkmncf_pokedex_locations SQLiteDataReader rdLocations = (SQLiteDataReader)connVeekun.ExecuteReader("SELECT id, region_id, " + "(SELECT game_index FROM location_game_indices WHERE location_id = locations.id AND generation_id = 3) AS value3, " + "(SELECT game_index FROM location_game_indices WHERE location_id = locations.id AND generation_id = 4) AS value4, " + "(SELECT game_index FROM location_game_indices WHERE location_id = locations.id AND generation_id = 5) AS value5, " + "(SELECT game_index FROM location_game_indices WHERE location_id = locations.id AND generation_id = 6) AS value6, " + "(SELECT name FROM location_names WHERE location_names.location_id = locations.id AND local_language_id = 1) AS name_ja, " + "(SELECT name FROM location_names WHERE location_names.location_id = locations.id AND local_language_id = 9) AS name_en, " + "(SELECT name FROM location_names WHERE location_names.location_id = locations.id AND local_language_id = 5) AS name_fr, " + "(SELECT name FROM location_names WHERE location_names.location_id = locations.id AND local_language_id = 8) AS name_it, " + "(SELECT name FROM location_names WHERE location_names.location_id = locations.id AND local_language_id = 6) AS name_de, " + "(SELECT name FROM location_names WHERE location_names.location_id = locations.id AND local_language_id = 7) AS name_es, " + "(SELECT name FROM location_names WHERE location_names.location_id = locations.id AND local_language_id = 3) AS name_ko " + "FROM locations WHERE id NOT IN (522, 523, 524)"); // 522, 523, and 524 are duplicates of Kanto routes 19, 20, and 21. // todo: gba/colo/xd encounter location values while (rdLocations.Read()) { Location l = new Location(null, Convert.ToInt32(rdLocations["id"]), VeekunLocationToRegion(rdLocations), (int ?)DatabaseExtender.Cast(rdLocations["value3"]), null, null, (int?)DatabaseExtender.Cast(rdLocations["value4"]), (int?)DatabaseExtender.Cast(rdLocations["value5"]), (int?)DatabaseExtender.Cast(rdLocations["value6"]), GetLocalizedString(rdLocations, "name_") ); db.PokedexInsertLocation(l); Console.WriteLine("Inserted location {0} {1}", l.ID, l.Name); } rdLocations.Close(); connVeekun.Close(); } #if DEBUG Console.ReadKey(); #endif } private static string[] LANGS = { "JA", "EN", "FR", "IT", "DE", "ES", "KO" }; private static LocalizedString GetLocalizedString(IDataReader reader, string column) { LocalizedString result = new LocalizedString(); foreach (string lang in LANGS) { string col = column + lang.ToLowerInvariant(); if (reader[col] is DBNull) continue; result.Add(lang, (string)reader[col]); } return result; } private static DamageClass GetDamageClass(IDataReader reader) { if (reader["damage_class_id"] is DBNull) return DamageClass.None; return (DamageClass)(Convert.ToInt32(reader["damage_class_id"]) - 1); } private static bool ProcessTSV(string filename, int requiredFields, Action action) { if (!File.Exists(filename)) { Console.WriteLine("File {0} not found, skipped.", filename); return false; } using (FileStream fs = File.Open(filename, FileMode.Open)) { StreamReader sr = new StreamReader(fs, Encoding.UTF8); string line; int lineNumber = 0; int validLineNumber = 0; while ((line = sr.ReadLine()) != null) { string[] fields = line.Split('\t'); if (fields.Length < requiredFields) { Console.WriteLine("File {0} line {1} has too few fields, skipped.", filename, lineNumber); lineNumber++; continue; } action(new TsvRow(lineNumber, validLineNumber, fields)); lineNumber++; validLineNumber++; } fs.Close(); } return true; } private static int VeekunLocationToRegion(SQLiteDataReader reader) { int id = Convert.ToInt32(reader["id"]); long? region = DatabaseExtender.Cast(reader["region_id"]); if (region == null) // not set, usually event { if (id == 256) return 2; // kanto if (id == 257) return 3; // johto if (id == 258) return 4; // hoenn if (id == 259) return 7; // sinnoh if (id == 260) return 5; // "distant land" (only used for orre?) if (id == 261) return 7; // traveling man (happini?) if (id == 262) return 7; // riley if (id == 263) return 7; // cynthia if (id == 342) return 3; // mr. pokemon if (id == 343) return 3; // primo return 1; } if (region == 1) // kanto and seviis { if (id >= 491 && id <= 497) return 6; // seven island unown chambers if (id >= 500 && id <= 521) return 6; // sevii islands if (id >= 526 && id <= 529) return 6; // sevii islands return 2; } if (region == 2) return 3; // johto if (region == 3) return 4; // hoenn if (region == 4) return 7; // sinnoh if (region == 5) return 8; // unova if (region == 6) return 9; // kalos return (int)region + 3; // for now, assume veekun won't skip more regions. } } internal class ItemLoading { public ItemLoading(int id, string name) { ID = id; Name = name; Value3 = Value4 = Value5 = Value6 = null; NameLocalized = null; PokeballValue = null; } public int ID; public string Name; public LocalizedString NameLocalized; public int? Value3, Value4, Value5, Value6; public int Price; public int? PokeballValue; public void SetGenerationValue(int ? value, int generation) { switch (generation) { case 3: Value3 = value; break; case 4: Value4 = value; break; case 5: Value5 = value; break; case 6: Value6 = value; break; } } } internal class RibbonLoading { public RibbonLoading(int id, string name, string description) { ID = id; Name = name; Description = description; Position3 = Position4 = Position5 = Position6 = null; } public int ID; public string Name; public string Description; public int? Position3, Position4, Position5, Position6; public void SetGenerationPosition(int? position, int generation) { switch (generation) { case 3: Position3 = position; break; case 4: Position4 = position; break; case 5: Position5 = position; break; case 6: Position6 = position; break; } } } internal class TsvRow { public TsvRow(int lineNumber, int validLineNumber, string[] fields) { LineNumber = lineNumber; ValidLineNumber = validLineNumber; Fields = fields; } public int LineNumber; public int ValidLineNumber; public string[] Fields; } } ================================================ FILE: VeekunImport/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("VeekunImport")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("VeekunImport")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1644dc02-2772-48f6-b123-e611638dbab0")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: VeekunImport/VeekunImport.csproj ================================================  Debug AnyCPU {2A761C4F-00C2-45D5-B4CA-C41558CEB2DF} Exe Properties VeekunImport VeekunImport v4.0 512 publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false false true AnyCPU true full false bin\Debug\ DEBUG;TRACE prompt 4 AnyCPU pdbonly true bin\Release\ TRACE prompt 4 true ..\packages\Stub.System.Data.SQLite.Core.NetFramework.1.0.115.5\lib\net40\System.Data.SQLite.dll ..\packages\System.Data.SQLite.Linq.1.0.115.5\lib\net40\System.Data.SQLite.Linq.dll Always Always Always Always Always Always Always Always Always Always Always Always Always Always Always Always Always Always Always Always Always Always {408efc7e-c6b0-4160-8628-2679e34385ce} Library False .NET Framework 3.5 SP1 false This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. ================================================ FILE: VeekunImport/app.config ================================================ 
================================================ FILE: VeekunImport/countries4.txt ================================================ 1 AF Afghanistan 2 AL Albania 3 DZ Algeria 6 AO Angola 8 AG Antigua and Barbuda 9 AR Argentina 12 AU Australia 13 AT Austria 15 BS Bahamas 16 BH Bahrain 17 BD Bangladesh 18 BB Barbados 20 BE Belgium 21 BZ Belize 22 BJ Benin 23 BM Bermuda 25 BO Bolivia 27 BW Botswana 28 BR Brazil 29 VG British Virgin Islands 31 BG Bulgaria 33 BI Burundi 34 KH Cambodia 35 CM Cameroon 36 CA Canada 40 TD Chad 42 CL Chile 43 CN China 45 CO Colombia 48 CG Congo 49 CK Cook Islands 50 CR Costa Rica 52 HR Croatia 54 CY Cyprus 55 CZ Czech Republic 56 DK Denmark 58 DM Dominica 59 DO Dominican Republic 60 EC Ecuador 61 EG Egypt 62 SV El Salvador 69 FJ Fiji 70 FI Finland 71 FR France 72 GF French Guiana 74 GA Gabon 77 DE Germany 78 GH Ghana 79 GI Gibraltar 80 GR Greece 81 GL Greenland 82 GD Grenada 83 GP Guadeloupe 85 GT Guatemala 86 GN Guinea 88 GY Guyana 89 HT Haiti 90 HN Honduras 91 HK Hong Kong 92 HU Hungary 93 IS Iceland 94 IN India 95 ID Indonesia 97 IQ Iraq 98 IE Ireland 100 IL Israel 101 IT Italy 102 JM Jamaica 103 JP Japan 104 JO Jordan 107 KE Kenya 110 KR Republic of Korea 111 KW Kuwait 115 LB Lebanon 117 LR Liberia 118 LY Libyan Arab Jamhiriya 121 LU Luxembourg 122 MO Macau 126 MY Malaysia 129 MT Malta 131 MQ Martinique 133 MU Mauritius 135 MX Mexico 140 MA Morocco 142 MM Myanmar 146 NL Netherlands 148 NC New Caledonia 149 NZ New Zealand 150 NI Nicaragua 151 NE Niger 152 NG Nigeria 156 NO Norway 157 OM Oman 158 PK Pakistan 160 PA Panama 161 PG Papua New Guinea 163 PE Peru 164 PH Philippines 166 PL Poland 167 PT Portugal 171 RO Romania 172 RU Russian Federation 179 WS Samoa 183 SN Senegal 186 SL Sierra Leone 187 SG Singapore 188 SK Slovakia 189 SI Slovenia 192 ZA South Africa 193 ES Spain 194 LK Sri Lanka 196 SR Suriname 198 SZ Swaziland 199 SE Sweden 200 CH Swiss Confederation 202 TW Taiwan 204 TZ United Republic of Tanzania 205 TH Thailand 207 TG Togo 211 TN Tunisia 212 TR Turkey 216 UG Uganda 218 AE United Arab Emirates 219 GB United Kingdom 220 US United States of America 221 VI United States Virgin Islands 222 UY Uruguay 224 VU Vanuatu 226 VE Venezuela 227 VN Vietnam ================================================ FILE: VeekunImport/countries5.txt ================================================ 1 AF Afghanistan 2 AL Albania 3 DZ Algeria 6 AO Angola 8 AG Antigua and Barbuda 9 AR Argentina 12 AU Australia 13 AT Austria 15 BS Bahamas 16 BH Bahrain 17 BD Bangladesh 18 BB Barbados 20 BE Belgium 21 BZ Belize 22 BJ Benin 23 BM Bermuda 25 BO Bolivia 27 BW Botswana 28 BR Brazil 29 VG British Virgin Islands 31 BG Bulgaria 33 BI Burundi 34 KH Cambodia 35 CM Cameroon 36 CA Canada 40 TD Chad 42 CL Chile 43 CN China 45 CO Colombia 47 CG Congo 48 CK Cook Islands 49 CR Costa Rica 51 HR Croatia 53 CY Cyprus 54 CZ Czech Republic 58 DK Denmark 60 DM Dominica 61 DO Dominican Republic 62 EC Ecuador 63 EG Egypt 64 SV El Salvador 71 FJ Fiji 72 FI Finland 73 FR France 74 GF French Guiana 76 GA Gabon 79 DE Germany 80 GH Ghana 81 GI Gibraltar 82 GR Greece 83 GL Greenland 84 GD Grenada 85 GP Guadeloupe 87 GT Guatemala 88 GN Guinea 90 GY Guyana 91 HT Haiti 92 HN Honduras 93 HU Hungary 94 IS Iceland 95 IN India 96 ID Indonesia 98 IQ Iraq 99 IE Ireland 101 IL Israel 102 IT Italy 103 JM Jamaica 105 JP Japan 106 JO Jordan 109 KE Kenya 111 KW Kuwait 115 LB Lebanon 117 LR Liberia 118 LY Libya 121 LU Luxembourg 125 MY Malaysia 128 MT Malta 130 MQ Martinique 132 MU Mauritius 134 MX Mexico 138 ME Montenegro 139 MA Morocco 141 MM Myanmar 145 NL Netherlands 147 NC New Caledonia 148 NZ New Zealand 149 NI Nicaragua 150 NE Niger 151 NG Nigeria 155 NO Norway 156 OM Oman 157 PK Pakistan 160 PA Panama 161 PG Papua New Guinea 163 PE Peru 164 PH Philippines 166 PL Poland 167 PT Portugal 170 KR South Korea 173 RO Romania 174 RU Russian Federation 181 WS Samoa 185 SN Senegal 186 RS Serbia 188 SL Sierra Leone 189 SG Singapore 190 SK Slovakia 191 SI Slovenia 194 ZA South Africa 195 ES Spain 196 LK Sri Lanka 198 SR Suriname 199 SZ Swaziland 200 SE Sweden 201 CH Switzerland 203 TW Taiwan 205 TH Thailand 206 TG Togo 210 TN Tunisia 211 TR Turkey 215 UG Uganda 217 AE United Arab Emirates 218 GB United Kingdom 219 TZ Tanzania 220 US United States of America 221 VI United States Virgin Islands 222 UY Uruguay 224 VU Vanatu 226 VE Venezuela 227 VN Vietnam ================================================ FILE: VeekunImport/families.txt ================================================ 010 172 172 000 000 0000 4 012 029 032 000 000 0000 4 013 173 173 000 000 0000 6 015 174 174 000 000 0000 6 046 236 236 000 000 0000 0 050 113 113 440 440 4319 8 056 122 122 439 439 4314 4 058 238 238 000 000 0000 8 059 239 239 000 000 0000 2 060 240 240 000 000 0000 2 071 143 143 446 446 4316 4 089 183 183 298 298 3220 4 090 185 185 438 438 4315 1 099 202 202 360 360 3221 4 115 226 226 458 458 4317 4 155 313 314 000 000 0000 4 156 315 315 406 406 4318 4 182 358 358 433 433 4320 4 ================================================ FILE: VeekunImport/families_map.txt ================================================ 001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 172 027 028 029 030 031 032 033 034 035 036 173 037 038 039 040 174 041 042 169 043 044 045 182 046 047 048 049 050 051 052 053 054 055 056 057 058 059 060 061 062 186 063 064 065 066 067 068 069 070 071 072 073 074 075 076 077 078 079 080 199 081 082 462 083 084 085 086 087 088 089 090 091 092 093 094 095 208 096 097 098 099 100 101 102 103 104 105 106 107 236 237 108 463 109 110 111 112 464 113 242 440 114 465 115 116 117 230 118 119 120 121 122 439 123 212 124 238 125 239 466 126 240 467 127 128 129 130 131 132 133 134 135 136 196 197 470 471 700 137 233 474 138 139 140 141 142 143 446 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 170 171 175 176 468 177 178 179 180 181 183 184 298 185 438 187 188 189 190 424 191 192 193 469 194 195 198 430 200 429 201 202 360 203 204 205 206 207 472 209 210 211 213 214 215 461 216 217 218 219 220 221 473 222 223 224 225 226 458 227 228 229 231 232 234 235 241 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 475 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 299 476 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 406 407 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 477 357 358 433 359 361 362 478 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 425 426 427 428 431 432 434 435 436 437 441 442 443 444 445 447 448 449 450 451 452 453 454 455 456 457 459 460 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 ================================================ FILE: VeekunImport/form_abilities3.txt ================================================ 00001 065 000 000 00002 065 000 000 00003 065 000 000 00004 066 000 000 00005 066 000 000 00006 066 000 000 00007 067 000 000 00008 067 000 000 00009 067 000 000 00010 019 000 000 00011 061 000 000 00012 014 000 000 00013 019 000 000 00014 061 000 000 00015 068 000 000 00016 051 000 000 00017 051 000 000 00018 051 000 000 00019 050 062 000 00020 050 062 000 00021 051 000 000 00022 051 000 000 00023 022 061 000 00024 022 061 000 00025 009 000 000 00026 009 000 000 00027 008 000 000 00028 008 000 000 00029 038 000 000 00030 038 000 000 00031 038 000 000 00032 038 000 000 00033 038 000 000 00034 038 000 000 00035 056 000 000 00036 056 000 000 00037 018 000 000 00038 018 000 000 00039 056 000 000 00040 056 000 000 00041 039 000 000 00042 039 000 000 00043 034 000 000 00044 034 000 000 00045 034 000 000 00046 027 000 000 00047 027 000 000 00048 014 000 000 00049 019 000 000 00050 008 071 000 00051 008 071 000 00052 053 000 000 00053 007 000 000 00054 006 013 000 00055 006 013 000 00056 072 000 000 00057 072 000 000 00058 022 018 000 00059 022 018 000 00060 011 006 000 00061 011 006 000 00062 011 006 000 00063 028 039 000 00064 028 039 000 00065 028 039 000 00066 062 000 000 00067 062 000 000 00068 062 000 000 00069 034 000 000 00070 034 000 000 00071 034 000 000 00072 029 064 000 00073 029 064 000 00074 069 005 000 00075 069 005 000 00076 069 005 000 00077 050 018 000 00078 050 018 000 00079 012 020 000 00080 012 020 000 00081 042 005 000 00082 042 005 000 00083 051 039 000 00084 050 048 000 00085 050 048 000 00086 047 000 000 00087 047 000 000 00088 001 060 000 00089 001 060 000 00090 075 000 000 00091 075 000 000 00092 026 000 000 00093 026 000 000 00094 026 000 000 00095 069 005 000 00096 015 000 000 00097 015 000 000 00098 052 075 000 00099 052 075 000 00100 043 009 000 00101 043 009 000 00102 034 000 000 00103 034 000 000 00104 069 031 000 00105 069 031 000 00106 007 000 000 00107 051 000 000 00108 020 012 000 00109 026 000 000 00110 026 000 000 00111 031 069 000 00112 031 069 000 00113 030 032 000 00114 034 000 000 00115 048 000 000 00116 033 000 000 00117 038 000 000 00118 033 041 000 00119 033 041 000 00120 035 030 000 00121 035 030 000 00122 043 000 000 00123 068 000 000 00124 012 000 000 00125 009 000 000 00126 049 000 000 00127 052 000 000 00128 022 000 000 00129 033 000 000 00130 022 000 000 00131 011 075 000 00132 007 000 000 00133 050 000 000 00134 011 000 000 00135 010 000 000 00136 018 000 000 00137 036 000 000 00138 033 075 000 00139 033 075 000 00140 033 004 000 00141 033 004 000 00142 069 046 000 00143 017 047 000 00144 046 000 000 00145 046 000 000 00146 046 000 000 00147 061 000 000 00148 061 000 000 00149 039 000 000 00150 046 000 000 00151 028 000 000 00152 065 000 000 00153 065 000 000 00154 065 000 000 00155 066 000 000 00156 066 000 000 00157 066 000 000 00158 067 000 000 00159 067 000 000 00160 067 000 000 00161 050 051 000 00162 050 051 000 00163 015 051 000 00164 015 051 000 00165 068 048 000 00166 068 048 000 00167 068 015 000 00168 068 015 000 00169 039 000 000 00170 010 035 000 00171 010 035 000 00172 009 000 000 00173 056 000 000 00174 056 000 000 00175 055 032 000 00176 055 032 000 00177 028 048 000 00178 028 048 000 00179 009 000 000 00180 009 000 000 00181 009 000 000 00182 034 000 000 00183 047 037 000 00184 047 037 000 00185 005 069 000 00186 011 006 000 00187 034 102 000 00188 034 102 000 00189 034 102 000 00190 050 053 000 00191 034 000 000 00192 034 000 000 00193 003 014 000 00194 006 011 000 00195 006 011 000 00196 028 000 000 00197 028 000 000 00198 015 000 000 00199 012 020 000 00200 026 000 000 00201 026 000 000 00202 023 000 000 00203 039 048 000 00204 005 000 000 00205 005 000 000 00206 032 050 000 00207 052 008 000 00208 069 005 000 00209 022 050 000 00210 022 000 000 00211 038 033 000 00212 068 000 000 00213 005 000 000 00214 068 062 000 00215 039 051 000 00216 053 000 000 00217 062 000 000 00218 040 049 000 00219 040 049 000 00220 012 000 000 00221 012 000 000 00222 055 030 000 00223 055 000 000 00224 021 000 000 00225 072 055 000 00226 033 011 000 00227 051 005 000 00228 048 018 000 00229 048 018 000 00230 033 000 000 00231 053 000 000 00232 005 000 000 00233 036 000 000 00234 022 000 000 00235 020 000 000 00236 062 000 000 00237 022 000 000 00238 012 000 000 00239 009 000 000 00240 049 000 000 00241 047 000 000 00242 030 032 000 00243 046 000 000 00244 046 000 000 00245 046 000 000 00246 062 000 000 00247 061 000 000 00248 045 000 000 00249 046 000 000 00250 046 000 000 00251 030 000 000 00252 065 000 000 00253 065 000 000 00254 065 000 000 00255 066 000 000 00256 066 000 000 00257 066 000 000 00258 067 000 000 00259 067 000 000 00260 067 000 000 00261 050 000 000 00262 022 000 000 00263 053 000 000 00264 053 000 000 00265 019 000 000 00266 061 000 000 00267 068 000 000 00268 061 000 000 00269 019 000 000 00270 033 044 000 00271 033 044 000 00272 033 044 000 00273 034 048 000 00274 034 048 000 00275 034 048 000 00276 062 000 000 00277 062 000 000 00278 051 000 000 00279 051 000 000 00280 028 036 000 00281 028 036 000 00282 028 036 000 00283 033 000 000 00284 022 000 000 00285 027 000 000 00286 027 000 000 00287 054 000 000 00288 072 000 000 00289 054 000 000 00290 014 000 000 00291 003 000 000 00292 025 000 000 00293 043 000 000 00294 043 000 000 00295 043 000 000 00296 047 062 000 00297 047 062 000 00298 047 037 000 00299 005 042 000 00300 056 000 000 00301 056 000 000 00302 051 000 000 00303 052 022 000 00304 005 069 000 00305 005 069 000 00306 005 069 000 00307 074 000 000 00308 074 000 000 00309 009 031 000 00310 009 031 000 00311 057 000 000 00312 058 000 000 00313 035 068 000 00314 012 000 000 00315 030 038 000 00316 064 060 000 00317 064 060 000 00318 024 000 000 00319 024 000 000 00320 041 012 000 00321 041 012 000 00322 012 000 000 00323 040 000 000 00324 073 000 000 00325 047 020 000 00326 047 020 000 00327 020 000 000 00328 052 071 000 00329 026 000 000 00330 026 000 000 00331 008 000 000 00332 008 000 000 00333 030 000 000 00334 030 000 000 00335 017 000 000 00336 061 000 000 00337 026 000 000 00338 026 000 000 00339 012 000 000 00340 012 000 000 00341 052 075 000 00342 052 075 000 00343 026 000 000 00344 026 000 000 00345 021 000 000 00346 021 000 000 00347 004 000 000 00348 004 000 000 00349 033 000 000 00350 063 000 000 00351 059 000 000 00352 016 000 000 00353 015 000 000 00354 015 000 000 00355 026 000 000 00356 046 000 000 00357 034 000 000 00358 026 000 000 00359 046 000 000 00360 023 000 000 00361 039 000 000 00362 039 000 000 00363 047 000 000 00364 047 000 000 00365 047 000 000 00366 075 000 000 00367 033 000 000 00368 033 000 000 00369 033 069 000 00370 033 000 000 00371 069 000 000 00372 069 000 000 00373 022 000 000 00374 029 000 000 00375 029 000 000 00376 029 000 000 00377 029 000 000 00378 029 000 000 00379 029 000 000 00380 026 000 000 00381 026 000 000 00382 002 000 000 00383 070 000 000 00384 076 000 000 00385 032 000 000 00386 046 000 000 10001 026 000 000 10002 026 000 000 10003 026 000 000 10004 026 000 000 10005 026 000 000 10006 026 000 000 10007 026 000 000 10008 026 000 000 10009 026 000 000 10010 026 000 000 10011 026 000 000 10012 026 000 000 10013 026 000 000 10014 026 000 000 10015 026 000 000 10016 026 000 000 10017 026 000 000 10018 026 000 000 10019 026 000 000 10020 026 000 000 10021 026 000 000 10022 026 000 000 10023 026 000 000 10024 026 000 000 10025 026 000 000 10026 026 000 000 10027 026 000 000 10028 059 000 000 10029 059 000 000 10030 059 000 000 10031 046 000 000 10032 046 000 000 10033 046 000 000 ================================================ FILE: VeekunImport/form_abilities4.txt ================================================ 00016 051 077 000 00017 051 077 000 00018 051 077 000 00029 038 079 000 00030 038 079 000 00031 038 079 000 00032 038 079 000 00033 038 079 000 00034 038 079 000 00035 056 098 000 00036 056 098 000 00046 027 087 000 00047 027 087 000 00048 014 110 000 00049 019 110 000 00052 053 101 000 00053 007 101 000 00056 072 083 000 00057 072 083 000 00066 062 099 000 00067 062 099 000 00068 062 099 000 00086 047 093 000 00087 047 093 000 00090 075 092 000 00091 075 092 000 00096 015 108 000 00097 015 108 000 00106 007 120 000 00107 051 089 000 00114 034 102 000 00115 048 113 000 00116 033 097 000 00117 038 097 000 00122 043 111 000 00123 068 101 000 00124 012 108 000 00127 052 104 000 00128 022 083 000 00133 050 091 000 00137 036 088 000 00173 056 098 000 00187 034 102 000 00188 034 102 000 00189 034 102 000 00191 034 094 000 00192 034 094 000 00198 015 105 000 00210 022 095 000 00212 068 101 000 00213 005 082 000 00216 053 095 000 00217 062 095 000 00220 012 081 000 00221 012 081 000 00223 055 097 000 00224 021 097 000 00230 033 097 000 00233 036 088 000 00234 022 119 000 00235 020 101 000 00236 062 080 000 00237 022 101 000 00238 012 108 000 00241 047 113 000 00261 050 095 000 00262 022 095 000 00263 053 082 000 00264 053 082 000 00285 027 090 000 00286 027 090 000 00300 056 096 000 00301 056 096 000 00302 051 100 000 00314 012 110 000 00322 012 086 000 00323 040 116 000 00327 020 077 000 00339 012 107 000 00340 012 107 000 00353 015 119 000 00354 015 119 000 00357 034 094 000 00359 046 105 000 00361 039 115 000 00362 039 115 000 00363 047 115 000 00364 047 115 000 00365 047 115 000 00387 065 000 000 00388 065 000 000 00389 065 000 000 00390 066 000 000 00391 066 000 000 00392 066 000 000 00393 067 000 000 00394 067 000 000 00395 067 000 000 00396 051 000 000 00397 022 000 000 00398 022 000 000 00399 086 109 000 00400 086 109 000 00401 061 000 000 00402 068 000 000 00403 079 022 000 00404 079 022 000 00405 079 022 000 00406 030 038 000 00407 030 038 000 00408 104 000 000 00409 104 000 000 00410 005 000 000 00411 005 000 000 00412 061 000 000 00413 107 000 000 00414 068 000 000 00415 118 000 000 00416 046 000 000 00417 050 053 000 00418 033 000 000 00419 033 000 000 00420 034 000 000 00421 122 000 000 00422 060 114 000 00423 060 114 000 00424 101 053 000 00425 106 084 000 00426 106 084 000 00427 050 103 000 00428 056 103 000 00429 026 000 000 00430 015 105 000 00431 007 020 000 00432 047 020 000 00433 026 000 000 00434 001 106 000 00435 001 106 000 00436 026 085 000 00437 026 085 000 00438 005 069 000 00439 043 111 000 00440 030 032 000 00441 051 077 000 00442 046 000 000 00443 008 000 000 00444 008 000 000 00445 008 000 000 00446 053 047 000 00447 080 039 000 00448 080 039 000 00449 045 000 000 00450 045 000 000 00451 004 097 000 00452 004 097 000 00453 107 087 000 00454 107 087 000 00455 026 000 000 00456 033 114 000 00457 033 114 000 00458 033 011 000 00459 117 000 000 00460 117 000 000 00461 046 000 000 00462 042 005 000 00463 020 012 000 00464 031 116 000 00465 034 102 000 00466 078 000 000 00467 049 000 000 00468 055 032 000 00469 003 110 000 00470 102 000 000 00471 081 000 000 00472 052 008 000 00473 012 081 000 00474 091 088 000 00475 080 000 000 00476 005 042 000 00477 046 000 000 00478 081 000 000 00479 026 000 000 00480 026 000 000 00481 026 000 000 00482 026 000 000 00483 046 000 000 00484 046 000 000 00485 018 000 000 00486 112 000 000 00487 046 000 000 00488 026 000 000 00489 093 000 000 00490 093 000 000 00491 123 000 000 00492 030 000 000 00493 121 000 000 10034 061 000 000 10035 061 000 000 10036 107 000 000 10037 107 000 000 10038 122 000 000 10039 060 114 000 10040 060 114 000 10041 121 000 000 10042 121 000 000 10043 121 000 000 10044 121 000 000 10045 121 000 000 10046 121 000 000 10047 121 000 000 10048 121 000 000 10049 121 000 000 10050 121 000 000 10051 121 000 000 10052 121 000 000 10053 121 000 000 10054 121 000 000 10055 121 000 000 10056 121 000 000 10057 121 000 000 10058 026 000 000 10059 026 000 000 10060 026 000 000 10061 026 000 000 10062 026 000 000 10063 026 000 000 10064 032 000 000 10065 009 000 000 ================================================ FILE: VeekunImport/form_abilities5.txt ================================================ 00001 065 000 034 00002 065 000 034 00003 065 000 034 00004 066 000 094 00005 066 000 094 00006 066 000 094 00007 067 000 044 00008 067 000 044 00009 067 000 044 00010 019 000 050 00011 061 000 000 00012 014 000 110 00013 019 000 050 00014 061 000 000 00015 068 000 097 00016 051 077 145 00017 051 077 145 00018 051 077 145 00019 050 062 055 00020 050 062 055 00021 051 000 097 00022 051 000 097 00023 022 061 127 00024 022 061 127 00025 009 000 031 00026 009 000 031 00027 008 000 146 00028 008 000 146 00029 038 079 055 00030 038 079 055 00031 038 079 125 00032 038 079 055 00033 038 079 055 00034 038 079 125 00035 056 098 132 00036 056 098 109 00037 018 000 070 00038 018 000 070 00039 056 000 132 00040 056 000 119 00041 039 000 151 00042 039 000 151 00043 034 000 050 00044 034 000 001 00045 034 000 027 00046 027 087 006 00047 027 087 006 00048 014 110 050 00049 019 110 147 00050 008 071 159 00051 008 071 159 00052 053 101 127 00053 007 101 127 00054 006 013 033 00055 006 013 033 00056 072 083 128 00057 072 083 128 00058 022 018 154 00059 022 018 154 00060 011 006 033 00061 011 006 033 00062 011 006 033 00063 028 039 098 00064 028 039 098 00065 028 039 098 00066 062 099 080 00067 062 099 080 00068 062 099 080 00069 034 000 082 00070 034 000 082 00071 034 000 082 00072 029 064 044 00073 029 064 044 00074 069 005 008 00075 069 005 008 00076 069 005 008 00077 050 018 049 00078 050 018 049 00079 012 020 144 00080 012 020 144 00081 042 005 148 00082 042 005 148 00083 051 039 128 00084 050 048 077 00085 050 048 077 00086 047 093 115 00087 047 093 115 00088 001 060 143 00089 001 060 143 00090 075 092 142 00091 075 092 142 00092 026 000 000 00093 026 000 000 00094 026 000 000 00095 069 005 133 00096 015 108 039 00097 015 108 039 00098 052 075 125 00099 052 075 125 00100 043 009 106 00101 043 009 106 00102 034 000 139 00103 034 000 139 00104 069 031 004 00105 069 031 004 00106 007 120 084 00107 051 089 039 00108 020 012 013 00109 026 000 000 00110 026 000 000 00111 031 069 120 00112 031 069 120 00113 030 032 131 00114 034 102 144 00115 048 113 039 00116 033 097 006 00117 038 097 006 00118 033 041 031 00119 033 041 031 00120 035 030 148 00121 035 030 148 00122 043 111 101 00123 068 101 080 00124 012 108 087 00125 009 000 072 00126 049 000 072 00127 052 104 153 00128 022 083 125 00129 033 000 155 00130 022 000 153 00131 011 075 093 00132 007 000 150 00133 050 091 107 00134 011 000 093 00135 010 000 095 00136 018 000 062 00137 036 088 148 00138 033 075 133 00139 033 075 133 00140 033 004 133 00141 033 004 133 00142 069 046 127 00143 017 047 082 00144 046 000 081 00145 046 000 031 00146 046 000 049 00147 061 000 063 00148 061 000 063 00149 039 000 136 00150 046 000 127 00151 028 000 000 00152 065 000 102 00153 065 000 102 00154 065 000 102 00155 066 000 018 00156 066 000 018 00157 066 000 018 00158 067 000 125 00159 067 000 125 00160 067 000 125 00161 050 051 119 00162 050 051 119 00163 015 051 110 00164 015 051 110 00165 068 048 155 00166 068 048 089 00167 068 015 097 00168 068 015 097 00169 039 000 151 00170 010 035 011 00171 010 035 011 00172 009 000 031 00173 056 098 132 00174 056 000 132 00175 055 032 105 00176 055 032 105 00177 028 048 156 00178 028 048 156 00179 009 000 057 00180 009 000 057 00181 009 000 057 00182 034 000 131 00183 047 037 157 00184 047 037 157 00185 005 069 155 00186 011 006 002 00187 034 102 151 00188 034 102 151 00189 034 102 151 00190 050 053 092 00191 034 094 048 00192 034 094 048 00193 003 014 119 00194 006 011 109 00195 006 011 109 00196 028 000 156 00197 028 000 039 00198 015 105 158 00199 012 020 144 00200 026 000 000 00201 026 000 000 00202 023 000 140 00203 039 048 157 00204 005 000 142 00205 005 000 142 00206 032 050 155 00207 052 008 017 00208 069 005 125 00209 022 050 155 00210 022 095 155 00211 038 033 022 00212 068 101 135 00213 005 082 126 00214 068 062 153 00215 039 051 124 00216 053 095 118 00217 062 095 127 00218 040 049 133 00219 040 049 133 00220 012 081 047 00221 012 081 047 00222 055 030 144 00223 055 097 141 00224 021 097 141 00225 072 055 015 00226 033 011 041 00227 051 005 133 00228 048 018 127 00229 048 018 127 00230 033 097 006 00231 053 000 008 00232 005 000 008 00233 036 088 148 00234 022 119 157 00235 020 101 141 00236 062 080 072 00237 022 101 080 00238 012 108 093 00239 009 000 072 00240 049 000 072 00241 047 113 157 00242 030 032 131 00243 046 000 010 00244 046 000 018 00245 046 000 011 00246 062 000 008 00247 061 000 000 00248 045 000 127 00249 046 000 136 00250 046 000 144 00251 030 000 000 00252 065 000 084 00253 065 000 084 00254 065 000 084 00255 066 000 003 00256 066 000 003 00257 066 000 003 00258 067 000 006 00259 067 000 006 00260 067 000 006 00261 050 095 155 00262 022 095 153 00263 053 082 095 00264 053 082 095 00265 019 000 050 00266 061 000 000 00267 068 000 079 00268 061 000 000 00269 019 000 014 00270 033 044 020 00271 033 044 020 00272 033 044 020 00273 034 048 124 00274 034 048 124 00275 034 048 124 00276 062 000 113 00277 062 000 113 00278 051 000 044 00279 051 000 044 00280 028 036 140 00281 028 036 140 00282 028 036 140 00283 033 000 044 00284 022 000 127 00285 027 090 095 00286 027 090 101 00287 054 000 000 00288 072 000 000 00289 054 000 000 00290 014 000 050 00291 003 000 151 00292 025 000 000 00293 043 000 155 00294 043 000 113 00295 043 000 113 00296 047 062 125 00297 047 062 125 00298 047 037 157 00299 005 042 159 00300 056 096 147 00301 056 096 147 00302 051 100 158 00303 052 022 125 00304 005 069 134 00305 005 069 134 00306 005 069 134 00307 074 000 140 00308 074 000 140 00309 009 031 058 00310 009 031 058 00311 057 000 000 00312 058 000 000 00313 035 068 158 00314 012 110 158 00315 030 038 102 00316 064 060 082 00317 064 060 082 00318 024 000 003 00319 024 000 003 00320 041 012 046 00321 041 012 046 00322 012 086 020 00323 040 116 083 00324 073 000 075 00325 047 020 082 00326 047 020 082 00327 020 077 126 00328 052 071 125 00329 026 000 000 00330 026 000 000 00331 008 000 011 00332 008 000 011 00333 030 000 013 00334 030 000 013 00335 017 000 137 00336 061 000 151 00337 026 000 000 00338 026 000 000 00339 012 107 093 00340 012 107 093 00341 052 075 091 00342 052 075 091 00343 026 000 000 00344 026 000 000 00345 021 000 114 00346 021 000 114 00347 004 000 033 00348 004 000 033 00349 033 000 091 00350 063 000 056 00351 059 000 000 00352 016 000 000 00353 015 119 130 00354 015 119 130 00355 026 000 000 00356 046 000 000 00357 034 094 139 00358 026 000 000 00359 046 105 154 00360 023 000 140 00361 039 115 141 00362 039 115 141 00363 047 115 012 00364 047 115 012 00365 047 115 012 00366 075 000 155 00367 033 000 041 00368 033 000 093 00369 033 069 005 00370 033 000 093 00371 069 000 125 00372 069 000 142 00373 022 000 153 00374 029 000 135 00375 029 000 135 00376 029 000 135 00377 029 000 005 00378 029 000 115 00379 029 000 135 00380 026 000 000 00381 026 000 000 00382 002 000 000 00383 070 000 000 00384 076 000 000 00385 032 000 000 00386 046 000 000 00387 065 000 075 00388 065 000 075 00389 065 000 075 00390 066 000 089 00391 066 000 089 00392 066 000 089 00393 067 000 128 00394 067 000 128 00395 067 000 128 00396 051 000 000 00397 022 000 120 00398 022 000 120 00399 086 109 141 00400 086 109 141 00401 061 000 050 00402 068 000 101 00403 079 022 062 00404 079 022 062 00405 079 022 062 00406 030 038 102 00407 030 038 101 00408 104 000 125 00409 104 000 125 00410 005 000 043 00411 005 000 043 00412 061 000 142 00413 107 000 142 00414 068 000 110 00415 118 000 055 00416 046 000 127 00417 050 053 010 00418 033 000 041 00419 033 000 041 00420 034 000 000 00421 122 000 000 00422 060 114 159 00423 060 114 159 00424 101 053 092 00425 106 084 138 00426 106 084 138 00427 050 103 007 00428 056 103 007 00429 026 000 000 00430 015 105 153 00431 007 020 051 00432 047 020 128 00433 026 000 000 00434 001 106 051 00435 001 106 051 00436 026 085 134 00437 026 085 134 00438 005 069 155 00439 043 111 101 00440 030 032 132 00441 051 077 145 00442 046 000 151 00443 008 000 024 00444 008 000 024 00445 008 000 024 00446 053 047 082 00447 080 039 158 00448 080 039 154 00449 045 000 159 00450 045 000 159 00451 004 097 051 00452 004 097 051 00453 107 087 143 00454 107 087 143 00455 026 000 000 00456 033 114 041 00457 033 114 041 00458 033 011 041 00459 117 000 043 00460 117 000 043 00461 046 000 124 00462 042 005 148 00463 020 012 013 00464 031 116 120 00465 034 102 144 00466 078 000 072 00467 049 000 072 00468 055 032 105 00469 003 110 119 00470 102 000 034 00471 081 000 115 00472 052 008 090 00473 012 081 047 00474 091 088 148 00475 080 000 154 00476 005 042 159 00477 046 000 000 00478 081 000 130 00479 026 000 000 00480 026 000 000 00481 026 000 000 00482 026 000 000 00483 046 000 140 00484 046 000 140 00485 018 000 049 00486 112 000 000 00487 046 000 140 00488 026 000 000 00489 093 000 000 00490 093 000 000 00491 123 000 000 00492 030 000 000 00493 121 000 000 00494 162 000 000 00495 065 000 126 00496 065 000 126 00497 065 000 126 00498 066 000 047 00499 066 000 047 00500 066 000 120 00501 067 000 075 00502 067 000 075 00503 067 000 075 00504 050 051 148 00505 035 051 148 00506 072 053 050 00507 022 146 113 00508 022 146 113 00509 007 084 158 00510 007 084 158 00511 082 000 065 00512 082 000 065 00513 082 000 066 00514 082 000 066 00515 082 000 067 00516 082 000 067 00517 108 028 140 00518 108 028 140 00519 145 105 079 00520 145 105 079 00521 145 105 079 00522 031 078 157 00523 031 078 157 00524 005 000 159 00525 005 000 159 00526 005 000 159 00527 109 103 086 00528 109 103 086 00529 146 159 104 00530 146 159 104 00531 131 144 103 00532 062 125 089 00533 062 125 089 00534 062 125 089 00535 033 093 011 00536 033 093 011 00537 033 143 011 00538 062 039 104 00539 005 039 104 00540 068 034 142 00541 102 034 142 00542 068 034 142 00543 038 068 095 00544 038 068 095 00545 038 068 095 00546 158 151 034 00547 158 151 034 00548 034 020 102 00549 034 020 102 00550 120 091 104 00551 022 153 083 00552 022 153 083 00553 022 153 083 00554 055 000 039 00555 125 000 161 00556 011 034 114 00557 005 075 133 00558 005 075 133 00559 061 153 022 00560 061 153 022 00561 147 098 110 00562 152 000 000 00563 152 000 000 00564 116 005 033 00565 116 005 033 00566 129 000 000 00567 129 000 000 00568 001 060 106 00569 001 133 106 00570 149 000 000 00571 149 000 000 00572 056 101 092 00573 056 101 092 00574 119 000 023 00575 119 000 023 00576 119 000 023 00577 142 098 144 00578 142 098 144 00579 142 098 144 00580 051 145 093 00581 051 145 093 00582 115 000 133 00583 115 000 133 00584 115 000 133 00585 034 157 032 00586 034 157 032 00587 009 000 078 00588 068 061 099 00589 068 075 142 00590 027 000 144 00591 027 000 144 00592 011 130 006 00593 011 130 006 00594 131 093 144 00595 014 127 068 00596 014 127 068 00597 160 000 000 00598 160 000 000 00599 057 058 029 00600 057 058 029 00601 057 058 029 00602 026 000 000 00603 026 000 000 00604 026 000 000 00605 140 028 148 00606 140 028 148 00607 018 049 023 00608 018 049 023 00609 018 049 023 00610 079 104 127 00611 079 104 127 00612 079 104 127 00613 081 000 155 00614 081 000 033 00615 026 000 000 00616 093 075 142 00617 093 060 084 00618 009 007 008 00619 039 144 120 00620 039 144 120 00621 024 125 104 00622 089 103 099 00623 089 103 099 00624 128 039 046 00625 128 039 046 00626 120 157 043 00627 051 125 055 00628 051 125 128 00629 145 142 133 00630 145 142 133 00631 082 018 073 00632 068 055 054 00633 055 000 000 00634 055 000 000 00635 026 000 000 00636 049 000 068 00637 049 000 068 00638 154 000 000 00639 154 000 000 00640 154 000 000 00641 158 000 128 00642 158 000 128 00643 163 000 000 00644 164 000 000 00645 159 000 125 00646 046 000 000 00647 154 000 000 00648 032 000 000 00649 088 000 000 10001 026 000 000 10002 026 000 000 10003 026 000 000 10004 026 000 000 10005 026 000 000 10006 026 000 000 10007 026 000 000 10008 026 000 000 10009 026 000 000 10010 026 000 000 10011 026 000 000 10012 026 000 000 10013 026 000 000 10014 026 000 000 10015 026 000 000 10016 026 000 000 10017 026 000 000 10018 026 000 000 10019 026 000 000 10020 026 000 000 10021 026 000 000 10022 026 000 000 10023 026 000 000 10024 026 000 000 10025 026 000 000 10026 026 000 000 10027 026 000 000 10028 059 000 000 10029 059 000 000 10030 059 000 000 10031 046 000 000 10032 046 000 000 10033 046 000 000 10034 061 000 142 10035 061 000 142 10036 107 000 142 10037 107 000 142 10038 122 000 000 10039 060 114 159 10040 060 114 159 10041 121 000 000 10042 121 000 000 10043 121 000 000 10044 121 000 000 10045 121 000 000 10046 121 000 000 10047 121 000 000 10048 121 000 000 10049 121 000 000 10050 121 000 000 10051 121 000 000 10052 121 000 000 10053 121 000 000 10054 121 000 000 10055 121 000 000 10056 121 000 000 10057 121 000 000 10058 026 000 000 10059 026 000 000 10060 026 000 000 10061 026 000 000 10062 026 000 000 10063 026 000 000 10064 032 000 000 10065 009 000 031 10066 069 091 104 10067 125 000 161 10068 034 157 032 10069 034 157 032 10070 034 157 032 10071 034 157 032 10072 034 157 032 10073 034 157 032 10074 032 000 000 10075 088 000 000 10076 088 000 000 10077 088 000 000 10078 088 000 000 10079 144 000 000 10080 010 000 000 10081 022 000 000 10082 164 000 000 10083 163 000 000 10084 154 000 000 ================================================ FILE: VeekunImport/form_abilities6.txt ================================================ 00039 056 172 132 00040 056 172 119 00145 046 000 009 00174 056 172 132 00311 057 000 031 00312 058 000 010 00349 033 012 091 00350 063 172 056 00352 016 000 168 00355 026 000 119 00356 046 000 119 00396 051 000 120 00477 046 000 119 00543 038 068 003 00544 038 068 003 00545 038 068 003 00574 119 172 023 00575 119 172 023 00576 119 172 023 00598 160 000 107 00607 018 049 151 00608 018 049 151 00609 018 049 151 00650 065 000 171 00651 065 000 171 00652 065 000 171 00653 066 000 170 00654 066 000 170 00655 066 000 170 00656 067 000 168 00657 067 000 168 00658 067 000 168 00659 053 167 037 00660 053 167 037 00661 145 000 177 00662 049 000 177 00663 049 000 177 00664 019 014 132 00665 061 000 132 00666 019 014 132 00667 079 127 153 00668 079 127 153 00669 166 000 180 00670 166 000 180 00671 166 000 180 00672 157 000 179 00673 157 000 179 00674 089 104 113 00675 089 104 113 00676 169 000 000 00677 051 151 020 00678 051 151 158 00679 099 000 000 00680 099 000 000 00681 176 000 000 00682 131 000 165 00683 131 000 165 00684 175 000 084 00685 175 000 084 00686 126 021 151 00687 126 021 151 00688 181 097 124 00689 181 097 124 00690 038 143 091 00691 038 143 091 00692 178 000 000 00693 178 000 000 00694 087 008 094 00695 087 008 094 00696 173 000 005 00697 173 000 069 00698 174 000 117 00699 174 000 117 00700 056 000 182 00701 007 084 104 00702 167 053 057 00703 029 000 005 00704 157 093 183 00705 157 093 183 00706 157 093 183 00707 158 000 170 00708 030 119 139 00709 030 119 139 00710 053 119 015 00711 053 119 015 00712 020 115 005 00713 020 115 005 00714 119 151 140 00715 119 151 140 00716 187 000 000 00717 186 000 000 00718 188 000 000 00719 029 000 000 00720 170 000 000 00721 011 000 000 10085 121 000 000 10086 019 014 132 10087 019 014 132 10088 019 014 132 10089 019 014 132 10090 019 014 132 10091 019 014 132 10092 019 014 132 10093 019 014 132 10094 019 014 132 10095 019 014 132 10096 019 014 132 10097 019 014 132 10098 019 014 132 10099 019 014 132 10100 019 014 132 10101 019 014 132 10102 019 014 132 10103 166 000 180 10104 166 000 180 10105 166 000 180 10106 166 000 180 10107 166 000 180 10108 166 000 180 10109 166 000 180 10110 166 000 180 10111 166 000 180 10112 166 000 180 10113 166 000 180 10114 166 000 180 10115 169 000 000 10116 169 000 000 10117 169 000 000 10118 169 000 000 10119 169 000 000 10120 169 000 000 10121 169 000 000 10122 169 000 000 10123 169 000 000 10124 051 151 172 10125 176 000 000 10126 053 119 015 10127 053 119 015 10128 053 119 015 10129 053 119 015 10130 053 119 015 10131 053 119 015 10132 187 000 000 10133 047 000 000 10134 181 000 000 10135 070 000 000 10136 178 000 000 10137 036 000 000 10138 023 000 000 10139 185 000 000 10140 184 000 000 10141 104 000 000 10142 181 000 000 10143 080 000 000 10144 015 000 000 10145 104 000 000 10146 101 000 000 10147 092 000 000 10148 094 000 000 10149 045 000 000 10150 003 000 000 10151 182 000 000 10152 037 000 000 10153 111 000 000 10154 074 000 000 10155 022 000 000 10156 158 000 000 10157 156 000 000 10158 159 000 000 10159 091 000 000 10160 117 000 000 10161 019 014 132 10162 019 014 132 10163 166 000 180 10164 026 000 000 10165 026 000 000 10166 033 000 000 10167 031 000 000 10168 156 000 000 10169 182 000 000 10170 039 000 000 10171 131 000 000 10172 173 000 000 10173 075 000 000 10174 159 000 000 10175 099 000 000 10176 174 000 000 10177 156 000 000 10178 181 000 000 10179 189 000 000 10180 190 000 000 10181 191 000 000 10182 009 000 031 10183 009 000 031 10184 009 000 031 10185 009 000 031 10186 009 000 031 10187 009 000 031 10188 170 000 000 10189 125 000 000 10190 113 000 000 10191 184 000 000 10192 091 000 000 ================================================ FILE: VeekunImport/form_stats1.txt ================================================ 00001 12 04 045 049 049 045 065 065 0 0 0 0 1 0 00002 12 04 060 062 063 060 080 080 0 0 0 0 1 1 00003 12 04 080 082 083 080 100 100 0 0 0 0 2 1 00004 10 00 039 052 043 065 050 050 0 0 0 1 0 0 00005 10 00 058 064 058 080 065 065 0 0 0 1 1 0 00006 10 03 078 084 078 100 085 085 0 0 0 0 3 0 00007 11 00 044 048 065 043 050 050 0 0 1 0 0 0 00008 11 00 059 063 080 058 065 065 0 0 1 0 0 1 00009 11 00 079 083 100 078 085 085 0 0 0 0 0 3 00010 07 00 045 030 035 045 020 020 1 0 0 0 0 0 00011 07 00 050 020 055 030 025 025 0 0 2 0 0 0 00012 07 03 060 045 050 070 080 080 0 0 0 0 2 1 00013 07 04 040 035 030 050 020 020 0 0 0 1 0 0 00014 07 04 045 025 050 035 025 025 0 0 2 0 0 0 00015 07 04 065 080 040 075 045 045 0 2 0 0 0 1 00016 01 03 040 045 040 056 035 035 0 0 0 1 0 0 00017 01 03 063 060 055 071 050 050 0 0 0 2 0 0 00018 01 03 083 080 075 091 070 070 0 0 0 3 0 0 00019 01 00 030 056 035 072 025 025 0 0 0 1 0 0 00020 01 00 055 081 060 097 050 050 0 0 0 2 0 0 00021 01 03 040 060 030 070 031 031 0 0 0 1 0 0 00022 01 03 065 090 065 100 061 061 0 0 0 2 0 0 00023 04 00 035 060 044 055 040 040 0 1 0 0 0 0 00024 04 00 060 085 069 080 065 065 0 2 0 0 0 0 00025 13 00 035 055 030 090 050 050 0 0 0 2 0 0 00026 13 00 060 090 055 110 090 090 0 0 0 3 0 0 00027 05 00 050 075 085 040 030 030 0 0 1 0 0 0 00028 05 00 075 100 110 065 055 055 0 0 2 0 0 0 00029 04 00 055 047 052 041 040 040 1 0 0 0 0 0 00030 04 00 070 062 067 056 055 055 2 0 0 0 0 0 00031 04 05 090 082 087 076 075 075 3 0 0 0 0 0 00032 04 00 046 057 040 050 040 040 0 1 0 0 0 0 00033 04 00 061 072 057 065 055 055 0 2 0 0 0 0 00034 04 05 081 092 077 085 075 075 0 3 0 0 0 0 00035 01 00 070 045 048 035 060 060 2 0 0 0 0 0 00036 01 00 095 070 073 060 085 085 3 0 0 0 0 0 00037 10 00 038 041 040 065 065 065 0 0 0 1 0 0 00038 10 00 073 076 075 100 100 100 0 0 0 1 0 1 00039 01 00 115 045 020 020 025 025 2 0 0 0 0 0 00040 01 00 140 070 045 045 050 050 3 0 0 0 0 0 00041 04 03 040 045 035 055 040 040 0 0 0 1 0 0 00042 04 03 075 080 070 090 075 075 0 0 0 2 0 0 00043 12 04 045 050 055 030 075 075 0 0 0 0 1 0 00044 12 04 060 065 070 040 085 085 0 0 0 0 2 0 00045 12 04 075 080 085 050 100 100 0 0 0 0 3 0 00046 07 12 035 070 055 025 055 055 0 1 0 0 0 0 00047 07 12 060 095 080 030 080 080 0 2 1 0 0 0 00048 07 04 060 055 050 045 040 040 0 0 0 0 0 1 00049 07 04 070 065 060 090 090 090 0 0 0 1 1 0 00050 05 00 010 055 025 095 045 045 0 0 0 1 0 0 00051 05 00 035 080 050 120 070 070 0 0 0 2 0 0 00052 01 00 040 045 035 090 040 040 0 0 0 1 0 0 00053 01 00 065 070 060 115 065 065 0 0 0 2 0 0 00054 11 00 050 052 048 055 050 050 0 0 0 0 1 0 00055 11 00 080 082 078 085 080 080 0 0 0 0 2 0 00056 02 00 040 080 035 070 035 035 0 1 0 0 0 0 00057 02 00 065 105 060 095 060 060 0 2 0 0 0 0 00058 10 00 055 070 045 060 050 050 0 1 0 0 0 0 00059 10 00 090 110 080 095 080 080 0 2 0 0 0 0 00060 11 00 040 050 040 090 040 040 0 0 0 1 0 0 00061 11 00 065 065 065 090 050 050 0 0 0 2 0 0 00062 11 02 090 085 095 070 070 070 0 0 3 0 0 0 00063 14 00 025 020 015 090 105 105 0 0 0 0 1 0 00064 14 00 040 035 030 105 120 120 0 0 0 0 2 0 00065 14 00 055 050 045 120 135 135 0 0 0 0 3 0 00066 02 00 070 080 050 035 035 035 0 1 0 0 0 0 00067 02 00 080 100 070 045 050 050 0 2 0 0 0 0 00068 02 00 090 130 080 055 065 065 0 3 0 0 0 0 00069 12 04 050 075 035 040 070 070 0 1 0 0 0 0 00070 12 04 065 090 050 055 085 085 0 2 0 0 0 0 00071 12 04 080 105 065 070 100 100 0 3 0 0 0 0 00072 11 04 040 040 035 070 100 100 0 0 0 0 0 1 00073 11 04 080 070 065 100 120 120 0 0 0 0 0 2 00074 06 05 040 080 100 020 030 030 0 0 1 0 0 0 00075 06 05 055 095 115 035 045 045 0 0 2 0 0 0 00076 06 05 080 110 130 045 055 055 0 0 3 0 0 0 00077 10 00 050 085 055 090 065 065 0 0 0 1 0 0 00078 10 00 065 100 070 105 080 080 0 0 0 2 0 0 00079 11 14 090 065 065 015 040 040 1 0 0 0 0 0 00080 11 14 095 075 110 030 080 080 0 0 2 0 0 0 00081 13 00 025 035 070 045 095 095 0 0 0 0 1 0 00082 13 00 050 060 095 070 120 120 0 0 0 0 2 0 00083 01 03 052 065 055 060 058 058 0 1 0 0 0 0 00084 01 03 035 085 045 075 035 035 0 1 0 0 0 0 00085 01 03 060 110 070 100 060 060 0 2 0 0 0 0 00086 11 00 065 045 055 045 070 070 0 0 0 0 0 1 00087 11 15 090 070 080 070 095 095 0 0 0 0 0 2 00088 04 00 080 080 050 025 040 040 1 0 0 0 0 0 00089 04 00 105 105 075 050 065 065 1 1 0 0 0 0 00090 11 00 030 065 100 040 045 045 0 0 1 0 0 0 00091 11 15 050 095 180 070 085 085 0 0 2 0 0 0 00092 08 04 030 035 030 080 100 100 0 0 0 0 1 0 00093 08 04 045 050 045 095 115 115 0 0 0 0 2 0 00094 08 04 060 065 060 110 130 130 0 0 0 0 3 0 00095 06 05 035 045 160 070 030 030 0 0 1 0 0 0 00096 14 00 060 048 045 042 090 090 0 0 0 0 0 1 00097 14 00 085 073 070 067 115 115 0 0 0 0 0 2 00098 11 00 030 105 090 050 025 025 0 1 0 0 0 0 00099 11 00 055 130 115 075 050 050 0 2 0 0 0 0 00100 13 00 040 030 050 100 055 055 0 0 0 1 0 0 00101 13 00 060 050 070 140 080 080 0 0 0 2 0 0 00102 12 14 060 040 080 040 060 060 0 0 1 0 0 0 00103 12 14 095 095 085 055 125 125 0 0 0 0 2 0 00104 05 00 050 050 095 035 040 040 0 0 1 0 0 0 00105 05 00 060 080 110 045 050 050 0 0 2 0 0 0 00106 02 00 050 120 053 087 035 035 0 2 0 0 0 0 00107 02 00 050 105 079 076 035 035 0 0 0 0 0 2 00108 01 00 090 055 075 030 060 060 2 0 0 0 0 0 00109 04 00 040 065 095 035 060 060 0 0 1 0 0 0 00110 04 00 065 090 120 060 085 085 0 0 2 0 0 0 00111 05 06 080 085 095 025 030 030 0 0 1 0 0 0 00112 05 06 105 130 120 040 045 045 0 2 0 0 0 0 00113 01 00 250 005 005 050 105 105 2 0 0 0 0 0 00114 12 00 065 055 115 060 100 100 0 0 1 0 0 0 00115 01 00 105 095 080 090 040 040 2 0 0 0 0 0 00116 11 00 030 040 070 060 070 070 0 0 0 0 1 0 00117 11 00 055 065 095 085 095 095 0 0 1 0 1 0 00118 11 00 045 067 060 063 050 050 0 1 0 0 0 0 00119 11 00 080 092 065 068 080 080 0 2 0 0 0 0 00120 11 00 030 045 055 085 070 070 0 0 0 1 0 0 00121 11 14 060 075 085 115 100 100 0 0 0 2 0 0 00122 14 00 040 045 065 090 100 100 0 0 0 0 0 2 00123 07 03 070 110 080 105 055 055 0 1 0 0 0 0 00124 15 14 065 050 035 095 095 095 0 0 0 0 2 0 00125 13 00 065 083 057 105 085 085 0 0 0 2 0 0 00126 10 00 065 095 057 093 085 085 0 0 0 0 2 0 00127 07 00 065 125 100 085 055 055 0 2 0 0 0 0 00128 01 00 075 100 095 110 070 070 0 1 0 1 0 0 00129 11 00 020 010 055 080 020 020 0 0 0 1 0 0 00130 11 03 095 125 079 081 100 100 0 2 0 0 0 0 00131 11 15 130 085 080 060 095 095 2 0 0 0 0 0 00132 01 00 048 048 048 048 048 048 1 0 0 0 0 0 00133 01 00 055 055 050 055 065 065 0 0 0 0 0 1 00134 11 00 130 065 060 065 110 110 2 0 0 0 0 0 00135 13 00 065 065 060 130 110 110 0 0 0 2 0 0 00136 10 00 065 130 060 065 110 110 0 2 0 0 0 0 00137 01 00 065 060 070 040 075 075 0 0 0 0 1 0 00138 06 11 035 040 100 035 090 090 0 0 1 0 0 0 00139 06 11 070 060 125 055 115 115 0 0 2 0 0 0 00140 06 11 030 080 090 055 045 045 0 0 1 0 0 0 00141 06 11 060 115 105 080 070 070 0 2 0 0 0 0 00142 06 03 080 105 065 130 060 060 0 0 0 2 0 0 00143 01 00 160 110 065 030 065 065 2 0 0 0 0 0 00144 15 03 090 085 100 085 125 125 0 0 0 0 0 3 00145 13 03 090 090 085 100 125 125 0 0 0 0 3 0 00146 10 03 090 100 090 090 125 125 0 0 0 0 3 0 00147 16 00 041 064 045 050 050 050 0 1 0 0 0 0 00148 16 00 061 084 065 070 070 070 0 2 0 0 0 0 00149 16 03 091 134 095 080 100 100 0 3 0 0 0 0 00150 14 00 106 110 090 130 154 154 0 0 0 0 3 0 00151 14 00 100 100 100 100 100 100 3 0 0 0 0 0 ================================================ FILE: VeekunImport/form_stats2.txt ================================================ 00004 10 00 039 052 043 065 060 050 0 0 0 1 0 0 00005 10 00 058 064 058 080 080 065 0 0 0 1 1 0 00006 10 03 078 084 078 100 109 085 0 0 0 0 3 0 00007 11 00 044 048 065 043 050 064 0 0 1 0 0 0 00008 11 00 059 063 080 058 065 080 0 0 1 0 0 1 00009 11 00 079 083 100 078 085 105 0 0 0 0 0 3 00015 07 04 065 080 040 075 045 080 0 2 0 0 0 1 00019 01 00 030 056 035 072 025 035 0 0 0 1 0 0 00020 01 00 055 081 060 097 050 070 0 0 0 2 0 0 00023 04 00 035 060 044 055 040 054 0 1 0 0 0 0 00024 04 00 060 085 069 080 065 079 0 2 0 0 0 0 00025 13 00 035 055 030 090 050 040 0 0 0 2 0 0 00026 13 00 060 090 055 110 090 080 0 0 0 3 0 0 00027 05 00 050 075 085 040 020 030 0 0 1 0 0 0 00028 05 00 075 100 110 065 045 055 0 0 2 0 0 0 00031 04 05 090 082 087 076 075 085 3 0 0 0 0 0 00034 04 05 081 092 077 085 085 075 0 3 0 0 0 0 00035 01 00 070 045 048 035 060 065 2 0 0 0 0 0 00036 01 00 095 070 073 060 085 090 3 0 0 0 0 0 00037 10 00 038 041 040 065 050 065 0 0 0 1 0 0 00038 10 00 073 076 075 100 081 100 0 0 0 1 0 1 00039 01 00 115 045 020 020 045 025 2 0 0 0 0 0 00040 01 00 140 070 045 045 075 050 3 0 0 0 0 0 00041 04 03 040 045 035 055 030 040 0 0 0 1 0 0 00042 04 03 075 080 070 090 065 075 0 0 0 2 0 0 00043 12 04 045 050 055 030 075 065 0 0 0 0 1 0 00044 12 04 060 065 070 040 085 075 0 0 0 0 2 0 00045 12 04 075 080 085 050 100 090 0 0 0 0 3 0 00046 07 12 035 070 055 025 045 055 0 1 0 0 0 0 00047 07 12 060 095 080 030 060 080 0 2 1 0 0 0 00048 07 04 060 055 050 045 040 055 0 0 0 0 0 1 00049 07 04 070 065 060 090 090 075 0 0 0 1 1 0 00050 05 00 010 055 025 095 035 045 0 0 0 1 0 0 00051 05 00 035 080 050 120 050 070 0 0 0 2 0 0 00054 11 00 050 052 048 055 065 050 0 0 0 0 1 0 00055 11 00 080 082 078 085 095 080 0 0 0 0 2 0 00056 02 00 040 080 035 070 035 045 0 1 0 0 0 0 00057 02 00 065 105 060 095 060 070 0 2 0 0 0 0 00058 10 00 055 070 045 060 070 050 0 1 0 0 0 0 00059 10 00 090 110 080 095 100 080 0 2 0 0 0 0 00062 11 02 090 085 095 070 070 090 0 0 3 0 0 0 00063 14 00 025 020 015 090 105 055 0 0 0 0 1 0 00064 14 00 040 035 030 105 120 070 0 0 0 0 2 0 00065 14 00 055 050 045 120 135 085 0 0 0 0 3 0 00067 02 00 080 100 070 045 050 060 0 2 0 0 0 0 00068 02 00 090 130 080 055 065 085 0 3 0 0 0 0 00069 12 04 050 075 035 040 070 030 0 1 0 0 0 0 00070 12 04 065 090 050 055 085 045 0 2 0 0 0 0 00071 12 04 080 105 065 070 100 060 0 3 0 0 0 0 00072 11 04 040 040 035 070 050 100 0 0 0 0 0 1 00073 11 04 080 070 065 100 080 120 0 0 0 0 0 2 00076 06 05 080 110 130 045 055 065 0 0 3 0 0 0 00080 11 14 095 075 110 030 100 080 0 0 2 0 0 0 00081 13 09 025 035 070 045 095 055 0 0 0 0 1 0 00082 13 09 050 060 095 070 120 070 0 0 0 0 2 0 00083 01 03 052 065 055 060 058 062 0 1 0 0 0 0 00086 11 00 065 045 055 045 045 070 0 0 0 0 0 1 00087 11 15 090 070 080 070 070 095 0 0 0 0 0 2 00088 04 00 080 080 050 025 040 050 1 0 0 0 0 0 00089 04 00 105 105 075 050 065 100 1 1 0 0 0 0 00090 11 00 030 065 100 040 045 025 0 0 1 0 0 0 00091 11 15 050 095 180 070 085 045 0 0 2 0 0 0 00092 08 04 030 035 030 080 100 035 0 0 0 0 1 0 00093 08 04 045 050 045 095 115 055 0 0 0 0 2 0 00094 08 04 060 065 060 110 130 075 0 0 0 0 3 0 00095 06 05 035 045 160 070 030 045 0 0 1 0 0 0 00096 14 00 060 048 045 042 043 090 0 0 0 0 0 1 00097 14 00 085 073 070 067 073 115 0 0 0 0 0 2 00102 12 14 060 040 080 040 060 045 0 0 1 0 0 0 00103 12 14 095 095 085 055 125 065 0 0 0 0 2 0 00104 05 00 050 050 095 035 040 050 0 0 1 0 0 0 00105 05 00 060 080 110 045 050 080 0 0 2 0 0 0 00106 02 00 050 120 053 087 035 110 0 2 0 0 0 0 00107 02 00 050 105 079 076 035 110 0 0 0 0 0 2 00108 01 00 090 055 075 030 060 075 2 0 0 0 0 0 00109 04 00 040 065 095 035 060 045 0 0 1 0 0 0 00110 04 00 065 090 120 060 085 070 0 0 2 0 0 0 00113 01 00 250 005 005 050 035 105 2 0 0 0 0 0 00114 12 00 065 055 115 060 100 040 0 0 1 0 0 0 00115 01 00 105 095 080 090 040 080 2 0 0 0 0 0 00116 11 00 030 040 070 060 070 025 0 0 0 0 1 0 00117 11 00 055 065 095 085 095 045 0 0 1 0 1 0 00118 11 00 045 067 060 063 035 050 0 1 0 0 0 0 00119 11 00 080 092 065 068 065 080 0 2 0 0 0 0 00120 11 00 030 045 055 085 070 055 0 0 0 1 0 0 00121 11 14 060 075 085 115 100 085 0 0 0 2 0 0 00122 14 00 040 045 065 090 100 120 0 0 0 0 0 2 00123 07 03 070 110 080 105 055 080 0 1 0 0 0 0 00124 15 14 065 050 035 095 115 095 0 0 0 0 2 0 00125 13 00 065 083 057 105 095 085 0 0 0 2 0 0 00126 10 00 065 095 057 093 100 085 0 0 0 0 2 0 00127 07 00 065 125 100 085 055 070 0 2 0 0 0 0 00128 01 00 075 100 095 110 040 070 0 1 0 1 0 0 00129 11 00 020 010 055 080 015 020 0 0 0 1 0 0 00130 11 03 095 125 079 081 060 100 0 2 0 0 0 0 00131 11 15 130 085 080 060 085 095 2 0 0 0 0 0 00133 01 00 055 055 050 055 045 065 0 0 0 0 0 1 00134 11 00 130 065 060 065 110 095 2 0 0 0 0 0 00135 13 00 065 065 060 130 110 095 0 0 0 2 0 0 00136 10 00 065 130 060 065 095 110 0 2 0 0 0 0 00137 01 00 065 060 070 040 085 075 0 0 0 0 1 0 00138 06 11 035 040 100 035 090 055 0 0 1 0 0 0 00139 06 11 070 060 125 055 115 070 0 0 2 0 0 0 00140 06 11 030 080 090 055 055 045 0 0 1 0 0 0 00141 06 11 060 115 105 080 065 070 0 2 0 0 0 0 00142 06 03 080 105 065 130 060 075 0 0 0 2 0 0 00143 01 00 160 110 065 030 065 110 2 0 0 0 0 0 00144 15 03 090 085 100 085 095 125 0 0 0 0 0 3 00145 13 03 090 090 085 100 125 090 0 0 0 0 3 0 00146 10 03 090 100 090 090 125 085 0 0 0 0 3 0 00150 14 00 106 110 090 130 154 090 0 0 0 0 3 0 00152 12 00 045 049 065 045 049 065 0 0 0 0 0 1 00153 12 00 060 062 080 060 063 080 0 0 1 0 0 1 00154 12 00 080 082 100 080 083 100 0 0 1 0 0 2 00155 10 00 039 052 043 065 060 050 0 0 0 1 0 0 00156 10 00 058 064 058 080 080 065 0 0 0 1 1 0 00157 10 00 078 084 078 100 109 085 0 0 0 0 3 0 00158 11 00 050 065 064 043 044 048 0 1 0 0 0 0 00159 11 00 065 080 080 058 059 063 0 1 1 0 0 0 00160 11 00 085 105 100 078 079 083 0 2 1 0 0 0 00161 01 00 035 046 034 020 035 045 0 1 0 0 0 0 00162 01 00 085 076 064 090 045 055 0 0 0 2 0 0 00163 01 03 060 030 030 050 036 056 1 0 0 0 0 0 00164 01 03 100 050 050 070 076 096 2 0 0 0 0 0 00165 07 03 040 020 030 055 040 080 0 0 0 0 0 1 00166 07 03 055 035 050 085 055 110 0 0 0 0 0 2 00167 07 04 040 060 040 030 040 040 0 1 0 0 0 0 00168 07 04 070 090 070 040 060 060 0 2 0 0 0 0 00169 04 03 085 090 080 130 070 080 0 0 0 3 0 0 00170 11 13 075 038 038 067 056 056 1 0 0 0 0 0 00171 11 13 125 058 058 067 076 076 2 0 0 0 0 0 00172 13 00 020 040 015 060 035 035 0 0 0 1 0 0 00173 01 00 050 025 028 015 045 055 0 0 0 0 0 1 00174 01 00 090 030 015 015 040 020 1 0 0 0 0 0 00175 01 00 035 020 065 020 040 065 0 0 0 0 0 1 00176 01 03 055 040 085 040 080 105 0 0 0 0 0 2 00177 14 03 040 050 045 070 070 045 0 0 0 0 1 0 00178 14 03 065 075 070 095 095 070 0 0 0 1 1 0 00179 13 00 055 040 040 035 065 045 0 0 0 0 1 0 00180 13 00 070 055 055 045 080 060 0 0 0 0 2 0 00181 13 00 090 075 075 055 115 090 0 0 0 0 3 0 00182 12 00 075 080 085 050 090 100 0 0 0 0 0 3 00183 11 00 070 020 050 040 020 050 2 0 0 0 0 0 00184 11 00 100 050 080 050 050 080 3 0 0 0 0 0 00185 06 00 070 100 115 030 030 065 0 0 2 0 0 0 00186 11 00 090 075 075 070 090 100 0 0 0 0 0 3 00187 12 03 035 035 040 050 035 055 0 0 0 0 0 1 00188 12 03 055 045 050 080 045 065 0 0 0 2 0 0 00189 12 03 075 055 070 110 055 085 0 0 0 3 0 0 00190 01 00 055 070 055 085 040 055 0 0 0 1 0 0 00191 12 00 030 030 030 030 030 030 0 0 0 0 1 0 00192 12 00 075 075 055 030 105 085 0 0 0 0 2 0 00193 07 03 065 065 045 095 075 045 0 0 0 1 0 0 00194 11 05 055 045 045 015 025 025 1 0 0 0 0 0 00195 11 05 095 085 085 035 065 065 2 0 0 0 0 0 00196 14 00 065 065 060 110 130 095 0 0 0 0 2 0 00197 17 00 095 065 110 065 060 130 0 0 0 0 0 2 00198 17 03 060 085 042 091 085 042 0 0 0 1 0 0 00199 11 14 095 075 080 030 100 110 0 0 0 0 0 3 00200 08 00 060 060 060 085 085 085 0 0 0 0 0 1 00201 14 00 048 072 048 048 072 048 0 1 0 0 1 0 00202 14 00 190 033 058 033 033 058 2 0 0 0 0 0 00203 01 14 070 080 065 085 090 065 0 0 0 0 2 0 00204 07 00 050 065 090 015 035 035 0 0 1 0 0 0 00205 07 09 075 090 140 040 060 060 0 0 2 0 0 0 00206 01 00 100 070 070 045 065 065 1 0 0 0 0 0 00207 05 03 065 075 105 085 035 065 0 0 1 0 0 0 00208 09 05 075 085 200 030 055 065 0 0 2 0 0 0 00209 01 00 060 080 050 030 040 040 0 1 0 0 0 0 00210 01 00 090 120 075 045 060 060 0 2 0 0 0 0 00211 11 04 065 095 075 085 055 055 0 1 0 0 0 0 00212 07 09 070 130 100 065 055 080 0 2 0 0 0 0 00213 07 06 020 010 230 005 010 230 0 0 1 0 0 1 00214 07 02 080 125 075 085 040 095 0 2 0 0 0 0 00215 17 15 055 095 055 115 035 075 0 0 0 1 0 0 00216 01 00 060 080 050 040 050 050 0 1 0 0 0 0 00217 01 00 090 130 075 055 075 075 0 2 0 0 0 0 00218 10 00 040 040 040 020 070 040 0 0 0 0 1 0 00219 10 06 050 050 120 030 080 080 0 0 2 0 0 0 00220 15 05 050 050 040 050 030 030 0 1 0 0 0 0 00221 15 05 100 100 080 050 060 060 1 1 0 0 0 0 00222 11 06 055 055 085 035 065 085 0 0 1 0 0 1 00223 11 00 035 065 035 065 065 035 0 0 0 0 1 0 00224 11 00 075 105 075 045 105 075 0 1 0 0 1 0 00225 15 03 045 055 045 075 065 045 0 0 0 1 0 0 00226 11 03 065 040 070 070 080 140 0 0 0 0 0 2 00227 09 03 065 080 140 070 040 070 0 0 2 0 0 0 00228 17 10 045 060 030 065 080 050 0 0 0 0 1 0 00229 17 10 075 090 050 095 110 080 0 0 0 0 2 0 00230 11 16 075 095 095 085 095 095 0 1 0 0 1 1 00231 05 00 090 060 060 040 040 040 1 0 0 0 0 0 00232 05 00 090 120 120 050 060 060 0 1 1 0 0 0 00233 01 00 085 080 090 060 105 095 0 0 0 0 2 0 00234 01 00 073 095 062 085 085 065 0 1 0 0 0 0 00235 01 00 055 020 035 075 020 045 0 0 0 1 0 0 00236 02 00 035 035 035 035 035 035 0 1 0 0 0 0 00237 02 00 050 095 095 070 035 110 0 0 0 0 0 2 00238 15 14 045 030 015 065 085 065 0 0 0 0 1 0 00239 13 00 045 063 037 095 065 055 0 0 0 1 0 0 00240 10 00 045 075 037 083 070 055 0 0 0 1 0 0 00241 01 00 095 080 105 100 040 070 0 0 2 0 0 0 00242 01 00 255 010 010 055 075 135 3 0 0 0 0 0 00243 13 00 090 085 075 115 115 100 0 0 0 2 1 0 00244 10 00 115 115 085 100 090 075 1 2 0 0 0 0 00245 11 00 100 075 115 085 090 115 0 0 1 0 0 2 00246 06 05 050 064 050 041 045 050 0 1 0 0 0 0 00247 06 05 070 084 070 051 065 070 0 2 0 0 0 0 00248 06 17 100 134 110 061 095 100 0 3 0 0 0 0 00249 14 03 106 090 130 110 090 154 0 0 0 0 0 3 00250 10 03 106 130 090 090 110 154 0 0 0 0 0 3 00251 14 12 100 100 100 100 100 100 3 0 0 0 0 0 10001 14 00 048 072 048 048 072 048 0 1 0 0 1 0 10002 14 00 048 072 048 048 072 048 0 1 0 0 1 0 10003 14 00 048 072 048 048 072 048 0 1 0 0 1 0 10004 14 00 048 072 048 048 072 048 0 1 0 0 1 0 10005 14 00 048 072 048 048 072 048 0 1 0 0 1 0 10006 14 00 048 072 048 048 072 048 0 1 0 0 1 0 10007 14 00 048 072 048 048 072 048 0 1 0 0 1 0 10008 14 00 048 072 048 048 072 048 0 1 0 0 1 0 10009 14 00 048 072 048 048 072 048 0 1 0 0 1 0 10010 14 00 048 072 048 048 072 048 0 1 0 0 1 0 10011 14 00 048 072 048 048 072 048 0 1 0 0 1 0 10012 14 00 048 072 048 048 072 048 0 1 0 0 1 0 10013 14 00 048 072 048 048 072 048 0 1 0 0 1 0 10014 14 00 048 072 048 048 072 048 0 1 0 0 1 0 10015 14 00 048 072 048 048 072 048 0 1 0 0 1 0 10016 14 00 048 072 048 048 072 048 0 1 0 0 1 0 10017 14 00 048 072 048 048 072 048 0 1 0 0 1 0 10018 14 00 048 072 048 048 072 048 0 1 0 0 1 0 10019 14 00 048 072 048 048 072 048 0 1 0 0 1 0 10020 14 00 048 072 048 048 072 048 0 1 0 0 1 0 10021 14 00 048 072 048 048 072 048 0 1 0 0 1 0 10022 14 00 048 072 048 048 072 048 0 1 0 0 1 0 10023 14 00 048 072 048 048 072 048 0 1 0 0 1 0 10024 14 00 048 072 048 048 072 048 0 1 0 0 1 0 10025 14 00 048 072 048 048 072 048 0 1 0 0 1 0 ================================================ FILE: VeekunImport/form_stats3.txt ================================================ 00252 12 00 040 045 035 070 065 055 0 0 0 1 0 0 00253 12 00 050 065 045 095 085 065 0 0 0 2 0 0 00254 12 00 070 085 065 120 105 085 0 0 0 3 0 0 00255 10 00 045 060 040 045 070 050 0 0 0 0 1 0 00256 10 02 060 085 060 055 085 060 0 1 0 0 1 0 00257 10 02 080 120 070 080 110 070 0 3 0 0 0 0 00258 11 00 050 070 050 040 050 050 0 1 0 0 0 0 00259 11 05 070 085 070 050 060 070 0 2 0 0 0 0 00260 11 05 100 110 090 060 085 090 0 3 0 0 0 0 00261 17 00 035 055 035 035 030 030 0 1 0 0 0 0 00262 17 00 070 090 070 070 060 060 0 2 0 0 0 0 00263 01 00 038 030 041 060 030 041 0 0 0 1 0 0 00264 01 00 078 070 061 100 050 061 0 0 0 2 0 0 00265 07 00 045 045 035 020 020 030 1 0 0 0 0 0 00266 07 00 050 035 055 015 025 025 0 0 2 0 0 0 00267 07 03 060 070 050 065 090 050 0 0 0 0 3 0 00268 07 00 050 035 055 015 025 025 0 0 2 0 0 0 00269 07 04 060 050 070 065 050 090 0 0 0 0 0 3 00270 11 12 040 030 030 030 040 050 0 0 0 0 0 1 00271 11 12 060 050 050 050 060 070 0 0 0 0 0 2 00272 11 12 080 070 070 070 090 100 0 0 0 0 0 3 00273 12 00 040 040 050 030 030 030 0 0 1 0 0 0 00274 12 17 070 070 040 060 060 040 0 2 0 0 0 0 00275 12 17 090 100 060 080 090 060 0 3 0 0 0 0 00276 01 03 040 055 030 085 030 030 0 0 0 1 0 0 00277 01 03 060 085 060 125 050 050 0 0 0 2 0 0 00278 11 03 040 030 030 085 055 030 0 0 0 1 0 0 00279 11 03 060 050 100 065 085 070 0 0 2 0 0 0 00280 14 00 028 025 025 040 045 035 0 0 0 0 1 0 00281 14 00 038 035 035 050 065 055 0 0 0 0 2 0 00282 14 00 068 065 065 080 125 115 0 0 0 0 3 0 00283 07 11 040 030 032 065 050 052 0 0 0 1 0 0 00284 07 03 070 060 062 060 080 082 0 0 0 0 1 1 00285 12 00 060 040 060 035 040 060 1 0 0 0 0 0 00286 12 02 060 130 080 070 060 060 0 2 0 0 0 0 00287 01 00 060 060 060 030 035 035 1 0 0 0 0 0 00288 01 00 080 080 080 090 055 055 0 0 0 2 0 0 00289 01 00 150 160 100 100 095 065 3 0 0 0 0 0 00290 07 05 031 045 090 040 030 030 0 0 1 0 0 0 00291 07 03 061 090 045 160 050 050 0 0 0 2 0 0 00292 07 08 001 090 045 040 030 030 2 0 0 0 0 0 00293 01 00 064 051 023 028 051 023 1 0 0 0 0 0 00294 01 00 084 071 043 048 071 043 2 0 0 0 0 0 00295 01 00 104 091 063 068 091 063 3 0 0 0 0 0 00296 02 00 072 060 030 025 020 030 1 0 0 0 0 0 00297 02 00 144 120 060 050 040 060 2 0 0 0 0 0 00298 01 00 050 020 040 020 020 040 1 0 0 0 0 0 00299 06 00 030 045 135 030 045 090 0 0 1 0 0 0 00300 01 00 050 045 045 050 035 035 0 0 0 1 0 0 00301 01 00 070 065 065 070 055 055 1 0 0 1 0 0 00302 17 08 050 075 075 050 065 065 0 1 1 0 0 0 00303 09 00 050 085 085 050 055 055 0 1 1 0 0 0 00304 09 06 050 070 100 030 040 040 0 0 1 0 0 0 00305 09 06 060 090 140 040 050 050 0 0 2 0 0 0 00306 09 06 070 110 180 050 060 060 0 0 3 0 0 0 00307 02 14 030 040 055 060 040 055 0 0 0 1 0 0 00308 02 14 060 060 075 080 060 075 0 0 0 2 0 0 00309 13 00 040 045 040 065 065 040 0 0 0 1 0 0 00310 13 00 070 075 060 105 105 060 0 0 0 2 0 0 00311 13 00 060 050 040 095 085 075 0 0 0 1 0 0 00312 13 00 060 040 050 095 075 085 0 0 0 1 0 0 00313 07 00 065 073 055 085 047 075 0 0 0 1 0 0 00314 07 00 065 047 055 085 073 075 0 0 0 1 0 0 00315 12 04 050 060 045 065 100 080 0 0 0 0 2 0 00316 04 00 070 043 053 040 043 053 1 0 0 0 0 0 00317 04 00 100 073 083 055 073 083 2 0 0 0 0 0 00318 11 17 045 090 020 065 065 020 0 1 0 0 0 0 00319 11 17 070 120 040 095 095 040 0 2 0 0 0 0 00320 11 00 130 070 035 060 070 035 1 0 0 0 0 0 00321 11 00 170 090 045 060 090 045 2 0 0 0 0 0 00322 10 05 060 060 040 035 065 045 0 0 0 0 1 0 00323 10 05 070 100 070 040 105 075 0 1 0 0 1 0 00324 10 00 070 085 140 020 085 070 0 0 2 0 0 0 00325 14 00 060 025 035 060 070 080 0 0 0 0 0 1 00326 14 00 080 045 065 080 090 110 0 0 0 0 0 2 00327 01 00 060 060 060 060 060 060 0 0 0 0 1 0 00328 05 00 045 100 045 010 045 045 0 1 0 0 0 0 00329 05 16 050 070 050 070 050 050 0 1 0 1 0 0 00330 05 16 080 100 080 100 080 080 0 1 0 2 0 0 00331 12 00 050 085 040 035 085 040 0 0 0 0 1 0 00332 12 17 070 115 060 055 115 060 0 1 0 0 1 0 00333 01 03 045 040 060 050 040 075 0 0 0 0 0 1 00334 16 03 075 070 090 080 070 105 0 0 0 0 0 2 00335 01 00 073 115 060 090 060 060 0 2 0 0 0 0 00336 04 00 073 100 060 065 100 060 0 1 0 0 1 0 00337 06 14 070 055 065 070 095 085 0 0 0 0 2 0 00338 06 14 070 095 085 070 055 065 0 2 0 0 0 0 00339 11 05 050 048 043 060 046 041 1 0 0 0 0 0 00340 11 05 110 078 073 060 076 071 2 0 0 0 0 0 00341 11 00 043 080 065 035 050 035 0 1 0 0 0 0 00342 11 17 063 120 085 055 090 055 0 2 0 0 0 0 00343 05 14 040 040 055 055 040 070 0 0 0 0 0 1 00344 05 14 060 070 105 075 070 120 0 0 0 0 0 2 00345 06 12 066 041 077 023 061 087 0 0 0 0 0 1 00346 06 12 086 081 097 043 081 107 0 0 0 0 0 2 00347 06 07 045 095 050 075 040 050 0 1 0 0 0 0 00348 06 07 075 125 100 045 070 080 0 2 0 0 0 0 00349 11 00 020 015 020 080 010 055 0 0 0 1 0 0 00350 11 00 095 060 079 081 100 125 0 0 0 0 0 2 00351 01 00 070 070 070 070 070 070 1 0 0 0 0 0 00352 01 00 060 090 070 040 060 120 0 0 0 0 0 1 00353 08 00 044 075 035 045 063 033 0 1 0 0 0 0 00354 08 00 064 115 065 065 083 063 0 2 0 0 0 0 00355 08 00 020 040 090 025 030 090 0 0 0 0 0 1 00356 08 00 040 070 130 025 060 130 0 0 1 0 0 1 00357 12 03 099 068 083 051 072 087 2 0 0 0 0 0 00358 14 00 065 050 070 065 095 080 0 0 0 0 1 1 00359 17 00 065 130 060 075 075 060 0 2 0 0 0 0 00360 14 00 095 023 048 023 023 048 1 0 0 0 0 0 00361 15 00 050 050 050 050 050 050 1 0 0 0 0 0 00362 15 00 080 080 080 080 080 080 2 0 0 0 0 0 00363 15 11 070 040 050 025 055 050 1 0 0 0 0 0 00364 15 11 090 060 070 045 075 070 2 0 0 0 0 0 00365 15 11 110 080 090 065 095 090 3 0 0 0 0 0 00366 11 00 035 064 085 032 074 055 0 0 1 0 0 0 00367 11 00 055 104 105 052 094 075 0 1 1 0 0 0 00368 11 00 055 084 105 052 114 075 0 0 0 0 2 0 00369 11 06 100 090 130 055 045 065 1 0 1 0 0 0 00370 11 00 043 030 055 097 040 065 0 0 0 1 0 0 00371 16 00 045 075 060 050 040 030 0 1 0 0 0 0 00372 16 00 065 095 100 050 060 050 0 0 2 0 0 0 00373 16 03 095 135 080 100 110 080 0 3 0 0 0 0 00374 09 14 040 055 080 030 035 060 0 0 1 0 0 0 00375 09 14 060 075 100 050 055 080 0 0 2 0 0 0 00376 09 14 080 135 130 070 095 090 0 0 3 0 0 0 00377 06 00 080 100 200 050 050 100 0 0 3 0 0 0 00378 15 00 080 050 100 050 100 200 0 0 0 0 0 3 00379 09 00 080 075 150 050 075 150 0 0 2 0 0 1 00380 16 14 080 080 090 110 110 130 0 0 0 0 0 3 00381 16 14 080 090 080 110 130 110 0 0 0 0 3 0 00382 11 00 100 100 090 090 150 140 0 0 0 0 3 0 00383 05 00 100 150 140 090 100 090 0 3 0 0 0 0 00384 16 03 105 150 090 095 150 090 0 2 0 0 1 0 00385 09 14 100 100 100 100 100 100 3 0 0 0 0 0 00386 14 00 050 150 050 150 150 050 0 1 0 1 1 0 10026 14 00 048 072 048 048 072 048 0 1 0 0 1 0 10027 14 00 048 072 048 048 072 048 0 1 0 0 1 0 10028 10 00 070 070 070 070 070 070 1 0 0 0 0 0 10029 11 00 070 070 070 070 070 070 1 0 0 0 0 0 10030 15 00 070 070 070 070 070 070 1 0 0 0 0 0 10031 14 00 050 180 020 150 180 020 0 2 0 0 1 0 10032 14 00 050 070 160 090 070 160 0 0 2 0 0 1 10033 14 00 050 095 090 180 095 090 0 0 0 3 0 0 ================================================ FILE: VeekunImport/form_stats4.txt ================================================ 00387 12 00 055 068 064 031 045 055 0 1 0 0 0 0 00388 12 00 075 089 085 036 055 065 0 1 1 0 0 0 00389 12 05 095 109 105 056 075 085 0 2 1 0 0 0 00390 10 00 044 058 044 061 058 044 0 0 0 1 0 0 00391 10 02 064 078 052 081 078 052 0 0 0 1 1 0 00392 10 02 076 104 071 108 104 071 0 1 0 1 1 0 00393 11 00 053 051 053 040 061 056 0 0 0 0 1 0 00394 11 00 064 066 068 050 081 076 0 0 0 0 2 0 00395 11 09 084 086 088 060 111 101 0 0 0 0 3 0 00396 01 03 040 055 030 060 030 030 0 0 0 1 0 0 00397 01 03 055 075 050 080 040 040 0 0 0 2 0 0 00398 01 03 085 120 070 100 050 050 0 3 0 0 0 0 00399 01 00 059 045 040 031 035 040 1 0 0 0 0 0 00400 01 11 079 085 060 071 055 060 0 2 0 0 0 0 00401 07 00 037 025 041 025 025 041 0 0 1 0 0 0 00402 07 00 077 085 051 065 055 051 0 2 0 0 0 0 00403 13 00 045 065 034 045 040 034 0 1 0 0 0 0 00404 13 00 060 085 049 060 060 049 0 2 0 0 0 0 00405 13 00 080 120 079 070 095 079 0 3 0 0 0 0 00406 12 04 040 030 035 055 050 070 0 0 0 0 1 0 00407 12 04 060 070 055 090 125 105 0 0 0 0 3 0 00408 06 00 067 125 040 058 030 030 0 1 0 0 0 0 00409 06 00 097 165 060 058 065 050 0 2 0 0 0 0 00410 06 09 030 042 118 030 042 088 0 0 1 0 0 0 00411 06 09 060 052 168 030 047 138 0 0 2 0 0 0 00412 07 00 040 029 045 036 029 045 0 0 0 0 0 1 00413 07 12 060 059 085 036 079 105 0 0 0 0 0 2 00414 07 03 070 094 050 066 094 050 0 1 0 0 1 0 00415 07 03 030 030 042 070 030 042 0 0 0 1 0 0 00416 07 03 070 080 102 040 080 102 0 0 1 0 0 1 00417 13 00 060 045 070 095 045 090 0 0 0 1 0 0 00418 11 00 055 065 035 085 060 030 0 0 0 1 0 0 00419 11 00 085 105 055 115 085 050 0 0 0 2 0 0 00420 12 00 045 035 045 035 062 053 0 0 0 0 1 0 00421 12 00 070 060 070 085 087 078 0 0 0 0 2 0 00422 11 00 076 048 048 034 057 062 1 0 0 0 0 0 00423 11 05 111 083 068 039 092 082 2 0 0 0 0 0 00424 01 00 075 100 066 115 060 066 0 0 0 2 0 0 00425 08 03 090 050 034 070 060 044 1 0 0 0 0 0 00426 08 03 150 080 044 080 090 054 2 0 0 0 0 0 00427 01 00 055 066 044 085 044 056 0 0 0 1 0 0 00428 01 00 065 076 084 105 054 096 0 0 0 2 0 0 00429 08 00 060 060 060 105 105 105 0 0 0 0 1 1 00430 17 03 100 125 052 071 105 052 0 2 0 0 0 0 00431 01 00 049 055 042 085 042 037 0 0 0 1 0 0 00432 01 00 071 082 064 112 064 059 0 0 0 2 0 0 00433 14 00 045 030 050 045 065 050 0 0 0 0 1 0 00434 04 17 063 063 047 074 041 041 0 0 0 1 0 0 00435 04 17 103 093 067 084 071 061 2 0 0 0 0 0 00436 09 14 057 024 086 023 024 086 0 0 1 0 0 0 00437 09 14 067 089 116 033 079 116 0 0 1 0 0 1 00438 06 00 050 080 095 010 010 045 0 0 1 0 0 0 00439 14 00 020 025 045 060 070 090 0 0 0 0 0 1 00440 01 00 100 005 005 030 015 065 1 0 0 0 0 0 00441 01 03 076 065 045 091 092 042 0 1 0 0 0 0 00442 08 17 050 092 108 035 092 108 0 0 1 0 0 1 00443 16 05 058 070 045 042 040 045 0 1 0 0 0 0 00444 16 05 068 090 065 082 050 055 0 2 0 0 0 0 00445 16 05 108 130 095 102 080 085 0 3 0 0 0 0 00446 01 00 135 085 040 005 040 085 1 0 0 0 0 0 00447 02 00 040 070 040 060 035 040 0 1 0 0 0 0 00448 02 09 070 110 070 090 115 070 0 1 0 0 1 0 00449 05 00 068 072 078 032 038 042 0 0 1 0 0 0 00450 05 00 108 112 118 047 068 072 0 0 2 0 0 0 00451 04 07 040 050 090 065 030 055 0 0 1 0 0 0 00452 04 17 070 090 110 095 060 075 0 0 2 0 0 0 00453 04 02 048 061 040 050 061 040 0 1 0 0 0 0 00454 04 02 083 106 065 085 086 065 0 2 0 0 0 0 00455 12 00 074 100 072 046 090 072 0 2 0 0 0 0 00456 11 00 049 049 056 066 049 061 0 0 0 1 0 0 00457 11 00 069 069 076 091 069 086 0 0 0 2 0 0 00458 11 03 045 020 050 050 060 120 0 0 0 0 0 1 00459 12 15 060 062 050 040 062 060 0 1 0 0 0 0 00460 12 15 090 092 075 060 092 085 0 1 0 0 1 0 00461 17 15 070 120 065 125 045 085 0 1 0 1 0 0 00462 13 09 070 070 115 060 130 090 0 0 0 0 3 0 00463 01 00 110 085 095 050 080 095 3 0 0 0 0 0 00464 05 06 115 140 130 040 055 055 0 3 0 0 0 0 00465 12 00 100 100 125 050 110 050 0 0 2 0 0 0 00466 13 00 075 123 067 095 095 085 0 3 0 0 0 0 00467 10 00 075 095 067 083 125 095 0 0 0 0 3 0 00468 01 03 085 050 095 080 120 115 0 0 0 0 2 1 00469 07 03 086 076 086 095 116 056 0 2 0 0 0 0 00470 12 00 065 110 130 095 060 065 0 0 2 0 0 0 00471 15 00 065 060 110 065 130 095 0 0 0 0 2 0 00472 05 03 075 095 125 095 045 075 0 0 2 0 0 0 00473 15 05 110 130 080 080 070 060 0 3 0 0 0 0 00474 01 00 085 080 070 090 135 075 0 0 0 0 3 0 00475 14 02 068 125 065 080 065 115 0 3 0 0 0 0 00476 06 09 060 055 145 040 075 150 0 0 1 0 0 2 00477 08 00 045 100 135 045 065 135 0 0 1 0 0 2 00478 15 08 070 080 070 110 080 070 0 0 0 2 0 0 00479 13 08 050 050 077 091 095 077 0 0 0 1 1 0 00480 14 00 075 075 130 095 075 130 0 0 2 0 0 1 00481 14 00 080 105 105 080 105 105 0 1 0 0 1 1 00482 14 00 075 125 070 115 125 070 0 2 0 0 1 0 00483 09 16 100 120 120 090 150 100 0 0 0 0 3 0 00484 11 16 090 120 100 100 150 120 0 0 0 0 3 0 00485 10 09 091 090 106 077 130 106 0 0 0 0 3 0 00486 01 00 110 160 110 100 080 110 0 3 0 0 0 0 00487 08 16 150 100 120 090 100 120 3 0 0 0 0 0 00488 14 00 120 070 120 085 075 130 0 0 0 0 0 3 00489 11 00 080 080 080 080 080 080 1 0 0 0 0 0 00490 11 00 100 100 100 100 100 100 3 0 0 0 0 0 00491 17 00 070 090 090 125 135 090 0 0 0 1 2 0 00492 12 00 100 100 100 100 100 100 3 0 0 0 0 0 00493 01 00 120 120 120 120 120 120 3 0 0 0 0 0 10034 07 00 040 029 045 036 029 045 0 0 0 0 0 1 10035 07 00 040 029 045 036 029 045 0 0 0 0 0 1 10036 07 05 060 079 105 036 059 085 0 0 2 0 0 0 10037 07 09 060 069 095 036 069 095 0 0 1 0 0 1 10038 12 00 070 060 070 085 087 078 0 0 0 0 2 0 10039 11 00 076 048 048 034 057 062 1 0 0 0 0 0 10040 11 05 111 083 068 039 092 082 2 0 0 0 0 0 10041 01 00 120 120 120 120 120 120 3 0 0 0 0 0 10042 01 00 120 120 120 120 120 120 3 0 0 0 0 0 10043 01 00 120 120 120 120 120 120 3 0 0 0 0 0 10044 01 00 120 120 120 120 120 120 3 0 0 0 0 0 10045 01 00 120 120 120 120 120 120 3 0 0 0 0 0 10046 01 00 120 120 120 120 120 120 3 0 0 0 0 0 10047 01 00 120 120 120 120 120 120 3 0 0 0 0 0 10048 01 00 120 120 120 120 120 120 3 0 0 0 0 0 10049 01 00 120 120 120 120 120 120 3 0 0 0 0 0 10050 01 00 120 120 120 120 120 120 3 0 0 0 0 0 10051 01 00 120 120 120 120 120 120 3 0 0 0 0 0 10052 01 00 120 120 120 120 120 120 3 0 0 0 0 0 10053 01 00 120 120 120 120 120 120 3 0 0 0 0 0 10054 01 00 120 120 120 120 120 120 3 0 0 0 0 0 10055 01 00 120 120 120 120 120 120 3 0 0 0 0 0 10056 01 00 120 120 120 120 120 120 3 0 0 0 0 0 10057 01 00 120 120 120 120 120 120 3 0 0 0 0 0 10058 13 08 050 065 107 086 105 107 0 0 0 1 1 0 10059 13 08 050 065 107 086 105 107 0 0 0 1 1 0 10060 13 08 050 065 107 086 105 107 0 0 0 1 1 0 10061 13 08 050 065 107 086 105 107 0 0 0 1 1 0 10062 13 08 050 065 107 086 105 107 0 0 0 1 1 0 10063 08 16 150 120 100 090 120 100 3 0 0 0 0 0 10064 12 03 100 103 075 127 120 075 0 0 0 3 0 0 10065 13 00 020 040 015 060 035 035 0 0 0 1 0 0 ================================================ FILE: VeekunImport/form_stats5.txt ================================================ 00494 14 10 100 100 100 100 100 100 3 0 0 0 0 0 00495 12 00 045 045 055 063 045 055 0 0 0 1 0 0 00496 12 00 060 060 075 083 060 075 0 0 0 2 0 0 00497 12 00 075 075 095 113 075 095 0 0 0 3 0 0 00498 10 00 065 063 045 045 045 045 1 0 0 0 0 0 00499 10 02 090 093 055 055 070 055 0 2 0 0 0 0 00500 10 02 110 123 065 065 100 065 0 3 0 0 0 0 00501 11 00 055 055 045 045 063 045 0 0 0 0 1 0 00502 11 00 075 075 060 060 083 060 0 0 0 0 2 0 00503 11 00 095 100 085 070 108 070 0 0 0 0 3 0 00504 01 00 045 055 039 042 035 039 0 1 0 0 0 0 00505 01 00 060 085 069 077 060 069 0 2 0 0 0 0 00506 01 00 045 060 045 055 025 045 0 1 0 0 0 0 00507 01 00 065 080 065 060 035 065 0 2 0 0 0 0 00508 01 00 085 100 090 080 045 090 0 3 0 0 0 0 00509 17 00 041 050 037 066 050 037 0 0 0 1 0 0 00510 17 00 064 088 050 106 088 050 0 0 0 2 0 0 00511 12 00 050 053 048 064 053 048 0 0 0 1 0 0 00512 12 00 075 098 063 101 098 063 0 0 0 2 0 0 00513 10 00 050 053 048 064 053 048 0 0 0 1 0 0 00514 10 00 075 098 063 101 098 063 0 0 0 2 0 0 00515 11 00 050 053 048 064 053 048 0 0 0 1 0 0 00516 11 00 075 098 063 101 098 063 0 0 0 2 0 0 00517 14 00 076 025 045 024 067 055 1 0 0 0 0 0 00518 14 00 116 055 085 029 107 095 2 0 0 0 0 0 00519 01 03 050 055 050 043 036 030 0 1 0 0 0 0 00520 01 03 062 077 062 065 050 042 0 2 0 0 0 0 00521 01 03 080 105 080 093 065 055 0 3 0 0 0 0 00522 13 00 045 060 032 076 050 032 0 0 0 1 0 0 00523 13 00 075 100 063 116 080 063 0 0 0 2 0 0 00524 06 00 055 075 085 015 025 025 0 0 1 0 0 0 00525 06 00 070 105 105 020 050 040 0 1 1 0 0 0 00526 06 00 085 135 130 025 060 070 0 3 0 0 0 0 00527 14 03 055 045 043 072 055 043 0 0 0 1 0 0 00528 14 03 067 057 055 114 077 055 0 0 0 2 0 0 00529 05 00 060 085 040 068 030 045 0 1 0 0 0 0 00530 05 09 110 135 060 088 050 065 0 2 0 0 0 0 00531 01 00 103 060 086 050 060 086 2 0 0 0 0 0 00532 02 00 075 080 055 035 025 035 0 1 0 0 0 0 00533 02 00 085 105 085 040 040 050 0 2 0 0 0 0 00534 02 00 105 140 095 045 055 065 0 3 0 0 0 0 00535 11 00 050 050 040 064 050 040 0 0 0 1 0 0 00536 11 05 075 065 055 069 065 055 2 0 0 0 0 0 00537 11 05 105 085 075 074 085 075 3 0 0 0 0 0 00538 02 00 120 100 085 045 030 085 2 0 0 0 0 0 00539 02 00 075 125 075 085 030 075 0 2 0 0 0 0 00540 07 12 045 053 070 042 040 060 0 0 1 0 0 0 00541 07 12 055 063 090 042 050 080 0 0 2 0 0 0 00542 07 12 075 103 080 092 070 070 0 3 0 0 0 0 00543 07 04 030 045 059 057 030 039 0 0 1 0 0 0 00544 07 04 040 055 099 047 040 079 0 0 2 0 0 0 00545 07 04 060 090 089 112 055 069 0 0 0 3 0 0 00546 12 00 040 027 060 066 037 050 0 0 0 1 0 0 00547 12 00 060 067 085 116 077 075 0 0 0 2 0 0 00548 12 00 045 035 050 030 070 050 0 0 0 0 1 0 00549 12 00 070 060 075 090 110 075 0 0 0 0 2 0 00550 11 00 070 092 065 098 080 055 0 0 0 2 0 0 00551 05 17 050 072 035 065 035 035 0 1 0 0 0 0 00552 05 17 060 082 045 074 045 045 0 2 0 0 0 0 00553 05 17 095 117 070 092 065 070 0 3 0 0 0 0 00554 10 00 070 090 045 050 015 045 0 1 0 0 0 0 00555 10 00 105 140 055 095 030 055 0 2 0 0 0 0 00556 12 00 075 086 067 060 106 067 0 0 0 0 2 0 00557 07 06 050 065 085 055 035 035 0 0 1 0 0 0 00558 07 06 070 095 125 045 065 075 0 0 2 0 0 0 00559 17 02 050 075 070 048 035 070 0 1 0 0 0 0 00560 17 02 065 090 115 058 045 115 0 0 1 0 0 1 00561 14 03 072 058 080 097 103 080 0 0 0 0 2 0 00562 08 00 038 030 085 030 055 065 0 0 1 0 0 0 00563 08 00 058 050 145 030 095 105 0 0 2 0 0 0 00564 11 06 054 078 103 022 053 045 0 0 1 0 0 0 00565 11 06 074 108 133 032 083 065 0 0 2 0 0 0 00566 06 03 055 112 045 070 074 045 0 1 0 0 0 0 00567 06 03 075 140 065 110 112 065 0 2 0 0 0 0 00568 04 00 050 050 062 065 040 062 0 0 0 1 0 0 00569 04 00 080 095 082 075 060 082 0 2 0 0 0 0 00570 17 00 040 065 040 065 080 040 0 0 0 0 1 0 00571 17 00 060 105 060 105 120 060 0 0 0 0 2 0 00572 01 00 055 050 040 075 040 040 0 0 0 1 0 0 00573 01 00 075 095 060 115 065 060 0 0 0 2 0 0 00574 14 00 045 030 050 045 055 065 0 0 0 0 0 1 00575 14 00 060 045 070 055 075 085 0 0 0 0 0 2 00576 14 00 070 055 095 065 095 110 0 0 0 0 0 3 00577 14 00 045 030 040 020 105 050 0 0 0 0 1 0 00578 14 00 065 040 050 030 125 060 0 0 0 0 2 0 00579 14 00 110 065 075 030 125 085 0 0 0 0 3 0 00580 11 03 062 044 050 055 044 050 1 0 0 0 0 0 00581 11 03 075 087 063 098 087 063 0 0 0 2 0 0 00582 15 00 036 050 050 044 065 060 0 0 0 0 1 0 00583 15 00 051 065 065 059 080 075 0 0 0 0 2 0 00584 15 00 071 095 085 079 110 095 0 0 0 0 3 0 00585 01 12 060 060 050 075 040 050 0 0 0 1 0 0 00586 01 12 080 100 070 095 060 070 0 2 0 0 0 0 00587 13 03 055 075 060 103 075 060 0 0 0 2 0 0 00588 07 00 050 075 045 060 040 045 0 1 0 0 0 0 00589 07 09 070 135 105 020 060 105 0 2 0 0 0 0 00590 12 04 069 055 045 015 055 055 1 0 0 0 0 0 00591 12 04 114 085 070 030 085 080 2 0 0 0 0 0 00592 11 08 055 040 050 040 065 085 0 0 0 0 0 1 00593 11 08 100 060 070 060 085 105 0 0 0 0 0 2 00594 11 00 165 075 080 065 040 045 2 0 0 0 0 0 00595 07 13 050 047 050 065 057 050 0 0 0 1 0 0 00596 07 13 070 077 060 108 097 060 0 0 0 2 0 0 00597 12 09 044 050 091 010 024 086 0 0 1 0 0 0 00598 12 09 074 094 131 020 054 116 0 0 2 0 0 0 00599 09 00 040 055 070 030 045 060 0 0 1 0 0 0 00600 09 00 060 080 095 050 070 085 0 0 2 0 0 0 00601 09 00 060 100 115 090 070 085 0 0 3 0 0 0 00602 13 00 035 055 040 060 045 040 0 0 0 1 0 0 00603 13 00 065 085 070 040 075 070 0 2 0 0 0 0 00604 13 00 085 115 080 050 105 080 0 3 0 0 0 0 00605 14 00 055 055 055 030 085 055 0 0 0 0 1 0 00606 14 00 075 075 075 040 125 095 0 0 0 0 2 0 00607 08 10 050 030 055 020 065 055 0 0 0 0 1 0 00608 08 10 060 040 060 055 095 060 0 0 0 0 2 0 00609 08 10 060 055 090 080 145 090 0 0 0 0 3 0 00610 16 00 046 087 060 057 030 040 0 1 0 0 0 0 00611 16 00 066 117 070 067 040 050 0 2 0 0 0 0 00612 16 00 076 147 090 097 060 070 0 3 0 0 0 0 00613 15 00 055 070 040 040 060 040 0 1 0 0 0 0 00614 15 00 095 110 080 050 070 080 0 2 0 0 0 0 00615 15 00 070 050 030 105 095 135 0 0 0 0 0 2 00616 07 00 050 040 085 025 040 065 0 0 1 0 0 0 00617 07 00 080 070 040 145 100 060 0 0 0 2 0 0 00618 05 13 109 066 084 032 081 099 2 0 0 0 0 0 00619 02 00 045 085 050 065 055 050 0 1 0 0 0 0 00620 02 00 065 125 060 105 095 060 0 2 0 0 0 0 00621 16 00 077 120 090 048 060 090 0 2 0 0 0 0 00622 05 08 059 074 050 035 035 050 0 1 0 0 0 0 00623 05 08 089 124 080 055 055 080 0 2 0 0 0 0 00624 17 09 045 085 070 060 040 040 0 1 0 0 0 0 00625 17 09 065 125 100 070 060 070 0 2 0 0 0 0 00626 01 00 095 110 095 055 040 095 0 2 0 0 0 0 00627 01 03 070 083 050 060 037 050 0 1 0 0 0 0 00628 01 03 100 123 075 080 057 075 0 2 0 0 0 0 00629 17 03 070 055 075 060 045 065 0 0 1 0 0 0 00630 17 03 110 065 105 080 055 095 0 0 0 0 2 0 00631 10 00 085 097 066 065 105 066 0 0 0 0 2 0 00632 07 09 058 109 112 109 048 048 0 0 2 0 0 0 00633 17 16 052 065 050 038 045 050 0 1 0 0 0 0 00634 17 16 072 085 070 058 065 070 0 2 0 0 0 0 00635 17 16 092 105 090 098 125 090 0 0 0 0 3 0 00636 07 10 055 085 055 060 050 055 0 1 0 0 0 0 00637 07 10 085 060 065 100 135 105 0 0 0 0 3 0 00638 09 02 091 090 129 108 090 072 0 0 3 0 0 0 00639 06 02 091 129 090 108 072 090 0 3 0 0 0 0 00640 12 02 091 090 072 108 090 129 0 0 0 0 0 3 00641 03 00 079 115 070 111 125 080 0 3 0 0 0 0 00642 13 03 079 115 070 111 125 080 0 3 0 0 0 0 00643 16 10 100 120 100 090 150 120 0 0 0 0 3 0 00644 16 13 100 150 120 090 120 100 0 3 0 0 0 0 00645 05 03 089 125 090 101 115 080 0 0 0 0 3 0 00646 16 15 125 130 090 095 130 090 1 1 0 0 1 0 00647 11 02 091 072 090 108 129 090 0 0 0 0 3 0 00648 01 14 100 077 077 090 128 128 0 0 0 1 1 1 00649 07 09 071 120 095 099 120 095 0 1 0 1 1 0 10058 13 10 050 065 107 086 105 107 0 0 0 1 1 0 10059 13 11 050 065 107 086 105 107 0 0 0 1 1 0 10060 13 15 050 065 107 086 105 107 0 0 0 1 1 0 10061 13 03 050 065 107 086 105 107 0 0 0 1 1 0 10062 13 12 050 065 107 086 105 107 0 0 0 1 1 0 10066 11 00 070 092 065 098 080 055 0 0 0 2 0 0 10067 10 14 105 030 105 055 140 105 0 0 0 0 2 0 10068 01 12 060 060 050 075 040 050 0 0 0 1 0 0 10069 01 12 060 060 050 075 040 050 0 0 0 1 0 0 10070 01 12 060 060 050 075 040 050 0 0 0 1 0 0 10071 01 12 080 100 070 095 060 070 0 2 0 0 0 0 10072 01 12 080 100 070 095 060 070 0 2 0 0 0 0 10073 01 12 080 100 070 095 060 070 0 2 0 0 0 0 10074 01 02 100 128 090 128 077 077 0 1 1 1 0 0 10075 07 09 071 120 095 099 120 095 0 1 0 1 1 0 10076 07 09 071 120 095 099 120 095 0 1 0 1 1 0 10077 07 09 071 120 095 099 120 095 0 1 0 1 1 0 10078 07 09 071 120 095 099 120 095 0 1 0 1 1 0 10079 03 00 079 100 080 121 110 090 0 0 0 3 0 0 10080 13 03 079 105 070 101 145 080 0 0 0 0 3 0 10081 05 03 089 145 090 091 105 080 0 3 0 0 0 0 10082 16 15 125 170 100 095 120 090 0 3 0 0 0 0 10083 16 15 125 120 090 095 170 100 0 0 0 0 3 0 10084 11 02 091 072 090 108 129 090 0 0 0 0 3 0 ================================================ FILE: VeekunImport/form_stats6.txt ================================================ 00012 07 03 060 045 050 070 090 080 0 0 0 0 2 1 00015 07 04 065 090 040 075 045 080 0 2 0 0 0 1 00018 01 03 083 080 075 101 070 070 0 0 0 3 0 0 00025 13 00 035 055 040 090 050 050 0 0 0 2 0 0 00026 13 00 060 090 055 110 090 080 0 0 0 3 0 0 00031 04 05 090 092 087 076 075 085 3 0 0 0 0 0 00034 04 05 081 102 077 085 085 075 0 3 0 0 0 0 00035 18 00 070 045 048 035 060 065 2 0 0 0 0 0 00036 18 00 095 070 073 060 095 090 3 0 0 0 0 0 00039 01 18 115 045 020 020 045 025 2 0 0 0 0 0 00040 01 18 140 070 045 045 085 050 3 0 0 0 0 0 00045 12 04 075 080 085 050 110 090 0 0 0 0 3 0 00062 11 02 090 095 095 070 070 090 0 0 3 0 0 0 00065 14 00 055 050 045 120 135 095 0 0 0 0 3 0 00071 12 04 080 105 065 070 100 070 0 3 0 0 0 0 00076 06 05 080 120 130 045 055 065 0 0 3 0 0 0 00122 14 18 040 045 065 090 100 120 0 0 0 0 0 2 00173 18 00 050 025 028 015 045 055 0 0 0 0 0 1 00174 01 18 090 030 015 015 040 020 1 0 0 0 0 0 00175 18 00 035 020 065 020 040 065 0 0 0 0 0 1 00176 18 03 055 040 085 040 080 105 0 0 0 0 0 2 00181 13 00 090 075 085 055 115 090 0 0 0 0 3 0 00182 12 00 075 080 095 050 090 100 0 0 0 0 0 3 00183 11 18 070 020 050 040 020 050 2 0 0 0 0 0 00184 11 18 100 050 080 050 060 080 3 0 0 0 0 0 00189 12 03 075 055 070 110 055 095 0 0 0 3 0 0 00209 18 00 060 080 050 030 040 040 0 1 0 0 0 0 00210 18 00 090 120 075 045 060 060 0 2 0 0 0 0 00267 07 03 060 070 050 065 100 050 0 0 0 0 3 0 00280 14 18 028 025 025 040 045 035 0 0 0 0 1 0 00281 14 18 038 035 035 050 065 055 0 0 0 0 2 0 00282 14 18 068 065 065 080 125 115 0 0 0 0 3 0 00295 01 00 104 091 063 068 091 073 3 0 0 0 0 0 00298 01 18 050 020 040 020 020 040 1 0 0 0 0 0 00303 09 18 050 085 085 050 055 055 0 1 1 0 0 0 00398 01 03 085 120 070 100 050 060 0 3 0 0 0 0 00407 12 04 060 070 065 090 125 105 0 0 0 0 3 0 00439 14 18 020 025 045 060 070 090 0 0 0 0 0 1 00468 18 03 085 050 095 080 120 115 0 0 0 0 2 1 00508 01 00 085 110 090 080 045 090 0 3 0 0 0 0 00521 01 03 080 115 080 093 065 055 0 3 0 0 0 0 00526 06 00 085 135 130 025 060 080 0 3 0 0 0 0 00537 11 05 105 095 075 074 085 075 3 0 0 0 0 0 00542 07 12 075 103 080 092 070 080 0 3 0 0 0 0 00545 07 04 060 100 089 112 055 069 0 0 0 3 0 0 00546 12 18 040 027 060 066 037 050 0 0 0 1 0 0 00547 12 18 060 067 085 116 077 075 0 0 0 2 0 0 00553 05 17 095 117 080 092 065 070 0 3 0 0 0 0 00650 12 00 056 061 065 038 048 045 0 0 1 0 0 0 00651 12 00 061 078 095 057 056 058 0 0 2 0 0 0 00652 12 02 088 107 122 064 074 075 0 0 3 0 0 0 00653 10 00 040 045 040 060 062 060 0 0 0 0 1 0 00654 10 00 059 059 058 073 090 070 0 0 0 0 2 0 00655 10 14 075 069 072 104 114 100 0 0 0 0 3 0 00656 11 00 041 056 040 071 062 044 0 0 0 1 0 0 00657 11 00 054 063 052 097 083 056 0 0 0 2 0 0 00658 11 17 072 095 067 122 103 071 0 0 0 3 0 0 00659 01 00 038 036 038 057 032 036 0 0 0 1 0 0 00660 01 05 085 056 077 078 050 077 2 0 0 0 0 0 00661 01 03 045 050 043 062 040 038 0 0 0 1 0 0 00662 10 03 062 073 055 084 056 052 0 0 0 2 0 0 00663 10 03 078 081 071 126 074 069 0 0 0 3 0 0 00664 07 00 038 035 040 035 027 025 0 0 1 0 0 0 00665 07 00 045 022 060 029 027 030 0 0 2 0 0 0 00666 07 03 080 052 050 089 090 050 1 0 0 1 1 0 00667 10 01 062 050 058 072 073 054 0 0 0 0 1 0 00668 10 01 086 068 072 106 109 066 0 0 0 0 2 0 00669 18 00 044 038 039 042 061 079 0 0 0 0 0 1 00670 18 00 054 045 047 052 075 098 0 0 0 0 0 2 00671 18 00 078 065 068 075 112 154 0 0 0 0 0 3 00672 12 00 066 065 048 052 062 057 1 0 0 0 0 0 00673 12 00 123 100 062 068 097 081 2 0 0 0 0 0 00674 02 00 067 082 062 043 046 048 0 1 0 0 0 0 00675 02 17 095 124 078 058 069 071 0 2 0 0 0 0 00676 01 00 075 080 060 102 065 090 0 0 0 1 0 0 00677 14 00 062 048 054 068 063 060 0 0 0 1 0 0 00678 14 00 074 048 076 104 083 081 0 0 0 2 0 0 00679 09 08 045 080 100 028 035 037 0 0 1 0 0 0 00680 09 08 059 110 150 035 045 049 0 0 2 0 0 0 00681 09 08 060 050 150 060 050 150 0 0 2 0 0 1 00682 18 00 078 052 060 023 063 065 1 0 0 0 0 0 00683 18 00 101 072 072 029 099 089 2 0 0 0 0 0 00684 18 00 062 048 066 049 059 057 0 0 1 0 0 0 00685 18 00 082 080 086 072 085 075 0 0 2 0 0 0 00686 17 14 053 054 053 045 037 046 0 1 0 0 0 0 00687 17 14 086 092 088 073 068 075 0 2 0 0 0 0 00688 06 11 042 052 067 050 039 056 0 1 0 0 0 0 00689 06 11 072 105 115 068 054 086 0 2 0 0 0 0 00690 04 11 050 060 060 030 060 060 0 0 0 0 0 1 00691 04 16 065 075 090 044 097 123 0 0 0 0 0 2 00692 11 00 050 053 062 044 058 063 0 0 0 0 1 0 00693 11 00 071 073 088 059 120 089 0 0 0 0 2 0 00694 13 01 044 038 033 070 061 043 0 0 0 1 0 0 00695 13 01 062 055 052 109 109 094 0 0 0 1 1 0 00696 06 16 058 089 077 048 045 045 0 1 0 0 0 0 00697 06 16 082 121 119 071 069 059 0 2 0 0 0 0 00698 06 15 077 059 050 046 067 063 1 0 0 0 0 0 00699 06 15 123 077 072 058 099 092 2 0 0 0 0 0 00700 18 00 095 065 065 060 110 130 0 0 0 0 0 2 00701 02 03 078 092 075 118 074 063 0 2 0 0 0 0 00702 13 18 067 058 057 101 081 067 0 0 0 2 0 0 00703 06 18 050 050 150 050 050 150 0 0 1 0 0 1 00704 16 00 045 050 035 040 055 075 0 0 0 0 0 1 00705 16 00 068 075 053 060 083 113 0 0 0 0 0 2 00706 16 00 090 100 070 080 110 150 0 0 0 0 0 3 00707 09 18 057 080 091 075 080 087 0 0 1 0 0 0 00708 08 12 043 070 048 038 050 060 0 1 0 0 0 0 00709 08 12 085 110 076 056 065 082 0 2 0 0 0 0 00710 08 12 049 066 070 051 044 055 0 0 1 0 0 0 00711 08 12 065 090 122 084 058 075 0 0 2 0 0 0 00712 15 00 055 069 085 028 032 035 0 0 1 0 0 0 00713 15 00 095 117 184 028 044 046 0 0 2 0 0 0 00714 03 16 040 030 035 055 045 040 0 0 0 1 0 0 00715 03 16 085 070 080 123 097 080 0 0 0 2 0 0 00716 18 00 126 131 095 099 131 098 3 0 0 0 0 0 00717 17 03 126 131 095 099 131 098 3 0 0 0 0 0 00718 16 05 108 100 121 095 081 095 3 0 0 0 0 0 00719 06 18 050 100 150 050 100 150 0 0 1 0 0 2 00720 14 08 080 110 060 070 150 130 0 0 0 0 3 0 00721 10 11 080 110 120 070 130 090 0 0 0 0 3 0 10085 01 00 120 120 120 120 120 120 3 0 0 0 0 0 10086 07 03 080 052 050 089 090 050 1 0 0 1 1 0 10087 07 03 080 052 050 089 090 050 1 0 0 1 1 0 10088 07 03 080 052 050 089 090 050 1 0 0 1 1 0 10089 07 03 080 052 050 089 090 050 1 0 0 1 1 0 10090 07 03 080 052 050 089 090 050 1 0 0 1 1 0 10091 07 03 080 052 050 089 090 050 1 0 0 1 1 0 10092 07 03 080 052 050 089 090 050 1 0 0 1 1 0 10093 07 03 080 052 050 089 090 050 1 0 0 1 1 0 10094 07 03 080 052 050 089 090 050 1 0 0 1 1 0 10095 07 03 080 052 050 089 090 050 1 0 0 1 1 0 10096 07 03 080 052 050 089 090 050 1 0 0 1 1 0 10097 07 03 080 052 050 089 090 050 1 0 0 1 1 0 10098 07 03 080 052 050 089 090 050 1 0 0 1 1 0 10099 07 03 080 052 050 089 090 050 1 0 0 1 1 0 10100 07 03 080 052 050 089 090 050 1 0 0 1 1 0 10101 07 03 080 052 050 089 090 050 1 0 0 1 1 0 10102 07 03 080 052 050 089 090 050 1 0 0 1 1 0 10103 18 00 044 038 039 042 061 079 0 0 0 0 0 1 10104 18 00 044 038 039 042 061 079 0 0 0 0 0 1 10105 18 00 044 038 039 042 061 079 0 0 0 0 0 1 10106 18 00 044 038 039 042 061 079 0 0 0 0 0 1 10107 18 00 054 045 047 052 075 098 0 0 0 0 0 2 10108 18 00 054 045 047 052 075 098 0 0 0 0 0 2 10109 18 00 054 045 047 052 075 098 0 0 0 0 0 2 10110 18 00 054 045 047 052 075 098 0 0 0 0 0 2 10111 18 00 078 065 068 075 112 154 0 0 0 0 0 3 10112 18 00 078 065 068 075 112 154 0 0 0 0 0 3 10113 18 00 078 065 068 075 112 154 0 0 0 0 0 3 10114 18 00 078 065 068 075 112 154 0 0 0 0 0 3 10115 01 00 075 080 060 102 065 090 0 0 0 1 0 0 10116 01 00 075 080 060 102 065 090 0 0 0 1 0 0 10117 01 00 075 080 060 102 065 090 0 0 0 1 0 0 10118 01 00 075 080 060 102 065 090 0 0 0 1 0 0 10119 01 00 075 080 060 102 065 090 0 0 0 1 0 0 10120 01 00 075 080 060 102 065 090 0 0 0 1 0 0 10121 01 00 075 080 060 102 065 090 0 0 0 1 0 0 10122 01 00 075 080 060 102 065 090 0 0 0 1 0 0 10123 01 00 075 080 060 102 065 090 0 0 0 1 0 0 10124 14 00 074 048 076 104 083 081 0 0 0 2 0 0 10125 09 08 060 150 050 060 150 050 0 2 0 0 1 0 10126 08 12 044 066 070 056 044 055 0 0 1 0 0 0 10127 08 12 054 066 070 046 044 055 0 0 1 0 0 0 10128 08 12 059 066 070 041 044 055 0 0 1 0 0 0 10129 08 12 055 085 122 099 058 075 0 0 2 0 0 0 10130 08 12 075 095 122 069 058 075 0 0 2 0 0 0 10131 08 12 085 100 122 054 058 075 0 0 2 0 0 0 10132 18 00 126 131 095 099 131 098 3 0 0 0 0 0 10133 12 04 080 100 123 080 122 120 0 0 0 0 2 1 10134 10 16 078 130 111 100 130 085 0 0 0 0 3 0 10135 10 03 078 104 078 100 159 115 0 0 0 0 3 0 10136 11 00 079 103 120 078 135 115 0 0 0 0 0 3 10137 14 00 055 050 065 150 175 095 0 0 0 0 3 0 10138 08 04 060 065 080 130 170 095 0 0 0 0 3 0 10139 01 00 105 125 100 100 060 100 2 0 0 0 0 0 10140 07 03 065 155 120 105 065 090 0 2 0 0 0 0 10141 11 17 095 155 109 081 070 130 0 2 0 0 0 0 10142 06 03 080 135 085 150 070 095 0 0 0 2 0 0 10143 14 02 106 190 100 130 154 100 0 0 0 0 3 0 10144 14 00 106 150 070 140 194 120 0 0 0 0 3 0 10145 13 16 090 095 105 045 165 110 0 0 0 0 3 0 10146 07 09 070 150 140 075 065 100 0 2 0 0 0 0 10147 07 02 080 185 115 075 040 105 0 2 0 0 0 0 10148 17 10 075 090 090 115 140 090 0 0 0 0 2 0 10149 06 17 100 164 150 071 095 120 0 3 0 0 0 0 10150 10 02 080 160 080 100 130 080 0 3 0 0 0 0 10151 14 18 068 085 065 100 165 135 0 0 0 0 3 0 10152 09 18 050 105 125 050 055 095 0 1 1 0 0 0 10153 09 00 070 140 230 050 060 080 0 0 3 0 0 0 10154 02 14 060 100 085 100 080 085 0 0 0 2 0 0 10155 13 00 070 075 080 135 135 080 0 0 0 2 0 0 10156 08 00 064 165 075 075 093 083 0 2 0 0 0 0 10157 17 00 065 150 060 115 115 060 0 2 0 0 0 0 10158 16 05 108 170 115 092 120 095 0 3 0 0 0 0 10159 02 09 070 145 088 112 140 070 0 1 0 0 1 0 10160 12 15 090 132 105 030 132 105 0 1 0 0 1 0 10161 07 03 080 052 050 089 090 050 1 0 0 1 1 0 10162 07 03 080 052 050 089 090 050 1 0 0 1 1 0 10163 18 00 074 065 067 092 125 128 0 0 0 0 0 2 10164 16 14 080 100 120 110 140 150 0 0 0 0 0 3 10165 16 14 080 130 100 110 160 120 0 0 0 0 3 0 10166 11 05 100 150 110 070 095 110 0 3 0 0 0 0 10167 12 16 070 110 075 145 145 085 0 0 0 3 0 0 10168 17 08 050 085 125 020 085 115 0 1 1 0 0 0 10169 16 18 075 110 110 080 110 105 0 0 0 0 0 2 10170 14 02 068 165 095 110 065 115 0 3 0 0 0 0 10171 01 18 103 060 126 050 080 126 2 0 0 0 0 0 10172 11 17 070 140 070 105 110 065 0 2 0 0 0 0 10173 11 14 095 075 180 030 130 080 0 0 2 0 0 0 10174 09 05 075 125 230 030 055 095 0 0 2 0 0 0 10175 01 03 083 080 080 121 135 080 0 0 0 3 0 0 10176 15 00 080 120 080 100 120 080 2 0 0 0 0 0 10177 06 18 050 160 110 110 160 110 0 0 1 0 0 2 10178 09 14 080 145 150 110 105 110 0 0 3 0 0 0 10179 11 00 100 150 090 090 180 160 0 0 0 0 3 0 10180 05 10 100 180 160 090 150 090 0 3 0 0 0 0 10181 16 03 105 180 100 115 180 100 0 2 0 0 1 0 10182 13 00 035 055 040 090 050 050 0 0 0 2 0 0 10183 13 00 035 055 040 090 050 050 0 0 0 2 0 0 10184 13 00 035 055 040 090 050 050 0 0 0 2 0 0 10185 13 00 035 055 040 090 050 050 0 0 0 2 0 0 10186 13 00 035 055 040 090 050 050 0 0 0 2 0 0 10187 13 00 035 055 040 090 050 050 0 0 0 2 0 0 10188 14 17 080 160 060 080 170 130 0 0 0 0 3 0 10189 10 05 070 120 100 020 145 105 0 1 0 0 1 0 10190 01 02 065 136 094 135 054 096 0 0 0 2 0 0 10191 16 03 095 145 130 120 120 090 0 3 0 0 0 0 10192 07 04 065 150 040 145 015 080 0 2 0 0 0 1 ================================================ FILE: VeekunImport/form_values.txt ================================================ 201 201 0 201 10001 1 201 10002 2 201 10003 3 201 10004 4 201 10005 5 201 10006 6 201 10007 7 201 10008 8 201 10009 9 201 10010 10 201 10011 11 201 10012 12 201 10013 13 201 10014 14 201 10015 15 201 10016 16 201 10017 17 201 10018 18 201 10019 19 201 10020 20 201 10021 21 201 10022 22 201 10023 23 201 10024 24 201 10025 25 201 10026 26 201 10027 27 493 493 0 493 10045 1 493 10047 2 493 10052 3 493 10050 4 493 10054 5 493 10041 6 493 10048 7 493 10055 8 493 10046 9 493 10056 10 493 10049 11 493 10044 12 493 10053 13 493 10051 14 493 10043 15 493 10042 16 493 10057 31 493 10085 17 646 646 0 646 10083 1 646 10082 2 649 649 0 649 10075 1 649 10076 2 649 10077 3 649 10078 4 676 676 0 676 10115 1 676 10116 2 676 10117 3 676 10118 4 676 10119 5 676 10120 6 676 10121 7 676 10122 8 676 10123 9 ================================================ FILE: VeekunImport/items3.txt ================================================ 1 Master Ball 3001 2 Ultra Ball 3002 3 Great Ball 3003 4 Poké Ball 3004 5 Safari Ball 3005 6 Net Ball 3006 7 Dive Ball 3007 8 Nest Ball 3008 9 Repeat Ball 3009 10 Timer Ball 3010 11 Luxury Ball 3011 12 Premier Ball 3012 13 Potion 3013 14 Antidote 3014 15 Burn Heal 3015 16 Ice Heal 3016 17 Awakening 3017 18 Parlyz Heal 3018 19 Full Restore 3019 20 Max Potion 3020 21 Hyper Potion 3021 22 Super Potion 3022 23 Full Heal 3023 24 Revive 3024 25 Max Revive 3025 26 Fresh Water 3026 27 Soda Pop 3027 28 Lemonade 3028 29 Moomoo Milk 3029 30 EnergyPowder 3030 31 Energy Root 3031 32 Heal Powder 3032 33 Revival Herb 3033 34 Ether 3034 35 Max Ether 3035 36 Elixir 3036 37 Max Elixir 3037 38 Lava Cookie 3038 39 Blue Flute 3039 40 Yellow Flute 3040 41 Red Flute 3041 42 Black Flute 3042 43 White Flute 3043 44 Berry Juice 3044 45 Sacred Ash 3045 46 Shoal Salt 3046 47 Shoal Shell 3047 48 Red Shard 3048 49 Blue Shard 3049 50 Yellow Shard 3050 51 Green Shard 3051 63 HP Up 3063 64 Protein 3064 65 Iron 3065 66 Carbos 3066 67 Calcium 3067 68 Rare Candy 3068 69 PP Up 3069 70 Zinc 3070 71 PP Max 3071 73 Guard Spec. 3073 74 Dire Hit 3074 75 X Attack 3075 76 X Defend 3076 77 X Speed 3077 78 X Accuracy 3078 79 X Special 3079 80 Poké Doll 3080 81 Fluffy Tail 3081 83 Super Repel 3083 84 Max Repel 3084 85 Escape Rope 3085 86 Repel 3086 93 Sun Stone 3093 94 Moon Stone 3094 95 Fire Stone 3095 96 Thunder Stone 3096 97 Water Stone 3097 98 Leaf Stone 3098 103 TinyMushroom 3103 104 Big Mushroom 3104 106 Pearl 3106 107 Big Pearl 3107 108 Stardust 3108 109 Star Piece 3109 110 Nugget 3110 111 Heart Scale 3111 121 Orange Mail 3121 122 Harbor Mail 3122 123 Glitter Mail 3123 124 Mech Mail 3124 125 Wood Mail 3125 126 Wave Mail 3126 127 Bead Mail 3127 128 Shadow Mail 3128 129 Tropic Mail 3129 130 Dream Mail 3130 131 Fab Mail 3131 132 Retro Mail 3132 133 Cheri Berry 3133 134 Chesto Berry 3134 135 Pecha Berry 3135 136 Rawst Berry 3136 137 Aspear Berry 3137 138 Leppa Berry 3138 139 Oran Berry 3139 140 Persim Berry 3140 141 Lum Berry 3141 142 Sitrus Berry 3142 143 Figy Berry 3143 144 Wiki Berry 3144 145 Mago Berry 3145 146 Aguav Berry 3146 147 Iapapa Berry 3147 148 Razz Berry 3148 149 Bluk Berry 3149 150 Nanab Berry 3150 151 Wepear Berry 3151 152 Pinap Berry 3152 153 Pomeg Berry 3153 154 Kelpsy Berry 3154 155 Qualot Berry 3155 156 Hondew Berry 3156 157 Grepa Berry 3157 158 Tamato Berry 3158 159 Cornn Berry 3159 160 Magost Berry 3160 161 Rabuta Berry 3161 162 Nomel Berry 3162 163 Spelon Berry 3163 164 Pamtre Berry 3164 165 Watmel Berry 3165 166 Durin Berry 3166 167 Belue Berry 3167 168 Liechi Berry 3168 169 Ganlon Berry 3169 170 Salac Berry 3170 171 Petaya Berry 3171 172 Apicot Berry 3172 173 Lansat Berry 3173 174 Starf Berry 3174 175 Enigma Berry 3175 179 BrightPowder 3179 180 White Herb 3180 181 Macho Brace 3181 182 Exp. Share 3182 183 Quick Claw 3183 184 Soothe Bell 3184 185 Mental Herb 3185 186 Choice Band 3186 187 King's Rock 3187 188 SilverPowder 3188 189 Amulet Coin 3189 190 Cleanse Tag 3190 191 Soul Dew 3191 192 DeepSeaTooth 3192 193 DeepSeaScale 3193 194 Smoke Ball 3194 195 Everstone 3195 196 Focus Band 3196 197 Lucky Egg 3197 198 Scope Lens 3198 199 Metal Coat 3199 200 Leftovers 3200 201 Dragon Scale 3201 202 Light Ball 3202 203 Soft Sand 3203 204 Hard Stone 3204 205 Miracle Seed 3205 206 BlackGlasses 3206 207 Black Belt 3207 208 Magnet 3208 209 Mystic Water 3209 210 Sharp Beak 3210 211 Poison Barb 3211 212 NeverMeltIce 3212 213 Spell Tag 3213 214 TwistedSpoon 3214 215 Charcoal 3215 216 Dragon Fang 3216 217 Silk Scarf 3217 218 Up-Grade 3218 219 Shell Bell 3219 220 Sea Incense 3220 221 Lax Incense 3221 222 Lucky Punch 3222 223 Metal Powder 3223 224 Thick Club 3224 225 Stick 3225 254 Red Scarf 3254 255 Blue Scarf 3255 256 Pink Scarf 3256 257 Green Scarf 3257 258 Yellow Scarf 3258 259 Mach Bike 3259 260 Coin Case 3260 261 Itemfinder 3261 262 Old Rod 3262 263 Good Rod 3263 264 Super Rod 3264 265 S.S. Ticket 3265 266 Contest Pass 3266 268 Wailmer Pail 3268 269 Devon Goods 3269 270 Soot Sack 3270 271 Basement Key 3271 272 Acro Bike 3272 273 Pokéblock Case 3273 274 Letter 3274 275 Eon Ticket 3275 276 Red Orb 3276 277 Blue Orb 3277 278 Scanner 3278 279 Go-Goggles 3279 280 Meteorite 3280 281 Rm. 1 Key 3281 282 Rm. 2 Key 3282 283 Rm. 4 Key 3283 284 Rm. 6 Key 3284 285 Storage Key 3285 286 Root Fossil 3286 287 Claw Fossil 3287 288 Devon Scope 3288 289 TM01 3289 290 TM02 3290 291 TM03 3291 292 TM04 3292 293 TM05 3293 294 TM06 3294 295 TM07 3295 296 TM08 3296 297 TM09 3297 298 TM10 3298 299 TM11 3299 300 TM12 3300 301 TM13 3301 302 TM14 3302 303 TM15 3303 304 TM16 3304 305 TM17 3305 306 TM18 3306 307 TM19 3307 308 TM20 3308 309 TM21 3309 310 TM22 3310 311 TM23 3311 312 TM24 3312 313 TM25 3313 314 TM26 3314 315 TM27 3315 316 TM28 3316 317 TM29 3317 318 TM30 3318 319 TM31 3319 320 TM32 3320 321 TM33 3321 322 TM34 3322 323 TM35 3323 324 TM36 3324 325 TM37 3325 326 TM38 3326 327 TM39 3327 328 TM40 3328 329 TM41 3329 330 TM42 3330 331 TM43 3331 332 TM44 3332 333 TM45 3333 334 TM46 3334 335 TM47 3335 336 TM48 3336 337 TM49 3337 338 TM50 3338 339 HM01 3339 340 HM02 3340 341 HM03 3341 342 HM04 3342 343 HM05 3343 344 HM06 3344 345 HM07 3345 346 HM08 3346 349 Oak's Parcel 3349 350 Poké Flute 3350 351 Secret Key 3351 352 Bike Voucher 3352 353 Gold Teeth 3353 354 Old Amber 3354 355 Card Key 3355 356 Lift Key 3356 357 Dome Fossil 3357 358 Helix Fossil 3358 359 Silph Scope 3359 360 Bicycle 3360 361 Town Map 3361 362 Vs. Seeker 3362 363 Fame Checker 3363 364 TM Case 3364 365 Berry Pouch 3365 366 Teachy TV 3366 367 Tri-Pass 3367 368 Rainbow Pass 3368 369 Tea 3369 370 MysticTicket 3370 371 AuroraTicket 3371 372 Powder Jar 3372 373 Ruby 3373 374 Sapphire 3374 375 Magma Emblem 3375 376 Old Sea Map 3376 ================================================ FILE: VeekunImport/items4.txt ================================================ 1 Master Ball 3001 2 Ultra Ball 3002 3 Great Ball 3003 4 Poké Ball 3004 5 Safari Ball 3005 6 Net Ball 3006 7 Dive Ball 3007 8 Nest Ball 3008 9 Repeat Ball 3009 10 Timer Ball 3010 11 Luxury Ball 3011 12 Premier Ball 3012 13 Dusk Ball 4013 14 Heal Ball 4014 15 Quick Ball 4015 16 Cherish Ball 4016 17 Potion 3013 18 Antidote 3014 19 Burn Heal 3015 20 Ice Heal 3016 21 Awakening 3017 22 Parlyz Heal 3018 23 Full Restore 3019 24 Max Potion 3020 25 Hyper Potion 3021 26 Super Potion 3022 27 Full Heal 3023 28 Revive 3024 29 Max Revive 3025 30 Fresh Water 3026 31 Soda Pop 3027 32 Lemonade 3028 33 Moomoo Milk 3029 34 EnergyPowder 3030 35 Energy Root 3031 36 Heal Powder 3032 37 Revival Herb 3033 38 Ether 3034 39 Max Ether 3035 40 Elixir 3036 41 Max Elixir 3037 42 Lava Cookie 3038 43 Berry Juice 3044 44 Sacred Ash 3045 45 HP Up 3063 46 Protein 3064 47 Iron 3065 48 Carbos 3066 49 Calcium 3067 50 Rare Candy 3068 51 PP Up 3069 52 Zinc 3070 53 PP Max 3071 54 Old Gateau 4054 55 Guard Spec. 3073 56 Dire Hit 3074 57 X Attack 3075 58 X Defend 3076 59 X Speed 3077 60 X Accuracy 3078 61 X Special 3079 62 X Sp. Def 4062 63 Poké Doll 3080 64 Fluffy Tail 3081 65 Blue Flute 3039 66 Yellow Flute 3040 67 Red Flute 3041 68 Black Flute 3042 69 White Flute 3043 70 Shoal Salt 3046 71 Shoal Shell 3047 72 Red Shard 3048 73 Blue Shard 3049 74 Yellow Shard 3050 75 Green Shard 3051 76 Super Repel 3083 77 Max Repel 3084 78 Escape Rope 3085 79 Repel 3086 80 Sun Stone 3093 81 Moon Stone 3094 82 Fire Stone 3095 83 Thunderstone 3096 84 Water Stone 3097 85 Leaf Stone 3098 86 TinyMushroom 3103 87 Big Mushroom 3104 88 Pearl 3106 89 Big Pearl 3107 90 Stardust 3108 91 Star Piece 3109 92 Nugget 3110 93 Heart Scale 3111 94 Honey 4094 95 Growth Mulch 4095 96 Damp Mulch 4096 97 Stable Mulch 4097 98 Gooey Mulch 4098 99 Root Fossil 3286 100 Claw Fossil 3287 101 Helix Fossil 3358 102 Dome Fossil 3357 103 Old Amber 3354 104 Armor Fossil 4104 105 Skull Fossil 4105 106 Rare Bone 4106 107 Shiny Stone 4107 108 Dusk Stone 4108 109 Dawn Stone 4109 110 Oval Stone 4110 111 Odd Keystone 4111 112 Griseous Orb 4112 135 Adamant Orb 4135 136 Lustrous Orb 4136 137 Grass Mail 4137 138 Flame Mail 4138 139 Bubble Mail 4139 140 Bloom Mail 4140 141 Tunnel Mail 4141 142 Steel Mail 4142 143 Heart Mail 4143 144 Snow Mail 4144 145 Space Mail 4145 146 Air Mail 4146 147 Mosaic Mail 4147 148 Brick Mail 4148 149 Cheri Berry 3133 150 Chesto Berry 3134 151 Pecha Berry 3135 152 Rawst Berry 3136 153 Aspear Berry 3137 154 Leppa Berry 3138 155 Oran Berry 3139 156 Persim Berry 3140 157 Lum Berry 3141 158 Sitrus Berry 3142 159 Figy Berry 3143 160 Wiki Berry 3144 161 Mago Berry 3145 162 Aguav Berry 3146 163 Iapapa Berry 3147 164 Razz Berry 3148 165 Bluk Berry 3149 166 Nanab Berry 3150 167 Wepear Berry 3151 168 Pinap Berry 3152 169 Pomeg Berry 3153 170 Kelpsy Berry 3154 171 Qualot Berry 3155 172 Hondew Berry 3156 173 Grepa Berry 3157 174 Tamato Berry 3158 175 Cornn Berry 3159 176 Magost Berry 3160 177 Rabuta Berry 3161 178 Nomel Berry 3162 179 Spelon Berry 3163 180 Pamtre Berry 3164 181 Watmel Berry 3165 182 Durin Berry 3166 183 Belue Berry 3167 184 Occa Berry 4184 185 Passho Berry 4185 186 Wacan Berry 4186 187 Rindo Berry 4187 188 Yache Berry 4188 189 Chople Berry 4189 190 Kebia Berry 4190 191 Shuca Berry 4191 192 Coba Berry 4192 193 Payapa Berry 4193 194 Tanga Berry 4194 195 Charti Berry 4195 196 Kasib Berry 4196 197 Haban Berry 4197 198 Colbur Berry 4198 199 Babiri Berry 4199 200 Chilan Berry 4200 201 Liechi Berry 3168 202 Ganlon Berry 3169 203 Salac Berry 3170 204 Petaya Berry 3171 205 Apicot Berry 3172 206 Lansat Berry 3173 207 Starf Berry 3174 208 Enigma Berry 3175 209 Micle Berry 4209 210 Custap Berry 4210 211 Jaboca Berry 4211 212 Rowap Berry 4212 213 BrightPowder 3179 214 White Herb 3180 215 Macho Brace 3181 216 Exp. Share 3182 217 Quick Claw 3183 218 Soothe Bell 3184 219 Mental Herb 3185 220 Choice Band 3186 221 King’s Rock 3187 222 SilverPowder 3188 223 Amulet Coin 3189 224 Cleanse Tag 3190 225 Soul Dew 3191 226 DeepSeaTooth 3192 227 DeepSeaScale 3193 228 Smoke Ball 3194 229 Everstone 3195 230 Focus Band 3196 231 Lucky Egg 3197 232 Scope Lens 3198 233 Metal Coat 3199 234 Leftovers 3200 235 Dragon Scale 3201 236 Light Ball 3202 237 Soft Sand 3203 238 Hard Stone 3204 239 Miracle Seed 3205 240 BlackGlasses 3206 241 Black Belt 3207 242 Magnet 3208 243 Mystic Water 3209 244 Sharp Beak 3210 245 Poison Barb 3211 246 NeverMeltIce 3212 247 Spell Tag 3213 248 TwistedSpoon 3214 249 Charcoal 3215 250 Dragon Fang 3216 251 Silk Scarf 3217 252 Up-Grade 3218 253 Shell Bell 3219 254 Sea Incense 3220 255 Lax Incense 3221 256 Lucky Punch 3222 257 Metal Powder 3223 258 Thick Club 3224 259 Stick 3225 260 Red Scarf 3254 261 Blue Scarf 3255 262 Pink Scarf 3256 263 Green Scarf 3257 264 Yellow Scarf 3258 265 Wide Lens 4265 266 Muscle Band 4266 267 Wise Glasses 4267 268 Expert Belt 4268 269 Light Clay 4269 270 Life Orb 4270 271 Power Herb 4271 272 Toxic Orb 4272 273 Flame Orb 4273 274 Quick Powder 4274 275 Focus Sash 4275 276 Zoom Lens 4276 277 Metronome 4277 278 Iron Ball 4278 279 Lagging Tail 4279 280 Destiny Knot 4280 281 Black Sludge 4281 282 Icy Rock 4282 283 Smooth Rock 4283 284 Heat Rock 4284 285 Damp Rock 4285 286 Grip Claw 4286 287 Choice Scarf 4287 288 Sticky Barb 4288 289 Power Bracer 4289 290 Power Belt 4290 291 Power Lens 4291 292 Power Band 4292 293 Power Anklet 4293 294 Power Weight 4294 295 Shed Shell 4295 296 Big Root 4296 297 Choice Specs 4297 298 Flame Plate 4298 299 Splash Plate 4299 300 Zap Plate 4300 301 Meadow Plate 4301 302 Icicle Plate 4302 303 Fist Plate 4303 304 Toxic Plate 4304 305 Earth Plate 4305 306 Sky Plate 4306 307 Mind Plate 4307 308 Insect Plate 4308 309 Stone Plate 4309 310 Spooky Plate 4310 311 Draco Plate 4311 312 Dread Plate 4312 313 Iron Plate 4313 314 Odd Incense 4314 315 Rock Incense 4315 316 Full Incense 4316 317 Wave Incense 4317 318 Rose Incense 4318 319 Luck Incense 4319 320 Pure Incense 4320 321 Protector 4321 322 Electirizer 4322 323 Magmarizer 4323 324 Dubious Disc 4324 325 Reaper Cloth 4325 326 Razor Claw 4326 327 Razor Fang 4327 328 TM01 3289 329 TM02 3290 330 TM03 3291 331 TM04 3292 332 TM05 3293 333 TM06 3294 334 TM07 3295 335 TM08 3296 336 TM09 3297 337 TM10 3298 338 TM11 3299 339 TM12 3300 340 TM13 3301 341 TM14 3302 342 TM15 3303 343 TM16 3304 344 TM17 3305 345 TM18 3306 346 TM19 3307 347 TM20 3308 348 TM21 3309 349 TM22 3310 350 TM23 3311 351 TM24 3312 352 TM25 3313 353 TM26 3314 354 TM27 3315 355 TM28 3316 356 TM29 3317 357 TM30 3318 358 TM31 3319 359 TM32 3320 360 TM33 3321 361 TM34 3322 362 TM35 3323 363 TM36 3324 364 TM37 3325 365 TM38 3326 366 TM39 3327 367 TM40 3328 368 TM41 3329 369 TM42 3330 370 TM43 3331 371 TM44 3332 372 TM45 3333 373 TM46 3334 374 TM47 3335 375 TM48 3336 376 TM49 3337 377 TM50 3338 378 TM51 4378 379 TM52 4379 380 TM53 4380 381 TM54 4381 382 TM55 4382 383 TM56 4383 384 TM57 4384 385 TM58 4385 386 TM59 4386 387 TM60 4387 388 TM61 4388 389 TM62 4389 390 TM63 4390 391 TM64 4391 392 TM65 4392 393 TM66 4393 394 TM67 4394 395 TM68 4395 396 TM69 4396 397 TM70 4397 398 TM71 4398 399 TM72 4399 400 TM73 4400 401 TM74 4401 402 TM75 4402 403 TM76 4403 404 TM77 4404 405 TM78 4405 406 TM79 4406 407 TM80 4407 408 TM81 4408 409 TM82 4409 410 TM83 4410 411 TM84 4411 412 TM85 4412 413 TM86 4413 414 TM87 4414 415 TM88 4415 416 TM89 4416 417 TM90 4417 418 TM91 4418 419 TM92 4419 420 HM01 3339 421 HM02 3340 422 HM03 3341 423 HM04 3342 424 HM05 3343 425 HM06 3344 426 HM07 3345 427 HM08 3346 428 Explorer Kit 4428 429 Loot Sack 4429 430 Rule Book 4430 431 Poké Radar 4431 432 Point Card 4432 433 Journal 4433 434 Seal Case 4434 435 Fashion Case 4435 436 Seal Bag 4436 437 Pal Pad 4437 438 Works Key 4438 439 Old Charm 4439 440 Galactic Key 4440 441 Red Chain 4441 442 Town Map 3361 443 Vs. Seeker 3362 444 Coin Case 3260 445 Old Rod 3262 446 Good Rod 3263 447 Super Rod 3264 448 Sprayduck 4448 449 Poffin Case 4449 450 Bicycle 3360 451 Suite Key 4451 452 Oak’s Letter 4452 453 Lunar Wing 4453 454 Member Card 4454 455 Azure Flute 4455 456 S.S. Ticket 3265 457 Contest Pass 3266 458 Magma Stone 4458 459 Parcel 4459 460 Coupon 1 4460 461 Coupon 2 4461 462 Coupon 3 4462 463 Storage Key 4463 464 SecretPotion 4464 465 Vs. Recorder 4465 466 Gracidea 4466 467 Secret Key 4467 468 Apricorn Box 4468 469 UNOWN Report 4469 470 Berry Pots 4470 471 Dowsing MCHN 4471 472 Blue Card 4472 473 SlowpokeTail 4473 474 Clear Bell 4474 475 Card Key 4475 476 Basement Key 4476 477 SquirtBottle 4477 478 Red Scale 4478 479 Lost Item 4479 480 Pass 4480 481 Machine Part 4481 482 Silver Wing 4482 483 Rainbow Wing 4483 484 Mystery Egg 4484 485 Red Apricorn 4485 486 Ylw Apricorn 4486 487 Blu Apricorn 4487 488 Grn Apricorn 4488 489 Pnk Apricorn 4489 490 Wht Apricorn 4490 491 Blk Apricorn 4491 492 Fast Ball 4492 493 Level Ball 4493 494 Lure Ball 4494 495 Heavy Ball 4495 496 Love Ball 4496 497 Friend Ball 4497 498 Moon Ball 4498 499 Sport Ball 4499 500 Park Ball 4500 501 Photo Album 4501 502 GB Sounds 4502 503 Tidal Bell 4503 504 RageCandyBar 4504 505 Data Card 01 4505 506 Data Card 02 4506 507 Data Card 03 4507 508 Data Card 04 4508 509 Data Card 05 4509 510 Data Card 06 4510 511 Data Card 07 4511 512 Data Card 08 4512 513 Data Card 09 4513 514 Data Card 10 4514 515 Data Card 11 4515 516 Data Card 12 4516 517 Data Card 13 4517 518 Data Card 14 4518 519 Data Card 15 4519 520 Data Card 16 4520 521 Data Card 17 4521 522 Data Card 18 4522 523 Data Card 19 4523 524 Data Card 20 4524 525 Data Card 21 4525 526 Data Card 22 4526 527 Data Card 23 4527 528 Data Card 24 4528 529 Data Card 25 4529 530 Data Card 26 4530 531 Data Card 27 4531 532 Jade Orb 4532 533 Lock Capsule 4533 534 Red Orb 3276 535 Blue Orb 3277 536 Enigma Stone 4536 ================================================ FILE: VeekunImport/items5.txt ================================================ 1 Master Ball 3001 2 Ultra Ball 3002 3 Great Ball 3003 4 Poké Ball 3004 5 Safari Ball 3005 6 Net Ball 3006 7 Dive Ball 3007 8 Nest Ball 3008 9 Repeat Ball 3009 10 Timer Ball 3010 11 Luxury Ball 3011 12 Premier Ball 3012 13 Dusk Ball 4013 14 Heal Ball 4014 15 Quick Ball 4015 16 Cherish Ball 4016 17 Potion 3013 18 Antidote 3014 19 Burn Heal 3015 20 Ice Heal 3016 21 Awakening 3017 22 Parlyz Heal 3018 23 Full Restore 3019 24 Max Potion 3020 25 Hyper Potion 3021 26 Super Potion 3022 27 Full Heal 3023 28 Revive 3024 29 Max Revive 3025 30 Fresh Water 3026 31 Soda Pop 3027 32 Lemonade 3028 33 Moomoo Milk 3029 34 EnergyPowder 3030 35 Energy Root 3031 36 Heal Powder 3032 37 Revival Herb 3033 38 Ether 3034 39 Max Ether 3035 40 Elixir 3036 41 Max Elixir 3037 42 Lava Cookie 3038 43 Berry Juice 3044 44 Sacred Ash 3045 45 HP Up 3063 46 Protein 3064 47 Iron 3065 48 Carbos 3066 49 Calcium 3067 50 Rare Candy 3068 51 PP Up 3069 52 Zinc 3070 53 PP Max 3071 54 Old Gateau 4054 55 Guard Spec. 3073 56 Dire Hit 3074 57 X Attack 3075 58 X Defend 3076 59 X Speed 3077 60 X Accuracy 3078 61 X Special 3079 62 X Sp. Def 4062 63 Poké Doll 3080 64 Fluffy Tail 3081 65 Blue Flute 3039 66 Yellow Flute 3040 67 Red Flute 3041 68 Black Flute 3042 69 White Flute 3043 70 Shoal Salt 3046 71 Shoal Shell 3047 72 Red Shard 3048 73 Blue Shard 3049 74 Yellow Shard 3050 75 Green Shard 3051 76 Super Repel 3083 77 Max Repel 3084 78 Escape Rope 3085 79 Repel 3086 80 Sun Stone 3093 81 Moon Stone 3094 82 Fire Stone 3095 83 Thunderstone 3096 84 Water Stone 3097 85 Leaf Stone 3098 86 TinyMushroom 3103 87 Big Mushroom 3104 88 Pearl 3106 89 Big Pearl 3107 90 Stardust 3108 91 Star Piece 3109 92 Nugget 3110 93 Heart Scale 3111 94 Honey 4094 95 Growth Mulch 4095 96 Damp Mulch 4096 97 Stable Mulch 4097 98 Gooey Mulch 4098 99 Root Fossil 3286 100 Claw Fossil 3287 101 Helix Fossil 3358 102 Dome Fossil 3357 103 Old Amber 3354 104 Armor Fossil 4104 105 Skull Fossil 4105 106 Rare Bone 4106 107 Shiny Stone 4107 108 Dusk Stone 4108 109 Dawn Stone 4109 110 Oval Stone 4110 111 Odd Keystone 4111 112 Griseous Orb 4112 116 Douse Drive 5116 117 Shock Drive 5117 118 Burn Drive 5118 119 Chill Drive 5119 134 Sweet Heart 5134 135 Adamant Orb 4135 136 Lustrous Orb 4136 137 Greet Mail 5137 138 Favored Mail 5138 139 RSVP Mail 5139 140 Thanks Mail 5140 141 Inquiry Mail 5141 142 Like Mail 5142 143 Reply Mail 5143 144 BridgeMail S 5144 145 BridgeMail D 5145 146 BridgeMail T 5146 147 BridgeMail V 5147 148 BridgeMail M 5148 149 Cheri Berry 3133 150 Chesto Berry 3134 151 Pecha Berry 3135 152 Rawst Berry 3136 153 Aspear Berry 3137 154 Leppa Berry 3138 155 Oran Berry 3139 156 Persim Berry 3140 157 Lum Berry 3141 158 Sitrus Berry 3142 159 Figy Berry 3143 160 Wiki Berry 3144 161 Mago Berry 3145 162 Aguav Berry 3146 163 Iapapa Berry 3147 164 Razz Berry 3148 165 Bluk Berry 3149 166 Nanab Berry 3150 167 Wepear Berry 3151 168 Pinap Berry 3152 169 Pomeg Berry 3153 170 Kelpsy Berry 3154 171 Qualot Berry 3155 172 Hondew Berry 3156 173 Grepa Berry 3157 174 Tamato Berry 3158 175 Cornn Berry 3159 176 Magost Berry 3160 177 Rabuta Berry 3161 178 Nomel Berry 3162 179 Spelon Berry 3163 180 Pamtre Berry 3164 181 Watmel Berry 3165 182 Durin Berry 3166 183 Belue Berry 3167 184 Occa Berry 4184 185 Passho Berry 4185 186 Wacan Berry 4186 187 Rindo Berry 4187 188 Yache Berry 4188 189 Chople Berry 4189 190 Kebia Berry 4190 191 Shuca Berry 4191 192 Coba Berry 4192 193 Payapa Berry 4193 194 Tanga Berry 4194 195 Charti Berry 4195 196 Kasib Berry 4196 197 Haban Berry 4197 198 Colbur Berry 4198 199 Babiri Berry 4199 200 Chilan Berry 4200 201 Liechi Berry 3168 202 Ganlon Berry 3169 203 Salac Berry 3170 204 Petaya Berry 3171 205 Apicot Berry 3172 206 Lansat Berry 3173 207 Starf Berry 3174 208 Enigma Berry 3175 209 Micle Berry 4209 210 Custap Berry 4210 211 Jaboca Berry 4211 212 Rowap Berry 4212 213 BrightPowder 3179 214 White Herb 3180 215 Macho Brace 3181 216 Exp. Share 3182 217 Quick Claw 3183 218 Soothe Bell 3184 219 Mental Herb 3185 220 Choice Band 3186 221 King’s Rock 3187 222 SilverPowder 3188 223 Amulet Coin 3189 224 Cleanse Tag 3190 225 Soul Dew 3191 226 DeepSeaTooth 3192 227 DeepSeaScale 3193 228 Smoke Ball 3194 229 Everstone 3195 230 Focus Band 3196 231 Lucky Egg 3197 232 Scope Lens 3198 233 Metal Coat 3199 234 Leftovers 3200 235 Dragon Scale 3201 236 Light Ball 3202 237 Soft Sand 3203 238 Hard Stone 3204 239 Miracle Seed 3205 240 BlackGlasses 3206 241 Black Belt 3207 242 Magnet 3208 243 Mystic Water 3209 244 Sharp Beak 3210 245 Poison Barb 3211 246 NeverMeltIce 3212 247 Spell Tag 3213 248 TwistedSpoon 3214 249 Charcoal 3215 250 Dragon Fang 3216 251 Silk Scarf 3217 252 Up-Grade 3218 253 Shell Bell 3219 254 Sea Incense 3220 255 Lax Incense 3221 256 Lucky Punch 3222 257 Metal Powder 3223 258 Thick Club 3224 259 Stick 3225 260 Red Scarf 3254 261 Blue Scarf 3255 262 Pink Scarf 3256 263 Green Scarf 3257 264 Yellow Scarf 3258 265 Wide Lens 4265 266 Muscle Band 4266 267 Wise Glasses 4267 268 Expert Belt 4268 269 Light Clay 4269 270 Life Orb 4270 271 Power Herb 4271 272 Toxic Orb 4272 273 Flame Orb 4273 274 Quick Powder 4274 275 Focus Sash 4275 276 Zoom Lens 4276 277 Metronome 4277 278 Iron Ball 4278 279 Lagging Tail 4279 280 Destiny Knot 4280 281 Black Sludge 4281 282 Icy Rock 4282 283 Smooth Rock 4283 284 Heat Rock 4284 285 Damp Rock 4285 286 Grip Claw 4286 287 Choice Scarf 4287 288 Sticky Barb 4288 289 Power Bracer 4289 290 Power Belt 4290 291 Power Lens 4291 292 Power Band 4292 293 Power Anklet 4293 294 Power Weight 4294 295 Shed Shell 4295 296 Big Root 4296 297 Choice Specs 4297 298 Flame Plate 4298 299 Splash Plate 4299 300 Zap Plate 4300 301 Meadow Plate 4301 302 Icicle Plate 4302 303 Fist Plate 4303 304 Toxic Plate 4304 305 Earth Plate 4305 306 Sky Plate 4306 307 Mind Plate 4307 308 Insect Plate 4308 309 Stone Plate 4309 310 Spooky Plate 4310 311 Draco Plate 4311 312 Dread Plate 4312 313 Iron Plate 4313 314 Odd Incense 4314 315 Rock Incense 4315 316 Full Incense 4316 317 Wave Incense 4317 318 Rose Incense 4318 319 Luck Incense 4319 320 Pure Incense 4320 321 Protector 4321 322 Electirizer 4322 323 Magmarizer 4323 324 Dubious Disc 4324 325 Reaper Cloth 4325 326 Razor Claw 4326 327 Razor Fang 4327 328 TM01 3289 329 TM02 3290 330 TM03 3291 331 TM04 3292 332 TM05 3293 333 TM06 3294 334 TM07 3295 335 TM08 3296 336 TM09 3297 337 TM10 3298 338 TM11 3299 339 TM12 3300 340 TM13 3301 341 TM14 3302 342 TM15 3303 343 TM16 3304 344 TM17 3305 345 TM18 3306 346 TM19 3307 347 TM20 3308 348 TM21 3309 349 TM22 3310 350 TM23 3311 351 TM24 3312 352 TM25 3313 353 TM26 3314 354 TM27 3315 355 TM28 3316 356 TM29 3317 357 TM30 3318 358 TM31 3319 359 TM32 3320 360 TM33 3321 361 TM34 3322 362 TM35 3323 363 TM36 3324 364 TM37 3325 365 TM38 3326 366 TM39 3327 367 TM40 3328 368 TM41 3329 369 TM42 3330 370 TM43 3331 371 TM44 3332 372 TM45 3333 373 TM46 3334 374 TM47 3335 375 TM48 3336 376 TM49 3337 377 TM50 3338 378 TM51 4378 379 TM52 4379 380 TM53 4380 381 TM54 4381 382 TM55 4382 383 TM56 4383 384 TM57 4384 385 TM58 4385 386 TM59 4386 387 TM60 4387 388 TM61 4388 389 TM62 4389 390 TM63 4390 391 TM64 4391 392 TM65 4392 393 TM66 4393 394 TM67 4394 395 TM68 4395 396 TM69 4396 397 TM70 4397 398 TM71 4398 399 TM72 4399 400 TM73 4400 401 TM74 4401 402 TM75 4402 403 TM76 4403 404 TM77 4404 405 TM78 4405 406 TM79 4406 407 TM80 4407 408 TM81 4408 409 TM82 4409 410 TM83 4410 411 TM84 4411 412 TM85 4412 413 TM86 4413 414 TM87 4414 415 TM88 4415 416 TM89 4416 417 TM90 4417 418 TM91 4418 419 TM92 4419 420 HM01 3339 421 HM02 3340 422 HM03 3341 423 HM04 3342 424 HM05 3343 425 HM06 3344 428 Explorer Kit 4428 429 Loot Sack 4429 430 Rule Book 4430 431 Poké Radar 4431 432 Point Card 4432 433 Journal 4433 434 Seal Case 4434 435 Fashion Case 4435 436 Seal Bag 4436 437 Pal Pad 4437 438 Works Key 4438 439 Old Charm 4439 440 Galactic Key 4440 441 Red Chain 4441 442 Town Map 3361 443 Vs. Seeker 3362 444 Coin Case 3260 445 Old Rod 3262 446 Good Rod 3263 447 Super Rod 3264 448 Sprayduck 4448 449 Poffin Case 4449 450 Bicycle 3360 451 Suite Key 4451 452 Oak’s Letter 4452 453 Lunar Wing 4453 454 Member Card 4454 455 Azure Flute 4455 456 S.S. Ticket 3265 457 Contest Pass 3266 458 Magma Stone 4458 459 Parcel 4459 460 Coupon 1 4460 461 Coupon 2 4461 462 Coupon 3 4462 463 Storage Key 4463 464 SecretPotion 4464 465 Vs. Recorder 4465 466 Gracidea 4466 467 Secret Key 4467 468 Apricorn Box 4468 469 UNOWN Report 4469 470 Berry Pots 4470 471 Dowsing MCHN 4471 472 Blue Card 4472 473 SlowpokeTail 4473 474 Clear Bell 4474 475 Card Key 4475 476 Basement Key 4476 477 SquirtBottle 4477 478 Red Scale 4478 479 Lost Item 4479 480 Pass 4480 481 Machine Part 4481 482 Silver Wing 4482 483 Rainbow Wing 4483 484 Mystery Egg 4484 485 Red Apricorn 4485 486 Ylw Apricorn 4486 487 Blu Apricorn 4487 488 Grn Apricorn 4488 489 Pnk Apricorn 4489 490 Wht Apricorn 4490 491 Blk Apricorn 4491 492 Fast Ball 4492 493 Level Ball 4493 494 Lure Ball 4494 495 Heavy Ball 4495 496 Love Ball 4496 497 Friend Ball 4497 498 Moon Ball 4498 499 Sport Ball 4499 500 Park Ball 4500 501 Photo Album 4501 502 GB Sounds 4502 503 Tidal Bell 4503 504 RageCandyBar 4504 505 Data Card 01 4505 506 Data Card 02 4506 507 Data Card 03 4507 508 Data Card 04 4508 509 Data Card 05 4509 510 Data Card 06 4510 511 Data Card 07 4511 512 Data Card 08 4512 513 Data Card 09 4513 514 Data Card 10 4514 515 Data Card 11 4515 516 Data Card 12 4516 517 Data Card 13 4517 518 Data Card 14 4518 519 Data Card 15 4519 520 Data Card 16 4520 521 Data Card 17 4521 522 Data Card 18 4522 523 Data Card 19 4523 524 Data Card 20 4524 525 Data Card 21 4525 526 Data Card 22 4526 527 Data Card 23 4527 528 Data Card 24 4528 529 Data Card 25 4529 530 Data Card 26 4530 531 Data Card 27 4531 532 Jade Orb 4532 533 Lock Capsule 4533 534 Red Orb 3276 535 Blue Orb 3277 536 Enigma Stone 4536 537 Prism Scale 5537 538 Eviolite 5538 539 Float Stone 5539 540 Rocky Helmet 5540 541 Air Balloon 5541 542 Red Card 5542 543 Ring Target 5543 544 Binding Band 5544 545 Absorb Bulb 5545 546 Cell Battery 5546 547 Eject Button 5547 548 Fire Gem 5548 549 Water Gem 5549 550 Electric Gem 5550 551 Grass Gem 5551 552 Ice Gem 5552 553 Fighting Gem 5553 554 Poison Gem 5554 555 Ground Gem 5555 556 Flying Gem 5556 557 Psychic Gem 5557 558 Bug Gem 5558 559 Rock Gem 5559 560 Ghost Gem 5560 561 Dragon Gem 5561 562 Dark Gem 5562 563 Steel Gem 5563 564 Normal Gem 5564 565 Health Wing 5565 566 Muscle Wing 5566 567 Resist Wing 5567 568 Genius Wing 5568 569 Clever Wing 5569 570 Swift Wing 5570 571 Pretty Wing 5571 572 Cover Fossil 5572 573 Plume Fossil 5573 574 Liberty Pass 5574 575 Pass Orb 5575 576 Dream Ball 5576 577 Poké Toy 5577 578 Prop Case 5578 579 Dragon Skull 5579 580 BalmMushroom 5580 581 Big Nugget 5581 582 Pearl String 5582 583 Comet Shard 5583 584 Relic Copper 5584 585 Relic Silver 5585 586 Relic Gold 5586 587 Relic Vase 5587 588 Relic Band 5588 589 Relic Statue 5589 590 Relic Crown 5590 591 Casteliacone 5591 592 Dire Hit 2 5592 593 X Speed 2 5593 594 X Special 2 5594 595 X Sp. Def 2 5595 596 X Defend 2 5596 597 X Attack 2 5597 598 X Accuracy 2 5598 599 X Speed 3 5599 600 X Special 3 5600 601 X Sp. Def 3 5601 602 X Defend 3 5602 603 X Attack 3 5603 604 X Accuracy 3 5604 605 X Speed 6 5605 606 X Special 6 5606 607 X Sp. Def 6 5607 608 X Defend 6 5608 609 X Attack 6 5609 610 X Accuracy 6 5610 611 Ability Urge 5611 612 Item Drop 5612 613 Item Urge 5613 614 Reset Urge 5614 615 Dire Hit 3 5615 616 Light Stone 5616 617 Dark Stone 5617 618 TM93 5618 619 TM94 5619 620 TM95 5620 621 Xtransceiver 5621 622 God Stone 5622 623 Gram 1 5623 624 Gram 2 5624 625 Gram 3 5625 626 Xtransceiver 5626 627 Medal Box 5627 628 DNA Splicers 5628 629 DNA Splicers 5629 630 Permit 5630 631 Oval Charm 5631 632 Shiny Charm 5632 633 Plasma Card 5633 634 Grubby Hanky 5634 635 Colress MCHN 5635 636 Dropped Item 5636 637 Dropped Item 5637 638 Reveal Glass 5638 ================================================ FILE: VeekunImport/items_balls.txt ================================================ 1 Master Ball 3001 2 Ultra Ball 3002 3 Great Ball 3003 4 Poké Ball 3004 5 Safari Ball 3005 6 Net Ball 3006 7 Dive Ball 3007 8 Nest Ball 3008 9 Repeat Ball 3009 10 Timer Ball 3010 11 Luxury Ball 3011 12 Premier Ball 3012 13 Dusk Ball 4013 14 Heal Ball 4014 15 Quick Ball 4015 16 Cherish Ball 4016 17 Fast Ball 4492 18 Level Ball 4493 19 Lure Ball 4494 20 Heavy Ball 4495 21 Love Ball 4496 22 Friend Ball 4497 23 Moon Ball 4498 24 Sport Ball 4499 25 Dream Ball 5576 #26 Beast Ball 7851 ================================================ FILE: VeekunImport/packages.config ================================================  ================================================ FILE: VeekunImport/regions.txt ================================================ 1 Event 2 Kanto 3 Johto 4 Hoenn 5 Orre 6 Sevii Islands 7 Sinnoh 8 Unova 9 Kalos ================================================ FILE: VeekunImport/ribbon_positions3.txt ================================================ 3021 15 ;Champion Ribbon 3022 16 ;Winning Ribbon 3023 17 ;Victory Ribbon 3024 18 ;Artist Ribbon 3025 19 ;Effort Ribbon ================================================ FILE: VeekunImport/ribbon_positions4.txt ================================================ 3001 0 ;Hoenn Cool Ribbon 3002 1 ;Hoenn Cool Ribbon Super 3003 2 ;Hoenn Cool Ribbon Hyper 3004 3 ;Hoenn Cool Ribbon Master 3005 4 ;Hoenn Beauty Ribbon 3006 5 ;Hoenn Beauty Ribbon Super 3007 6 ;Hoenn Beauty Ribbon Hyper 3008 7 ;Hoenn Beauty Ribbon Master 3009 8 ;Hoenn Cute Ribbon 3010 9 ;Hoenn Cute Ribbon Super 3011 10 ;Hoenn Cute Ribbon Hyper 3012 11 ;Hoenn Cute Ribbon Master 3013 12 ;Hoenn Smart Ribbon 3014 13 ;Hoenn Smart Ribbon Super 3015 14 ;Hoenn Smart Ribbon Hyper 3016 15 ;Hoenn Smart Ribbon Master 3017 16 ;Hoenn Tough Ribbon 3018 17 ;Hoenn Tough Ribbon Super 3019 18 ;Hoenn Tough Ribbon Hyper 3020 19 ;Hoenn Tough Ribbon Master 3021 20 ;Champion Ribbon 3022 21 ;Winning Ribbon 3023 22 ;Victory Ribbon 3024 23 ;Artist Ribbon 3025 24 ;Effort Ribbon 3026 25 ;Marine Ribbon 3027 26 ;Land Ribbon 3028 27 ;Sky Ribbon 3029 28 ;Country Ribbon 3030 29 ;National Ribbon 3031 30 ;Earth Ribbon 3032 31 ;World Ribbon 4001 32 ;Sinnoh Champ Ribbon 4002 33 ;Ability Ribbon 4003 34 ;Great Ability Ribbon 4004 35 ;Double Ability Ribbon 4005 36 ;Multi Ability Ribbon 4006 37 ;Pair Ability Ribbon 4007 38 ;World Ability Ribbon 4008 39 ;Alert Ribbon 4009 40 ;Shock Ribbon 4010 41 ;Downcast Ribbon 4011 42 ;Careless Ribbon 4012 43 ;Relax Ribbon 4013 44 ;Snooze Ribbon 4014 45 ;Smile Ribbon 4015 46 ;Gorgeous Ribbon 4016 47 ;Royal Ribbon 4017 48 ;Gorgeous Royal Ribbon 4018 49 ;Footprint Ribbon 4019 50 ;Record Ribbon 4020 51 ;History Ribbon 4021 52 ;Legend Ribbon 4022 53 ;Red Ribbon 4023 54 ;Green Ribbon 4024 55 ;Blue Ribbon 4025 56 ;Festival Ribbon 4026 57 ;Carnival Ribbon 4027 58 ;Classic Ribbon 4028 59 ;Premier Ribbon 4029 64 ;Sinnoh Cool Ribbon 4030 65 ;Sinnoh Cool Ribbon Great 4031 66 ;Sinnoh Cool Ribbon Ultra 4032 67 ;Sinnoh Cool Ribbon Master 4033 68 ;Sinnoh Beauty Ribbon 4034 69 ;Sinnoh Beauty Ribbon Great 4035 70 ;Sinnoh Beauty Ribbon Ultra 4036 71 ;Sinnoh Beauty Ribbon Master 4037 72 ;Sinnoh Cute Ribbon 4038 73 ;Sinnoh Cute Ribbon Great 4039 74 ;Sinnoh Cute Ribbon Ultra 4040 75 ;Sinnoh Cute Ribbon Master 4041 76 ;Sinnoh Smart Ribbon 4042 77 ;Sinnoh Smart Ribbon Great 4043 78 ;Sinnoh Smart Ribbon Ultra 4044 79 ;Sinnoh Smart Ribbon Master 4045 80 ;Sinnoh Tough Ribbon 4046 81 ;Sinnoh Tough Ribbon Great 4047 82 ;Sinnoh Tough Ribbon Ultra 4048 83 ;Sinnoh Tough Ribbon Master ================================================ FILE: VeekunImport/ribbon_positions5.txt ================================================ 3001 0 ;Hoenn Cool Ribbon 3002 1 ;Hoenn Cool Ribbon Super 3003 2 ;Hoenn Cool Ribbon Hyper 3004 3 ;Hoenn Cool Ribbon Master 3005 4 ;Hoenn Beauty Ribbon 3006 5 ;Hoenn Beauty Ribbon Super 3007 6 ;Hoenn Beauty Ribbon Hyper 3008 7 ;Hoenn Beauty Ribbon Master 3009 8 ;Hoenn Cute Ribbon 3010 9 ;Hoenn Cute Ribbon Super 3011 10 ;Hoenn Cute Ribbon Hyper 3012 11 ;Hoenn Cute Ribbon Master 3013 12 ;Hoenn Smart Ribbon 3014 13 ;Hoenn Smart Ribbon Super 3015 14 ;Hoenn Smart Ribbon Hyper 3016 15 ;Hoenn Smart Ribbon Master 3017 16 ;Hoenn Tough Ribbon 3018 17 ;Hoenn Tough Ribbon Super 3019 18 ;Hoenn Tough Ribbon Hyper 3020 19 ;Hoenn Tough Ribbon Master 3021 20 ;Champion Ribbon 3022 21 ;Winning Ribbon 3023 22 ;Victory Ribbon 3024 23 ;Artist Ribbon 3025 24 ;Effort Ribbon 5001 25 ;Battle Champion Ribbon 5002 26 ;Regional Champion Ribbon 5003 27 ;National Champion Ribbon 3029 28 ;Country Ribbon 3030 29 ;National Ribbon 3031 30 ;Earth Ribbon 3032 31 ;World Ribbon 4001 32 ;Sinnoh Champ Ribbon 4002 33 ;Ability Ribbon 4003 34 ;Great Ability Ribbon 4004 35 ;Double Ability Ribbon 4005 36 ;Multi Ability Ribbon 4006 37 ;Pair Ability Ribbon 4007 38 ;World Ability Ribbon 4008 39 ;Alert Ribbon 4009 40 ;Shock Ribbon 4010 41 ;Downcast Ribbon 4011 42 ;Careless Ribbon 4012 43 ;Relax Ribbon 4013 44 ;Snooze Ribbon 4014 45 ;Smile Ribbon 4015 46 ;Gorgeous Ribbon 4016 47 ;Royal Ribbon 4017 48 ;Gorgeous Royal Ribbon 4018 49 ;Footprint Ribbon 4019 50 ;Record Ribbon 5004 51 ;Event Ribbon 4021 52 ;Legend Ribbon 5005 53 ;World Champion Ribbon 5006 54 ;Birthday Ribbon 5007 55 ;Special Ribbon 5008 56 ;Souvenir Ribbon 5009 57 ;Wishing Ribbon 4027 58 ;Classic Ribbon 4028 59 ;Premier Ribbon 4029 64 ;Sinnoh Cool Ribbon 4030 65 ;Sinnoh Cool Ribbon Great 4031 66 ;Sinnoh Cool Ribbon Ultra 4032 67 ;Sinnoh Cool Ribbon Master 4033 68 ;Sinnoh Beauty Ribbon 4034 69 ;Sinnoh Beauty Ribbon Great 4035 70 ;Sinnoh Beauty Ribbon Ultra 4036 71 ;Sinnoh Beauty Ribbon Master 4037 72 ;Sinnoh Cute Ribbon 4038 73 ;Sinnoh Cute Ribbon Great 4039 74 ;Sinnoh Cute Ribbon Ultra 4040 75 ;Sinnoh Cute Ribbon Master 4041 76 ;Sinnoh Smart Ribbon 4042 77 ;Sinnoh Smart Ribbon Great 4043 78 ;Sinnoh Smart Ribbon Ultra 4044 79 ;Sinnoh Smart Ribbon Master 4045 80 ;Sinnoh Tough Ribbon 4046 81 ;Sinnoh Tough Ribbon Great 4047 82 ;Sinnoh Tough Ribbon Ultra 4048 83 ;Sinnoh Tough Ribbon Master ================================================ FILE: VeekunImport/ribbons.txt ================================================ 3001 Cool Ribbon Hoenn Cool Contest Normal Rank winner! 3002 Cool Ribbon Super Hoenn Cool Contest Super Rank winner! 3003 Cool Ribbon Hyper Hoenn Cool Contest Hyper Rank winner! 3004 Cool Ribbon Master Hoenn Cool Contest Master Rank winner! 3005 Beauty Ribbon Hoenn Beauty Contest Normal Rank winner! 3006 Beauty Ribbon Super Hoenn Beauty Contest Super Rank winner! 3007 Beauty Ribbon Hyper Hoenn Beauty Contest Hyper Rank winner! 3008 Beauty Ribbon Master Hoenn Beauty Contest Master Rank winner! 3009 Cute Ribbon Hoenn Cute Contest Normal Rank winner! 3010 Cute Ribbon Super Hoenn Cute Contest Super Rank winner! 3011 Cute Ribbon Hyper Hoenn Cute Contest Hyper Rank winner! 3012 Cute Ribbon Master Hoenn Cute Contest Master Rank winner! 3013 Smart Ribbon Hoenn Smart Contest Normal Rank winner! 3014 Smart Ribbon Super Hoenn Smart Contest Super Rank winner! 3015 Smart Ribbon Hyper Hoenn Smart Contest Hyper Rank winner! 3016 Smart Ribbon Master Hoenn Smart Contest Master Rank winner! 3017 Tough Ribbon Hoenn Tough Contest Normal Rank winner! 3018 Tough Ribbon Super Hoenn Tough Contest Super Rank winner! 3019 Tough Ribbon Hyper Hoenn Tough Contest Hyper Rank winner! 3020 Tough Ribbon Master Hoenn Tough Contest Master Rank winner! 3021 Champion Ribbon A Ribbon awarded for clearing the Pokémon League and entering the Hall of Fame in another region. 3022 Winning Ribbon Ribbon awarded for clearing Hoenn's Battle Tower's Lv. 50 challenge. 3023 Victory Ribbon Ribbon awarded for clearing Hoenn's Battle Tower's Lv. 100 challenge. 3024 Artist Ribbon A Ribbon awarded for being chosen as a super sketch model in the Hoenn Region. 3025 Effort Ribbon A Ribbon awarded for being an exceptionally hard worker. 3026 Marine Ribbon A commemorative Ribbon obtained in a Mystery Zone. 3027 Land Ribbon A commemorative Ribbon obtained in a Mystery Zone. 3028 Sky Ribbon A commemorative Ribbon obtained in a Mystery Zone. 3029 Country Ribbon A Ribbon awarded to a Pokémon League Champion. 3030 National Ribbon A Ribbon awarded for overcoming all difficult challenges. 3031 Earth Ribbon A Ribbon awarded for winning 100 battles in a row. 3032 World Ribbon A Ribbon awarded to a Pokémon League Champion. 4001 Sinnoh Champ Ribbon A Ribbon awarded for beating the Sinnoh Champion and entering the Sinnoh Hall of Fame. 4002 Ability Ribbon A Ribbon awarded for defeating the Tower Tycoon at the Battle Tower. 4003 Great Ability Ribbon A Ribbon awarded for defeating the Tower Tycoon at the Battle Tower. 4004 Double Ability Ribbon A Ribbon awarded for completing the Battle Tower Double challenge. 4005 Multi Ability Ribbon A Ribbon awarded for completing the Battle Tower Multi challenge. 4006 Pair Ability Ribbon A Ribbon awarded for completing the Battle Tower Link Multi challenge. 4007 World Ability Ribbon A Ribbon awarded for completing the Wi-Fi Battle Tower challenge. 4008 Alert Ribbon A Ribbon for recalling an invigorating event that created life energy. 4009 Shock Ribbon A Ribbon for recalling a thrilling event that made life more exciting. 4010 Downcast Ribbon A Ribbon for recalling feelings of sadness that added spice to life. 4011 Careless Ribbon A Ribbon for recalling a careless error that helped steer life decisions. 4012 Relax Ribbon A Ribbon for recalling a refreshing event that added sparkle to life. 4013 Snooze Ribbon A Ribbon for recalling a deep slumber that made life soothing. 4014 Smile Ribbon A Ribbon for recalling that smiles enrich the quality of life. 4015 Gorgeous Ribbon An extraordinarily gorgeous and extravagant Ribbon. 4016 Royal Ribbon An incredibly regal Ribbon with an air of nobility. 4017 Gorgeous Royal Ribbon A gorgeous and regal Ribbon that is the peak of fabulous. 4018 Footprint Ribbon A Ribbon awarded to a Pokémon deemed to have a top-quality footprint. 4019 Record Ribbon A Ribbon awarded for setting an incredible record. 4020 History Ribbon A Ribbon awarded for setting a historical record. 4021 Legend Ribbon A Ribbon awarded for setting a legendary record. 4022 Red Ribbon A commemorative Ribbon obtained in a Mystery Zone. 4023 Green Ribbon A commemorative Ribbon obtained in a Mystery Zone. 4024 Blue Ribbon A commemorative Ribbon obtained in a Mystery Zone. 4025 Festival Ribbon A commemorative Ribbon obtained in a Mystery Zone. 4026 Carnival Ribbon A commemorative Ribbon obtained in a Mystery Zone. 4027 Classic Ribbon A Ribbon that proclaims love for Pokémon. 4028 Premier Ribbon A Ribbon awarded for a special holdiay. 4029 Cool Ribbon Super Contest Cool Category Normal Rank winner! 4030 Cool Ribbon Great Super Contest Cool Category Great Rank winner! 4031 Cool Ribbon Ultra Super Contest Cool Category Ultra Rank winner! 4032 Cool Ribbon Master Super Contest Cool Category Master Rank winner! 4033 Beauty Ribbon Super Contest Beauty Category Normal Rank winner! 4034 Beauty Ribbon Great Super Contest Beauty Category Great Rank winner! 4035 Beauty Ribbon Ultra Super Contest Beauty Category Ultra Rank winner! 4036 Beauty Ribbon Master Super Contest Beauty Category Master Rank winner! 4037 Cute Ribbon Super Contest Cute Category Normal Rank winner! 4038 Cute Ribbon Great Super Contest Cute Category Great Rank winner! 4039 Cute Ribbon Ultra Super Contest Cute Category Ultra Rank winner! 4040 Cute Ribbon Master Super Contest Cute Category Master Rank winner! 4041 Smart Ribbon Super Contest Smart Category Normal Rank winner! 4042 Smart Ribbon Great Super Contest Smart Category Great Rank winner! 4043 Smart Ribbon Ultra Super Contest Smart Category Ultra Rank winner! 4044 Smart Ribbon Master Super Contest Smart Category Master Rank winner! 4045 Tough Ribbon Super Contest Tough Category Normal Rank winner! 4046 Tough Ribbon Great Super Contest Tough Category Great Rank winner! 4047 Tough Ribbon Ultra Super Contest Tough Category Ultra Rank winner! 4048 Tough Ribbon Master Super Contest Tough Category Master Rank winner! 5001 Battle Champion Ribbon A Ribbon awarded to a Battle Competition Champion. 5002 Regional Champion Ribbon A Ribbon awarded to a Regional Champion in the Pokémon World Championships. 5003 National Champion Ribbon A Ribbon awarded to a National Champion in the Pokémon World Championships. 5004 Event Ribbon A Ribbon awarded for participating in a special Pokémon event. 5005 World Champion Ribbon A Ribbon awarded to a World Champion in the Pokémon World Championships. 5006 Birthday Ribbon A Ribbon that commemorates a birthday. 5007 Special Ribbon A special Ribbon for a special day. 5008 Souvenir Ribbon A Ribbon for cherishing a special memory. 5009 Wishing Ribbon A Ribbon said to make your wish come true. ================================================ FILE: bvCrawler4/App.config ================================================  ================================================ FILE: bvCrawler4/Program.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Net.Sockets; using System.Threading; using MySql.Data.MySqlClient; using System.Configuration; using PkmnFoundations.Data; using PkmnFoundations.Support; using System.Data; namespace PkmnFoundations { public class BvCrawler4 { public static void Main(string[] args) { m_pad = new byte[256]; using (FileStream s = File.Open("Box Upload Xor Pad.bin", FileMode.Open)) { s.Read(m_pad, 0, m_pad.Length); s.Close(); } m_upload_dir = ConfigurationManager.AppSettings["pkmnFoundationsBoxUpload4Dir"]; Console.WriteLine("Pokémon Plat/HG/SS Battle Video Crawler by mm201"); int pid = 207823279; // Platinum Hikari Directory.CreateDirectory(String.Format("{0}", m_upload_dir)); DateTime last_top30 = DateTime.MinValue; DateTime last_retry_all = DateTime.MinValue; while (true) { ulong videoId; try { using (MySqlConnection db = CreateConnection()) { db.Open(); videoId = DequeueVideo(db); db.Close(); } } catch (Exception ex) { // haven't touched the server, sleep short LogError(ex); Thread.Sleep(1000 * 1); continue; } if (videoId == 0) { try { if (last_retry_all < DateTime.Now.AddHours(-6)) { last_retry_all = DateTime.Now; RetryAll(); continue; } if (last_top30 < DateTime.Now.AddMinutes(-60)) { last_top30 = DateTime.Now; QueueTop30(pid); continue; } else if (RunSearch(pid)) { continue; } } catch (Exception ex) { LogError(ex); Thread.Sleep(1000 * 30); continue; } Console.WriteLine("Nothing to do. Idling 1 minute."); Thread.Sleep(1000 * 60); continue; } String formatted = FormatVideoId(videoId); String filename = String.Format("{0}\\{1}.bin", m_upload_dir, formatted); if (File.Exists(filename)) { Console.WriteLine("Skipped video {0}. Already present on disk.", formatted); Thread.Sleep(1000 * 1); continue; } byte[] data; try { data = GetBattleVideo(pid, videoId); using (FileStream file = File.Create(filename)) { file.Write(data, 0, data.Length); file.Close(); } } catch (Exception ex) { LogError(ex); Thread.Sleep(1000 * 30); continue; } Console.WriteLine("Successfully saved battle video {0}.", formatted); Thread.Sleep(1000 * 30); } } private static byte[] m_pad; private static String m_upload_dir; public static String FormatVideoId(ulong videoId) { String number = videoId.ToString("D12"); String[] split = new String[3]; split[0] = number.Substring(0, number.Length - 10); split[1] = number.Substring(number.Length - 10, 5); split[2] = number.Substring(number.Length - 5, 5); return String.Join("-", split); } public static byte[] GetBattleVideo(int pid, ulong videoId) { String formatted = FormatVideoId(videoId); Console.WriteLine("Attempting to retrieve battle video {0} from server.", formatted); byte[] data = new byte[0x14c]; MemoryStream request = new MemoryStream(data); request.Write(new byte[4], 0, 4); // length goes here, see end request.Write(new byte[] { 0xda, 0xae, 0x00, 0x00 }, 0, 4); // request type, sanity 0000 request.Write(BitConverter.GetBytes(pid), 0, 4); // pid, hopefully this doesn't ban me request.Write(new byte[] { 0x07, 0x02 }, 0, 2); // there is some random bytes contained in this sometimes. Could be trainer profile // related, I don't know... request.Write(new byte[0x132], 0, 0x132); request.Write(BitConverter.GetBytes(videoId), 0, 8); request.Write(new byte[] { 0x40, 0x01, 0x00, 0x00 }, 0, 4); request.Flush(); Encrypt(data, 0xba); PutLength(data); byte[] response = Conversation(data); if (response.Length < 9) throw new InvalidDataException("Battle video was not retrieved."); Console.WriteLine("Successfully retrieved {0} byte response for battle video {1}.", response.Length, formatted); return response; } public static bool RunSearch(int pid) { Random rand = new Random(); SearchMetagames[] metagames = (SearchMetagames[])Enum.GetValues(typeof(SearchMetagames)); int metaCount = metagames.Length - 1; // exclude Top30 which is at the end int metaIndex = rand.Next(0, metaCount); SearchMetagames metagame = metagames[metaIndex]; ushort species = (ushort)rand.Next(0, 493); byte country = 0xff; byte region = 0xff; using (MySqlConnection db = CreateConnection()) { db.Open(); if ((long)db.ExecuteScalar( "SELECT Count(*) FROM BattleVideoSearchHistory WHERE Metagame = @metagame " + "AND Species = @species AND Country = @country AND Region = @region", new MySqlParameter("@metagame", (int)metagame), new MySqlParameter("@species", (int)species), new MySqlParameter("@country", (int)country), new MySqlParameter("@region", (int)region)) == 0) { // exact match QueueSearch(pid, species, metagame, country, region); return true; } DataTable dt; dt = db.ExecuteDataTable("SELECT DISTINCT Metagame, Species, Country, Region " + "FROM BattleVideoSearchHistory WHERE Metagame = @metagame ORDER BY Species", new MySqlParameter("@metagame", (int)metagame)); if (dt.Rows.Count < 493) { int prevSpecies = 1; foreach (DataRow row in dt.Rows) { if ((int)row["Species"] != prevSpecies) { QueueSearch(pid, (ushort)(prevSpecies), metagame, country, region); return true; } prevSpecies++; } } dt = db.ExecuteDataTable("SELECT DISTINCT Metagame, Species, Country, Region " + "FROM BattleVideoSearchHistory WHERE Species = @species ORDER BY Metagame", new MySqlParameter("@species", (int)species)); if (dt.Rows.Count < metaCount) { int prevMeta = 0; foreach (DataRow row in dt.Rows) { if ((int)row["Metagame"] != (int)metagames[prevMeta]) { QueueSearch(pid, species, metagames[prevMeta], country, region); return true; } prevMeta++; } } dt = db.ExecuteDataTable("SELECT DISTINCT Metagame, Species, Country, Region " + "FROM BattleVideoSearchHistory ORDER BY Metagame, Species"); if (dt.Rows.Count < 493 * metaCount) { int prevSpecies = 1; int prevMeta = 0; foreach (DataRow row in dt.Rows) { if ((int)row["Species"] != prevSpecies || (int)row["Metagame"] != (int)metagames[prevMeta]) { QueueSearch(pid, (ushort)(prevSpecies), metagames[prevMeta], country, region); return true; } prevSpecies++; if (prevSpecies > 493) { prevSpecies = 1; prevMeta++; } } } } return false; } public static void QueueTop30(int pid) { QueueSearch(pid, 0xffff, SearchMetagames.Latest30, 0xff, 0xff); } public static void QueueSearch(int pid, ushort species, SearchMetagames meta, byte country, byte region) { bool hasSearch = species == 0xffff && meta == SearchMetagames.Latest30 && country == 0xff && region == 0xff; if (hasSearch) Console.WriteLine("Searching for latest 30 videos."); else { Console.Write("Searching for "); if (species != 0xffff) Console.Write("species {0}, ", species); if (meta != SearchMetagames.Latest30) Console.Write("{0}, ", meta); if (country != 0xff) Console.Write("country {0}, ", region); if (region != 0xff) Console.Write("region {0}", region); } byte[] data = new byte[0x15c]; MemoryStream request = new MemoryStream(data); request.Write(new byte[4], 0, 4); // length goes here, see end request.Write(new byte[] { 0xd9, 0xc4, 0x00, 0x00 }, 0, 4); // request type, sanity 0000 request.Write(BitConverter.GetBytes(pid), 0, 4); // pid, hopefully this doesn't ban me request.Write(new byte[] { 0x0c, 0x02 }, 0, 2); // there is some random bytes contained in this sometimes. Could be trainer profile // related, I don't know... request.Write(new byte[0x132], 0, 0x132); request.Write(new byte[] { 0x00, 0x00, 0x00, 0x00 }, 0, 4); request.Write(BitConverter.GetBytes(species), 0, 2); request.WriteByte((byte)meta); request.WriteByte(country); request.WriteByte(region); request.Write(new byte[] { 0x00, 0x00, 0x00, 0x40, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xdc, 0xf6, 0x1b, 0x02, 0x0c, 0x03, 0x00, 0x00 }, 0, 19); request.Flush(); Encrypt(data, 0xc9); PutLength(data); byte[] response = Conversation(data); if (!hasSearch) { using (MySqlConnection db = CreateConnection()) { db.Open(); db.ExecuteNonQuery("INSERT INTO BattleVideoSearchHistory (Metagame, Species, " + "Country, Region) VALUES (@metagame, @species, @country, @region)", new MySqlParameter("@metagame", (int)meta), new MySqlParameter("@species", (int)species), new MySqlParameter("@country", (int)country), new MySqlParameter("@region", (int)region)); db.Close(); } } QueueSearchResults(response); } public static void QueueSearchResults(byte[] data) { if (data.Length % 240 != 12) throw new InvalidDataException("Search results blob should be 12 bytes + 240 per result."); Decrypt(data); AssertHelper.Assert(data[6] == 0x00); AssertHelper.Assert(data[7] == 0x00); // saaaaanity int count = data.Length / 240; Console.WriteLine("{0} results found.", count); if (count == 0) { // Nothing found. Sleep as to not spam the server with lots of empty searches Thread.Sleep(1000 * 15); return; } // 12 bytes of header plus 240 bytes per search result. using (MySqlConnection db = CreateConnection()) { db.Open(); for (int x = 0; x < count; x++) { ulong videoId = BitConverter.ToUInt64(data, 16 + x * 240); QueueVideoId(db, videoId); } db.Close(); } } public static void QueueVideoId(MySqlConnection db, ulong id) { String formatted = FormatVideoId(id); using (MySqlTransaction tran = db.BeginTransaction()) { long count = (long)tran.ExecuteScalar("SELECT Count(*) FROM BattleVideoCrawlQueue WHERE SerialNumber = @serial_number", new MySqlParameter("@serial_number", id)); if (count > 0) { tran.Rollback(); Console.WriteLine("Skipped video {0}. Already present in database.", formatted); return; } tran.ExecuteNonQuery("INSERT INTO BattleVideoCrawlQueue (SerialNumber, `Timestamp`) VALUES (@serial_number, NOW())", new MySqlParameter("@serial_number", id)); tran.Commit(); Console.WriteLine("Queued video {0}.", formatted); } } public static ulong DequeueVideo(MySqlConnection db) { using (MySqlTransaction tran = db.BeginTransaction()) { object o = tran.ExecuteScalar("SELECT SerialNumber FROM BattleVideoCrawlQueue WHERE Complete = 0 ORDER BY `Timestamp` LIMIT 1"); if (o == null || o == DBNull.Value) { tran.Rollback(); return 0; } ulong id = (ulong)o; tran.ExecuteNonQuery("UPDATE BattleVideoCrawlQueue SET Complete = 1 WHERE SerialNumber = @serial_number", new MySqlParameter("@serial_number", id)); tran.Commit(); return id; } } public static void PutLength(byte[] data) { // places the actual length in the first 4 bytes. byte[] length = BitConverter.GetBytes(data.Length); Array.Copy(length, data, 4); } public static byte[] Conversation(byte[] request) { MemoryStream response = new MemoryStream(); using (TcpClient client = new TcpClient("pkgdsprod.nintendo.co.jp", 12400)) { NetworkStream s = client.GetStream(); s.Write(request, 0, request.Length); s.CopyTo(response); s.Close(); } response.Flush(); byte[] dataResponse = response.ToArray(); int length = BitConverter.ToInt32(dataResponse, 0); AssertHelper.Equals(length, dataResponse.Length); return dataResponse; } public static void Encrypt(byte[] data, int padOffset) { // encrypt and decrypt are the same operation... for (int x = 6; x < data.Length; x++) { data[x] ^= m_pad[(x + padOffset) % 256]; } } public static void Decrypt(byte[] data) { int padOffset = (Array.IndexOf(m_pad, data[6]) + 250) % 256; Encrypt(data, padOffset); } public static void RetryAll() { String path = String.Format("{0}", m_upload_dir); using (MySqlConnection db = CreateConnection()) { db.Open(); DataTable SerialNumbers = db.ExecuteDataTable("SELECT SerialNumber FROM BattleVideoCrawlQueue WHERE Complete = 1"); SerialNumbers.PrimaryKey = new DataColumn[] { SerialNumbers.Columns["SerialNumber"] }; IEnumerable filenames = Directory.EnumerateFiles(path); foreach (String s in filenames) { int slash = s.LastIndexOf(Path.DirectorySeparatorChar) + 1; int dot = s.LastIndexOf("."); if (dot < 0) dot = s.Length; if (dot < slash) dot = s.Length; ulong SerialNumber; UInt64.TryParse(s.Substring(slash, dot - slash).Replace("-", ""), out SerialNumber); if (SerialNumber == 0) continue; DataRow row = SerialNumbers.Rows.Find(SerialNumber); if (row == null) continue; // video in the folder but not database. todo: insert. SerialNumbers.Rows.Remove(row); } StringBuilder toRecheck = new StringBuilder(); bool hasRows = false; foreach (DataRow row in SerialNumbers.Rows) { ulong SerialNumber = (ulong)row["SerialNumber"]; if (hasRows) toRecheck.Append(','); toRecheck.Append(SerialNumber.ToString()); hasRows = true; Console.WriteLine("Battle video {0} in database but not in directory. Requeueing.", FormatVideoId(SerialNumber)); } if (hasRows) { db.ExecuteNonQuery("UPDATE BattleVideoCrawlQueue SET Complete = 0 " + "WHERE SerialNumber IN (" + toRecheck.ToString() + ")"); } db.Clone(); } } public static MySqlConnection CreateConnection() { return new MySqlConnection(ConfigurationManager.ConnectionStrings["pkmnFoundationsConnectionString"].ConnectionString); } public static void LogError(Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } public enum SearchMetagames : byte { Latest30 = 0xff, ColosseumSingleNoRestrictions = 0xfa, ColosseumSingleCupMatch = 0xfb, ColosseumDoubleNoRestrictions = 0xfc, ColosseumDoubleCupMatch = 0xfd, ColosseumMulti = 0x0e, BattleTowerSingle = 0x0f, BattleTowerDouble = 0x10, BattleTowerMulti = 0x11, BattleFactoryLv50Single = 0x12, BattleFactoryLv50Double = 0x13, BattleFactoryLv50Multi = 0x14, BattleFactoryOpenSingle = 0x15, BattleFactoryOpenDouble = 0x16, BattleFactoryOpenMulti = 0x17, BattleHallSingle = 0x18, BattleHallDouble = 0x19, BattleHallMulti = 0x1a, BattleCastleSingle = 0x1b, BattleCastleDouble = 0x1c, BattleCastleMulti = 0x1d, BattleArcadeSingle = 0x1e, BattleArcadeDouble = 0x1f, BattleArcadeMulti = 0x20, } } } ================================================ FILE: bvCrawler4/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("bvCrawler4")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("bvCrawler4")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("01abd719-4ed0-4a30-9f67-663f7cfe03e2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: bvCrawler4/bvCrawler4.csproj ================================================  Debug x86 8.0.30703 2.0 {04E4EB3B-166B-4D8B-86AA-2178F2A927D5} Exe Properties bvCrawler4 bvCrawler4 v4.0 512 AnyCPU true full false bin\Debug\ DEBUG;TRACE prompt 4 x86 pdbonly true bin\Release\ TRACE prompt 4 ..\packages\MySql.Data.6.9.8\lib\net40\MySql.Data.dll Designer Always {408EFC7E-C6B0-4160-8628-2679E34385CE} Library ================================================ FILE: bvCrawler4/packages.config ================================================  ================================================ FILE: bvCrawler5/App.config ================================================  ================================================ FILE: bvCrawler5/Program.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Net.Sockets; using System.Threading; using MySql.Data.MySqlClient; using System.Configuration; using PkmnFoundations.Data; using PkmnFoundations.Support; using System.Data; using System.Net.Security; using System.Security.Cryptography.X509Certificates; namespace PkmnFoundations { public class BvCrawler5 { public static void Main(string[] args) { m_upload_dir = ConfigurationManager.AppSettings["pkmnFoundationsBoxUpload5Dir"]; Console.WriteLine("Pokémon BW/BW2 Battle Video Crawler by mm201"); int pid = 330241374; // White 1 Jenny (?) Directory.CreateDirectory(String.Format("{0}", m_upload_dir)); DateTime last_top30 = DateTime.MinValue; DateTime last_top_link = DateTime.MinValue; DateTime last_top_subway = DateTime.MinValue; DateTime last_retry_all = DateTime.MinValue; m_session_key = new byte[]{ 0x66, 0x87, 0xF1, 0xB5, 0x96, 0x47, 0x4D, 0xFB, 0x0E, 0x0B, 0x19, 0xBD, 0xBD, 0x69, 0x5E, 0x71, 0x03, 0x39, 0xED, 0xB2, 0x38, 0xA7, 0xD5, 0x5A, 0x19, 0x80, 0x09, 0xD4, 0xAA, 0x7F, 0xAE, 0xD3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; m_session_time = DateTime.MinValue; while (true) { ulong videoId; try { using (MySqlConnection db = CreateConnection()) { db.Open(); videoId = DequeueVideo(db); db.Close(); } } catch (Exception ex) { // haven't touched the server, sleep short LogError(ex); Thread.Sleep(1000 * 1); continue; } if (videoId == 0) { try { if (last_retry_all < DateTime.Now.AddHours(-6)) { last_retry_all = DateTime.Now; RetryAll(); continue; } if (last_top30 < DateTime.Now.AddMinutes(-60)) { last_top30 = DateTime.Now; QueueSpecial(pid, SearchSpecial.Latest30); continue; } if (last_top_link < DateTime.Now.AddMinutes(-120)) { last_top_link = DateTime.Now; QueueSpecial(pid, SearchSpecial.TopLinkBattles); continue; } if (last_top_subway < DateTime.Now.AddMinutes(-120)) { last_top_subway = DateTime.Now; QueueSpecial(pid, SearchSpecial.TopSubwayBattles); continue; } else if (RunSearch(pid)) { continue; } } catch (Exception ex) { LogError(ex); Thread.Sleep(1000 * 30); continue; } Console.WriteLine("Nothing to do. Idling 1 minute."); Thread.Sleep(1000 * 60); continue; } String formatted = FormatVideoId(videoId); String filename = String.Format("{0}\\{1}.bin", m_upload_dir, formatted); if (File.Exists(filename)) { Console.WriteLine("Skipped video {0}. Already present on disk.", formatted); Thread.Sleep(1000 * 1); continue; } byte[] data; try { data = GetBattleVideo(pid, videoId); using (FileStream file = File.Create(filename)) { file.Write(data, 0, data.Length); file.Close(); } } catch (Exception ex) { LogError(ex); Thread.Sleep(1000 * 30); continue; } Console.WriteLine("Successfully saved battle video {0}.", formatted); Thread.Sleep(1000 * 30); } } private static String m_upload_dir; private static byte[] m_session_key; private static String m_session_str; private static DateTime m_session_time; public static String FormatVideoId(ulong videoId) { String number = videoId.ToString("D12"); String[] split = new String[3]; split[0] = number.Substring(0, number.Length - 10); split[1] = number.Substring(number.Length - 10, 5); split[2] = number.Substring(number.Length - 5, 5); return String.Join("-", split); } public static void WriteBase64shit(Stream s) { // First 32 bytes shared by all: // 6687F1B596474DFB0E0B19BDBD695E710339EDB238A7D55A198009D4AA7FAED3 // // The last 32 bytes seem to be random but verifiable: // White 1: A194196DAC7CAA4B75A9038E0FF2C71E64E61C40CFA0340178FBB9B6B72C4A63 // White 1: F8A9E7EA602F169A146429A49AB7BF2D26BBB178AA2BCF1DA259310A263D41ED // White 1: BEAB158B25170200BEEBD9C456CD5BE00A19A3C4F69F4749DED6427AD173834E // Black 2: C307898C422687861BCA69B25C9FC007B6516A098A05E027BB49764EF2E8B5B1 // Black 2: BFAA5408C6474EDDE340CF57D3405379E61A78B331191637AA6CE2818ECCE42B // // I'm guessing it's Hash(Secret + Random) // The bytes don't vary with a session but are changed when you reset your DS. if (m_session_str == null || m_session_time.AddMinutes(60) < DateTime.Now) { m_session_time = DateTime.Now; Random rnd = new Random(); byte[] data = new byte[32]; rnd.NextBytes(data); // hack in data = new byte[]{ 0xBE, 0xAB, 0x15, 0x8B, 0x25, 0x17, 0x02, 0x00, 0xBE, 0xEB, 0xD9, 0xC4, 0x56, 0xCD, 0x5B, 0xE0, 0x0A, 0x19, 0xA3, 0xC4, 0xF6, 0x9F, 0x47, 0x49, 0xDE, 0xD6, 0x42, 0x7A, 0xD1, 0x73, 0x83, 0x4E }; Array.Copy(data, 0, m_session_key, 32, 32); m_session_str = Convert.ToBase64String(m_session_key); } StreamWriter w = new StreamWriter(s); w.Write(m_session_str); w.Flush(); } public static byte[] GetBattleVideo(int pid, ulong videoId) { String formatted = FormatVideoId(videoId); Console.WriteLine("Attempting to retrieve battle video {0} from server.", formatted); byte[] data = new byte[0x14c]; MemoryStream request = new MemoryStream(data); request.Write(new byte[4], 0, 4); // length goes here, see end request.Write(new byte[] { 0xf2, 0x55, 0x00, 0x00 }, 0, 4); // request type, sanity 0000 request.Write(BitConverter.GetBytes(pid), 0, 4); // pid, hopefully this doesn't ban me request.Write(new byte[] { 0x17, 0x02 }, 0, 2); WriteBase64shit(request); request.Write(new byte[0xda], 0, 0xda); request.Write(BitConverter.GetBytes(videoId), 0, 8); request.Write(new byte[] { 0x64, 0x00, 0x00, 0x00 }, 0, 4); request.Flush(); PutLength(data); byte[] response = Conversation(data); if (response.Length < 9) throw new InvalidDataException("Battle video was not retrieved."); Console.WriteLine("Successfully retrieved {0} byte response for battle video {1}.", response.Length, formatted); return response; } public static bool RunSearch(int pid) { Random rand = new Random(); SearchMetagames[] metagames = (SearchMetagames[])Enum.GetValues(typeof(SearchMetagames)); int metaCount = metagames.Length - 1; // remove None from the list int metaIndex = rand.Next(1, metaCount + 1); SearchMetagames metagame = metagames[metaIndex]; ushort species = (ushort)rand.Next(0, 649); byte country = 0xff; byte region = 0xff; using (MySqlConnection db = CreateConnection()) { db.Open(); if ((long)db.ExecuteScalar( "SELECT Count(*) FROM BattleVideoSearchHistory5 WHERE Metagame = @metagame " + "AND Species = @species AND Country = @country AND Region = @region AND Special = 0", new MySqlParameter("@metagame", (int)metagame), new MySqlParameter("@species", (int)species), new MySqlParameter("@country", (int)country), new MySqlParameter("@region", (int)region)) == 0) { // exact match QueueSearch(pid, SearchSpecial.None, species, metagame, country, region); return true; } DataTable dt; dt = db.ExecuteDataTable("SELECT DISTINCT Metagame, Species, Country, Region " + "FROM BattleVideoSearchHistory5 WHERE Metagame = @metagame AND Special = 0 ORDER BY Species", new MySqlParameter("@metagame", (int)metagame)); if (dt.Rows.Count < 649) { int prevSpecies = 1; foreach (DataRow row in dt.Rows) { if ((int)row["Species"] != prevSpecies) { QueueSearch(pid, SearchSpecial.None, (ushort)(prevSpecies), metagame, country, region); return true; } prevSpecies++; } } dt = db.ExecuteDataTable("SELECT DISTINCT Metagame, Species, Country, Region " + "FROM BattleVideoSearchHistory5 WHERE Species = @species AND Special = 0 ORDER BY Metagame", new MySqlParameter("@species", (int)species)); if (dt.Rows.Count < metaCount) { int prevMeta = 1; foreach (DataRow row in dt.Rows) { if ((int)row["Metagame"] != (int)metagames[prevMeta]) { QueueSearch(pid, SearchSpecial.None, species, metagames[prevMeta], country, region); return true; } prevMeta++; } } dt = db.ExecuteDataTable("SELECT DISTINCT Metagame, Species, Country, Region " + "FROM BattleVideoSearchHistory5 WHERE Special = 0 ORDER BY Metagame, Species"); if (dt.Rows.Count < 649 * metaCount) { int prevSpecies = 1; int prevMeta = 1; foreach (DataRow row in dt.Rows) { if ((int)row["Species"] != prevSpecies || (int)row["Metagame"] != (int)metagames[prevMeta]) { QueueSearch(pid, SearchSpecial.None, (ushort)(prevSpecies), metagames[prevMeta], country, region); return true; } prevSpecies++; if (prevSpecies > 649) { prevSpecies = 1; prevMeta++; } } } } return false; } public static void QueueSpecial(int pid, SearchSpecial special) { QueueSearch(pid, special, 0x0000, SearchMetagames.None, 0x00, 0x00); } public static void QueueSearch(int pid, SearchSpecial special, ushort species, SearchMetagames meta, byte country, byte region) { switch (special) { case SearchSpecial.Latest30: Console.WriteLine("Searching for latest 30 videos."); break; case SearchSpecial.TopLinkBattles: Console.WriteLine("Searching for top link battles."); break; case SearchSpecial.TopSubwayBattles: Console.WriteLine("Searching for top Subway battles."); break; default: { Console.Write("Searching for "); if (species != 0xffff) Console.Write("species {0}, ", species); if (meta != SearchMetagames.None) Console.Write("{0}, ", meta); if (country != 0xff) Console.Write("country {0}, ", region); if (region != 0xff) Console.Write("region {0}", region); } break; } byte[] data = new byte[0x15c]; MemoryStream request = new MemoryStream(data); request.Write(new byte[4], 0, 4); // length goes here, see end request.Write(new byte[] { 0xf1, 0x55, 0x00, 0x00 }, 0, 4); // request type, sanity 0000 request.Write(BitConverter.GetBytes(pid), 0, 4); // pid, hopefully this doesn't ban me request.Write(new byte[] { 0x14, 0x02 }, 0, 2); WriteBase64shit(request); request.Write(new byte[0xda], 0, 0xda); request.Write(BitConverter.GetBytes((uint)special), 0, 4); request.Write(BitConverter.GetBytes(species), 0, 2); request.Write(BitConverter.GetBytes((uint)meta), 0, 4); request.WriteByte(country); request.WriteByte(region); request.Write(new byte[] { 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0, 16); request.Flush(); PutLength(data); byte[] response = Conversation(data); if (special != SearchSpecial.Latest30) { using (MySqlConnection db = CreateConnection()) { db.Open(); db.ExecuteNonQuery("INSERT INTO BattleVideoSearchHistory5 (Metagame, Species, " + "Country, Region, Special) VALUES (@metagame, @species, @country, @region, @special)", new MySqlParameter("@metagame", (int)meta), new MySqlParameter("@species", (int)species), new MySqlParameter("@country", (int)country), new MySqlParameter("@region", (int)region), new MySqlParameter("@special", (int)special)); db.Close(); } } QueueSearchResults(response); } public static void QueueSearchResults(byte[] data) { if (data.Length % 208 != 12) throw new InvalidDataException("Search results blob should be 12 bytes + 208 per result."); int count = data.Length / 208; Console.WriteLine("{0} results found.", count); if (count == 0) { // Nothing found. Sleep as to not spam the server with lots of empty searches Thread.Sleep(1000 * 15); return; } // 12 bytes of header plus 208 bytes per search result. using (MySqlConnection db = CreateConnection()) { db.Open(); for (int x = 0; x < count; x++) { ulong videoId = BitConverter.ToUInt64(data, 16 + x * 208); QueueVideoId(db, videoId); } db.Close(); } } public static void QueueVideoId(MySqlConnection db, ulong id) { String formatted = FormatVideoId(id); using (MySqlTransaction tran = db.BeginTransaction()) { long count = (long)tran.ExecuteScalar("SELECT Count(*) FROM BattleVideoCrawlQueue5 WHERE SerialNumber = @serial_number", new MySqlParameter("@serial_number", id)); if (count > 0) { tran.Rollback(); Console.WriteLine("Skipped video {0}. Already present in database.", formatted); return; } tran.ExecuteNonQuery("INSERT INTO BattleVideoCrawlQueue5 (SerialNumber, `Timestamp`) VALUES (@serial_number, NOW())", new MySqlParameter("@serial_number", id)); tran.Commit(); Console.WriteLine("Queued video {0}.", formatted); } } public static ulong DequeueVideo(MySqlConnection db) { using (MySqlTransaction tran = db.BeginTransaction()) { object o = tran.ExecuteScalar("SELECT SerialNumber FROM BattleVideoCrawlQueue5 WHERE Complete = 0 ORDER BY `Timestamp` LIMIT 1"); if (o == null || o == DBNull.Value) { tran.Rollback(); return 0; } ulong id = (ulong)o; tran.ExecuteNonQuery("UPDATE BattleVideoCrawlQueue5 SET Complete = 1 WHERE SerialNumber = @serial_number", new MySqlParameter("@serial_number", id)); tran.Commit(); return id; } } public static void PutLength(byte[] data) { // places the actual length in the first 4 bytes. byte[] length = BitConverter.GetBytes(data.Length); Array.Copy(length, data, 4); } public static byte[] Conversation(byte[] request) { MemoryStream response = new MemoryStream(); using (TcpClient client = new TcpClient("pkgdsprod.nintendo.co.jp", 12401)) { SslStream sslClient = new SslStream(client.GetStream(), false, delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; }); sslClient.AuthenticateAsClient("pkgdsprod.nintendo.co.jp"); sslClient.Write(request, 0, request.Length); sslClient.CopyTo(response); sslClient.Close(); } response.Flush(); byte[] dataResponse = response.ToArray(); int length = BitConverter.ToInt32(dataResponse, 0); AssertHelper.Equals(length, dataResponse.Length); return dataResponse; } public static void RetryAll() { String path = String.Format("{0}", m_upload_dir); using (MySqlConnection db = CreateConnection()) { db.Open(); DataTable SerialNumbers = db.ExecuteDataTable("SELECT SerialNumber FROM BattleVideoCrawlQueue5 WHERE Complete = 1"); SerialNumbers.PrimaryKey = new DataColumn[] { SerialNumbers.Columns["SerialNumber"] }; IEnumerable filenames = Directory.EnumerateFiles(path); foreach (String s in filenames) { int slash = s.LastIndexOf(Path.DirectorySeparatorChar) + 1; int dot = s.LastIndexOf("."); if (dot < 0) dot = s.Length; if (dot < slash) dot = s.Length; ulong SerialNumber; UInt64.TryParse(s.Substring(slash, dot - slash).Replace("-", ""), out SerialNumber); if (SerialNumber == 0) continue; DataRow row = SerialNumbers.Rows.Find(SerialNumber); if (row == null) continue; // video in the folder but not database. todo: insert. SerialNumbers.Rows.Remove(row); } StringBuilder toRecheck = new StringBuilder(); bool hasRows = false; foreach (DataRow row in SerialNumbers.Rows) { ulong SerialNumber = (ulong)row["SerialNumber"]; if (hasRows) toRecheck.Append(','); toRecheck.Append(SerialNumber.ToString()); hasRows = true; Console.WriteLine("Battle video {0} in database but not in directory. Requeueing.", FormatVideoId(SerialNumber)); } if (hasRows) { db.ExecuteNonQuery("UPDATE BattleVideoCrawlQueue5 SET Complete = 0 " + "WHERE SerialNumber IN (" + toRecheck.ToString() + ")"); } db.Clone(); } } public static MySqlConnection CreateConnection() { return new MySqlConnection(ConfigurationManager.ConnectionStrings["pkmnFoundationsConnectionString"].ConnectionString); } public static void LogError(Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } public enum SearchSpecial : uint { None = 0x00000000, // if special, all other fields are 0 Latest30 = 0x00000001, // 01 00 00 00 00 00 00 00 00 00 00 00 TopLinkBattles = 0x00000003, // 03 00 00 00 00 00 00 00 00 00 00 00 TopSubwayBattles = 0x00000002, // 02 00 00 00 00 00 00 00 00 00 00 00 } public enum SearchMetagames : uint { None = 0x00000000, // Spcial (4), Species (2), Meta (4), Country (1), Region (1) ColosseumSingleNoLauncher = 0x00bf0018, // 00 00 00 00 ff ff 18 00 bf 00 ff ff ColosseumSingleLauncher = 0x00bf0098, // 00 00 00 00 ff ff 98 00 bf 00 ff ff ColosseumDoubleNoLauncher = 0x00bf0019, // 00 00 00 00 ff ff 19 00 bf 00 ff ff ColosseumDoubleLauncher = 0x00bf0099, // 00 00 00 00 ff ff 99 00 bf 00 ff ff ColosseumTripleNoLauncher = 0x00bf001a, // 00 00 00 00 ff ff 1a 00 bf 00 ff ff ColosseumTripleLauncher = 0x00bf009a, // 00 00 00 00 ff ff 9a 00 bf 00 ff ff ColosseumRotationNoLauncher = 0x00bf001b, // 00 00 00 00 ff ff 1b 00 bf 00 ff ff ColosseumRotationLauncher = 0x00bf009b, // 00 00 00 00 ff ff 9b 00 bf 00 ff ff ColosseumMultiNoLauncher = 0x00bf001c, // 00 00 00 00 ff ff 1c 00 bf 00 ff ff ColosseumMultiLauncher = 0x00bf009c, // 00 00 00 00 ff ff 9c 00 bf 00 ff ff BattleSubwaySingle = 0x003f0000, // 00 00 00 00 ff ff 00 00 3f 00 ff ff BattleSubwayDouble = 0x003f0001, // 00 00 00 00 ff ff 01 00 3f 00 ff ff BattleSubwayMulti = 0x003f0004, // 00 00 00 00 ff ff 04 00 3f 00 ff ff RandomMatchupSingle = 0x003f0028, // 00 00 00 00 ff ff 28 00 3f 00 ff ff RandomMatchupDouble = 0x003f0029, // 00 00 00 00 ff ff 29 00 3f 00 ff ff RandomMatchupTriple = 0x003f002a, // 00 00 00 00 ff ff 2a 00 3f 00 ff ff RandomMatchupRotation = 0x003f002b, // 00 00 00 00 ff ff 2b 00 3f 00 ff ff RandomMatchupLauncher = 0x00bf00aa, // 00 00 00 00 ff ff aa 00 bf 00 ff ff BattleCompetition = 0x00380038, // 00 00 00 00 ff ff 38 00 38 00 ff ff } } } ================================================ FILE: bvCrawler5/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("bvCrawler5")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("bvCrawler5")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8e1b6ee9-f993-4675-af27-963fe91e7fbe")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: bvCrawler5/bvCrawler5.csproj ================================================  Debug x86 8.0.30703 2.0 {BEA49E66-2204-4C10-8ED6-17F58018C2BD} Exe Properties bvCrawler5 bvCrawler5 v4.0 512 AnyCPU true full false bin\Debug\ DEBUG;TRACE prompt 4 x86 pdbonly true bin\Release\ TRACE prompt 4 ..\packages\MySql.Data.6.9.8\lib\net40\MySql.Data.dll {408EFC7E-C6B0-4160-8628-2679E34385CE} Library Designer ================================================ FILE: bvCrawler5/packages.config ================================================  ================================================ FILE: bvRestorer4/App.config ================================================ ================================================ FILE: bvRestorer4/Program.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using PkmnFoundations.Support; using PkmnFoundations.Structures; using PkmnFoundations.Data; using PkmnFoundations.Wfc; namespace bvRestorer4 { class Program { static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Usage: bvRestorer4 "); Console.WriteLine("Attempts to insert all the files in path\ninto the database in app configuration."); return; } m_pad = new byte[256]; FileStream s = File.OpenRead(AppDomain.CurrentDomain.BaseDirectory + Path.DirectorySeparatorChar + "pad.bin"); s.Read(m_pad, 0, m_pad.Length); s.Close(); String[] filenames = Directory.GetFiles(args[0]); int successCount = 0; foreach (String filename in filenames) { FileStream fs = File.OpenRead(filename); if (fs.Length != 0x1d60) { Console.WriteLine("{0}: file size is wrong, skipped.", filename); continue; } byte[] data = new byte[0x1d60]; fs.ReadBlock(data, 0, 0x1d60); fs.Close(); int length = BitConverter.ToInt32(data, 0); if (length != 0x1d60) { Console.WriteLine("{0}: size field is wrong, skipped.", filename); continue; } if (data[4] != 0xda) { Console.WriteLine("{0}: request type is wrong, skipped.", filename); continue; } CryptMessage(data); if (data[5] != 0x59 || data[6] != 0x00 || data[7] != 0x00) { Console.WriteLine("{0}: sanity bytes are wrong, skipped.", filename); continue; } int pid = BitConverter.ToInt32(data, 0x08); ulong serial = BitConverter.ToUInt64(data, 0x0c); byte[] mainData = new byte[0x1d4c]; Array.Copy(data, 0x14, mainData, 0, 0x1d4c); BattleVideoRecord4 record = new BattleVideoRecord4(pid, serial, mainData); Database.Instance.BattleVideoUpload4(record); Console.WriteLine("Video {0} added successfully.", BattleVideoHeader4.FormatSerial(serial)); successCount++; } Console.WriteLine("{0} battle videos successfully added.", successCount); Console.ReadKey(); } private static byte[] m_pad; private static void CryptMessage(byte[] message) { if (message.Length < 5) return; byte padOffset = (byte)(message[0] + message[4]); // encrypt and decrypt are the same operation... for (int x = 5; x < message.Length; x++) message[x] ^= m_pad[(x + padOffset) & 0xff]; } } } ================================================ FILE: bvRestorer4/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("bvRestorer4")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("bvRestorer4")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("68dcec49-1275-442c-adfd-3bd45e17f50b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: bvRestorer4/bvRestorer4.csproj ================================================  Debug x86 8.0.30703 2.0 {5174CBF0-2A5D-466B-BC32-CE53B9AC4EAF} Exe Properties bvRestorer4 bvRestorer4 v3.5 512 AnyCPU true full false bin\Debug\ DEBUG;TRACE prompt 4 x86 pdbonly true bin\Release\ TRACE prompt 4 Always {408EFC7E-C6B0-4160-8628-2679E34385CE} Library ================================================ FILE: bvRestorer5/App.config ================================================ ================================================ FILE: bvRestorer5/Program.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using PkmnFoundations.Data; using PkmnFoundations.Structures; using PkmnFoundations.Support; using PkmnFoundations.Wfc; namespace bvRestorer5 { class Program { static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Usage: bvRestorer5 "); Console.WriteLine("Attempts to insert all the files in path\ninto the database in app configuration."); return; } String[] filenames = Directory.GetFiles(args[0]); int successCount = 0; foreach (String filename in filenames) { FileStream fs = File.OpenRead(filename); if (fs.Length != 0x18b8) { Console.WriteLine("{0}: file size is wrong, skipped.", filename); continue; } byte[] data = new byte[0x18b8]; fs.ReadBlock(data, 0, 0x18b8); fs.Close(); int length = BitConverter.ToInt32(data, 0); if (length != 0x18b8) { Console.WriteLine("{0}: size field is wrong, skipped.", filename); continue; } if (data[4] != 0xf2) { Console.WriteLine("{0}: request type is wrong, skipped.", filename); continue; } if (data[5] != 0x55 || data[6] != 0x00 || data[7] != 0x00) { Console.WriteLine("{0}: sanity bytes are wrong, skipped.", filename); continue; } int pid = BitConverter.ToInt32(data, 0x08); ulong serial = BitConverter.ToUInt64(data, 0x0c); byte[] mainData = new byte[0x18a4]; Array.Copy(data, 0x14, mainData, 0, 0x18a4); BattleVideoRecord5 record = new BattleVideoRecord5(pid, serial, mainData); Database.Instance.BattleVideoUpload5(record); Console.WriteLine("Video {0} added successfully.", BattleVideoHeader4.FormatSerial(serial)); successCount++; } Console.WriteLine("{0} battle videos successfully added.", successCount); Console.ReadKey(); } } } ================================================ FILE: bvRestorer5/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("bvRestorer5")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("bvRestorer5")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f2709d12-5840-4398-8f25-30c8c8e1bd99")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: bvRestorer5/bvRestorer5.csproj ================================================  Debug AnyCPU {9F2A0A44-B90E-4B30-8DFF-2B5E273F5BEC} Exe Properties bvRestorer5 bvRestorer5 v3.5 512 AnyCPU true full false bin\Debug\ DEBUG;TRACE prompt 4 AnyCPU pdbonly true bin\Release\ TRACE prompt 4 Designer {408efc7e-c6b0-4160-8628-2679e34385ce} Library ================================================ FILE: gts/Global.asax ================================================ <%@ Application Codebehind="Global.asax.cs" Inherits="PkmnFoundations.GTS.Global" Language="C#" %> ================================================ FILE: gts/Global.asax.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; using System.Web.SessionState; using GamestatsBase; using PkmnFoundations.Data; namespace PkmnFoundations.GTS { public class Global : System.Web.HttpApplication { void Application_Start(object sender, EventArgs e) { // Code that runs on application startup AppStateHelper.Pokedex(Application); } void Application_End(object sender, EventArgs e) { // Code that runs on application shutdown } void Application_Error(object sender, EventArgs e) { // Code that runs when an unhandled error occurs } void Session_Start(object sender, EventArgs e) { // Code that runs when a new session is started } void Session_End(object sender, EventArgs e) { // Code that runs when a session ends. // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web.config file. If session mode is set to StateServer // or SQLServer, the event is not raised. } void Application_BeginRequest(object sender, EventArgs e) { String pathInfo, query; String targetUrl = RewriteUrl(Request.Url.PathAndQuery, out pathInfo, out query); if (targetUrl != null) { Context.RewritePath(targetUrl, pathInfo, query, false); } } void Application_EndRequest(object sender, EventArgs e) { GamestatsSessionManager.FromContext(Context).PruneSessions(); } public static String RewriteUrl(String url, out String pathInfo, out String query) { int q = url.IndexOf('?'); String path; pathInfo = ""; if (q < 0) { path = url; query = ""; } else { path = url.Substring(0, q); query = url.Substring(q + 1); } // todo: optimize and extend url pattern matching // fixme: this doesn't work if the application isn't mounted at root String[] split = path.Split('/'); if (split[0].Length > 0) return null; if (split.Length > 2 && split[1] == "pokemondpds" && split[2] == "web") { pathInfo = "/" + String.Join("/", split, 3, split.Length - 3); return VirtualPathUtility.ToAbsolute("~/pokemondpds_web.ashx"); } else if (split.Length > 1 && split[1] == "pokemondpds") { pathInfo = "/" + String.Join("/", split, 2, split.Length - 2); return VirtualPathUtility.ToAbsolute("~/pokemondpds.ashx"); } else if (split.Length > 2 && split[1] == "syachi2ds" && split[2] == "web") { pathInfo = "/" + String.Join("/", split, 3, split.Length - 3); return VirtualPathUtility.ToAbsolute("~/syachi2ds.ashx"); } else if (split.Length > 1 && split[1] == "pokemon" && split[2] == "validate") { pathInfo = "/pokemon/validate"; return VirtualPathUtility.ToAbsolute("~/pkvldtprod.ashx"); } else if (split.Length > 1 && split[1] == "dsio" && split[2] == "gw") { pathInfo = "/dsio/gw"; return VirtualPathUtility.ToAbsolute("~/pgl.ashx"); } else return null; } } } ================================================ FILE: gts/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("gts")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("gts")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0c0aba84-599e-47fb-a8ac-15e08edd136a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: gts/Properties/PublishProfiles/Local IIS.pubxml ================================================  True False True Debug Any CPU FileSystem C:\inetpub\gts FileSystem ================================================ FILE: gts/Properties/PublishProfiles/Public.pubxml ================================================ MSDeploy Release Any CPU True False False WMSVC True <_SavePWD>False ================================================ FILE: gts/Web.Public.config ================================================ ================================================ FILE: gts/Web.config ================================================  ================================================ FILE: gts/admin/Sessions.aspx ================================================ <%@ Page Title="" Language="C#" MasterPageFile="~/masters/MasterPage.master" AutoEventWireup="true" CodeBehind="Sessions.aspx.cs" Inherits="PkmnFoundations.GTS.admin.Sessions" %> ================================================ FILE: gts/admin/Sessions.aspx.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using GamestatsBase; namespace PkmnFoundations.GTS.admin { public partial class Sessions : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { StringBuilder builder = new StringBuilder(); GamestatsSessionManager gsm = GamestatsSessionManager.FromContext(Context); builder.Append("Active sessions ("); builder.Append(gsm.Sessions.Count); builder.Append("):
"); foreach (KeyValuePair session in gsm.Sessions) { builder.Append("Game ID: "); builder.Append(session.Value.GameId); builder.Append("
PID: "); builder.Append(session.Value.PID); builder.Append("
Token: "); builder.Append(session.Value.Token); builder.Append("
Hash: "); builder.Append(session.Value.Hash); builder.Append("
URL: "); builder.Append(session.Value.URL); builder.Append("
Expires: "); builder.Append(session.Value.ExpiryDate); builder.Append("

"); } litDebug.Text = builder.ToString(); } } } ================================================ FILE: gts/admin/Sessions.aspx.designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace PkmnFoundations.GTS.admin { public partial class Sessions { /// /// litDebug control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litDebug; } } ================================================ FILE: gts/admin/Web.Debug.config ================================================ ================================================ FILE: gts/admin/Web.Release.config ================================================ ================================================ FILE: gts/admin/Web.config ================================================  ================================================ FILE: gts/gts.csproj ================================================  Debug AnyCPU 2.0 {2EEAF2A8-68B7-4DB5-8818-36285D5CF9B3} {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} Library Properties PkmnFoundations.GTS PkmnFoundations.GTS v4.0 true 4.0 true full false bin\ DEBUG;TRACE prompt 4 AnyCPU pdbonly true bin\ TRACE prompt 4 Web.config Web.config Designer Web.config Sessions.aspx ASPXCodeBehind Sessions.aspx MasterPage.master ASPXCodeBehind MasterPage.master pgl.ashx pkvldtprod.ashx pokemondpds_web.ashx syachi2ds.ashx pokemondpds.ashx Global.asax {2d667f5b-f10d-44e2-93f6-dd555d9ee7df} GamestatsBase {408EFC7E-C6B0-4160-8628-2679E34385CE} Library 10.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) False True 50067 / False False False ================================================ FILE: gts/masters/MasterPage.master ================================================ <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.master.cs" Inherits="PkmnFoundations.GTS.masters.MasterPage" %> ================================================ FILE: gts/masters/MasterPage.master.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace PkmnFoundations.GTS.masters { public partial class MasterPage : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { } } } ================================================ FILE: gts/masters/MasterPage.master.designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace PkmnFoundations.GTS.masters { public partial class MasterPage { /// /// cpHead control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.ContentPlaceHolder cpHead; /// /// cpMain control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.ContentPlaceHolder cpMain; } } ================================================ FILE: gts/pgl.ashx ================================================ <%@ WebHandler Language="C#" CodeBehind="pgl.ashx.cs" Class="PkmnFoundations.GTS.pgl" %> ================================================ FILE: gts/pgl.ashx.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using PkmnFoundations.Support; namespace PkmnFoundations.GTS { /// /// Summary description for pgl /// public class pgl : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.StatusCode = 502;// 200; return; // error messages by status code: // 403, 404, 500: Comm error (13209) // 502: The server is undergoing maintenance (13212) // 503: The server is experiencing high traffic volumes (13211) var qs = context.Request.QueryString; if (context.Request.HttpMethod == "GET") { switch (qs["p"]) { case "account.playstatus": context.Response.OutputStream.WriteBytes(new byte[] { 0x00, 0x00, 0x00, 0x00 }); for (int i = 0; i < 0x7c; i++) { context.Response.OutputStream.WriteByte(0x00); } //# The command codes only work if is sleeping. // Command codes: // \x00 - Wake up normally // \x01 - "This Pokemon is not dreaming yet." // \x02 - "This Pokemon is dreaming." // \x03 - Wake up + download new changes from server // \x04 - Wake up normally? // \x05 - Put Pokemon to sleep if none is sleeping // \x08 - Leads to account.create.upload context.Response.OutputStream.WriteBytes(new byte[] { 0x00, 0x00, 0x00, 0x00 }); for (int i = 0; i < 0x40; i++) { context.Response.OutputStream.WriteByte(0x00); } break; case "sleepily.bitlist": context.Response.OutputStream.WriteBytes(new byte[] { 0x00, 0x00, 0x00, 0x00 }); for (int i = 0; i < 0x7c; i++) { context.Response.OutputStream.WriteByte(0x00); } for (int i = 0; i < 0x80; i++) { context.Response.OutputStream.WriteByte(0xff); } break; case "savedata.getbw": context.Response.StatusCode = 502; //context.Response.OutputStream.WriteBytes(new byte[] { 0x05, 0x00, 0x00, 0x00 }); break; case "savedata.download": context.Response.OutputStream.WriteBytes(new byte[] { 0x00, 0x00, 0x00, 0x00 }); break; case "worldbattle.download": context.Response.StatusCode = 502; break; default: context.Response.StatusCode = 502; break; } } else if (context.Request.HttpMethod == "POST") { switch (qs["p"]) { case "account.createdata": context.Response.OutputStream.WriteBytes(new byte[] { 0x00, 0x00, 0x00, 0x00 }); break; case "account.create.upload": context.Response.OutputStream.WriteBytes(new byte[] { 0x00, 0x00, 0x00, 0x00 }); break; case "savedata.upload": context.Response.OutputStream.WriteBytes(new byte[] { 0x00, 0x00, 0x00, 0x00 }); break; case "worldbattle.upload": context.Response.OutputStream.WriteBytes(new byte[] { 0x00, 0x00, 0x00, 0x00 }); break; case "savedata.download.finish": context.Response.OutputStream.WriteBytes(new byte[] { 0x00, 0x00, 0x00, 0x00 }); break; default: context.Response.StatusCode = 502; break; } } } public bool IsReusable { get { return true; } } } } ================================================ FILE: gts/pkvldtprod.ashx ================================================ <%@ WebHandler Language="C#" CodeBehind="pkvldtprod.ashx.cs" Class="PkmnFoundations.GTS.pkvldtprod" %> ================================================ FILE: gts/pkvldtprod.ashx.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; using PkmnFoundations.Support; using System.Text; namespace PkmnFoundations.GTS { /// /// Summary description for pkvldtprod /// public class pkvldtprod : IHttpHandler { public void ProcessRequest(HttpContext context) { byte[] requestData = new byte[(int)context.Request.InputStream.Length]; context.Request.InputStream.ReadBlock(requestData, 0, (int)context.Request.InputStream.Length); // this is a mysterious token of unknown purpose. It seems to vary // with the type of request being done. // On GTS requests, it's 83 characters long and begins with NDS. // In Random Matchup, it looks more like a base64 string, is 88 // chars long and encodes 64 bytes of random looking data. // It is null terminated (variable length), followed immediately // by the rest of the message. int tokenLength = Array.IndexOf(requestData, 0x00); String token = StringHelper.BytesToString(requestData, 0, tokenLength, Encoding.UTF8); int offset = tokenLength + 1; RequestType type = (RequestType)BitConverter.ToInt16(requestData, offset); offset += 2; PokemonValidationResult[] results; switch (type) { case RequestType.RandomMatchup: case RequestType.GTS: { int pkmCount = (requestData.Length - offset) / 220; results = new PokemonValidationResult[pkmCount]; for (int x = 0; x < results.Length; x++) { byte[] data = new byte[220]; Array.Copy(requestData, offset + x, data, 0, 220); Pokemon5 pkm = new Pokemon5(data); // todo: actual validation goes here results[x] = PokemonValidationResult.Valid; } } break; /* case RequestType.BattleSubway: { // todo: Need more info on this structure // todo: Perform actual validation here so that we can // error out before the player actually does their challenge } break; */ // todo: there also appears to be a Battle Video request? default: { // Don't understand this request. Give it a response containing // all 00s so stuff depending on it won't break. // The game accepts a hash of all 00s and doesn't care what's contained // in the response beyond its expected length so this will work. // fixme: Once we start generating real signatures, they will prevent // this from returning the necessary number of 00s in all cases. results = new PokemonValidationResult[]{ PokemonValidationResult.Valid, PokemonValidationResult.Valid, PokemonValidationResult.Valid, PokemonValidationResult.Valid, PokemonValidationResult.Valid, PokemonValidationResult.Valid}; } break; } PartyValidationResult result = PartyValidationResult.Valid; foreach (PokemonValidationResult pkr in results) { if (pkr != PokemonValidationResult.Valid) result = PartyValidationResult.Invalid; } context.Response.ContentType = "text/plain"; context.Response.OutputStream.WriteByte((byte)result); // success foreach (PokemonValidationResult pkr in results) { context.Response.OutputStream.Write(BitConverter.GetBytes((int)pkr), 0, 4); } // placeholder for signature. // Should be 128 bytes of an unknown hashing/signing algorithm context.Response.Write("Hey this is a totally legit pkvldtprod signature pwease accept it uwu"); context.Response.OutputStream.Write(new byte[69], 0, 69); // nice //context.Response.OutputStream.Write(new byte[128], 0, 128); } private enum PartyValidationResult : byte { Valid = 0x00, Invalid = 0x01 } private enum PokemonValidationResult : int { Valid = 0x00000000, Invalid = 0x3c000000 } private enum RequestType : short { RandomMatchup = 0x0000, GTS = 0x0100, BattleSubway = 0x0400 } private void Error400(HttpContext context) { context.Response.StatusCode = 400; context.Response.ContentType = "text/plain"; context.Response.Write("Bad request"); } public bool IsReusable { get { return true; } } } internal class Pokemon5 { // placeholder until I actually do this for real... byte[] Data; public Pokemon5(byte[] data) { if (data.Length != 220) throw new ArgumentException(); Data = data; } } } ================================================ FILE: gts/pokemondpds.ashx ================================================ <%@ WebHandler Language="C#" CodeBehind="pokemondpds.ashx.cs" Class="PkmnFoundations.GTS.pokemondpds" %> ================================================ FILE: gts/pokemondpds.ashx.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.SessionState; using PkmnFoundations.Data; using PkmnFoundations.Structures; using PkmnFoundations.Support; using System.IO; using System.Threading; using GamestatsBase; using PkmnFoundations.Wfc; namespace PkmnFoundations.GTS { /// /// Summary description for pokemondpds /// public class pokemondpds : GamestatsHandler { public pokemondpds() : base("sAdeqWo3voLeC5r16DYv", 0x45, 0x1111, 0x80000000, 0x4a3b2c1d, "pokemondpds", GamestatsRequestVersions.Version2, GamestatsResponseVersions.Version1, true, true) { } public override void ProcessGamestatsRequest(byte[] data, MemoryStream response, string url, int pid, HttpContext context, GamestatsSession session) { { BanStatus ban = BanHelper.GetBanStatus(pid, IpAddressHelper.GetIpAddress(context.Request), Generations.Generation4); if (ban != null && ban.Level > BanLevels.Restricted) { ShowError(context, 403); return; } } Pokedex.Pokedex pokedex = AppStateHelper.Pokedex(context.Application); switch (url) { default: SessionManager.Remove(session); // unrecognized page url ShowError(context, 404); return; #region Common // Called during startup. Seems to contain trainer profile stats. case "/pokemondpds/common/setProfile.asp": { SessionManager.Remove(session); if (data.Length != 100) { ShowError(context, 400); return; } #if !DEBUG try { #endif byte[] profileBinary = new byte[100]; Array.Copy(data, 0, profileBinary, 0, 100); TrainerProfile4 profile = new TrainerProfile4(pid, profileBinary, IpAddressHelper.GetIpAddress(context.Request)); Database.Instance.GamestatsSetProfile4(profile); #if !DEBUG } catch { } #endif short clientSecret = BitConverter.ToInt16(data, 96); short mailSecret = BitConverter.ToInt16(data, 98); // response: // 4 bytes of response code A // 4 bytes of response code B // Response code A values: // 0: Continues normally. // 1: The data was corrupted. It could not be sent. // 2: The server is undergoing maintenance. Please connect again later. // 3: BSOD if (mailSecret == -1) { // Register wii mail // Response code B values: // 0: There was a communication error. // 1: The Registration Code has been sent to your Wii console. Please enter the Registration Code. // 2: There was an error while attempting to send an authentication Wii message. // 3: There was a communication error. // 4: BSOD response.Write(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00 }, 0, 8); } else if (mailSecret != 0 || clientSecret != 0) { // Send wii mail confirmation code OR GTS when mail is configured (we can't tell them apart T__T) // (todo: We could use database to tell them apart. // If the previously stored profile has mailSecret == -1 then this is a wii mail confirmation. // If the previously stored profile has mailSecret == this mailSecret then this is GTS.) // Response code B values: // 0: Your Wii Number has been registered. // 1: There was a communication error. // 2: There was a communication error. // 3: Incorrect Registration Code. // 4: BSOD response.Write(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0, 8); } else { // GTS // Response code B values: // 0: Continues normally // 1: There was a communication error. // 2: There was a communication error. // 3: There was a Wii message authentication error. // 4: BSOD response.Write(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0, 8); } } break; #endregion #region GTS // Called during startup. Unknown purpose. case "/pokemondpds/worldexchange/info.asp": { SessionManager.Remove(session); // todo: find out the meaning of this request. // is it simply done to check whether the GTS is online? var ip = IpAddressHelper.GetIpAddress(context.Request); Database.Instance.GamestatsBumpProfile4(pid, ip); response.Write(new byte[] { 0x01, 0x00 }, 0, 2); } break; // Called during startup and when you check your pokemon's status. case "/pokemondpds/worldexchange/result.asp": { SessionManager.Remove(session); /* After the above step(s) or performing any of * the tasks below other than searching, the game * makes a request to /pokemondpds/worldexchange/result.asp. * If the game has had a Pokémon sent to it via a trade, * the server responds with the entire encrypted Pokémon * save struct. Otherwise, if there is a Pokémon deposited * in the GTS, it responds with 0x0004; if not, it responds * with 0x0005. */ GtsRecord4 record = Database.Instance.GtsDataForUser4(pokedex, pid); if (record == null) { // No pokemon in the system response.Write(new byte[] { 0x05, 0x00 }, 0, 2); } else if (record.IsExchanged > 0) { // traded pokemon arriving!!! response.Write(record.Save(), 0, 292); } else { // my existing pokemon is in the system, untraded response.Write(new byte[] { 0x04, 0x00 }, 0, 2); } // other responses: // 0-2 causes a BSOD but it flashes siezure. Scary // 3 causes it to be "checking GTS's status" forever. // 6 is also the flashy BSOD. So probably all invalid values do that. } break; // Called after result.asp returns 4 when you check your pokemon's status case "/pokemondpds/worldexchange/get.asp": { SessionManager.Remove(session); // This can be called in 3 circumstances: // 1. After result.asp when it says your existing pokemon is in the system // 2. When you check the summary of your pokemon (Platinum onward) // 3. When you attempt to retract your offer, just before saving. GtsRecord4 record = Database.Instance.GtsDataForUser4(pokedex, pid); if (record == null) { // No pokemon in the system // response codes: // 0x01: BSOD // 0x02: BSOD // 0x03, entering GTS: Causes it to show no pokemon in the system, as if result.asp returned 5. // 0x03, checking summary: A communication error has occurred. You will be returned to the title screen. Please press the A Button. // 0x03, retracting: Communication error... (and it boots you) // 0x04: BSOD // 0x05, entering GTS: Causes it to show no pokemon in the system, as if result.asp returned 5. // 0x05, checking summary: A communication error has occurred. You will be returned to the title screen. Please press the A Button. // 0x05, retracting: Communication error... (and it boots you) // 0x06: BSOD // 0x07: BSOD response.Write(new byte[] { 0x05, 0x00 }, 0, 2); return; } else { // just write the record whether traded or not... // todo: confirm that writing a traded record here will allow the trade to conclude response.Write(record.Save(), 0, 292); } } break; // Called after result.asp returns an inbound pokemon record to delete it case "/pokemondpds/worldexchange/delete.asp": { SessionManager.Remove(session); GtsRecord4 record = Database.Instance.GtsDataForUser4(pokedex, pid); if (record == null) { response.Write(new byte[] { 0x03, 0x00 }, 0, 2); } else if (record.IsExchanged > 0) { // Responses: // 0x00: BSOD // 0x01: Success // 0x02: BSOD // 0x03: A communication error has occurred. You have been disconnected from Nintendo Wi-Fi Connection. You will be returned to wherever you last saved. Please press the A Button. // 0x04: BSOD // 0x05: Either the GTS is experiencing high traffic volumes or the service is down. Please wait a while and try again. You have been disconnected from Nintendo Wi-Fi Connection, Please press the A Button. // 0x06: BSOD // 0x07: BSOD // delete the arrived pokemon from the system // todo: add transactions // todo: log the successful trade? // (either here or when the trade is done) bool success = Database.Instance.GtsDeletePokemon4(pid); if (success) response.Write(new byte[] { 0x01, 0x00 }, 0, 2); else response.Write(new byte[] { 0x05, 0x00 }, 0, 2); } else { // own pokemon is there, fail. Use return.asp instead. response.Write(new byte[] { 0x03, 0x00 }, 0, 2); } } break; // called to delete your own pokemon after taking it back case "/pokemondpds/worldexchange/return.asp": { SessionManager.Remove(session); GtsRecord4 record = Database.Instance.GtsDataForUser4(pokedex, pid); if (record == null || // no pokemon in the system record.IsExchanged > 0 || // a traded pokemon is there, fail. Use delete.asp instead. !Database.Instance.GtsCheckLockStatus4(record.TradeId, pid)) // someone else is in the process of trading for this { response.Write(new byte[] { 0x02, 0x00 }, 0, 2); } else { // delete own pokemon // todo: add transactions bool success = Database.Instance.GtsDeletePokemon4(pid); if (success) { response.Write(new byte[] { 0x01, 0x00 }, 0, 2); } else { response.Write(new byte[] { 0x02, 0x00 }, 0, 2); } } } break; // Called when you deposit a pokemon into the system. case "/pokemondpds/worldexchange/post.asp": { if (data.Length != 292) { SessionManager.Remove(session); ShowError(context, 400); return; } // todo: add transaction if (Database.Instance.GtsDataForUser4(pokedex, pid) != null) { // there's already a pokemon inside. // Force the player out so they'll recheck its status. SessionManager.Remove(session); response.Write(new byte[] { 0x0e, 0x00 }, 0, 2); break; } // keep the record in memory while we wait for post_finish.asp request byte[] recordBinary = new byte[292]; Array.Copy(data, 0, recordBinary, 0, 292); GtsRecord4 record = new GtsRecord4(pokedex, recordBinary); record.IsExchanged = 0; if (!record.Validate()) { // hack check failed SessionManager.Remove(session); // responses: // 0x00: Appears to start depositing? todo: test if this code leads to a normal deposit. // 0x01: successful deposit // 0x02-0x03: Communication error... // 0x04-0x06: bsod // 0x07: The GTS is very crowded now. Please try again later. (and it boots you!) // 0x08-0x0d: That Pokémon may not be offered for trade! // 0x0e: You were disconnected from the GTS. Returning to the reception counter. // 0x0f: Blue screen of death response.Write(new byte[] { 0x0c, 0x00 }, 0, 2); break; } // the following two fields are blank in the uploaded record. // The server must provide them instead. record.TimeDeposited = DateTime.UtcNow; record.TimeExchanged = null; record.PID = pid; session.Tag = record; // todo: delete any other post.asp sessions registered under this PID response.Write(new byte[] { 0x01, 0x00 }, 0, 2); } break; case "/pokemondpds/worldexchange/post_finish.asp": { SessionManager.Remove(session); if (data.Length != 8) { ShowError(context, 400); return; } // todo: these _finish requests seem to come with a magic number of 4 bytes // at offset 0. Find out what this is supposed to do and how to validate it. // find a matching session which contains our record GamestatsSession prevSession = SessionManager.FindSession(pid, "/pokemondpds/worldexchange/post.asp"); if (prevSession == null) { response.Write(new byte[] { 0x02, 0x00 }, 0, 2); return; } SessionManager.Remove(prevSession); if (prevSession.Tag == null) { response.Write(new byte[] { 0x02, 0x00 }, 0, 2); return; } AssertHelper.Assert(prevSession.Tag is GtsRecord4); GtsRecord4 record = (GtsRecord4)prevSession.Tag; if (Database.Instance.GtsDepositPokemon4(record)) { // Responses: // 0x00: BSOD // 0x01: Success // 0x02: A communication error has occurred. You have been disconnected from Nintendo Wi-Fi Connection. You will be returned to wherever you last saved. Please press the A Button. // 0x03: Communication error... (and it thinks the upload was successful) // 0x04: BSOD // 0x05: A communication error has occurred. You have been disconnected from Nintendo Wi-Fi Connection. You will be returned to wherever you last saved. Please press the A Button. // 0x06: BSOD // 0x07: BSOD response.Write(new byte[] { 0x01, 0x00 }, 0, 2); } else response.Write(new byte[] { 0x05, 0x00 }, 0, 2); } break; // the search request has a funny bit string request of search terms // and just returns a chunk of records end to end. case "/pokemondpds/worldexchange/search.asp": { SessionManager.Remove(session); if (data.Length < 7 || data.Length > 8) { ShowError(context, 400); return; } ushort species = BitConverter.ToUInt16(data, 0); if (species < 1) { ShowError(context, 400); return; } int resultsCount = (int)data[6]; if (resultsCount < 1) break; // optimize away requests for no rows Genders gender = (Genders)data[2]; byte minLevel = data[3]; byte maxLevel = data[4]; // byte 5 unknown byte country = 0; if (data.Length > 7) country = data[7]; if (resultsCount > 7) resultsCount = 7; // stop DDOS GtsRecord4[] records = Database.Instance.GtsSearch4(pokedex, pid, species, gender, minLevel, maxLevel, country, resultsCount); foreach (GtsRecord4 record in records) { response.Write(record.Save(), 0, 292); } Database.Instance.GtsSetLastSearch4(pid); } break; // the exchange request uploads a record of the exchangee pokemon // plus the desired PID to trade for at the very end. case "/pokemondpds/worldexchange/exchange.asp": { if (data.Length != 296) { SessionManager.Remove(session); ShowError(context, 400); return; } byte[] uploadData = new byte[292]; Array.Copy(data, 0, uploadData, 0, 292); GtsRecord4 upload = new GtsRecord4(pokedex, uploadData); upload.IsExchanged = 0; int targetPid = BitConverter.ToInt32(data, 292); GtsRecord4 result = Database.Instance.GtsDataForUser4(pokedex, targetPid); DateTime ? searchTime = Database.Instance.GtsGetLastSearch4(pid); if (result == null || searchTime == null || result.TimeDeposited > (DateTime)searchTime || // If this condition is met, it means the pokemon in the system is DIFFERENT from the one the user is trying to trade for, ie. it was deposited AFTER the user did their search. The one the user wants was either taken back or traded. result.IsExchanged != 0) { // Pokémon is traded (or was never here to begin with) SessionManager.Remove(session); response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } // enforce request requirements server side if (!upload.Validate() || !upload.CanTrade(result)) { // todo: find the correct codes for these SessionManager.Remove(session); // responses: // 0x00-0x01: bsod // 0x02: Unfortunately, it was traded to another Trainer. // 0x03-0x07: bsod // 0x08-0x0d: That Pokémon may not be offered for trade! // 0x0e: You were disconnected from the GTS. Returning to the reception counter. // 0x0f: bsod response.Write(new byte[] { 0x0c, 0x00 }, 0, 2); return; } if (!Database.Instance.GtsLockPokemon4(result.TradeId, pid)) { // failed to acquire lock, implying someone else beat us here. Say already traded. SessionManager.Remove(session); response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } // uncomment these two lines if you're replaying gamestats requests and need to skip the random token //session = new GamestatsSession(this.GameId, this.Salt, pid, "/pokemondpds/worldexchange/exchange.asp"); //SessionManager.Add(session); object[] tag = new GtsRecord4[2]; tag[0] = upload; tag[1] = result; session.Tag = tag; GtsRecord4 tradedResult = result.Clone(); tradedResult.FlagTraded(upload); // only real purpose is to generate a proper response // todo: we need a mechanism to "reserve" a pokemon being traded at this // point in the process, but be able to relinquish it if exchange_finish // never happens. // Currently, if two people try to take the same pokemon, it will appear // to work for both but then fail for the second after they've saved // their game. This causes a hard crash and a "save file is corrupt, // "previous will be loaded" error when restarting. // the reservation can be done in application state and has no reason // to touch the database. (exchange_finish won't work anyway if application // state is lost.) // I also have a hunch that failure to send the exchange_finish request // is what causes the notorious GTS glitch where a pokemon is listed // under the wrong species and you can't trade it response.Write(result.Save(), 0, 292); } break; case "/pokemondpds/worldexchange/exchange_finish.asp": { //if (session != null) SessionManager.Remove(session); if (data.Length != 8) { ShowError(context, 400); return; } // find a matching session which contains our record GamestatsSession prevSession = SessionManager.FindSession(pid, "/pokemondpds/worldexchange/exchange.asp"); if (prevSession == null) { // response codes: // 0x00: I thought this meant fail but it also sometimes succeeds // 0x01: Success (the normal success response) // 0x02: Either the GTS is experiencing high traffic volumes or the service is down. Please wait a while and try again. // 0x03: Success (apparently) // 0x04: Success (apparently) // 0x05: Success (apparently) // 0x06: Success (apparently) // ... // 0x0f: Success (apparently) // I'm going to reason that responses other than 0x02 will all succeed, at least on platinum response.Write(new byte[] { 0x02, 0x00 }, 0, 2); return; } SessionManager.Remove(prevSession); if (prevSession.Tag == null) { response.Write(new byte[] { 0x02, 0x00 }, 0, 2); return; } AssertHelper.Assert(prevSession.Tag is GtsRecord4[]); GtsRecord4[] tag = (GtsRecord4[])prevSession.Tag; AssertHelper.Assert(tag.Length == 2); GtsRecord4 upload = tag[0]; GtsRecord4 result = tag[1]; if (Database.Instance.GtsTradePokemon4(upload, result, pid)) response.Write(new byte[] { 0x01, 0x00 }, 0, 2); else response.Write(new byte[] { 0x02, 0x00 }, 0, 2); } break; #endregion #region Battle Tower case "/pokemondpds/battletower/info.asp": SessionManager.Remove(session); // Probably an availability/status code. Database.Instance.GamestatsBumpProfile4(pid, IpAddressHelper.GetIpAddress(context.Request)); // Response codes: // 0x00: BSOD // 0x01: Continues normally // 0x02: BSOD // 0x03: The Wi-Fi Battle Tower is currently undergoing maintenance. Please try again later. // 0x04: The Wi-Fi Battle Tower is very crowded. Please try again later. // 0x05: Unable to connect to the Wi-Fi Battle Tower. Returning to the reception counter. // 0x06: BSOD response.Write(new byte[] { 0x01, 0x00 }, 0, 2); break; case "/pokemondpds/battletower/roomnum.asp": SessionManager.Remove(session); //byte rank = data[0x00]; response.Write(new byte[] { 0x32, 0x00 }, 0, 2); break; case "/pokemondpds/battletower/download.asp": { SessionManager.Remove(session); if (data.Length != 2) { ShowError(context, 400); return; } byte rank = data[0x00]; byte roomNum = data[0x01]; if (rank > 9 || roomNum > 49) { ShowError(context, 400); return; } FakeOpponentFactory4 fact = new FakeOpponentFactory4(); BattleTowerRecord4[] opponents = Database.Instance.BattleTowerGetOpponents4(pokedex, pid, rank, roomNum); BattleTowerProfile4[] leaders = Database.Instance.BattleTowerGetLeaders4(pokedex, rank, roomNum); BattleTowerRecordBase[] fakeOpponents = FakeOpponentGenerator.GenerateFakeOpponents(fact, 7 - opponents.Length); foreach (BattleTowerRecord4 record in fakeOpponents) { response.Write(record.Save(), 0, 228); } foreach (BattleTowerRecord4 record in opponents) { response.Write(record.Save(), 0, 228); } foreach (BattleTowerProfile4 leader in leaders) { response.Write(leader.Save(), 0, 34); } if (leaders.Length < 30) { byte[] fakeLeader = new BattleTowerProfile4 ( new EncodedString4("-----", 16), Versions.Platinum, Languages.English, 0, 0, 0x00000000, new TrendyPhrase4(5, 0, 0, 0), 0, 0 ).Save(); for (int x = leaders.Length; x < 30; x++) { response.Write(fakeLeader, 0, 34); } } // This is completely insane. The game crashes when you // use Check Leaders if the response arrives too fast, // so we artificially delay it. // todo: This is slower than it needs to be if the // database is slow to respond. We should sleep for a // variable time based on when the request was received. Thread.Sleep(500); } break; case "/pokemondpds/battletower/upload.asp": { SessionManager.Remove(session); if (data.Length != 239) { ShowError(context, 400); return; } BattleTowerRecord4 record = new BattleTowerRecord4(pokedex, data, 0); record.Rank = data[0xe4]; record.RoomNum = data[0xe5]; record.BattlesWon = data[0xe6]; record.Unknown5 = BitConverter.ToUInt64(data, 0xe7); record.PID = pid; foreach (var p in record.Party) { // todo: add battle tower specific checks: // item clause, species clause, banned species, banned items // https://bulbapedia.bulbagarden.net/wiki/Battle_Tower_(Sinnoh)#Restrictions if (!p.Validate().IsValid) { // Tell the client it was successful so they don't keep retrying. response.Write(new byte[] { 0x01, 0x00 }, 0, 2); return; } } // todo: Do we want to store their record anyway if they lost the first round? if (record.BattlesWon > 0) Database.Instance.BattleTowerUpdateRecord4(record); if (record.BattlesWon == 7) Database.Instance.BattleTowerAddLeader4(record); // List of responses: // 0x00: BSOD // 0x01: Uploads successfully // 0x02: That number cannot be specified for the Wi-Fi Battle Tower. // 0x03: BSOD // 0x04: The Wi-Fi Battle Tower is very crowded. Please try again later. // 0x05: Unable to connect to the Wi-Fi Battle Tower. Returning to the reception counter. // 0x06: BSOD // 0x07: BSOD // 0x08: BSOD response.Write(new byte[] { 0x01, 0x00 }, 0, 2); } break; #endregion } } } } ================================================ FILE: gts/pokemondpds_web.ashx ================================================ <%@ WebHandler Language="C#" CodeBehind="pokemondpds_web.ashx.cs" Class="PkmnFoundations.GTS.pokemondpds_web" %> ================================================ FILE: gts/pokemondpds_web.ashx.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using GamestatsBase; using PkmnFoundations.Data; using PkmnFoundations.Structures; using PkmnFoundations.Wfc; namespace PkmnFoundations.GTS { /// /// Gamestats handler for Wi-Fi Plaza /// public class pokemondpds_web : GamestatsHandler { public pokemondpds_web() : base("uLMOGEiiJogofchScpXb000244fd00006015100000005b440e7epokemondpds", GamestatsRequestVersions.Version3, GamestatsResponseVersions.Version2, true, true) { } public override void ProcessGamestatsRequest(byte[] request, MemoryStream response, string url, int pid, HttpContext context, GamestatsSession session) { switch (url) { default: SessionManager.Remove(session); // unrecognized page url ShowError(context, 404); return; case "/pokemondpds/web/enc/lobby/checkProfile.asp": { if (request.Length != 168) { ShowError(context, 400); return; } byte[] requestData = new byte[164]; Array.Copy(request, 4, requestData, 0, 164); TrainerProfilePlaza requestProfile = new TrainerProfilePlaza(pid, requestData); Database.Instance.PlazaSetProfile(requestProfile); TrainerProfilePlaza responseProfile = Database.Instance.PlazaGetProfile(requestProfile.PID); response.Write(responseProfile.Data, 12, 152); // skip first 12 bytes of profile data on response } break; case "/pokemondpds/web/enc/lobby/getSchedule.asp": { // This is a replayed response from a game I had with Pipian. // It appears to be 49 ints. // todo(mythra): A real implementation // - we can generate events manually now, but we have a few // missing fields, so more research will need to be done before // that implementation. // note(mythra): this response is usually overwritten by the // peerchat server (through GETCHANKEY `b_lib_c_lobby`). // this is only taken if that channel key returns an // "empty" response. PlazaSchedule ps = new PlazaSchedule(); ps.Duration = 1200; ps.Unknown1 = -1485781858; ps.FootprintOptions = PlazaFootprintOptions.Normal; ps.RoomType = PlazaRoomTypes.Grass; ps.Season = PlazaSeasons.None; ps.Schedule = new[] { // todo: Have different, randomized schedules but in a way that makes sense new PlazaScheduleEntry(0, (PlazaEventTypes)1), new PlazaScheduleEntry(0, (PlazaEventTypes)7), new PlazaScheduleEntry(0, (PlazaEventTypes)11), new PlazaScheduleEntry(780, (PlazaEventTypes)8), new PlazaScheduleEntry(840, (PlazaEventTypes)2), new PlazaScheduleEntry(840, (PlazaEventTypes)9), new PlazaScheduleEntry(900, (PlazaEventTypes)3), new PlazaScheduleEntry(900, (PlazaEventTypes)10), new PlazaScheduleEntry(900, (PlazaEventTypes)12), new PlazaScheduleEntry(960, (PlazaEventTypes)4), new PlazaScheduleEntry(960, (PlazaEventTypes)9), new PlazaScheduleEntry(960, (PlazaEventTypes)13), new PlazaScheduleEntry(960, (PlazaEventTypes)15), new PlazaScheduleEntry(1020, (PlazaEventTypes)5), new PlazaScheduleEntry(1020, (PlazaEventTypes)14), new PlazaScheduleEntry(1020, (PlazaEventTypes)16), new PlazaScheduleEntry(1075, (PlazaEventTypes)18), new PlazaScheduleEntry(1080, (PlazaEventTypes)6), new PlazaScheduleEntry(1080, (PlazaEventTypes)13), new PlazaScheduleEntry(1080, (PlazaEventTypes)17), new PlazaScheduleEntry(1140, (PlazaEventTypes)11), new PlazaScheduleEntry(1200, (PlazaEventTypes)19), }; Random rand = new Random(); int roomChoice = rand.Next(13); if (roomChoice < 1) { ps.RoomType = PlazaRoomTypes.Mew; ps.FootprintOptions = PlazaFootprintOptions.Arceus; } else { ps.RoomType = (PlazaRoomTypes)((roomChoice - 1) / 3); // todo: Seasons. Based on the irl season? Maybe use GenV's season? That would be a nice callout } response.Write(new byte[] { 0x00, 0x00, 0x00, 0x00 }, 0, 4); response.Write(ps.Save(), 0, ps.Size); } break; case "/pokemondpds/web/enc/lobby/getVIP.asp": { // todo: keep VIPs in database response.Write(new byte[] { 0x00, 0x00, 0x00, 0x00 }, 0, 4); // VIPs. foreach (var vip in VIPs) { response.Write(vip.Save(), 0, vip.Size); } } break; case "/pokemondpds/web/enc/lobby/getQuestionnaire.asp": { // This is a replayed response that asks the question, // "Which move would you most like to use?" Cut/Surf/Strength // It also includes results for "last week"'s survey: // "Do you know anyone that looks like a Gym Leader?" Yes/No/Yes, a little // Apparently it's possible not just to use built-in survey // questions but to also pose unique new ones? // todo: Turn this into a PlazaQuestionnaire object. response.Write(new byte[]{ 0x00, 0x00, 0x00, 0x00, 0x2a, 0x01, 0x00, 0x00, 0x2d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x01, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x46, 0x00, 0x00, 0x00, 0x33, 0x00, 0x00, 0x00, 0x64, 0x01, 0x00, 0x00, 0x11, 0x01, 0x00, 0x00, 0x83, 0x00, 0x00, 0x00 }, 0, 732); /* response.Write(new byte[] { 0x0, 0x0, 0x0, 0x0 }, 0, 4); response.Write(staticQuestionnaire, 0, staticQuestionnaire.Length); */ } break; case "/pokemondpds/web/enc/lobby/submitQuestionnaire.asp": { // One day we could parse as 'SubmittedQuestionnaire', and save in a DB somewhere. // that'd be cool! // // literally 'thx' in ascii... lol response.Write(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x74, 0x68, 0x78, 0x00 }, 0, 8); } break; } } /// /// The list of "VIPs". /// /// Being a VIP gives you the following benefits: /// /// 1. Your Tap Toy is immediately upgraded to level 3. /// 2. You get a gold trainer card, instead of a blue trainer card. /// 3. You get a special color on the list of people in a lobby. /// 4. You get a special color name on the footprint board. /// 5. Some other mini games have a special color for your name. /// /// VIPs can also have custom "passphrases" that show when you bump /// into them. These are generated from the standard word list you /// could choose in any word box. These will show when you bump into /// a user. /// private static VipRecord[] VIPs = new VipRecord[] { new VipRecord(600403373, 0, 0, 0, 0), new VipRecord(601315647, 0, 0, 0, 0), new VipRecord(601988829, 0, 0, 0, 0), new VipRecord(602778198, 4, 4, 4, 4), // "STEEL STEEL STEEL STEEL" // Etchy -- for finding vips in the first place. new VipRecord(602778716, 0, 0, 0, 0) }; /// /// A static questionnaire, who's id is not above 1k so it doesn't load the custom question text. /// /// The last weeks results is still taken. /// And the footer of unknown data is copied from static responses. /// private static byte[] staticQuestionnaire = new PlazaQuestionnaire( new PlazaQuestion(730, "Not used", new string[] { "N/A", "N/A", "N/A" }, new byte[12], false), new PlazaQuestion(729, "Not used", new string[] { "N/A", "N/A", "N/A" }, new byte[12], false), new int[] { 69, 420, 100 }, new byte[] { 0x64, 0x01, 0x00, 0x00, 0x11, 0x01, 0x00, 0x00, 0x83, 0x00, 0x00, 0x00 }).Save(); } } ================================================ FILE: gts/src/AppStateHelper.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using PkmnFoundations.Data; namespace PkmnFoundations.GTS { public static class AppStateHelper { /// /// Gets the Pokédex stored in Application State or else instances a /// new one from the default database. /// /// App State reference for this request /// Pokédex public static Pokedex.Pokedex Pokedex(HttpApplicationState application) { return GetTypedApplicationObject(application, "pkmncfPokedex", () => new Pokedex.Pokedex(Database.Instance, false)); } public static T GetTypedApplicationObject(HttpApplicationState application, String key, Func initializer) where T : class { object o = application[key]; T t = o as T; if (t == null) { t = initializer(); application.Add(key, t); } return t; } } } ================================================ FILE: gts/src/BanHelper.cs ================================================ using PkmnFoundations.Data; using PkmnFoundations.Structures; using PkmnFoundations.Wfc; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace PkmnFoundations.GTS { public static class BanHelper { public static BanStatus GetBanStatus(int pid, string IpAddress, Generations generation) { try { BanStatus pidBan = Database.Instance.CheckBanStatus(pid); BanStatus ipBan = Database.Instance.CheckBanStatus(IpAddress); BanStatus macBan = null; BanStatus saveBan = null; BanStatus ipRangeBan = null; try { switch (generation) { case Generations.Generation4: { var profile = Database.Instance.GamestatsGetProfile4(pid); if (profile != null) { macBan = Database.Instance.CheckBanStatus(profile.MacAddress); saveBan = Database.Instance.CheckBanStatus(profile); } break; } case Generations.Generation5: { var profile = Database.Instance.GamestatsGetProfile5(pid); if (profile != null) { macBan = Database.Instance.CheckBanStatus(profile.MacAddress); saveBan = Database.Instance.CheckBanStatus(profile); } break; } } } catch (Exception) { } try { uint ipBinary = IpAddressHelper.Ipv4ToBinary(IpAddress); ipRangeBan = Database.Instance.CheckBanStatus(ipBinary); } catch (Exception) { } return new[] { pidBan, ipBan, macBan, saveBan, ipRangeBan }.Where(ban => ban != null).OrderBy(ban => ban.Level).LastOrDefault(); } catch (Exception) { return null; } } } } ================================================ FILE: gts/src/FakeOpponentGenerator.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using PkmnFoundations.Structures; using PkmnFoundations.Support; using PkmnFoundations.Wfc; namespace PkmnFoundations.GTS { /// /// Provides a source of fake battle tower opponents. /// public static class FakeOpponentGenerator { const int FAKE_OPPONENTS_COUNT_4 = 8; const int FAKE_OPPONENTS_COUNT_5 = 8; /// /// Randomly selects some fake opponents without repeats (if possible) /// /// /// public static BattleTowerRecordBase[] GenerateFakeOpponents(FakeOpponentFactory factory, int count) { if (count == 0) return new BattleTowerRecordBase[0]; int fakeOpponentsCount = (factory.Generation < Generations.Generation5) ? FAKE_OPPONENTS_COUNT_4 : FAKE_OPPONENTS_COUNT_5; int residualCount = count % fakeOpponentsCount; int repeatCount = count / fakeOpponentsCount; List values = new List(count); Random rand = new Random(); for (int x = 0; x < repeatCount; x++) { values.AddRange(Enumerable.Range(0, fakeOpponentsCount)); } values.AddRange(Enumerable.Range(0, fakeOpponentsCount).DrawWithoutReplacement(rand).Take(residualCount)); var pokedex = AppStateHelper.Pokedex(HttpContext.Current.Application); var results = values.DrawWithoutReplacement(rand).Select(i => GenerateFakeOpponent(factory, pokedex, i)); return results.ToArray(); } public static BattleTowerRecordBase GenerateFakeOpponent(FakeOpponentFactory factory, Pokedex.Pokedex pokedex, int index) { BattleTowerRecordBase record = factory.CreateRecord(pokedex); bool gen4 = factory.Generation <= Generations.Generation4; // Trainer classes in gen4: https://projectpokemon.org/rawdb/diamond/msg/560.php // Trainer classes in gen5: https://projectpokemon.org/rawdb/black/msg/191.php switch (index) { default: throw new ArgumentOutOfRangeException("index"); case 0: record.Party[0] = factory.CreatePokemon(pokedex, 129, 0, // Magikarp 3133, // Cheri new ushort[] { 150, // Splash 33, // Tackle 175, // Flail 340 // Bounce }, 0x01020304, 3, // Adamant IvStatValues.PackIVs(31, 31, 21, 31, 21, 21), new byte[] { 6, 252, 0, 252, 0, 0 }, 0, Languages.English, 33, // Swift swim 255, "Carp" ); record.Party[1] = factory.CreatePokemon(pokedex, 223, 0, // Remoraid 3134, // Chesto new ushort[] { 60, // Psybeam 61, // Bubblebeam 62, // Aurora beam 324 // Signal beam }, 0x01020304, 10, // Timid IvStatValues.PackIVs(31, 21, 21, 31, 31, 21), new byte[] { 6, 252, 0, 252, 0, 0 }, 0, Languages.English, 97, // Sniper 255, "Gunter" ); record.Party[2] = factory.CreatePokemon(pokedex, 349, 0, // Feebas 3134, // Chesto new ushort[] { 150, // Splash 33, // Tackle 175, // Flail 240 // Rain Dance }, 0x01020304, 13, // Jolly IvStatValues.PackIVs(31, 21, 21, 31, 31, 21), new byte[] { 252, 0, 6, 0, 0, 252 }, 0, Languages.English, 33, // Swift swim 255, "Meryl" ); record.Profile = factory.CreateProfile( "Steve", Versions.Platinum, Languages.English, 0, 0, 0x01020304, gen4 ? factory.CreateTrendyPhrase(0, 16, 291, 7) // Ninjask! Squirtle power! : factory.CreateTrendyPhrase(1, 6, 7, 884), // Watch my Squirtle power take care of Metal Claw! 0, 11 // Fisherman ); if (gen4) { record.PhraseChallenged = factory.CreateTrendyPhrase(1, 14, 1347, 65535); // This FISHING was really good! record.PhraseWon = factory.CreateTrendyPhrase(1, 11, 766, 65535); // I might have won with HELPING HAND! record.PhraseLost = factory.CreateTrendyPhrase(2, 15, 1347, 65535); // I would’ve won if this\nwere FISHING... } else { record.PhraseChallenged = factory.CreateTrendyPhrase(1, 6, 7, 884); // Watch my Squirtle power take care of Metal Claw! record.PhraseWon = factory.CreateTrendyPhrase(5, 0, 1611, 65535); record.PhraseLost = factory.CreateTrendyPhrase(5, 0, 1611, 65535); } break; case 1: record.Party[0] = factory.CreatePokemon(pokedex, 376, 0, // Metagross 268, // Expert belt new ushort[] { 89, // EQ 309, // Meteor mash 9, // Thunderpunch 153 // Explosion }, 15562158, 2106656978, // Actual TID/PV. Adamant, chained shiny 493780176, // Actual IVs which are crap. new byte[] { 252, 238, 0, 20, 0, 0 }, 0, Languages.English, 29, // Clear body 255, "Goldfinger" ); record.Party[1] = factory.CreatePokemon(pokedex, 282, 0, // Gardevoir 297, // Choice specs new ushort[] { 94, // Psychic 85, // Thunderbolt 247, // Shadow ball 271 // Trick }, 15562158, 4094067015, // Actual TID/PV. Modest, chained shiny 663420771, // Actual IVs, should be decent new byte[] { 254, 0, 56, 144, 56, 0 }, 0, Languages.English, 36, // Trace 255, "Curly" ); record.Party[2] = factory.CreatePokemon(pokedex, 134, 0, // Vaporeon 234, // Leftovers new ushort[] { 57, // Surf 164, // Substitute 273, // Wish 226 // Baton pass }, 15562158, 895218680, // Bold 514292539, new byte[] { 204, 0, 254, 0, 52, 0 }, 0, Languages.English, 11, // Water absorb 255, "Seabiscuit" ); record.Profile = factory.CreateProfile( "Megan", Versions.Platinum, Languages.English, 0, 0, 0x02030405, gen4 ? factory.CreateTrendyPhrase(3, 8, 1487, 65535) // There's only WI-FI left! : factory.CreateTrendyPhrase(5, 0, 1611, 65535), // fixme 2, 33 // Lady ); if (gen4) { record.PhraseChallenged = factory.CreateTrendyPhrase(3, 8, 1487, 65535); // There's only WI-FI left! record.PhraseWon = factory.CreateTrendyPhrase(3, 3, 1492, 1439); // This BATTLE TOWER is DIFFICULT, isn't it? record.PhraseLost = factory.CreateTrendyPhrase(3, 2, 1493, 1492); // I love GTS! I love BATTLE TOWER too! } else { record.PhraseChallenged = factory.CreateTrendyPhrase(5, 0, 1611, 65535); // Glad to meet you! I am MACHINE! record.PhraseWon = factory.CreateTrendyPhrase(5, 0, 1611, 65535); record.PhraseLost = factory.CreateTrendyPhrase(5, 0, 1611, 65535); } break; case 2: record.Party[0] = factory.CreatePokemon(pokedex, 392, 0, // Infernape 275, // Focus sash new ushort[] { 252, // Fake out 283, // Endeavour 183, // Mach punch 7 // Fire punch }, 0x02030405, 13, // Jolly IvStatValues.PackIVs(31, 31, 20, 31, 10, 20), new byte[] { 6, 252, 0, 252, 0, 0 }, 0, Languages.English, 66, // Blaze 255, "FunkyMunky" ); record.Party[1] = factory.CreatePokemon(pokedex, 235, 0, // Smeargle 210, // Custap new ushort[] { 147, // Spore 169, // Spider web 286, // Imprison 144 // Transform }, 0x02030405, 10, // Timid IvStatValues.PackIVs(31, 10, 31, 31, 10, 20), new byte[] { 252, 0, 6, 252, 0, 0 }, 0, Languages.English, 101, // Technician 255, "Yourself" ); record.Party[2] = factory.CreatePokemon(pokedex, 365, 0, // Walrein 217, // Quick claw new ushort[] { 156, // Rest 214, // Sleep talk 104, // Double team 329 // Sheer cold }, 5, 5, // Bold, shiny IvStatValues.PackIVs(31, 10, 20, 31, 10, 31), new byte[] { 252, 0, 0, 252, 0, 6 }, 0, Languages.English, 47, // Thick fat 255, "Problem?" ); record.Profile = factory.CreateProfile( "Dennis", Versions.Platinum, Languages.English, 0, 0, 0x02030405, gen4 ? factory.CreateTrendyPhrase(1, 12, 1147, 65535) // I get the happiest with MOTHER : factory.CreateTrendyPhrase(5, 0, 1611, 65535), // fixme 0, 32 // Rich boy ); if (gen4) { record.PhraseChallenged = factory.CreateTrendyPhrase(1, 12, 1147, 65535); // I get the happiest with MOTHER record.PhraseWon = factory.CreateTrendyPhrase(2, 8, 1140, 65535); // You're WEAK, aren't you? record.PhraseLost = factory.CreateTrendyPhrase(2, 6, 1421, 65535); // ROFL! How awful! } else { record.PhraseChallenged = factory.CreateTrendyPhrase(5, 0, 1611, 65535); // Glad to meet you! I am MACHINE! record.PhraseWon = factory.CreateTrendyPhrase(5, 0, 1611, 65535); record.PhraseLost = factory.CreateTrendyPhrase(5, 0, 1611, 65535); } break; case 3: record.Party[0] = factory.CreatePokemon(pokedex, 248, 0, // Tyranitar 189, // Chople new ushort[] { 446, // Stealth rock 349, // Dragon dance 89, // EQ 444 // Stone edge }, 13, 13, // Jolly, shiny IvStatValues.PackIVs(31, 31, 20, 31, 10, 20), new byte[] { 6, 252, 0, 252, 0, 0 }, 0, Languages.English, 45, // Sand stream 255, "Tyranitar" ); record.Party[1] = factory.CreatePokemon(pokedex, 212, 0, // Scizor 270, // Life orb new ushort[] { 418, // Bullet punch 450, // Bug bite 14, // Swords dance 355 // Roost }, 0x03040506, 3, // Adamant IvStatValues.PackIVs(31, 31, 20, 31, 10, 20), new byte[] { 6, 252, 0, 252, 0, 0 }, 0, Languages.English, 101, // Technician 255, "Scizor" ); record.Party[2] = factory.CreatePokemon(pokedex, 485, 0, // Heatran 234, // Leftovers new ushort[] { 436, // Lava plume 414, // Earth power 156, // Rest 214 // Sleep talk }, 0x03040506, 3, // Modest // fixme: these IVs are unreasonably high for Soft Resetting. IvStatValues.PackIVs(31, 10, 20, 20, 31, 31), new byte[] { 250, 0, 0, 0, 56, 204 }, 0, Languages.English, 18, // Flash fire 255, "Heatran" ); record.Profile = factory.CreateProfile( "Dusty", Versions.Platinum, Languages.English, 0, 0, 0x03040506, gen4 ? factory.CreateTrendyPhrase(3, 4, 1342, 65535) // I can do anything for TREASURE : factory.CreateTrendyPhrase(5, 0, 1611, 65535), // fixme 0, 48 // Ruin Maniac ); if (gen4) { record.PhraseChallenged = factory.CreateTrendyPhrase(3, 4, 1342, 65535); // I can do anything for TREASURE record.PhraseWon = factory.CreateTrendyPhrase(3, 6, 1148, 1107); // GRANDFATHER is the real NO.1 record.PhraseLost = factory.CreateTrendyPhrase(3, 10, 1389, 65535); // I prefer VACATION after all } else { record.PhraseChallenged = factory.CreateTrendyPhrase(5, 0, 1611, 65535); // Glad to meet you! I am MACHINE! record.PhraseWon = factory.CreateTrendyPhrase(5, 0, 1611, 65535); record.PhraseLost = factory.CreateTrendyPhrase(5, 0, 1611, 65535); } break; case 4: record.Party[0] = factory.CreatePokemon(pokedex, 460, 0, // Abomasnow 287, // Scarf new ushort[] { 59, // Blizzard 452, // Wood hammer 237, // Hidden power 89 // EQ }, 0x04050607, 11, // Hasty IvStatValues.PackIVs(19, 31, 18, 30, 28, 19), // HP:fire base 59 // Original EVs: 228Spe/164Atk/116SAtk // Adjusted for Hidden Power IVs, sacrificing some Attack new byte[] { 0, 148, 0, 234, 128, 0 }, 0, Languages.English, 117, // Snow warning 255, "Abomasnow" ); record.Party[1] = factory.CreatePokemon(pokedex, 471, 0, // Glaceon 246, // Nevermeltice new ushort[] { 59, // Blizzard 247, // Shadow ball 273, // Wish 182 // Protect }, 15, 15, // Modest, shiny IvStatValues.PackIVs(31, 10, 20, 31, 31, 20), new byte[] { 6, 0, 0, 252, 252, 0 }, 0, Languages.English, 81, // Snow cloak 255, "Glaceon" ); record.Party[2] = factory.CreatePokemon(pokedex, 461, 0, // Weavile 275, // Focus sash new ushort[] { 14, // Swords dance 400, // Night slash 8, // Ice punch 67 // Low kick }, 13, 13, // Jolly, shiny IvStatValues.PackIVs(31, 31, 20, 31, 10, 20), new byte[] { 40, 252, 0, 218, 0, 0 }, 0, Languages.English, 46, // Pressure 255, "Weavile" ); record.Profile = factory.CreateProfile( "Frosty", Versions.Platinum, Languages.English, 0, 0, 0x04050607, gen4 ? factory.CreateTrendyPhrase(3, 3, 677, 1438) // This POWDER SNOW is NICE, isn't it? : factory.CreateTrendyPhrase(5, 0, 1611, 65535), // fixme 2, 35 // Socialite ); if (gen4) { record.PhraseChallenged = factory.CreateTrendyPhrase(3, 3, 677, 1438); // This POWDER SNOW is NICE, isn't it? record.PhraseWon = factory.CreateTrendyPhrase(1, 14, 797, 65535); // This ICE BALL was really good record.PhraseLost = factory.CreateTrendyPhrase(2, 5, 752, 65535); // Could it be? HEAT WAVE } else { record.PhraseChallenged = factory.CreateTrendyPhrase(5, 0, 1611, 65535); // Glad to meet you! I am MACHINE! record.PhraseWon = factory.CreateTrendyPhrase(5, 0, 1611, 65535); record.PhraseLost = factory.CreateTrendyPhrase(5, 0, 1611, 65535); } break; case 5: record.Party[0] = factory.CreatePokemon(pokedex, 437, 0, // Bronzong 234, // Leftovers new ushort[] { 433, // Trick room 360, // Gyro ball 95, // Hypnosis 153 // Explosion }, 22, 22, // Sassy, shiny IvStatValues.PackIVs(31, 20, 31, 0, 10, 20), new byte[] { 252, 0, 252, 0, 0, 6 }, 0, Languages.English, 26, // Levitate 255, "Bronzong" ); record.Party[1] = factory.CreatePokemon(pokedex, 464, 0, // Rhyperior 270, // Life orb new ushort[] { 89, // EQ 444, // Stone edge 401, // Aqua tail 224 // Megahorn }, 0x05060708, 2, // Brave IvStatValues.PackIVs(31, 31, 31, 10, 10, 20), new byte[] { 248, 252, 10, 0, 0, 0 }, 0, Languages.English, 116, // Solid rock 255, "Rhyperior" ); record.Party[2] = factory.CreatePokemon(pokedex, 462, 0, // Magnezone 268, // Expert belt new ushort[] { 237, // Hidden power 430, // Flash cannon 85, // Thunderbolt 393 // Magnet rise }, 0x05060708, 17, // Quiet IvStatValues.PackIVs(31, 10, 31, 10, 31, 20), new byte[] { 252, 0, 6, 0, 252, 0 }, 0, Languages.English, 42, // Magnet pull 255, "Magnezone" ); record.Profile = factory.CreateProfile( "Cassie", Versions.Platinum, Languages.English, 0, 0, 0x05060708, gen4 ? factory.CreateTrendyPhrase(2, 3, 1146, 65535) // I want to go home with YOU... : factory.CreateTrendyPhrase(5, 0, 1611, 65535), // fixme 2, 85 // Idol ); if (gen4) { record.PhraseChallenged = factory.CreateTrendyPhrase(2, 3, 1146, 65535); // I want to go home with YOU... record.PhraseWon = factory.CreateTrendyPhrase(4, 10, 1245, 65535); // Let's GO AHEAD! record.PhraseLost = factory.CreateTrendyPhrase(4, 11, 1348, 65535); // Want to DATE? } else { record.PhraseChallenged = factory.CreateTrendyPhrase(5, 0, 1611, 65535); // Glad to meet you! I am MACHINE! record.PhraseWon = factory.CreateTrendyPhrase(5, 0, 1611, 65535); record.PhraseLost = factory.CreateTrendyPhrase(5, 0, 1611, 65535); } break; case 6: record.Party[0] = factory.CreatePokemon(pokedex, 65, 0, // Alakazam 275, // Focus sash new ushort[] { 269, // Taunt 94, // Psychic 411, // Focus blast 324 // Signal beam }, 15, 15, // Modest, shiny IvStatValues.PackIVs(31, 10, 20, 31, 31, 20), new byte[] { 6, 0, 0, 252, 252, 6 }, 0, Languages.English, 39, // Inner focus 255, "Alakazam" ); record.Party[1] = factory.CreatePokemon(pokedex, 445, 0, // Garchomp 270, // Life orb new ushort[] { 14, // Swords dance 89, // EQ 200, // Outrage 424 // Fire fang }, 0x06070809, 13, // Jolly IvStatValues.PackIVs(31, 31, 20, 31, 10, 20), new byte[] { 6, 252, 0, 252, 0, 0 }, 0, Languages.English, 8, // Sand veil 255, "Garchomp" ); record.Party[2] = factory.CreatePokemon(pokedex, 242, 0, // Blissey 234, // Leftovers new ushort[] { 135, // Softboiled 104, // Double team 92, // Toxic 69 // Seismic toss }, 0x06070809, 5, // Bold IvStatValues.PackIVs(31, 10, 31, 31, 20, 20), new byte[] { 252, 0, 252, 6, 0, 0 }, 0, Languages.English, 30, // Natural cure 255, "Blissey" ); record.Profile = factory.CreateProfile( "Evan", Versions.Platinum, Languages.English, 0, 0, 0x06070809, gen4 ? factory.CreateTrendyPhrase(0, 2, 566, 65535) // I'll battle with STRENGTH! : factory.CreateTrendyPhrase(5, 0, 1611, 65535), // fixme 0, 24 // Ace trainer M ); if (gen4) { record.PhraseChallenged = factory.CreateTrendyPhrase(0, 2, 566, 65535); // I'll battle with STRENGTH! record.PhraseWon = factory.CreateTrendyPhrase(1, 1, 1418, 65535); // I won! I won with SKILLFUL! record.PhraseLost = factory.CreateTrendyPhrase(2, 17, 1428, 65535); // The way I lost... It's like RARE... } else { record.PhraseChallenged = factory.CreateTrendyPhrase(5, 0, 1611, 65535); // Glad to meet you! I am MACHINE! record.PhraseWon = factory.CreateTrendyPhrase(5, 0, 1611, 65535); record.PhraseLost = factory.CreateTrendyPhrase(5, 0, 1611, 65535); } break; case 7: record.Party[0] = factory.CreatePokemon(pokedex, 9, 0, // Blastoise 234, // Leftovers new ushort[] { 57, // Surf 58, // Ice beam 252, // Fake out 156 // Rest }, 0x01020304, 15, // Modest IvStatValues.PackIVs(31, 10, 20, 31, 31, 20), new byte[] { 6, 0, 0, 252, 252, 0 }, 0, Languages.English, 67, // Torrent 255, "Leonardo" ); record.Party[1] = factory.CreatePokemon(pokedex, 389, 0, // Torterra 287, // Choice scarf new ushort[] { 452, // Wood hammer 89, // Earthquake 276, // Superpower 242 // Crunch }, 0x01020304, 13, // Jolly IvStatValues.PackIVs(31, 31, 20, 31, 10, 20), new byte[] { 6, 252, 0, 252, 0, 0 }, 0, Languages.English, 65, // Overgrow 255, "Donatello" ); record.Party[2] = factory.CreatePokemon(pokedex, 324, 0, // Torkoal 217, // Quick claw new ushort[] { 133, // Amnesia 156, // Rest 261, // Will-o-wisp 90 // Fissure }, 0x01020304, 23, // Careful IvStatValues.PackIVs(31, 10, 31, 20, 10, 31), new byte[] { 252, 0, 6, 0, 0, 252 }, 0, Languages.English, 73, // White smoke 255, "Raphael" ); record.Profile = factory.CreateProfile( "Splnter", Versions.Platinum, Languages.English, 0, 0, 0x01020304, gen4 ? factory.CreateTrendyPhrase(0, 16, 291, 7) // Ninjask! Squirtle power! : factory.CreateTrendyPhrase(1, 6, 7, 884), // Watch my Squirtle power take care of Metal Claw! 0, 14 // Black belt ); if (gen4) { record.PhraseChallenged = factory.CreateTrendyPhrase(0, 16, 291, 7); // Ninjask! Squirtle power! record.PhraseWon = factory.CreateTrendyPhrase(1, 11, 766, 65535); // I might have won with HELPING HAND! record.PhraseLost = factory.CreateTrendyPhrase(2, 8, 1406, 65535); // You're INCREDIBLE, aren't you? } else { record.PhraseChallenged = factory.CreateTrendyPhrase(1, 6, 7, 884); // Watch my Squirtle power take care of Metal Claw! record.PhraseWon = factory.CreateTrendyPhrase(5, 0, 1611, 65535); record.PhraseLost = factory.CreateTrendyPhrase(5, 0, 1611, 65535); } break; } return record; } } public abstract class FakeOpponentFactory { public abstract BattleTowerRecordBase CreateRecord(Pokedex.Pokedex pokedex); public abstract BattleTowerPokemonBase CreatePokemon(Pokedex.Pokedex pokedex, ushort species, byte form, ushort held_item, ushort[] moveset, uint ot, uint personality, uint ivs, byte[] evs, byte pp_ups, Languages language, byte ability, byte happiness, string nickname); public abstract BattleTowerProfileBase CreateProfile(string name, Versions version, Languages language, byte country, byte region, uint ot, TrendyPhraseBase phrase_leader, byte gender, byte unknown); public abstract TrendyPhraseBase CreateTrendyPhrase(ushort mood, ushort index, ushort word1, ushort word2); public abstract Generations Generation { get; } } public class FakeOpponentFactory4 : FakeOpponentFactory { public override BattleTowerRecordBase CreateRecord(Pokedex.Pokedex pokedex) { BattleTowerRecord4 record = new BattleTowerRecord4(pokedex); record.Party = new BattleTowerPokemon4[3]; record.Unknown3 = 6969; return record; } public override BattleTowerPokemonBase CreatePokemon(Pokedex.Pokedex pokedex, ushort species, byte form, ushort held_item, ushort[] moveset, uint ot, uint personality, uint ivs, byte[] evs, byte pp_ups, Languages language, byte ability, byte happiness, string nickname) { return new BattleTowerPokemon4(pokedex, species, form, held_item, moveset, ot, personality, ivs, evs, pp_ups, language, ability, happiness, new EncodedString4(nickname, 22) ); } public override BattleTowerProfileBase CreateProfile(string name, Versions version, Languages language, byte country, byte region, uint ot, TrendyPhraseBase phrase_leader, byte gender, byte unknown) { return new BattleTowerProfile4( new EncodedString4(name, 16), version, language, country, region, ot, (TrendyPhrase4)phrase_leader, gender, unknown ); } public override TrendyPhraseBase CreateTrendyPhrase(ushort mood, ushort index, ushort word1, ushort word2) { return new TrendyPhrase4(mood, index, word1, word2); } public override Generations Generation { get { return Generations.Generation4; } } } public class FakeOpponentFactory5 : FakeOpponentFactory { public override BattleTowerRecordBase CreateRecord(Pokedex.Pokedex pokedex) { BattleSubwayRecord5 record = new BattleSubwayRecord5(pokedex); record.Party = new BattleSubwayPokemon5[3]; record.Unknown3 = 6969; return record; } public override BattleTowerPokemonBase CreatePokemon(Pokedex.Pokedex pokedex, ushort species, byte form, ushort held_item, ushort[] moveset, uint ot, uint personality, uint ivs, byte[] evs, byte pp_ups, Languages language, byte ability, byte happiness, string nickname) { return new BattleSubwayPokemon5(pokedex, species, form, held_item, moveset, ot, personality, ivs, evs, pp_ups, language, ability, happiness, new EncodedString5(nickname, 22), 0 ); } public override BattleTowerProfileBase CreateProfile(string name, Versions version, Languages language, byte country, byte region, uint ot, TrendyPhraseBase phrase_leader, byte gender, byte unknown) { return new BattleSubwayProfile5( new EncodedString5(name, 16), version, language, country, region, ot, (TrendyPhrase5)phrase_leader, gender, unknown ); } public override TrendyPhraseBase CreateTrendyPhrase(ushort mood, ushort index, ushort word1, ushort word2) { return new TrendyPhrase5(mood, index, word1, word2); } public override Generations Generation { get { return Generations.Generation5; } } } } ================================================ FILE: gts/src/IpAddressHelper.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; namespace PkmnFoundations.GTS { public static class IpAddressHelper { public static string GetIpAddress(HttpRequest request) { var allowedProxies = ConfigurationManager.AppSettings["AllowedProxies"].Split(',').Select(s => s.Trim()); string hostAddress = RemovePort(request.UserHostAddress.Trim()); if (!allowedProxies.Contains(hostAddress)) return hostAddress; // return real IP if not a blessed proxy if (request.Headers["X-Forwarded-For"] == null) return hostAddress; var xForwardedFor = request.Headers["X-Forwarded-For"].Split(',').Select(s => RemovePort(s.Trim())); foreach (string s in xForwardedFor.Reverse()) { if (!allowedProxies.Contains(s)) return s; // return LAST IP in the proxy chain that's not trusted. (everything coming earlier could be spoofed) } // these conditions can only happen if the real user is at a blessed proxy IP address. (probably localhost) return xForwardedFor.FirstOrDefault() ?? hostAddress; } private static string RemovePort(string ip) { if (ip.Contains(':') && ip.Contains('.')) return ip.Substring(0, ip.IndexOf(':')); else return ip; } public static uint Ipv4ToBinary(string ip) { string[] split = ip.Split('.'); if (split.Length != 4) throw new FormatException("Format not valid for an IPV4 address."); return BitConverter.ToUInt32(split.Select(s => Convert.ToByte(s)).Reverse().ToArray(), 0); } } } ================================================ FILE: gts/syachi2ds.ashx ================================================ <%@ WebHandler Language="C#" CodeBehind="syachi2ds.ashx.cs" Class="PkmnFoundations.GTS.syachi2ds" %> ================================================ FILE: gts/syachi2ds.ashx.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.SessionState; using PkmnFoundations.Data; using PkmnFoundations.Structures; using PkmnFoundations.Support; using System.IO; using GamestatsBase; using PkmnFoundations.Wfc; namespace PkmnFoundations.GTS { /// /// Summary description for pokemondpds /// public class syachi2ds : GamestatsHandler { public syachi2ds() : base("HZEdGCzcGGLvguqUEKQN0001d93500002dd5000000082db842b2syachi2ds", GamestatsRequestVersions.Version3, GamestatsResponseVersions.Version2, false, true) { } public override void ProcessGamestatsRequest(byte[] request, MemoryStream response, string url, int pid, HttpContext context, GamestatsSession session) { { BanStatus ban = BanHelper.GetBanStatus(pid, IpAddressHelper.GetIpAddress(context.Request), Generations.Generation5); if (ban != null && ban.Level > BanLevels.Restricted) { ShowError(context, 403); return; } } Pokedex.Pokedex pokedex = AppStateHelper.Pokedex(context.Application); switch (url) { default: SessionManager.Remove(session); // unrecognized page url ShowError(context, 404); return; #region Common // Called during startup. Seems to contain trainer profile stats. case "/syachi2ds/web/common/setProfile.asp": SessionManager.Remove(session); if (request.Length != 100) { ShowError(context, 400); return; } #if !DEBUG try { #endif // this blob appears to share the same format with GenIV only with (obviously) a GenV string for the trainer name // and the email-related fields dummied out. // Specifically, email, notification status, and the two secrets appear to always be 0. byte[] profileBinary = new byte[100]; Array.Copy(request, 0, profileBinary, 0, 100); TrainerProfile5 profile = new TrainerProfile5(pid, profileBinary, IpAddressHelper.GetIpAddress(context.Request)); Database.Instance.GamestatsSetProfile5(profile); #if !DEBUG } catch { } #endif response.Write(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0, 8); break; #endregion #region GTS // Called during startup. Unknown purpose. case "/syachi2ds/web/worldexchange/info.asp": SessionManager.Remove(session); // todo: find out the meaning of this request. // is it simply done to check whether the GTS is online? response.Write(new byte[] { 0x01, 0x00 }, 0, 2); break; // Called during startup and when you check your pokemon's status. case "/syachi2ds/web/worldexchange/result.asp": { SessionManager.Remove(session); // todo: more fun stuff is contained in this blob on genV. // my guess is that it's trainer profile info like setProfile.asp // There's a long string of 0s which could be a trainer card signature raster GtsRecord5 record = Database.Instance.GtsDataForUser5(pokedex, pid); if (record == null) { // No pokemon in the system response.Write(new byte[] { 0x05, 0x00 }, 0, 2); } else if (record.IsExchanged > 0) { // traded pokemon arriving!!! response.Write(record.Save(), 0, 296); } else { // my existing pokemon is in the system, untraded response.Write(new byte[] { 0x04, 0x00 }, 0, 2); } } break; // Called after result.asp returns 4 when you check your pokemon's status case "/syachi2ds/web/worldexchange/get.asp": { SessionManager.Remove(session); // This can be called in 3 circumstances: // 1. After result.asp when it says your existing pokemon is in the system // 2. When you check the summary of your pokemon (Platinum onward) // 3. When you attempt to retract your offer, just before saving. // todo: the same big blob of stuff from result.asp is sent here too. GtsRecord5 record = Database.Instance.GtsDataForUser5(pokedex, pid); if (record == null) { // No pokemon in the system response.Write(new byte[] { 0x05, 0x00 }, 0, 2); return; } else { // just write the record whether traded or not... // todo: confirm that writing a traded record here will allow the trade to conclude response.Write(record.Save(), 0, 296); } } break; // Called after result.asp returns an inbound pokemon record to delete it case "/syachi2ds/web/worldexchange/delete.asp": { SessionManager.Remove(session); // todo: the same big blob of stuff from result.asp is sent here too. GtsRecord5 record = Database.Instance.GtsDataForUser5(pokedex, pid); if (record == null) { response.Write(new byte[] { 0x05, 0x00 }, 0, 2); } else if (record.IsExchanged > 0) { // Responses: // 0x03: BSOD // 0x05: 13263 // delete the arrived pokemon from the system // todo: add transactions // todo: log the successful trade? // (either here or when the trade is done) bool success = Database.Instance.GtsDeletePokemon5(pid); if (success) response.Write(new byte[] { 0x01, 0x00 }, 0, 2); else response.Write(new byte[] { 0x05, 0x00 }, 0, 2); } else { // own pokemon is there, fail. Use return.asp instead. response.Write(new byte[] { 0x05, 0x00 }, 0, 2); } } break; // called to delete your own pokemon after taking it back case "/syachi2ds/web/worldexchange/return.asp": { SessionManager.Remove(session); GtsRecord5 record = Database.Instance.GtsDataForUser5(pokedex, pid); if (record == null || // no pokemon in the system record.IsExchanged > 0 || // a traded pokemon is there, fail. Use delete.asp instead. !Database.Instance.GtsCheckLockStatus5(record.TradeId, pid)) // someone else is in the process of trading for this { response.Write(new byte[] { 0x02, 0x00 }, 0, 2); } else { // delete own pokemon // todo: add transactions bool success = Database.Instance.GtsDeletePokemon5(pid); if (success) { response.Write(new byte[] { 0x01, 0x00 }, 0, 2); // todo: invalidate cache //manager.RefreshStats(); } else { response.Write(new byte[] { 0x02, 0x00 }, 0, 2); } } } break; // Called when you deposit a pokemon into the system. case "/syachi2ds/web/worldexchange/post.asp": { if (request.Length != 432) { SessionManager.Remove(session); ShowError(context, 400); return; } // todo: add transaction if (Database.Instance.GtsDataForUser5(pokedex, pid) != null) { // there's already a pokemon inside // Force the player out so they'll recheck its status. SessionManager.Remove(session); response.Write(new byte[] { 0x0e, 0x00 }, 0, 2); break; } // keep the record in memory while we wait for post_finish.asp request byte[] recordBinary = new byte[296]; Array.Copy(request, 0, recordBinary, 0, 296); GtsRecord5 record = new GtsRecord5(pokedex, recordBinary); record.IsExchanged = 0; // todo: figure out what bytes 296-431 do: // appears to be 4 bytes of 00, 128 bytes of stuff, 4 bytes of 80 00 00 00 // probably a pkvldtprod signature if (!record.Validate()) { // hack check failed SessionManager.Remove(session); // responses: // 0x00: bsod // 0x01: successful deposit // 0x02: Communication error 13265 // 0x03: Communication error 13264 // 0x04-0x06: bsod // 0x07: The GTS is very crowded now. Please try again later (13261). (and it boots you) // 0x08: That Pokémon may not be offered for trade (13268)! // 0x09: That Pokémon may not be offered for trade (13269)! // 0x0a: That Pokémon may not be offered for trade (13270)! // 0x0b: That Pokémon may not be offered for trade (13271)! // 0x0c: That Pokémon may not be offered for trade (13266)! // 0x0d: That Pokémon may not be offered for trade (13267)! // 0x0e: You were disconnected from the GTS. Error code: 13262 (and it boots you) // 0x0f: bsod response.Write(new byte[] { 0x0c, 0x00 }, 0, 2); break; } // the following two fields are blank in the uploaded record. // The server must provide them instead. record.TimeDeposited = DateTime.UtcNow; record.TimeExchanged = null; record.PID = pid; session.Tag = record; // todo: delete any other post.asp sessions registered under this PID response.Write(new byte[] { 0x01, 0x00 }, 0, 2); } break; case "/syachi2ds/web/worldexchange/post_finish.asp": { SessionManager.Remove(session); if (request.Length != 8) { ShowError(context, 400); return; } // find a matching session which contains our record GamestatsSession prevSession = SessionManager.FindSession(pid, "/syachi2ds/web/worldexchange/post.asp"); if (prevSession == null) { response.Write(new byte[] { 0x02, 0x00 }, 0, 2); return; } SessionManager.Remove(prevSession); if (prevSession.Tag == null) { response.Write(new byte[] { 0x02, 0x00 }, 0, 2); return; } AssertHelper.Assert(prevSession.Tag is GtsRecord5); GtsRecord5 record = (GtsRecord5)prevSession.Tag; if (Database.Instance.GtsDepositPokemon5(record)) { // todo: invalidate cache //manager.RefreshStats(); response.Write(new byte[] { 0x01, 0x00 }, 0, 2); } else response.Write(new byte[] { 0x02, 0x00 }, 0, 2); } break; // the search request has a funny bit string request of search terms // and just returns a chunk of records end to end. case "/syachi2ds/web/worldexchange/search.asp": { SessionManager.Remove(session); if (request.Length < 7 || request.Length > 8) { ShowError(context, 400); return; } int resultsCount = (int)request[6]; ushort species = BitConverter.ToUInt16(request, 0); if (species < 1) { ShowError(context, 400); return; } response.Write(new byte[] { 0x01, 0x00 }, 0, 2); if (resultsCount < 1) break; // optimize away requests for no rows Genders gender = (Genders)request[2]; byte minLevel = request[3]; byte maxLevel = request[4]; // byte 5 unknown byte country = 0; if (request.Length > 7) country = request[7]; if (resultsCount > 7) resultsCount = 7; // stop DDOS GtsRecord5[] records = Database.Instance.GtsSearch5(pokedex, pid, species, gender, minLevel, maxLevel, country, resultsCount); foreach (GtsRecord5 record in records) { response.Write(record.Save(), 0, 296); } Database.Instance.GtsSetLastSearch5(pid); } break; // the exchange request uploads a record of the exchangee pokemon // plus the desired PID to trade for at the very end. case "/syachi2ds/web/worldexchange/exchange.asp": { if (request.Length != 432) { SessionManager.Remove(session); ShowError(context, 400); return; } byte[] uploadData = new byte[296]; Array.Copy(request, 0, uploadData, 0, 296); GtsRecord5 upload = new GtsRecord5(pokedex, uploadData); upload.IsExchanged = 0; int targetPid = BitConverter.ToInt32(request, 296); GtsRecord5 result = Database.Instance.GtsDataForUser5(pokedex, targetPid); DateTime ? searchTime = Database.Instance.GtsGetLastSearch5(pid); if (result == null || searchTime == null || result.TimeDeposited > (DateTime)searchTime || // If this condition is met, it means the pokemon in the system is DIFFERENT from the one the user is trying to trade for, ie. it was deposited AFTER the user did their search. The one the user wants was either taken back or traded. result.IsExchanged != 0) { // Pokémon is traded (or was never here to begin with) SessionManager.Remove(session); response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } // enforce request requirements server side if (!upload.Validate() || !upload.CanTrade(result)) { // todo: find the correct codes for these SessionManager.Remove(session); // responses: // 0x00-0x01: bsod // 0x02: Unfortunately, it was traded to another Trainer. // 0x03-0x07: bsod // 0x08: That Pokémon may not be offered for trade (13268)! // 0x09: That Pokémon may not be offered for trade (13269)! // 0x0a: That Pokémon may not be offered for trade (13270)! // 0x0b: That Pokémon may not be offered for trade (13271)! // 0x0c: That Pokémon may not be offered for trade (13266)! // 0x0d: That Pokémon may not be offered for trade (13267)! // 0x0e: You were disconnected from the GTS. Error code: 13262 // 0x0f: bsod response.Write(new byte[] { 0x0c, 0x00 }, 0, 2); return; } if (!Database.Instance.GtsLockPokemon5(result.TradeId, pid)) { // failed to acquire lock, implying someone else beat us here. Say already traded. SessionManager.Remove(session); response.Write(new byte[] { 0x02, 0x00 }, 0, 2); break; } object[] tag = new GtsRecord5[2]; tag[0] = upload; tag[1] = result; session.Tag = tag; GtsRecord5 tradedResult = result.Clone(); tradedResult.FlagTraded(upload); // only real purpose is to generate a proper response // todo: we need a mechanism to "reserve" a pokemon being traded at this // point in the process, but be able to relinquish it if exchange_finish // never happens. // Currently, if two people try to take the same pokemon, it will appear // to work for both but then fail for the second after they've saved // their game. This causes a hard crash and a "save file is corrupt, // "previous will be loaded" error when restarting. // the reservation can be done in application state and has no reason // to touch the database. (exchange_finish won't work anyway if application // state is lost.) response.Write(result.Save(), 0, 296); } break; case "/syachi2ds/web/worldexchange/exchange_finish.asp": { SessionManager.Remove(session); if (request.Length != 8) { ShowError(context, 400); return; } // find a matching session which contains our record GamestatsSession prevSession = SessionManager.FindSession(pid, "/syachi2ds/web/worldexchange/exchange.asp"); if (prevSession == null) { response.Write(new byte[] { 0x02, 0x00 }, 0, 2); return; } SessionManager.Remove(prevSession); if (prevSession.Tag == null) { response.Write(new byte[] { 0x02, 0x00 }, 0, 2); return; } AssertHelper.Assert(prevSession.Tag is GtsRecord5[]); GtsRecord5[] tag = (GtsRecord5[])prevSession.Tag; AssertHelper.Assert(tag.Length == 2); GtsRecord5 upload = tag[0]; GtsRecord5 result = tag[1]; if (Database.Instance.GtsTradePokemon5(upload, result, pid)) response.Write(new byte[] { 0x01, 0x00 }, 0, 2); else response.Write(new byte[] { 0x02, 0x00 }, 0, 2); } break; #endregion #region Battle Subway case "/syachi2ds/web/battletower/info.asp": SessionManager.Remove(session); // Probably an availability/status code. // Response codes: // 0x00: BSOD // 0x01: Continues normally // 0x02: BSOD // 0x03: Continues normally??? // 0x04: Continues normally // 0x05: Unable to connect to the Wi-Fi Train. Returning to the reception counter. (13262) // 0x06: BSOD response.Write(new byte[] { 0x01, 0x00 }, 0, 2); break; case "/syachi2ds/web/battletower/roomnum.asp": SessionManager.Remove(session); //byte rank = data[0x00]; response.Write(new byte[] { 0x32, 0x00 }, 0, 2); break; case "/syachi2ds/web/battletower/download.asp": { SessionManager.Remove(session); if (request.Length != 2) { ShowError(context, 400); return; } byte rank = request[0]; byte roomNum = request[1]; if (rank > 9 || roomNum > 49) { ShowError(context, 400); return; } FakeOpponentFactory5 fact = new FakeOpponentFactory5(); BattleSubwayRecord5[] opponents = Database.Instance.BattleSubwayGetOpponents5(pokedex, pid, rank, roomNum); BattleSubwayProfile5[] leaders = Database.Instance.BattleSubwayGetLeaders5(pokedex, rank, roomNum); BattleTowerRecordBase[] fakeOpponents = FakeOpponentGenerator.GenerateFakeOpponents(fact, 7 - opponents.Length); foreach (BattleSubwayRecord5 record in fakeOpponents) { response.Write(record.Save(), 0, 240); } foreach (BattleSubwayRecord5 record in opponents) { response.Write(record.Save(), 0, 240); } foreach (BattleSubwayProfile5 leader in leaders) { response.Write(leader.Save(), 0, 34); } if (leaders.Length < 30) { byte[] fakeLeader = new BattleSubwayProfile5 ( new EncodedString5("-----", 16), Versions.White, Languages.English, 0, 0, 0x00000000, new TrendyPhrase5(0, 20, 0, 0), 0, 0 ).Save(); for (int x = leaders.Length; x < 30; x++) { response.Write(fakeLeader, 0, 34); } } } break; case "/syachi2ds/web/battletower/upload.asp": { SessionManager.Remove(session); if (request.Length != 388) { ShowError(context, 400); return; } BattleSubwayRecord5 record = new BattleSubwayRecord5(pokedex, request, 0); record.Rank = request[0xf0]; record.RoomNum = request[0xf1]; record.BattlesWon = request[0xf2]; record.Unknown4 = new byte[5]; Array.Copy(request, 0xf3, record.Unknown4, 0, 5); record.Unknown5 = BitConverter.ToUInt64(request, 0xf8); record.PID = pid; foreach (var p in record.Party) { // todo: add battle tower specific checks: // item clause, species clause, banned species, banned items // https://bulbapedia.bulbagarden.net/wiki/Battle_Subway#Restrictions if (!p.Validate().IsValid) { // Tell the client it was successful so they don't keep retrying. response.Write(new byte[] { 0x01, 0x00 }, 0, 2); return; } } // todo: Do we want to store their record anyway if they lost the first round? if (record.BattlesWon > 0) Database.Instance.BattleSubwayUpdateRecord5(record); if (record.BattlesWon == 7) Database.Instance.BattleSubwayAddLeader5(record); // List of responses: // 0x00: BSOD // 0x01: Uploads successfully // 0x02: That number cannot be specified for the Wi-Fi Train. (13263) // 0x03: BSOD // 0x04: The Wi-Fi Train is very crowded. Please try again later. (13261) // 0x05: Unable to connect to the Wi-Fi Train. Returning to the reception counter. (13262) // 0x06: BSOD // 0x07: BSOD // 0x08: BSOD response.Write(new byte[] { 0x01, 0x00 }, 0, 2); } break; #endregion } } } } ================================================ FILE: library/Data/DataMysql.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using MySql.Data.MySqlClient; using PkmnFoundations.Structures; using PkmnFoundations.Support; using System.Security.Cryptography; using PkmnFoundations.Pokedex; using PkmnFoundations.Wfc; namespace PkmnFoundations.Data { // todo: This class is getting quite large. We should move some things with // limited usefulness (eg. database creation) into separate classes. public class DataMysql : Database { #region Initialization public DataMysql(string connString) { ConnectionString = connString; } public string ConnectionString { get; set; } private MySqlConnection CreateConnection() { return new MySqlConnection(ConnectionString); } #endregion #region Utility public static string SqlSanitize(string s) { return SqlSanitize(s, ""); } public static string SqlSanitize(string s, string newChar) { string result = s.Replace("\'", newChar).Replace("[", newChar).Replace("]", newChar).Replace("`", newChar); int x = result.IndexOf("--"); if (x != -1) result = result.Substring(0, x); return result; } #endregion #region Transaction helpers public delegate T WithMysqlTransactionDelegate(MySqlTransaction tran, out bool success); /// /// Provides a MySqlConnection and transaction to the command and runs /// it. The transaction always commits unless an exception is thrown. /// private T WithTransaction(Func command) { T result; using (MySqlConnection db = CreateConnection()) { db.Open(); using (MySqlTransaction tran = db.BeginTransaction()) { result = command(tran); tran.Commit(); } db.Close(); } return result; } /// /// Provides a MySqlConnection and transaction to the command and runs /// it. The transaction always commits unless an exception is thrown. /// private void WithTransaction(Action command) { using (MySqlConnection db = CreateConnection()) { db.Open(); using (MySqlTransaction tran = db.BeginTransaction()) { command(tran); tran.Commit(); } db.Close(); } } /// /// Provides a MySqlConnection and transaction to the command and runs /// it. The transaction is committed if success is set to true. /// Otherwise it's rolled back. The transaction also rolls back if your /// function throws. /// private T WithTransaction(WithMysqlTransactionDelegate command) { T result; using (MySqlConnection db = CreateConnection()) { db.Open(); using (MySqlTransaction tran = db.BeginTransaction()) { bool success; result = command(tran, out success); if (success) tran.Commit(); else tran.Rollback(); } db.Close(); } return result; } /// /// Provides a MySqlConnection and transaction to the command and runs /// it. The transaction is committed if the function returns true. /// Otherwise it's rolled back. The transaction also rolls back if your /// function throws. /// private bool WithTransactionSuccessful(Func command) { bool success; using (MySqlConnection db = CreateConnection()) { db.Open(); using (MySqlTransaction tran = db.BeginTransaction()) { success = command(tran); if (success) tran.Commit(); else tran.Rollback(); } db.Close(); } return success; } #endregion #region GTS 4 public GtsRecord4 GtsDataForUser4(MySqlTransaction tran, Pokedex.Pokedex pokedex, int pid) { using (MySqlDataReader reader = (MySqlDataReader)tran.ExecuteReader("SELECT id, Data, Species, Gender, Level, " + "RequestedSpecies, RequestedGender, RequestedMinLevel, RequestedMaxLevel, " + "Unknown1, TrainerGender, Unknown2, TimeDeposited, TimeExchanged, pid, " + "TrainerName, TrainerOT, TrainerCountry, TrainerRegion, TrainerClass, " + "IsExchanged, TrainerVersion, TrainerLanguage FROM GtsPokemon4 WHERE pid = @pid", new MySqlParameter("@pid", pid))) { if (!reader.Read()) { reader.Close(); return null; } GtsRecord4 result = Record4FromReader(pokedex, reader); #if DEBUG AssertHelper.Equals(result.PID, pid); #endif reader.Close(); return result; } } public override GtsRecord4 GtsDataForUser4(Pokedex.Pokedex pokedex, int pid) { return WithTransaction(tran => GtsDataForUser4(tran, pokedex, pid)); } public GtsRecord4 GtsGetRecord4(MySqlTransaction tran, Pokedex.Pokedex pokedex, long tradeId, bool isExchanged, bool allowHistory) { using (MySqlDataReader reader = (MySqlDataReader)tran.ExecuteReader("SELECT id, Data, Species, Gender, Level, " + "RequestedSpecies, RequestedGender, RequestedMinLevel, RequestedMaxLevel, " + "Unknown1, TrainerGender, Unknown2, TimeDeposited, TimeExchanged, pid, " + "TrainerName, TrainerOT, TrainerCountry, TrainerRegion, TrainerClass, " + "IsExchanged, TrainerVersion, TrainerLanguage FROM GtsPokemon4 " + "WHERE id = @id AND IsExchanged = @is_exchanged", new MySqlParameter("@id", tradeId), new MySqlParameter("@is_exchanged", isExchanged ? 1 : 0))) { if (reader.Read()) { GtsRecord4 result = Record4FromReader(pokedex, reader); reader.Close(); return result; } reader.Close(); } if (allowHistory) { using (MySqlDataReader reader = (MySqlDataReader)tran.ExecuteReader("SELECT id, Data, Species, Gender, Level, " + "RequestedSpecies, RequestedGender, RequestedMinLevel, RequestedMaxLevel, " + "Unknown1, TrainerGender, Unknown2, TimeDeposited, TimeExchanged, pid, " + "TrainerName, TrainerOT, TrainerCountry, TrainerRegion, TrainerClass, " + "IsExchanged, TrainerVersion, TrainerLanguage FROM GtsHistory4 " + "WHERE trade_id = @id AND IsExchanged = @is_exchanged", new MySqlParameter("@id", tradeId), new MySqlParameter("@is_exchanged", isExchanged ? 1 : 0))) { if (reader.Read()) { GtsRecord4 result = Record4FromReader(pokedex, reader); reader.Close(); return result; } } } return null; } public override GtsRecord4 GtsGetRecord4(Pokedex.Pokedex pokedex, long tradeId, bool isExchanged, bool allowHistory) { return WithTransaction(tran => GtsGetRecord4(tran, pokedex, tradeId, isExchanged, allowHistory)); } public bool GtsDepositPokemon4(MySqlTransaction tran, GtsRecord4 record) { if (record.Data.Count != 236) throw new FormatException("pkm data must be 236 bytes."); if (record.TrainerNameEncoded.RawData.Length != 16) throw new FormatException("Trainer name must be 16 bytes."); // note that IsTraded being true in the record is not an error condition // since it might have use later on. You should check for this in the upload handler. long count = (long)tran.ExecuteScalar("SELECT Count(*) FROM GtsPokemon4 WHERE pid = @pid", new MySqlParameter("@pid", record.PID)); if (count > 0) { // This player already has a pokemon in the system. // we can possibly allow multiples under some future conditions return false; } tran.ExecuteNonQuery("INSERT INTO GtsPokemon4 " + "(Data, Species, Gender, Level, RequestedSpecies, RequestedGender, " + "RequestedMinLevel, RequestedMaxLevel, Unknown1, TrainerGender, " + "Unknown2, TimeDeposited, TimeExchanged, pid, TrainerName, TrainerOT, " + "TrainerCountry, TrainerRegion, TrainerClass, IsExchanged, TrainerVersion, " + "TrainerLanguage) " + "VALUES (@Data, @Species, @Gender, @Level, @RequestedSpecies, " + "@RequestedGender, @RequestedMinLevel, @RequestedMaxLevel, @Unknown1, " + "@TrainerGender, @Unknown2, @TimeDeposited, @TimeExchanged, @pid, " + "@TrainerName, @TrainerOT, @TrainerCountry, @TrainerRegion, @TrainerClass, " + "@IsExchanged, @TrainerVersion, @TrainerLanguage)", ParamsFromRecord4(record)); return true; } public override bool GtsDepositPokemon4(GtsRecord4 record) { if (record.Data.Count != 236) throw new FormatException("pkm data must be 236 bytes."); if (record.TrainerNameEncoded.RawData.Length != 16) throw new FormatException("Trainer name must be 16 bytes."); return WithTransactionSuccessful(tran => GtsDepositPokemon4(tran, record)); } public ulong ? GtsGetDepositId4(MySqlTransaction tran, int pid) { object o = tran.ExecuteScalar("SELECT id FROM GtsPokemon4 WHERE pid = @pid " + "ORDER BY IsExchanged DESC, TimeExchanged, TimeDeposited LIMIT 1", new MySqlParameter("@pid", pid)); if (o == null || o == DBNull.Value) return null; return Convert.ToUInt64(o); } public bool GtsDeletePokemon4(MySqlTransaction tran, int pid) { ulong ? pkmnId = GtsGetDepositId4(tran, pid); if (pkmnId == null) return false; #if !DEBUG try { #endif // this has to run before deletion or isExchanged information is lost. // fixme: the trade_id is wrong here because logs use the // deposited trade ID, not the exchanged one GtsSetWithdrawTime4(tran, (ulong)pkmnId); #if !DEBUG } catch { } #endif tran.ExecuteNonQuery("DELETE FROM GtsPokemon4 WHERE id = @id", new MySqlParameter("@id", pkmnId)); return true; } public override bool GtsDeletePokemon4(int pid) { return WithTransactionSuccessful(tran => GtsDeletePokemon4(tran, pid)); } private void GtsSetWithdrawTime4(MySqlTransaction tran, ulong trade_id) { // only set the withdraw time if IsExchanged is true. // If false, no trade has happened; we are withdrawing our old pokemon. if (Convert.ToByte( tran.ExecuteScalar("SELECT IsExchanged FROM GtsPokemon4 WHERE id = @id", new MySqlParameter("@id", trade_id))) != 0) { tran.ExecuteNonQuery("UPDATE GtsHistory4 " + "SET TimeWithdrawn = @now " + "WHERE trade_id = @trade_id", new MySqlParameter("@now", DateTime.UtcNow), new MySqlParameter("@trade_id", trade_id)); } } public override bool GtsTradePokemon4(int pidSrc, int pidDest) { throw new NotImplementedException(); } public bool GtsTradePokemon4(MySqlTransaction tran, GtsRecord4 upload, GtsRecord4 result, int partner_pid) { GtsRecord4 traded = upload.Clone(); traded.FlagTraded(result); ulong? trade_id = GtsGetDepositId4(tran, result.PID); GtsRecord4 resultOrig = GtsDataForUser4(tran, result.Pokedex, result.PID); if (trade_id == null || resultOrig == null || resultOrig != result || !GtsCheckLockStatus4(tran, (ulong)trade_id, partner_pid)) // looks like the pokemon was ninja'd between the Exchange and Exchange_finish return false; if (!GtsDeletePokemon4(tran, result.PID)) return false; if (!GtsDepositPokemon4(tran, traded)) return false; #if !DEBUG try { #endif GtsLogTrade4(tran, result, null, partner_pid, trade_id); GtsLogTrade4(tran, traded, null, partner_pid, trade_id); #if !DEBUG } catch { } #endif return true; } public override bool GtsTradePokemon4(GtsRecord4 upload, GtsRecord4 result, int partner_pid) { return WithTransactionSuccessful(tran => GtsTradePokemon4(tran, upload, result, partner_pid)); } public override bool GtsLockPokemon4(ulong tradeId, int partner_pid) { return WithTransaction(tran => GtsLockPokemon4(tran, tradeId, partner_pid)); } public bool GtsLockPokemon4(MySqlTransaction tran, ulong tradeId, int partner_pid) { DateTime now = DateTime.UtcNow; int rows = tran.ExecuteNonQuery("UPDATE GtsPokemon4 SET LockedUntil = @locked_until, LockedBy = @locked_by " + "WHERE id = @trade_id AND (LockedUntil < @now OR LockedUntil IS NULL OR LockedBy = @locked_by)", new MySqlParameter("@trade_id", tradeId), new MySqlParameter("@locked_until", now.AddSeconds(GTS_LOCK_DURATION)), new MySqlParameter("@locked_by", partner_pid), new MySqlParameter("@now", now)); return rows != 0; } public override bool GtsCheckLockStatus4(ulong tradeId, int partner_pid) { return WithTransaction(tran => GtsCheckLockStatus4(tran, tradeId, partner_pid)); } public bool GtsCheckLockStatus4(MySqlTransaction tran, ulong tradeId, int partner_pid) { int rows = Convert.ToInt32(tran.ExecuteScalar("SELECT count(*) FROM GtsPokemon4 " + "WHERE id = @trade_id AND (LockedUntil < @now OR LockedUntil IS NULL OR LockedBy = @locked_by)", new MySqlParameter("@trade_id", tradeId), new MySqlParameter("@locked_by", partner_pid), new MySqlParameter("@now", DateTime.UtcNow) )); return rows != 0; // No rows means a lock is in effect or nothing was found } public GtsRecord4[] GtsSearch4(MySqlTransaction tran, Pokedex.Pokedex pokedex, int pid, ushort species, Genders gender, byte minLevel, byte maxLevel, byte country, int count) { List _params = new List(); string where = "WHERE pid != @pid AND IsExchanged = 0 AND (LockedUntil < @now OR LockedUntil IS NULL)"; _params.Add(new MySqlParameter("@pid", pid)); _params.Add(new MySqlParameter("@now", DateTime.UtcNow)); if (species > 0) { where += " AND Species = @species"; _params.Add(new MySqlParameter("@species", species)); } if (gender != Genders.Either) { where += " AND Gender IN (@gender, 3)"; _params.Add(new MySqlParameter("@gender", (byte)gender)); } if (minLevel > 0 && maxLevel > 0) { where += " AND Level BETWEEN @min_level AND @max_level"; _params.Add(new MySqlParameter("@min_level", minLevel)); _params.Add(new MySqlParameter("@max_level", maxLevel)); } else if (minLevel > 0) { where += " AND Level >= @min_level"; _params.Add(new MySqlParameter("@min_level", minLevel)); } else if (maxLevel > 0) { where += " AND Level <= @max_level"; _params.Add(new MySqlParameter("@max_level", maxLevel)); } if (country > 0) { where += " AND TrainerCountry = @country"; _params.Add(new MySqlParameter("@country", country)); } string limit = ""; if (count > 0) { _params.Add(new MySqlParameter("@count", count)); limit = " LIMIT @count"; } // todo: sort me in creative ways using (MySqlDataReader reader = (MySqlDataReader)tran.ExecuteReader("SELECT Data, Species, Gender, Level, " + "RequestedSpecies, RequestedGender, RequestedMinLevel, RequestedMaxLevel, " + "Unknown1, TrainerGender, Unknown2, TimeDeposited, TimeExchanged, pid, " + "TrainerName, TrainerOT, TrainerCountry, TrainerRegion, TrainerClass, " + "IsExchanged, TrainerVersion, TrainerLanguage, id FROM GtsPokemon4 " + where + " ORDER BY TimeDeposited DESC" + limit, _params.ToArray())) { List records; if (count > 0) records = new List(count); else records = new List(); while (reader.Read()) { var record = Record4FromReader(pokedex, reader); record.TradeId = DatabaseExtender.Cast(reader["id"]); records.Add(record); } reader.Close(); return records.ToArray(); } } public override GtsRecord4[] GtsSearch4(Pokedex.Pokedex pokedex, int pid, ushort species, Genders gender, byte minLevel, byte maxLevel, byte country, int count) { return WithTransaction(tran => GtsSearch4(tran, pokedex, pid, species, gender, minLevel, maxLevel, country, count)); } private static GtsRecord4 Record4FromReader(Pokedex.Pokedex pokedex, MySqlDataReader reader) { GtsRecord4 result = new GtsRecord4(pokedex); result.TradeId = DatabaseExtender.Cast(reader["id"]); result.Data = DatabaseExtender.Cast(reader["Data"]); result.Species = DatabaseExtender.Cast(reader["Species"]); result.Gender = (Genders)DatabaseExtender.Cast(reader["Gender"]); result.Level = DatabaseExtender.Cast(reader["Level"]); result.RequestedSpecies = DatabaseExtender.Cast(reader["RequestedSpecies"]); result.RequestedGender = (Genders)DatabaseExtender.Cast(reader["RequestedGender"]); result.RequestedMinLevel = DatabaseExtender.Cast(reader["RequestedMinLevel"]); result.RequestedMaxLevel = DatabaseExtender.Cast(reader["RequestedMaxLevel"]); result.Unknown1 = DatabaseExtender.Cast(reader["Unknown1"]); result.TrainerGender = (TrainerGenders)DatabaseExtender.Cast(reader["TrainerGender"]); result.Unknown2 = DatabaseExtender.Cast(reader["Unknown2"]); result.TimeDeposited = DatabaseExtender.Cast(reader["TimeDeposited"]); result.TimeExchanged = DatabaseExtender.Cast(reader["TimeExchanged"]); result.PID = DatabaseExtender.Cast(reader["pid"]); result.TrainerNameEncoded = new EncodedString4(DatabaseExtender.Cast(reader["TrainerName"])); result.TrainerOT = DatabaseExtender.Cast(reader["TrainerOT"]); result.TrainerCountry = DatabaseExtender.Cast(reader["TrainerCountry"]); result.TrainerRegion = DatabaseExtender.Cast(reader["TrainerRegion"]); result.TrainerClass = DatabaseExtender.Cast(reader["TrainerClass"]); result.IsExchanged = DatabaseExtender.Cast(reader["IsExchanged"]); result.TrainerVersion = (Versions)DatabaseExtender.Cast(reader["TrainerVersion"]); result.TrainerLanguage = (Languages)DatabaseExtender.Cast(reader["TrainerLanguage"]); return result; } private static MySqlParameter[] ParamsFromRecord4(GtsRecord4 record) { MySqlParameter[] result = new MySqlParameter[22]; result[0] = new MySqlParameter("@Data", record.Data.ToArray()); result[1] = new MySqlParameter("@Species", record.Species); result[2] = new MySqlParameter("@Gender", (byte)record.Gender); result[3] = new MySqlParameter("@Level", record.Level); result[4] = new MySqlParameter("@RequestedSpecies", record.RequestedSpecies); result[5] = new MySqlParameter("@RequestedGender", (byte)record.RequestedGender); result[6] = new MySqlParameter("@RequestedMinLevel", record.RequestedMinLevel); result[7] = new MySqlParameter("@RequestedMaxLevel", record.RequestedMaxLevel); result[8] = new MySqlParameter("@Unknown1", record.Unknown1); result[9] = new MySqlParameter("@TrainerGender", (byte)record.TrainerGender); result[10] = new MySqlParameter("@Unknown2", record.Unknown2); result[11] = new MySqlParameter("@TimeDeposited", record.TimeDeposited); result[12] = new MySqlParameter("@TimeExchanged", record.TimeExchanged); result[13] = new MySqlParameter("@pid", record.PID); result[14] = new MySqlParameter("@TrainerName", record.TrainerNameEncoded.RawData); result[15] = new MySqlParameter("@TrainerOT", record.TrainerOT); result[16] = new MySqlParameter("@TrainerCountry", record.TrainerCountry); result[17] = new MySqlParameter("@TrainerRegion", record.TrainerRegion); result[18] = new MySqlParameter("@TrainerClass", record.TrainerClass); result[19] = new MySqlParameter("@IsExchanged", record.IsExchanged); result[20] = new MySqlParameter("@TrainerVersion", record.TrainerVersion); result[21] = new MySqlParameter("@TrainerLanguage", record.TrainerLanguage); return result; } public int GtsAvailablePokemon4(MySqlTransaction tran) { return Convert.ToInt32(tran.ExecuteScalar("SELECT Count(*) FROM GtsPokemon4 WHERE IsExchanged = 0")); } public override int GtsAvailablePokemon4() { return WithTransaction(tran => GtsAvailablePokemon4(tran)); } public void GtsLogTrade4(MySqlTransaction tran, GtsRecord4 record, DateTime? timeWithdrawn, int ? partner_pid, ulong ? trade_id) { if (record.Data.Count != 236) throw new FormatException("pkm data must be 236 bytes."); if (record.TrainerNameEncoded.RawData.Length != 16) throw new FormatException("Trainer name must be 16 bytes."); // note that IsTraded being true in the record is not an error condition // since it might have use later on. You should check for this in the upload handler. if (trade_id == null) trade_id = GtsGetDepositId4(tran, record.PID); // when calling delete.asp, the partner pid can't be told from the request alone, // so obtain it from the database instead. if (record.IsExchanged != 0 && trade_id != null && partner_pid == null) { partner_pid = (int?)tran.ExecuteScalar("SELECT partner_pid FROM GtsHistory4 " + "WHERE trade_id = @trade_id AND IsExchanged = 0", new MySqlParameter("@trade_id", trade_id)); } MySqlParameter[] _params = ParamsFromRecord4(record); MySqlParameter[] _params2 = new MySqlParameter[25]; Array.Copy(_params, _params2, 22); _params2[22] = new MySqlParameter("@TimeWithdrawn", timeWithdrawn); _params2[23] = new MySqlParameter("@trade_id", trade_id); _params2[24] = new MySqlParameter("@partner_pid", partner_pid); tran.ExecuteNonQuery("INSERT INTO GtsHistory4 " + "(Data, Species, Gender, Level, RequestedSpecies, RequestedGender, " + "RequestedMinLevel, RequestedMaxLevel, Unknown1, TrainerGender, " + "Unknown2, TimeDeposited, TimeExchanged, pid, TrainerName, TrainerOT, " + "TrainerCountry, TrainerRegion, TrainerClass, IsExchanged, TrainerVersion, " + "TrainerLanguage, TimeWithdrawn, trade_id, partner_pid) " + "VALUES (@Data, @Species, @Gender, @Level, @RequestedSpecies, " + "@RequestedGender, @RequestedMinLevel, @RequestedMaxLevel, @Unknown1, " + "@TrainerGender, @Unknown2, @TimeDeposited, @TimeExchanged, @pid, " + "@TrainerName, @TrainerOT, @TrainerCountry, @TrainerRegion, @TrainerClass, " + "@IsExchanged, @TrainerVersion, @TrainerLanguage, @TimeWithdrawn, " + "@trade_id, @partner_pid)", _params2); } public void GtsLogTrade4(GtsRecord4 record, DateTime? timeWithdrawn, int? partner_pid, ulong ? trade_id) { if (record.Data.Count != 236) throw new FormatException("pkm data must be 236 bytes."); if (record.TrainerNameEncoded.RawData.Length != 16) throw new FormatException("Trainer name must be 16 bytes."); WithTransaction(tran => GtsLogTrade4(tran, record, timeWithdrawn, partner_pid, trade_id)); } public void GtsSetLastSearch4(MySqlTransaction tran, int pid) { tran.ExecuteNonQuery("UPDATE GtsProfiles4 SET TimeLastSearch = " + "@now WHERE pid = @pid", new MySqlParameter("@now", DateTime.UtcNow), new MySqlParameter("@pid", pid)); } public override void GtsSetLastSearch4(int pid) { WithTransaction(tran => GtsSetLastSearch4(tran, pid)); } public DateTime ? GtsGetLastSearch4(MySqlTransaction tran, int pid) { object result = tran.ExecuteScalar("SELECT TimeLastSearch " + "FROM GtsProfiles4 WHERE pid = @pid", new MySqlParameter("@pid", pid)); if (result == null || result is DBNull) return null; return (DateTime)result; } public override DateTime ? GtsGetLastSearch4(int pid) { return WithTransaction(tran => GtsGetLastSearch4(tran, pid)); } #endregion #region Battle Tower 4 private ulong BattleTowerUpdateRecord4(MySqlTransaction tran, BattleTowerRecord4 record) { if (record.BattlesWon > 7) throw new ArgumentException("Battles won can not be greater than 7."); // Does this player already have a record in this room? // Also get primary key if it does. (We need it for updating party) // // The official server doesn't seem to ever replace existing // records. This worked fine for them, but we don't have nearly // as many active players, so doing this will cause too many // duplicates. Instead, we require the trainers in a given room to // be unique by replacing their old record with a new one. ulong pkey = FindBattleTowerRecord4(tran, record, false); if (pkey != 0) { // If the player already has a record, move everyone below it up one position // (effectively removing this record from the ordering) // todo: In the case that the player's rank hasn't changed, // we can optimize this and the next down to a single BETWEEN // query. // This does require retrieving their old rank from the db. tran.ExecuteNonQuery("SELECT Rank, Position INTO @old_rank, @old_position " + "FROM GtsBattleTower4 WHERE id = @pkey; " + "UPDATE GtsBattleTower4 SET Position = Position - 1 " + "WHERE RoomNum = @room AND Rank = @old_rank AND Position > @old_position", new MySqlParameter("@pkey", pkey), new MySqlParameter("@room", record.RoomNum)); } uint position = (uint)(7 - record.BattlesWon); // Shift down all the players in the player's new rank by one. tran.ExecuteNonQuery("UPDATE GtsBattleTower4 SET Position = Position + 1 " + "WHERE RoomNum = @room AND Rank = @rank AND Position >= @position", new MySqlParameter("@room", record.RoomNum), new MySqlParameter("@rank", record.Rank), new MySqlParameter("@position", position)); object lastPosition = tran.ExecuteScalar("SELECT MAX(Position) " + "FROM GtsBattleTower4 WHERE RoomNum = @room AND Rank = @rank", new MySqlParameter("@room", record.RoomNum), new MySqlParameter("@rank", record.Rank)); // If the room has fewer than 7 trainers, insert this one at the // end but don't leave any gaps in the numbering. if (lastPosition is DBNull) position = 0; else position = Math.Min(position, (uint)lastPosition + 1); // Update the actual record if (pkey != 0) { List _params = ParamsFromBattleTowerRecord4(record, false); _params.Add(new MySqlParameter("@position", position)); _params.Add(new MySqlParameter("@id", pkey)); tran.ExecuteNonQuery("UPDATE GtsBattleTower4 SET pid = @pid, Name = @name, " + "Version = @version, Language = @language, Country = @country, " + "Region = @region, TrainerID = @trainer_id, " + "PhraseLeader = @phrase_leader, Gender = @gender, " + "Unknown2 = @unknown2, PhraseChallenged = @phrase_challenged, " + "PhraseWon = @phrase_won, PhraseLost = @phrase_lost, " + "Unknown3 = @unknown3, " + "Unknown5 = @unknown5, ParseVersion = 1, Rank = @rank, " + "BattlesWon = @battles_won, Position = @position, " + "TimeUpdated = UTC_TIMESTAMP() WHERE id = @id", _params.ToArray()); UpdateBattleTowerPokemon4(tran, (BattleTowerPokemon4)record.Party[0], pkey, 0); UpdateBattleTowerPokemon4(tran, (BattleTowerPokemon4)record.Party[1], pkey, 1); UpdateBattleTowerPokemon4(tran, (BattleTowerPokemon4)record.Party[2], pkey, 2); } else { List _params = ParamsFromBattleTowerRecord4(record, false); _params.Add(new MySqlParameter("@position", position)); pkey = Convert.ToUInt64(tran.ExecuteScalar("INSERT INTO GtsBattleTower4 " + "(pid, Name, Version, Language, Country, Region, TrainerID, " + "PhraseLeader, Gender, Unknown2, PhraseChallenged, PhraseWon, " + "PhraseLost, Unknown3, Unknown5, ParseVersion, " + "Rank, RoomNum, BattlesWon, Position, TimeAdded, TimeUpdated) VALUES " + "(@pid, @name, @version, @language, @country, @region, @trainer_id, " + "@phrase_leader, @gender, @unknown2, @phrase_challenged, @phrase_won, " + "@phrase_lost, @unknown3, @unknown5, 1, " + "@rank, @room, @battles_won, @position, UTC_TIMESTAMP(), UTC_TIMESTAMP()); " + "SELECT LAST_INSERT_ID()", _params.ToArray())); InsertBattleTowerPokemon4(tran, (BattleTowerPokemon4)record.Party[0], pkey, 0); InsertBattleTowerPokemon4(tran, (BattleTowerPokemon4)record.Party[1], pkey, 1); InsertBattleTowerPokemon4(tran, (BattleTowerPokemon4)record.Party[2], pkey, 2); } return pkey; } public override ulong BattleTowerUpdateRecord4(BattleTowerRecord4 record) { if (record.BattlesWon > 7) throw new ArgumentException("Battles won can not be greater than 7."); return WithTransaction(tran => BattleTowerUpdateRecord4(tran, record)); } private void InsertBattleTowerPokemon4(MySqlTransaction tran, BattleTowerPokemon4 pokemon, ulong partyId, byte slot) { List _params = ParamsFromBattleTowerPokemon4(pokemon); _params.Add(new MySqlParameter("@id", partyId)); _params.Add(new MySqlParameter("@slot", slot)); tran.ExecuteNonQuery("INSERT INTO GtsBattleTowerPokemon4 " + "(party_id, Slot, Species, Form, HeldItem, Move1, Move2, Move3, Move4, TrainerID, " + "Personality, IVs, EVs, Unknown1, Language, Ability, Happiness, Nickname) VALUES " + "(@id, @slot, @species, @form, @held_item, @move1, @move2, @move3, @move4, @trainer_id, " + "@personality, @ivs, @evs, @unknown1, @language, @ability, @happiness, @nickname)", _params.ToArray()); } private void UpdateBattleTowerPokemon4(MySqlTransaction tran, BattleTowerPokemon4 pokemon, ulong partyId, byte slot) { List _params = ParamsFromBattleTowerPokemon4(pokemon); _params.Add(new MySqlParameter("@id", partyId)); _params.Add(new MySqlParameter("@slot", slot)); tran.ExecuteNonQuery("UPDATE GtsBattleTowerPokemon4 SET Species = @species, " + "Form = @form, HeldItem = @held_item, Move1 = @move1, Move2 = @move2, " + "Move3 = @move3, Move4 = @move4, TrainerID = @trainer_id, " + "Personality = @personality, IVs = @ivs, EVs = @evs, Unknown1 = @unknown1, " + "Language = @language, Ability = @ability, Happiness = @happiness, " + "Nickname = @nickname " + "WHERE party_id = @id AND Slot = @slot", _params.ToArray()); } private List ParamsFromBattleTowerRecord4(BattleTowerRecord4 record, bool leader) { List result = new List(15); BattleTowerProfile4 profile = (BattleTowerProfile4)record.Profile; result.Add(new MySqlParameter("@pid", record.PID)); result.Add(new MySqlParameter("@name", profile.Name.RawData)); result.Add(new MySqlParameter("@version", (byte)profile.Version)); result.Add(new MySqlParameter("@language", (byte)profile.Language)); result.Add(new MySqlParameter("@country", profile.Country)); result.Add(new MySqlParameter("@region", profile.Region)); result.Add(new MySqlParameter("@trainer_id", profile.OT)); result.Add(new MySqlParameter("@phrase_leader", profile.PhraseLeader.Data)); result.Add(new MySqlParameter("@gender", profile.Gender)); result.Add(new MySqlParameter("@unknown2", profile.Unknown)); result.Add(new MySqlParameter("@rank", record.Rank)); result.Add(new MySqlParameter("@room", record.RoomNum)); if (!leader) { result.Add(new MySqlParameter("@phrase_challenged", record.PhraseChallenged.Data)); result.Add(new MySqlParameter("@phrase_won", record.PhraseWon.Data)); result.Add(new MySqlParameter("@phrase_lost", record.PhraseLost.Data)); result.Add(new MySqlParameter("@unknown3", record.Unknown3)); result.Add(new MySqlParameter("@unknown5", record.Unknown5)); result.Add(new MySqlParameter("@battles_won", record.BattlesWon)); } return result; } private List ParamsFromBattleTowerPokemon4(BattleTowerPokemon4 pokemon) { List result = new List(15); result.Add(new MySqlParameter("@species", pokemon.SpeciesID)); result.Add(new MySqlParameter("@form", pokemon.FormID)); result.Add(new MySqlParameter("@held_item", pokemon.HeldItemID)); result.Add(new MySqlParameter("@move1", (ushort)pokemon.Moves[0].MoveID)); result.Add(new MySqlParameter("@move2", (ushort)pokemon.Moves[1].MoveID)); result.Add(new MySqlParameter("@move3", (ushort)pokemon.Moves[2].MoveID)); result.Add(new MySqlParameter("@move4", (ushort)pokemon.Moves[3].MoveID)); result.Add(new MySqlParameter("@trainer_id", pokemon.TrainerID)); result.Add(new MySqlParameter("@personality", pokemon.Personality)); result.Add(new MySqlParameter("@ivs", pokemon.IVs.ToInt32() | (int)pokemon.IvFlags)); result.Add(new MySqlParameter("@evs", pokemon.EVs.ToArray())); result.Add(new MySqlParameter("@unknown1", pokemon.GetPpUps())); result.Add(new MySqlParameter("@language", (byte)pokemon.Language)); result.Add(new MySqlParameter("@ability", pokemon.AbilityID)); result.Add(new MySqlParameter("@happiness", pokemon.Happiness)); result.Add(new MySqlParameter("@nickname", pokemon.NicknameEncoded.RawData)); return result; } private ulong BattleTowerAddLeader4(MySqlTransaction tran, BattleTowerRecord4 record) { ulong pkey = FindBattleTowerRecord4(tran, record, true); // Update the actual record if (pkey != 0) { List _params = ParamsFromBattleTowerRecord4(record, true); _params.Add(new MySqlParameter("@id", pkey)); tran.ExecuteNonQuery("UPDATE GtsBattleTowerLeaders4 SET " + "pid = @pid, Name = @name, Version = @version, " + "Language = @language, Country = @country, Region = @region, " + "TrainerID = @trainer_id, " + "PhraseLeader = @phrase_leader, Gender = @gender, Unknown2 = @unknown2, " + "ParseVersion = 1, Rank = @rank, " + "TimeUpdated = UTC_TIMESTAMP() WHERE id = @id", _params.ToArray()); } else { List _params = ParamsFromBattleTowerRecord4(record, true); pkey = Convert.ToUInt64(tran.ExecuteScalar("INSERT INTO " + "GtsBattleTowerLeaders4 " + "(pid, Name, Version, Language, Country, Region, TrainerID, " + "PhraseLeader, Gender, Unknown2, ParseVersion, Rank, " + "RoomNum, TimeAdded, TimeUpdated) VALUES " + "(@pid, @name, @version, @language, @country, @region, @trainer_id, " + "@phrase_leader, @gender, @unknown2, 1, @rank, " + "@room, UTC_TIMESTAMP(), UTC_TIMESTAMP()); " + "SELECT LAST_INSERT_ID()", _params.ToArray())); } return pkey; } public override ulong BattleTowerAddLeader4(BattleTowerRecord4 record) { return WithTransaction(tran => BattleTowerAddLeader4(tran, record)); } /// /// Tries to find an existing database record for the provided player /// record. The match must be found in the same rank and room number. /// /// /// /// If true, look up against the Leaders table. /// Otherwise looks up against the opponents table. /// The match's primary key or 0 if no match is found /// private ulong FindBattleTowerRecord4(MySqlTransaction tran, BattleTowerRecord4 record, bool leader) { string tblName = leader ? "GtsBattleTowerLeaders4" : "GtsBattleTower4"; // If PID is missing, this is restored data. // We assume the original server took care of matching existing // records, so we don't allow it to match here. if (record.PID == 0) return 0; // Match normally. object oPkey = tran.ExecuteScalar("SELECT id FROM " + tblName + " WHERE pid = @pid AND RoomNum = @room AND Rank = @rank", new MySqlParameter("@pid", record.PID), new MySqlParameter("@rank", record.Rank), new MySqlParameter("@room", record.RoomNum)); if (oPkey == null) { BattleTowerProfile4 profile = (BattleTowerProfile4)record.Profile; // PID isn't found. Try to match one of Pikachu025's saved // records based on unchanging properties of the savegame. oPkey = tran.ExecuteScalar("SELECT id FROM " + tblName + " WHERE pid = 0 AND RoomNum = @room AND Rank = @rank " + "AND Name = @name AND Version = @version " + "AND Language = @language AND TrainerID = @trainer_id", new MySqlParameter("@rank", record.Rank), new MySqlParameter("@room", record.RoomNum), new MySqlParameter("@name", profile.Name.RawData), new MySqlParameter("@version", (byte)profile.Version), new MySqlParameter("@language", (byte)profile.Language), new MySqlParameter("@trainer_id", profile.OT) ); } // Don't need to worry about DBNull since the column is non-null. return (ulong)(oPkey ?? 0UL); } public BattleTowerRecord4[] BattleTowerGetOpponents4(MySqlTransaction tran, Pokedex.Pokedex pokedex, int pid, byte rank, byte roomNum) { List records = new List(7); List keys = new List(7); using (MySqlDataReader reader = (MySqlDataReader)tran.ExecuteReader( "SELECT id, pid, Name, " + "Version, Language, Country, Region, TrainerID, " + "PhraseLeader, Gender, Unknown2, PhraseChallenged, " + "PhraseWon, PhraseLost, Unknown3, Unknown5 FROM GtsBattleTower4 " + "WHERE Rank = @rank AND RoomNum = @room AND pid != @pid " + "ORDER BY Position LIMIT 7", new MySqlParameter("@rank", rank), new MySqlParameter("@room", roomNum), new MySqlParameter("@pid", pid))) { while (reader.Read()) { BattleTowerRecord4 record = BattleTowerRecord4FromReader(reader, pokedex); record.Party = new BattleTowerPokemon4[3]; records.Add(record); keys.Add(reader.GetUInt64(0)); } reader.Close(); } if (records.Count == 0) return new BattleTowerRecord4[0]; string inClause = String.Join(", ", keys.Select(i => i.ToString()).ToArray()); using (MySqlDataReader reader = (MySqlDataReader)tran.ExecuteReader("SELECT party_id, " + "Slot, Species, Form, HeldItem, Move1, Move2, Move3, Move4, " + "TrainerID, Personality, IVs, EVs, Unknown1, Language, " + "Ability, Happiness, Nickname FROM GtsBattleTowerPokemon4 " + "WHERE party_id IN (" + inClause + ")")) { while (reader.Read()) { BattleTowerRecord4 record = records[keys.IndexOf(reader.GetUInt64(0))]; record.Party[reader.GetByte(1)] = BattleTowerPokemon4FromReader(reader, pokedex); } reader.Close(); } return Enumerable.Reverse(records).ToArray(); } public override BattleTowerRecord4[] BattleTowerGetOpponents4(Pokedex.Pokedex pokedex, int pid, byte rank, byte roomNum) { return WithTransaction(tran => BattleTowerGetOpponents4(tran, pokedex, pid, rank, roomNum)); } private BattleTowerRecord4 BattleTowerRecord4FromReader(MySqlDataReader reader, Pokedex.Pokedex pokedex) { // xxx: Stop using ordinals everywhere. BattleTowerRecord4 result = new BattleTowerRecord4(pokedex); result.PID = reader.GetInt32(1); if (reader.FieldCount > 11) result.PhraseChallenged = new TrendyPhrase4(reader.GetByteArray(11, 8)); if (reader.FieldCount > 12) result.PhraseWon = new TrendyPhrase4(reader.GetByteArray(12, 8)); if (reader.FieldCount > 13) result.PhraseLost = new TrendyPhrase4(reader.GetByteArray(13, 8)); if (reader.FieldCount > 14) result.Unknown3 = reader.GetUInt16(14); if (reader.FieldCount > 15) result.Unknown5 = reader.GetUInt64(15); BattleTowerProfile4 profile = new BattleTowerProfile4(); profile.Name = new EncodedString4(reader.GetByteArray(2, 16)); profile.Version = (Versions)reader.GetByte(3); profile.Language = (Languages)reader.GetByte(4); profile.Country = reader.GetByte(5); profile.Region = reader.GetByte(6); profile.OT = reader.GetUInt32(7); profile.PhraseLeader = new TrendyPhrase4(reader.GetByteArray(8, 8)); profile.Gender = reader.GetByte(9); profile.Unknown = reader.GetByte(10); result.Profile = profile; return result; } private BattleTowerPokemon4 BattleTowerPokemon4FromReader(MySqlDataReader reader, Pokedex.Pokedex pokedex) { ushort? speciesId = DatabaseExtender.Cast(reader["Species"]); ushort? formId = DatabaseExtender.Cast(reader["Form"]); return new BattleTowerPokemon4(pokedex, (int)speciesId, (byte)formId, DatabaseExtender.Cast(reader["HeldItem"]), DatabaseExtender.Cast(reader["Move1"]), DatabaseExtender.Cast(reader["Move2"]), DatabaseExtender.Cast(reader["Move3"]), DatabaseExtender.Cast(reader["Move4"]), DatabaseExtender.Cast(reader["TrainerID"]), DatabaseExtender.Cast(reader["Personality"]), DatabaseExtender.Cast(reader["IVs"]), DatabaseExtender.Cast(reader["EVs"]), DatabaseExtender.Cast(reader["Unknown1"]), (Languages)DatabaseExtender.Cast(reader["Language"]), DatabaseExtender.Cast(reader["Ability"]), DatabaseExtender.Cast(reader["Happiness"]), new EncodedString4(DatabaseExtender.Cast(reader["Nickname"]), 0, 22) ); } public BattleTowerProfile4[] BattleTowerGetLeaders4(MySqlTransaction tran, Pokedex.Pokedex pokedex, byte rank, byte roomNum) { List profiles = new List(30); using (MySqlDataReader reader = (MySqlDataReader)tran.ExecuteReader( "SELECT id, pid, Name, " + "Version, Language, Country, Region, TrainerID, " + "PhraseLeader, Gender, Unknown2 FROM GtsBattleTowerLeaders4 " + "WHERE Rank = @rank AND RoomNum = @room " + "ORDER BY TimeUpdated DESC, id LIMIT 30", new MySqlParameter("@rank", rank), new MySqlParameter("@room", roomNum))) { while (reader.Read()) profiles.Add((BattleTowerProfile4)BattleTowerRecord4FromReader(reader, pokedex).Profile); reader.Close(); } return profiles.ToArray(); } public override BattleTowerProfile4[] BattleTowerGetLeaders4(Pokedex.Pokedex pokedex, byte rank, byte roomNum) { return WithTransaction(tran => BattleTowerGetLeaders4(tran, pokedex, rank, roomNum)); } #endregion #region Wi-fi Plaza public override TrainerProfilePlaza PlazaGetProfile(int pid) { return WithTransaction(tran => PlazaGetProfile(tran, pid)); } public TrainerProfilePlaza PlazaGetProfile(MySqlTransaction tran, int pid) { // todo next maintenance: remove this CONCAT after the database is updated. using (MySqlDataReader reader = (MySqlDataReader)tran.ExecuteReader("SELECT " + "Data FROM pkmncf_plaza_profiles " + "WHERE pid = @pid", new MySqlParameter("@pid", pid))) { if (reader.Read()) { TrainerProfilePlaza result = new TrainerProfilePlaza(pid, reader.GetByteArray(0, 164)); reader.Close(); return result; } else return null; } } public override bool PlazaSetProfile(TrainerProfilePlaza profile) { return WithTransaction(tran => PlazaSetProfile(tran, profile)); } public bool PlazaSetProfile(MySqlTransaction tran, TrainerProfilePlaza profile) { if (profile.Data.Length != 164) throw new FormatException("Profile data must be 164 bytes."); bool exists = Convert.ToSByte(tran.ExecuteScalar("SELECT EXISTS(SELECT * FROM pkmncf_plaza_profiles WHERE pid = @pid)", new MySqlParameter("@pid", profile.PID))) != 0; // todo next maintenance: Remove this @data_prefix parameter once all data is corrected MySqlParameter[] _params = new MySqlParameter[]{ new MySqlParameter("@pid", profile.PID), new MySqlParameter("@data", profile.Data), new MySqlParameter("@version", (byte)profile.Version), new MySqlParameter("@language", (byte)profile.Language), new MySqlParameter("@country", profile.Country), new MySqlParameter("@region", profile.Region), new MySqlParameter("@ot", profile.OT), new MySqlParameter("@name", profile.Name.RawData) }; if (exists) { return tran.ExecuteNonQuery("UPDATE pkmncf_plaza_profiles " + "SET Data = @data, " + "Version = @version, Language = @language, Country = @country, " + "Region = @region, OT = @ot, Name = @name, ParseVersion = 1, " + "TimeUpdated = UTC_TIMESTAMP() " + "WHERE pid = @pid", _params) > 0; } else { return tran.ExecuteNonQuery("INSERT INTO pkmncf_plaza_profiles " + "(pid, Data, Version, Language, Country, Region, OT, Name, " + "ParseVersion, TimeAdded, TimeUpdated) VALUES " + "(@pid, @data, @version, @language, @country, @region, @ot, " + "@name, 1, UTC_TIMESTAMP(), UTC_TIMESTAMP())", _params) > 0; } } #endregion #region Other Gamestats 4 public override bool GamestatsBumpProfile4(int pid, string ip_address) { return WithTransaction(tran => GamestatsBumpProfile4(tran, pid, ip_address)); } public bool GamestatsBumpProfile4(MySqlTransaction tran, int pid, string ip_address) { bool exists = Convert.ToSByte(tran.ExecuteScalar("SELECT EXISTS(SELECT * FROM GtsProfiles4 WHERE pid = @pid)", new MySqlParameter("@pid", pid))) != 0; if (exists) { return tran.ExecuteNonQuery("UPDATE GtsProfiles4 SET " + "TimeUpdated = UTC_TIMESTAMP(), IpAddress = @ip_address " + "WHERE pid = @pid", new MySqlParameter("@ip_address", ip_address), new MySqlParameter("@pid", pid)) > 0; } else { return tran.ExecuteNonQuery("INSERT INTO GtsProfiles4 " + "(pid, TimeAdded, TimeUpdated, IpAddress) VALUES (@pid, UTC_TIMESTAMP(), " + "UTC_TIMESTAMP(), @ip_address)", new MySqlParameter("@pid", pid), new MySqlParameter("@ip_address", ip_address)) > 0; } } public override bool GamestatsSetProfile4(TrainerProfile4 profile) { return WithTransaction(tran => GamestatsSetProfile4(tran, profile)); } public bool GamestatsSetProfile4(MySqlTransaction tran, TrainerProfile4 profile) { if (profile.Data.Length != 100) throw new FormatException("Profile data must be 100 bytes."); bool exists = Convert.ToSByte(tran.ExecuteScalar("SELECT EXISTS(SELECT * FROM GtsProfiles4 WHERE pid = @pid)", new MySqlParameter("@pid", profile.PID))) != 0; MySqlParameter[] _params = new MySqlParameter[]{ new MySqlParameter("@pid", profile.PID), new MySqlParameter("@data", profile.Data), new MySqlParameter("@version", (byte)profile.Version), new MySqlParameter("@language", (byte)profile.Language), new MySqlParameter("@country", profile.Country), new MySqlParameter("@region", profile.Region), new MySqlParameter("@ot", profile.OT), new MySqlParameter("@name", profile.Name.RawData), new MySqlParameter("@mac_address", profile.MacAddress), new MySqlParameter("@email", profile.Email), new MySqlParameter("@has_notifications", profile.HasNotifications), new MySqlParameter("@client_secret", profile.ClientSecret), new MySqlParameter("@mail_secret", profile.MailSecret), new MySqlParameter("@ip_address", profile.IpAddress) }; if (exists) { return tran.ExecuteNonQuery("UPDATE GtsProfiles4 SET Data = @data, " + "Version = @version, Language = @language, Country = @country, " + "Region = @region, OT = @ot, Name = @name, MacAddress = @mac_address, " + "Email = @email, HasNotifications = @has_notifications, " + "ClientSecret = @client_secret, MailSecret = @mail_secret, " + "IpAddress = @ip_address, ParseVersion = 2, TimeUpdated = UTC_TIMESTAMP() " + "WHERE pid = @pid", _params) > 0; } else { return tran.ExecuteNonQuery("INSERT INTO GtsProfiles4 " + "(pid, Data, Version, Language, Country, Region, OT, Name, " + "MacAddress, Email, HasNotifications, ClientSecret, MailSecret, " + "IpAddress, ParseVersion, TimeAdded, TimeUpdated) VALUES " + "(@pid, @data, @version, @language, @country, @region, @ot, " + "@name, @mac_address, @email, @has_notifications, " + "@client_secret, @mail_secret, @ip_address, 2, UTC_TIMESTAMP(), UTC_TIMESTAMP())", _params) > 0; } } public override TrainerProfile4 GamestatsGetProfile4(int pid) { return WithTransaction(tran => GamestatsGetProfile4(tran, pid)); } public TrainerProfile4 GamestatsGetProfile4(MySqlTransaction tran, int pid) { DataTable result = tran.ExecuteDataTable("SELECT Data, IpAddress FROM GtsProfiles4 WHERE pid = @pid", new MySqlParameter("@pid", pid)); if (result.Rows.Count == 0) return null; DataRow row = result.Rows[0]; byte[] data = DatabaseExtender.Cast(row["Data"]); if (data == null) return null; return new TrainerProfile4(pid, data, DatabaseExtender.Cast(row["IpAddress"])); } #endregion #region Bans public override BanStatus CheckBanStatus(int pid) { return WithTransaction(tran => CheckBanStatus(tran, pid)); } public BanStatus CheckBanStatus(MySqlTransaction tran, int pid) { DataTable result = tran.ExecuteDataTable("SELECT Level, Reason, Expires FROM pkmncf_gamestats_bans_pid WHERE pid = @pid AND (Expires > UTC_TIMESTAMP() OR Expires IS NULL)", new MySqlParameter("@pid", pid)); if (result.Rows.Count == 0) return new BanStatus(BanLevels.None, null, DateTime.MinValue); DataRow row = result.Rows[0]; return new BanStatus( (BanLevels)DatabaseExtender.Cast(row["Level"]), DatabaseExtender.Cast(row["Reason"]), DatabaseExtender.Cast(row["Expires"]) ); } public override BanStatus CheckBanStatus(byte[] mac_address) { return WithTransaction(tran => CheckBanStatus(tran, mac_address)); } public BanStatus CheckBanStatus(MySqlTransaction tran, byte[] mac_address) { DataTable result = tran.ExecuteDataTable("SELECT Level, Reason, Expires FROM pkmncf_gamestats_bans_mac WHERE MacAddress = @mac_address AND (Expires > UTC_TIMESTAMP() OR Expires IS NULL)", new MySqlParameter("@mac_address", mac_address)); if (result.Rows.Count == 0) return new BanStatus(BanLevels.None, null, DateTime.MinValue); DataRow row = result.Rows[0]; return new BanStatus( (BanLevels)DatabaseExtender.Cast(row["Level"]), DatabaseExtender.Cast(row["Reason"]), DatabaseExtender.Cast(row["Expires"]) ); } public override BanStatus CheckBanStatus(string ip_address) { return WithTransaction(tran => CheckBanStatus(tran, ip_address)); } public BanStatus CheckBanStatus(MySqlTransaction tran, string ip_address) { DataTable result = tran.ExecuteDataTable("SELECT Level, Reason, Expires FROM pkmncf_gamestats_bans_ip WHERE IpAddress = @ip_address AND (Expires > UTC_TIMESTAMP() OR Expires IS NULL)", new MySqlParameter("@ip_address", ip_address)); if (result.Rows.Count == 0) return new BanStatus(BanLevels.None, null, DateTime.MinValue); DataRow row = result.Rows[0]; return new BanStatus( (BanLevels)DatabaseExtender.Cast(row["Level"]), DatabaseExtender.Cast(row["Reason"]), DatabaseExtender.Cast(row["Expires"]) ); } /// /// Checks JUST for a matching savefile ban. Use the appropriate pid/MAC CheckBanStatus overload to check those tables. /// /// /// public override BanStatus CheckBanStatus(TrainerProfileBase profile) { return WithTransaction(tran => CheckBanStatus(tran, profile)); } public BanStatus CheckBanStatus(MySqlTransaction tran, TrainerProfileBase profile) { byte[] name = null; if (profile is TrainerProfile4) { name = ((TrainerProfile4)profile).Name.RawData; } if (profile is TrainerProfile5) { name = ((TrainerProfile5)profile).Name.RawData; } DataTable result = tran.ExecuteDataTable("SELECT Level, Reason, Expires " + "FROM pkmncf_gamestats_bans_savefile WHERE Version = @version AND Language = @language AND OT = @ot AND Name = @name " + "AND (Expires > UTC_TIMESTAMP() OR Expires IS NULL)", new MySqlParameter("@version", profile.Version), new MySqlParameter("@language", profile.Language), new MySqlParameter("@ot", profile.OT), new MySqlParameter("@name", name)); if (result.Rows.Count == 0) return new BanStatus(BanLevels.None, null, DateTime.MinValue); DataRow row = result.Rows[0]; return new BanStatus( (BanLevels)DatabaseExtender.Cast(row["Level"]), DatabaseExtender.Cast(row["Reason"]), DatabaseExtender.Cast(row["Expires"]) ); } public override BanStatus CheckBanStatus(uint ip_address) { return WithTransaction(tran => CheckBanStatus(tran, ip_address)); } public BanStatus CheckBanStatus(MySqlTransaction tran, uint ip_address) { DataTable result = tran.ExecuteDataTable("SELECT Level, Reason, Expires " + "FROM pkmncf_gamestats_bans_ipv4_range " + "WHERE (@ip BETWEEN IpAddressMin AND IpAddressMax) AND (Expires > UTC_TIMESTAMP() OR Expires IS NULL)", new MySqlParameter("@ip", ip_address)); if (result.Rows.Count == 0) return new BanStatus(BanLevels.None, null, DateTime.MinValue); DataRow row = result.Rows[0]; return new BanStatus( (BanLevels)DatabaseExtender.Cast(row["Level"]), DatabaseExtender.Cast(row["Reason"]), DatabaseExtender.Cast(row["Expires"]) ); } public override void AddBan(int pid, BanStatus status) { WithTransaction(tran => AddBan(tran, pid, status)); } public void AddBan(MySqlTransaction tran, int pid, BanStatus status) { AddBan(tran, "pkmncf_gamestats_bans_pid", "pid", new MySqlParameter("@pk", pid), status); } public override void AddBan(byte[] mac_address, BanStatus status) { WithTransaction(tran => AddBan(tran, mac_address, status)); } public void AddBan(MySqlTransaction tran, byte[] mac_address, BanStatus status) { AddBan(tran, "pkmncf_gamestats_bans_mac", "MacAddress", new MySqlParameter("@pk", mac_address), status); } public override void AddBan(string ip_address, BanStatus status) { WithTransaction(tran => AddBan(tran, ip_address, status)); } public void AddBan(MySqlTransaction tran, string ip_address, BanStatus status) { AddBan(tran, "pkmncf_gamestats_bans_ip", "IpAddress", new MySqlParameter("@pk", ip_address), status); } private void AddBan(MySqlTransaction tran, string tbl, string primary_key, MySqlParameter pk_param, BanStatus status) { string pkParamName = pk_param.ParameterName; string sqlExists = "SELECT EXISTS(SELECT * FROM " + tbl + " WHERE " + primary_key + " = " + pkParamName + ")"; string sqlInsert = "INSERT INTO " + tbl + " (" + primary_key + ", Level, Reason, Expires) VALUES (" + pkParamName + ", @level, @reason, @expires)"; string sqlUpdate = "UPDATE " + tbl + " SET Level = @level, Reason = @reason, Expires = GREATEST(Expires, @expires) WHERE " + primary_key + " = " + pkParamName; if (Convert.ToSByte(tran.ExecuteScalar(sqlExists, pk_param.CloneParameter())) > 0) { tran.ExecuteNonQuery(sqlUpdate, pk_param.CloneParameter(), new MySqlParameter("@level", status.Level), new MySqlParameter("@reason", status.Reason), new MySqlParameter("@expires", status.Expires)); } else { tran.ExecuteNonQuery(sqlInsert, pk_param.CloneParameter(), new MySqlParameter("@level", status.Level), new MySqlParameter("@reason", status.Reason), new MySqlParameter("@expires", status.Expires)); } } #endregion #region GTS 5 public GtsRecord5 GtsDataForUser5(MySqlTransaction tran, Pokedex.Pokedex pokedex, int pid) { using (MySqlDataReader reader = (MySqlDataReader)tran.ExecuteReader("SELECT id, Data, Unknown0, " + "Species, Gender, Level, " + "RequestedSpecies, RequestedGender, RequestedMinLevel, RequestedMaxLevel, " + "Unknown1, TrainerGender, Unknown2, TimeDeposited, TimeExchanged, pid, " + "TrainerOT, TrainerName, TrainerCountry, TrainerRegion, TrainerClass, " + "IsExchanged, TrainerVersion, TrainerLanguage, TrainerBadges, TrainerUnityTower " + "FROM GtsPokemon5 WHERE pid = @pid", new MySqlParameter("@pid", pid))) { if (!reader.Read()) { reader.Close(); return null; } GtsRecord5 result = Record5FromReader(pokedex, reader); #if DEBUG AssertHelper.Equals(result.PID, pid); #endif reader.Close(); return result; } } public override GtsRecord5 GtsDataForUser5(Pokedex.Pokedex pokedex, int pid) { return WithTransaction(tran => GtsDataForUser5(tran, pokedex, pid)); } public GtsRecord5 GtsGetRecord5(MySqlTransaction tran, Pokedex.Pokedex pokedex, long tradeId, bool isExchanged, bool allowHistory) { using (MySqlDataReader reader = (MySqlDataReader)tran.ExecuteReader("SELECT id, Data, Unknown0, " + "Species, Gender, Level, " + "RequestedSpecies, RequestedGender, RequestedMinLevel, RequestedMaxLevel, " + "Unknown1, TrainerGender, Unknown2, TimeDeposited, TimeExchanged, pid, " + "TrainerOT, TrainerName, TrainerCountry, TrainerRegion, TrainerClass, " + "IsExchanged, TrainerVersion, TrainerLanguage, TrainerBadges, TrainerUnityTower " + "FROM GtsPokemon5 WHERE id = @id AND IsExchanged = @is_exchanged", new MySqlParameter("@id", tradeId), new MySqlParameter("@is_exchanged", isExchanged ? 1 : 0))) { if (reader.Read()) { GtsRecord5 result = Record5FromReader(pokedex, reader); reader.Close(); return result; } reader.Close(); } if (allowHistory) { using (MySqlDataReader reader = (MySqlDataReader)tran.ExecuteReader("SELECT id, Data, Unknown0, " + "Species, Gender, Level, " + "RequestedSpecies, RequestedGender, RequestedMinLevel, RequestedMaxLevel, " + "Unknown1, TrainerGender, Unknown2, TimeDeposited, TimeExchanged, pid, " + "TrainerOT, TrainerName, TrainerCountry, TrainerRegion, TrainerClass, " + "IsExchanged, TrainerVersion, TrainerLanguage, TrainerBadges, TrainerUnityTower " + "FROM GtsHistory5 WHERE trade_id = @id AND IsExchanged = @is_exchanged", new MySqlParameter("@id", tradeId), new MySqlParameter("@is_exchanged", isExchanged ? 1 : 0))) { if (reader.Read()) { GtsRecord5 result = Record5FromReader(pokedex, reader); reader.Close(); return result; } } } return null; } public override GtsRecord5 GtsGetRecord5(Pokedex.Pokedex pokedex, long tradeId, bool isExchanged, bool allowHistory) { return WithTransaction(tran => GtsGetRecord5(tran, pokedex, tradeId, isExchanged, allowHistory)); } public bool GtsDepositPokemon5(MySqlTransaction tran, GtsRecord5 record) { if (record == null) throw new ArgumentNullException("record"); if (record.Data.Count != 236) throw new FormatException("pkm data must be 236 bytes."); if (record.TrainerNameEncoded.RawData.Length != 16) throw new FormatException("Trainer name must be 16 bytes."); // note that IsTraded being true in the record is not an error condition // since it might have use later on. You should check for this in the upload handler. long count = (long)tran.ExecuteScalar("SELECT Count(*) FROM GtsPokemon5 WHERE pid = @pid", new MySqlParameter("@pid", record.PID)); if (count > 0) { // This player already has a pokemon in the system. // we can possibly allow multiples under some future conditions return false; } tran.ExecuteNonQuery("INSERT INTO GtsPokemon5 " + "(Data, Unknown0, Species, Gender, Level, RequestedSpecies, RequestedGender, " + "RequestedMinLevel, RequestedMaxLevel, Unknown1, TrainerGender, " + "Unknown2, TimeDeposited, TimeExchanged, pid, TrainerOT, TrainerName, " + "TrainerCountry, TrainerRegion, TrainerClass, IsExchanged, TrainerVersion, " + "TrainerLanguage, TrainerBadges, TrainerUnityTower) " + "VALUES (@Data, @Unknown0, @Species, @Gender, @Level, @RequestedSpecies, " + "@RequestedGender, @RequestedMinLevel, @RequestedMaxLevel, @Unknown1, " + "@TrainerGender, @Unknown2, @TimeDeposited, @TimeExchanged, @pid, " + "@TrainerOT, @TrainerName, @TrainerCountry, @TrainerRegion, @TrainerClass, " + "@IsExchanged, @TrainerVersion, @TrainerLanguage, @TrainerBadges, @TrainerUnityTower)", ParamsFromRecord5(record)); return true; } public override bool GtsDepositPokemon5(GtsRecord5 record) { if (record == null) throw new ArgumentNullException("record"); if (record.Data.Count != 236) throw new FormatException("pkm data must be 236 bytes."); if (record.TrainerNameEncoded.RawData.Length != 16) throw new FormatException("Trainer name must be 16 bytes."); return WithTransactionSuccessful(tran => GtsDepositPokemon5(tran, record)); } public ulong ? GtsGetDepositId5(MySqlTransaction tran, int pid) { object o = tran.ExecuteScalar("SELECT id FROM GtsPokemon5 WHERE pid = @pid " + "ORDER BY IsExchanged DESC, TimeExchanged, TimeDeposited LIMIT 1", new MySqlParameter("@pid", pid)); if (o == null || o == DBNull.Value) return null; return Convert.ToUInt64(o); } public bool GtsDeletePokemon5(MySqlTransaction tran, int pid) { ulong ? pkmnId = GtsGetDepositId5(tran, pid); if (pkmnId == null) return false; #if !DEBUG try { #endif // this has to run before deletion or isExchanged information is lost. // fixme: the trade_id is wrong here because logs use the // deposited trade ID, not the exchanged one GtsSetWithdrawTime5(tran, (ulong)pkmnId); #if !DEBUG } catch { } #endif tran.ExecuteNonQuery("DELETE FROM GtsPokemon5 WHERE id = @id", new MySqlParameter("@id", pkmnId)); return true; } public override bool GtsDeletePokemon5(int pid) { return WithTransactionSuccessful(tran => GtsDeletePokemon5(tran, pid)); } private void GtsSetWithdrawTime5(MySqlTransaction tran, ulong trade_id) { // only set the withdraw time if IsExchanged is true. // If false, no trade has happened; we are withdrawing our old pokemon. if (Convert.ToByte( tran.ExecuteScalar("SELECT IsExchanged FROM GtsPokemon5 WHERE id = @id", new MySqlParameter("@id", trade_id))) != 0) { tran.ExecuteNonQuery("UPDATE GtsHistory5 " + "SET TimeWithdrawn = @now " + "WHERE trade_id = @trade_id", new MySqlParameter("@now", DateTime.UtcNow), new MySqlParameter("@trade_id", trade_id)); } } public override bool GtsTradePokemon5(int pidSrc, int pidDest) { throw new NotImplementedException(); } public bool GtsTradePokemon5(MySqlTransaction tran, GtsRecord5 upload, GtsRecord5 result, int partner_pid) { GtsRecord5 traded = upload.Clone(); traded.FlagTraded(result); ulong? trade_id = GtsGetDepositId5(tran, result.PID); GtsRecord5 resultOrig = GtsDataForUser5(tran, result.Pokedex, result.PID); if (trade_id == null || resultOrig == null || resultOrig != result || !GtsCheckLockStatus5(tran, (ulong)trade_id, partner_pid)) // looks like the pokemon was ninja'd between the Exchange and Exchange_finish return false; if (!GtsDeletePokemon5(tran, result.PID)) return false; if (!GtsDepositPokemon5(tran, traded)) return false; #if !DEBUG try { #endif GtsLogTrade5(tran, result, null, partner_pid, trade_id); GtsLogTrade5(tran, traded, null, partner_pid, trade_id); #if !DEBUG } catch { } #endif return true; } public override bool GtsTradePokemon5(GtsRecord5 upload, GtsRecord5 result, int partner_pid) { return WithTransactionSuccessful(tran => GtsTradePokemon5(tran, upload, result, partner_pid)); } public override bool GtsLockPokemon5(ulong tradeId, int partner_pid) { return WithTransaction(tran => GtsLockPokemon5(tran, tradeId, partner_pid)); } public bool GtsLockPokemon5(MySqlTransaction tran, ulong tradeId, int partner_pid) { DateTime now = DateTime.UtcNow; int rows = tran.ExecuteNonQuery("UPDATE GtsPokemon5 SET LockedUntil = @locked_until, LockedBy = @locked_by " + "WHERE id = @trade_id AND (LockedUntil < @now OR LockedUntil IS NULL OR LockedBy = @locked_by)", new MySqlParameter("@trade_id", tradeId), new MySqlParameter("@locked_until", now.AddSeconds(GTS_LOCK_DURATION)), new MySqlParameter("@locked_by", partner_pid), new MySqlParameter("@now", now)); return rows != 0; } public override bool GtsCheckLockStatus5(ulong tradeId, int partner_pid) { return WithTransaction(tran => GtsCheckLockStatus5(tran, tradeId, partner_pid)); } public bool GtsCheckLockStatus5(MySqlTransaction tran, ulong tradeId, int partner_pid) { int rows = Convert.ToInt32(tran.ExecuteScalar("SELECT count(*) FROM GtsPokemon5 " + "WHERE id = @trade_id AND (LockedUntil < @now OR LockedUntil IS NULL OR LockedBy = @locked_by)", new MySqlParameter("@trade_id", tradeId), new MySqlParameter("@locked_by", partner_pid), new MySqlParameter("@now", DateTime.UtcNow) )); return rows != 0; // No rows means a lock is in effect or nothing was found } public override GtsRecord5[] GtsSearch5(Pokedex.Pokedex pokedex, int pid, ushort species, Genders gender, byte minLevel, byte maxLevel, byte country, int count) { return WithTransaction(tran => GtsSearch5(tran, pokedex, pid, species, gender, minLevel, maxLevel, country, count)); } public GtsRecord5[] GtsSearch5(MySqlTransaction tran, Pokedex.Pokedex pokedex, int pid, ushort species, Genders gender, byte minLevel, byte maxLevel, byte country, int count) { List _params = new List(); string where = "WHERE pid != @pid AND IsExchanged = 0 AND (LockedUntil < @now OR LockedUntil IS NULL)"; _params.Add(new MySqlParameter("@pid", pid)); _params.Add(new MySqlParameter("@now", DateTime.UtcNow)); if (species > 0) { where += " AND Species = @species"; _params.Add(new MySqlParameter("@species", species)); } if (gender != Genders.Either) { where += " AND Gender IN (@gender, 3)"; _params.Add(new MySqlParameter("@gender", (byte)gender)); } if (minLevel > 0 && maxLevel > 0) { where += " AND Level BETWEEN @min_level AND @max_level"; _params.Add(new MySqlParameter("@min_level", minLevel)); _params.Add(new MySqlParameter("@max_level", maxLevel)); } else if (minLevel > 0) { where += " AND Level >= @min_level"; _params.Add(new MySqlParameter("@min_level", minLevel)); } else if (maxLevel > 0) { where += " AND Level <= @max_level"; _params.Add(new MySqlParameter("@max_level", maxLevel)); } if (country > 0) { where += " AND TrainerCountry = @country"; _params.Add(new MySqlParameter("@country", country)); } string limit = ""; if (count > 0) { _params.Add(new MySqlParameter("@count", count)); limit = " LIMIT @count"; } // todo: sort me in creative ways using (MySqlDataReader reader = (MySqlDataReader)tran.ExecuteReader("SELECT Data, Unknown0, " + "Species, Gender, Level, " + "RequestedSpecies, RequestedGender, RequestedMinLevel, RequestedMaxLevel, " + "Unknown1, TrainerGender, Unknown2, TimeDeposited, TimeExchanged, pid, " + "TrainerOT, TrainerName, TrainerCountry, TrainerRegion, TrainerClass, " + "IsExchanged, TrainerVersion, TrainerLanguage, TrainerBadges, TrainerUnityTower, id " + "FROM GtsPokemon5 " + where + " ORDER BY TimeDeposited DESC" + limit, _params.ToArray())) { List records; if (count > 0) records = new List(count); else records = new List(); while (reader.Read()) { var record = Record5FromReader(pokedex, reader); record.TradeId = DatabaseExtender.Cast(reader["id"]); records.Add(record); } reader.Close(); return records.ToArray(); } } private static GtsRecord5 Record5FromReader(Pokedex.Pokedex pokedex, MySqlDataReader reader) { GtsRecord5 result = new GtsRecord5(pokedex); result.TradeId = DatabaseExtender.Cast(reader["id"]); // xxx: Data and Unknown0 should share a database field. // (This requires migrating a lot of existing data) byte[] data = DatabaseExtender.Cast(reader["Data"]); byte[] unknown0 = DatabaseExtender.Cast(reader["Unknown0"]); byte[] combined = new byte[236]; Array.Copy(data, 0, combined, 0, 220); Array.Copy(unknown0, 0, combined, 220, 16); result.Data = combined; result.Species = DatabaseExtender.Cast(reader["Species"]); result.Gender = (Genders)DatabaseExtender.Cast(reader["Gender"]); result.Level = DatabaseExtender.Cast(reader["Level"]); result.RequestedSpecies = DatabaseExtender.Cast(reader["RequestedSpecies"]); result.RequestedGender = (Genders)DatabaseExtender.Cast(reader["RequestedGender"]); result.RequestedMinLevel = DatabaseExtender.Cast(reader["RequestedMinLevel"]); result.RequestedMaxLevel = DatabaseExtender.Cast(reader["RequestedMaxLevel"]); result.Unknown1 = DatabaseExtender.Cast(reader["Unknown1"]); result.TrainerGender = (TrainerGenders)DatabaseExtender.Cast(reader["TrainerGender"]); result.Unknown2 = DatabaseExtender.Cast(reader["Unknown2"]); result.TimeDeposited = DatabaseExtender.Cast(reader["TimeDeposited"]); result.TimeExchanged = DatabaseExtender.Cast(reader["TimeExchanged"]); result.PID = DatabaseExtender.Cast(reader["pid"]); result.TrainerOT = DatabaseExtender.Cast(reader["TrainerOT"]); result.TrainerNameEncoded = new EncodedString5(DatabaseExtender.Cast(reader["TrainerName"])); result.TrainerCountry = DatabaseExtender.Cast(reader["TrainerCountry"]); result.TrainerRegion = DatabaseExtender.Cast(reader["TrainerRegion"]); result.TrainerClass = DatabaseExtender.Cast(reader["TrainerClass"]); result.IsExchanged = DatabaseExtender.Cast(reader["IsExchanged"]); result.TrainerVersion = (Versions)DatabaseExtender.Cast(reader["TrainerVersion"]); result.TrainerLanguage = (Languages)DatabaseExtender.Cast(reader["TrainerLanguage"]); result.TrainerBadges = DatabaseExtender.Cast(reader["TrainerBadges"]); result.TrainerUnityTower = DatabaseExtender.Cast(reader["TrainerUnityTower"]); return result; } private static MySqlParameter[] ParamsFromRecord5(GtsRecord5 record) { MySqlParameter[] result = new MySqlParameter[25]; byte[] src = record.Data.ToArray(); // xxx: why is there no IList.CopyTo(T[] dest, int destOffset, int count) overload?? byte[] data = new byte[220]; byte[] unknown0 = new byte[16]; Array.Copy(src, 0, data, 0, 220); Array.Copy(src, 220, unknown0, 0, 16); result[0] = new MySqlParameter("@Data", data); result[1] = new MySqlParameter("@Unknown0", unknown0); result[2] = new MySqlParameter("@Species", record.Species); result[3] = new MySqlParameter("@Gender", (byte)record.Gender); result[4] = new MySqlParameter("@Level", record.Level); result[5] = new MySqlParameter("@RequestedSpecies", record.RequestedSpecies); result[6] = new MySqlParameter("@RequestedGender", (byte)record.RequestedGender); result[7] = new MySqlParameter("@RequestedMinLevel", record.RequestedMinLevel); result[8] = new MySqlParameter("@RequestedMaxLevel", record.RequestedMaxLevel); result[9] = new MySqlParameter("@Unknown1", record.Unknown1); result[10] = new MySqlParameter("@TrainerGender", (byte)record.TrainerGender); result[11] = new MySqlParameter("@Unknown2", record.Unknown2); result[12] = new MySqlParameter("@TimeDeposited", record.TimeDeposited); result[13] = new MySqlParameter("@TimeExchanged", record.TimeExchanged); result[14] = new MySqlParameter("@pid", record.PID); result[15] = new MySqlParameter("@TrainerOT", record.TrainerOT); result[16] = new MySqlParameter("@TrainerName", record.TrainerNameEncoded.RawData); result[17] = new MySqlParameter("@TrainerCountry", record.TrainerCountry); result[18] = new MySqlParameter("@TrainerRegion", record.TrainerRegion); result[19] = new MySqlParameter("@TrainerClass", record.TrainerClass); result[20] = new MySqlParameter("@IsExchanged", record.IsExchanged); result[21] = new MySqlParameter("@TrainerVersion", record.TrainerVersion); result[22] = new MySqlParameter("@TrainerLanguage", record.TrainerLanguage); result[23] = new MySqlParameter("@TrainerBadges", record.TrainerBadges); result[24] = new MySqlParameter("@TrainerUnityTower", record.TrainerUnityTower); return result; } public override int GtsAvailablePokemon5() { return WithTransaction(tran => GtsAvailablePokemon5(tran)); } public int GtsAvailablePokemon5(MySqlTransaction tran) { return Convert.ToInt32(tran.ExecuteScalar("SELECT Count(*) FROM GtsPokemon5 WHERE IsExchanged = 0")); } public void GtsLogTrade5(GtsRecord5 record, DateTime ? timeWithdrawn, int ? partner_pid, ulong ? trade_id) { WithTransaction(tran => GtsLogTrade5(tran, record, timeWithdrawn, partner_pid, trade_id)); } public void GtsLogTrade5(MySqlTransaction tran, GtsRecord5 record, DateTime ? timeWithdrawn, int ? partner_pid, ulong ? trade_id) { // todo: Bring these out into a ValidateRecord5 method if (record == null) throw new ArgumentNullException("record"); if (record.Data.Count != 236) throw new FormatException("pkm data must be 236 bytes."); if (record.TrainerNameEncoded.RawData.Length != 16) throw new FormatException("Trainer name must be 16 bytes."); // note that IsTraded being true in the record is not an error condition // since it might have use later on. You should check for this in the upload handler. if (trade_id == null) trade_id = GtsGetDepositId5(tran, record.PID); // when calling delete.asp, the partner pid can't be told from the request alone, // so obtain it from the database instead. if (record.IsExchanged != 0 && trade_id != null && partner_pid == null) partner_pid = (int ?)tran.ExecuteScalar("SELECT partner_pid FROM GtsHistory5 " + "WHERE trade_id = @trade_id AND IsExchanged = 0", new MySqlParameter("@trade_id", trade_id)); MySqlParameter[] _params = ParamsFromRecord5(record); MySqlParameter[] _params2 = new MySqlParameter[28]; Array.Copy(_params, _params2, 25); _params2[25] = new MySqlParameter("@TimeWithdrawn", timeWithdrawn); _params2[26] = new MySqlParameter("@trade_id", trade_id); _params2[27] = new MySqlParameter("@partner_pid", partner_pid); tran.ExecuteNonQuery("INSERT INTO GtsHistory5 " + "(Data, Unknown0, Species, Gender, Level, RequestedSpecies, RequestedGender, " + "RequestedMinLevel, RequestedMaxLevel, Unknown1, TrainerGender, " + "Unknown2, TimeDeposited, TimeExchanged, pid, TrainerOT, TrainerName, " + "TrainerCountry, TrainerRegion, TrainerClass, IsExchanged, TrainerVersion, " + "TrainerLanguage, TrainerBadges, TrainerUnityTower, TimeWithdrawn, " + "trade_id, partner_pid) " + "VALUES (@Data, @Unknown0, @Species, @Gender, @Level, @RequestedSpecies, " + "@RequestedGender, @RequestedMinLevel, @RequestedMaxLevel, @Unknown1, " + "@TrainerGender, @Unknown2, @TimeDeposited, @TimeExchanged, @pid, " + "@TrainerOT, @TrainerName, @TrainerCountry, @TrainerRegion, @TrainerClass, " + "@IsExchanged, @TrainerVersion, @TrainerLanguage, @TrainerBadges, " + "@TrainerUnityTower, @TimeWithdrawn, @trade_id, @partner_pid)", _params2); } public void GtsSetLastSearch5(MySqlTransaction tran, int pid) { tran.ExecuteNonQuery("UPDATE GtsProfiles5 SET TimeLastSearch = " + "@now WHERE pid = @pid", new MySqlParameter("@now", DateTime.UtcNow), new MySqlParameter("@pid", pid)); } public override void GtsSetLastSearch5(int pid) { WithTransaction(tran => GtsSetLastSearch5(tran, pid)); } public DateTime? GtsGetLastSearch5(MySqlTransaction tran, int pid) { object result = tran.ExecuteScalar("SELECT TimeLastSearch " + "FROM GtsProfiles5 WHERE pid = @pid", new MySqlParameter("@pid", pid)); if (result == null || result is DBNull) return null; return (DateTime)result; } public override DateTime? GtsGetLastSearch5(int pid) { return WithTransaction(tran => GtsGetLastSearch5(tran, pid)); } #endregion #region Battle Subway 5 public override ulong BattleSubwayUpdateRecord5(BattleSubwayRecord5 record) { if (record.BattlesWon > 7) throw new ArgumentException("Battles won can not be greater than 7."); return WithTransaction(tran => BattleSubwayUpdateRecord5(tran, record)); } private ulong BattleSubwayUpdateRecord5(MySqlTransaction tran, BattleSubwayRecord5 record) { if (record.BattlesWon > 7) throw new ArgumentException("Battles won can not be greater than 7."); // Does this player already have a record in this room? // Also get primary key if it does. (We need it for updating party) ulong pkey = FindBattleSubwayRecord5(tran, record, false); if (pkey != 0) { // If the player already has a record, move everyone below it up one position // (effectively removing this record from the ordering) // todo: In the case that the player's rank hasn't changed, // we can optimize this and the next down to a single BETWEEN // query. // This does require retrieving their old rank from the db. tran.ExecuteNonQuery("SELECT Rank, Position INTO @old_rank, @old_position " + "FROM GtsBattleSubway5 WHERE id = @pkey; " + "UPDATE GtsBattleSubway5 SET Position = Position - 1 " + "WHERE RoomNum = @room AND Rank = @old_rank AND Position > @old_position", new MySqlParameter("@pkey", pkey), new MySqlParameter("@room", record.RoomNum)); } uint position = (uint)(7 - record.BattlesWon); // Shift down all the players in the player's new rank by one. tran.ExecuteNonQuery("UPDATE GtsBattleSubway5 SET Position = Position + 1 " + "WHERE RoomNum = @room AND Rank = @rank AND Position >= @position", new MySqlParameter("@room", record.RoomNum), new MySqlParameter("@rank", record.Rank), new MySqlParameter("@position", position)); object lastPosition = tran.ExecuteScalar("SELECT MAX(Position) " + "FROM GtsBattleSubway5 WHERE RoomNum = @room AND Rank = @rank", new MySqlParameter("@room", record.RoomNum), new MySqlParameter("@rank", record.Rank)); // If the room has fewer than 7 trainers, insert this one at the // end but don't leave any gaps in the numbering. if (lastPosition is DBNull) position = 0; else position = Math.Min(position, (uint)lastPosition + 1); // Update the actual record if (pkey != 0) { List _params = ParamsFromBattleSubwayRecord5(record, false); _params.Add(new MySqlParameter("@position", position)); _params.Add(new MySqlParameter("@id", pkey)); tran.ExecuteNonQuery("UPDATE GtsBattleSubway5 SET pid = @pid, Name = @name, " + "Version = @version, Language = @language, Country = @country, " + "Region = @region, TrainerID = @trainer_id, " + "PhraseLeader = @phrase_leader, Gender = @gender, " + "Unknown2 = @unknown2, PhraseChallenged = @phrase_challenged, " + "PhraseWon = @phrase_won, PhraseLost = @phrase_lost, Unknown3 = @unknown3, " + "Unknown4 = @unknown4, Unknown5 = @unknown5, ParseVersion = 1, Rank = @rank, " + "BattlesWon = @battles_won, Position = @position, " + "TimeUpdated = UTC_TIMESTAMP() WHERE id = @id", _params.ToArray()); UpdateBattleSubwayPokemon5(tran, (BattleSubwayPokemon5)record.Party[0], pkey, 0); UpdateBattleSubwayPokemon5(tran, (BattleSubwayPokemon5)record.Party[1], pkey, 1); UpdateBattleSubwayPokemon5(tran, (BattleSubwayPokemon5)record.Party[2], pkey, 2); } else { List _params = ParamsFromBattleSubwayRecord5(record, false); _params.Add(new MySqlParameter("@position", position)); pkey = Convert.ToUInt64(tran.ExecuteScalar("INSERT INTO GtsBattleSubway5 " + "(pid, Name, Version, Language, Country, Region, TrainerID, " + "PhraseLeader, Gender, Unknown2, PhraseChallenged, PhraseWon, " + "PhraseLost, Unknown3, Unknown4, Unknown5, ParseVersion, " + "Rank, RoomNum, BattlesWon, Position, TimeAdded, TimeUpdated) VALUES " + "(@pid, @name, @version, @language, @country, @region, @trainer_id, " + "@phrase_leader, @gender, @unknown2, @phrase_challenged, @phrase_won, " + "@phrase_lost, @unknown3, @unknown4, @unknown5, 1, " + "@rank, @room, @battles_won, @position, UTC_TIMESTAMP(), UTC_TIMESTAMP()); " + "SELECT LAST_INSERT_ID()", _params.ToArray())); InsertBattleSubwayPokemon5(tran, (BattleSubwayPokemon5)record.Party[0], pkey, 0); InsertBattleSubwayPokemon5(tran, (BattleSubwayPokemon5)record.Party[1], pkey, 1); InsertBattleSubwayPokemon5(tran, (BattleSubwayPokemon5)record.Party[2], pkey, 2); } return pkey; } private void InsertBattleSubwayPokemon5(MySqlTransaction tran, BattleSubwayPokemon5 pokemon, ulong partyId, byte slot) { List _params = ParamsFromBattleSubwayPokemon5(pokemon); _params.Add(new MySqlParameter("@id", partyId)); _params.Add(new MySqlParameter("@slot", slot)); tran.ExecuteNonQuery("INSERT INTO GtsBattleSubwayPokemon5 " + "(party_id, Slot, Species, Form, HeldItem, Move1, Move2, Move3, Move4, TrainerID, " + "Personality, IVs, EVs, Unknown1, Language, Ability, Happiness, " + "Nickname, Unknown2) VALUES " + "(@id, @slot, @species, @form, @held_item, @move1, @move2, @move3, @move4, @trainer_id, " + "@personality, @ivs, @evs, @unknown1, @language, @ability, @happiness, " + "@nickname, @unknown2)", _params.ToArray()); } private void UpdateBattleSubwayPokemon5(MySqlTransaction tran, BattleSubwayPokemon5 pokemon, ulong partyId, byte slot) { List _params = ParamsFromBattleSubwayPokemon5(pokemon); _params.Add(new MySqlParameter("@id", partyId)); _params.Add(new MySqlParameter("@slot", slot)); tran.ExecuteNonQuery("UPDATE GtsBattleSubwayPokemon5 SET Species = @species, " + "Form = @form, HeldItem = @held_item, Move1 = @move1, Move2 = @move2, " + "Move3 = @move3, Move4 = @move4, TrainerID = @trainer_id, " + "Personality = @personality, IVs = @ivs, EVs = @evs, Unknown1 = @unknown1, " + "Language = @language, Ability = @ability, Happiness = @happiness, " + "Nickname = @nickname, Unknown2 = @unknown2 " + "WHERE party_id = @id AND Slot = @slot", _params.ToArray()); } private List ParamsFromBattleSubwayRecord5(BattleSubwayRecord5 record, bool leader) { BattleSubwayProfile5 profile = (BattleSubwayProfile5)record.Profile; List result = new List(15); result.Add(new MySqlParameter("@pid", record.PID)); result.Add(new MySqlParameter("@name", profile.Name.RawData)); result.Add(new MySqlParameter("@version", (byte)profile.Version)); result.Add(new MySqlParameter("@language", (byte)profile.Language)); result.Add(new MySqlParameter("@country", profile.Country)); result.Add(new MySqlParameter("@region", profile.Region)); result.Add(new MySqlParameter("@trainer_id", profile.OT)); result.Add(new MySqlParameter("@phrase_leader", profile.PhraseLeader.Data)); result.Add(new MySqlParameter("@gender", profile.Gender)); result.Add(new MySqlParameter("@unknown2", profile.Unknown)); result.Add(new MySqlParameter("@rank", record.Rank)); result.Add(new MySqlParameter("@room", record.RoomNum)); if (!leader) { result.Add(new MySqlParameter("@phrase_challenged", record.PhraseChallenged.Data)); result.Add(new MySqlParameter("@phrase_won", record.PhraseWon.Data)); result.Add(new MySqlParameter("@phrase_lost", record.PhraseLost.Data)); result.Add(new MySqlParameter("@unknown3", record.Unknown3)); result.Add(new MySqlParameter("@unknown4", record.Unknown4 ?? new byte[5])); result.Add(new MySqlParameter("@unknown5", record.Unknown5)); result.Add(new MySqlParameter("@battles_won", record.BattlesWon)); } return result; } private List ParamsFromBattleSubwayPokemon5(BattleSubwayPokemon5 pokemon) { List result = new List(15); result.Add(new MySqlParameter("@species", pokemon.SpeciesID)); result.Add(new MySqlParameter("@form", pokemon.FormID)); result.Add(new MySqlParameter("@held_item", pokemon.HeldItemID)); result.Add(new MySqlParameter("@move1", pokemon.Moves[0].MoveID)); result.Add(new MySqlParameter("@move2", pokemon.Moves[1].MoveID)); result.Add(new MySqlParameter("@move3", pokemon.Moves[2].MoveID)); result.Add(new MySqlParameter("@move4", pokemon.Moves[3].MoveID)); result.Add(new MySqlParameter("@trainer_id", pokemon.TrainerID)); result.Add(new MySqlParameter("@personality", pokemon.Personality)); result.Add(new MySqlParameter("@ivs", pokemon.IVs.ToInt32() | (int)pokemon.IvFlags)); result.Add(new MySqlParameter("@evs", pokemon.EVs.ToArray())); result.Add(new MySqlParameter("@unknown1", pokemon.GetPpUps())); result.Add(new MySqlParameter("@language", (byte)pokemon.Language)); result.Add(new MySqlParameter("@ability", pokemon.AbilityID)); result.Add(new MySqlParameter("@happiness", pokemon.Happiness)); result.Add(new MySqlParameter("@nickname", pokemon.NicknameEncoded.RawData)); result.Add(new MySqlParameter("@unknown2", pokemon.Unknown2)); return result; } public override ulong BattleSubwayAddLeader5(BattleSubwayRecord5 record) { return WithTransaction(tran => BattleSubwayAddLeader5(tran, record)); } private ulong BattleSubwayAddLeader5(MySqlTransaction tran, BattleSubwayRecord5 record) { ulong pkey = FindBattleSubwayRecord5(tran, record, true); // Update the actual record if (pkey != 0) { List _params = ParamsFromBattleSubwayRecord5(record, true); _params.Add(new MySqlParameter("@id", pkey)); tran.ExecuteNonQuery("UPDATE GtsBattleSubwayLeaders5 SET " + "pid = @pid, Name = @name, Version = @version, " + "Language = @language, Country = @country, Region = @region, " + "TrainerID = @trainer_id, " + "PhraseLeader = @phrase_leader, Gender = @gender, Unknown2 = @unknown2, " + "ParseVersion = 1, Rank = @rank, " + "TimeUpdated = UTC_TIMESTAMP() WHERE id = @id", _params.ToArray()); } else { List _params = ParamsFromBattleSubwayRecord5(record, true); pkey = Convert.ToUInt64(tran.ExecuteScalar("INSERT INTO " + "GtsBattleSubwayLeaders5 " + "(pid, Name, Version, Language, Country, Region, TrainerID, " + "PhraseLeader, Gender, Unknown2, ParseVersion, Rank, " + "RoomNum, TimeAdded, TimeUpdated) VALUES " + "(@pid, @name, @version, @language, @country, @region, @trainer_id, " + "@phrase_leader, @gender, @unknown2, 1, @rank, " + "@room, UTC_TIMESTAMP(), UTC_TIMESTAMP()); " + "SELECT LAST_INSERT_ID()", _params.ToArray())); } return pkey; } /// /// Tries to find an existing database record for the provided player /// record. The match must be found in the same rank and room number. /// /// /// /// If true, look up against the Leaders table. /// Otherwise looks up against the opponents table. /// The match's primary key or 0 if no match is found /// private ulong FindBattleSubwayRecord5(MySqlTransaction tran, BattleSubwayRecord5 record, bool leader) { string tblName = leader ? "GtsBattleSubwayLeaders5" : "GtsBattleSubway5"; // If PID is missing, this is restored data. // We assume the original server took care of matching existing // records, so we don't allow it to match here. if (record.PID == 0) return 0; // Match normally. object oPkey = tran.ExecuteScalar("SELECT id FROM " + tblName + " WHERE pid = @pid AND RoomNum = @room AND Rank = @rank", // Only require rank to match if this is the leaderboard. new MySqlParameter("@pid", record.PID), new MySqlParameter("@rank", record.Rank), new MySqlParameter("@room", record.RoomNum)); if (oPkey == null) { BattleSubwayProfile5 profile = (BattleSubwayProfile5)record.Profile; // PID isn't found. Try to match one of Pikachu025's saved // records based on unchanging properties of the savegame. oPkey = tran.ExecuteScalar("SELECT id FROM " + tblName + " WHERE pid = 0 AND RoomNum = @room AND Rank = @rank " + // Only require rank to match if this is the leaderboard. "AND Name = @name AND Version = @version " + "AND Language = @language AND TrainerID = @trainer_id", new MySqlParameter("@rank", record.Rank), new MySqlParameter("@room", record.RoomNum), new MySqlParameter("@name", profile.Name.RawData), new MySqlParameter("@version", (byte)profile.Version), new MySqlParameter("@language", (byte)profile.Language), new MySqlParameter("@trainer_id", profile.OT) ); } // Don't need to worry about DBNull since the column is non-null. return (ulong)(oPkey ?? 0UL); } public override BattleSubwayRecord5[] BattleSubwayGetOpponents5(Pokedex.Pokedex pokedex, int pid, byte rank, byte roomNum) { return WithTransaction(tran => BattleSubwayGetOpponents5(tran, pokedex, pid, rank, roomNum)); } public BattleSubwayRecord5[] BattleSubwayGetOpponents5(MySqlTransaction tran, Pokedex.Pokedex pokedex, int pid, byte rank, byte roomNum) { List records = new List(7); List keys = new List(7); using (MySqlDataReader reader = (MySqlDataReader)tran.ExecuteReader( "SELECT id, pid, Name, " + "Version, Language, Country, Region, TrainerID, " + "PhraseLeader, Gender, Unknown2, PhraseChallenged, " + "PhraseWon, PhraseLost, Unknown3, Unknown4, Unknown5 " + "FROM GtsBattleSubway5 " + "WHERE Rank = @rank AND RoomNum = @room AND pid != @pid " + "ORDER BY Position LIMIT 7", new MySqlParameter("@rank", rank), new MySqlParameter("@room", roomNum), new MySqlParameter("@pid", pid))) { while (reader.Read()) { BattleSubwayRecord5 record = BattleSubwayRecord5FromReader(reader, pokedex); record.Party = new BattleSubwayPokemon5[3]; records.Add(record); keys.Add(reader.GetUInt64(0)); } reader.Close(); } if (records.Count == 0) return new BattleSubwayRecord5[0]; string inClause = String.Join(", ", keys.Select(i => i.ToString()).ToArray()); using (MySqlDataReader reader = (MySqlDataReader)tran.ExecuteReader("SELECT party_id, " + "Slot, Species, Form, HeldItem, Move1, Move2, Move3, Move4, " + "TrainerID, Personality, IVs, EVs, Unknown1, Language, " + "Ability, Happiness, Nickname, Unknown2 FROM GtsBattleSubwayPokemon5 " + "WHERE party_id IN (" + inClause + ")")) { while (reader.Read()) { BattleSubwayRecord5 record = records[keys.IndexOf(reader.GetUInt64(0))]; record.Party[reader.GetByte(1)] = BattleSubwayPokemon5FromReader(reader, pokedex); } reader.Close(); } return Enumerable.Reverse(records).ToArray(); } private BattleSubwayRecord5 BattleSubwayRecord5FromReader(MySqlDataReader reader, Pokedex.Pokedex pokedex) { // todo: Stop using ordinals everywhere. BattleSubwayRecord5 result = new BattleSubwayRecord5(pokedex); result.PID = reader.GetInt32(1); // this is unsustainable. What happens if I add columns to Leaders? if (reader.FieldCount > 11) result.PhraseChallenged = new TrendyPhrase5(reader.GetByteArray(11, 8)); if (reader.FieldCount > 12) result.PhraseWon = new TrendyPhrase5(reader.GetByteArray(12, 8)); if (reader.FieldCount > 13) result.PhraseLost = new TrendyPhrase5(reader.GetByteArray(13, 8)); if (reader.FieldCount > 14) result.Unknown3 = reader.GetUInt16(14); if (reader.FieldCount > 15 && !reader.IsDBNull(15)) result.Unknown4 = reader.GetByteArray(15, 5); if (reader.FieldCount > 16) result.Unknown5 = reader.GetUInt64(16); BattleSubwayProfile5 profile = new BattleSubwayProfile5(); profile.Name = new EncodedString5(reader.GetByteArray(2, 16)); profile.Version = (Versions)reader.GetByte(3); profile.Language = (Languages)reader.GetByte(4); profile.Country = reader.GetByte(5); profile.Region = reader.GetByte(6); profile.OT = reader.GetUInt32(7); profile.PhraseLeader = new TrendyPhrase5(reader.GetByteArray(8, 8)); profile.Gender = reader.GetByte(9); profile.Unknown = reader.GetByte(10); result.Profile = profile; return result; } private BattleSubwayPokemon5 BattleSubwayPokemon5FromReader(MySqlDataReader reader, Pokedex.Pokedex pokedex) { ushort? speciesId = DatabaseExtender.Cast(reader["Species"]); ushort? formId = DatabaseExtender.Cast(reader["Form"]); return new BattleSubwayPokemon5(pokedex, (int)speciesId, (byte)formId, DatabaseExtender.Cast(reader["HeldItem"]), DatabaseExtender.Cast(reader["Move1"]), DatabaseExtender.Cast(reader["Move2"]), DatabaseExtender.Cast(reader["Move3"]), DatabaseExtender.Cast(reader["Move4"]), DatabaseExtender.Cast(reader["TrainerID"]), DatabaseExtender.Cast(reader["Personality"]), DatabaseExtender.Cast(reader["IVs"]), DatabaseExtender.Cast(reader["EVs"]), DatabaseExtender.Cast(reader["Unknown1"]), (Languages)DatabaseExtender.Cast(reader["Language"]), DatabaseExtender.Cast(reader["Ability"]), DatabaseExtender.Cast(reader["Happiness"]), new EncodedString5(DatabaseExtender.Cast(reader["Nickname"]), 0, 22), DatabaseExtender.Cast(reader["Unknown2"]) ); } public override BattleSubwayProfile5[] BattleSubwayGetLeaders5(Pokedex.Pokedex pokedex, byte rank, byte roomNum) { return WithTransaction(tran => BattleSubwayGetLeaders5(tran, pokedex, rank, roomNum)); } public BattleSubwayProfile5[] BattleSubwayGetLeaders5(MySqlTransaction tran, Pokedex.Pokedex pokedex, byte rank, byte roomNum) { List profiles = new List(30); using (MySqlDataReader reader = (MySqlDataReader)tran.ExecuteReader( "SELECT id, pid, Name, " + "Version, Language, Country, Region, TrainerID, " + "PhraseLeader, Gender, Unknown2 FROM GtsBattleSubwayLeaders5 " + "WHERE Rank = @rank AND RoomNum = @room " + "ORDER BY TimeUpdated DESC, id LIMIT 30", new MySqlParameter("@rank", rank), new MySqlParameter("@room", roomNum))) { while (reader.Read()) profiles.Add((BattleSubwayProfile5)BattleSubwayRecord5FromReader(reader, pokedex).Profile); reader.Close(); } return profiles.ToArray(); } #endregion #region Other Gamestats 5 public override bool GamestatsSetProfile5(TrainerProfile5 profile) { return WithTransaction(tran => GamestatsSetProfile5(tran, profile)); } public bool GamestatsSetProfile5(MySqlTransaction tran, TrainerProfile5 profile) { // Although GenV doesn't actually support email notifications, // we're using the same database structure here as for GenIV // as a rule of least surprise and maybe in the hopes of // removing this code duplication eventually. if (profile.Data.Length != 100) throw new FormatException("Profile data must be 100 bytes."); bool exists = Convert.ToSByte(tran.ExecuteScalar("SELECT EXISTS(SELECT * FROM GtsProfiles5 WHERE pid = @pid)", new MySqlParameter("@pid", profile.PID))) != 0; MySqlParameter[] _params = new MySqlParameter[]{ new MySqlParameter("@pid", profile.PID), new MySqlParameter("@data", profile.Data), new MySqlParameter("@version", (byte)profile.Version), new MySqlParameter("@language", (byte)profile.Language), new MySqlParameter("@country", profile.Country), new MySqlParameter("@region", profile.Region), new MySqlParameter("@ot", profile.OT), new MySqlParameter("@name", profile.Name.RawData), new MySqlParameter("@mac_address", profile.MacAddress), new MySqlParameter("@email", profile.Email), new MySqlParameter("@has_notifications", profile.HasNotifications), new MySqlParameter("@client_secret", profile.ClientSecret), new MySqlParameter("@mail_secret", profile.MailSecret), new MySqlParameter("@ip_address", profile.IpAddress) }; if (exists) { return tran.ExecuteNonQuery("UPDATE GtsProfiles5 SET Data = @data, " + "Version = @version, Language = @language, Country = @country, " + "Region = @region, OT = @ot, Name = @name, MacAddress = @mac_address, " + "Email = @email, HasNotifications = @has_notifications, " + "ClientSecret = @client_secret, MailSecret = @mail_secret, " + "IpAddress = @ip_address, ParseVersion = 2, TimeUpdated = UTC_TIMESTAMP() " + "WHERE pid = @pid", _params) > 0; } else { return tran.ExecuteNonQuery("INSERT INTO GtsProfiles5 " + "(pid, Data, Version, Language, Country, Region, OT, Name, " + "MacAddress, Email, HasNotifications, ClientSecret, MailSecret, " + "IpAddress, ParseVersion, TimeAdded, TimeUpdated) VALUES " + "(@pid, @data, @version, @language, @country, @region, @ot, " + "@name, @mac_address, @email, @has_notifications, " + "@client_secret, @mail_secret, @ip_address, 2, UTC_TIMESTAMP(), UTC_TIMESTAMP())", _params) > 0; } } public override TrainerProfile5 GamestatsGetProfile5(int pid) { return WithTransaction(tran => GamestatsGetProfile5(tran, pid)); } public TrainerProfile5 GamestatsGetProfile5(MySqlTransaction tran, int pid) { DataTable result = tran.ExecuteDataTable("SELECT Data, IpAddress FROM GtsProfiles4 WHERE pid = @pid", new MySqlParameter("@pid", pid)); if (result.Rows.Count == 0) return null; DataRow row = result.Rows[0]; byte[] data = DatabaseExtender.Cast(row["Data"]); if (data == null) return null; return new TrainerProfile5(pid, data, DatabaseExtender.Cast(row["IpAddress"])); } #endregion #region Global Terminal 4 public ulong DressupUpload4(MySqlTransaction tran, DressupRecord4 record) { if (record.Data.Length != 224) throw new ArgumentException("Dressup data must be 224 bytes."); bool exists = Convert.ToSByte(tran.ExecuteScalar("SELECT EXISTS(SELECT * FROM TerminalDressup4 WHERE md5 = unhex(md5(@data)) AND Data = @data)", new MySqlParameter("@data", record.Data))) != 0; if (exists) return 0; if (record.SerialNumber == 0) { ulong serial = Convert.ToUInt64(tran.ExecuteScalar("INSERT INTO TerminalDressup4 (pid, " + "Data, md5, TimeAdded, ParseVersion, Species) VALUES (@pid, @data, " + "unhex(md5(@data)), UTC_TIMESTAMP(), 1, @species); SELECT LAST_INSERT_ID()", new MySqlParameter("@pid", record.PID), new MySqlParameter("@data", record.Data), new MySqlParameter("@species", record.Species))); return serial; } else { int rows = tran.ExecuteNonQuery("INSERT INTO TerminalDressup4 (pid, SerialNumber, " + "Data, md5, TimeAdded, ParseVersion, Species) VALUES (@pid, @serial, @data, " + "unhex(md5(@data)), UTC_TIMESTAMP(), 1, @species)", new MySqlParameter("@pid", record.PID), new MySqlParameter("@serial", record.SerialNumber), new MySqlParameter("@data", record.Data), new MySqlParameter("@species", record.Species)); return rows > 0 ? record.SerialNumber : 0; } } public override ulong DressupUpload4(DressupRecord4 record) { if (record.Data.Length != 224) throw new ArgumentException("Dressup data must be 224 bytes."); return WithTransaction(tran => DressupUpload4(tran, record)); } public DressupRecord4[] DressupSearch4(MySqlTransaction tran, ushort species, int count) { List results = new List(count); using (MySqlDataReader reader = (MySqlDataReader)tran.ExecuteReader("SELECT pid, " + "SerialNumber, Data FROM TerminalDressup4 WHERE Species = @species " + "ORDER BY TimeAdded DESC LIMIT @count", new MySqlParameter("@species", species), new MySqlParameter("@count", count))) { while (reader.Read()) results.Add(Dressup4FromReader(reader)); reader.Close(); } return results.ToArray(); } public override DressupRecord4[] DressupSearch4(ushort species, int count) { return WithTransaction(tran => DressupSearch4(tran, species, count)); } private DressupRecord4 Dressup4FromReader(MySqlDataReader reader) { // xxx: don't use ordinals byte[] data = new byte[224]; reader.GetBytes(2, 0, data, 0, 224); return new DressupRecord4(reader.GetInt32(0), reader.GetUInt64(1), data); } public ulong BoxUpload4(MySqlTransaction tran, BoxRecord4 record) { if (record.Data.Length != 540) throw new ArgumentException("Box data must be 540 bytes."); bool exists = Convert.ToSByte(tran.ExecuteScalar("SELECT EXISTS(SELECT * FROM TerminalBoxes4 WHERE md5 = unhex(md5(@data)) AND Data = @data)", new MySqlParameter("@data", record.Data))) != 0; if (exists) return 0; // xxx: it would be better to return a null ulong ? than 0 if (record.SerialNumber == 0) { ulong serial = Convert.ToUInt64(tran.ExecuteScalar("INSERT INTO TerminalBoxes4 (pid, " + "Data, md5, TimeAdded, ParseVersion, Label) VALUES (@pid, @data, " + "unhex(md5(@data)), UTC_TIMESTAMP(), 1, @label); SELECT LAST_INSERT_ID()", new MySqlParameter("@pid", record.PID), new MySqlParameter("@data", record.Data), new MySqlParameter("@label", (int)record.Label))); return serial; } else { int rows = tran.ExecuteNonQuery("INSERT INTO TerminalBoxes4 (pid, SerialNumber, " + "Data, md5, TimeAdded, ParseVersion, Label) VALUES (@pid, @serial, @data, " + "unhex(md5(@data)), UTC_TIMESTAMP(), 1, @label)", new MySqlParameter("@pid", record.PID), new MySqlParameter("@serial", record.SerialNumber), new MySqlParameter("@data", record.Data), new MySqlParameter("@label", (int)record.Label)); return rows > 0 ? record.SerialNumber : 0; } } public override ulong BoxUpload4(BoxRecord4 record) { if (record.Data.Length != 540) throw new ArgumentException("Box data must be 540 bytes."); return WithTransaction(tran => BoxUpload4(tran, record)); } public BoxRecord4[] BoxSearch4(MySqlTransaction tran, BoxLabels4 label, int count) { List results = new List(count); using (MySqlDataReader reader = (MySqlDataReader)tran.ExecuteReader("SELECT pid, " + "Label, SerialNumber, Data FROM TerminalBoxes4 WHERE Label = @label " + "ORDER BY TimeAdded DESC LIMIT @count", new MySqlParameter("@label", (int)label), new MySqlParameter("@count", count))) { while (reader.Read()) results.Add(Box4FromReader(reader)); reader.Close(); } return results.ToArray(); } public override BoxRecord4[] BoxSearch4(BoxLabels4 label, int count) { return WithTransaction(tran => BoxSearch4(tran, label, count)); } private BoxRecord4 Box4FromReader(MySqlDataReader reader) { // xxx: don't use ordinals byte[] data = new byte[540]; reader.GetBytes(3, 0, data, 0, 540); return new BoxRecord4(reader.GetInt32(0), (BoxLabels4)reader.GetInt32(1), reader.GetUInt64(2), data); } public ulong BattleVideoUpload4(MySqlTransaction tran, BattleVideoRecord4 record) { if (record.Data.Length != 7272) throw new ArgumentException(); if (record.Header.Data.Length != 228) throw new ArgumentException(); bool exists = Convert.ToSByte(tran.ExecuteScalar("SELECT EXISTS(SELECT * " + "FROM TerminalBattleVideos4 WHERE md5 = unhex(md5(CONCAT(@header, @data))) " + "AND Data = @data AND Header = @header)", new MySqlParameter("@header", record.Header.Data), new MySqlParameter("@data", record.Data))) != 0; if (exists) return 0; DateTime now = DateTime.UtcNow; DateTime hypeTime = GetActiveHypeDate(now); double adjustedHype = HypeDecay(HYPE_NEW_VIDEO, now, hypeTime); ulong serial; if (record.SerialNumber == 0) { ulong key = Convert.ToUInt64(tran.ExecuteScalar("INSERT INTO TerminalBattleVideos4 " + "(pid, Header, Data, md5, TimeAdded, ParseVersion, Streak, TrainerName, " + "Metagame, Country, Region, Hype, HypeTimestamp) " + "VALUES (@pid, @header, @data, unhex(md5(CONCAT(@header, @data))), " + "UTC_TIMESTAMP(), 1, @streak, @trainer, @metagame, @country, @region, @hype, @hype_timestamp); " + "SELECT LAST_INSERT_ID()", new MySqlParameter("@pid", record.PID), new MySqlParameter("@header", record.Header.Data), new MySqlParameter("@data", record.Data), new MySqlParameter("@streak", record.Header.Streak), new MySqlParameter("@trainer", record.Header.TrainerName), new MySqlParameter("@metagame", (byte)record.Header.Metagame), new MySqlParameter("@country", (byte)record.Header.Country), new MySqlParameter("@region", (byte)record.Header.Region), new MySqlParameter("@hype", adjustedHype), new MySqlParameter("@hype_timestamp", hypeTime) )); serial = BattleVideoHeader4.KeyToSerial(key); tran.ExecuteNonQuery("UPDATE TerminalBattleVideos4 SET " + "SerialNumber = @serial WHERE id = @key", new MySqlParameter("@serial", serial), new MySqlParameter("@key", key)); // todo: make a proc to insert both video and party. InsertBattleVideoParty4(record.Header, key, tran); } else { ulong key = BattleVideoHeader4.SerialToKey(record.SerialNumber); int rows = tran.ExecuteNonQuery("INSERT INTO TerminalBattleVideos4 " + "(id, pid, SerialNumber, Header, Data, md5, TimeAdded, " + "ParseVersion, Streak, TrainerName, " + "Metagame, Country, Region, Hype, HypeTimestamp) " + "VALUES (@key, @pid, @serial, @header, @data, " + "unhex(md5(CONCAT(@header, @data))), " + "UTC_TIMESTAMP(), 1, @streak, @trainer, @metagame, @country, @region, @hype, @hype_timestamp)", new MySqlParameter("@key", key), new MySqlParameter("@pid", record.PID), new MySqlParameter("@serial", record.SerialNumber), new MySqlParameter("@header", record.Header.Data), new MySqlParameter("@data", record.Data), new MySqlParameter("@streak", record.Header.Streak), new MySqlParameter("@trainer", record.Header.TrainerName), new MySqlParameter("@metagame", (byte)record.Header.Metagame), new MySqlParameter("@country", (byte)record.Header.Country), new MySqlParameter("@region", (byte)record.Header.Region), new MySqlParameter("@hype", adjustedHype), new MySqlParameter("@hype_timestamp", hypeTime) ); if (rows == 0) return 0; serial = record.SerialNumber; InsertBattleVideoParty4(record.Header, key, tran); } BattleVideoUpdateHypeTimes4(tran, hypeTime); return serial; } public override ulong BattleVideoUpload4(BattleVideoRecord4 record) { if (record.Data.Length != 7272) throw new ArgumentException(); if (record.Header.Data.Length != 228) throw new ArgumentException(); return WithTransaction(tran => BattleVideoUpload4(tran, record)); } private void InsertBattleVideoParty4(BattleVideoHeader4 header, ulong key, MySqlTransaction tran) { MySqlCommand cmd = new MySqlCommand("INSERT INTO " + "TerminalBattleVideoPokemon4 (video_id, Slot, Species) VALUES " + "(@key, @slot, @species)", tran.Connection, tran); cmd.Parameters.Add("@key", MySqlDbType.UInt64).Value = key; cmd.Parameters.Add("@slot", MySqlDbType.UByte); cmd.Parameters.Add("@species", MySqlDbType.UInt16); ushort[] party = header.Party; for (byte x = 0; x < 12; x++) { ushort species = party[x]; if (species == 0) continue; cmd.Parameters["@slot"].Value = x; cmd.Parameters["@species"].Value = species; cmd.ExecuteNonQuery(); } } private void BattleVideoUpdateHypeTimes(MySqlTransaction tran, string tableName, DateTime hypeTime) { // todo: run this less often by caching the HypeTimestamp somewhere // run it only once a week // use cached timestamp for insertions/updates too // common case: HypeTimestamp is in the past and needs to be updated and decay applied. tran.ExecuteNonQuery("UPDATE " + tableName + " " + "SET Hype = Hype / (1 << FLOOR(DATEDIFF(@hypetime, HypeTimestamp) / @decay)), HypeTimestamp = @hypetime " + "WHERE HypeTimestamp < @hypetime", new MySqlParameter("@hypetime", hypeTime), new MySqlParameter("@decay", HYPE_DECAY_DAYS)); // unusual case: HypeTimestamp is in the future and reverse decay needs to be applied. tran.ExecuteNonQuery("UPDATE " + tableName + " " + "SET Hype = Hype * (1 << FLOOR(DATEDIFF(HypeTimestamp, @hypetime) / @decay)), HypeTimestamp = @hypetime " + "WHERE HypeTimestamp > @hypetime", new MySqlParameter("@hypetime", hypeTime), new MySqlParameter("@decay", HYPE_DECAY_DAYS)); } private void BattleVideoUpdateHypeTimes4(MySqlTransaction tran, DateTime hypeTime) { BattleVideoUpdateHypeTimes(tran, "TerminalBattleVideos4", hypeTime); } public BattleVideoHeader4[] BattleVideoSearch4(MySqlTransaction tran, ushort species, BattleVideoRankings4 ranking, BattleVideoMetagames4 metagame, byte country, byte region, int count) { List _params = new List(); string where = ""; string sort = ""; bool hasSearch = false; if (ranking == BattleVideoRankings4.None) { if (species != 0xffff) { where += " WHERE EXISTS(SELECT * FROM TerminalBattleVideoPokemon4 " + "WHERE video_id = TerminalBattleVideos4.id AND Species = @species)"; _params.Add(new MySqlParameter("@species", species)); hasSearch = true; } if (metagame == BattleVideoMetagames4.SearchColosseumSingleNoRestrictions) metagame = BattleVideoMetagames4.ColosseumSingleNoRestrictions; if (metagame == BattleVideoMetagames4.SearchColosseumDoubleNoRestrictions) metagame = BattleVideoMetagames4.ColosseumDoubleNoRestrictions; if (metagame == BattleVideoMetagames4.SearchColosseumSingleCupMatch) { where += (hasSearch ? " AND " : " WHERE ") + "Metagame BETWEEN 1 AND 6"; hasSearch = true; } else if (metagame == BattleVideoMetagames4.SearchColosseumDoubleCupMatch) { where += (hasSearch ? " AND " : " WHERE ") + "Metagame BETWEEN 8 AND 13"; hasSearch = true; } else if (metagame == BattleVideoMetagames4.SearchNoBattleFrontier) { where += (hasSearch ? " AND " : " WHERE ") + "Metagame BETWEEN 0 AND 14"; hasSearch = true; } else if (metagame != BattleVideoMetagames4.SearchLatest30) { where += (hasSearch ? " AND " : " WHERE ") + "Metagame = @metagame"; _params.Add(new MySqlParameter("@metagame", (byte)metagame)); hasSearch = true; } if (country != 0xff) { where += (hasSearch ? " AND " : " WHERE ") + "Country = @country"; _params.Add(new MySqlParameter("@country", country)); hasSearch = true; } if (region != 0xff) { where += (hasSearch ? " AND " : " WHERE ") + "Region = @region"; _params.Add(new MySqlParameter("@region", region)); } sort = " ORDER BY TimeAdded DESC, id DESC"; } else if (ranking == BattleVideoRankings4.Colosseum) { where = " WHERE Metagame BETWEEN 0 AND 14"; sort = " ORDER BY Hype DESC, TimeAdded DESC, id DESC"; } else if (ranking == BattleVideoRankings4.BattleFrontier) { where = " WHERE NOT (Metagame BETWEEN 0 AND 14)"; sort = " ORDER BY Hype DESC, TimeAdded DESC, id DESC"; } else { sort = " ORDER BY TimeAdded DESC, id DESC"; } _params.Add(new MySqlParameter("@count", count)); List results = new List(count); using (MySqlDataReader reader = (MySqlDataReader)tran.ExecuteReader("SELECT pid, " + "SerialNumber, Header FROM TerminalBattleVideos4" + where + sort + " LIMIT @count", _params.ToArray())) { while (reader.Read()) results.Add(BattleVideoHeader4FromReader(reader)); reader.Close(); } return results.ToArray(); } public override BattleVideoHeader4[] BattleVideoSearch4(ushort species, BattleVideoRankings4 ranking, BattleVideoMetagames4 metagame, byte country, byte region, int count) { return WithTransaction(tran => BattleVideoSearch4(tran, species, ranking, metagame, country, region, count)); } private BattleVideoHeader4 BattleVideoHeader4FromReader(MySqlDataReader reader) { byte[] data = new byte[228]; reader.GetBytes(2, 0, data, 0, 228); return new BattleVideoHeader4(reader.GetInt32(0), reader.GetUInt64(1), data); } public MySqlDataReader BattleVideoGet(MySqlTransaction tran, string tableName, ulong serial, bool incrementViews) { string update; MySqlParameter[] _params; if (incrementViews) { DateTime now = DateTime.UtcNow; DateTime hypeTime = GetActiveHypeDate(now); double hype = HypeDecay(HYPE_WATCHED_VIDEO, now, hypeTime); BattleVideoUpdateHypeTimes(tran, tableName, hypeTime); update = "UPDATE " + tableName + " " + "SET Views = Views + 1, Hype = Hype + @hype WHERE SerialNumber = @serial; "; _params = new[] { new MySqlParameter("@hype", hype), new MySqlParameter("@hype_timestamp", hypeTime), new MySqlParameter("@serial", serial) }; } else { update = ""; _params = new[] { new MySqlParameter("@serial", serial) }; } return (MySqlDataReader)tran.ExecuteReader(update + "SELECT pid, " + "SerialNumber, Header, Data FROM " + tableName + " " + "WHERE SerialNumber = @serial", _params); } public BattleVideoRecord4 BattleVideoGet4(MySqlTransaction tran, ulong serial, bool incrementViews = false) { BattleVideoRecord4 result = null; using (var reader = BattleVideoGet(tran, "TerminalBattleVideos4", serial, incrementViews)) { if (reader.Read()) result = BattleVideo4FromReader(reader); } return result; } public override BattleVideoRecord4 BattleVideoGet4(ulong serial, bool incrementViews = false) { return WithTransaction(tran => BattleVideoGet4(tran, serial, incrementViews)); } private BattleVideoRecord4 BattleVideo4FromReader(MySqlDataReader reader) { byte[] data = new byte[7272]; reader.GetBytes(3, 0, data, 0, 7272); BattleVideoHeader4 header = BattleVideoHeader4FromReader(reader); return new BattleVideoRecord4(header.PID, header.SerialNumber, header, data); } public bool BattleVideoFlagSaved4(MySqlTransaction tran, ulong serial) { DateTime now = DateTime.UtcNow; DateTime hypeTime = GetActiveHypeDate(now); double hype = HypeDecay(HYPE_SAVED_VIDEO, now, hypeTime); BattleVideoUpdateHypeTimes4(tran, hypeTime); int results = tran.ExecuteNonQuery("UPDATE TerminalBattleVideos4 " + "SET Saves = Saves + 1, Hype = Hype + @hype WHERE SerialNumber = @serial", new MySqlParameter("@hype", hype), new MySqlParameter("@hype_timestamp", hypeTime), new MySqlParameter("@serial", serial)); return results > 0; } public override bool BattleVideoFlagSaved4(ulong serial) { return WithTransaction(tran => BattleVideoFlagSaved4(tran, serial)); } public ulong BattleVideoCount4(MySqlTransaction tran) { return Convert.ToUInt64(tran.ExecuteScalar("SELECT Count(*) FROM TerminalBattleVideos4")); } public override ulong BattleVideoCount4() { return WithTransaction(tran => BattleVideoCount4(tran)); } public override bool TrainerRankingsPerformRollover() { return WithTransaction(tran => TrainerRankingsPerformRollover(tran)); } public bool TrainerRankingsPerformRollover(MySqlTransaction tran) { // Use one single date for this transaction to avoid any possible inconsistencies. // An inconsistency here could lead to creating an extra leaderboard for the past week. DateTime now = DateTime.UtcNow; // 1. Check if current leaderboard is still valid. // It's best to just check that a future end date is in existence. // Adding more checks, e.g. start < now < end, could allow things to get funny if the clock changes. // Just use the futuremost leaderboard as the current one, and start a new one if we think that leaderboard is in the past. DataTable tblLastReport = tran.ExecuteDataTable( "SELECT report_id, StartDate, EndDate FROM pkmncf_terminal_trainer_rankings_reports ORDER BY EndDate DESC LIMIT 1", new MySqlParameter("@now", now)); if (tblLastReport.Rows.Count > 0) { DataRow rowLastReport = tblLastReport.Rows[0]; if (DatabaseExtender.Cast(rowLastReport["EndDate"]) > now) return false; // found leaderboard still good int lastReportId = DatabaseExtender.Cast(rowLastReport["report_id"]); // update leaderboard aggregates for the most recently concluded leaderboard tran.ExecuteProcedure("pkmncf_terminal_proc_create_leaderboards_for_report", new MySqlParameter("_report_id", lastReportId)); } // 2. Pick new record-types, preferring ones which haven't been used in a while. DataTable tblRecordTypes = tran.ExecuteDataTable("SELECT RecordType, MAX(StartDate) AS LastUsed " + "FROM ( " + "SELECT RecordType1 AS RecordType, StartDate FROM pkmncf_terminal_trainer_rankings_reports " + "UNION " + "SELECT RecordType2 AS RecordType, StartDate FROM pkmncf_terminal_trainer_rankings_reports " + "UNION " + "SELECT RecordType3 AS RecordType, StartDate FROM pkmncf_terminal_trainer_rankings_reports " + ") AS tbl4 " + "GROUP BY RecordType"); TrainerRankingsRecordTypes[] enumValues = (TrainerRankingsRecordTypes[])Enum.GetValues(typeof(TrainerRankingsRecordTypes)); // outer join enum values to include those recordtypes that have never been used var combined = enumValues .GroupJoin(tblRecordTypes.AsEnumerable(), i => i, row => (TrainerRankingsRecordTypes)DatabaseExtender.Cast(row["RecordType"]), (i, rows) => new { RecordType = i, LastUsed = rows.Count() == 0 ? DateTime.MinValue : DatabaseExtender.Cast(rows.First()["LastUsed"]) } ) .OrderBy(r => r.LastUsed).ToList(); List chosen = new List(3); Random rand = new Random(); // todo: use better rng here. Maybe when the framework gets good RNGs // pick a random sampling of 3 recordtypes near the start of the list (oldest) but not always just the first 3 for a little randomness but not too much: for (int i = 0; i < 3; i++) { // here we do a kind of "itunes shuffle" type algorithm where // we cycle through recordtypes but vary the order a little bit // each time. // We do this by choosing from the recordypes in the bottom 10% // according to last used date and iterating DateTime cutoff = DateLerp(combined[0].LastUsed, combined[combined.Count - 1].LastUsed, 0.1); int acceptableCount = combined.Count(row => row.LastUsed <= cutoff); // xxx: can do faster since we know this is sorted int chosenIndex = rand.Next(acceptableCount); chosen.Add(combined[chosenIndex].RecordType); combined.RemoveAt(chosenIndex); } // 3. Init a new report. // Note that if more than a whole week has passed since a visit, go ahead and skip the blank week(s). It's a little white lie but makes the data look more presentable than a bunch of 0s. DateTime startDate = now.Date.AddDays(-(int)now.Date.DayOfWeek); // DayOfWeek zero-based starting on sunday DateTime endDate = startDate.AddDays(7); tran.ExecuteNonQuery("INSERT INTO pkmncf_terminal_trainer_rankings_reports " + "(StartDate, EndDate, RecordType1, RecordType2, RecordType3) VALUES " + "(@start_date, @end_date, @record_type1, @record_type2, @record_type3)", new MySqlParameter("@start_date", startDate), new MySqlParameter("@end_date", endDate), new MySqlParameter("@record_type1", chosen[0]), new MySqlParameter("@record_type2", chosen[1]), new MySqlParameter("@record_type3", chosen[2])); return true; } public override IList TrainerRankingsGetActiveRecordTypes() { return WithTransaction(tran => TrainerRankingsGetActiveRecordTypes(tran)); } public IList TrainerRankingsGetActiveRecordTypes(MySqlTransaction tran) { DateTime now = DateTime.UtcNow; DataTable tbl = tran.ExecuteDataTable( "SELECT RecordType1, RecordType2, RecordType3 FROM pkmncf_terminal_trainer_rankings_reports ORDER BY EndDate DESC LIMIT 1", new MySqlParameter("@now", now)); if (tbl.Rows.Count == 0) return new List(); DataRow row = tbl.Rows[0]; return new List() { (TrainerRankingsRecordTypes)DatabaseExtender.Cast(row["RecordType1"]), (TrainerRankingsRecordTypes)DatabaseExtender.Cast(row["RecordType2"]), (TrainerRankingsRecordTypes)DatabaseExtender.Cast(row["RecordType3"]), }; } public override void TrainerRankingsSubmit(TrainerRankingsSubmission submission) { WithTransaction(tran => TrainerRankingsSubmit(tran, submission)); } public void TrainerRankingsSubmit(MySqlTransaction tran, TrainerRankingsSubmission submission) { tran.ExecuteNonQuery("IF (SELECT EXISTS(SELECT * FROM pkmncf_terminal_trainer_rankings_teams WHERE pid = @pid)) THEN " + "UPDATE pkmncf_terminal_trainer_rankings_teams SET " + "TrainerClass = @trainer_class, BirthMonth = @birth_month, " + "FavouritePokemon = @favourite_pokemon, " + "Unknown1 = @unknown1, Unknown2 = @unknown2, " + "Unknown3 = @unknown3, LastUpdated = UTC_TIMESTAMP() " + "WHERE pid = @pid; " + "ELSE " + "INSERT INTO pkmncf_terminal_trainer_rankings_teams " + "(pid, TrainerClass, BirthMonth, FavouritePokemon, Unknown1, Unknown2, Unknown3, LastUpdated) " + "VALUES (@pid, @trainer_class, @birth_month, @favourite_pokemon, @unknown1, @unknown2, @unknown3, UTC_TIMESTAMP()); " + "END IF;", new MySqlParameter("@pid", submission.PID), new MySqlParameter("@trainer_class", submission.TrainerClass), new MySqlParameter("@birth_month", submission.BirthMonth), new MySqlParameter("@favourite_pokemon", submission.FavouritePokemon), new MySqlParameter("@unknown1", submission.Unknown1), new MySqlParameter("@unknown2", submission.Unknown2), new MySqlParameter("@unknown3", submission.Unknown3) ); foreach (var entry in submission.Entries) { tran.ExecuteNonQuery("DELETE FROM pkmncf_terminal_trainer_rankings_records WHERE pid = @pid AND RecordType = @record_type; " + "INSERT INTO pkmncf_terminal_trainer_rankings_records (pid, RecordType, Score, LastUpdated) " + "VALUES (@pid, @record_type, @score, UTC_TIMESTAMP())", new MySqlParameter("@pid", submission.PID), new MySqlParameter("@record_type", entry.RecordType), new MySqlParameter("@score", entry.Score)); } } public override TrainerRankingsReport[] TrainerRankingsGetReport(DateTime start, DateTime end, int limit) { return WithTransaction(tran => TrainerRankingsGetReport(tran, start, end, limit)); } public TrainerRankingsReport[] TrainerRankingsGetReport(MySqlTransaction tran, DateTime start, DateTime end, int limit) { DataTable tblReports = tran.ExecuteDataTable( "SELECT report_id, StartDate, EndDate, RecordType1, RecordType2, RecordType3 " + "FROM pkmncf_terminal_trainer_rankings_reports " + "WHERE EndDate >= @start_date AND StartDate <= @end_date " + "ORDER BY StartDate DESC" + (limit > 0 ? " LIMIT @limit" : ""), new MySqlParameter("@start_date", start), new MySqlParameter("@end_date", end), new MySqlParameter("@limit", limit)); var result = new TrainerRankingsReport[tblReports.Rows.Count]; for (int res = 0; res < result.Length; res++) { DataRow row = tblReports.Rows[res]; var groups = new TrainerRankingsLeaderboardGroup[3]; var groupCols = new[] { "RecordType1", "RecordType2", "RecordType3" }; var reportId = DatabaseExtender.Cast(row["report_id"]); for (int grp = 0; grp < 3; grp++) { var recordType = (TrainerRankingsRecordTypes)DatabaseExtender.Cast(row[groupCols[grp]]); groups[grp] = new TrainerRankingsLeaderboardGroup ( recordType, GetSpecificLeaderboard(tran, reportId, recordType, TrainerRankingsTeamCategories.TrainerClass), GetSpecificLeaderboard(tran, reportId, recordType, TrainerRankingsTeamCategories.BirthMonth), GetSpecificLeaderboard(tran, reportId, recordType, TrainerRankingsTeamCategories.FavouritePokemon) ); } result[res] = new TrainerRankingsReport(DatabaseExtender.Cast(row["StartDate"]), DatabaseExtender.Cast(row["EndDate"]), groups); } return result; } private TrainerRankingsLeaderboard GetSpecificLeaderboard(MySqlTransaction tran, int reportId, TrainerRankingsRecordTypes recordType, TrainerRankingsTeamCategories teamCategory) { string tableName, teamColumnName, teamBetween; switch (teamCategory) { case TrainerRankingsTeamCategories.TrainerClass: tableName = "pkmncf_terminal_trainer_rankings_leaderboards_class"; teamColumnName = "TrainerClass"; teamBetween = "TrainerClass BETWEEN 0 and 16"; break; case TrainerRankingsTeamCategories.BirthMonth: tableName = "pkmncf_terminal_trainer_rankings_leaderboards_month"; teamColumnName = "Month"; teamBetween = "Month BETWEEN 1 and 12"; break; case TrainerRankingsTeamCategories.FavouritePokemon: tableName = "pkmncf_terminal_trainer_rankings_leaderboards_pokemon"; teamColumnName = "pokemon_id"; teamBetween = "pokemon_id BETWEEN 1 and 493"; break; default: throw new ArgumentOutOfRangeException("teamCategory"); } var tblLeaderboard = tran.ExecuteDataTable("SELECT " + teamColumnName + " AS Team, Score FROM " + tableName + " WHERE report_id = @report_id AND RecordType = @record_type AND " + teamBetween + " ORDER BY Score DESC", new MySqlParameter("@report_id", reportId), new MySqlParameter("@record_type", recordType)); var entries = tblLeaderboard.AsEnumerable() .Select(rowEntry => new TrainerRankingsLeaderboardEntry( DatabaseExtender.Cast(rowEntry["Team"]), DatabaseExtender.Cast(rowEntry["Score"]))).ToArray(); return new TrainerRankingsLeaderboard(teamCategory, entries); } public override TrainerRankingsReport TrainerRankingsGetPendingReport() { return WithTransaction(tran => TrainerRankingsGetPendingReport(tran)); } public TrainerRankingsReport TrainerRankingsGetPendingReport(MySqlTransaction tran) { DataTable tblReports = tran.ExecuteDataTable( "SELECT report_id, StartDate, EndDate, RecordType1, RecordType2, RecordType3 " + "FROM pkmncf_terminal_trainer_rankings_reports " + "ORDER BY StartDate DESC LIMIT 1"); if (tblReports.Rows.Count < 1) return null; DataRow row = tblReports.Rows[0]; var groups = new TrainerRankingsLeaderboardGroup[3]; var groupCols = new[] { "RecordType1", "RecordType2", "RecordType3" }; var startDate = DatabaseExtender.Cast(row["StartDate"]); for (int grp = 0; grp < 3; grp++) { var recordType = (TrainerRankingsRecordTypes)DatabaseExtender.Cast(row[groupCols[grp]]); groups[grp] = new TrainerRankingsLeaderboardGroup ( recordType, GetSpecificPendingLeaderboard(tran, recordType, TrainerRankingsTeamCategories.TrainerClass, startDate), GetSpecificPendingLeaderboard(tran, recordType, TrainerRankingsTeamCategories.BirthMonth, startDate), GetSpecificPendingLeaderboard(tran, recordType, TrainerRankingsTeamCategories.FavouritePokemon, startDate) ); } return new TrainerRankingsReport(startDate, DatabaseExtender.Cast(row["EndDate"]), groups); } private TrainerRankingsLeaderboard GetSpecificPendingLeaderboard(MySqlTransaction tran, TrainerRankingsRecordTypes recordType, TrainerRankingsTeamCategories teamCategory, DateTime startDate) { string teamColumnName, teamBetween; // different column names than above... switch (teamCategory) { case TrainerRankingsTeamCategories.TrainerClass: teamColumnName = "TrainerClass"; teamBetween = "TrainerClass BETWEEN 0 and 16"; break; case TrainerRankingsTeamCategories.BirthMonth: teamColumnName = "BirthMonth"; teamBetween = "BirthMonth BETWEEN 1 and 12"; break; case TrainerRankingsTeamCategories.FavouritePokemon: teamColumnName = "FavouritePokemon"; teamBetween = "FavouritePokemon BETWEEN 1 and 493"; break; default: throw new ArgumentOutOfRangeException("teamCategory"); } var tblLeaderboard = tran.ExecuteDataTable("SELECT " + teamColumnName + " AS Team, SUM(Score) AS Score " + "FROM pkmncf_terminal_trainer_rankings_records " + "INNER JOIN pkmncf_terminal_trainer_rankings_teams " + "ON pkmncf_terminal_trainer_rankings_records.pid = pkmncf_terminal_trainer_rankings_teams.pid " + "WHERE pkmncf_terminal_trainer_rankings_records.LastUpdated >= @start_date " + "AND RecordType = @record_type AND " + teamBetween + " GROUP BY Team ORDER BY Score DESC", new MySqlParameter("@record_type", recordType), new MySqlParameter("@start_date", startDate)); var entries = tblLeaderboard.AsEnumerable() .Select(rowEntry => new TrainerRankingsLeaderboardEntry( DatabaseExtender.Cast(rowEntry["Team"]), Convert.ToInt64(rowEntry["Score"]))).ToArray(); return new TrainerRankingsLeaderboard(teamCategory, entries); } #endregion #region Global Terminal 5 public ulong MusicalUpload5(MySqlTransaction tran, MusicalRecord5 record) { bool exists = Convert.ToSByte(tran.ExecuteScalar("SELECT EXISTS(SELECT * " + "FROM TerminalMusicals5 WHERE md5 = unhex(md5(@data)) " + "AND Data = @data)", new MySqlParameter("@data", record.Data))) != 0; if (exists) return 0; if (record.SerialNumber == 0) { ulong serial = Convert.ToUInt64(tran.ExecuteScalar("INSERT INTO TerminalMusicals5 " + "(pid, Data, md5, TimeAdded, ParseVersion) " + "VALUES (@pid, @data, unhex(md5(@data)), " + "UTC_TIMESTAMP(), 1); " + "SELECT LAST_INSERT_ID()", new MySqlParameter("@pid", record.PID), new MySqlParameter("@data", record.Data) )); // todo: make a proc to insert both musical and party. InsertMusicalParticipants5(record, serial, tran); return serial; } else { int rows = tran.ExecuteNonQuery("INSERT INTO TerminalMusicals5 " + "(pid, SerialNumber, Data, md5, TimeAdded, ParseVersion) " + "VALUES (@pid, @serial, @data, unhex(md5(@data)), " + "UTC_TIMESTAMP(), 1)", new MySqlParameter("@pid", record.PID), new MySqlParameter("@serial", record.SerialNumber), new MySqlParameter("@data", record.Data) ); if (rows == 0) return 0; InsertMusicalParticipants5(record, record.SerialNumber, tran); return record.SerialNumber; } } public override ulong MusicalUpload5(MusicalRecord5 record) { if (record.Data.Length != 560) throw new ArgumentException(); return WithTransaction(tran => MusicalUpload5(tran, record)); } private void InsertMusicalParticipants5(MusicalRecord5 record, ulong SerialNumber, MySqlTransaction tran) { MySqlCommand cmd = new MySqlCommand("INSERT INTO " + "TerminalMusicalPokemon5 (musical_id, Slot, Species) VALUES " + "(@serial, @slot, @species)", tran.Connection, tran); cmd.Parameters.Add("@serial", MySqlDbType.UInt64).Value = SerialNumber; cmd.Parameters.Add("@slot", MySqlDbType.UByte); cmd.Parameters.Add("@species", MySqlDbType.UInt16); MusicalParticipant5[] participants = record.Participants; for (byte x = 0; x < 4; x++) { ushort species = participants[x].Species; if (species == 0) continue; cmd.Parameters["@slot"].Value = x; cmd.Parameters["@species"].Value = species; cmd.ExecuteNonQuery(); } } public MusicalRecord5[] MusicalSearch5(MySqlTransaction tran, ushort species, int count) { List results = new List(count); using (MySqlDataReader reader = (MySqlDataReader)tran.ExecuteReader("SELECT pid, " + "SerialNumber, Data FROM TerminalMusicals5 " + "WHERE EXISTS(SELECT * FROM TerminalMusicalPokemon5 " + "WHERE musical_id = TerminalMusicals5.SerialNumber AND Species = @species) " + "ORDER BY TimeAdded DESC LIMIT @count", new MySqlParameter("@species", species), new MySqlParameter("@count", count))) { while (reader.Read()) results.Add(Musical5FromReader(reader)); reader.Close(); } return results.ToArray(); } public override MusicalRecord5[] MusicalSearch5(ushort species, int count) { return WithTransaction(tran => MusicalSearch5(tran, species, count)); } private MusicalRecord5 Musical5FromReader(MySqlDataReader reader) { byte[] data = new byte[560]; reader.GetBytes(2, 0, data, 0, 560); return new MusicalRecord5(reader.GetInt32(0), reader.GetUInt64(1), data); } public ulong BattleVideoUpload5(MySqlTransaction tran, BattleVideoRecord5 record) { if (record.Data.Length != 6112) throw new ArgumentException(); if (record.Header.Data.Length != 196) throw new ArgumentException(); bool exists = Convert.ToSByte(tran.ExecuteScalar("SELECT EXISTS(SELECT * " + "FROM TerminalBattleVideos5 WHERE md5 = unhex(md5(CONCAT(@header, @data))) " + "AND Data = @data AND Header = @header)", new MySqlParameter("@header", record.Header.Data), new MySqlParameter("@data", record.Data))) != 0; if (exists) return 0; DateTime now = DateTime.UtcNow; DateTime hypeTime = GetActiveHypeDate(now); double adjustedHype = HypeDecay(HYPE_NEW_VIDEO, now, hypeTime); ulong serial; if (record.SerialNumber == 0) { ulong key = Convert.ToUInt64(tran.ExecuteScalar("INSERT INTO TerminalBattleVideos5 " + "(pid, Header, Data, md5, TimeAdded, ParseVersion, Streak, TrainerName, " + "Metagame, Country, Region, Hype, HypeTimestamp) " + "VALUES (@pid, @header, @data, unhex(md5(CONCAT(@header, @data))), " + "UTC_TIMESTAMP(), 1, @streak, @trainer, @metagame, @country, @region, @hype, @hype_timestamp); " + "SELECT LAST_INSERT_ID()", new MySqlParameter("@pid", record.PID), new MySqlParameter("@header", record.Header.Data), new MySqlParameter("@data", record.Data), new MySqlParameter("@streak", record.Header.Streak), new MySqlParameter("@trainer", record.Header.TrainerName), new MySqlParameter("@metagame", (byte)record.Header.Metagame), new MySqlParameter("@country", (byte)record.Header.Country), new MySqlParameter("@region", (byte)record.Header.Region), new MySqlParameter("@hype", adjustedHype), new MySqlParameter("@hype_timestamp", hypeTime) )); serial = BattleVideoHeader4.KeyToSerial(key); tran.ExecuteNonQuery("UPDATE TerminalBattleVideos5 SET " + "SerialNumber = @serial WHERE id = @key", new MySqlParameter("@serial", serial), new MySqlParameter("@key", key)); // todo: make a proc to insert both video and party. InsertBattleVideoParty5(record.Header, key, tran); } else { ulong key = (ulong)BattleVideoHeader4.SerialToKey(record.SerialNumber); int rows = tran.ExecuteNonQuery("INSERT INTO TerminalBattleVideos5 " + "(id, pid, SerialNumber, Header, Data, md5, TimeAdded, " + "ParseVersion, Streak, TrainerName, " + "Metagame, Country, Region, Hype, HypeTimestamp) " + "VALUES (@key, @pid, @serial, @header, @data, " + "unhex(md5(CONCAT(@header, @data))), " + "UTC_TIMESTAMP(), 1, @streak, @trainer, @metagame, @country, @region, @hype, @hype_timestamp)", new MySqlParameter("@key", key), new MySqlParameter("@pid", record.PID), new MySqlParameter("@serial", record.SerialNumber), new MySqlParameter("@header", record.Header.Data), new MySqlParameter("@data", record.Data), new MySqlParameter("@streak", record.Header.Streak), new MySqlParameter("@trainer", record.Header.TrainerName), new MySqlParameter("@metagame", (byte)record.Header.Metagame), new MySqlParameter("@country", (byte)record.Header.Country), new MySqlParameter("@region", (byte)record.Header.Region), new MySqlParameter("@hype", adjustedHype), new MySqlParameter("@hype_timestamp", hypeTime) ); if (rows == 0) return 0; serial = record.SerialNumber; InsertBattleVideoParty5(record.Header, key, tran); } BattleVideoUpdateHypeTimes5(tran, hypeTime); return serial; } public override ulong BattleVideoUpload5(BattleVideoRecord5 record) { if (record.Data.Length != 6112) throw new ArgumentException(); if (record.Header.Data.Length != 196) throw new ArgumentException(); return WithTransaction(tran => BattleVideoUpload5(tran, record)); } private void InsertBattleVideoParty5(BattleVideoHeader5 header, ulong key, MySqlTransaction tran) { MySqlCommand cmd = new MySqlCommand("INSERT INTO " + "TerminalBattleVideoPokemon5 (video_id, Slot, Species) VALUES " + "(@key, @slot, @species)", tran.Connection, tran); cmd.Parameters.Add("@key", MySqlDbType.UInt64).Value = key; cmd.Parameters.Add("@slot", MySqlDbType.UByte); cmd.Parameters.Add("@species", MySqlDbType.UInt16); ushort[] party = header.Party; for (byte x = 0; x < 12; x++) { ushort species = party[x]; if (species == 0) continue; cmd.Parameters["@slot"].Value = x; cmd.Parameters["@species"].Value = species; cmd.ExecuteNonQuery(); } } private void BattleVideoUpdateHypeTimes5(MySqlTransaction tran, DateTime hypeTime) { BattleVideoUpdateHypeTimes(tran, "TerminalBattleVideos5", hypeTime); } public BattleVideoHeader5[] BattleVideoSearch5(MySqlTransaction tran, ushort species, BattleVideoRankings5 ranking, BattleVideoMetagames5 metagame, byte country, byte region, int count) { List _params = new List(); string where = ""; string sort = ""; bool hasSearch = false; if (ranking == BattleVideoRankings5.None) { if (species != 0xffff) { where += (hasSearch ? " AND " : " WHERE ") + "EXISTS(SELECT * FROM TerminalBattleVideoPokemon5 " + "WHERE video_id = TerminalBattleVideos5.id AND Species = @species)"; _params.Add(new MySqlParameter("@species", species)); hasSearch = true; } if (metagame == BattleVideoMetagames5.RandomMatchupSingle) { where += (hasSearch ? " AND " : " WHERE ") + "Metagame IN (40, 104)"; hasSearch = true; } else if (metagame == BattleVideoMetagames5.RandomMatchupDouble) { where += (hasSearch ? " AND " : " WHERE ") + "Metagame IN (41, 105)"; hasSearch = true; } else if (metagame == BattleVideoMetagames5.RandomMatchupTriple) { where += (hasSearch ? " AND " : " WHERE ") + "Metagame IN (42, 106)"; hasSearch = true; } else if (metagame == BattleVideoMetagames5.RandomMatchupRotation) { where += (hasSearch ? " AND " : " WHERE ") + "Metagame IN (43, 107)"; hasSearch = true; } else if (metagame == BattleVideoMetagames5.SearchBattleCompetition) { where += (hasSearch ? " AND " : " WHERE ") + "Metagame BETWEEN 56 AND 59"; hasSearch = true; } else if (metagame != BattleVideoMetagames5.SearchNone) { where += (hasSearch ? " AND " : " WHERE ") + "Metagame = @metagame"; _params.Add(new MySqlParameter("@metagame", (byte)metagame)); hasSearch = true; } if (country != 0xff) { where += (hasSearch ? " AND " : " WHERE ") + "Country = @country"; _params.Add(new MySqlParameter("@country", country)); hasSearch = true; } if (region != 0xff) { where += (hasSearch ? " AND " : " WHERE ") + "Region = @region"; _params.Add(new MySqlParameter("@region", region)); } sort = " ORDER BY TimeAdded DESC, id DESC"; } else if (ranking == BattleVideoRankings5.LinkBattles) { where = " WHERE NOT (Metagame BETWEEN 0 AND 4)"; sort = " ORDER BY Hype DESC, TimeAdded DESC, id DESC"; } else if (ranking == BattleVideoRankings5.SubwayBattles) { where = " WHERE Metagame BETWEEN 0 AND 4"; sort = " ORDER BY Hype DESC, TimeAdded DESC, id DESC"; } else { sort = " ORDER BY TimeAdded DESC, id DESC"; } _params.Add(new MySqlParameter("@count", count)); List results = new List(count); using (MySqlDataReader reader = (MySqlDataReader)tran.ExecuteReader("SELECT pid, " + "SerialNumber, Header FROM TerminalBattleVideos5" + where + sort + " LIMIT @count", _params.ToArray())) { while (reader.Read()) results.Add(BattleVideoHeader5FromReader(reader)); reader.Close(); } return results.ToArray(); } public override BattleVideoHeader5[] BattleVideoSearch5(ushort species, BattleVideoRankings5 ranking, BattleVideoMetagames5 metagame, byte country, byte region, int count) { return WithTransaction(tran => BattleVideoSearch5(tran, species, ranking, metagame, country, region, count)); } private BattleVideoHeader5 BattleVideoHeader5FromReader(MySqlDataReader reader) { byte[] data = new byte[196]; reader.GetBytes(2, 0, data, 0, 196); return new BattleVideoHeader5(reader.GetInt32(0), reader.GetUInt64(1), data); } public BattleVideoRecord5 BattleVideoGet5(MySqlTransaction tran, ulong serial, bool incrementViews = false) { BattleVideoRecord5 result = null; using (var reader = BattleVideoGet(tran, "TerminalBattleVideos5", serial, incrementViews)) { if (reader.Read()) result = BattleVideo5FromReader(reader); } return result; } public override BattleVideoRecord5 BattleVideoGet5(ulong serial, bool incrementViews = false) { return WithTransaction(tran => BattleVideoGet5(tran, serial, incrementViews)); } private BattleVideoRecord5 BattleVideo5FromReader(MySqlDataReader reader) { byte[] data = new byte[6112]; reader.GetBytes(3, 0, data, 0, 6112); BattleVideoHeader5 header = BattleVideoHeader5FromReader(reader); return new BattleVideoRecord5(header.PID, header.SerialNumber, header, data); } public bool BattleVideoFlagSaved5(MySqlTransaction tran, ulong serial) { DateTime now = DateTime.UtcNow; DateTime hypeTime = GetActiveHypeDate(now); double hype = HypeDecay(HYPE_SAVED_VIDEO, now, hypeTime); BattleVideoUpdateHypeTimes5(tran, hypeTime); int results = tran.ExecuteNonQuery("UPDATE TerminalBattleVideos5 " + "SET Saves = Saves + 1, Hype = Hype + @hype WHERE SerialNumber = @serial", new MySqlParameter("@hype", hype), new MySqlParameter("@hype_timestamp", hypeTime), new MySqlParameter("@serial", serial)); return results > 0; } public override bool BattleVideoFlagSaved5(ulong serial) { return WithTransaction(tran => BattleVideoFlagSaved5(tran, serial)); } public ulong BattleVideoCount5(MySqlTransaction tran) { return Convert.ToUInt64(tran.ExecuteScalar("SELECT Count(*) FROM TerminalBattleVideos5")); } public override ulong BattleVideoCount5() { return WithTransaction(tran => BattleVideoCount5(tran)); } #endregion #region Pokedex creation private const string INSERT_COLUMNS = "Name_JA, Name_EN, Name_FR, Name_IT, Name_DE, Name_ES, Name_KO"; private const string INSERT_VALUES = "@name_ja, @name_en, @name_fr, @name_it, @name_de, @name_es, @name_ko"; private static string[] m_query_langs = new string[] { "JA", "EN", "FR", "IT", "DE", "ES", "KO" }; private static void CreateLocalizedStringQueryPieces(LocalizedString s, List insertParams, string prefix = "@name_") { foreach (string lang in m_query_langs) { MySqlParameter param = new MySqlParameter(prefix + lang.ToLowerInvariant(), s.ContainsKey(lang) ? s[lang] : (object)DBNull.Value); insertParams.Add(param); } } private static string CreateLocalizedInsertColumns(string prefix) { return String.Join(", ", m_query_langs.Select(lang => prefix + lang).ToArray()); } private static string CreateLocalizedInsertValues(string prefix) { return String.Join(", ", m_query_langs.Select(lang => prefix + lang.ToLowerInvariant()).ToArray()); } public override void PokedexInsertSpecies(Species s) { using (MySqlConnection db = CreateConnection()) { db.Open(); List insertParams = new List(); insertParams.Add(new MySqlParameter("@national_dex", s.NationalDex)); insertParams.Add(new MySqlParameter("@family_id", s.FamilyID)); insertParams.Add(new MySqlParameter("@growth_rate", (int)s.GrowthRate)); insertParams.Add(new MySqlParameter("@gender_ratio", s.GenderRatio)); insertParams.Add(new MySqlParameter("@egg_group_1", (byte)s.EggGroup1)); insertParams.Add(new MySqlParameter("@egg_group_2", (byte)s.EggGroup2)); insertParams.Add(new MySqlParameter("@egg_steps", s.EggSteps)); insertParams.Add(new MySqlParameter("@gender_variations", s.GenderVariations)); CreateLocalizedStringQueryPieces(s.Name, insertParams); db.ExecuteNonQuery("INSERT INTO pkmncf_pokedex_pokemon (NationalDex, family_id, " + INSERT_COLUMNS + ", GrowthRate, GenderRatio, EggGroup1, EggGroup2, EggSteps, " + "GenderVariations) VALUES (@national_dex, @family_id, " + INSERT_VALUES + ", @growth_rate, @gender_ratio, @egg_group_1, @egg_group_2, " + "@egg_steps, @gender_variations)", insertParams.ToArray()); db.Close(); } } public override void PokedexInsertForm(Form f) { using (MySqlConnection db = CreateConnection()) { db.Open(); List insertParams = new List(); insertParams.Add(new MySqlParameter("@id", f.ID)); insertParams.Add(new MySqlParameter("@national_dex", f.SpeciesID)); insertParams.Add(new MySqlParameter("@form_value", f.Value)); insertParams.Add(new MySqlParameter("@form_suffix", f.Suffix)); insertParams.Add(new MySqlParameter("@height", f.Height)); insertParams.Add(new MySqlParameter("@weight", f.Weight)); insertParams.Add(new MySqlParameter("@experience", f.Experience)); CreateLocalizedStringQueryPieces(f.Name, insertParams); db.ExecuteNonQuery("INSERT INTO pkmncf_pokedex_pokemon_forms (id, NationalDex, " + "FormValue, " + INSERT_COLUMNS + ", FormSuffix, Height, Weight, Experience) VALUES (" + "@id, @national_dex, @form_value, " + INSERT_VALUES + ", @form_suffix, @height, @weight, @experience)", insertParams.ToArray()); db.Close(); } } public override void PokedexInsertFormStats(FormStats f) { using (MySqlConnection db = CreateConnection()) { db.Open(); db.ExecuteNonQuery("INSERT INTO pkmncf_pokedex_pokemon_form_stats " + "(form_id, MinGeneration, Type1, Type2, " + "BaseHP, BaseAttack, BaseDefense, BaseSpeed, BaseSpAttack, BaseSpDefense, " + "RewardHP, RewardAttack, RewardDefense, RewardSpeed, RewardSpAttack, RewardSpDefense) " + "VALUES (@form_id, @min_generation, @type1, @type2, " + "@base_hp, @base_attack, @base_defense, @base_speed, @base_sp_attack, @base_sp_defense, " + "@reward_hp, @reward_attack, @reward_defense, @reward_speed, @reward_sp_attack, @reward_sp_defense)", new MySqlParameter("@form_id", f.FormID), new MySqlParameter("@min_generation", (int)f.MinGeneration), new MySqlParameter("@type1", f.Type1ID), new MySqlParameter("@type2", f.Type2ID), new MySqlParameter("@base_hp", f.BaseStats.Hp), new MySqlParameter("@base_attack", f.BaseStats.Attack), new MySqlParameter("@base_defense", f.BaseStats.Defense), new MySqlParameter("@base_speed", f.BaseStats.Speed), new MySqlParameter("@base_sp_attack", f.BaseStats.SpecialAttack), new MySqlParameter("@base_sp_defense", f.BaseStats.SpecialDefense), new MySqlParameter("@reward_hp", (byte)f.RewardEvs.Hp), new MySqlParameter("@reward_attack", (byte)f.RewardEvs.Attack), new MySqlParameter("@reward_defense", (byte)f.RewardEvs.Defense), new MySqlParameter("@reward_speed", (byte)f.RewardEvs.Speed), new MySqlParameter("@reward_sp_attack", (byte)f.RewardEvs.SpecialAttack), new MySqlParameter("@reward_sp_defense", (byte)f.RewardEvs.SpecialDefense) ); db.Close(); } } public override void PokedexInsertFormAbilities(FormAbilities f) { using (MySqlConnection db = CreateConnection()) { db.Open(); db.ExecuteNonQuery("INSERT INTO pkmncf_pokedex_pokemon_form_abilities " + "(form_id, MinGeneration, Ability1, Ability2, HiddenAbility1) " + "VALUES (@form_id, @min_generation, @ability1, @ability2, @hidden_ability1)", new MySqlParameter("@form_id", f.FormID), new MySqlParameter("@min_generation", (int)f.MinGeneration), new MySqlParameter("@ability1", f.Ability1ID == 0 ? (int?)null : f.Ability1ID), new MySqlParameter("@ability2", f.Ability2ID == 0 ? (int?)null : f.Ability2ID), new MySqlParameter("@hidden_ability1", f.HiddenAbility1ID == 0 ? (int?)null : f.HiddenAbility1ID) ); db.Close(); } } public override void PokedexInsertFamily(Family f) { using (MySqlConnection db = CreateConnection()) { db.Open(); db.ExecuteNonQuery("INSERT INTO pkmncf_pokedex_pokemon_families " + "(id, BasicMale, BasicFemale, BabyMale, BabyFemale, " + "Incense, GenderRatio) VALUES (@id, @basic_male, " + "@basic_female, @baby_male, @baby_female, @incense, " + "@gender_ratio)", // todo: collapse 0 to null sometimes new MySqlParameter("@id", f.ID), new MySqlParameter("@basic_male", f.BasicMaleID), new MySqlParameter("@basic_female", f.BasicFemaleID), new MySqlParameter("@baby_male", f.BabyMaleID), new MySqlParameter("@baby_female", f.BabyFemaleID), new MySqlParameter("@incense", f.IncenseID), new MySqlParameter("@gender_ratio", f.GenderRatio) ); db.Close(); } } public override void PokedexInsertEvolution(Evolution f) { throw new NotImplementedException(); } public override void PokedexInsertType(Pokedex.Type t) { using (MySqlConnection db = CreateConnection()) { db.Open(); List insertParams = new List(); insertParams.Add(new MySqlParameter("@id", t.ID)); insertParams.Add(new MySqlParameter("@damage_class", (byte)t.DamageClass)); CreateLocalizedStringQueryPieces(t.Name, insertParams); db.ExecuteNonQuery("INSERT INTO pkmncf_pokedex_types (id, " + INSERT_COLUMNS + ", DamageClass) VALUES (@id, " + INSERT_VALUES + ", @damage_class)", insertParams.ToArray()); db.Close(); } } public override void PokedexInsertItem(Item i) { using (MySqlConnection db = CreateConnection()) { db.Open(); List insertParams = new List(); insertParams.Add(new MySqlParameter("@id", i.ID)); insertParams.Add(new MySqlParameter("@value3", i.Value3)); insertParams.Add(new MySqlParameter("@value4", i.Value4)); insertParams.Add(new MySqlParameter("@value5", i.Value5)); insertParams.Add(new MySqlParameter("@value6", i.Value6)); insertParams.Add(new MySqlParameter("@pokeball_value", i.PokeballValue)); insertParams.Add(new MySqlParameter("@price", i.Price)); CreateLocalizedStringQueryPieces(i.Name, insertParams); db.ExecuteNonQuery("INSERT INTO pkmncf_pokedex_items (id, Value3, " + "Value4, Value5, Value6, PokeballValue, " + INSERT_COLUMNS + ", Price) VALUES (" + "@id, @value3, @value4, @value5, @value6, @pokeball_value, " + INSERT_VALUES + ", @price)", insertParams.ToArray()); db.Close(); } } public override void PokedexInsertMove(Move m) { using (MySqlConnection db = CreateConnection()) { db.Open(); List insertParams = new List(); insertParams.Add(new MySqlParameter("@value", m.ID)); insertParams.Add(new MySqlParameter("@type_id", m.TypeID)); insertParams.Add(new MySqlParameter("@damage_class", (int)m.DamageClass)); insertParams.Add(new MySqlParameter("@damage", m.Damage)); insertParams.Add(new MySqlParameter("@pp", m.PP)); insertParams.Add(new MySqlParameter("@accuracy", m.Accuracy)); insertParams.Add(new MySqlParameter("@priority", m.Priority)); insertParams.Add(new MySqlParameter("@target", (int)m.Target)); CreateLocalizedStringQueryPieces(m.Name, insertParams); db.ExecuteNonQuery("INSERT INTO pkmncf_pokedex_moves (Value, type_id, " + "DamageClass, " + INSERT_COLUMNS + ", Damage, PP, Accuracy, " + "Priority, Target) VALUES (@value, @type_id, @damage_class, " + INSERT_VALUES + ", @damage, @pp, " + "@accuracy, @priority, @target)", insertParams.ToArray()); db.Close(); } } public override void PokedexInsertAbility(Ability a) { using (MySqlConnection db = CreateConnection()) { db.Open(); List insertParams = new List(); insertParams.Add(new MySqlParameter("@value", a.Value)); CreateLocalizedStringQueryPieces(a.Name, insertParams); db.ExecuteNonQuery("INSERT INTO pkmncf_pokedex_abilities (Value, " + INSERT_COLUMNS + ") VALUES (@value, " + INSERT_VALUES + ")", insertParams.ToArray()); db.Close(); } } public void PokedexInsertRibbon(MySqlTransaction tran, Ribbon r) { List insertParams = new List(); insertParams.Add(new MySqlParameter("@id", r.ID)); insertParams.Add(new MySqlParameter("@position3", r.Position3)); insertParams.Add(new MySqlParameter("@position4", r.Position4)); insertParams.Add(new MySqlParameter("@position5", r.Position5)); insertParams.Add(new MySqlParameter("@position6", r.Position6)); insertParams.Add(new MySqlParameter("@value3", r.Value3)); insertParams.Add(new MySqlParameter("@value4", r.Value4)); insertParams.Add(new MySqlParameter("@value5", r.Value5)); insertParams.Add(new MySqlParameter("@value6", r.Value6)); CreateLocalizedStringQueryPieces(r.Name, insertParams); CreateLocalizedStringQueryPieces(r.Name, insertParams, "@description_"); tran.ExecuteNonQuery("INSERT INTO pkmncf_pokedex_ribbons (ID, " + "Position3, Position4, Position5, Position6, Value3, Value4, " + "Value5, Value6, " + INSERT_COLUMNS + ", " + CreateLocalizedInsertColumns("Description_") + ") VALUES (@id, " + "@position3, @position4, @position5, @position6, @value3, " + "@value4, @value5, @value6, " + INSERT_VALUES + ", " + CreateLocalizedInsertValues("@description_") + ")", insertParams.ToArray()); } public override void PokedexInsertRibbon(Ribbon r) { WithTransaction(tran => PokedexInsertRibbon(tran, r)); } public void PokedexInsertRegion(MySqlTransaction tran, Region r) { List insertParams = new List(); insertParams.Add(new MySqlParameter("@id", r.ID)); CreateLocalizedStringQueryPieces(r.Name, insertParams); tran.ExecuteNonQuery("INSERT INTO pkmncf_pokedex_regions (ID, " + INSERT_COLUMNS + ") VALUES (@id, " + INSERT_VALUES + ")", insertParams.ToArray()); } public override void PokedexInsertRegion(Region r) { WithTransaction(tran => PokedexInsertRegion(tran, r)); } public void PokedexInsertLocation(MySqlTransaction tran, Location l) { List insertParams = new List(); insertParams.Add(new MySqlParameter("@id", l.ID)); insertParams.Add(new MySqlParameter("@region_id", l.RegionID)); insertParams.Add(new MySqlParameter("@value3", l.Value3)); insertParams.Add(new MySqlParameter("@value_colo", l.ValueColo)); insertParams.Add(new MySqlParameter("@value_xd", l.ValueXd)); insertParams.Add(new MySqlParameter("@value4", l.Value4)); insertParams.Add(new MySqlParameter("@value5", l.Value5)); insertParams.Add(new MySqlParameter("@value6", l.Value6)); CreateLocalizedStringQueryPieces(l.Name, insertParams); tran.ExecuteNonQuery("INSERT INTO pkmncf_pokedex_locations (ID, region_id, " + "Value3, Value_Colo, Value_XD, Value4, Value5, Value6, " + INSERT_COLUMNS + ") VALUES (@id, @region_id, @value3, @value_colo, @value_xd, @value4, @value5, @value6, " + INSERT_VALUES + ")", insertParams.ToArray()); } public override void PokedexInsertLocation(Location l) { WithTransaction(tran => PokedexInsertLocation(tran, l)); } #endregion #region Pokedex retrieval private List ReaderToList(MySqlDataReader reader, Pokedex.Pokedex pokedex, Func ctor) where T : PokedexRecordBase { List result = new List(); while (reader.Read()) { result.Add(ctor()); } return result; } public override List PokedexGetAllSpecies(Pokedex.Pokedex pokedex) { using (MySqlConnection db = CreateConnection()) { db.Open(); using (MySqlDataReader reader = (MySqlDataReader)db.ExecuteReader("SELECT " + "NationalDex, family_id, " + INSERT_COLUMNS + ", GrowthRate, " + "GenderRatio, EggGroup1, EggGroup2, EggSteps, GenderVariations " + "FROM pkmncf_pokedex_pokemon")) { return ReaderToList(reader, pokedex, () => new Species(pokedex, reader)); } } } public override List
PokedexGetAllForms(Pokedex.Pokedex pokedex) { using (MySqlConnection db = CreateConnection()) { db.Open(); using (MySqlDataReader reader = (MySqlDataReader)db.ExecuteReader("SELECT " + "id, NationalDex, FormValue, " + INSERT_COLUMNS + ", FormSuffix, " + "Height, Weight, Experience " + "FROM pkmncf_pokedex_pokemon_forms")) { return ReaderToList(reader, pokedex, () => new Form(pokedex, reader)); } } } public override List PokedexGetAllFormStats(Pokedex.Pokedex pokedex) { using (MySqlConnection db = CreateConnection()) { db.Open(); using (MySqlDataReader reader = (MySqlDataReader)db.ExecuteReader("SELECT " + "form_id, MinGeneration, Type1, Type2, BaseHP, BaseAttack, " + "BaseDefense, BaseSpeed, BaseSpAttack, BaseSpDefense, RewardHP, " + "RewardAttack, RewardDefense, RewardSpeed, RewardSpAttack, RewardSpDefense " + "FROM pkmncf_pokedex_pokemon_form_stats")) { return ReaderToList(reader, pokedex, () => new FormStats(pokedex, reader)); } } } public override List PokedexGetAllFormAbilities(Pokedex.Pokedex pokedex) { using (MySqlConnection db = CreateConnection()) { db.Open(); using (MySqlDataReader reader = (MySqlDataReader)db.ExecuteReader("SELECT " + "form_id, MinGeneration, Ability1, Ability2, HiddenAbility1 " + "FROM pkmncf_pokedex_pokemon_form_abilities")) { return ReaderToList(reader, pokedex, () => new FormAbilities(pokedex, reader)); } } } public override List PokedexGetAllFamilies(Pokedex.Pokedex pokedex) { using (MySqlConnection db = CreateConnection()) { db.Open(); using (MySqlDataReader reader = (MySqlDataReader)db.ExecuteReader("SELECT " + "id, BasicMale, BasicFemale, BabyMale, BabyFemale, Incense, GenderRatio " + "FROM pkmncf_pokedex_pokemon_families")) { return ReaderToList(reader, pokedex, () => new Family(pokedex, reader)); } } } public override List PokedexGetAllEvolutions(Pokedex.Pokedex pokedex) { // todo throw new NotImplementedException(); using (MySqlConnection db = CreateConnection()) { db.Open(); using (MySqlDataReader reader = (MySqlDataReader)db.ExecuteReader("SELECT " + "id " + "FROM pkmncf_pokedex_pokemon_evolutions")) { //return ReaderToList(reader, pokedex, () => new Evolution(pokedex, reader)); } } } public override List PokedexGetAllTypes(Pokedex.Pokedex pokedex) { using (MySqlConnection db = CreateConnection()) { db.Open(); using (MySqlDataReader reader = (MySqlDataReader)db.ExecuteReader("SELECT " + "id, " + INSERT_COLUMNS + ", DamageClass " + "FROM pkmncf_pokedex_types")) { return ReaderToList(reader, pokedex, () => new Pokedex.Type(pokedex, reader)); } } } public override List PokedexGetAllItems(Pokedex.Pokedex pokedex) { using (MySqlConnection db = CreateConnection()) { db.Open(); using (MySqlDataReader reader = (MySqlDataReader)db.ExecuteReader("SELECT " + "id, Value3, Value4, Value5, Value6, PokeballValue, " + INSERT_COLUMNS + ", Price " + "FROM pkmncf_pokedex_items")) { return ReaderToList(reader, pokedex, () => new Item(pokedex, reader)); } } } public override List PokedexGetAllMoves(Pokedex.Pokedex pokedex) { using (MySqlConnection db = CreateConnection()) { db.Open(); using (MySqlDataReader reader = (MySqlDataReader)db.ExecuteReader("SELECT " + "Value, type_id, DamageClass, " + INSERT_COLUMNS + ", Damage, " + "PP, Accuracy, Priority, Target " + "FROM pkmncf_pokedex_moves")) { return ReaderToList(reader, pokedex, () => new Move(pokedex, reader)); } } } public override List PokedexGetAllAbilities(Pokedex.Pokedex pokedex) { using (MySqlConnection db = CreateConnection()) { db.Open(); using (MySqlDataReader reader = (MySqlDataReader)db.ExecuteReader("SELECT " + "Value, " + INSERT_COLUMNS + " FROM pkmncf_pokedex_abilities")) { return ReaderToList(reader, pokedex, () => new Ability(pokedex, reader)); } } } public List PokedexGetAllRibbons(MySqlTransaction tran, Pokedex.Pokedex pokedex) { using (MySqlDataReader reader = (MySqlDataReader)tran.ExecuteReader("SELECT " + "ID, Position3, Position4, Position5, Position6, Value3, " + "Value4, Value5, Value6, " + INSERT_COLUMNS + ", " + CreateLocalizedInsertColumns("Description_") + " FROM pkmncf_pokedex_ribbons")) { return ReaderToList(reader, pokedex, () => new Ribbon(pokedex, reader)); } } public override List PokedexGetAllRibbons(Pokedex.Pokedex pokedex) { return WithTransaction(tran => PokedexGetAllRibbons(tran, pokedex)); } public List PokedexGetAllRegions(MySqlTransaction tran, Pokedex.Pokedex pokedex) { using (MySqlDataReader reader = (MySqlDataReader)tran.ExecuteReader("SELECT " + "ID, " + INSERT_COLUMNS + " FROM pkmncf_pokedex_regions")) { return ReaderToList(reader, pokedex, () => new Region(pokedex, reader)); } } public override List PokedexGetAllRegions(Pokedex.Pokedex pokedex) { return WithTransaction(tran => PokedexGetAllRegions(tran, pokedex)); } public List PokedexGetAllLocations(MySqlTransaction tran, Pokedex.Pokedex pokedex) { using (MySqlDataReader reader = (MySqlDataReader)tran.ExecuteReader("SELECT " + "id, region_id, Value3, Value_Colo, Value_XD, Value4, Value5, Value6, " + INSERT_COLUMNS + " FROM pkmncf_pokedex_locations")) { return ReaderToList(reader, pokedex, () => new Location(pokedex, reader)); } } public override List PokedexGetAllLocations(Pokedex.Pokedex pokedex) { return WithTransaction(tran => PokedexGetAllLocations(tran, pokedex)); } #endregion } } ================================================ FILE: library/Data/DataSqlite.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SQLite; namespace PkmnFoundations.Data { // todo public class DataSqlite// : DataAbstract { public SQLiteConnection CreateConnection() { return CreateConnection(DefaultFilename); } public SQLiteConnection CreateConnection(string filename) { if (filename.Contains('\"')) throw new ArgumentException(); return new SQLiteConnection("Data Source=" + filename + ";Version=3;"); } public string DefaultFilename = "pokedex.sqlite"; } } ================================================ FILE: library/Data/Database.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using PkmnFoundations.Structures; using System.Configuration; using PkmnFoundations.Pokedex; using PkmnFoundations.Wfc; namespace PkmnFoundations.Data { public abstract class Database { #region Initialization private static Database m_instance; public static Database Instance { get { // fixme: this is not thread safe if (m_instance == null) { m_instance = CreateInstance(); } return m_instance; } } public static Database CreateInstance() { ConnectionStringSettings connStr = ConfigurationManager.ConnectionStrings["pkmnFoundationsConnectionString"]; if (connStr == null) throw new NotSupportedException("No database connection string provided. Please add one in web.config or app.config."); return CreateInstance(connStr); } public static Database CreateInstance(ConnectionStringSettings connStr) { if (connStr == null) throw new ArgumentNullException("connStr"); return CreateInstance(connStr.ConnectionString, connStr.ProviderName); } public static Database CreateInstance(string connStr, string provider) { if (connStr == null) throw new ArgumentNullException("connStr"); if (provider == null) throw new ArgumentNullException("provider"); switch (provider) { case "MySql.Data.MySqlClient": return new DataMysql(connStr); default: throw new NotSupportedException("Database provider not supported."); } } #endregion #region Utility internal static DateTime DateLerp(DateTime first, DateTime second, double weight) { TimeSpan diff = second - first; return first + new TimeSpan((long)(diff.Ticks * weight)); } internal const double HYPE_DECAY_DAYS = 7.0d; internal const double HYPE_DECAY_RATE = -0.09902102579427790134531887449403; // -ln(2)/HYPE_DECAY_DAYS internal const double HYPE_NEW_VIDEO = 5.0d; internal const double HYPE_WATCHED_VIDEO = 1.0d; internal const double HYPE_SAVED_VIDEO = 1.0d; // Note that when the client wants to save, it will call both Get and FlagSaved /// /// Calculates how much Hype has changed between two times. This could be /// /// /// /// /// internal static double HypeDecay(double oldHype, DateTime oldDate, DateTime newDate) { TimeSpan ts = newDate - oldDate; double decays = HYPE_DECAY_RATE * ts.Ticks / TimeSpan.FromDays(1).Ticks; return Math.Exp(decays) * oldHype; // e^(days*-ln(2)/7), should decay by half each week. } /// /// Gets the desired date to use for hype ratings. Changes exactly once a week. /// /// /// internal static DateTime GetActiveHypeDate(DateTime now) { DateTime dateNow = now.Date; return dateNow.AddDays(-(int)dateNow.DayOfWeek); } internal const double GTS_LOCK_DURATION = 60.0d; #endregion #region GTS 4 public const int GTS_VERSION_4 = 0; public abstract GtsRecord4 GtsDataForUser4(Pokedex.Pokedex pokedex, int pid); public abstract GtsRecord4 GtsGetRecord4(Pokedex.Pokedex pokedex, long tradeId, bool isExchanged, bool allowHistory); public abstract bool GtsDepositPokemon4(GtsRecord4 record); public abstract bool GtsDeletePokemon4(int pid); public abstract bool GtsLockPokemon4(ulong tradeId, int partner_pid); public abstract bool GtsCheckLockStatus4(ulong tradeId, int partner_pid); public abstract bool GtsTradePokemon4(int pidSrc, int pidDest); public abstract bool GtsTradePokemon4(GtsRecord4 upload, GtsRecord4 result, int partner_pid); public abstract GtsRecord4[] GtsSearch4(Pokedex.Pokedex pokedex, int pid, ushort species, Genders gender, byte minLevel, byte maxLevel, byte country, int count); public abstract int GtsAvailablePokemon4(); public abstract void GtsSetLastSearch4(int pid); public abstract DateTime? GtsGetLastSearch4(int pid); #endregion #region Battle Tower 4 public abstract ulong BattleTowerUpdateRecord4(BattleTowerRecord4 record); public abstract ulong BattleTowerAddLeader4(BattleTowerRecord4 record); public abstract BattleTowerRecord4[] BattleTowerGetOpponents4(Pokedex.Pokedex pokedex, int pid, byte rank, byte roomNum); public abstract BattleTowerProfile4[] BattleTowerGetLeaders4(Pokedex.Pokedex pokedex, byte rank, byte roomNum); #endregion #region Wi-fi Plaza public abstract TrainerProfilePlaza PlazaGetProfile(int pid); public abstract bool PlazaSetProfile(TrainerProfilePlaza profile); #endregion #region Other Gamestats 4 public abstract bool GamestatsBumpProfile4(int pid, string ip_address); public abstract bool GamestatsSetProfile4(TrainerProfile4 profile); public abstract TrainerProfile4 GamestatsGetProfile4(int pid); #endregion #region Bans public abstract BanStatus CheckBanStatus(int pid); public abstract BanStatus CheckBanStatus(byte[] mac_address); public abstract BanStatus CheckBanStatus(string ip_address); public abstract BanStatus CheckBanStatus(TrainerProfileBase profile); public abstract BanStatus CheckBanStatus(uint ip_address); public abstract void AddBan(int pid, BanStatus status); public abstract void AddBan(byte[] mac_address, BanStatus status); public abstract void AddBan(string ip_address, BanStatus status); #endregion #region GTS 5 public const int GTS_VERSION_5 = 0; public abstract GtsRecord5 GtsDataForUser5(Pokedex.Pokedex pokedex, int pid); public abstract GtsRecord5 GtsGetRecord5(Pokedex.Pokedex pokedex, long tradeId, bool isExchanged, bool allowHistory); public abstract bool GtsDepositPokemon5(GtsRecord5 record); public abstract bool GtsDeletePokemon5(int pid); public abstract bool GtsLockPokemon5(ulong tradeId, int partner_pid); public abstract bool GtsCheckLockStatus5(ulong tradeId, int partner_pid); public abstract bool GtsTradePokemon5(int pidSrc, int pidDest); public abstract bool GtsTradePokemon5(GtsRecord5 upload, GtsRecord5 result, int partner_pid); public abstract GtsRecord5[] GtsSearch5(Pokedex.Pokedex pokedex, int pid, ushort species, Genders gender, byte minLevel, byte maxLevel, byte country, int count); public abstract int GtsAvailablePokemon5(); public abstract void GtsSetLastSearch5(int pid); public abstract DateTime ? GtsGetLastSearch5(int pid); #endregion #region Other Gamestats 5 public abstract bool GamestatsSetProfile5(TrainerProfile5 profile); public abstract TrainerProfile5 GamestatsGetProfile5(int pid); #endregion #region Battle Subway 5 public abstract ulong BattleSubwayUpdateRecord5(BattleSubwayRecord5 record); public abstract ulong BattleSubwayAddLeader5(BattleSubwayRecord5 record); public abstract BattleSubwayRecord5[] BattleSubwayGetOpponents5(Pokedex.Pokedex pokedex, int pid, byte rank, byte roomNum); public abstract BattleSubwayProfile5[] BattleSubwayGetLeaders5(Pokedex.Pokedex pokedex, byte rank, byte roomNum); #endregion #region Global Terminal 4 public const int DRESSUP_VERSION_4 = 1; public const int BOX_VERSION_4 = 1; public const int BATTLEVIDEO_VERSION_4 = 1; public abstract ulong DressupUpload4(DressupRecord4 record); public abstract DressupRecord4[] DressupSearch4(ushort species, int count); public abstract ulong BoxUpload4(BoxRecord4 record); public abstract BoxRecord4[] BoxSearch4(BoxLabels4 label, int count); public abstract ulong BattleVideoUpload4(BattleVideoRecord4 record); public abstract BattleVideoHeader4[] BattleVideoSearch4(ushort species, BattleVideoRankings4 ranking, BattleVideoMetagames4 metagame, byte country, byte region, int count); public abstract BattleVideoRecord4 BattleVideoGet4(ulong serial, bool incrementViews = false); public abstract bool BattleVideoFlagSaved4(ulong serial); public abstract ulong BattleVideoCount4(); /// /// Instructs the database that the provided datetime is now active. /// If the new datetime is outside the active leaderboard's datetime /// range, a new leaderboard should be initialized. /// /// /// True if it began a new leaderboard public abstract bool TrainerRankingsPerformRollover(); /// /// Gets the three record types being collected for the active leaderboard. /// /// RecordTypes public abstract IList TrainerRankingsGetActiveRecordTypes(); /// /// Submits trainer rankings data for one player and populates the active leaderboard with it. /// /// public abstract void TrainerRankingsSubmit(TrainerRankingsSubmission submission); /// /// Gets past reports, sorted descending, falling within a specified date range. /// /// Datetime during which the oldest returned leaderboard was active /// Datetime during which the newest returned leaderboard was active /// Limit on the number of results or less than 1 for unlimited /// Reports public abstract TrainerRankingsReport[] TrainerRankingsGetReport(DateTime start, DateTime end, int limit); /// /// Gets past reports, sorted descending, falling within a specified date range. /// /// Datetime during which the oldest returned leaderboard was active /// Datetime during which the newest returned leaderboard was active /// Reports public TrainerRankingsReport[] TrainerRankingsGetReport(DateTime start, DateTime end) { return TrainerRankingsGetReport(start, end, 0); } /// /// Gets the single report which was active during the specified date. /// /// /// Report public TrainerRankingsReport TrainerRankingsGetReport(DateTime during) { return TrainerRankingsGetReport(during, during, 1).FirstOrDefault(); } /// /// Gets the most recently finished report /// /// Report public TrainerRankingsReport TrainerRankingsGetReport() { return TrainerRankingsGetReport(DateTime.MinValue, DateTime.UtcNow, 1).FirstOrDefault(); } /// /// Gets the currently active, incomplete report. /// /// public abstract TrainerRankingsReport TrainerRankingsGetPendingReport(); #endregion #region Global Terminal 5 public const int MUSICAL_VERSION_5 = 1; public const int BATTLEVIDEO_VERSION_5 = 1; public abstract ulong MusicalUpload5(MusicalRecord5 record); public abstract MusicalRecord5[] MusicalSearch5(ushort species, int count); public abstract ulong BattleVideoUpload5(BattleVideoRecord5 record); public abstract BattleVideoHeader5[] BattleVideoSearch5(ushort species, BattleVideoRankings5 ranking, BattleVideoMetagames5 metagame, byte country, byte region, int count); public abstract BattleVideoRecord5 BattleVideoGet5(ulong serial, bool incrementViews = false); public abstract bool BattleVideoFlagSaved5(ulong serial); public abstract ulong BattleVideoCount5(); #endregion #region Pokedex creation public abstract void PokedexInsertSpecies(Species s); public abstract void PokedexInsertForm(Form f); public abstract void PokedexInsertFormStats(FormStats f); public abstract void PokedexInsertFormAbilities(FormAbilities f); public abstract void PokedexInsertFamily(Family f); public abstract void PokedexInsertEvolution(Evolution f); public abstract void PokedexInsertType(PkmnFoundations.Pokedex.Type t); public abstract void PokedexInsertItem(Item i); public abstract void PokedexInsertMove(Move m); public abstract void PokedexInsertAbility(Ability a); public abstract void PokedexInsertRibbon(Ribbon r); public abstract void PokedexInsertRegion(Region r); public abstract void PokedexInsertLocation(Location l); #endregion #region Pokedex retrieval public abstract List PokedexGetAllSpecies(Pokedex.Pokedex pokedex); public abstract List PokedexGetAllForms(Pokedex.Pokedex pokedex); public abstract List PokedexGetAllFormStats(Pokedex.Pokedex pokedex); public abstract List PokedexGetAllFormAbilities(Pokedex.Pokedex pokedex); public abstract List PokedexGetAllFamilies(Pokedex.Pokedex pokedex); public abstract List PokedexGetAllEvolutions(Pokedex.Pokedex pokedex); public abstract List PokedexGetAllTypes(Pokedex.Pokedex pokedex); public abstract List PokedexGetAllItems(Pokedex.Pokedex pokedex); public abstract List PokedexGetAllMoves(Pokedex.Pokedex pokedex); public abstract List PokedexGetAllAbilities(Pokedex.Pokedex pokedex); public abstract List PokedexGetAllRibbons(Pokedex.Pokedex pokedex); public abstract List PokedexGetAllRegions(Pokedex.Pokedex pokedex); public abstract List PokedexGetAllLocations(Pokedex.Pokedex pokedex); #endregion } } ================================================ FILE: library/Data/DatabaseExtender.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Data.Common; using System.IO; namespace PkmnFoundations.Data { /// /// Provides extension and convenience methods for working with ADO.NET databases. /// public static class DatabaseExtender { #region Command Execution /// /// Runs a command and returns a DataTable containing its results. /// /// Command already initialized with an open connection public static DataTable ExecuteDataTable(this DbCommand cmd) { IDataReader reader = cmd.ExecuteReader(); DataTable result = new DataTable(); result.Load(reader); return result; } /// /// Runs a command and returns a DataTable containing its results. /// /// Open data connection /// SQL string /// List of parameters to use with the SQL public static DataTable ExecuteDataTable(this DbConnection db, string sqlstr, params IDataParameter[] _params) { IDataReader reader = db.ExecuteReader(sqlstr, _params); DataTable result = new DataTable(); result.Load(reader); return result; } /// /// Runs a command and returns a DataTable containing its results. /// /// Open data connection /// SQL string /// List of parameters to use with the SQL public static DataTable ExecuteDataTable(this DbConnection db, string sqlstr, IEnumerable _params) { IDataReader reader = db.ExecuteReader(sqlstr, _params.ToArray()); DataTable result = new DataTable(); result.Load(reader); return result; } /// /// Runs a command and returns a DataTable containing its results. /// /// Open data connection /// SQL string /// List of parameters to use with the SQL public static DataTable ExecuteDataTable(this DbTransaction tran, string sqlstr, params IDataParameter[] _params) { IDataReader reader = tran.ExecuteReader(sqlstr, _params); DataTable result = new DataTable(); result.Load(reader); return result; } /// /// Runs a command and returns a DataTable containing its results. /// /// Open data connection /// SQL string /// List of parameters to use with the SQL public static DataTable ExecuteDataTable(this DbTransaction tran, string sqlstr, IEnumerable _params) { IDataReader reader = tran.ExecuteReader(sqlstr, _params.ToArray()); DataTable result = new DataTable(); result.Load(reader); return result; } /// /// Runs a command and returns a reader that iterates its results. /// /// Open data connection /// SQL string /// List of parameters to use with the SQL public static IDataReader ExecuteReader(this DbConnection db, string sqlstr, params IDataParameter[] _params) { // hooray DbConnection provides a command factory DbCommand cmd = db.CreateCommand(); cmd.CommandText = sqlstr; // fixme: catch "System.ArgumentException: The SqlParameter is already contained // by another SqlParameterCollection." and add a clone instead cmd.Parameters.AddRange(_params); return cmd.ExecuteReader(); } /// /// Runs a command and returns a reader that iterates its results. /// /// Open data connection /// SQL string /// List of parameters to use with the SQL public static IDataReader ExecuteReader(this DbConnection db, string sqlstr, IEnumerable _params) { return db.ExecuteReader(sqlstr, _params.ToArray()); } /// /// Runs a command and returns a reader that iterates its results. /// /// Open data connection /// SQL string /// List of parameters to use with the SQL public static IDataReader ExecuteReader(this DbTransaction tran, string sqlstr, params IDataParameter[] _params) { // hooray DbConnection provides a command factory DbCommand cmd = tran.Connection.CreateCommand(); cmd.CommandText = sqlstr; cmd.Transaction = tran; cmd.Parameters.AddRange(_params); return cmd.ExecuteReader(); } /// /// Runs a command and returns a reader that iterates its results. /// /// Open data connection /// SQL string /// List of parameters to use with the SQL public static IDataReader ExecuteReader(this DbTransaction tran, string sqlstr, IEnumerable _params) { return tran.ExecuteReader(sqlstr, _params.ToArray()); } /// /// Runs a command and returns the first column of the first row in the query. /// /// Open data connection /// SQL string /// List of parameters to use with the SQL public static object ExecuteScalar(this DbConnection db, string sqlstr, params IDataParameter[] _params) { DbCommand cmd = db.CreateCommand(); cmd.CommandText = sqlstr; cmd.Parameters.AddRange(_params); return cmd.ExecuteScalar(); } /// /// Runs a command and returns the number of rows affected, subject to the usual quirkiness of ExecuteNonQuery. /// /// Open data connection /// SQL string /// List of parameters to use with the SQL public static int ExecuteNonQuery(this DbConnection db, string sqlstr, params IDataParameter[] _params) { DbCommand cmd = db.CreateCommand(); cmd.CommandText = sqlstr; cmd.Parameters.AddRange(_params); return cmd.ExecuteNonQuery(); } /// /// Runs a command and returns the first column of the first row in the query. /// /// Open data connection /// SQL string /// List of parameters to use with the SQL public static object ExecuteScalar(this DbTransaction tran, string sqlstr, params IDataParameter[] _params) { DbCommand cmd = tran.Connection.CreateCommand(); cmd.CommandText = sqlstr; cmd.Transaction = tran; cmd.Parameters.AddRange(_params); return cmd.ExecuteScalar(); } /// /// Runs a command and returns the number of rows affected, subject to the usual quirkiness of ExecuteNonQuery. /// /// Open data connection /// SQL string /// List of parameters to use with the SQL public static int ExecuteNonQuery(this DbTransaction tran, string sqlstr, params IDataParameter[] _params) { DbCommand cmd = tran.Connection.CreateCommand(); cmd.CommandText = sqlstr; cmd.Transaction = tran; cmd.Parameters.AddRange(_params); return cmd.ExecuteNonQuery(); } #endregion #region DataReader convenience /// /// Obtains a string value or returns a default value if null. /// /// Active reader with data /// Column ordinal /// Default value /// public static string GetStringOrDefault(this IDataReader reader, int column, string _default) { return reader.IsDBNull(column) ? _default : reader.GetString(column); } /// /// Obtains a string value or returns an empty string if null. /// /// Active reader with data /// Column ordinal /// public static string GetStringOrDefault(this IDataReader reader, int column) { return reader.IsDBNull(column) ? "" : reader.GetString(column); } /// /// Obtains a string value or returns a default value if null. /// /// Active reader with data /// Column name /// Default value /// public static string GetStringOrDefault(this IDataReader reader, string column, string _default) { return (reader[column] is DBNull) ? _default : (string)reader[column]; } /// /// Obtains a string value or returns an empty string if null. /// /// Active reader with data /// Column name /// public static string GetStringOrDefault(this IDataReader reader, string column) { return (reader[column] is DBNull) ? "" : (string)reader[column]; } public static void GetBytes(this IDataReader reader, string column, long fieldOffset, byte[] buffer, int bufferOffset, int length) { reader.GetBytes(reader.GetOrdinal(column), fieldOffset, buffer, bufferOffset, length); } public static byte[] GetByteArray(this IDataReader reader, int column) { // optimized version of http://msdn.microsoft.com/en-us/library/87z0hy49%28v=vs.110%29.aspx MemoryStream m = new MemoryStream(); const int BUFFER_LENGTH = 256; byte[] buffer = new byte[BUFFER_LENGTH]; long progress = 0; long lastProgress; do { lastProgress = reader.GetBytes(column, progress, buffer, 0, BUFFER_LENGTH); m.Write(buffer, 0, (int)lastProgress); progress += lastProgress; } while (lastProgress == BUFFER_LENGTH); m.Flush(); return m.GetBuffer(); } public static byte[] GetByteArray(this IDataReader reader, int column, int length) { byte[] result = new byte[length]; reader.GetBytes(column, 0, result, 0, length); return result; } public static byte[] GetByteArray(this IDataReader reader, string column) { return GetByteArray(reader, reader.GetOrdinal(column)); } public static byte[] GetByteArray(this IDataReader reader, string column, int length) { return GetByteArray(reader, reader.GetOrdinal(column), length); } public static bool IsDBNull(this IDataReader reader, string column) { return reader.IsDBNull(reader.GetOrdinal(column)); } #endregion public static T Cast(object value) { if (value is DBNull) value = null; return (T)value; // Allow InvalidCastException to escape. } public static List Collect(this IDataReader reader, Func collector) { List result = new List(); while (reader.Read()) { result.Add(collector(reader)); } return result; } public static List ExecuteCollection(this DbConnection conn, string sqlstr, Func collector, params IDataParameter[] _params) { return conn.ExecuteReader(sqlstr, _params).Collect(collector); } public static List ExecuteCollection(this DbTransaction tran, string sqlstr, Func collector, params IDataParameter[] _params) { return tran.ExecuteReader(sqlstr, _params).Collect(collector); } public static List ExecuteCollection(this DbCommand cmd, Func collector) { return cmd.ExecuteReader().Collect(collector); } } } ================================================ FILE: library/Data/MySqlDatabaseExtender.cs ================================================ using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using MySql.Data.MySqlClient; namespace PkmnFoundations.Data { public static class MySqlDatabaseExtender { // I can't find anything like a "parameter factory" in ADO.NET nor a virutal clone method, // so we need an implementation of these for each database engine. /// /// Creates a clone of the SqlParameter collection /// /// Collection to be cloned public static MySqlParameter[] CloneParameters(this IEnumerable collection) { int count = collection.Count(); MySqlParameter[] result = new MySqlParameter[count]; int x = 0; foreach (MySqlParameter p in collection) { result[x] = p.CloneParameter(); x++; } return result; } public static MySqlParameter CloneParameter(this MySqlParameter param) { MySqlParameter result = new MySqlParameter(param.ParameterName, (MySqlDbType)param.DbType, param.Size, param.Direction, param.IsNullable, param.Precision, param.Scale, param.SourceColumn, param.SourceVersion, param.Value); result.DbType = param.DbType; return result; } /// /// Runs a proc and returns its return value. /// /// Open data connection /// SQL string /// Return value's expected type /// List of parameters to use with the SQL public static object ExecuteProcedure(this MySqlConnection db, string name, MySqlDbType return_type, params MySqlParameter[] _params) { return ExecuteProcedureInternal(db.CreateCommand(), name, return_type, _params); } /// /// Runs a proc. /// /// Open data connection /// SQL string /// List of parameters to use with the SQL public static int ExecuteProcedure(this MySqlConnection db, string name, params MySqlParameter[] _params) { MySqlCommand cmd = db.CreateCommand(); cmd.CommandText = name; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddRange(_params); return cmd.ExecuteNonQuery(); } /// /// Runs a proc and returns its return value. /// /// Open data connection /// SQL string /// Return value's expected type /// List of parameters to use with the SQL public static object ExecuteProcedure(this MySqlTransaction tran, string name, MySqlDbType return_type, params MySqlParameter[] _params) { MySqlCommand cmd = tran.Connection.CreateCommand(); cmd.Transaction = tran; return ExecuteProcedureInternal(cmd, name, return_type, _params); } /// /// Runs a proc. /// /// Open data connection /// SQL string /// List of parameters to use with the SQL public static int ExecuteProcedure(this MySqlTransaction tran, string name, params MySqlParameter[] _params) { MySqlCommand cmd = tran.Connection.CreateCommand(); cmd.CommandText = name; cmd.Transaction = tran; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddRange(_params); return cmd.ExecuteNonQuery(); } private static object ExecuteProcedureInternal(MySqlCommand cmd, string name, MySqlDbType return_type, MySqlParameter[] _params) { cmd.CommandText = name; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddRange(_params); string pname = "result"; while (cmd.Parameters.Contains("@" + pname)) pname = "x" + pname; pname = "@" + pname; MySqlParameter p = new MySqlParameter(pname, return_type); p.Direction = ParameterDirection.ReturnValue; cmd.Parameters.Add(p); cmd.ExecuteNonQuery(); return cmd.Parameters[pname].Value; } } } ================================================ FILE: library/Data/SqlDatabaseExtender.cs ================================================ using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; namespace PkmnFoundations.Data { public static class SqlDatabaseExtender { // I can't find anything like a "parameter factory" in ADO.NET nor a virutal clone method, // so we need an implementation of these for each database engine. /// /// Creates a clone of the SqlParameter collection /// /// Collection to be cloned public static SqlParameter[] CloneParameters(this IEnumerable collection) { int count = collection.Count(); SqlParameter[] result = new SqlParameter[count]; int x = 0; foreach (SqlParameter p in collection) { SqlParameter param = new SqlParameter(p.ParameterName, (SqlDbType)p.DbType, p.Size, p.Direction, p.IsNullable, p.Precision, p.Scale, p.SourceColumn, p.SourceVersion, p.Value); param.DbType = p.DbType; result[x] = param; x++; } return result; } /// /// Runs a proc and returns its return value. /// /// Open data connection /// SQL string /// Return value's expected type /// List of parameters to use with the SQL public static object ExecuteProcedure(this SqlConnection db, string name, SqlDbType return_type, params SqlParameter[] _params) { return ExecuteProcedureInternal(db.CreateCommand(), name, return_type, _params); } /// /// Runs a proc. /// /// Open data connection /// SQL string /// List of parameters to use with the SQL public static int ExecuteProcedure(this SqlConnection db, string name, params SqlParameter[] _params) { SqlCommand cmd = db.CreateCommand(); cmd.CommandText = name; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddRange(_params); return cmd.ExecuteNonQuery(); } /// /// Runs a proc and returns its return value. /// /// Open data connection /// SQL string /// Return value's expected type /// List of parameters to use with the SQL public static object ExecuteProcedure(this SqlTransaction tran, string name, SqlDbType return_type, params SqlParameter[] _params) { SqlCommand cmd = tran.Connection.CreateCommand(); cmd.Transaction = tran; return ExecuteProcedureInternal(cmd, name, return_type, _params); } /// /// Runs a proc. /// /// Open data connection /// SQL string /// List of parameters to use with the SQL public static int ExecuteProcedure(this SqlTransaction tran, string name, params SqlParameter[] _params) { SqlCommand cmd = tran.Connection.CreateCommand(); cmd.CommandText = name; cmd.Transaction = tran; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddRange(_params); return cmd.ExecuteNonQuery(); } private static object ExecuteProcedureInternal(SqlCommand cmd, string name, SqlDbType return_type, SqlParameter[] _params) { cmd.CommandText = name; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddRange(_params); string pname = "result"; while (cmd.Parameters.Contains("@" + pname)) pname = "x" + pname; pname = "@" + pname; SqlParameter p = new SqlParameter(pname, return_type); p.Direction = ParameterDirection.ReturnValue; cmd.Parameters.Add(p); cmd.ExecuteNonQuery(); return cmd.Parameters[pname].Value; } } } ================================================ FILE: library/Library.csproj ================================================  Debug AnyCPU 8.0.30703 2.0 {408EFC7E-C6B0-4160-8628-2679E34385CE} Library Properties PkmnFoundations PkmnFoundations.Library v3.5 512 21c4ccbf true full false bin\Debug\ DEBUG;TRACE prompt 4 AnyCPU pdbonly true bin\Release\ TRACE prompt 4 ..\packages\MySql.Data.6.9.8\lib\net20\MySql.Data.dll False ..\packages\System.Data.SQLite.Core.1.0.94.0\lib\net20\System.Data.SQLite.dll ..\packages\System.Data.SQLite.Linq.1.0.94.1\lib\net20\System.Data.SQLite.Linq.dll This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. ================================================ FILE: library/Pokedex/Ability.cs ================================================ using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using PkmnFoundations.Support; namespace PkmnFoundations.Pokedex { public class Ability : PokedexRecordBase { public Ability(Pokedex pokedex, int value, LocalizedString name) : base(pokedex) { Value = value; Name = name; // todo: Nice description text } public Ability(Pokedex pokedex, IDataReader reader) : this( pokedex, Convert.ToInt32(reader["Value"]), LocalizedStringFromReader(reader, "Name_") ) { } public int Value { get; private set; } public LocalizedString Name { get; private set; } public static LazyKeyValuePair CreatePair(Pokedex pokedex) { return new LazyKeyValuePair( k => k == 0 ? null : (pokedex == null ? null : pokedex.Abilities[k]), v => v == null ? 0 : v.Value); } } } ================================================ FILE: library/Pokedex/Evolution.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PkmnFoundations.Pokedex { public class Evolution //: PokedexRecordBase { } } ================================================ FILE: library/Pokedex/Family.cs ================================================ using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using PkmnFoundations.Support; namespace PkmnFoundations.Pokedex { public class Family : PokedexRecordBase { public Family(Pokedex pokedex, int id, int basic_male_id, int basic_female_id, int baby_male_id, int baby_female_id, int incense_id, byte gender_ratio) : base(pokedex) { m_basic_male_pair = Species.CreatePair(m_pokedex); m_basic_female_pair = Species.CreatePair(m_pokedex); m_baby_male_pair = Species.CreatePair(m_pokedex); m_baby_female_pair = Species.CreatePair(m_pokedex); m_incense_pair = Item.CreatePair(m_pokedex); m_lazy_pairs.Add(m_basic_male_pair); m_lazy_pairs.Add(m_basic_female_pair); m_lazy_pairs.Add(m_baby_male_pair); m_lazy_pairs.Add(m_baby_female_pair); m_lazy_pairs.Add(m_incense_pair); ID = id; m_basic_male_pair.Key = basic_male_id; m_basic_female_pair.Key = basic_female_id; m_baby_male_pair.Key = baby_male_id; m_baby_female_pair.Key = baby_female_id; m_incense_pair.Key = incense_id; GenderRatio = gender_ratio; } public Family(Pokedex pokedex, IDataReader reader) : this( pokedex, Convert.ToInt32(reader["id"]), Convert.ToInt32(reader["BasicMale"]), Convert.ToInt32(reader["BasicFemale"]), Convert.ToInt32(reader["BabyMale"]), Convert.ToInt32(reader["BabyFemale"]), Convert.ToInt32(reader["Incense"]), Convert.ToByte(reader["GenderRatio"]) ) { } public int ID { get; private set; } public byte GenderRatio { get; private set; } private LazyKeyValuePair m_basic_male_pair; private LazyKeyValuePair m_basic_female_pair; private LazyKeyValuePair m_baby_male_pair; private LazyKeyValuePair m_baby_female_pair; private LazyKeyValuePair m_incense_pair; public int BasicMaleID { get { return m_basic_male_pair.Key; } } public Species BasicMale { get { return m_basic_male_pair.Value; } } public int BasicFemaleID { get { return m_basic_female_pair.Key; } } public Species BasicFemale { get { return m_basic_female_pair.Value; } } public int BabyMaleID { get { return m_baby_male_pair.Key; } } public Species BabyMale { get { return m_baby_male_pair.Value; } } public int BabyFemaleID { get { return m_baby_female_pair.Key; } } public Species BabyFemale { get { return m_baby_female_pair.Value; } } public int IncenseID { get { return m_incense_pair.Key; } } public Item Incense { get { return m_incense_pair.Value; } } public static LazyKeyValuePair CreatePair(Pokedex pokedex) { return new LazyKeyValuePair( k => k == 0 ? null : (pokedex == null ? null : pokedex.Families[k]), v => v == null ? 0 : v.ID); } } } ================================================ FILE: library/Pokedex/Form.cs ================================================ using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using PkmnFoundations.Structures; using PkmnFoundations.Support; namespace PkmnFoundations.Pokedex { public class Form : PokedexRecordBase { public Form(Pokedex pokedex, int id, int species_id, byte value, LocalizedString name, string suffix, int height, int weight, int experience) : base(pokedex) { m_species_pair = Species.CreatePair(m_pokedex); m_lazy_pairs.Add(m_species_pair); ID = id; m_species_pair.Key = species_id; Value = value; Name = name; Suffix = suffix; Height = height; Weight = weight; Experience = experience; } public Form(Pokedex pokedex, IDataReader reader) : this( pokedex, Convert.ToInt32(reader["id"]), Convert.ToInt32(reader["NationalDex"]), Convert.ToByte(reader["FormValue"]), LocalizedStringFromReader(reader, "Name_"), reader["FormSuffix"].ToString(), Convert.ToInt32(reader["Height"]), Convert.ToInt32(reader["Weight"]), Convert.ToInt32(reader["Experience"]) ) { } internal override void PrefetchRelations() { base.PrefetchRelations(); m_form_stats = m_pokedex.FormStats(ID); m_form_abilities = m_pokedex.FormAbilities(ID); } public int ID { get; private set; } public byte Value { get; private set; } public LocalizedString Name { get; private set; } public string Suffix { get; private set; } public int Height { get; private set; } public int Weight { get; private set; } public int Experience { get; private set; } private LazyKeyValuePair m_species_pair; public int SpeciesID { get { return m_species_pair.Key; } } public Species Species { get { return m_species_pair.Value; } } private SortedList m_form_stats; public FormStats BaseStats(Generations generation) { if (m_form_stats == null) m_form_stats = m_pokedex.FormStats(ID); // xxx: this is O(n) and we can do O(log n) but it requires rolling // our own binary search and YAGNI for a list of at most 6 values. // http://stackoverflow.com/questions/20474896/finding-nearest-value-in-a-sorteddictionary return m_form_stats.Last(pair => (int)(pair.Key) <= (int)generation).Value; } private SortedList m_form_abilities; public FormAbilities Abilities(Generations generation) { if (m_form_abilities == null) m_form_abilities = m_pokedex.FormAbilities(ID); // xxx: above return m_form_abilities.Last(pair => (int)(pair.Key) <= (int)generation).Value; } public static LazyKeyValuePair CreatePair(Pokedex pokedex) { return new LazyKeyValuePair( k => k == 0 ? null : (pokedex == null ? null : pokedex.Forms[k]), v => v == null ? 0 : v.ID); } public static LazyKeyValuePair CreatePairForSpecies(Pokedex pokedex, Func speciesGetter) { // 0 is a valid value here--don't map it to null! return new LazyKeyValuePair( k => speciesGetter().Forms(k), v => v.Value); } } } ================================================ FILE: library/Pokedex/FormAbilities.cs ================================================ using PkmnFoundations.Data; using PkmnFoundations.Structures; using PkmnFoundations.Support; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; namespace PkmnFoundations.Pokedex { public class FormAbilities : PokedexRecordBase { public FormAbilities(Pokedex pokedex, int form_id, Generations min_generation, int ability1, int ability2, int hiddenAbility1) : base(pokedex) { m_form_pair = Form.CreatePair(m_pokedex); m_ability1_pair = Ability.CreatePair(m_pokedex); m_ability2_pair = Ability.CreatePair(m_pokedex); m_hidden_ability1_pair = Ability.CreatePair(m_pokedex); m_lazy_pairs.Add(m_form_pair); m_lazy_pairs.Add(m_ability1_pair); m_lazy_pairs.Add(m_hidden_ability1_pair); m_form_pair.Key = form_id; MinGeneration = min_generation; m_ability1_pair.Key = ability1; m_ability2_pair.Key = ability2; m_hidden_ability1_pair.Key = hiddenAbility1; } public FormAbilities(Pokedex pokedex, IDataReader reader) : this( pokedex, Convert.ToInt32(reader["form_id"]), (Generations)Convert.ToInt32(reader["MinGeneration"]), (int)(DatabaseExtender.Cast(reader["Ability1"]) ?? 0), (int)(DatabaseExtender.Cast(reader["Ability2"]) ?? 0), (int)(DatabaseExtender.Cast(reader["HiddenAbility1"]) ?? 0) ) { } public Generations MinGeneration { get; private set; } private LazyKeyValuePair m_form_pair; private LazyKeyValuePair m_ability1_pair; private LazyKeyValuePair m_ability2_pair; private LazyKeyValuePair m_hidden_ability1_pair; public int FormID { get { return m_form_pair.Key; } } public Form Form { get { return m_form_pair.Value; } } public int Ability1ID { get { return m_ability1_pair.Key; } } public Ability Ability1 { get { return m_ability1_pair.Value; } } public int Ability2ID { get { return m_ability2_pair.Key; } } public Ability Ability2 { get { return m_ability2_pair.Value; } } public int HiddenAbility1ID { get { return m_hidden_ability1_pair.Key; } } public Ability HiddenAbility1 { get { return m_hidden_ability1_pair.Value; } } public Ability[] Abilities { get { // xxx: We probably want the actual data to be stored in a collection to avoid this silly if-else. if (Ability1 != null && Ability2 != null) return new Ability[] { Ability1, Ability2 }; else if (Ability1 != null) return new Ability[] { Ability1 }; else if (Ability2 != null) return new Ability[] { Ability2 }; else return new Ability[] { }; } } public Ability[] HiddenAbilities { get { if (HiddenAbility1 != null) return new Ability[] { HiddenAbility1 }; else return new Ability[] { }; } } } } ================================================ FILE: library/Pokedex/FormStats.cs ================================================ using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using PkmnFoundations.Structures; using PkmnFoundations.Support; namespace PkmnFoundations.Pokedex { public class FormStats : PokedexRecordBase { public FormStats(Pokedex pokedex, int form_id, Generations min_generation, int type1, int type2, IntStatValues base_stats, ByteStatValues reward_evs) : base(pokedex) { m_form_pair = Form.CreatePair(m_pokedex); // xxx: Do we maybe want to expose types as some sort of collection maybe? m_type1_pair = Type.CreatePair(m_pokedex); m_type2_pair = Type.CreatePair(m_pokedex); m_lazy_pairs.Add(m_form_pair); m_lazy_pairs.Add(m_type1_pair); m_lazy_pairs.Add(m_type2_pair); m_form_pair.Key = form_id; MinGeneration = min_generation; m_type1_pair.Key = type1; m_type2_pair.Key = type2; BaseStats = base_stats; RewardEvs = reward_evs; } public FormStats(Pokedex pokedex, IDataReader reader) : this( pokedex, Convert.ToInt32(reader["form_id"]), (Generations)Convert.ToInt32(reader["MinGeneration"]), Convert.ToInt32(reader["Type1"]), Convert.ToInt32(reader["Type2"]), new IntStatValues( Convert.ToInt32(reader["BaseHP"]), Convert.ToInt32(reader["BaseAttack"]), Convert.ToInt32(reader["BaseDefense"]), Convert.ToInt32(reader["BaseSpeed"]), Convert.ToInt32(reader["BaseSpAttack"]), Convert.ToInt32(reader["BaseSpDefense"]) ), new ByteStatValues( Convert.ToByte(reader["RewardHP"]), Convert.ToByte(reader["RewardAttack"]), Convert.ToByte(reader["RewardDefense"]), Convert.ToByte(reader["RewardSpeed"]), Convert.ToByte(reader["RewardSpAttack"]), Convert.ToByte(reader["RewardSpDefense"]) ) ) { } public Generations MinGeneration { get; private set; } public IntStatValues BaseStats { get; private set; } public ByteStatValues RewardEvs { get; private set; } private LazyKeyValuePair m_form_pair; private LazyKeyValuePair m_type1_pair; private LazyKeyValuePair m_type2_pair; public int FormID { get { return m_form_pair.Key; } } public Form Form { get { return m_form_pair.Value; } } public int Type1ID { get { return m_type1_pair.Key; } } public PkmnFoundations.Pokedex.Type Type1 { get { return m_type1_pair.Value; } } public int Type2ID { get { return m_type2_pair.Key; } } public PkmnFoundations.Pokedex.Type Type2 { get { return m_type2_pair.Value; } } } } ================================================ FILE: library/Pokedex/Item.cs ================================================ using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using PkmnFoundations.Structures; using PkmnFoundations.Support; namespace PkmnFoundations.Pokedex { public class Item : PokedexRecordBase { public Item(Pokedex pokedex, int id, int ? value3, int ? value4, int ? value5, int ? value6, int ? pokeball_value, int price, LocalizedString name) : base(pokedex) { ID = id; // todo: Since ID numbers stopped moving around in Gen 4 -> 5, we // only need to store value3, value4 and a minGenerationRequired field Value3 = value3; Value4 = value4; Value5 = value5; Value6 = value6; PokeballValue = pokeball_value; Price = price; Name = name; } public Item(Pokedex pokedex, IDataReader reader) : this( pokedex, Convert.ToInt32(reader["id"]), reader["Value3"] is DBNull ? null : (int?)Convert.ToInt32(reader["Value3"]), reader["Value4"] is DBNull ? null : (int?)Convert.ToInt32(reader["Value4"]), reader["Value5"] is DBNull ? null : (int?)Convert.ToInt32(reader["Value5"]), reader["Value6"] is DBNull ? null : (int?)Convert.ToInt32(reader["Value6"]), reader["PokeballValue"] is DBNull ? null : (int?)Convert.ToInt32(reader["PokeballValue"]), Convert.ToInt32(reader["Price"]), LocalizedStringFromReader(reader, "Name_") ) { } public int ID { get; private set; } public int ? Value3 { get; private set; } public int ? Value4 { get; private set; } public int ? Value5 { get; private set; } public int ? Value6 { get; private set; } public int Price { get; private set; } public LocalizedString Name { get; private set; } public int ? Value(Generations generation) { switch (generation) { case Generations.Generation1: case Generations.Generation2: throw new NotSupportedException(); case Generations.Generation3: return Value3; case Generations.Generation4: return Value4; case Generations.Generation5: return Value5; case Generations.Generation6: default: return Value6; } } public int ? PokeballValue { get; private set; } public static LazyKeyValuePair CreatePair(Pokedex pokedex) { return new LazyKeyValuePair( k => k == 0 ? null : (pokedex == null ? null : pokedex.Items[k]), v => v == null ? 0 : v.ID); } public static LazyKeyValuePair CreatePairForGeneration(Pokedex pokedex, Func generationGetter) { return new LazyKeyValuePair( k => k == 0 ? null : (pokedex == null ? null : pokedex.ItemsByGeneration(generationGetter())[k]), v => v == null ? 0 : (v.Value(generationGetter()) ?? -1)); } public static LazyKeyValuePair CreatePairPokeball(Pokedex pokedex) { return new LazyKeyValuePair( k => k == 0 ? null : (pokedex == null ? null : pokedex.Pokeballs[k]), v => v == null ? 0 : v.ID); } } } ================================================ FILE: library/Pokedex/Location.cs ================================================ using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using PkmnFoundations.Data; using PkmnFoundations.Structures; using PkmnFoundations.Support; namespace PkmnFoundations.Pokedex { public class Location : PokedexRecordBase { public Location(Pokedex pokedex, int id, int region_id, int ? value3, int ? value_colo, int ? value_xd, int ? value4, int ? value5, int ? value6, LocalizedString name) : base(pokedex) { m_region_pair = Region.CreatePair(m_pokedex); m_lazy_pairs.Add(m_region_pair); ID = id; m_region_pair.Key = region_id; Value3 = value3; ValueColo = value_colo; ValueXd = value_xd; Value4 = value4; Value5 = value5; Value6 = value6; Name = name; } public Location(Pokedex pokedex, IDataReader reader) : this(pokedex, Convert.ToInt32(reader["id"]), Convert.ToInt32(reader["region_id"]), (int ?)DatabaseExtender.Cast(reader["Value3"]), (int?)DatabaseExtender.Cast(reader["Value_Colo"]), (int?)DatabaseExtender.Cast(reader["Value_XD"]), (int?)DatabaseExtender.Cast(reader["Value4"]), (int?)DatabaseExtender.Cast(reader["Value5"]), (int?)DatabaseExtender.Cast(reader["Value6"]), LocalizedStringFromReader(reader, "Name_")) { } public int ID { get; private set; } public LocalizedString Name { get; private set; } private LazyKeyValuePair m_region_pair; public int RegionID { get { return m_region_pair.Key; } } public Region Region { get { return m_region_pair.Value; } } // xxx: All these 3/4/5/6 fields are repetitive. // We need a GenerationField helper which bottles them all up into // one field. Basically Dictionary but with a helper to // pull out a T ? public int? Value3 { get; private set; } public int? ValueColo { get; private set; } public int? ValueXd { get; private set; } public int? Value4 { get; private set; } public int? Value5 { get; private set; } public int? Value6 { get; private set; } public int? Value(Generations generation) { LocationNumbering numbering = GenerationToLocationNumbering(generation); return Value(numbering); } public int ? Value(LocationNumbering numbering) { switch (numbering) { case LocationNumbering.Generation1: case LocationNumbering.Generation2: throw new NotSupportedException(); case LocationNumbering.Generation3: return Value3; case LocationNumbering.Colosseum: return ValueColo; case LocationNumbering.XD: return ValueXd; case LocationNumbering.Generation4: return Value4; case LocationNumbering.Generation5: return Value5; case LocationNumbering.Generation6: return Value6; default: throw new ArgumentException(); } } public static LocationNumbering GenerationToLocationNumbering(Generations generation) { switch (generation) { case Generations.Generation1: return LocationNumbering.Generation1; case Generations.Generation2: return LocationNumbering.Generation2; case Generations.Generation3: return LocationNumbering.Generation3; case Generations.Generation4: return LocationNumbering.Generation4; case Generations.Generation5: return LocationNumbering.Generation5; case Generations.Generation6: return LocationNumbering.Generation6; default: throw new ArgumentException(); } } public static LazyKeyValuePair CreatePair(Pokedex pokedex) { return new LazyKeyValuePair( k => k == 0 ? null : (pokedex == null ? null : pokedex.Locations[k]), v => v == null ? 0 : v.ID); } public static LazyKeyValuePair CreatePairForGeneration(Pokedex pokedex, Func generationGetter) { return new LazyKeyValuePair( k => { if (k == 0) return null; if (pokedex == null) return null; var locations = pokedex.LocationsByGeneration(GenerationToLocationNumbering(generationGetter())); if (locations == null) return null; if (!locations.ContainsKey(k)) return null; return locations[k]; }, v => v == null ? 0 : (v.Value(generationGetter()) ?? -1)); } public static LazyKeyValuePair CreatePairForLocationNumbering(Pokedex pokedex, Func generationGetter) { return new LazyKeyValuePair( k => { if (k == 0) return null; if (pokedex == null) return null; var locations = pokedex.LocationsByGeneration(generationGetter()); if (locations == null) return null; if (!locations.ContainsKey(k)) return null; return locations[k]; }, v => v == null ? 0 : (v.Value(generationGetter()) ?? -1)); } } } ================================================ FILE: library/Pokedex/Move.cs ================================================ using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using PkmnFoundations.Structures; using PkmnFoundations.Support; namespace PkmnFoundations.Pokedex { public class Move : PokedexRecordBase { public Move(Pokedex pokedex, int id, int type_id, LocalizedString name, DamageClass damage_class, int damage, int pp, int accuracy, int priority, BattleTargets target) : base(pokedex) { m_type_pair = Type.CreatePair(m_pokedex); m_lazy_pairs.Add(m_type_pair); ID = id; m_type_pair.Key = type_id; Name = name; DamageClass = damage_class; Damage = damage; PP = pp; Accuracy = accuracy; Priority = priority; Target = target; // todo: Nice description text } public Move(Pokedex pokedex, IDataReader reader) : this( pokedex, Convert.ToInt32(reader["Value"]), Convert.ToInt32(reader["type_id"]), LocalizedStringFromReader(reader, "Name_"), (DamageClass)Convert.ToInt32(reader["DamageClass"]), Convert.ToInt32(reader["Damage"]), Convert.ToInt32(reader["PP"]), Convert.ToInt32(reader["Accuracy"]), Convert.ToInt32(reader["Priority"]), (BattleTargets)Convert.ToInt32(reader["Target"]) ) { } public int ID { get; private set; } public LocalizedString Name { get; private set; } public DamageClass DamageClass { get; private set; } public int Damage { get; private set; } public int PP { get; private set; } public int Accuracy { get; private set; } public int Priority { get; private set; } public BattleTargets Target { get; private set; } private LazyKeyValuePair m_type_pair; public int TypeID { get { return m_type_pair.Key; } } public PkmnFoundations.Pokedex.Type Type { get { return m_type_pair.Value; } } public static LazyKeyValuePair CreatePair(Pokedex pokedex) { return new LazyKeyValuePair( k => k == 0 ? null : (pokedex == null ? null : pokedex.Moves[k]), v => v == null ? 0 : v.ID); } } } ================================================ FILE: library/Pokedex/Pokedex.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using PkmnFoundations.Data; using PkmnFoundations.Structures; using PkmnFoundations.Support; namespace PkmnFoundations.Pokedex { public class Pokedex { public Pokedex(Database db, bool lazy) { if (lazy) throw new NotImplementedException(); GetAllData(db); BuildAdditionalIndexes(); PrefetchRelations(); } private void GetAllData(Database db) { m_species = db.PokedexGetAllSpecies(this).ToDictionary(s => s.NationalDex, s => s); m_families = db.PokedexGetAllFamilies(this).ToDictionary(f => f.ID, f => f); m_forms = db.PokedexGetAllForms(this).ToDictionary(f => f.ID, f => f); m_items = db.PokedexGetAllItems(this).ToDictionary(i => i.ID, i => i); m_moves = db.PokedexGetAllMoves(this).ToDictionary(m => m.ID, m => m); m_types = db.PokedexGetAllTypes(this).ToDictionary(t => t.ID, t => t); m_abilities = db.PokedexGetAllAbilities(this).ToDictionary(a => a.Value, a => a); m_ribbons = db.PokedexGetAllRibbons(this).ToDictionary(r => r.ID, r => r); m_regions = db.PokedexGetAllRegions(this).ToDictionary(r => r.ID, r => r); m_locations = db.PokedexGetAllLocations(this).ToDictionary(l => l.ID, l => l); List form_stats = db.PokedexGetAllFormStats(this); m_form_stats = ProcessGenerationalChangeset(form_stats, fs => fs.FormID, fs => fs.MinGeneration); List form_abilities = db.PokedexGetAllFormAbilities(this); m_form_abilities = ProcessGenerationalChangeset(form_abilities, fa => fa.FormID, fa => fa.MinGeneration); } private void BuildAdditionalIndexes() { m_forms_by_value = new Dictionary>(); foreach (var pair in m_species) m_forms_by_value.Add(pair.Key, new Dictionary()); foreach (var pair in m_forms) { #if !DEBUG if (!m_forms_by_value[pair.Value.SpeciesID].ContainsKey(pair.Value.Value)) #endif m_forms_by_value[pair.Value.SpeciesID].Add(pair.Value.Value, pair.Value); } Dictionary items3 = new Dictionary(); Dictionary items4 = new Dictionary(); Dictionary items5 = new Dictionary(); Dictionary items6 = new Dictionary(); m_items_generations = new Dictionary>(); m_items_generations.Add(Generations.Generation3, items3); m_items_generations.Add(Generations.Generation4, items4); m_items_generations.Add(Generations.Generation5, items5); m_items_generations.Add(Generations.Generation6, items6); m_pokeballs = new Dictionary(); foreach (var pair in m_items) { Item i = pair.Value; if (i.Value3 != null) items3.Add((int)i.Value3, i); if (i.Value4 != null) items4.Add((int)i.Value4, i); if (i.Value5 != null) items5.Add((int)i.Value5, i); if (i.Value6 != null) items6.Add((int)i.Value6, i); if (i.PokeballValue != null) m_pokeballs.Add((int)i.PokeballValue, i); } m_ribbon_positions_generations = new Dictionary>(); AddGeneration(m_ribbon_positions_generations, m_ribbons, Generations.Generation3, r => r.Position3); AddGeneration(m_ribbon_positions_generations, m_ribbons, Generations.Generation4, r => r.Position4); AddGeneration(m_ribbon_positions_generations, m_ribbons, Generations.Generation5, r => r.Position5); AddGeneration(m_ribbon_positions_generations, m_ribbons, Generations.Generation6, r => r.Position6); m_ribbon_values_generations = new Dictionary>(); AddGeneration(m_ribbon_values_generations, m_ribbons, Generations.Generation3, r => r.Value3); AddGeneration(m_ribbon_values_generations, m_ribbons, Generations.Generation4, r => r.Value4); AddGeneration(m_ribbon_values_generations, m_ribbons, Generations.Generation5, r => r.Value5); AddGeneration(m_ribbon_values_generations, m_ribbons, Generations.Generation6, r => r.Value6); m_location_values_generations = new Dictionary>(); AddGeneration(m_location_values_generations, m_locations, LocationNumbering.Generation3, l => l.Value3); AddGeneration(m_location_values_generations, m_locations, LocationNumbering.Generation4, l => l.Value4); AddGeneration(m_location_values_generations, m_locations, LocationNumbering.Generation5, l => l.Value5); AddGeneration(m_location_values_generations, m_locations, LocationNumbering.Generation6, l => l.Value6); } private Dictionary> ProcessGenerationalChangeset(List data, Func idGetter, Func minGenerationGetter) { // xxx: Instead of passing in these two lamdbas, we want an IGenerationalChangesetItem interface with corresponding properties. var sorted = data.ToList(); sorted.Sort(delegate (T f, T other) { int idF = idGetter(f); int idOther = idGetter(other); if (idF != idOther) return idF.CompareTo(idOther); Generations genF = minGenerationGetter(f); Generations genOther = minGenerationGetter(other); return genF.CompareTo(genOther); }); Dictionary> resultFormStats = new Dictionary>(); SortedList currFormStats = null; int currFormId = 0; foreach (T f in sorted) { int idF = idGetter(f); if (currFormStats == null || currFormId != idF) { if (currFormStats != null) resultFormStats.Add(currFormId, currFormStats); currFormStats = new SortedList(); } currFormStats.Add(minGenerationGetter(f), f); currFormId = idF; } if (currFormStats != null) resultFormStats.Add(currFormId, currFormStats); return resultFormStats; } private void AddGeneration(Dictionary> dest, Dictionary src, TGen generation, Func keyGetter) where TKey : struct { dest.Add(generation, src.Where(pair => keyGetter(pair.Value) != null) .ToDictionary(pair => (TKey)keyGetter(pair.Value), pair => pair.Value)); } private void PrefetchRelations() { // xxx: clean this up // todo: reflect these classes to decide whether or not prefetching // is even needed foreach (var k in m_species) k.Value.PrefetchRelations(); foreach (var k in m_families) k.Value.PrefetchRelations(); foreach (var k in m_forms) k.Value.PrefetchRelations(); foreach (var k in m_items) k.Value.PrefetchRelations(); foreach (var k in m_moves) k.Value.PrefetchRelations(); foreach (var k in m_types) k.Value.PrefetchRelations(); foreach (var k in m_abilities) k.Value.PrefetchRelations(); foreach (var k in m_ribbons) k.Value.PrefetchRelations(); foreach (var k in m_regions) k.Value.PrefetchRelations(); foreach (var k in m_locations) k.Value.PrefetchRelations(); foreach (var k in m_form_stats) { foreach (var j in k.Value) j.Value.PrefetchRelations(); } foreach (var k in m_form_abilities) { foreach (var j in k.Value) j.Value.PrefetchRelations(); } } private Dictionary m_species; private Dictionary m_families; private Dictionary m_forms; private Dictionary> m_forms_by_value; private Dictionary> m_form_stats; private Dictionary> m_form_abilities; //private Dictionary m_evolutions; private Dictionary m_items; private Dictionary m_moves; private Dictionary m_types; private Dictionary m_abilities; private Dictionary m_ribbons; private Dictionary> m_items_generations; private Dictionary m_pokeballs; private Dictionary> m_ribbon_positions_generations; private Dictionary> m_ribbon_values_generations; private Dictionary m_regions; private Dictionary m_locations; private Dictionary> m_location_values_generations; // todo: use readonly wrappers public IDictionary Species { get { return m_species; } } public IDictionary Families { get { return m_families; } } public IDictionary Forms { get { return m_forms; } } internal Dictionary FormsByValue(int national_dex) { return m_forms_by_value[national_dex]; } internal SortedList FormStats(int form_id) { return m_form_stats[form_id]; } internal SortedList FormAbilities(int form_id) { return m_form_abilities[form_id]; } public IDictionary Items { get { return m_items; } } public IDictionary ItemsByGeneration(Generations generation) { return m_items_generations[generation]; } public IDictionary Pokeballs { get { return m_pokeballs; } } public IDictionary Moves { get { return m_moves; } } public IDictionary Types { get { return m_types; } } public IDictionary Abilities { get { return m_abilities; } } public IDictionary Ribbons { get { return m_ribbons; } } public IDictionary RibbonsByGeneration(Generations generation) { return m_ribbon_positions_generations[generation]; } public IDictionary Regions { get { return m_regions; } } public IDictionary Locations { get { return m_locations; } } public IDictionary LocationsByGeneration(LocationNumbering generation) { return m_location_values_generations[generation]; } public static int SpeciesAtGeneration(Generations generation) { // xxx: Pull from database switch (generation) { case Generations.Generation1: return 151; case Generations.Generation2: return 251; case Generations.Generation3: return 386; case Generations.Generation4: return 493; case Generations.Generation5: return 649; case Generations.Generation6: return 721; case Generations.Generation7: return 807; // Sorry, LGPE is Gen8 case Generations.Generation8: return 905; default: throw new NotSupportedException(); } } } } ================================================ FILE: library/Pokedex/PokedexRecordBase.cs ================================================ using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using PkmnFoundations.Support; namespace PkmnFoundations.Pokedex { public class PokedexRecordBase { internal PokedexRecordBase(Pokedex pokedex) { m_pokedex = pokedex; m_lazy_pairs = new List>(); } protected Pokedex m_pokedex; protected List> m_lazy_pairs; internal virtual void PrefetchRelations() { foreach (ILazyKeyValuePair p in m_lazy_pairs) p.Evaluate(); } public static LocalizedString LocalizedStringFromReader(IDataReader reader, string prefix) { // fixme: share this field with CreateLocalizedStringQueryPieces string[] langs = new string[] { "JA", "EN", "FR", "IT", "DE", "ES", "KO" }; LocalizedString result = new LocalizedString(); foreach (string lang in langs) { try { int ordinal = reader.GetOrdinal(prefix + lang); if (reader.IsDBNull(ordinal)) continue; result.Add(lang, reader.GetString(ordinal)); } catch (IndexOutOfRangeException) { continue; } } return result; } } } ================================================ FILE: library/Pokedex/Region.cs ================================================ using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using PkmnFoundations.Support; namespace PkmnFoundations.Pokedex { public class Region : PokedexRecordBase { public Region(Pokedex pokedex, int id, LocalizedString name) : base(pokedex) { ID = id; Name = name; } public Region(Pokedex pokedex, IDataReader reader) : this(pokedex, Convert.ToInt32(reader["id"]), LocalizedStringFromReader(reader, "Name_")) { } public int ID { get; private set; } public LocalizedString Name { get; private set; } public static LazyKeyValuePair CreatePair(Pokedex pokedex) { return new LazyKeyValuePair( k => k == 0 ? null : (pokedex == null ? null : pokedex.Regions[k]), v => v == null ? 0 : v.ID); } } } ================================================ FILE: library/Pokedex/Ribbon.cs ================================================ using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using PkmnFoundations.Structures; using PkmnFoundations.Support; namespace PkmnFoundations.Pokedex { public class Ribbon : PokedexRecordBase { public Ribbon(Pokedex pokedex, int id, LocalizedString name, LocalizedString description, int ? position3, int ? position4, int ? position5, int ? position6, int ? value3, int ? value4, int ? value5, int ? value6) : base(pokedex) { ID = id; Name = name; Description = description; Position3 = position3; Position4 = position4; Position5 = position5; Position6 = position6; Value3 = value3; Value4 = value4; Value5 = value5; Value6 = value6; } public Ribbon(Pokedex pokedex, IDataReader reader) : this(pokedex, Convert.ToInt32(reader["id"]), LocalizedStringFromReader(reader, "Name_"), LocalizedStringFromReader(reader, "Description_"), reader["Position3"] is DBNull ? null : (int?)Convert.ToInt32(reader["Position3"]), reader["Position4"] is DBNull ? null : (int?)Convert.ToInt32(reader["Position4"]), reader["Position5"] is DBNull ? null : (int?)Convert.ToInt32(reader["Position5"]), reader["Position6"] is DBNull ? null : (int?)Convert.ToInt32(reader["Position6"]), reader["Value3"] is DBNull ? null : (int?)Convert.ToInt32(reader["Value3"]), reader["Value4"] is DBNull ? null : (int?)Convert.ToInt32(reader["Value4"]), reader["Value5"] is DBNull ? null : (int?)Convert.ToInt32(reader["Value5"]), reader["Value6"] is DBNull ? null : (int?)Convert.ToInt32(reader["Value6"]) ) { } public int ID { get; private set; } public LocalizedString Name { get; private set; } public LocalizedString Description { get; private set; } public int? Position3 { get; private set; } public int? Position4 { get; private set; } public int? Position5 { get; private set; } public int? Position6 { get; private set; } public int? Value3 { get; private set; } public int? Value4 { get; private set; } public int? Value5 { get; private set; } public int? Value6 { get; private set; } public int? Position(Generations generation) { switch (generation) { case Generations.Generation1: case Generations.Generation2: throw new NotSupportedException(); case Generations.Generation3: return Position3; case Generations.Generation4: return Position4; case Generations.Generation5: return Position5; case Generations.Generation6: default: return Position6; } } public int? Value(Generations generation) { switch (generation) { case Generations.Generation1: case Generations.Generation2: throw new NotSupportedException(); case Generations.Generation3: return Value3; case Generations.Generation4: return Value4; case Generations.Generation5: return Value5; case Generations.Generation6: default: return Value6; } } } } ================================================ FILE: library/Pokedex/Species.cs ================================================ using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using PkmnFoundations.Structures; using PkmnFoundations.Support; namespace PkmnFoundations.Pokedex { public class Species : PokedexRecordBase { public Species(Pokedex pokedex, int national_dex, int family_id, LocalizedString name, GrowthRates growth_rate, byte gender_ratio, EggGroups egg_group_1, EggGroups egg_group_2, int egg_steps, bool gender_variations) : base(pokedex) { m_family_pair = Family.CreatePair(m_pokedex); m_lazy_pairs.Add(m_family_pair); NationalDex = national_dex; m_family_pair.Key = family_id; Name = name; GrowthRate = growth_rate; GenderRatio = gender_ratio; EggGroup1 = egg_group_1; EggGroup2 = egg_group_2; EggSteps = egg_steps; GenderVariations = gender_variations; } // xxx: We shouldn't have column names hardcoded like this since they might change. // there should be const strings instead and they should be reused by the Database classes. public Species(Pokedex pokedex, IDataReader reader) : this( pokedex, Convert.ToInt32(reader["NationalDex"]), Convert.ToInt32(reader["family_id"]), LocalizedStringFromReader(reader, "Name_"), (GrowthRates)Convert.ToInt32(reader["GrowthRate"]), Convert.ToByte(reader["GenderRatio"]), (EggGroups)Convert.ToByte(reader["EggGroup1"]), (EggGroups)Convert.ToByte(reader["EggGroup2"]), Convert.ToInt32(reader["EggSteps"]), Convert.ToBoolean(reader["GenderVariations"]) ) { } internal override void PrefetchRelations() { base.PrefetchRelations(); m_forms = m_pokedex.FormsByValue(NationalDex); } // todo: Implement IEquitable and compare against NationalDex // Same goes for all these pokedex classes. public int NationalDex { get; private set; } public LocalizedString Name { get; private set; } public GrowthRates GrowthRate { get; private set; } /// /// Represents the odds, out of 8, of the Pokémon being female. 255 is reserved for genderless Pokémon. /// public byte GenderRatio { get; private set; } public EggGroups EggGroup1 { get; private set; } public EggGroups EggGroup2 { get; private set; } public int EggSteps { get; private set; } public bool GenderVariations { get; private set; } private LazyKeyValuePair m_family_pair; public int FamilyID { get { return m_family_pair.Key; } } public Family Family { get { return m_family_pair.Value; } } private Dictionary m_forms; public Form Forms(byte value) { if (m_forms == null) m_forms = m_pokedex.FormsByValue(NationalDex); return m_forms[value]; } public static LazyKeyValuePair CreatePair(Pokedex pokedex) { // xxx: we need to return null when there's a KeyNotFoundException // since we want the Pokemon4/5 ctor to succeed regardless of how // broken the underlying data is. return new LazyKeyValuePair( k => k == 0 ? null : (pokedex == null ? null : pokedex.Species[k]), v => v == null ? 0 : v.NationalDex); } } } ================================================ FILE: library/Pokedex/Type.cs ================================================ using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using PkmnFoundations.Structures; using PkmnFoundations.Support; namespace PkmnFoundations.Pokedex { public class Type : PokedexRecordBase { public Type(Pokedex pokedex, int id, LocalizedString name, DamageClass damage_class) : base(pokedex) { ID = id; Name = name; DamageClass = damage_class; } public Type(Pokedex pokedex, IDataReader reader) : this( pokedex, Convert.ToInt32(reader["id"]), LocalizedStringFromReader(reader, "Name_"), (DamageClass)Convert.ToInt32(reader["DamageClass"]) ) { } public int ID { get; private set; } public LocalizedString Name { get; private set; } public DamageClass DamageClass { get; private set; } public static LazyKeyValuePair CreatePair(Pokedex pokedex) { return new LazyKeyValuePair( k => k == 0 ? null : (pokedex == null ? null : pokedex.Types[k]), v => v == null ? 0 : v.ID); } public String Identifier { get { // xxx: this is a hack. Should database this field instead. return Name["EN"].ToLowerInvariant(); } } } } ================================================ FILE: library/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("library")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("library")] [assembly: AssemblyCopyright("Copyright © Microsoft 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("eae0bffb-742f-472f-8490-75c4bd769a39")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: library/Structures/ByteStatValues.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PkmnFoundations.Structures { public class ByteStatValues : StatValues { public ByteStatValues(byte hp, byte attack, byte defense, byte speed, byte special_attack, byte special_defense) : base(hp, attack, defense, speed, special_attack, special_defense) { } public ByteStatValues(IEnumerable s) : base(s) { } } } ================================================ FILE: library/Structures/ContestStatValues.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PkmnFoundations.Structures { public class ConditionValues : StatValuesBase { public ConditionValues(byte cool, byte beauty, byte cute, byte smart, byte tough, byte sheen) : base(cool, beauty, cute, smart, tough, sheen) { } public byte Cool { get { return Stats[0]; } set { Stats[0] = value; } } public byte Beauty { get { return Stats[1]; } set { Stats[1] = value; } } public byte Cute { get { return Stats[2]; } set { Stats[2] = value; } } public byte Smart { get { return Stats[3]; } set { Stats[3] = value; } } public byte Tough { get { return Stats[4]; } set { Stats[4] = value; } } public byte Sheen { get { return Stats[5]; } set { Stats[5] = value; } } public static int ConditionsIndex(Conditions condition) { return (int)condition - 1; } public virtual byte this[Conditions stat] { get { int index = ConditionsIndex(stat); if (index < 0 || index >= 6) throw new ArgumentException(); return Stats[index]; } set { int index = ConditionsIndex(stat); if (index < 0 || index >= 6) throw new ArgumentException(); Stats[index] = value; } } } } ================================================ FILE: library/Structures/Enums.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PkmnFoundations.Structures { public enum Generations { Generation1 = 1, Generation2 = 2, Generation3 = 3, Generation4 = 4, Generation5 = 5, Generation6 = 6, Generation7 = 7, Generation8 = 8 } [Flags] public enum GenerationFlags { Generation1 = 1, Generation2 = 2, Generation3 = 4, Generation4 = 8, Generation5 = 16, Generation6 = 32, Generation7 = 64, Generation8 = 128 } public enum LocationNumbering { Generation1, Generation2, Generation3, Colosseum, XD, Generation4, Generation5, Generation6 } public enum Versions : byte { // todo: fact check that these GenIII values // are retained as-is through pal park. FatefulEncounter = 0x00, Sapphire = 0x01, Ruby = 0x02, Emerald = 0x03, FireRed = 0x04, LeafGreen = 0x05, Colosseum = 0x0f, Diamond = 0x0a, Pearl = 0x0b, Platinum = 0x0c, HeartGold = 0x07, SoulSilver = 0x08, White = 0x14, Black = 0x15, White2 = 0x16, Black2 = 0x17, X = 0x18, Y = 0x19, AlphaSapphire = 0x1a, OmegaRuby = 0x1b, } public enum Languages : byte { Japanese = 0x01, English = 0x02, French = 0x03, Italian = 0x04, German = 0x05, Spanish = 0x07, Korean = 0x08, } public enum EvolutionTriggers { Level = 1, Item = 2, Trade = 3, Shed = 4 } public enum TimeOfDay { Morning = 1, Day = 2, Night = 3 } public enum Stats { Hp = 1, Attack = 2, Defense = 3, Speed = 4, SpecialAttack = 5, SpecialDefense = 6 } [Flags] public enum StatFlags { None = 0, Hp = 1, Attack = 2, Defense = 4, Speed = 8, SpecialAttack = 16, SpecialDefense = 32 } public enum Potential { Decent, AboveAverage, RelativelySuperior, Outstanding } public enum Conditions { Cool = 1, Beauty = 2, Cute = 3, Smart = 4, Tough = 5, Sheen = 6, } public enum DamageClass { None = 0, Physical = 1, Special = 2, Support = 3 } public enum GrowthRates { Slow = 1, Medium = 2, Fast = 3, MediumSlow = 4, Erratic = 5, Fluctuating = 6 } public enum Genders : byte { Male = 1, Female = 2, None = 3, Either = 3 } public enum TrainerGenders : byte { Male = 0, Female = 1 } [Flags] public enum Markings : byte { Circle = 0x01, Triangle = 0x02, Square = 0x04, Heart = 0x08, Star = 0x10, Diamond = 0x20 } public enum EggGroups : byte { None = 0, Monster = 1, Water1 = 2, Bug = 3, Flying = 4, Ground = 5, Fairy = 6, Plant = 7, HumanShape = 8, Water3 = 9, Mineral = 10, Indeterminate = 11, Water2 = 12, Ditto = 13, Dragon = 14, NoEggs = 15 } public enum BattleTargets : byte { // Pasted straight from veekun. // todo: Review and maybe clarify these names SpecificMove = 1, SelectedPokemonMeFirst = 2, Ally = 3, UsersField = 4, UserOrAlly = 5, OpponentsField = 6, User = 7, RandomOpponent = 8, AllOtherPokemon = 9, SelectedPokemon = 10, AllOpponents = 11, EntireField = 12, UserAndAllies = 13, AllPokemon = 14 } public enum Natures : uint { Hardy = 0, Lonely = 1, Brave = 2, Adamant = 3, Naughty = 4, Bold = 5, Docile = 6, Relaxed = 7, Impish = 8, Lax = 9, Timid = 10, Hasty = 11, Serious = 12, Jolly = 13, Naive = 14, Modest = 15, Mild = 16, Quiet = 17, Bashful = 18, Rash = 19, Calm = 20, Gentle = 21, Sassy = 22, Careful = 23, Quirky = 24 } public enum Pokerus { None, Infected, Cured } [Flags] public enum ShinyLeaves : byte { LeafA = 1, LeafB = 2, LeafC = 4, LeafD = 8, LeafE = 16, Crown = 32 } } ================================================ FILE: library/Structures/Format.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PkmnFoundations.Structures { public static class Format { private static string[] m_marks = new string[] { "●", "▲", "■", "♥", "★", "♦" }; public static string Markings(Markings markings, string trueFormat, string falseFormat, string delimiter) { StringBuilder result = new StringBuilder(); int marking = 1; for (int value = 0; value < 6; value++) { if (marking > 1) result.Append(delimiter); string format = (((int)markings & marking) != 0) ? trueFormat : falseFormat; result.Append(String.Format(format, m_marks[value])); marking <<= 1; } return result.ToString(); } public static string GenderSymbol(Genders gender) { switch (gender) { case Genders.Male: return "♂"; case Genders.Female: return "♀"; default: return ""; } } public static string ToIso639_1(Languages lang) { switch (lang) { case Languages.Japanese: return "JA"; case Languages.English: return "EN"; case Languages.French: return "FR"; case Languages.Italian: return "IT"; case Languages.German: return "DE"; case Languages.Spanish: return "ES"; case Languages.Korean: return "KO"; default: throw new ArgumentException(); } } public static Languages FromIso639_1(string lang) { switch (lang.ToUpperInvariant()) { case "JA": return Languages.Japanese; case "EN": return Languages.English; case "FR": return Languages.French; case "IT": return Languages.Italian; case "DE": return Languages.German; case "ES": return Languages.Spanish; case "KO": return Languages.Korean; default: throw new ArgumentException(); } } } } ================================================ FILE: library/Structures/IntStatValues.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PkmnFoundations.Structures { public class IntStatValues : StatValues { public IntStatValues(int hp, int attack, int defense, int speed, int special_attack, int special_defense) : base(hp, attack, defense, speed, special_attack, special_defense) { } public IntStatValues(IEnumerable s) : base(s) { } } } ================================================ FILE: library/Structures/IvStatValues.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PkmnFoundations.Structures { public class IvStatValues : ByteStatValues { public IvStatValues(byte hp, byte attack, byte defense, byte speed, byte special_attack, byte special_defense) : base(hp, attack, defense, speed, special_attack, special_defense) { } public IvStatValues(IEnumerable s) : base(s) { foreach (byte b in s) { if (b > 31) throw new ArgumentOutOfRangeException(); } } public IvStatValues(int ivs) : base(new byte[6]) { for (int x = 0; x < 6; x++) { Stats[x] = (byte)(ivs & 31); ivs >>= 5; } } public override byte this[Stats stat] { get { return base[stat]; } set { if (value > 31) throw new ArgumentOutOfRangeException(); base[stat] = value; } } public int ToInt32() { int shift = 0; int result = 0; foreach (byte iv in Stats) { result |= iv << shift; shift += 5; } return result; } public static byte UnpackIV(uint ivs, Stats stat) { int shift = (int)stat * 5 - 5; return (byte)(ivs << shift & 0x1f); } public static uint PackIVs(byte HP, byte Attack, byte Defense, byte Speed, byte SpAttack, byte SpDefense) { return (uint)((HP & 31) | ((Attack & 31) << 5) | ((Defense & 31) << 10) | ((Speed & 31) << 15) | ((SpAttack & 31) << 20) | ((SpDefense & 31) << 25)); } public JudgeSummary JudgeSummary { get { Potential overall = Potential.Decent; int overallInt = Stats.Sum(s => (int)s); if (overallInt > 90) overall = Potential.AboveAverage; if (overallInt > 120) overall = Potential.RelativelySuperior; if (overallInt > 150) overall = Potential.Outstanding; byte bestIvValue = 0; StatFlags bestIvs = StatFlags.None; StatFlags zeroIvs = StatFlags.None; int current = 1; for (int x = 0; x < Stats.Length; x++) { if (Stats[x] > bestIvValue) { bestIvValue = Stats[x]; bestIvs = (StatFlags)current; } else if (Stats[x] == bestIvValue) { bestIvs |= (StatFlags)current; } if (Stats[x] == 0) { zeroIvs |= (StatFlags)current; } current <<= 1; } Potential bestPotential = Potential.Decent; if (bestIvValue > 15) bestPotential = Potential.AboveAverage; if (bestIvValue > 25) bestPotential = Potential.RelativelySuperior; if (bestIvValue > 30) bestPotential = Potential.Outstanding; return new JudgeSummary(overall, bestIvs, bestPotential, zeroIvs); } } } public struct JudgeSummary { public Potential OverallPotential; public StatFlags BestIvs; public Potential BestPotential; public StatFlags ZeroIvs; public JudgeSummary(Potential overall_potential, StatFlags best_ivs, Potential best_potential, StatFlags zero_ivs) { OverallPotential = overall_potential; BestIvs = best_ivs; BestPotential = best_potential; ZeroIvs = zero_ivs; } } } ================================================ FILE: library/Structures/MoveSlot.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using PkmnFoundations.Pokedex; using PkmnFoundations.Support; namespace PkmnFoundations.Structures { public class MoveSlot { public MoveSlot(Pokedex.Pokedex pokedex, int moveId, byte ppUps, byte remainingPp) { m_pokedex = pokedex; Initialize(); MoveID = moveId; PPUps = ppUps; RemainingPP = remainingPp; } public void Initialize() { m_move_pair = Move.CreatePair(m_pokedex); } private Pokedex.Pokedex m_pokedex; private LazyKeyValuePair m_move_pair; public int MoveID { get { return m_move_pair.Key; } set { m_move_pair.Key = value; } } public Move Move { get { return m_move_pair.Value; } set { m_move_pair.Value = value; } } public byte PPUps { get; set; } // todo: validate range public byte RemainingPP { get; set; } // todo: validate range (against pokedex data and pp ups) public int PP { get { return Move == null ? 0 : Move.PP * (5 + PPUps) / 5; } } } } ================================================ FILE: library/Structures/Pokemon4.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using PkmnFoundations.Pokedex; using PkmnFoundations.Support; using PkmnFoundations.Wfc; namespace PkmnFoundations.Structures { public class Pokemon4 : PokemonPartyBase { public Pokemon4(Pokedex.Pokedex pokedex) : base(pokedex) { Initialize(); } public Pokemon4(Pokedex.Pokedex pokedex, BinaryReader data) : base(pokedex) { Initialize(); Load(data); } public Pokemon4(Pokedex.Pokedex pokedex, byte[] data) : base(pokedex) { Initialize(); Load(data); } public Pokemon4(Pokedex.Pokedex pokedex, byte[] data, int offset) : base(pokedex) { Initialize(); Load(data, offset); } private void Initialize() { } protected override void Load(BinaryReader reader) { // header (unencrypted) Personality = reader.ReadUInt32(); // 0000 ushort zero = reader.ReadUInt16(); // 0004 ushort checksum = reader.ReadUInt16(); // 0006 // read out the main payload, apply xor decryption byte[][] blocks = new byte[4][]; for (int x = 0; x < 4; x++) // 0008 blocks[x] = reader.ReadBytes(32); DecryptBlocks(blocks, checksum); ShuffleBlocks(blocks, Personality, true); IsBadEgg = ComputeChecksum(blocks) != checksum; int ribbons1, ribbons2, ribbons3; { byte[] block = blocks[0]; SpeciesID = BitConverter.ToUInt16(block, 0); HeldItemID = BitConverter.ToUInt16(block, 2); TrainerID = BitConverter.ToUInt32(block, 4); Experience = BitConverter.ToInt32(block, 8); Happiness = block[12]; AbilityID = block[13]; Markings = (Markings)block[14]; Language = (Languages)block[15]; EVs = new ByteStatValues(block[16], block[17], block[18], block[19], block[20], block[21]); ContestStats = new ConditionValues(block[22], block[23], block[24], block[25], block[26], block[27]); ribbons2 = BitConverter.ToInt32(block, 28); } { byte[] block = blocks[1]; Moves[0] = new MoveSlot(m_pokedex, BitConverter.ToUInt16(block, 0), block[12], block[8]); Moves[1] = new MoveSlot(m_pokedex, BitConverter.ToUInt16(block, 2), block[13], block[9]); Moves[2] = new MoveSlot(m_pokedex, BitConverter.ToUInt16(block, 4), block[14], block[10]); Moves[3] = new MoveSlot(m_pokedex, BitConverter.ToUInt16(block, 6), block[15], block[11]); int ivs = BitConverter.ToInt32(block, 16); IVs = new IvStatValues(ivs & 0x3fffffff); IsEgg = (ivs & 0x40000000) != 0; HasNickname = (ivs & 0x80000000) != 0; ribbons1 = BitConverter.ToInt32(block, 20); byte forme = block[24]; FatefulEncounter = (forme & 0x01) != 0; m_female = (forme & 0x02) != 0; m_genderless = (forme & 0x04) != 0; FormID = (byte)(forme >> 3); ShinyLeaves = (ShinyLeaves)block[25]; Unknown1 = BitConverter.ToUInt16(block, 26); EggLocationID_Plat = BitConverter.ToUInt16(block, 28); LocationID_Plat = BitConverter.ToUInt16(block, 30); } { byte[] block = blocks[2]; NicknameEncoded = new EncodedString4(block, 0, 22); Unknown2 = block[22]; Version = (Versions)block[23]; ribbons3 = BitConverter.ToInt32(block, 24); Unknown3 = BitConverter.ToUInt32(block, 28); } { byte[] block = blocks[3]; TrainerNameEncoded = new EncodedString4(block, 0, 16); // todo: store as DateTime EggDate = new byte[3]; Array.Copy(block, 16, EggDate, 0, 3); Date = new byte[3]; Array.Copy(block, 19, Date, 0, 3); EggLocationID = BitConverter.ToUInt16(block, 22); LocationID = BitConverter.ToUInt16(block, 24); byte pokerusStatus = block[26]; PokerusDaysLeft = (byte)(pokerusStatus & 0x0f); PokerusStrain = (byte)(pokerusStatus >> 4); PokeBallID = block[27]; byte encounter_level = block[28]; EncounterLevel = (byte)(encounter_level & 0x7f); bool trainerFemale = (encounter_level & 0x80) != 0; TrainerGender = trainerFemale ? TrainerGenders.Female : TrainerGenders.Male; EncounterType = block[29]; PokeBallID_Hgss = block[30]; Unknown4 = block[31]; } byte[] ribbons = new byte[12]; Array.Copy(BitConverter.GetBytes(ribbons1), 0, ribbons, 0, 4); Array.Copy(BitConverter.GetBytes(ribbons2), 0, ribbons, 4, 4); Array.Copy(BitConverter.GetBytes(ribbons3), 0, ribbons, 8, 4); Ribbons.Clear(); UnknownRibbons.Clear(); IDictionary allRibbons = m_pokedex.RibbonsByGeneration(Generations.Generation4); for (int x = 0; x < 96; x++) { if (PokemonPartyBase.HasRibbon(ribbons, x)) { if (allRibbons.ContainsKey(x)) Ribbons.Add(allRibbons[x]); else UnknownRibbons.Add(x); } } } protected override void Save(BinaryWriter writer) { // todo: implement save throw new NotImplementedException(); } public override Generations Generation { get { return Generations.Generation4; } } public ShinyLeaves ShinyLeaves { get; set; } public ushort Unknown1 { get; set; } // appears just after a flags region storing gender, forme, shiny leaves, etc. public EncodedString4 NicknameEncoded { get; set; } // public so trash bytes can be inspected/manipulated public override string Nickname { get { return (NicknameEncoded == null) ? null : NicknameEncoded.Text; } set { if (Nickname == value) return; if (NicknameEncoded == null) NicknameEncoded = new EncodedString4(value, 22); else NicknameEncoded.Text = value; } } public byte Unknown2 { get; set; } // appears just before Version public uint Unknown3 { get; set; } // appears just after the last ribbon block public EncodedString4 TrainerNameEncoded { get; set; } public override string TrainerName { get { return (TrainerNameEncoded == null) ? null : TrainerNameEncoded.Text; } set { if (TrainerName == value) return; if (TrainerNameEncoded == null) TrainerNameEncoded = new EncodedString4(value, 16); else TrainerNameEncoded.Text = value; } } // Dates encoding seems to be 1 byte for year, starting in 2000, // 1 byte for month (1-12), and 1 byte for day of month (1-31, depending) // EggDate is all 0s if not hatched. // Platinum locations are 0 on DP, egg locations are 0 if not hatched. public byte[] EggDate { get; set; } // 3 bytes public byte[] Date { get; set; } // 3 bytes public ushort EggLocationID { get; set; } public ushort LocationID { get; set; } public ushort EggLocationID_Plat { get; set; } public ushort LocationID_Plat { get; set; } public byte EncounterLevel { get; set; } public override TrainerMemo TrainerMemo { get { // fixme: Pal Park memos are just saying Pal Park. We should be able to get the region too. ushort eggLocationId, locationId; bool plat = IsPlatHgss(); eggLocationId = (plat && EggLocationID_Plat != 0) ? EggLocationID_Plat : EggLocationID; locationId = (plat && LocationID_Plat != 0) ? LocationID_Plat : LocationID; return new TrainerMemo(m_pokedex, LocationNumbering.Generation4, TrainerMemoDateTime(EggDate), TrainerMemoDateTime(Date), eggLocationId, locationId, EncounterLevel == 0, EncounterLevel); } set { throw new NotImplementedException(); } } public byte Unknown4 { get; set; } // appears just after HGSS pokeball // todo: obtain complete list of Pokeball IDs in HGSS public byte PokeBallID { get; set; } public byte PokeBallID_Hgss { get; set; } private Item m_pokeball; public override Pokedex.Item Pokeball { get { if (m_pokeball != null) return m_pokeball; int pokeballId = IsHgss() ? PokeBallID_Hgss : PokeBallID; if (!m_pokedex.Pokeballs.ContainsKey(pokeballId)) return null; m_pokeball = m_pokedex.Pokeballs[pokeballId]; return m_pokeball; } set { if (m_pokeball == value) return; if (value == null) throw new ArgumentNullException(); if (value.PokeballValue == null) throw new ArgumentException("Item is not a valid Pokeball."); if ((int)value.PokeballValue > 255 || (int)value.PokeballValue < 0) throw new ArgumentOutOfRangeException("Pokeball ID must be within the valid range for a byte."); int pokeballId = (int)value.PokeballValue; bool is_hgss = IsHgss(); bool is_hgss_pokeball = IsHgssPokeball(pokeballId); if (!is_hgss && is_hgss_pokeball) throw new NotSupportedException("Can't place an HGSS Pokeball on a DPPt Pokémon."); // xxx: we can probably allow an hgss pokeball on a dppt pokemon // although the structure won't be valid // todo: fact check how hgss responds in this situation. // todo: fact check these 3 values: // 1. a pokemon in an HGSS ball has a DPPt value of 4 // 2. any pokemon from DPPt has an HGSS value of 0 // 3. a pokemon from HGSS in a DPPt ball has equal HGSS and DPPt values? Or is its HGSS value 0? // (investigating pokemon in the system should be enough) PokeBallID = (byte)(is_hgss_pokeball ? 4 : pokeballId); PokeBallID_Hgss = (byte)(is_hgss ? pokeballId : 0); } } private bool IsPlatHgss() { return (Version == Versions.Platinum || Version == Versions.HeartGold || Version == Versions.SoulSilver); } private bool IsHgss() { return (Version == Versions.HeartGold || Version == Versions.SoulSilver); } private static bool IsHgssPokeball(int pokeballId) { return pokeballId > 16; } public override ushort HP { get { return (ushort)Stats[Structures.Stats.Hp]; } } public override int Size { get { return 136; } } public static ValidationSummary ValidateActual(PokemonBase thePokemon) { if (thePokemon.SpeciesID < 1 || thePokemon.SpeciesID > 493) return new ValidationSummary() { IsValid = false }; try { if (thePokemon.Form == null) return new ValidationSummary() { IsValid = false }; } catch (KeyNotFoundException) { return new ValidationSummary() { IsValid = false }; // form not in pokedex } // todo: Hardcoded checks don't belong here, but in the database. // We need a Form.Generation and Form.CompatibleGeneration field // to denote which generation a form was introduced in, and which // generation it's broadly compatible with for trading. //if (thePokemon.Form.CompatibleGeneration > Generations.Generation4) return new ValidationSummary() { IsValid = false }; if (thePokemon.SpeciesID == 479 && thePokemon.FormID != 0) return new ValidationSummary() { IsValid = false }; // rotoms if (thePokemon.SpeciesID == 487 && thePokemon.FormID != 0) return new ValidationSummary() { IsValid = false }; // origin giratina if (thePokemon.SpeciesID == 492 && thePokemon.FormID != 0) return new ValidationSummary() { IsValid = false }; // sky shaymin if (thePokemon.Form.Suffix == "spiky-eared") return new ValidationSummary() { IsValid = false }; if (thePokemon.Form.Suffix == "fairy") return new ValidationSummary() { IsValid = false }; if (thePokemon.Form.Suffix == "mega") return new ValidationSummary() { IsValid = false }; if (thePokemon.Form.Suffix == "mega-x") return new ValidationSummary() { IsValid = false }; if (thePokemon.Form.Suffix == "mega-y") return new ValidationSummary() { IsValid = false }; if (thePokemon.Form.Suffix == "primal") return new ValidationSummary() { IsValid = false }; if (thePokemon.SpeciesID == 25 && thePokemon.FormID > 0) return new ValidationSummary() { IsValid = false }; // cosplay pikachu if (thePokemon.HeldItemID < 0) return new ValidationSummary() { IsValid = false }; if (thePokemon.HeldItemID >= 112 && thePokemon.HeldItemID <= 134) return new ValidationSummary() { IsValid = false }; if (thePokemon.HeldItemID >= 428) return new ValidationSummary() { IsValid = false }; if (thePokemon.AbilityID <= 0) return new ValidationSummary() { IsValid = false }; if (thePokemon.AbilityID > 123) return new ValidationSummary() { IsValid = false }; if (!thePokemon.Form.Abilities(Generations.Generation4).Abilities.Contains(thePokemon.Ability)) return new ValidationSummary() { IsValid = false }; foreach (MoveSlot move in thePokemon.Moves) { if (move.MoveID < 0) return new ValidationSummary() { IsValid = false }; if (move.MoveID == 165) return new ValidationSummary() { IsValid = false }; // struggle if (move.MoveID > 467) return new ValidationSummary() { IsValid = false }; } if (thePokemon is Pokemon4) { var thePokemon4 = (Pokemon4)thePokemon; if (!thePokemon4.NicknameEncoded.IsValid) return new ValidationSummary() { IsValid = false }; if (!thePokemon4.TrainerNameEncoded.IsValid) return new ValidationSummary() { IsValid = false }; } else if (thePokemon is BattleTowerPokemon4) { var theBattleTowerPokemon4 = (BattleTowerPokemon4)thePokemon; if (!theBattleTowerPokemon4.NicknameEncoded.IsValid) return new ValidationSummary() { IsValid = false }; } return new ValidationSummary() { IsValid = true }; } } } ================================================ FILE: library/Structures/Pokemon5.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using PkmnFoundations.Pokedex; using PkmnFoundations.Support; using PkmnFoundations.Wfc; namespace PkmnFoundations.Structures { public class Pokemon5 : PokemonPartyBase { public Pokemon5(Pokedex.Pokedex pokedex) : base(pokedex) { Initialize(); } public Pokemon5(Pokedex.Pokedex pokedex, BinaryReader data) : base(pokedex) { Initialize(); Load(data); } public Pokemon5(Pokedex.Pokedex pokedex, byte[] data) : base(pokedex) { Initialize(); Load(data); } public Pokemon5(Pokedex.Pokedex pokedex, byte[] data, int offset) : base(pokedex) { Initialize(); Load(data, offset); } private void Initialize() { } protected override void Load(BinaryReader reader) { // header (unencrypted) Personality = reader.ReadUInt32(); // 0000 ushort zero = reader.ReadUInt16(); // 0004 ushort checksum = reader.ReadUInt16(); // 0006 // read out the main payload, apply xor decryption byte[][] blocks = new byte[4][]; for (int x = 0; x < 4; x++) // 0008 blocks[x] = reader.ReadBytes(32); DecryptBlocks(blocks, checksum); ShuffleBlocks(blocks, Personality, true); IsBadEgg = ComputeChecksum(blocks) != checksum; int ribbons1, ribbons2, ribbons3; { byte[] block = blocks[0]; SpeciesID = BitConverter.ToUInt16(block, 0); HeldItemID = BitConverter.ToUInt16(block, 2); TrainerID = BitConverter.ToUInt32(block, 4); Experience = BitConverter.ToInt32(block, 8); Happiness = block[12]; AbilityID = block[13]; Markings = (Markings)block[14]; Language = (Languages)block[15]; EVs = new ByteStatValues(block[16], block[17], block[18], block[19], block[20], block[21]); ContestStats = new ConditionValues(block[22], block[23], block[24], block[25], block[26], block[27]); ribbons2 = BitConverter.ToInt32(block, 28); } { byte[] block = blocks[1]; Moves[0] = new MoveSlot(m_pokedex, BitConverter.ToUInt16(block, 0), block[12], block[8]); Moves[1] = new MoveSlot(m_pokedex, BitConverter.ToUInt16(block, 2), block[13], block[9]); Moves[2] = new MoveSlot(m_pokedex, BitConverter.ToUInt16(block, 4), block[14], block[10]); Moves[3] = new MoveSlot(m_pokedex, BitConverter.ToUInt16(block, 6), block[15], block[11]); int ivs = BitConverter.ToInt32(block, 16); IVs = new IvStatValues(ivs & 0x3fffffff); IsEgg = (ivs & 0x40000000) != 0; HasNickname = (ivs & 0x80000000) != 0; ribbons1 = BitConverter.ToInt32(block, 20); byte forme = block[24]; FatefulEncounter = (forme & 0x01) != 0; m_female = (forme & 0x02) != 0; m_genderless = (forme & 0x04) != 0; FormID = (byte)(forme >> 3); m_nature = block[25]; // todo: which nature is real? Do they both need to match? m_bw_flags = BitConverter.ToUInt16(block, 26); HiddenAbility = (m_bw_flags & 0x01) != 0; N = (m_bw_flags & 0x02) != 0; Unknown1 = BitConverter.ToUInt32(block, 28); EggLocationID_Plat = BitConverter.ToUInt16(block, 28); LocationID_Plat = BitConverter.ToUInt16(block, 30); } { byte[] block = blocks[2]; NicknameEncoded = new EncodedString5(block, 0, 22); Unknown2 = block[22]; Version = (Versions)block[23]; ribbons3 = BitConverter.ToInt32(block, 24); Unknown3 = BitConverter.ToUInt32(block, 28); } { byte[] block = blocks[3]; TrainerNameEncoded = new EncodedString5(block, 0, 16); EggDate = new byte[3]; Array.Copy(block, 16, EggDate, 0, 3); Date = new byte[3]; Array.Copy(block, 19, Date, 0, 3); EggLocationID = BitConverter.ToUInt16(block, 22); LocationID = BitConverter.ToUInt16(block, 24); byte pokerusStatus = block[26]; PokerusDaysLeft = (byte)(pokerusStatus & 0x0f); PokerusStrain = (byte)(pokerusStatus >> 4); PokeBallID = block[27]; byte encounter_level = block[28]; EncounterLevel = (byte)(encounter_level & 0x7f); bool trainerFemale = (encounter_level & 0x80) != 0; TrainerGender = trainerFemale ? TrainerGenders.Female : TrainerGenders.Male; EncounterType = block[29]; Unknown4 = BitConverter.ToUInt16(block, 30); } byte[] ribbons = new byte[12]; Array.Copy(BitConverter.GetBytes(ribbons1), 0, ribbons, 0, 4); Array.Copy(BitConverter.GetBytes(ribbons2), 0, ribbons, 4, 4); Array.Copy(BitConverter.GetBytes(ribbons3), 0, ribbons, 8, 4); Ribbons.Clear(); UnknownRibbons.Clear(); IDictionary allRibbons = m_pokedex.RibbonsByGeneration(Generations.Generation5); for (int x = 0; x < 96; x++) { if (PokemonPartyBase.HasRibbon(ribbons, x)) { if (allRibbons.ContainsKey(x)) Ribbons.Add(allRibbons[x]); else UnknownRibbons.Add(x); } } } protected override void Save(BinaryWriter writer) { // todo: implement save throw new NotImplementedException(); } public override Generations Generation { get { return Generations.Generation5; } } private byte m_nature; public override Natures Nature { get { return (Natures)(m_nature % 25u); } } private ushort m_bw_flags; public bool HiddenAbility { get; set; } public bool N { get; set; } public uint Unknown1 { get; set; } // appears just after a flags region storing DW ability and N ownership. public EncodedString5 NicknameEncoded { get; set; } // public so trash bytes can be inspected/manipulated public override string Nickname { get { return (NicknameEncoded == null) ? null : NicknameEncoded.Text; } set { if (Nickname == value) return; if (NicknameEncoded == null) NicknameEncoded = new EncodedString5(value, 22); else NicknameEncoded.Text = value; } } public byte Unknown2 { get; set; } // appears just before Version public uint Unknown3 { get; set; } // appears just after the last ribbon block public EncodedString5 TrainerNameEncoded { get; set; } public override string TrainerName { get { return (TrainerNameEncoded == null) ? null : TrainerNameEncoded.Text; } set { if (TrainerName == value) return; if (TrainerNameEncoded == null) TrainerNameEncoded = new EncodedString5(value, 16); else TrainerNameEncoded.Text = value; } } public byte[] EggDate { get; set; } // 3 bytes public byte[] Date { get; set; } // 3 bytes public ushort EggLocationID { get; set; } public ushort LocationID { get; set; } public ushort EggLocationID_Plat { get; set; } public ushort LocationID_Plat { get; set; } public byte EncounterLevel { get; set; } public override TrainerMemo TrainerMemo { get { // todo: fact check how BW2 stores trainer memo locations not present in BW1 ushort eggLocationId, locationId; bool plat = false;// IsBw2(); eggLocationId = (plat && EggLocationID_Plat != 0) ? EggLocationID_Plat : EggLocationID; locationId = (plat && LocationID_Plat != 0) ? LocationID_Plat : LocationID; return new TrainerMemo(m_pokedex, LocationNumbering.Generation5, TrainerMemoDateTime(EggDate), TrainerMemoDateTime(Date), eggLocationId, locationId, EncounterLevel == 0, EncounterLevel); } set { throw new NotImplementedException(); } } public ushort Unknown4 { get; set; } // appears just after encounter type. (includes what was HGSS's pokeball field) // todo: obtain complete list of Pokeball IDs in Gen5. (same issue as hgss) public byte PokeBallID { get; set; } private Item m_pokeball; public override Pokedex.Item Pokeball { get { if (m_pokeball != null) return m_pokeball; if (!m_pokedex.Pokeballs.ContainsKey(PokeBallID)) return null; m_pokeball = m_pokedex.Pokeballs[PokeBallID]; return m_pokeball; } set { if (m_pokeball == value) return; if (value == null) throw new ArgumentNullException(); if (value.PokeballValue == null) throw new ArgumentException("Item is not a valid Pokeball."); if ((int)value.PokeballValue > 255 || (int)value.PokeballValue < 0) throw new ArgumentOutOfRangeException("Pokeball ID must be within the valid range for a byte."); int pokeballId = (int)value.PokeballValue; PokeBallID = (byte)(pokeballId); } } public override ushort HP { get { return (ushort)Stats[Structures.Stats.Hp]; } } private bool IsBw2() { return (Version == Versions.Black2 || Version == Versions.White2); } public override int Size { get { return 136; } } public static ValidationSummary ValidateActual(PokemonBase thePokemon) { if (thePokemon.SpeciesID < 1 || thePokemon.SpeciesID > 649) return new ValidationSummary() { IsValid = false }; try { if (thePokemon.Form == null) return new ValidationSummary() { IsValid = false }; } catch (KeyNotFoundException) { return new ValidationSummary() { IsValid = false }; // form not in pokedex } if (thePokemon.SpeciesID == 641 && thePokemon.FormID != 0) return new ValidationSummary() { IsValid = false }; // therian tornadus if (thePokemon.SpeciesID == 642 && thePokemon.FormID != 0) return new ValidationSummary() { IsValid = false }; // therian thundrus if (thePokemon.SpeciesID == 645 && thePokemon.FormID != 0) return new ValidationSummary() { IsValid = false }; // therian landorus if (thePokemon.SpeciesID == 646 && thePokemon.FormID != 0) return new ValidationSummary() { IsValid = false }; // black/white kyurem if (thePokemon.SpeciesID == 647 && thePokemon.FormID != 0) return new ValidationSummary() { IsValid = false }; // resolute keldeo if (thePokemon.Form.Suffix == "spiky-eared") return new ValidationSummary() { IsValid = false }; if (thePokemon.Form.Suffix == "fairy") return new ValidationSummary() { IsValid = false }; if (thePokemon.Form.Suffix == "mega") return new ValidationSummary() { IsValid = false }; if (thePokemon.Form.Suffix == "mega-x") return new ValidationSummary() { IsValid = false }; if (thePokemon.Form.Suffix == "mega-y") return new ValidationSummary() { IsValid = false }; if (thePokemon.Form.Suffix == "primal") return new ValidationSummary() { IsValid = false }; if (thePokemon.SpeciesID == 25 && thePokemon.FormID > 0) return new ValidationSummary() { IsValid = false }; // cosplay pikachu if (thePokemon.HeldItemID < 0) return new ValidationSummary() { IsValid = false }; if (thePokemon.HeldItemID >= 113 && thePokemon.HeldItemID <= 115) return new ValidationSummary() { IsValid = false }; if (thePokemon.HeldItemID >= 120 && thePokemon.HeldItemID <= 133) return new ValidationSummary() { IsValid = false }; if (thePokemon.HeldItemID >= 328 && thePokemon.HeldItemID <= 503) return new ValidationSummary() { IsValid = false }; if (thePokemon.HeldItemID >= 505 && thePokemon.HeldItemID <= 536) return new ValidationSummary() { IsValid = false }; if (thePokemon.HeldItemID == 574) return new ValidationSummary() { IsValid = false }; if (thePokemon.HeldItemID == 576) return new ValidationSummary() { IsValid = false }; if (thePokemon.HeldItemID >= 578 && thePokemon.HeldItemID <= 579) return new ValidationSummary() { IsValid = false }; if (thePokemon.HeldItemID >= 592) return new ValidationSummary() { IsValid = false }; if (thePokemon.AbilityID <= 0) return new ValidationSummary() { IsValid = false }; if (thePokemon.AbilityID > 164) return new ValidationSummary() { IsValid = false }; if (!thePokemon.Form.Abilities(Generations.Generation5).Abilities.Contains(thePokemon.Ability) && !thePokemon.Form.Abilities(Generations.Generation5).HiddenAbilities.Contains(thePokemon.Ability) && // Allow Blue Basculin to have Reckless. https://bulbapedia.bulbagarden.net/wiki/Basculin_(Pok%C3%A9mon)#Trivia !(thePokemon.Form.Suffix == "blue-striped" && thePokemon.AbilityID == 120)) return new ValidationSummary() { IsValid = false }; foreach (MoveSlot move in thePokemon.Moves) { if (move.MoveID < 0) return new ValidationSummary() { IsValid = false }; if (move.MoveID == 165) return new ValidationSummary() { IsValid = false }; // struggle if (move.MoveID > 559) return new ValidationSummary() { IsValid = false }; } if (thePokemon is Pokemon5) { var thePokemon5 = (Pokemon5)thePokemon; if (!thePokemon5.NicknameEncoded.IsValid) return new ValidationSummary() { IsValid = false }; if (!thePokemon5.TrainerNameEncoded.IsValid) return new ValidationSummary() { IsValid = false }; } else if (thePokemon is BattleSubwayPokemon5) { var theBattleSubwayPokemon5 = (BattleSubwayPokemon5)thePokemon; if (!theBattleSubwayPokemon5.NicknameEncoded.IsValid) return new ValidationSummary() { IsValid = false }; } return new ValidationSummary() { IsValid = true }; } } } ================================================ FILE: library/Structures/PokemonBase.cs ================================================ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Text; using PkmnFoundations.Pokedex; using PkmnFoundations.Support; namespace PkmnFoundations.Structures { public abstract class PokemonBase : BinarySerializableBase { public PokemonBase(Pokedex.Pokedex pokedex) : base() { m_pokedex = pokedex; Initialize(); } private void Initialize() { m_species_pair = Species.CreatePair(m_pokedex); m_form_pair = Form.CreatePairForSpecies(m_pokedex, () => Species); m_item_pair = Item.CreatePairForGeneration(m_pokedex, () => Generation); m_ability_pair = Ability.CreatePair(m_pokedex); } protected Pokedex.Pokedex m_pokedex; private MoveSlot[] m_moves = new MoveSlot[4]; private LazyKeyValuePair m_species_pair; public int SpeciesID { get { return m_species_pair.Key; } set { // changing species will cause the looked up Form to be // incorrect so null it out. m_species_pair.Key = value; m_form_pair.Invalidate(); } } public Species Species { get { return m_species_pair.Value; } set { m_species_pair.Value = value; m_form_pair.Invalidate(); } } private LazyKeyValuePair m_form_pair; public byte FormID { get { return m_form_pair.Key; } set { m_form_pair.Key = value; } } public Form Form { get { return m_form_pair.Value; } set { SpeciesID = value.SpeciesID; m_form_pair.Value = value; } } public abstract Generations Generation { get; } private LazyKeyValuePair m_item_pair; public int HeldItemID { get { return m_item_pair.Key; } set { m_item_pair.Key = value; } } public Item HeldItem { get { return m_item_pair.Value; } set { m_item_pair.Value = value; } } private LazyKeyValuePair m_ability_pair; public int AbilityID { get { return m_ability_pair.Key; } set { m_ability_pair.Key = value; } } public Ability Ability { get { return m_ability_pair.Value; } set { m_ability_pair.Value = value; } } public IList Moves { get { return m_moves; } } public uint TrainerID { get; set; } public uint Personality { get; set; } public virtual Natures Nature { get { return (Natures)(Personality % 25u); } } public byte Happiness { get; set; } public Languages Language { get; set; } public IvStatValues IVs { get; set; } public ByteStatValues EVs { get; set; } public abstract byte Level { get; set; } public virtual Genders Gender { get { // https://bulbapedia.bulbagarden.net/wiki/Gender#In_Generations_III_to_V var ratio = Species.GenderRatio; switch (ratio) { case 0: return Genders.Male; case 8: return Genders.Female; case 255: return Genders.None; default: { // massage gender value into the corresponding value in bulbapedia table. // This is off-by-one in true Game Freak fashion, causing a slight bias towards male Pokémon. uint mangledRatio = ratio * 32u - 1; uint pGender = Personality & 0xffu; return pGender >= mangledRatio ? Genders.Male : Genders.Female; } } } set { // xxx: we don't really want this setter at all but we need to be able to override and provide a setter // https://github.com/dotnet/csharplang/issues/1568 throw new NotSupportedException(); } } public abstract string Nickname { get; set; } public virtual bool IsShiny { get { // Gen3/4/5 formula. Gen6 must override. return ShinyTest(Personality, TrainerID, 3); } } public static bool ShinyTest(uint personality, uint trainerId, int trimBits) { uint step1 = personality ^ trainerId; int step2 = (int)((step1 >> 16) ^ (step1 & 0xffffu)); return step2 >> trimBits == 0; } public Characteristic Characteristic { get { int toCheck = (int)(Personality % 6u); Stats bestStat = (Structures.Stats)(toCheck + 1); byte bestStatValue = 0; for (int x = 0; x < 6; x++) { if (IVs[(Structures.Stats)(x + 1)] > bestStatValue) { bestStat = (Structures.Stats)(toCheck + 1); bestStatValue = IVs[(Structures.Stats)(x + 1)]; } toCheck++; toCheck %= 6; } return new Characteristic(bestStat, (byte)(bestStatValue % (byte)5)); } } public virtual ValidationSummary Validate() { // xxx: this is another one of those inheritance diamond things. // Since we specialize by generation after specializing by // structure type, we have to roll our own vtable here to be able // to have generation-specific validation in each inheritance // branch. // todo: Move some cross-generational validation logic over to // this base method. switch (this.Generation) { case Generations.Generation4: return Pokemon4.ValidateActual(this); case Generations.Generation5: return Pokemon5.ValidateActual(this); default: return new ValidationSummary() { IsValid = true }; } } protected static List BlockScramble(uint personality) { int x = 4; // todo: this can be an argument but YAGNI int xFactorial = 24; //if (x < 0) throw new ArgumentOutOfRangeException(); //if (x == 0) return new int[0]; int index; List remaining = Enumerable.Range(0, x).ToList(); List result = new List(x); while (x > 0) { int xMinusOneFactorial = xFactorial / x; index = (int)((personality % xFactorial) / xMinusOneFactorial); result.Add(remaining[index]); remaining.RemoveAt(index); x--; xFactorial = xMinusOneFactorial; } return result; } protected static List Invert(List arg) { // todo: this is of general utility and should go in a utility class. int max = arg.Max(); List result = new List(max); for (int x = 0; x <= max; x++) result.Add(arg.IndexOf(x)); return result; } #region Experience formulas public static int ExperienceAt(int level, GrowthRates gr) { if (level > 100 || level < 1) throw new ArgumentOutOfRangeException("level"); if (level == 1) return 0; switch (gr) { case GrowthRates.Slow: return ExperienceAt_Slow(level); case GrowthRates.Medium: return ExperienceAt_Medium(level); case GrowthRates.Fast: return ExperienceAt_Fast(level); case GrowthRates.MediumSlow: return ExperienceAt_MediumSlow(level); case GrowthRates.Erratic: return ExperienceAt_Erratic(level); case GrowthRates.Fluctuating: return ExperienceAt_Fluctuating(level); } throw new ArgumentException("gr"); } public static byte LevelAt(int experience, GrowthRates gr) { if (experience < 0) throw new ArgumentOutOfRangeException("experience"); int minLevel = 1, maxLevel = 100; int minExp = ExperienceAt(1, gr), maxExp = ExperienceAt(100, gr); while (1 < 2) { if (maxExp <= experience) return (byte)maxLevel; if (minLevel + 1 >= maxLevel) return (byte)minLevel; int midLevel = (minLevel + maxLevel) >> 1; int midExp = ExperienceAt(midLevel, gr); if (experience >= midExp) { minLevel = midLevel; minExp = midExp; } else { maxLevel = midLevel; maxExp = midExp; } } } private static int ExperienceAt_Slow(int level) { int cube = level * level * level; return 5 * cube / 4; } private static int ExperienceAt_Medium(int level) { int cube = level * level * level; return cube; } private static int ExperienceAt_Fast(int level) { int cube = level * level * level; return 4 * cube / 5; } private static int ExperienceAt_MediumSlow(int level) { int square = level * level; int cube = square * level; return 6 * cube / 5 - 15 * square + 100 * level - 140; } private static int ExperienceAt_Erratic(int level) { int cube = level * level * level; if (level < 50) return (cube * (100 - level)) / 50; else if (level < 68) return (cube * (150 - level)) / 100; else if (level < 98) // note that there is intentional rounding error cause by /3 inside the formula. return (cube * ((1911 - 10 * level) / 3)) / 500; else return (cube * (160 - level)) / 100; } private static int ExperienceAt_Fluctuating(int level) { int cube = level * level * level; if (level < 15) return cube * ((level + 1) / 3 + 24) / 50; else if (level < 36) return cube * (level + 14) / 50; else return cube * (level / 2 + 32) / 50; } #endregion } public struct Characteristic { public Stats BestIv; public byte BestIvModulo; public Characteristic(Stats best_iv, byte best_iv_modulo) { BestIv = best_iv; BestIvModulo = best_iv_modulo; } private static String[,] m_phrases = new String[,] { { "Loves to eat", "Takes plenty of siestas", "Nods off a lot", "Scatters things often", "Likes to relax"}, { "Proud of its power", "Likes to thrash about", "A little quick tempered", "Likes to fight", "Quick tempered"}, { "Sturdy body", "Capable of taking hits", "Highly persistent", "Good endurance", "Good perseverance"}, { "Likes to run", "Alert to sounds", "Impetuous and silly", "Somewhat of a clown", "Quick to flee"}, { "Highly curious", "Mischievous", "Thoroughly cunning", "Often lost in thought", "Very finicky"}, { "Strong willed", "Somewhat vain", "Strongly defiant", "Hates to lose", "Somewhat stubborn"}, }; public override string ToString() { // http://bulbapedia.bulbagarden.net/wiki/Characteristic#List_of_Characteristics // todo: i18n if (BestIv < Stats.Hp || BestIv > Stats.SpecialDefense) throw new InvalidOperationException(); if (BestIvModulo > 4) throw new InvalidOperationException(); return m_phrases[(int)BestIv - 1, BestIvModulo]; } } } ================================================ FILE: library/Structures/PokemonParty4.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace PkmnFoundations.Structures { public class PokemonParty4 : Pokemon4 { public PokemonParty4(Pokedex.Pokedex pokedex) : base(pokedex) { Initialize(); } public PokemonParty4(Pokedex.Pokedex pokedex, BinaryReader data) : base(pokedex) { Initialize(); Load(data); } public PokemonParty4(Pokedex.Pokedex pokedex, byte[] data) : base(pokedex) { Initialize(); Load(data); } public PokemonParty4(Pokedex.Pokedex pokedex, byte[] data, int offset) : base(pokedex) { Initialize(); Load(data, offset); } private void Initialize() { } protected override void Load(BinaryReader reader) { base.Load(reader); { int rand = (int)Personality; byte[] block = reader.ReadBytes(100); for (int pos = 0; pos < 100; pos += 2) { rand = DecryptRNG(rand); block[pos] ^= (byte)(rand >> 16); block[pos + 1] ^= (byte)(rand >> 24); } StatusAffliction = block[0]; Unknown5 = block[1]; Unknown6 = BitConverter.ToUInt16(block, 2); // todo: validate this against the computed level //Level = block[4]; CapsuleIndex = block[5]; _HP = BitConverter.ToUInt16(block, 6); m_stats = new IntStatValues(BitConverter.ToUInt16(block, 8), BitConverter.ToUInt16(block, 10), BitConverter.ToUInt16(block, 12), BitConverter.ToUInt16(block, 14), BitConverter.ToUInt16(block, 16), BitConverter.ToUInt16(block, 18)); HeldItemTrash = new byte[56]; Array.Copy(block, 20, HeldItemTrash, 0, 56); Seals = new byte[24]; Array.Copy(block, 76, Seals, 0, 24); } } // todo: parse status afflictions (enum + sleep turns) public byte StatusAffliction { get; set; } // todo: Parse ball seals public byte Unknown5 { get; set; } public ushort Unknown6 { get; set; } public byte CapsuleIndex { get; set; } public override ushort HP { get { return _HP; } } // remaining hp public ushort _HP { get; set; } public byte[] HeldItemTrash { get; set; } // 56 bytes public byte[] Seals { get; set; } // 24 bytes // cached stats on the party structure. This gives rise to the // "box trick" on Gens 1-4 whereby putting the pokemon into the box // recalculates its stats. private IntStatValues m_stats; public override IntStatValues Stats { get { return m_stats; } } public override int Size { get { return 236; } } } } ================================================ FILE: library/Structures/PokemonParty5.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace PkmnFoundations.Structures { public class PokemonParty5 : Pokemon5 { public PokemonParty5(Pokedex.Pokedex pokedex) : base(pokedex) { Initialize(); } public PokemonParty5(Pokedex.Pokedex pokedex, BinaryReader data) : base(pokedex) { Initialize(); Load(data); } public PokemonParty5(Pokedex.Pokedex pokedex, byte[] data) : base(pokedex) { Initialize(); Load(data); } public PokemonParty5(Pokedex.Pokedex pokedex, byte[] data, int offset) : base(pokedex) { Initialize(); Load(data, offset); } private void Initialize() { } protected override void Load(BinaryReader reader) { base.Load(reader); { int rand = (int)Personality; byte[] block = reader.ReadBytes(100); for (int pos = 0; pos < 100; pos += 2) { rand = DecryptRNG(rand); block[pos] ^= (byte)(rand >> 16); block[pos + 1] ^= (byte)(rand >> 24); } StatusAffliction = block[0]; Unknown5 = block[1]; Unknown6 = BitConverter.ToUInt16(block, 2); // todo: validate this against the computed level //Level = block[4]; CapsuleIndex = block[5]; _HP = BitConverter.ToUInt16(block, 6); // todo: validate this against computed stats m_stats = new IntStatValues(BitConverter.ToUInt16(block, 8), BitConverter.ToUInt16(block, 10), BitConverter.ToUInt16(block, 12), BitConverter.ToUInt16(block, 14), BitConverter.ToUInt16(block, 16), BitConverter.ToUInt16(block, 18)); Mail = new byte[56]; Array.Copy(block, 20, Mail, 0, 56); Unknown7 = new byte[8]; Array.Copy(block, 76, Unknown7, 0, 8); Padding = new byte[16]; Array.Copy(block, 84, Padding, 0, 16); } } // todo: parse status afflictions (enum + sleep turns) public byte StatusAffliction { get; set; } public byte Unknown5 { get; set; } public ushort Unknown6 { get; set; } public byte CapsuleIndex { get; set; } public override ushort HP { get { return _HP; } } // remaining hp public ushort _HP { get; set; } public byte[] Mail { get; set; } // 56 bytes public byte[] Unknown7 { get; set; } // 8 bytes public byte[] Padding { get; set; } // 16 bytes. Pads the length to match the gen4 structure. private IntStatValues m_stats; public override IntStatValues Stats { get { return m_stats; } } public override int Size { get { return 236; } } } } ================================================ FILE: library/Structures/PokemonPartyBase.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using PkmnFoundations.Pokedex; using PkmnFoundations.Support; namespace PkmnFoundations.Structures { public abstract class PokemonPartyBase : PokemonBase { public PokemonPartyBase(Pokedex.Pokedex pokedex) : base(pokedex) { Initialize(); } private void Initialize() { Ribbons = new HashSet(); UnknownRibbons = new HashSet(); } private int m_experience; public int Experience { get { return m_experience; } set { if (m_experience == value) return; m_experience = value; m_level = null; // xxx: if exp changes but level doesn't, this gets invalidated for no reason. // (really needs observable) m_stats = null; } } private byte? m_level; public override byte Level { get { if (m_level == null) m_level = LevelAt(m_experience, Species.GrowthRate); return (byte)m_level; } set { if (m_level == value) return; m_experience = ExperienceAt(value, Species.GrowthRate); m_level = value; m_stats = null; } } protected bool m_female; protected bool m_genderless; public override Genders Gender { get { if (m_genderless) return Genders.None; if (m_female) return Genders.Female; return Genders.Male; } set { m_female = value == Genders.Female; m_genderless = value == Genders.None; } } public Markings Markings { get; set; } public ConditionValues ContestStats { get; set; } public bool IsEgg { get; set; } public bool IsBadEgg { get; set; } /// /// this field decides whether or not its name gets reverted when it evolves. /// public bool HasNickname { get; set; } /// /// aka. obedience flag. A few pokemon, eg. Mew, are disobedient unless this is set. /// public bool FatefulEncounter { get; set; } public Versions Version { get; set; } public virtual TrainerMemo TrainerMemo { get; set; } // this is the notorious genIV encounter type flag, not used for much besides validation public byte EncounterType { get; set; } public abstract String TrainerName { get; set; } public TrainerGenders TrainerGender { get; set; } public abstract Item Pokeball { get; set; } public HashSet Ribbons { get; private set; } /// /// This allows preservation of unknown ribbon flags when saving. /// public HashSet UnknownRibbons { get; private set; } private IntStatValues m_stats = null; public virtual IntStatValues Stats { get { if (m_stats == null) { // todo: stat formula throw new NotImplementedException(); } return m_stats; } } private byte m_pokerus_days_left = 0; public virtual byte PokerusDaysLeft { get { return m_pokerus_days_left; } set { if (value > 15) throw new ArgumentOutOfRangeException(); m_pokerus_days_left = value; } } private byte m_pokerus_strain = 0; public virtual byte PokerusStrain { get { return m_pokerus_strain; } set { if (value > 15) throw new ArgumentOutOfRangeException(); m_pokerus_strain = value; } } public Pokerus Pokerus { get { // note: "strain 0" is invalid and will cause the pokemon to // lose pokerus entirely once its days left hits 0. if (PokerusDaysLeft > 0) return Pokerus.Infected; if (PokerusStrain > 0) return Pokerus.Cured; return Pokerus.None; } } public abstract ushort HP { get; } public static ushort ComputeChecksum(byte[] data) { ushort result = 0; for (int x = 0; x < data.Length; x += 2) result += BitConverter.ToUInt16(data, x); return result; } public static ushort ComputeChecksum(byte[][] data) { return (ushort)data.Sum(inner => ComputeChecksum(inner)); } protected static int DecryptRNG(int prev) { return prev * 0x41c64e6d + 0x6073; } protected static void DecryptBlocks(byte[][] blocks, ushort checksum) { int rand = (int)checksum; for (int x = 0; x < 4; x++) { byte[] block = blocks[x]; for (int pos = 0; pos < 32; pos += 2) { rand = DecryptRNG(rand); block[pos] ^= (byte)(rand >> 16); block[pos + 1] ^= (byte)(rand >> 24); } } } protected static void ShuffleBlocks(byte[][] blocks, uint personality, bool unshuffle) { // shuffle blocks to their correct order List blockSequence = BlockScramble((personality & 0x0003e000) >> 0x0d); if (unshuffle) blockSequence = Invert(blockSequence); AssertHelper.Equals(blockSequence.Count, 4); { byte[][] blocks2 = new byte[4][]; for (int x = 0; x < 4; x++) blocks2[x] = blocks[blockSequence[x]]; for (int x = 0; x < 4; x++) blocks[x] = blocks2[x]; } } public static bool HasRibbon(byte[] ribbons, int value) { if (value >= 96 || value < 0) throw new ArgumentOutOfRangeException(); int offset = value >> 3; byte mask = (byte)(1 << (value & 0x07)); return (ribbons[offset] & mask) != 0; } protected static DateTime? TrainerMemoDateTime(byte[] data) { // todo: merge with GtsRecordBase datetime helper. if (data.Length != 3) throw new ArgumentException(); if (data[1] == 0 && data[2] == 0 && data[0] == 0) return null; try { return new DateTime(2000 + data[0], data[1], data[2]); } catch (ArgumentOutOfRangeException) { return null; } } } } ================================================ FILE: library/Structures/StatValues.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PkmnFoundations.Structures { public class StatValues : StatValuesBase where T : struct { public StatValues(T hp, T attack, T defense, T speed, T special_attack, T special_defense) : base(hp, attack, defense, speed, special_attack, special_defense) { } public StatValues(IEnumerable s) : base(s) { } public T Hp { get { return Stats[0]; } set { Stats[0] = value; } } public T Attack { get { return Stats[1]; } set { Stats[1] = value; } } public T Defense { get { return Stats[2]; } set { Stats[2] = value; } } public T Speed { get { return Stats[3]; } set { Stats[3] = value; } } public T SpecialAttack { get { return Stats[4]; } set { Stats[4] = value; } } public T SpecialDefense { get { return Stats[5]; } set { Stats[5] = value; } } public static int StatsIndex(Stats stat) { return (int)stat - 1; } public virtual T this[Stats stat] { get { int index = StatsIndex(stat); if (index < 0 || index >= 6) throw new ArgumentException(); return Stats[index]; } set { int index = StatsIndex(stat); if (index < 0 || index >= 6) throw new ArgumentException(); Stats[index] = value; } } public override string ToString() { return String.Format("{0}/{1}/{2}/{4}/{5}/{3}", Hp, Attack, Defense, Speed, SpecialAttack, SpecialDefense); } } } ================================================ FILE: library/Structures/StatValuesBase.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PkmnFoundations.Structures { public abstract class StatValuesBase where T : struct { protected StatValuesBase(IEnumerable s) { // fail without enumerating if possible if (s is IList && ((IList)s).Count != 6) throw new ArgumentException("Collection must have exactly 6 elements.", "s"); var arr = s.ToArray(); if (arr.Length != 6) throw new ArgumentException("Collection must have exactly 6 elements.", "s"); Stats = arr; } protected StatValuesBase(T s0, T s1, T s2, T s3, T s4, T s5) : this(new T[6] { s0, s1, s2, s3, s4, s5 }) { } protected T[] Stats { get; private set; } public T[] ToArray() { return Stats.ToArray(); } } } ================================================ FILE: library/Structures/TrainerMemo.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using PkmnFoundations.Pokedex; using PkmnFoundations.Support; namespace PkmnFoundations.Structures { public class TrainerMemo { public TrainerMemo(Pokedex.Pokedex pokedex, LocationNumbering numbering, DateTime ? time_egg_obtained, DateTime ? time_encountered, int location_egg_obtained_id, int location_encountered_id, bool is_hatched, byte level_encountered) { m_pokedex = pokedex; m_location_egg_obtained_pair = Location.CreatePairForLocationNumbering(m_pokedex, () => Numbering); m_location_encountered_pair = Location.CreatePairForLocationNumbering(m_pokedex, () => Numbering); Numbering = numbering; TimeEggObtained = time_egg_obtained; TimeEncountered = time_encountered; m_location_egg_obtained_pair.Key = location_egg_obtained_id; m_location_encountered_pair.Key = location_encountered_id; IsHatched = is_hatched; LevelEncountered = level_encountered; } private Pokedex.Pokedex m_pokedex; public LocationNumbering Numbering { get; private set; } public DateTime? TimeEggObtained { get; private set; } public DateTime? TimeEncountered { get; private set; } private LazyKeyValuePair m_location_egg_obtained_pair; public int LocationEggObtainedID { get { return m_location_egg_obtained_pair.Key; } } public Location LocationEggObtained { get { return m_location_egg_obtained_pair.Value; } } private LazyKeyValuePair m_location_encountered_pair; public int LocationEncounteredID { get { return m_location_encountered_pair.Key; } } public Location LocationEncountered { get { return m_location_encountered_pair.Value; } } public bool IsHatched { get; private set; } public byte LevelEncountered { get; private set; } public override String ToString() { if (IsHatched) { String timeEgg = TimeEggObtained == null ? "???" : ((DateTime)TimeEggObtained).ToString("D"); String timeGiven = TimeEncountered == null ? "???" : ((DateTime)TimeEncountered).ToString("D"); return String.Format("Egg obtained from {1} on {0:D}. Hatched in {3} on {2:D}.", timeEgg, LocationToString(LocationEggObtained, LocationEggObtainedID), timeGiven, LocationToString(LocationEncountered, LocationEncounteredID)); } else { String level = LevelEncountered.ToString(); String time = TimeEncountered == null ? "???" : ((DateTime)TimeEncountered).ToString("D"); return String.Format("Met at Lv. {0} in {2} on {1:D}.", level, time, LocationToString(LocationEncountered, LocationEncounteredID)); } } private String LocationToString(Location l, int id) { if (l == null || l.Name == null) return "Mystery zone #" + id.ToString(); return l.Name.ToString(); } } } ================================================ FILE: library/Support/AliasTable.cs ================================================ using System; using System.Collections.Generic; namespace PkmnFoundations.Support { /// /// Vose's implementation of the Alias method for choosing weighted randomly from a set. /// /// See: https://www.keithschwarz.com/darts-dice-coins/ /// public class AliasTable { public static AliasTable NewWithWeights(Dictionary typesWithProbabilities) { List elements = new List(); foreach (var pair in typesWithProbabilities) { elements.Add(pair.Key); } Dictionary table = new Dictionary(); Dictionary probs = new Dictionary(); double size = (double)typesWithProbabilities.Count; Stack smallTypes = new Stack(); Stack largeTypes = new Stack(); Dictionary scaledProbabilityMap = new Dictionary(); foreach (var pair in typesWithProbabilities) { double scaledProbability = pair.Value * size; scaledProbabilityMap[pair.Key] = scaledProbability; if (scaledProbability < 1.0) { smallTypes.Push(pair.Key); } else { largeTypes.Push(pair.Key); } } while (smallTypes.Count != 0 && largeTypes.Count != 0) { Type smallElement = smallTypes.Pop(); Type largeElement = largeTypes.Pop(); table[smallElement] = largeElement; double scaledSmall = scaledProbabilityMap[smallElement]; double scaledLarge = scaledProbabilityMap[largeElement]; probs[smallElement] = scaledSmall; double newLarge = (scaledLarge + scaledSmall) - 1.0; probs[largeElement] = newLarge; if (newLarge < 1.0) { smallTypes.Push(largeElement); } else { largeTypes.Push(largeElement); } } while (largeTypes.Count != 0) { Type largeElement = largeTypes.Pop(); probs[largeElement] = 1.0; } while (smallTypes.Count != 0) { Type smallElement = smallTypes.Pop(); probs[smallElement] = 1.0; } return new AliasTable(table, elements, probs); } public Type Sample() { Type element = elements[rng.Next(0, elements.Count)]; int number = rng.Next(0, 101); double probability = probabilities[element]; if (number <= (probability * 100)) { return element; } else { return underlyingTable[element]; } } private AliasTable(Dictionary table, List elem, Dictionary probs) { underlyingTable = table; elements = elem; probabilities = probs; rng = new Random(); } private Dictionary underlyingTable; private List elements; private Dictionary probabilities; private Random rng; } } ================================================ FILE: library/Support/AssertHelper.cs ================================================ using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.IO; namespace PkmnFoundations.Support { public class AssertHelper { public static void Assert(bool condition, String message) { if (!condition) LogHelper.Write(message, EventLogEntryType.Error); #if DEBUG Debug.Assert(condition, message); #endif } public static void Assert(bool condition) { Assert(condition, "Assert failed."); } public static void Unreachable() { Assert(false, "Assert failed: Unreachable code has been reached."); } public static void Equals(T first, T second) where T : IEquatable { Assert(((IEquatable)first).Equals((IEquatable)second), "Assert failed: Values are not equal."); } } } ================================================ FILE: library/Support/BinarySerializableBase.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Text; namespace PkmnFoundations.Support { /// /// Base class for objects which serialize using BinaryReader and BinaryWriter /// public abstract class BinarySerializableBase : ISerializable { // xxx: ISerializable may be useless or even non-idiomatic on this class. public BinarySerializableBase() { } public BinarySerializableBase(SerializationInfo info, StreamingContext context) { byte[] data = (byte[])info.GetValue("data", typeof(byte[])); Load(data, 0); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("data", Save()); } protected abstract void Save(BinaryWriter writer); protected abstract void Load(BinaryReader reader); /// /// Size of the serialized structure in bytes /// public abstract int Size { get; } public byte[] Save() { byte[] data = new byte[Size]; Save(new BinaryWriter(new MemoryStream(data))); return data; } public void Load(byte[] data, int offset) { if (offset + Size > data.Length) throw new ArgumentOutOfRangeException("offset"); if (offset < 0) throw new ArgumentOutOfRangeException("offset"); MemoryStream m = new MemoryStream(data, offset, Size); Load(new BinaryReader(m)); } public void Load(byte[] data) { if (Size > data.Length) throw new ArgumentException("Buffer is too small"); Load(data, 0); } } } ================================================ FILE: library/Support/EncodedString4.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace PkmnFoundations.Support { public class EncodedString4 : EncodedStringBase { /// /// Instances an EncodedString4 from its binary representation. /// /// This buffer is copied. public EncodedString4(byte[] data) : base(data) { } /// /// Instances an EncodedString4 from its binary representation. /// /// Buffer to copy from /// Offset in buffer /// Number of bytes (not chars) to copy public EncodedString4(byte[] data, int start, int length) : base(data, start, length) { } /// /// Instances an EncodedString4 from a Unicode string. /// /// text /// Length of encoded buffer in bytes (not chars) public EncodedString4(string text, int length) : base(text, length) { } // todo: Use pointers for both of these public static string DecodeString_impl(byte[] data, int start, int count) { if (data.Length < start + count) throw new ArgumentOutOfRangeException("count"); if (count < 0) throw new ArgumentOutOfRangeException("count"); StringBuilder sb = new StringBuilder(); for (int i = start; i < start + count * 2; i += 2) { ushort gamecode = BitConverter.ToUInt16(data, i); if (gamecode == 0xffff) { break; } char ch = Generation4TextLookupTable.ContainsKey(gamecode) ? Generation4TextLookupTable[gamecode] : '?'; sb.Append(ch); } return sb.ToString(); } public static string DecodeString_impl(byte[] data) { return DecodeString_impl(data, 0, data.Length >> 1); } public static byte[] EncodeString_impl(string str, int size) { int actualLength = (size >> 1) - 1; if (str.Length > actualLength) throw new ArgumentOutOfRangeException("size"); byte[] result = new byte[size]; MemoryStream m = new MemoryStream(result); foreach (char c in str.ToCharArray()) { m.Write(BitConverter.GetBytes(LookupReverse.ContainsKey(c) ? LookupReverse[c] : (ushort)0x01ac), 0, 2); } m.WriteByte(0xff); m.WriteByte(0xff); return result; } protected override string DecodeString(byte[] data, int start, int count) { return DecodeString_impl(data, start, count); } protected override byte[] EncodeString(string str, int size) { return EncodeString_impl(str, size); } public override bool IsValid { get { for (int i = 0; i < RawData.Length; i += 2) { ushort gamecode = BitConverter.ToUInt16(RawData, i); if (gamecode == 0xffff) break; if (gamecode == 0x0000) return false; } return true; } } public EncodedString4 Clone() { return new EncodedString4(RawData); } private static Dictionary m_lookup_reverse = null; private static Dictionary LookupReverse { get { if (m_lookup_reverse == null) { Dictionary reverse = new Dictionary(Generation4TextLookupTable.Count); foreach (KeyValuePair pair in Generation4TextLookupTable) { if (!reverse.ContainsKey(pair.Value)) reverse.Add(pair.Value, pair.Key); } m_lookup_reverse = reverse; } return m_lookup_reverse; } } // Lookup table courtesy of Aqua // https://github.com/projectpokemon/PPRE/blob/master/Table.tbl private static Dictionary Generation4TextLookupTable = new Dictionary { {0x0001, '\u3000'}, {0x0002, '\u3041'}, {0x0003, '\u3042'}, {0x0004, '\u3043'}, {0x0005, '\u3044'}, {0x0006, '\u3045'}, {0x0007, '\u3046'}, {0x0008, '\u3047'}, {0x0009, '\u3048'}, {0x000a, '\u3049'}, {0x000b, '\u304a'}, {0x000c, '\u304b'}, {0x000d, '\u304c'}, {0x000e, '\u304d'}, {0x000f, '\u304e'}, {0x0010, '\u304f'}, {0x0011, '\u3050'}, {0x0012, '\u3051'}, {0x0013, '\u3052'}, {0x0014, '\u3053'}, {0x0015, '\u3054'}, {0x0016, '\u3055'}, {0x0017, '\u3056'}, {0x0018, '\u3057'}, {0x0019, '\u3058'}, {0x001a, '\u3059'}, {0x001b, '\u305a'}, {0x001c, '\u305b'}, {0x001d, '\u305c'}, {0x001e, '\u305d'}, {0x001f, '\u305e'}, {0x0020, '\u305f'}, {0x0021, '\u3060'}, {0x0022, '\u3061'}, {0x0023, '\u3062'}, {0x0024, '\u3063'}, {0x0025, '\u3064'}, {0x0026, '\u3065'}, {0x0027, '\u3066'}, {0x0028, '\u3067'}, {0x0029, '\u3068'}, {0x002a, '\u3069'}, {0x002b, '\u306a'}, {0x002c, '\u306b'}, {0x002d, '\u306c'}, {0x002e, '\u306d'}, {0x002f, '\u306e'}, {0x0030, '\u306f'}, {0x0031, '\u3070'}, {0x0032, '\u3071'}, {0x0033, '\u3072'}, {0x0034, '\u3073'}, {0x0035, '\u3074'}, {0x0036, '\u3075'}, {0x0037, '\u3076'}, {0x0038, '\u3077'}, {0x0039, '\u3078'}, {0x003a, '\u3079'}, {0x003b, '\u307a'}, {0x003c, '\u307b'}, {0x003d, '\u307c'}, {0x003e, '\u307d'}, {0x003f, '\u307e'}, {0x0040, '\u307f'}, {0x0041, '\u3080'}, {0x0042, '\u3081'}, {0x0043, '\u3082'}, {0x0044, '\u3083'}, {0x0045, '\u3084'}, {0x0046, '\u3085'}, {0x0047, '\u3086'}, {0x0048, '\u3087'}, {0x0049, '\u3088'}, {0x004a, '\u3089'}, {0x004b, '\u308a'}, {0x004c, '\u308b'}, {0x004d, '\u308c'}, {0x004e, '\u308d'}, {0x004f, '\u308f'}, {0x0050, '\u3092'}, {0x0051, '\u3093'}, {0x0052, '\u30a1'}, {0x0053, '\u30a2'}, {0x0054, '\u30a3'}, {0x0055, '\u30a4'}, {0x0056, '\u30a5'}, {0x0057, '\u30a6'}, {0x0058, '\u30a7'}, {0x0059, '\u30a8'}, {0x005a, '\u30a9'}, {0x005b, '\u30aa'}, {0x005c, '\u30ab'}, {0x005d, '\u30ac'}, {0x005e, '\u30ad'}, {0x005f, '\u30ae'}, {0x0060, '\u30af'}, {0x0061, '\u30b0'}, {0x0062, '\u30b1'}, {0x0063, '\u30b2'}, {0x0064, '\u30b3'}, {0x0065, '\u30b4'}, {0x0066, '\u30b5'}, {0x0067, '\u30b6'}, {0x0068, '\u30b7'}, {0x0069, '\u30b8'}, {0x006a, '\u30b9'}, {0x006b, '\u30ba'}, {0x006c, '\u30bb'}, {0x006d, '\u30bc'}, {0x006e, '\u30bd'}, {0x006f, '\u30be'}, {0x0070, '\u30bf'}, {0x0071, '\u30c0'}, {0x0072, '\u30c1'}, {0x0073, '\u30c2'}, {0x0074, '\u30c3'}, {0x0075, '\u30c4'}, {0x0076, '\u30c5'}, {0x0077, '\u30c6'}, {0x0078, '\u30c7'}, {0x0079, '\u30c8'}, {0x007a, '\u30c9'}, {0x007b, '\u30ca'}, {0x007c, '\u30cb'}, {0x007d, '\u30cc'}, {0x007e, '\u30cd'}, {0x007f, '\u30ce'}, {0x0080, '\u30cf'}, {0x0081, '\u30d0'}, {0x0082, '\u30d1'}, {0x0083, '\u30d2'}, {0x0084, '\u30d3'}, {0x0085, '\u30d4'}, {0x0086, '\u30d5'}, {0x0087, '\u30d6'}, {0x0088, '\u30d7'}, {0x0089, '\u30d8'}, {0x008a, '\u30d9'}, {0x008b, '\u30da'}, {0x008c, '\u30db'}, {0x008d, '\u30dc'}, {0x008e, '\u30dd'}, {0x008f, '\u30de'}, {0x0090, '\u30df'}, {0x0091, '\u30e0'}, {0x0092, '\u30e1'}, {0x0093, '\u30e2'}, {0x0094, '\u30e3'}, {0x0095, '\u30e4'}, {0x0096, '\u30e5'}, {0x0097, '\u30e6'}, {0x0098, '\u30e7'}, {0x0099, '\u30e8'}, {0x009a, '\u30e9'}, {0x009b, '\u30ea'}, {0x009c, '\u30eb'}, {0x009d, '\u30ec'}, {0x009e, '\u30ed'}, {0x009f, '\u30ef'}, {0x00a0, '\u30f2'}, {0x00a1, '\u30f3'}, {0x00a2, '\uff10'}, {0x00a3, '\uff11'}, {0x00a4, '\uff12'}, {0x00a5, '\uff13'}, {0x00a6, '\uff14'}, {0x00a7, '\uff15'}, {0x00a8, '\uff16'}, {0x00a9, '\uff17'}, {0x00aa, '\uff18'}, {0x00ab, '\uff19'}, {0x00ac, '\uff21'}, {0x00ad, '\uff22'}, {0x00ae, '\uff23'}, {0x00af, '\uff24'}, {0x00b0, '\uff25'}, {0x00b1, '\uff26'}, {0x00b2, '\uff27'}, {0x00b3, '\uff28'}, {0x00b4, '\uff29'}, {0x00b5, '\uff2a'}, {0x00b6, '\uff2b'}, {0x00b7, '\uff2c'}, {0x00b8, '\uff2d'}, {0x00b9, '\uff2e'}, {0x00ba, '\uff2f'}, {0x00bb, '\uff30'}, {0x00bc, '\uff31'}, {0x00bd, '\uff32'}, {0x00be, '\uff33'}, {0x00bf, '\uff34'}, {0x00c0, '\uff35'}, {0x00c1, '\uff36'}, {0x00c2, '\uff37'}, {0x00c3, '\uff38'}, {0x00c4, '\uff39'}, {0x00c5, '\uff3a'}, {0x00c6, '\uff41'}, {0x00c7, '\uff42'}, {0x00c8, '\uff43'}, {0x00c9, '\uff44'}, {0x00ca, '\uff45'}, {0x00cb, '\uff46'}, {0x00cc, '\uff47'}, {0x00cd, '\uff48'}, {0x00ce, '\uff49'}, {0x00cf, '\uff4a'}, {0x00d0, '\uff4b'}, {0x00d1, '\uff4c'}, {0x00d2, '\uff4d'}, {0x00d3, '\uff4e'}, {0x00d4, '\uff4f'}, {0x00d5, '\uff50'}, {0x00d6, '\uff51'}, {0x00d7, '\uff52'}, {0x00d8, '\uff53'}, {0x00d9, '\uff54'}, {0x00da, '\uff55'}, {0x00db, '\uff56'}, {0x00dc, '\uff57'}, {0x00dd, '\uff58'}, {0x00de, '\uff59'}, {0x00df, '\uff5a'}, {0x00e1, '\uff01'}, {0x00e2, '\uff1f'}, {0x00e3, '\u3001'}, {0x00e4, '\u3002'}, {0x00e5, '\u22ef'}, {0x00e6, '\u30fb'}, {0x00e7, '\uff0f'}, {0x00e8, '\u300c'}, {0x00e9, '\u300d'}, {0x00ea, '\u300e'}, {0x00eb, '\u300f'}, {0x00ec, '\uff08'}, {0x00ed, '\uff09'}, {0x00ee, '\u2642'}, {0x00ef, '\u2640'}, {0x00f0, '\uff0b'}, {0x00f1, '\uff0d'}, {0x00f2, '\u00d7'}, {0x00f3, '\u00f7'}, {0x00f4, '\uff1d'}, {0x00f5, '\uff5a'}, {0x00f6, '\uff1a'}, {0x00f7, '\uff1b'}, {0x00f8, '\uff0e'}, {0x00f9, '\uff0c'}, {0x00fa, '\u2664'}, {0x00fb, '\u2667'}, {0x00fc, '\u2665'}, {0x00fd, '\u2662'}, {0x00fe, '\u2606'}, {0x00ff, '\u25ce'}, {0x0100, '\u25cb'}, {0x0101, '\u25a1'}, {0x0102, '\u25b3'}, {0x0103, '\u25c7'}, {0x0104, '\uff20'}, {0x0105, '\u266a'}, {0x0106, '\uff05'}, {0x0107, '\u2600'}, {0x0108, '\u2601'}, {0x0109, '\u2602'}, {0x010a, '\u2744'}, {0x010b, '\u260b'}, {0x010c, '\u2654'}, {0x010d, '\u2655'}, {0x010e, '\u260a'}, {0x010f, '\u21d7'}, {0x0110, '\u21d8'}, {0x0111, '\u263e'}, {0x0112, '\u00a5'}, {0x0113, '\u2648'}, {0x0114, '\u2649'}, {0x0115, '\u264a'}, {0x0116, '\u264b'}, {0x0117, '\u264c'}, {0x0118, '\u264d'}, {0x0119, '\u264e'}, {0x011a, '\u264f'}, {0x011b, '\u2190'}, {0x011c, '\u2191'}, {0x011d, '\u2193'}, {0x011e, '\u2192'}, {0x011f, '\u2023'}, {0x0120, '\uff06'}, {0x0121, '\u0030'}, {0x0122, '\u0031'}, {0x0123, '\u0032'}, {0x0124, '\u0033'}, {0x0125, '\u0034'}, {0x0126, '\u0035'}, {0x0127, '\u0036'}, {0x0128, '\u0037'}, {0x0129, '\u0038'}, {0x012a, '\u0039'}, {0x012b, '\u0041'}, {0x012c, '\u0042'}, {0x012d, '\u0043'}, {0x012e, '\u0044'}, {0x012f, '\u0045'}, {0x0130, '\u0046'}, {0x0131, '\u0047'}, {0x0132, '\u0048'}, {0x0133, '\u0049'}, {0x0134, '\u004a'}, {0x0135, '\u004b'}, {0x0136, '\u004c'}, {0x0137, '\u004d'}, {0x0138, '\u004e'}, {0x0139, '\u004f'}, {0x013a, '\u0050'}, {0x013b, '\u0051'}, {0x013c, '\u0052'}, {0x013d, '\u0053'}, {0x013e, '\u0054'}, {0x013f, '\u0055'}, {0x0140, '\u0056'}, {0x0141, '\u0057'}, {0x0142, '\u0058'}, {0x0143, '\u0059'}, {0x0144, '\u005a'}, {0x0145, '\u0061'}, {0x0146, '\u0062'}, {0x0147, '\u0063'}, {0x0148, '\u0064'}, {0x0149, '\u0065'}, {0x014a, '\u0066'}, {0x014b, '\u0067'}, {0x014c, '\u0068'}, {0x014d, '\u0069'}, {0x014e, '\u006a'}, {0x014f, '\u006b'}, {0x0150, '\u006c'}, {0x0151, '\u006d'}, {0x0152, '\u006e'}, {0x0153, '\u006f'}, {0x0154, '\u0070'}, {0x0155, '\u0071'}, {0x0156, '\u0072'}, {0x0157, '\u0073'}, {0x0158, '\u0074'}, {0x0159, '\u0075'}, {0x015a, '\u0076'}, {0x015b, '\u0077'}, {0x015c, '\u0078'}, {0x015d, '\u0079'}, {0x015e, '\u007a'}, {0x015f, '\u00c0'}, {0x0160, '\u00c1'}, {0x0161, '\u00c2'}, {0x0162, '\u00c3'}, {0x0163, '\u00c4'}, {0x0164, '\u00c5'}, {0x0165, '\u00c6'}, {0x0166, '\u00c7'}, {0x0167, '\u00c8'}, {0x0168, '\u00c9'}, {0x0169, '\u00ca'}, {0x016a, '\u00cb'}, {0x016b, '\u00cc'}, {0x016c, '\u00cd'}, {0x016d, '\u00ce'}, {0x016e, '\u00cf'}, {0x016f, '\u00d0'}, {0x0170, '\u00d1'}, {0x0171, '\u00d2'}, {0x0172, '\u00d3'}, {0x0173, '\u00d4'}, {0x0174, '\u00d5'}, {0x0175, '\u00d6'}, {0x0176, '\u00d7'}, {0x0177, '\u00d8'}, {0x0178, '\u00d9'}, {0x0179, '\u00da'}, {0x017a, '\u00db'}, {0x017b, '\u00dc'}, {0x017c, '\u00dd'}, {0x017d, '\u00de'}, {0x017e, '\u00df'}, {0x017f, '\u00e0'}, {0x0180, '\u00e1'}, {0x0181, '\u00e2'}, {0x0182, '\u00e3'}, {0x0183, '\u00e4'}, {0x0184, '\u00e5'}, {0x0185, '\u00e6'}, {0x0186, '\u00e7'}, {0x0187, '\u00e8'}, {0x0188, '\u00e9'}, {0x0189, '\u00ea'}, {0x018a, '\u00eb'}, {0x018b, '\u00ec'}, {0x018c, '\u00ed'}, {0x018d, '\u00ee'}, {0x018e, '\u00ef'}, {0x018f, '\u00f0'}, {0x0190, '\u00f1'}, {0x0191, '\u00f2'}, {0x0192, '\u00f3'}, {0x0193, '\u00f4'}, {0x0194, '\u00f5'}, {0x0195, '\u00f6'}, {0x0196, '\u00f7'}, {0x0197, '\u00f8'}, {0x0198, '\u00f9'}, {0x0199, '\u00fa'}, {0x019a, '\u00fb'}, {0x019b, '\u00fc'}, {0x019c, '\u00fd'}, {0x019d, '\u00fe'}, {0x019e, '\u00ff'}, {0x019f, '\u0152'}, {0x01a0, '\u0153'}, {0x01a1, '\u015e'}, {0x01a2, '\u015f'}, {0x01a3, '\u00aa'}, {0x01a4, '\u00ba'}, {0x01a5, '\u00b9'}, {0x01a6, '\u00b2'}, {0x01a7, '\u00b3'}, {0x01a8, '\u0024'}, {0x01a9, '\u00a1'}, {0x01aa, '\u00bf'}, {0x01ab, '\u0021'}, {0x01ac, '\u003f'}, {0x01ad, '\u002c'}, {0x01ae, '\u002e'}, {0x01af, '\u2026'}, {0x01b0, '\uff65'}, {0x01b1, '\u002f'}, {0x01b2, '\u2018'}, {0x01b3, '\u2019'}, {0x01b4, '\u201c'}, {0x01b5, '\u201d'}, {0x01b6, '\u201e'}, {0x01b7, '\u300a'}, {0x01b8, '\u300b'}, {0x01b9, '\u0028'}, {0x01ba, '\u0029'}, {0x01bb, '\u2642'}, {0x01bc, '\u2640'}, {0x01bd, '\u002b'}, {0x01be, '\u002d'}, {0x01bf, '\u002a'}, {0x01c0, '\u0023'}, {0x01c1, '\u003d'}, {0x01c2, '\u0026'}, {0x01c3, '\u007e'}, {0x01c4, '\u003a'}, {0x01c5, '\u003b'}, {0x01c6, '\u246f'}, {0x01c7, '\u2470'}, {0x01c8, '\u2471'}, {0x01c9, '\u2472'}, {0x01ca, '\u2473'}, {0x01cb, '\u2474'}, {0x01cc, '\u2475'}, {0x01cd, '\u2476'}, {0x01ce, '\u2477'}, {0x01cf, '\u2478'}, {0x01d0, '\u0040'}, {0x01d1, '\u2479'}, {0x01d2, '\u0025'}, {0x01d3, '\u247a'}, {0x01d4, '\u247b'}, {0x01d5, '\u247c'}, {0x01d6, '\u247d'}, {0x01d7, '\u247e'}, {0x01d8, '\u247f'}, {0x01d9, '\u2480'}, {0x01da, '\u2481'}, {0x01db, '\u2482'}, {0x01dc, '\u2483'}, {0x01dd, '\u2484'}, {0x01de, '\u0020'}, {0x01df, '\u2485'}, {0x01e0, '\u2486'}, {0x01e1, '\u2487'}, {0x01e8, '\u00b0'}, {0x01e9, '\u005f'}, {0x01ea, '\uff3f'}, {0x0400, '\uac00'}, {0x0401, '\uac01'}, {0x0402, '\uac04'}, {0x0403, '\uac07'}, {0x0404, '\uac08'}, {0x0405, '\uac09'}, {0x0406, '\uac0a'}, {0x0407, '\uac10'}, {0x0408, '\uac11'}, {0x0409, '\uac12'}, {0x040a, '\uac13'}, {0x040b, '\uac14'}, {0x040c, '\uac15'}, {0x040d, '\uac16'}, {0x040e, '\uac17'}, {0x0410, '\uac19'}, {0x0411, '\uac1a'}, {0x0412, '\uac1b'}, {0x0413, '\uac1c'}, {0x0414, '\uac1d'}, {0x0415, '\uac20'}, {0x0416, '\uac24'}, {0x0417, '\uac2c'}, {0x0418, '\uac2d'}, {0x0419, '\uac2f'}, {0x041a, '\uac30'}, {0x041b, '\uac31'}, {0x041c, '\uac38'}, {0x041d, '\uac39'}, {0x041e, '\uac3c'}, {0x041f, '\uac40'}, {0x0420, '\uac4b'}, {0x0421, '\uac4d'}, {0x0422, '\uac54'}, {0x0423, '\uac58'}, {0x0424, '\uac5c'}, {0x0425, '\uac70'}, {0x0426, '\uac71'}, {0x0427, '\uac74'}, {0x0428, '\uac77'}, {0x0429, '\uac78'}, {0x042a, '\uac7a'}, {0x042b, '\uac80'}, {0x042c, '\uac81'}, {0x042d, '\uac83'}, {0x042e, '\uac84'}, {0x042f, '\uac85'}, {0x0430, '\uac86'}, {0x0431, '\uac89'}, {0x0432, '\uac8a'}, {0x0433, '\uac8b'}, {0x0434, '\uac8c'}, {0x0435, '\uac90'}, {0x0436, '\uac94'}, {0x0437, '\uac9c'}, {0x0438, '\uac9d'}, {0x0439, '\uac9f'}, {0x043a, '\uaca0'}, {0x043b, '\uaca1'}, {0x043c, '\uaca8'}, {0x043d, '\uaca9'}, {0x043e, '\uacaa'}, {0x043f, '\uacac'}, {0x0440, '\uacaf'}, {0x0441, '\uacb0'}, {0x0442, '\uacb8'}, {0x0443, '\uacb9'}, {0x0444, '\uacbb'}, {0x0445, '\uacbc'}, {0x0446, '\uacbd'}, {0x0447, '\uacc1'}, {0x0448, '\uacc4'}, {0x0449, '\uacc8'}, {0x044a, '\uaccc'}, {0x044b, '\uacd5'}, {0x044c, '\uacd7'}, {0x044d, '\uace0'}, {0x044e, '\uace1'}, {0x044f, '\uace4'}, {0x0450, '\uace7'}, {0x0451, '\uace8'}, {0x0452, '\uacea'}, {0x0453, '\uacec'}, {0x0454, '\uacef'}, {0x0455, '\uacf0'}, {0x0456, '\uacf1'}, {0x0457, '\uacf3'}, {0x0458, '\uacf5'}, {0x0459, '\uacf6'}, {0x045a, '\uacfc'}, {0x045b, '\uacfd'}, {0x045c, '\uad00'}, {0x045d, '\uad04'}, {0x045e, '\uad06'}, {0x045f, '\uad0c'}, {0x0460, '\uad0d'}, {0x0461, '\uad0f'}, {0x0462, '\uad11'}, {0x0463, '\uad18'}, {0x0464, '\uad1c'}, {0x0465, '\uad20'}, {0x0466, '\uad29'}, {0x0467, '\uad2c'}, {0x0468, '\uad2d'}, {0x0469, '\uad34'}, {0x046a, '\uad35'}, {0x046b, '\uad38'}, {0x046c, '\uad3c'}, {0x046d, '\uad44'}, {0x046e, '\uad45'}, {0x046f, '\uad47'}, {0x0470, '\uad49'}, {0x0471, '\uad50'}, {0x0472, '\uad54'}, {0x0473, '\uad58'}, {0x0474, '\uad61'}, {0x0475, '\uad63'}, {0x0476, '\uad6c'}, {0x0477, '\uad6d'}, {0x0478, '\uad70'}, {0x0479, '\uad73'}, {0x047a, '\uad74'}, {0x047b, '\uad75'}, {0x047c, '\uad76'}, {0x047d, '\uad7b'}, {0x047e, '\uad7c'}, {0x047f, '\uad7d'}, {0x0480, '\uad7f'}, {0x0481, '\uad81'}, {0x0482, '\uad82'}, {0x0483, '\uad88'}, {0x0484, '\uad89'}, {0x0485, '\uad8c'}, {0x0486, '\uad90'}, {0x0487, '\uad9c'}, {0x0488, '\uad9d'}, {0x0489, '\uada4'}, {0x048a, '\uadb7'}, {0x048b, '\uadc0'}, {0x048c, '\uadc1'}, {0x048d, '\uadc4'}, {0x048e, '\uadc8'}, {0x048f, '\uadd0'}, {0x0490, '\uadd1'}, {0x0491, '\uadd3'}, {0x0492, '\uaddc'}, {0x0493, '\uade0'}, {0x0494, '\uade4'}, {0x0495, '\uadf8'}, {0x0496, '\uadf9'}, {0x0497, '\uadfc'}, {0x0498, '\uadff'}, {0x0499, '\uae00'}, {0x049a, '\uae01'}, {0x049b, '\uae08'}, {0x049c, '\uae09'}, {0x049d, '\uae0b'}, {0x049e, '\uae0d'}, {0x049f, '\uae14'}, {0x04a0, '\uae30'}, {0x04a1, '\uae31'}, {0x04a2, '\uae34'}, {0x04a3, '\uae37'}, {0x04a4, '\uae38'}, {0x04a5, '\uae3a'}, {0x04a6, '\uae40'}, {0x04a7, '\uae41'}, {0x04a8, '\uae43'}, {0x04a9, '\uae45'}, {0x04aa, '\uae46'}, {0x04ab, '\uae4a'}, {0x04ac, '\uae4c'}, {0x04ad, '\uae4d'}, {0x04ae, '\uae4e'}, {0x04af, '\uae50'}, {0x04b0, '\uae54'}, {0x04b1, '\uae56'}, {0x04b2, '\uae5c'}, {0x04b3, '\uae5d'}, {0x04b4, '\uae5f'}, {0x04b5, '\uae60'}, {0x04b6, '\uae61'}, {0x04b7, '\uae65'}, {0x04b8, '\uae68'}, {0x04b9, '\uae69'}, {0x04ba, '\uae6c'}, {0x04bb, '\uae70'}, {0x04bc, '\uae78'}, {0x04bd, '\uae79'}, {0x04be, '\uae7b'}, {0x04bf, '\uae7c'}, {0x04c0, '\uae7d'}, {0x04c1, '\uae84'}, {0x04c2, '\uae85'}, {0x04c3, '\uae8c'}, {0x04c4, '\uaebc'}, {0x04c5, '\uaebd'}, {0x04c6, '\uaebe'}, {0x04c7, '\uaec0'}, {0x04c8, '\uaec4'}, {0x04c9, '\uaecc'}, {0x04ca, '\uaecd'}, {0x04cb, '\uaecf'}, {0x04cc, '\uaed0'}, {0x04cd, '\uaed1'}, {0x04ce, '\uaed8'}, {0x04cf, '\uaed9'}, {0x04d0, '\uaedc'}, {0x04d1, '\uaee8'}, {0x04d2, '\uaeeb'}, {0x04d3, '\uaeed'}, {0x04d4, '\uaef4'}, {0x04d5, '\uaef8'}, {0x04d6, '\uaefc'}, {0x04d7, '\uaf07'}, {0x04d8, '\uaf08'}, {0x04d9, '\uaf0d'}, {0x04da, '\uaf10'}, {0x04db, '\uaf2c'}, {0x04dc, '\uaf2d'}, {0x04dd, '\uaf30'}, {0x04de, '\uaf32'}, {0x04df, '\uaf34'}, {0x04e0, '\uaf3c'}, {0x04e1, '\uaf3d'}, {0x04e2, '\uaf3f'}, {0x04e3, '\uaf41'}, {0x04e4, '\uaf42'}, {0x04e5, '\uaf43'}, {0x04e6, '\uaf48'}, {0x04e7, '\uaf49'}, {0x04e8, '\uaf50'}, {0x04e9, '\uaf5c'}, {0x04ea, '\uaf5d'}, {0x04eb, '\uaf64'}, {0x04ec, '\uaf65'}, {0x04ed, '\uaf79'}, {0x04ee, '\uaf80'}, {0x04ef, '\uaf84'}, {0x04f0, '\uaf88'}, {0x04f1, '\uaf90'}, {0x04f2, '\uaf91'}, {0x04f3, '\uaf95'}, {0x04f4, '\uaf9c'}, {0x04f5, '\uafb8'}, {0x04f6, '\uafb9'}, {0x04f7, '\uafbc'}, {0x04f8, '\uafc0'}, {0x04f9, '\uafc7'}, {0x04fa, '\uafc8'}, {0x04fb, '\uafc9'}, {0x04fc, '\uafcb'}, {0x04fd, '\uafcd'}, {0x04fe, '\uafce'}, {0x04ff, '\uafd4'}, {0x0500, '\uafdc'}, {0x0501, '\uafe8'}, {0x0502, '\uafe9'}, {0x0503, '\uaff0'}, {0x0504, '\uaff1'}, {0x0505, '\uaff4'}, {0x0506, '\uaff8'}, {0x0507, '\ub000'}, {0x0508, '\ub001'}, {0x0509, '\ub004'}, {0x050a, '\ub00c'}, {0x050b, '\ub010'}, {0x050c, '\ub014'}, {0x050d, '\ub01c'}, {0x050e, '\ub01d'}, {0x050f, '\ub028'}, {0x0510, '\ub044'}, {0x0511, '\ub045'}, {0x0512, '\ub048'}, {0x0513, '\ub04a'}, {0x0514, '\ub04c'}, {0x0515, '\ub04e'}, {0x0516, '\ub053'}, {0x0517, '\ub054'}, {0x0518, '\ub055'}, {0x0519, '\ub057'}, {0x051a, '\ub059'}, {0x051b, '\ub05d'}, {0x051c, '\ub07c'}, {0x051d, '\ub07d'}, {0x051e, '\ub080'}, {0x051f, '\ub084'}, {0x0520, '\ub08c'}, {0x0521, '\ub08d'}, {0x0522, '\ub08f'}, {0x0523, '\ub091'}, {0x0524, '\ub098'}, {0x0525, '\ub099'}, {0x0526, '\ub09a'}, {0x0527, '\ub09c'}, {0x0528, '\ub09f'}, {0x0529, '\ub0a0'}, {0x052a, '\ub0a1'}, {0x052b, '\ub0a2'}, {0x052c, '\ub0a8'}, {0x052d, '\ub0a9'}, {0x052e, '\ub0ab'}, {0x052f, '\ub0ac'}, {0x0530, '\ub0ad'}, {0x0531, '\ub0ae'}, {0x0532, '\ub0af'}, {0x0533, '\ub0b1'}, {0x0534, '\ub0b3'}, {0x0535, '\ub0b4'}, {0x0536, '\ub0b5'}, {0x0537, '\ub0b8'}, {0x0538, '\ub0bc'}, {0x0539, '\ub0c4'}, {0x053a, '\ub0c5'}, {0x053b, '\ub0c7'}, {0x053c, '\ub0c8'}, {0x053d, '\ub0c9'}, {0x053e, '\ub0d0'}, {0x053f, '\ub0d1'}, {0x0540, '\ub0d4'}, {0x0541, '\ub0d8'}, {0x0542, '\ub0e0'}, {0x0543, '\ub0e5'}, {0x0544, '\ub108'}, {0x0545, '\ub109'}, {0x0546, '\ub10b'}, {0x0547, '\ub10c'}, {0x0548, '\ub110'}, {0x0549, '\ub112'}, {0x054a, '\ub113'}, {0x054b, '\ub118'}, {0x054c, '\ub119'}, {0x054d, '\ub11b'}, {0x054e, '\ub11c'}, {0x054f, '\ub11d'}, {0x0550, '\ub123'}, {0x0551, '\ub124'}, {0x0552, '\ub125'}, {0x0553, '\ub128'}, {0x0554, '\ub12c'}, {0x0555, '\ub134'}, {0x0556, '\ub135'}, {0x0557, '\ub137'}, {0x0558, '\ub138'}, {0x0559, '\ub139'}, {0x055a, '\ub140'}, {0x055b, '\ub141'}, {0x055c, '\ub144'}, {0x055d, '\ub148'}, {0x055e, '\ub150'}, {0x055f, '\ub151'}, {0x0560, '\ub154'}, {0x0561, '\ub155'}, {0x0562, '\ub158'}, {0x0563, '\ub15c'}, {0x0564, '\ub160'}, {0x0565, '\ub178'}, {0x0566, '\ub179'}, {0x0567, '\ub17c'}, {0x0568, '\ub180'}, {0x0569, '\ub182'}, {0x056a, '\ub188'}, {0x056b, '\ub189'}, {0x056c, '\ub18b'}, {0x056d, '\ub18d'}, {0x056e, '\ub192'}, {0x056f, '\ub193'}, {0x0570, '\ub194'}, {0x0571, '\ub198'}, {0x0572, '\ub19c'}, {0x0573, '\ub1a8'}, {0x0574, '\ub1cc'}, {0x0575, '\ub1d0'}, {0x0576, '\ub1d4'}, {0x0577, '\ub1dc'}, {0x0578, '\ub1dd'}, {0x0579, '\ub1df'}, {0x057a, '\ub1e8'}, {0x057b, '\ub1e9'}, {0x057c, '\ub1ec'}, {0x057d, '\ub1f0'}, {0x057e, '\ub1f9'}, {0x057f, '\ub1fb'}, {0x0580, '\ub1fd'}, {0x0581, '\ub204'}, {0x0582, '\ub205'}, {0x0583, '\ub208'}, {0x0584, '\ub20b'}, {0x0585, '\ub20c'}, {0x0586, '\ub214'}, {0x0587, '\ub215'}, {0x0588, '\ub217'}, {0x0589, '\ub219'}, {0x058a, '\ub220'}, {0x058b, '\ub234'}, {0x058c, '\ub23c'}, {0x058d, '\ub258'}, {0x058e, '\ub25c'}, {0x058f, '\ub260'}, {0x0590, '\ub268'}, {0x0591, '\ub269'}, {0x0592, '\ub274'}, {0x0593, '\ub275'}, {0x0594, '\ub27c'}, {0x0595, '\ub284'}, {0x0596, '\ub285'}, {0x0597, '\ub289'}, {0x0598, '\ub290'}, {0x0599, '\ub291'}, {0x059a, '\ub294'}, {0x059b, '\ub298'}, {0x059c, '\ub299'}, {0x059d, '\ub29a'}, {0x059e, '\ub2a0'}, {0x059f, '\ub2a1'}, {0x05a0, '\ub2a3'}, {0x05a1, '\ub2a5'}, {0x05a2, '\ub2a6'}, {0x05a3, '\ub2aa'}, {0x05a4, '\ub2ac'}, {0x05a5, '\ub2b0'}, {0x05a6, '\ub2b4'}, {0x05a7, '\ub2c8'}, {0x05a8, '\ub2c9'}, {0x05a9, '\ub2cc'}, {0x05aa, '\ub2d0'}, {0x05ab, '\ub2d2'}, {0x05ac, '\ub2d8'}, {0x05ad, '\ub2d9'}, {0x05ae, '\ub2db'}, {0x05af, '\ub2dd'}, {0x05b0, '\ub2e2'}, {0x05b1, '\ub2e4'}, {0x05b2, '\ub2e5'}, {0x05b3, '\ub2e6'}, {0x05b4, '\ub2e8'}, {0x05b5, '\ub2eb'}, {0x05b6, '\ub2ec'}, {0x05b7, '\ub2ed'}, {0x05b8, '\ub2ee'}, {0x05b9, '\ub2ef'}, {0x05ba, '\ub2f3'}, {0x05bb, '\ub2f4'}, {0x05bc, '\ub2f5'}, {0x05bd, '\ub2f7'}, {0x05be, '\ub2f8'}, {0x05bf, '\ub2f9'}, {0x05c0, '\ub2fa'}, {0x05c1, '\ub2fb'}, {0x05c2, '\ub2ff'}, {0x05c3, '\ub300'}, {0x05c4, '\ub301'}, {0x05c5, '\ub304'}, {0x05c6, '\ub308'}, {0x05c7, '\ub310'}, {0x05c8, '\ub311'}, {0x05c9, '\ub313'}, {0x05ca, '\ub314'}, {0x05cb, '\ub315'}, {0x05cc, '\ub31c'}, {0x05cd, '\ub354'}, {0x05ce, '\ub355'}, {0x05cf, '\ub356'}, {0x05d0, '\ub358'}, {0x05d1, '\ub35b'}, {0x05d2, '\ub35c'}, {0x05d3, '\ub35e'}, {0x05d4, '\ub35f'}, {0x05d5, '\ub364'}, {0x05d6, '\ub365'}, {0x05d7, '\ub367'}, {0x05d8, '\ub369'}, {0x05d9, '\ub36b'}, {0x05da, '\ub36e'}, {0x05db, '\ub370'}, {0x05dc, '\ub371'}, {0x05dd, '\ub374'}, {0x05de, '\ub378'}, {0x05df, '\ub380'}, {0x05e0, '\ub381'}, {0x05e1, '\ub383'}, {0x05e2, '\ub384'}, {0x05e3, '\ub385'}, {0x05e4, '\ub38c'}, {0x05e5, '\ub390'}, {0x05e6, '\ub394'}, {0x05e7, '\ub3a0'}, {0x05e8, '\ub3a1'}, {0x05e9, '\ub3a8'}, {0x05ea, '\ub3ac'}, {0x05eb, '\ub3c4'}, {0x05ec, '\ub3c5'}, {0x05ed, '\ub3c8'}, {0x05ee, '\ub3cb'}, {0x05ef, '\ub3cc'}, {0x05f0, '\ub3ce'}, {0x05f1, '\ub3d0'}, {0x05f2, '\ub3d4'}, {0x05f3, '\ub3d5'}, {0x05f4, '\ub3d7'}, {0x05f5, '\ub3d9'}, {0x05f6, '\ub3db'}, {0x05f7, '\ub3dd'}, {0x05f8, '\ub3e0'}, {0x05f9, '\ub3e4'}, {0x05fa, '\ub3e8'}, {0x05fb, '\ub3fc'}, {0x05fc, '\ub410'}, {0x05fd, '\ub418'}, {0x05fe, '\ub41c'}, {0x05ff, '\ub420'}, {0x0600, '\ub428'}, {0x0601, '\ub429'}, {0x0602, '\ub42b'}, {0x0603, '\ub434'}, {0x0604, '\ub450'}, {0x0605, '\ub451'}, {0x0606, '\ub454'}, {0x0607, '\ub458'}, {0x0608, '\ub460'}, {0x0609, '\ub461'}, {0x060a, '\ub463'}, {0x060b, '\ub465'}, {0x060c, '\ub46c'}, {0x060d, '\ub480'}, {0x060e, '\ub488'}, {0x060f, '\ub49d'}, {0x0610, '\ub4a4'}, {0x0611, '\ub4a8'}, {0x0612, '\ub4ac'}, {0x0613, '\ub4b5'}, {0x0614, '\ub4b7'}, {0x0615, '\ub4b9'}, {0x0616, '\ub4c0'}, {0x0617, '\ub4c4'}, {0x0618, '\ub4c8'}, {0x0619, '\ub4d0'}, {0x061a, '\ub4d5'}, {0x061b, '\ub4dc'}, {0x061c, '\ub4dd'}, {0x061d, '\ub4e0'}, {0x061e, '\ub4e3'}, {0x061f, '\ub4e4'}, {0x0620, '\ub4e6'}, {0x0621, '\ub4ec'}, {0x0622, '\ub4ed'}, {0x0623, '\ub4ef'}, {0x0624, '\ub4f1'}, {0x0625, '\ub4f8'}, {0x0626, '\ub514'}, {0x0627, '\ub515'}, {0x0628, '\ub518'}, {0x0629, '\ub51b'}, {0x062a, '\ub51c'}, {0x062b, '\ub524'}, {0x062c, '\ub525'}, {0x062d, '\ub527'}, {0x062e, '\ub528'}, {0x062f, '\ub529'}, {0x0630, '\ub52a'}, {0x0631, '\ub530'}, {0x0632, '\ub531'}, {0x0633, '\ub534'}, {0x0634, '\ub538'}, {0x0635, '\ub540'}, {0x0636, '\ub541'}, {0x0637, '\ub543'}, {0x0638, '\ub544'}, {0x0639, '\ub545'}, {0x063a, '\ub54b'}, {0x063b, '\ub54c'}, {0x063c, '\ub54d'}, {0x063d, '\ub550'}, {0x063e, '\ub554'}, {0x063f, '\ub55c'}, {0x0640, '\ub55d'}, {0x0641, '\ub55f'}, {0x0642, '\ub560'}, {0x0643, '\ub561'}, {0x0644, '\ub5a0'}, {0x0645, '\ub5a1'}, {0x0646, '\ub5a4'}, {0x0647, '\ub5a8'}, {0x0648, '\ub5aa'}, {0x0649, '\ub5ab'}, {0x064a, '\ub5b0'}, {0x064b, '\ub5b1'}, {0x064c, '\ub5b3'}, {0x064d, '\ub5b4'}, {0x064e, '\ub5b5'}, {0x064f, '\ub5bb'}, {0x0650, '\ub5bc'}, {0x0651, '\ub5bd'}, {0x0652, '\ub5c0'}, {0x0653, '\ub5c4'}, {0x0654, '\ub5cc'}, {0x0655, '\ub5cd'}, {0x0656, '\ub5cf'}, {0x0657, '\ub5d0'}, {0x0658, '\ub5d1'}, {0x0659, '\ub5d8'}, {0x065a, '\ub5ec'}, {0x065b, '\ub610'}, {0x065c, '\ub611'}, {0x065d, '\ub614'}, {0x065e, '\ub618'}, {0x065f, '\ub625'}, {0x0660, '\ub62c'}, {0x0661, '\ub634'}, {0x0662, '\ub648'}, {0x0663, '\ub664'}, {0x0664, '\ub668'}, {0x0665, '\ub69c'}, {0x0666, '\ub69d'}, {0x0667, '\ub6a0'}, {0x0668, '\ub6a4'}, {0x0669, '\ub6ab'}, {0x066a, '\ub6ac'}, {0x066b, '\ub6b1'}, {0x066c, '\ub6d4'}, {0x066d, '\ub6f0'}, {0x066e, '\ub6f4'}, {0x066f, '\ub6f8'}, {0x0670, '\ub700'}, {0x0671, '\ub701'}, {0x0672, '\ub705'}, {0x0673, '\ub728'}, {0x0674, '\ub729'}, {0x0675, '\ub72c'}, {0x0676, '\ub72f'}, {0x0677, '\ub730'}, {0x0678, '\ub738'}, {0x0679, '\ub739'}, {0x067a, '\ub73b'}, {0x067b, '\ub744'}, {0x067c, '\ub748'}, {0x067d, '\ub74c'}, {0x067e, '\ub754'}, {0x067f, '\ub755'}, {0x0680, '\ub760'}, {0x0681, '\ub764'}, {0x0682, '\ub768'}, {0x0683, '\ub770'}, {0x0684, '\ub771'}, {0x0685, '\ub773'}, {0x0686, '\ub775'}, {0x0687, '\ub77c'}, {0x0688, '\ub77d'}, {0x0689, '\ub780'}, {0x068a, '\ub784'}, {0x068b, '\ub78c'}, {0x068c, '\ub78d'}, {0x068d, '\ub78f'}, {0x068e, '\ub790'}, {0x068f, '\ub791'}, {0x0690, '\ub792'}, {0x0691, '\ub796'}, {0x0692, '\ub797'}, {0x0693, '\ub798'}, {0x0694, '\ub799'}, {0x0695, '\ub79c'}, {0x0696, '\ub7a0'}, {0x0697, '\ub7a8'}, {0x0698, '\ub7a9'}, {0x0699, '\ub7ab'}, {0x069a, '\ub7ac'}, {0x069b, '\ub7ad'}, {0x069c, '\ub7b4'}, {0x069d, '\ub7b5'}, {0x069e, '\ub7b8'}, {0x069f, '\ub7c7'}, {0x06a0, '\ub7c9'}, {0x06a1, '\ub7ec'}, {0x06a2, '\ub7ed'}, {0x06a3, '\ub7f0'}, {0x06a4, '\ub7f4'}, {0x06a5, '\ub7fc'}, {0x06a6, '\ub7fd'}, {0x06a7, '\ub7ff'}, {0x06a8, '\ub800'}, {0x06a9, '\ub801'}, {0x06aa, '\ub807'}, {0x06ab, '\ub808'}, {0x06ac, '\ub809'}, {0x06ad, '\ub80c'}, {0x06ae, '\ub810'}, {0x06af, '\ub818'}, {0x06b0, '\ub819'}, {0x06b1, '\ub81b'}, {0x06b2, '\ub81d'}, {0x06b3, '\ub824'}, {0x06b4, '\ub825'}, {0x06b5, '\ub828'}, {0x06b6, '\ub82c'}, {0x06b7, '\ub834'}, {0x06b8, '\ub835'}, {0x06b9, '\ub837'}, {0x06ba, '\ub838'}, {0x06bb, '\ub839'}, {0x06bc, '\ub840'}, {0x06bd, '\ub844'}, {0x06be, '\ub851'}, {0x06bf, '\ub853'}, {0x06c0, '\ub85c'}, {0x06c1, '\ub85d'}, {0x06c2, '\ub860'}, {0x06c3, '\ub864'}, {0x06c4, '\ub86c'}, {0x06c5, '\ub86d'}, {0x06c6, '\ub86f'}, {0x06c7, '\ub871'}, {0x06c8, '\ub878'}, {0x06c9, '\ub87c'}, {0x06ca, '\ub88d'}, {0x06cb, '\ub8a8'}, {0x06cc, '\ub8b0'}, {0x06cd, '\ub8b4'}, {0x06ce, '\ub8b8'}, {0x06cf, '\ub8c0'}, {0x06d0, '\ub8c1'}, {0x06d1, '\ub8c3'}, {0x06d2, '\ub8c5'}, {0x06d3, '\ub8cc'}, {0x06d4, '\ub8d0'}, {0x06d5, '\ub8d4'}, {0x06d6, '\ub8dd'}, {0x06d7, '\ub8df'}, {0x06d8, '\ub8e1'}, {0x06d9, '\ub8e8'}, {0x06da, '\ub8e9'}, {0x06db, '\ub8ec'}, {0x06dc, '\ub8f0'}, {0x06dd, '\ub8f8'}, {0x06de, '\ub8f9'}, {0x06df, '\ub8fb'}, {0x06e0, '\ub8fd'}, {0x06e1, '\ub904'}, {0x06e2, '\ub918'}, {0x06e3, '\ub920'}, {0x06e4, '\ub93c'}, {0x06e5, '\ub93d'}, {0x06e6, '\ub940'}, {0x06e7, '\ub944'}, {0x06e8, '\ub94c'}, {0x06e9, '\ub94f'}, {0x06ea, '\ub951'}, {0x06eb, '\ub958'}, {0x06ec, '\ub959'}, {0x06ed, '\ub95c'}, {0x06ee, '\ub960'}, {0x06ef, '\ub968'}, {0x06f0, '\ub969'}, {0x06f1, '\ub96b'}, {0x06f2, '\ub96d'}, {0x06f3, '\ub974'}, {0x06f4, '\ub975'}, {0x06f5, '\ub978'}, {0x06f6, '\ub97c'}, {0x06f7, '\ub984'}, {0x06f8, '\ub985'}, {0x06f9, '\ub987'}, {0x06fa, '\ub989'}, {0x06fb, '\ub98a'}, {0x06fc, '\ub98d'}, {0x06fd, '\ub98e'}, {0x06fe, '\ub9ac'}, {0x06ff, '\ub9ad'}, {0x0700, '\ub9b0'}, {0x0701, '\ub9b4'}, {0x0702, '\ub9bc'}, {0x0703, '\ub9bd'}, {0x0704, '\ub9bf'}, {0x0705, '\ub9c1'}, {0x0706, '\ub9c8'}, {0x0707, '\ub9c9'}, {0x0708, '\ub9cc'}, {0x0709, '\ub9ce'}, {0x070a, '\ub9cf'}, {0x070b, '\ub9d0'}, {0x070c, '\ub9d1'}, {0x070d, '\ub9d2'}, {0x070e, '\ub9d8'}, {0x070f, '\ub9d9'}, {0x0710, '\ub9db'}, {0x0711, '\ub9dd'}, {0x0712, '\ub9de'}, {0x0713, '\ub9e1'}, {0x0714, '\ub9e3'}, {0x0715, '\ub9e4'}, {0x0716, '\ub9e5'}, {0x0717, '\ub9e8'}, {0x0718, '\ub9ec'}, {0x0719, '\ub9f4'}, {0x071a, '\ub9f5'}, {0x071b, '\ub9f7'}, {0x071c, '\ub9f8'}, {0x071d, '\ub9f9'}, {0x071e, '\ub9fa'}, {0x071f, '\uba00'}, {0x0720, '\uba01'}, {0x0721, '\uba08'}, {0x0722, '\uba15'}, {0x0723, '\uba38'}, {0x0724, '\uba39'}, {0x0725, '\uba3c'}, {0x0726, '\uba40'}, {0x0727, '\uba42'}, {0x0728, '\uba48'}, {0x0729, '\uba49'}, {0x072a, '\uba4b'}, {0x072b, '\uba4d'}, {0x072c, '\uba4e'}, {0x072d, '\uba53'}, {0x072e, '\uba54'}, {0x072f, '\uba55'}, {0x0730, '\uba58'}, {0x0731, '\uba5c'}, {0x0732, '\uba64'}, {0x0733, '\uba65'}, {0x0734, '\uba67'}, {0x0735, '\uba68'}, {0x0736, '\uba69'}, {0x0737, '\uba70'}, {0x0738, '\uba71'}, {0x0739, '\uba74'}, {0x073a, '\uba78'}, {0x073b, '\uba83'}, {0x073c, '\uba84'}, {0x073d, '\uba85'}, {0x073e, '\uba87'}, {0x073f, '\uba8c'}, {0x0740, '\ubaa8'}, {0x0741, '\ubaa9'}, {0x0742, '\ubaab'}, {0x0743, '\ubaac'}, {0x0744, '\ubab0'}, {0x0745, '\ubab2'}, {0x0746, '\ubab8'}, {0x0747, '\ubab9'}, {0x0748, '\ubabb'}, {0x0749, '\ubabd'}, {0x074a, '\ubac4'}, {0x074b, '\ubac8'}, {0x074c, '\ubad8'}, {0x074d, '\ubad9'}, {0x074e, '\ubafc'}, {0x074f, '\ubb00'}, {0x0750, '\ubb04'}, {0x0751, '\ubb0d'}, {0x0752, '\ubb0f'}, {0x0753, '\ubb11'}, {0x0754, '\ubb18'}, {0x0755, '\ubb1c'}, {0x0756, '\ubb20'}, {0x0757, '\ubb29'}, {0x0758, '\ubb2b'}, {0x0759, '\ubb34'}, {0x075a, '\ubb35'}, {0x075b, '\ubb36'}, {0x075c, '\ubb38'}, {0x075d, '\ubb3b'}, {0x075e, '\ubb3c'}, {0x075f, '\ubb3d'}, {0x0760, '\ubb3e'}, {0x0761, '\ubb44'}, {0x0762, '\ubb45'}, {0x0763, '\ubb47'}, {0x0764, '\ubb49'}, {0x0765, '\ubb4d'}, {0x0766, '\ubb4f'}, {0x0767, '\ubb50'}, {0x0768, '\ubb54'}, {0x0769, '\ubb58'}, {0x076a, '\ubb61'}, {0x076b, '\ubb63'}, {0x076c, '\ubb6c'}, {0x076d, '\ubb88'}, {0x076e, '\ubb8c'}, {0x076f, '\ubb90'}, {0x0770, '\ubba4'}, {0x0771, '\ubba8'}, {0x0772, '\ubbac'}, {0x0773, '\ubbb4'}, {0x0774, '\ubbb7'}, {0x0775, '\ubbc0'}, {0x0776, '\ubbc4'}, {0x0777, '\ubbc8'}, {0x0778, '\ubbd0'}, {0x0779, '\ubbd3'}, {0x077a, '\ubbf8'}, {0x077b, '\ubbf9'}, {0x077c, '\ubbfc'}, {0x077d, '\ubbff'}, {0x077e, '\ubc00'}, {0x077f, '\ubc02'}, {0x0780, '\ubc08'}, {0x0781, '\ubc09'}, {0x0782, '\ubc0b'}, {0x0783, '\ubc0c'}, {0x0784, '\ubc0d'}, {0x0785, '\ubc0f'}, {0x0786, '\ubc11'}, {0x0787, '\ubc14'}, {0x0788, '\ubc15'}, {0x0789, '\ubc16'}, {0x078a, '\ubc17'}, {0x078b, '\ubc18'}, {0x078c, '\ubc1b'}, {0x078d, '\ubc1c'}, {0x078e, '\ubc1d'}, {0x078f, '\ubc1e'}, {0x0790, '\ubc1f'}, {0x0791, '\ubc24'}, {0x0792, '\ubc25'}, {0x0793, '\ubc27'}, {0x0794, '\ubc29'}, {0x0795, '\ubc2d'}, {0x0796, '\ubc30'}, {0x0797, '\ubc31'}, {0x0798, '\ubc34'}, {0x0799, '\ubc38'}, {0x079a, '\ubc40'}, {0x079b, '\ubc41'}, {0x079c, '\ubc43'}, {0x079d, '\ubc44'}, {0x079e, '\ubc45'}, {0x079f, '\ubc49'}, {0x07a0, '\ubc4c'}, {0x07a1, '\ubc4d'}, {0x07a2, '\ubc50'}, {0x07a3, '\ubc5d'}, {0x07a4, '\ubc84'}, {0x07a5, '\ubc85'}, {0x07a6, '\ubc88'}, {0x07a7, '\ubc8b'}, {0x07a8, '\ubc8c'}, {0x07a9, '\ubc8e'}, {0x07aa, '\ubc94'}, {0x07ab, '\ubc95'}, {0x07ac, '\ubc97'}, {0x07ad, '\ubc99'}, {0x07ae, '\ubc9a'}, {0x07af, '\ubca0'}, {0x07b0, '\ubca1'}, {0x07b1, '\ubca4'}, {0x07b2, '\ubca7'}, {0x07b3, '\ubca8'}, {0x07b4, '\ubcb0'}, {0x07b5, '\ubcb1'}, {0x07b6, '\ubcb3'}, {0x07b7, '\ubcb4'}, {0x07b8, '\ubcb5'}, {0x07b9, '\ubcbc'}, {0x07ba, '\ubcbd'}, {0x07bb, '\ubcc0'}, {0x07bc, '\ubcc4'}, {0x07bd, '\ubccd'}, {0x07be, '\ubccf'}, {0x07bf, '\ubcd0'}, {0x07c0, '\ubcd1'}, {0x07c1, '\ubcd5'}, {0x07c2, '\ubcd8'}, {0x07c3, '\ubcdc'}, {0x07c4, '\ubcf4'}, {0x07c5, '\ubcf5'}, {0x07c6, '\ubcf6'}, {0x07c7, '\ubcf8'}, {0x07c8, '\ubcfc'}, {0x07c9, '\ubd04'}, {0x07ca, '\ubd05'}, {0x07cb, '\ubd07'}, {0x07cc, '\ubd09'}, {0x07cd, '\ubd10'}, {0x07ce, '\ubd14'}, {0x07cf, '\ubd24'}, {0x07d0, '\ubd2c'}, {0x07d1, '\ubd40'}, {0x07d2, '\ubd48'}, {0x07d3, '\ubd49'}, {0x07d4, '\ubd4c'}, {0x07d5, '\ubd50'}, {0x07d6, '\ubd58'}, {0x07d7, '\ubd59'}, {0x07d8, '\ubd64'}, {0x07d9, '\ubd68'}, {0x07da, '\ubd80'}, {0x07db, '\ubd81'}, {0x07dc, '\ubd84'}, {0x07dd, '\ubd87'}, {0x07de, '\ubd88'}, {0x07df, '\ubd89'}, {0x07e0, '\ubd8a'}, {0x07e1, '\ubd90'}, {0x07e2, '\ubd91'}, {0x07e3, '\ubd93'}, {0x07e4, '\ubd95'}, {0x07e5, '\ubd99'}, {0x07e6, '\ubd9a'}, {0x07e7, '\ubd9c'}, {0x07e8, '\ubda4'}, {0x07e9, '\ubdb0'}, {0x07ea, '\ubdb8'}, {0x07eb, '\ubdd4'}, {0x07ec, '\ubdd5'}, {0x07ed, '\ubdd8'}, {0x07ee, '\ubddc'}, {0x07ef, '\ubde9'}, {0x07f0, '\ubdf0'}, {0x07f1, '\ubdf4'}, {0x07f2, '\ubdf8'}, {0x07f3, '\ube00'}, {0x07f4, '\ube03'}, {0x07f5, '\ube05'}, {0x07f6, '\ube0c'}, {0x07f7, '\ube0d'}, {0x07f8, '\ube10'}, {0x07f9, '\ube14'}, {0x07fa, '\ube1c'}, {0x07fb, '\ube1d'}, {0x07fc, '\ube1f'}, {0x07fd, '\ube44'}, {0x07fe, '\ube45'}, {0x07ff, '\ube48'}, {0x0800, '\ube4c'}, {0x0801, '\ube4e'}, {0x0802, '\ube54'}, {0x0803, '\ube55'}, {0x0804, '\ube57'}, {0x0805, '\ube59'}, {0x0806, '\ube5a'}, {0x0807, '\ube5b'}, {0x0808, '\ube60'}, {0x0809, '\ube61'}, {0x080a, '\ube64'}, {0x080b, '\ube68'}, {0x080c, '\ube6a'}, {0x080d, '\ube70'}, {0x080e, '\ube71'}, {0x080f, '\ube73'}, {0x0810, '\ube74'}, {0x0811, '\ube75'}, {0x0812, '\ube7b'}, {0x0813, '\ube7c'}, {0x0814, '\ube7d'}, {0x0815, '\ube80'}, {0x0816, '\ube84'}, {0x0817, '\ube8c'}, {0x0818, '\ube8d'}, {0x0819, '\ube8f'}, {0x081a, '\ube90'}, {0x081b, '\ube91'}, {0x081c, '\ube98'}, {0x081d, '\ube99'}, {0x081e, '\ubea8'}, {0x081f, '\ubed0'}, {0x0820, '\ubed1'}, {0x0821, '\ubed4'}, {0x0822, '\ubed7'}, {0x0823, '\ubed8'}, {0x0824, '\ubee0'}, {0x0825, '\ubee3'}, {0x0826, '\ubee4'}, {0x0827, '\ubee5'}, {0x0828, '\ubeec'}, {0x0829, '\ubf01'}, {0x082a, '\ubf08'}, {0x082b, '\ubf09'}, {0x082c, '\ubf18'}, {0x082d, '\ubf19'}, {0x082e, '\ubf1b'}, {0x082f, '\ubf1c'}, {0x0830, '\ubf1d'}, {0x0831, '\ubf40'}, {0x0832, '\ubf41'}, {0x0833, '\ubf44'}, {0x0834, '\ubf48'}, {0x0835, '\ubf50'}, {0x0836, '\ubf51'}, {0x0837, '\ubf55'}, {0x0838, '\ubf94'}, {0x0839, '\ubfb0'}, {0x083a, '\ubfc5'}, {0x083b, '\ubfcc'}, {0x083c, '\ubfcd'}, {0x083d, '\ubfd0'}, {0x083e, '\ubfd4'}, {0x083f, '\ubfdc'}, {0x0840, '\ubfdf'}, {0x0841, '\ubfe1'}, {0x0842, '\uc03c'}, {0x0843, '\uc051'}, {0x0844, '\uc058'}, {0x0845, '\uc05c'}, {0x0846, '\uc060'}, {0x0847, '\uc068'}, {0x0848, '\uc069'}, {0x0849, '\uc090'}, {0x084a, '\uc091'}, {0x084b, '\uc094'}, {0x084c, '\uc098'}, {0x084d, '\uc0a0'}, {0x084e, '\uc0a1'}, {0x084f, '\uc0a3'}, {0x0850, '\uc0a5'}, {0x0851, '\uc0ac'}, {0x0852, '\uc0ad'}, {0x0853, '\uc0af'}, {0x0854, '\uc0b0'}, {0x0855, '\uc0b3'}, {0x0856, '\uc0b4'}, {0x0857, '\uc0b5'}, {0x0858, '\uc0b6'}, {0x0859, '\uc0bc'}, {0x085a, '\uc0bd'}, {0x085b, '\uc0bf'}, {0x085c, '\uc0c0'}, {0x085d, '\uc0c1'}, {0x085e, '\uc0c5'}, {0x085f, '\uc0c8'}, {0x0860, '\uc0c9'}, {0x0861, '\uc0cc'}, {0x0862, '\uc0d0'}, {0x0863, '\uc0d8'}, {0x0864, '\uc0d9'}, {0x0865, '\uc0db'}, {0x0866, '\uc0dc'}, {0x0867, '\uc0dd'}, {0x0868, '\uc0e4'}, {0x0869, '\uc0e5'}, {0x086a, '\uc0e8'}, {0x086b, '\uc0ec'}, {0x086c, '\uc0f4'}, {0x086d, '\uc0f5'}, {0x086e, '\uc0f7'}, {0x086f, '\uc0f9'}, {0x0870, '\uc100'}, {0x0871, '\uc104'}, {0x0872, '\uc108'}, {0x0873, '\uc110'}, {0x0874, '\uc115'}, {0x0875, '\uc11c'}, {0x0876, '\uc11d'}, {0x0877, '\uc11e'}, {0x0878, '\uc11f'}, {0x0879, '\uc120'}, {0x087a, '\uc123'}, {0x087b, '\uc124'}, {0x087c, '\uc126'}, {0x087d, '\uc127'}, {0x087e, '\uc12c'}, {0x087f, '\uc12d'}, {0x0880, '\uc12f'}, {0x0881, '\uc130'}, {0x0882, '\uc131'}, {0x0883, '\uc136'}, {0x0884, '\uc138'}, {0x0885, '\uc139'}, {0x0886, '\uc13c'}, {0x0887, '\uc140'}, {0x0888, '\uc148'}, {0x0889, '\uc149'}, {0x088a, '\uc14b'}, {0x088b, '\uc14c'}, {0x088c, '\uc14d'}, {0x088d, '\uc154'}, {0x088e, '\uc155'}, {0x088f, '\uc158'}, {0x0890, '\uc15c'}, {0x0891, '\uc164'}, {0x0892, '\uc165'}, {0x0893, '\uc167'}, {0x0894, '\uc168'}, {0x0895, '\uc169'}, {0x0896, '\uc170'}, {0x0897, '\uc174'}, {0x0898, '\uc178'}, {0x0899, '\uc185'}, {0x089a, '\uc18c'}, {0x089b, '\uc18d'}, {0x089c, '\uc18e'}, {0x089d, '\uc190'}, {0x089e, '\uc194'}, {0x089f, '\uc196'}, {0x08a0, '\uc19c'}, {0x08a1, '\uc19d'}, {0x08a2, '\uc19f'}, {0x08a3, '\uc1a1'}, {0x08a4, '\uc1a5'}, {0x08a5, '\uc1a8'}, {0x08a6, '\uc1a9'}, {0x08a7, '\uc1ac'}, {0x08a8, '\uc1b0'}, {0x08a9, '\uc1bd'}, {0x08aa, '\uc1c4'}, {0x08ab, '\uc1c8'}, {0x08ac, '\uc1cc'}, {0x08ad, '\uc1d4'}, {0x08ae, '\uc1d7'}, {0x08af, '\uc1d8'}, {0x08b0, '\uc1e0'}, {0x08b1, '\uc1e4'}, {0x08b2, '\uc1e8'}, {0x08b3, '\uc1f0'}, {0x08b4, '\uc1f1'}, {0x08b5, '\uc1f3'}, {0x08b6, '\uc1fc'}, {0x08b7, '\uc1fd'}, {0x08b8, '\uc200'}, {0x08b9, '\uc204'}, {0x08ba, '\uc20c'}, {0x08bb, '\uc20d'}, {0x08bc, '\uc20f'}, {0x08bd, '\uc211'}, {0x08be, '\uc218'}, {0x08bf, '\uc219'}, {0x08c0, '\uc21c'}, {0x08c1, '\uc21f'}, {0x08c2, '\uc220'}, {0x08c3, '\uc228'}, {0x08c4, '\uc229'}, {0x08c5, '\uc22b'}, {0x08c6, '\uc22d'}, {0x08c7, '\uc22f'}, {0x08c8, '\uc231'}, {0x08c9, '\uc232'}, {0x08ca, '\uc234'}, {0x08cb, '\uc248'}, {0x08cc, '\uc250'}, {0x08cd, '\uc251'}, {0x08ce, '\uc254'}, {0x08cf, '\uc258'}, {0x08d0, '\uc260'}, {0x08d1, '\uc265'}, {0x08d2, '\uc26c'}, {0x08d3, '\uc26d'}, {0x08d4, '\uc270'}, {0x08d5, '\uc274'}, {0x08d6, '\uc27c'}, {0x08d7, '\uc27d'}, {0x08d8, '\uc27f'}, {0x08d9, '\uc281'}, {0x08da, '\uc288'}, {0x08db, '\uc289'}, {0x08dc, '\uc290'}, {0x08dd, '\uc298'}, {0x08de, '\uc29b'}, {0x08df, '\uc29d'}, {0x08e0, '\uc2a4'}, {0x08e1, '\uc2a5'}, {0x08e2, '\uc2a8'}, {0x08e3, '\uc2ac'}, {0x08e4, '\uc2ad'}, {0x08e5, '\uc2b4'}, {0x08e6, '\uc2b5'}, {0x08e7, '\uc2b7'}, {0x08e8, '\uc2b9'}, {0x08e9, '\uc2dc'}, {0x08ea, '\uc2dd'}, {0x08eb, '\uc2e0'}, {0x08ec, '\uc2e3'}, {0x08ed, '\uc2e4'}, {0x08ee, '\uc2eb'}, {0x08ef, '\uc2ec'}, {0x08f0, '\uc2ed'}, {0x08f1, '\uc2ef'}, {0x08f2, '\uc2f1'}, {0x08f3, '\uc2f6'}, {0x08f4, '\uc2f8'}, {0x08f5, '\uc2f9'}, {0x08f6, '\uc2fb'}, {0x08f7, '\uc2fc'}, {0x08f8, '\uc300'}, {0x08f9, '\uc308'}, {0x08fa, '\uc309'}, {0x08fb, '\uc30c'}, {0x08fc, '\uc30d'}, {0x08fd, '\uc313'}, {0x08fe, '\uc314'}, {0x08ff, '\uc315'}, {0x0900, '\uc318'}, {0x0901, '\uc31c'}, {0x0902, '\uc324'}, {0x0903, '\uc325'}, {0x0904, '\uc328'}, {0x0905, '\uc329'}, {0x0906, '\uc345'}, {0x0907, '\uc368'}, {0x0908, '\uc369'}, {0x0909, '\uc36c'}, {0x090a, '\uc370'}, {0x090b, '\uc372'}, {0x090c, '\uc378'}, {0x090d, '\uc379'}, {0x090e, '\uc37c'}, {0x090f, '\uc37d'}, {0x0910, '\uc384'}, {0x0911, '\uc388'}, {0x0912, '\uc38c'}, {0x0913, '\uc3c0'}, {0x0914, '\uc3d8'}, {0x0915, '\uc3d9'}, {0x0916, '\uc3dc'}, {0x0917, '\uc3df'}, {0x0918, '\uc3e0'}, {0x0919, '\uc3e2'}, {0x091a, '\uc3e8'}, {0x091b, '\uc3e9'}, {0x091c, '\uc3ed'}, {0x091d, '\uc3f4'}, {0x091e, '\uc3f5'}, {0x091f, '\uc3f8'}, {0x0920, '\uc408'}, {0x0921, '\uc410'}, {0x0922, '\uc424'}, {0x0923, '\uc42c'}, {0x0924, '\uc430'}, {0x0925, '\uc434'}, {0x0926, '\uc43c'}, {0x0927, '\uc43d'}, {0x0928, '\uc448'}, {0x0929, '\uc464'}, {0x092a, '\uc465'}, {0x092b, '\uc468'}, {0x092c, '\uc46c'}, {0x092d, '\uc474'}, {0x092e, '\uc475'}, {0x092f, '\uc479'}, {0x0930, '\uc480'}, {0x0931, '\uc494'}, {0x0932, '\uc49c'}, {0x0933, '\uc4b8'}, {0x0934, '\uc4bc'}, {0x0935, '\uc4e9'}, {0x0936, '\uc4f0'}, {0x0937, '\uc4f1'}, {0x0938, '\uc4f4'}, {0x0939, '\uc4f8'}, {0x093a, '\uc4fa'}, {0x093b, '\uc4ff'}, {0x093c, '\uc500'}, {0x093d, '\uc501'}, {0x093e, '\uc50c'}, {0x093f, '\uc510'}, {0x0940, '\uc514'}, {0x0941, '\uc51c'}, {0x0942, '\uc528'}, {0x0943, '\uc529'}, {0x0944, '\uc52c'}, {0x0945, '\uc530'}, {0x0946, '\uc538'}, {0x0947, '\uc539'}, {0x0948, '\uc53b'}, {0x0949, '\uc53d'}, {0x094a, '\uc544'}, {0x094b, '\uc545'}, {0x094c, '\uc548'}, {0x094d, '\uc549'}, {0x094e, '\uc54a'}, {0x094f, '\uc54c'}, {0x0950, '\uc54d'}, {0x0951, '\uc54e'}, {0x0952, '\uc553'}, {0x0953, '\uc554'}, {0x0954, '\uc555'}, {0x0955, '\uc557'}, {0x0956, '\uc558'}, {0x0957, '\uc559'}, {0x0958, '\uc55d'}, {0x0959, '\uc55e'}, {0x095a, '\uc560'}, {0x095b, '\uc561'}, {0x095c, '\uc564'}, {0x095d, '\uc568'}, {0x095e, '\uc570'}, {0x095f, '\uc571'}, {0x0960, '\uc573'}, {0x0961, '\uc574'}, {0x0962, '\uc575'}, {0x0963, '\uc57c'}, {0x0964, '\uc57d'}, {0x0965, '\uc580'}, {0x0966, '\uc584'}, {0x0967, '\uc587'}, {0x0968, '\uc58c'}, {0x0969, '\uc58d'}, {0x096a, '\uc58f'}, {0x096b, '\uc591'}, {0x096c, '\uc595'}, {0x096d, '\uc597'}, {0x096e, '\uc598'}, {0x096f, '\uc59c'}, {0x0970, '\uc5a0'}, {0x0971, '\uc5a9'}, {0x0972, '\uc5b4'}, {0x0973, '\uc5b5'}, {0x0974, '\uc5b8'}, {0x0975, '\uc5b9'}, {0x0976, '\uc5bb'}, {0x0977, '\uc5bc'}, {0x0978, '\uc5bd'}, {0x0979, '\uc5be'}, {0x097a, '\uc5c4'}, {0x097b, '\uc5c5'}, {0x097c, '\uc5c6'}, {0x097d, '\uc5c7'}, {0x097e, '\uc5c8'}, {0x097f, '\uc5c9'}, {0x0980, '\uc5ca'}, {0x0981, '\uc5cc'}, {0x0982, '\uc5ce'}, {0x0983, '\uc5d0'}, {0x0984, '\uc5d1'}, {0x0985, '\uc5d4'}, {0x0986, '\uc5d8'}, {0x0987, '\uc5e0'}, {0x0988, '\uc5e1'}, {0x0989, '\uc5e3'}, {0x098a, '\uc5e5'}, {0x098b, '\uc5ec'}, {0x098c, '\uc5ed'}, {0x098d, '\uc5ee'}, {0x098e, '\uc5f0'}, {0x098f, '\uc5f4'}, {0x0990, '\uc5f6'}, {0x0991, '\uc5f7'}, {0x0992, '\uc5fc'}, {0x0993, '\uc5fd'}, {0x0994, '\uc5fe'}, {0x0995, '\uc5ff'}, {0x0996, '\uc600'}, {0x0997, '\uc601'}, {0x0998, '\uc605'}, {0x0999, '\uc606'}, {0x099a, '\uc607'}, {0x099b, '\uc608'}, {0x099c, '\uc60c'}, {0x099d, '\uc610'}, {0x099e, '\uc618'}, {0x099f, '\uc619'}, {0x09a0, '\uc61b'}, {0x09a1, '\uc61c'}, {0x09a2, '\uc624'}, {0x09a3, '\uc625'}, {0x09a4, '\uc628'}, {0x09a5, '\uc62c'}, {0x09a6, '\uc62d'}, {0x09a7, '\uc62e'}, {0x09a8, '\uc630'}, {0x09a9, '\uc633'}, {0x09aa, '\uc634'}, {0x09ab, '\uc635'}, {0x09ac, '\uc637'}, {0x09ad, '\uc639'}, {0x09ae, '\uc63b'}, {0x09af, '\uc640'}, {0x09b0, '\uc641'}, {0x09b1, '\uc644'}, {0x09b2, '\uc648'}, {0x09b3, '\uc650'}, {0x09b4, '\uc651'}, {0x09b5, '\uc653'}, {0x09b6, '\uc654'}, {0x09b7, '\uc655'}, {0x09b8, '\uc65c'}, {0x09b9, '\uc65d'}, {0x09ba, '\uc660'}, {0x09bb, '\uc66c'}, {0x09bc, '\uc66f'}, {0x09bd, '\uc671'}, {0x09be, '\uc678'}, {0x09bf, '\uc679'}, {0x09c0, '\uc67c'}, {0x09c1, '\uc680'}, {0x09c2, '\uc688'}, {0x09c3, '\uc689'}, {0x09c4, '\uc68b'}, {0x09c5, '\uc68d'}, {0x09c6, '\uc694'}, {0x09c7, '\uc695'}, {0x09c8, '\uc698'}, {0x09c9, '\uc69c'}, {0x09ca, '\uc6a4'}, {0x09cb, '\uc6a5'}, {0x09cc, '\uc6a7'}, {0x09cd, '\uc6a9'}, {0x09ce, '\uc6b0'}, {0x09cf, '\uc6b1'}, {0x09d0, '\uc6b4'}, {0x09d1, '\uc6b8'}, {0x09d2, '\uc6b9'}, {0x09d3, '\uc6ba'}, {0x09d4, '\uc6c0'}, {0x09d5, '\uc6c1'}, {0x09d6, '\uc6c3'}, {0x09d7, '\uc6c5'}, {0x09d8, '\uc6cc'}, {0x09d9, '\uc6cd'}, {0x09da, '\uc6d0'}, {0x09db, '\uc6d4'}, {0x09dc, '\uc6dc'}, {0x09dd, '\uc6dd'}, {0x09de, '\uc6e0'}, {0x09df, '\uc6e1'}, {0x09e0, '\uc6e8'}, {0x09e1, '\uc6e9'}, {0x09e2, '\uc6ec'}, {0x09e3, '\uc6f0'}, {0x09e4, '\uc6f8'}, {0x09e5, '\uc6f9'}, {0x09e6, '\uc6fd'}, {0x09e7, '\uc704'}, {0x09e8, '\uc705'}, {0x09e9, '\uc708'}, {0x09ea, '\uc70c'}, {0x09eb, '\uc714'}, {0x09ec, '\uc715'}, {0x09ed, '\uc717'}, {0x09ee, '\uc719'}, {0x09ef, '\uc720'}, {0x09f0, '\uc721'}, {0x09f1, '\uc724'}, {0x09f2, '\uc728'}, {0x09f3, '\uc730'}, {0x09f4, '\uc731'}, {0x09f5, '\uc733'}, {0x09f6, '\uc735'}, {0x09f7, '\uc737'}, {0x09f8, '\uc73c'}, {0x09f9, '\uc73d'}, {0x09fa, '\uc740'}, {0x09fb, '\uc744'}, {0x09fc, '\uc74a'}, {0x09fd, '\uc74c'}, {0x09fe, '\uc74d'}, {0x09ff, '\uc74f'}, {0x0a00, '\uc751'}, {0x0a01, '\uc752'}, {0x0a02, '\uc753'}, {0x0a03, '\uc754'}, {0x0a04, '\uc755'}, {0x0a05, '\uc756'}, {0x0a06, '\uc757'}, {0x0a07, '\uc758'}, {0x0a08, '\uc75c'}, {0x0a09, '\uc760'}, {0x0a0a, '\uc768'}, {0x0a0b, '\uc76b'}, {0x0a0c, '\uc774'}, {0x0a0d, '\uc775'}, {0x0a0e, '\uc778'}, {0x0a0f, '\uc77c'}, {0x0a10, '\uc77d'}, {0x0a11, '\uc77e'}, {0x0a12, '\uc783'}, {0x0a13, '\uc784'}, {0x0a14, '\uc785'}, {0x0a15, '\uc787'}, {0x0a16, '\uc788'}, {0x0a17, '\uc789'}, {0x0a18, '\uc78a'}, {0x0a19, '\uc78e'}, {0x0a1a, '\uc790'}, {0x0a1b, '\uc791'}, {0x0a1c, '\uc794'}, {0x0a1d, '\uc796'}, {0x0a1e, '\uc797'}, {0x0a1f, '\uc798'}, {0x0a20, '\uc79a'}, {0x0a21, '\uc7a0'}, {0x0a22, '\uc7a1'}, {0x0a23, '\uc7a3'}, {0x0a24, '\uc7a4'}, {0x0a25, '\uc7a5'}, {0x0a26, '\uc7a6'}, {0x0a27, '\uc7ac'}, {0x0a28, '\uc7ad'}, {0x0a29, '\uc7b0'}, {0x0a2a, '\uc7b4'}, {0x0a2b, '\uc7bc'}, {0x0a2c, '\uc7bd'}, {0x0a2d, '\uc7bf'}, {0x0a2e, '\uc7c0'}, {0x0a2f, '\uc7c1'}, {0x0a30, '\uc7c8'}, {0x0a31, '\uc7c9'}, {0x0a32, '\uc7cc'}, {0x0a33, '\uc7ce'}, {0x0a34, '\uc7d0'}, {0x0a35, '\uc7d8'}, {0x0a36, '\uc7dd'}, {0x0a37, '\uc7e4'}, {0x0a38, '\uc7e8'}, {0x0a39, '\uc7ec'}, {0x0a3a, '\uc800'}, {0x0a3b, '\uc801'}, {0x0a3c, '\uc804'}, {0x0a3d, '\uc808'}, {0x0a3e, '\uc80a'}, {0x0a3f, '\uc810'}, {0x0a40, '\uc811'}, {0x0a41, '\uc813'}, {0x0a42, '\uc815'}, {0x0a43, '\uc816'}, {0x0a44, '\uc81c'}, {0x0a45, '\uc81d'}, {0x0a46, '\uc820'}, {0x0a47, '\uc824'}, {0x0a48, '\uc82c'}, {0x0a49, '\uc82d'}, {0x0a4a, '\uc82f'}, {0x0a4b, '\uc831'}, {0x0a4c, '\uc838'}, {0x0a4d, '\uc83c'}, {0x0a4e, '\uc840'}, {0x0a4f, '\uc848'}, {0x0a50, '\uc849'}, {0x0a51, '\uc84c'}, {0x0a52, '\uc84d'}, {0x0a53, '\uc854'}, {0x0a54, '\uc870'}, {0x0a55, '\uc871'}, {0x0a56, '\uc874'}, {0x0a57, '\uc878'}, {0x0a58, '\uc87a'}, {0x0a59, '\uc880'}, {0x0a5a, '\uc881'}, {0x0a5b, '\uc883'}, {0x0a5c, '\uc885'}, {0x0a5d, '\uc886'}, {0x0a5e, '\uc887'}, {0x0a5f, '\uc88b'}, {0x0a60, '\uc88c'}, {0x0a61, '\uc88d'}, {0x0a62, '\uc894'}, {0x0a63, '\uc89d'}, {0x0a64, '\uc89f'}, {0x0a65, '\uc8a1'}, {0x0a66, '\uc8a8'}, {0x0a67, '\uc8bc'}, {0x0a68, '\uc8bd'}, {0x0a69, '\uc8c4'}, {0x0a6a, '\uc8c8'}, {0x0a6b, '\uc8cc'}, {0x0a6c, '\uc8d4'}, {0x0a6d, '\uc8d5'}, {0x0a6e, '\uc8d7'}, {0x0a6f, '\uc8d9'}, {0x0a70, '\uc8e0'}, {0x0a71, '\uc8e1'}, {0x0a72, '\uc8e4'}, {0x0a73, '\uc8f5'}, {0x0a74, '\uc8fc'}, {0x0a75, '\uc8fd'}, {0x0a76, '\uc900'}, {0x0a77, '\uc904'}, {0x0a78, '\uc905'}, {0x0a79, '\uc906'}, {0x0a7a, '\uc90c'}, {0x0a7b, '\uc90d'}, {0x0a7c, '\uc90f'}, {0x0a7d, '\uc911'}, {0x0a7e, '\uc918'}, {0x0a7f, '\uc92c'}, {0x0a80, '\uc934'}, {0x0a81, '\uc950'}, {0x0a82, '\uc951'}, {0x0a83, '\uc954'}, {0x0a84, '\uc958'}, {0x0a85, '\uc960'}, {0x0a86, '\uc961'}, {0x0a87, '\uc963'}, {0x0a88, '\uc96c'}, {0x0a89, '\uc970'}, {0x0a8a, '\uc974'}, {0x0a8b, '\uc97c'}, {0x0a8c, '\uc988'}, {0x0a8d, '\uc989'}, {0x0a8e, '\uc98c'}, {0x0a8f, '\uc990'}, {0x0a90, '\uc998'}, {0x0a91, '\uc999'}, {0x0a92, '\uc99b'}, {0x0a93, '\uc99d'}, {0x0a94, '\uc9c0'}, {0x0a95, '\uc9c1'}, {0x0a96, '\uc9c4'}, {0x0a97, '\uc9c7'}, {0x0a98, '\uc9c8'}, {0x0a99, '\uc9ca'}, {0x0a9a, '\uc9d0'}, {0x0a9b, '\uc9d1'}, {0x0a9c, '\uc9d3'}, {0x0a9d, '\uc9d5'}, {0x0a9e, '\uc9d6'}, {0x0a9f, '\uc9d9'}, {0x0aa0, '\uc9da'}, {0x0aa1, '\uc9dc'}, {0x0aa2, '\uc9dd'}, {0x0aa3, '\uc9e0'}, {0x0aa4, '\uc9e2'}, {0x0aa5, '\uc9e4'}, {0x0aa6, '\uc9e7'}, {0x0aa7, '\uc9ec'}, {0x0aa8, '\uc9ed'}, {0x0aa9, '\uc9ef'}, {0x0aaa, '\uc9f0'}, {0x0aab, '\uc9f1'}, {0x0aac, '\uc9f8'}, {0x0aad, '\uc9f9'}, {0x0aae, '\uc9fc'}, {0x0aaf, '\uca00'}, {0x0ab0, '\uca08'}, {0x0ab1, '\uca09'}, {0x0ab2, '\uca0b'}, {0x0ab3, '\uca0c'}, {0x0ab4, '\uca0d'}, {0x0ab5, '\uca14'}, {0x0ab6, '\uca18'}, {0x0ab7, '\uca29'}, {0x0ab8, '\uca4c'}, {0x0ab9, '\uca4d'}, {0x0aba, '\uca50'}, {0x0abb, '\uca54'}, {0x0abc, '\uca5c'}, {0x0abd, '\uca5d'}, {0x0abe, '\uca5f'}, {0x0abf, '\uca60'}, {0x0ac0, '\uca61'}, {0x0ac1, '\uca68'}, {0x0ac2, '\uca7d'}, {0x0ac3, '\uca84'}, {0x0ac4, '\uca98'}, {0x0ac5, '\ucabc'}, {0x0ac6, '\ucabd'}, {0x0ac7, '\ucac0'}, {0x0ac8, '\ucac4'}, {0x0ac9, '\ucacc'}, {0x0aca, '\ucacd'}, {0x0acb, '\ucacf'}, {0x0acc, '\ucad1'}, {0x0acd, '\ucad3'}, {0x0ace, '\ucad8'}, {0x0acf, '\ucad9'}, {0x0ad0, '\ucae0'}, {0x0ad1, '\ucaec'}, {0x0ad2, '\ucaf4'}, {0x0ad3, '\ucb08'}, {0x0ad4, '\ucb10'}, {0x0ad5, '\ucb14'}, {0x0ad6, '\ucb18'}, {0x0ad7, '\ucb20'}, {0x0ad8, '\ucb21'}, {0x0ad9, '\ucb41'}, {0x0ada, '\ucb48'}, {0x0adb, '\ucb49'}, {0x0adc, '\ucb4c'}, {0x0add, '\ucb50'}, {0x0ade, '\ucb58'}, {0x0adf, '\ucb59'}, {0x0ae0, '\ucb5d'}, {0x0ae1, '\ucb64'}, {0x0ae2, '\ucb78'}, {0x0ae3, '\ucb79'}, {0x0ae4, '\ucb9c'}, {0x0ae5, '\ucbb8'}, {0x0ae6, '\ucbd4'}, {0x0ae7, '\ucbe4'}, {0x0ae8, '\ucbe7'}, {0x0ae9, '\ucbe9'}, {0x0aea, '\ucc0c'}, {0x0aeb, '\ucc0d'}, {0x0aec, '\ucc10'}, {0x0aed, '\ucc14'}, {0x0aee, '\ucc1c'}, {0x0aef, '\ucc1d'}, {0x0af0, '\ucc21'}, {0x0af1, '\ucc22'}, {0x0af2, '\ucc27'}, {0x0af3, '\ucc28'}, {0x0af4, '\ucc29'}, {0x0af5, '\ucc2c'}, {0x0af6, '\ucc2e'}, {0x0af7, '\ucc30'}, {0x0af8, '\ucc38'}, {0x0af9, '\ucc39'}, {0x0afa, '\ucc3b'}, {0x0afb, '\ucc3c'}, {0x0afc, '\ucc3d'}, {0x0afd, '\ucc3e'}, {0x0afe, '\ucc44'}, {0x0aff, '\ucc45'}, {0x0b00, '\ucc48'}, {0x0b01, '\ucc4c'}, {0x0b02, '\ucc54'}, {0x0b03, '\ucc55'}, {0x0b04, '\ucc57'}, {0x0b05, '\ucc58'}, {0x0b06, '\ucc59'}, {0x0b07, '\ucc60'}, {0x0b08, '\ucc64'}, {0x0b09, '\ucc66'}, {0x0b0a, '\ucc68'}, {0x0b0b, '\ucc70'}, {0x0b0c, '\ucc75'}, {0x0b0d, '\ucc98'}, {0x0b0e, '\ucc99'}, {0x0b0f, '\ucc9c'}, {0x0b10, '\ucca0'}, {0x0b11, '\ucca8'}, {0x0b12, '\ucca9'}, {0x0b13, '\uccab'}, {0x0b14, '\uccac'}, {0x0b15, '\uccad'}, {0x0b16, '\uccb4'}, {0x0b17, '\uccb5'}, {0x0b18, '\uccb8'}, {0x0b19, '\uccbc'}, {0x0b1a, '\uccc4'}, {0x0b1b, '\uccc5'}, {0x0b1c, '\uccc7'}, {0x0b1d, '\uccc9'}, {0x0b1e, '\uccd0'}, {0x0b1f, '\uccd4'}, {0x0b20, '\ucce4'}, {0x0b21, '\uccec'}, {0x0b22, '\uccf0'}, {0x0b23, '\ucd01'}, {0x0b24, '\ucd08'}, {0x0b25, '\ucd09'}, {0x0b26, '\ucd0c'}, {0x0b27, '\ucd10'}, {0x0b28, '\ucd18'}, {0x0b29, '\ucd19'}, {0x0b2a, '\ucd1b'}, {0x0b2b, '\ucd1d'}, {0x0b2c, '\ucd24'}, {0x0b2d, '\ucd28'}, {0x0b2e, '\ucd2c'}, {0x0b2f, '\ucd39'}, {0x0b30, '\ucd5c'}, {0x0b31, '\ucd60'}, {0x0b32, '\ucd64'}, {0x0b33, '\ucd6c'}, {0x0b34, '\ucd6d'}, {0x0b35, '\ucd6f'}, {0x0b36, '\ucd71'}, {0x0b37, '\ucd78'}, {0x0b38, '\ucd88'}, {0x0b39, '\ucd94'}, {0x0b3a, '\ucd95'}, {0x0b3b, '\ucd98'}, {0x0b3c, '\ucd9c'}, {0x0b3d, '\ucda4'}, {0x0b3e, '\ucda5'}, {0x0b3f, '\ucda7'}, {0x0b40, '\ucda9'}, {0x0b41, '\ucdb0'}, {0x0b42, '\ucdc4'}, {0x0b43, '\ucdcc'}, {0x0b44, '\ucdd0'}, {0x0b45, '\ucde8'}, {0x0b46, '\ucdec'}, {0x0b47, '\ucdf0'}, {0x0b48, '\ucdf8'}, {0x0b49, '\ucdf9'}, {0x0b4a, '\ucdfb'}, {0x0b4b, '\ucdfd'}, {0x0b4c, '\uce04'}, {0x0b4d, '\uce08'}, {0x0b4e, '\uce0c'}, {0x0b4f, '\uce14'}, {0x0b50, '\uce19'}, {0x0b51, '\uce20'}, {0x0b52, '\uce21'}, {0x0b53, '\uce24'}, {0x0b54, '\uce28'}, {0x0b55, '\uce30'}, {0x0b56, '\uce31'}, {0x0b57, '\uce33'}, {0x0b58, '\uce35'}, {0x0b59, '\uce58'}, {0x0b5a, '\uce59'}, {0x0b5b, '\uce5c'}, {0x0b5c, '\uce5f'}, {0x0b5d, '\uce60'}, {0x0b5e, '\uce61'}, {0x0b5f, '\uce68'}, {0x0b60, '\uce69'}, {0x0b61, '\uce6b'}, {0x0b62, '\uce6d'}, {0x0b63, '\uce74'}, {0x0b64, '\uce75'}, {0x0b65, '\uce78'}, {0x0b66, '\uce7c'}, {0x0b67, '\uce84'}, {0x0b68, '\uce85'}, {0x0b69, '\uce87'}, {0x0b6a, '\uce89'}, {0x0b6b, '\uce90'}, {0x0b6c, '\uce91'}, {0x0b6d, '\uce94'}, {0x0b6e, '\uce98'}, {0x0b6f, '\ucea0'}, {0x0b70, '\ucea1'}, {0x0b71, '\ucea3'}, {0x0b72, '\ucea4'}, {0x0b73, '\ucea5'}, {0x0b74, '\uceac'}, {0x0b75, '\ucead'}, {0x0b76, '\ucec1'}, {0x0b77, '\ucee4'}, {0x0b78, '\ucee5'}, {0x0b79, '\ucee8'}, {0x0b7a, '\uceeb'}, {0x0b7b, '\uceec'}, {0x0b7c, '\ucef4'}, {0x0b7d, '\ucef5'}, {0x0b7e, '\ucef7'}, {0x0b7f, '\ucef8'}, {0x0b80, '\ucef9'}, {0x0b81, '\ucf00'}, {0x0b82, '\ucf01'}, {0x0b83, '\ucf04'}, {0x0b84, '\ucf08'}, {0x0b85, '\ucf10'}, {0x0b86, '\ucf11'}, {0x0b87, '\ucf13'}, {0x0b88, '\ucf15'}, {0x0b89, '\ucf1c'}, {0x0b8a, '\ucf20'}, {0x0b8b, '\ucf24'}, {0x0b8c, '\ucf2c'}, {0x0b8d, '\ucf2d'}, {0x0b8e, '\ucf2f'}, {0x0b8f, '\ucf30'}, {0x0b90, '\ucf31'}, {0x0b91, '\ucf38'}, {0x0b92, '\ucf54'}, {0x0b93, '\ucf55'}, {0x0b94, '\ucf58'}, {0x0b95, '\ucf5c'}, {0x0b96, '\ucf64'}, {0x0b97, '\ucf65'}, {0x0b98, '\ucf67'}, {0x0b99, '\ucf69'}, {0x0b9a, '\ucf70'}, {0x0b9b, '\ucf71'}, {0x0b9c, '\ucf74'}, {0x0b9d, '\ucf78'}, {0x0b9e, '\ucf80'}, {0x0b9f, '\ucf85'}, {0x0ba0, '\ucf8c'}, {0x0ba1, '\ucfa1'}, {0x0ba2, '\ucfa8'}, {0x0ba3, '\ucfb0'}, {0x0ba4, '\ucfc4'}, {0x0ba5, '\ucfe0'}, {0x0ba6, '\ucfe1'}, {0x0ba7, '\ucfe4'}, {0x0ba8, '\ucfe8'}, {0x0ba9, '\ucff0'}, {0x0baa, '\ucff1'}, {0x0bab, '\ucff3'}, {0x0bac, '\ucff5'}, {0x0bad, '\ucffc'}, {0x0bae, '\ud000'}, {0x0baf, '\ud004'}, {0x0bb0, '\ud011'}, {0x0bb1, '\ud018'}, {0x0bb2, '\ud02d'}, {0x0bb3, '\ud034'}, {0x0bb4, '\ud035'}, {0x0bb5, '\ud038'}, {0x0bb6, '\ud03c'}, {0x0bb7, '\ud044'}, {0x0bb8, '\ud045'}, {0x0bb9, '\ud047'}, {0x0bba, '\ud049'}, {0x0bbb, '\ud050'}, {0x0bbc, '\ud054'}, {0x0bbd, '\ud058'}, {0x0bbe, '\ud060'}, {0x0bbf, '\ud06c'}, {0x0bc0, '\ud06d'}, {0x0bc1, '\ud070'}, {0x0bc2, '\ud074'}, {0x0bc3, '\ud07c'}, {0x0bc4, '\ud07d'}, {0x0bc5, '\ud081'}, {0x0bc6, '\ud0a4'}, {0x0bc7, '\ud0a5'}, {0x0bc8, '\ud0a8'}, {0x0bc9, '\ud0ac'}, {0x0bca, '\ud0b4'}, {0x0bcb, '\ud0b5'}, {0x0bcc, '\ud0b7'}, {0x0bcd, '\ud0b9'}, {0x0bce, '\ud0c0'}, {0x0bcf, '\ud0c1'}, {0x0bd0, '\ud0c4'}, {0x0bd1, '\ud0c8'}, {0x0bd2, '\ud0c9'}, {0x0bd3, '\ud0d0'}, {0x0bd4, '\ud0d1'}, {0x0bd5, '\ud0d3'}, {0x0bd6, '\ud0d4'}, {0x0bd7, '\ud0d5'}, {0x0bd8, '\ud0dc'}, {0x0bd9, '\ud0dd'}, {0x0bda, '\ud0e0'}, {0x0bdb, '\ud0e4'}, {0x0bdc, '\ud0ec'}, {0x0bdd, '\ud0ed'}, {0x0bde, '\ud0ef'}, {0x0bdf, '\ud0f0'}, {0x0be0, '\ud0f1'}, {0x0be1, '\ud0f8'}, {0x0be2, '\ud10d'}, {0x0be3, '\ud130'}, {0x0be4, '\ud131'}, {0x0be5, '\ud134'}, {0x0be6, '\ud138'}, {0x0be7, '\ud13a'}, {0x0be8, '\ud140'}, {0x0be9, '\ud141'}, {0x0bea, '\ud143'}, {0x0beb, '\ud144'}, {0x0bec, '\ud145'}, {0x0bed, '\ud14c'}, {0x0bee, '\ud14d'}, {0x0bef, '\ud150'}, {0x0bf0, '\ud154'}, {0x0bf1, '\ud15c'}, {0x0bf2, '\ud15d'}, {0x0bf3, '\ud15f'}, {0x0bf4, '\ud161'}, {0x0bf5, '\ud168'}, {0x0bf6, '\ud16c'}, {0x0bf7, '\ud17c'}, {0x0bf8, '\ud184'}, {0x0bf9, '\ud188'}, {0x0bfa, '\ud1a0'}, {0x0bfb, '\ud1a1'}, {0x0bfc, '\ud1a4'}, {0x0bfd, '\ud1a8'}, {0x0bfe, '\ud1b0'}, {0x0bff, '\ud1b1'}, {0x0c00, '\ud1b3'}, {0x0c01, '\ud1b5'}, {0x0c02, '\ud1ba'}, {0x0c03, '\ud1bc'}, {0x0c04, '\ud1c0'}, {0x0c05, '\ud1d8'}, {0x0c06, '\ud1f4'}, {0x0c07, '\ud1f8'}, {0x0c08, '\ud207'}, {0x0c09, '\ud209'}, {0x0c0a, '\ud210'}, {0x0c0b, '\ud22c'}, {0x0c0c, '\ud22d'}, {0x0c0d, '\ud230'}, {0x0c0e, '\ud234'}, {0x0c0f, '\ud23c'}, {0x0c10, '\ud23d'}, {0x0c11, '\ud23f'}, {0x0c12, '\ud241'}, {0x0c13, '\ud248'}, {0x0c14, '\ud25c'}, {0x0c15, '\ud264'}, {0x0c16, '\ud280'}, {0x0c17, '\ud281'}, {0x0c18, '\ud284'}, {0x0c19, '\ud288'}, {0x0c1a, '\ud290'}, {0x0c1b, '\ud291'}, {0x0c1c, '\ud295'}, {0x0c1d, '\ud29c'}, {0x0c1e, '\ud2a0'}, {0x0c1f, '\ud2a4'}, {0x0c20, '\ud2ac'}, {0x0c21, '\ud2b1'}, {0x0c22, '\ud2b8'}, {0x0c23, '\ud2b9'}, {0x0c24, '\ud2bc'}, {0x0c25, '\ud2bf'}, {0x0c26, '\ud2c0'}, {0x0c27, '\ud2c2'}, {0x0c28, '\ud2c8'}, {0x0c29, '\ud2c9'}, {0x0c2a, '\ud2cb'}, {0x0c2b, '\ud2d4'}, {0x0c2c, '\ud2d8'}, {0x0c2d, '\ud2dc'}, {0x0c2e, '\ud2e4'}, {0x0c2f, '\ud2e5'}, {0x0c30, '\ud2f0'}, {0x0c31, '\ud2f1'}, {0x0c32, '\ud2f4'}, {0x0c33, '\ud2f8'}, {0x0c34, '\ud300'}, {0x0c35, '\ud301'}, {0x0c36, '\ud303'}, {0x0c37, '\ud305'}, {0x0c38, '\ud30c'}, {0x0c39, '\ud30d'}, {0x0c3a, '\ud30e'}, {0x0c3b, '\ud310'}, {0x0c3c, '\ud314'}, {0x0c3d, '\ud316'}, {0x0c3e, '\ud31c'}, {0x0c3f, '\ud31d'}, {0x0c40, '\ud31f'}, {0x0c41, '\ud320'}, {0x0c42, '\ud321'}, {0x0c43, '\ud325'}, {0x0c44, '\ud328'}, {0x0c45, '\ud329'}, {0x0c46, '\ud32c'}, {0x0c47, '\ud330'}, {0x0c48, '\ud338'}, {0x0c49, '\ud339'}, {0x0c4a, '\ud33b'}, {0x0c4b, '\ud33c'}, {0x0c4c, '\ud33d'}, {0x0c4d, '\ud344'}, {0x0c4e, '\ud345'}, {0x0c4f, '\ud37c'}, {0x0c50, '\ud37d'}, {0x0c51, '\ud380'}, {0x0c52, '\ud384'}, {0x0c53, '\ud38c'}, {0x0c54, '\ud38d'}, {0x0c55, '\ud38f'}, {0x0c56, '\ud390'}, {0x0c57, '\ud391'}, {0x0c58, '\ud398'}, {0x0c59, '\ud399'}, {0x0c5a, '\ud39c'}, {0x0c5b, '\ud3a0'}, {0x0c5c, '\ud3a8'}, {0x0c5d, '\ud3a9'}, {0x0c5e, '\ud3ab'}, {0x0c5f, '\ud3ad'}, {0x0c60, '\ud3b4'}, {0x0c61, '\ud3b8'}, {0x0c62, '\ud3bc'}, {0x0c63, '\ud3c4'}, {0x0c64, '\ud3c5'}, {0x0c65, '\ud3c8'}, {0x0c66, '\ud3c9'}, {0x0c67, '\ud3d0'}, {0x0c68, '\ud3d8'}, {0x0c69, '\ud3e1'}, {0x0c6a, '\ud3e3'}, {0x0c6b, '\ud3ec'}, {0x0c6c, '\ud3ed'}, {0x0c6d, '\ud3f0'}, {0x0c6e, '\ud3f4'}, {0x0c6f, '\ud3fc'}, {0x0c70, '\ud3fd'}, {0x0c71, '\ud3ff'}, {0x0c72, '\ud401'}, {0x0c73, '\ud408'}, {0x0c74, '\ud41d'}, {0x0c75, '\ud440'}, {0x0c76, '\ud444'}, {0x0c77, '\ud45c'}, {0x0c78, '\ud460'}, {0x0c79, '\ud464'}, {0x0c7a, '\ud46d'}, {0x0c7b, '\ud46f'}, {0x0c7c, '\ud478'}, {0x0c7d, '\ud479'}, {0x0c7e, '\ud47c'}, {0x0c7f, '\ud47f'}, {0x0c80, '\ud480'}, {0x0c81, '\ud482'}, {0x0c82, '\ud488'}, {0x0c83, '\ud489'}, {0x0c84, '\ud48b'}, {0x0c85, '\ud48d'}, {0x0c86, '\ud494'}, {0x0c87, '\ud4a9'}, {0x0c88, '\ud4cc'}, {0x0c89, '\ud4d0'}, {0x0c8a, '\ud4d4'}, {0x0c8b, '\ud4dc'}, {0x0c8c, '\ud4df'}, {0x0c8d, '\ud4e8'}, {0x0c8e, '\ud4ec'}, {0x0c8f, '\ud4f0'}, {0x0c90, '\ud4f8'}, {0x0c91, '\ud4fb'}, {0x0c92, '\ud4fd'}, {0x0c93, '\ud504'}, {0x0c94, '\ud508'}, {0x0c95, '\ud50c'}, {0x0c96, '\ud514'}, {0x0c97, '\ud515'}, {0x0c98, '\ud517'}, {0x0c99, '\ud53c'}, {0x0c9a, '\ud53d'}, {0x0c9b, '\ud540'}, {0x0c9c, '\ud544'}, {0x0c9d, '\ud54c'}, {0x0c9e, '\ud54d'}, {0x0c9f, '\ud54f'}, {0x0ca0, '\ud551'}, {0x0ca1, '\ud558'}, {0x0ca2, '\ud559'}, {0x0ca3, '\ud55c'}, {0x0ca4, '\ud560'}, {0x0ca5, '\ud565'}, {0x0ca6, '\ud568'}, {0x0ca7, '\ud569'}, {0x0ca8, '\ud56b'}, {0x0ca9, '\ud56d'}, {0x0caa, '\ud574'}, {0x0cab, '\ud575'}, {0x0cac, '\ud578'}, {0x0cad, '\ud57c'}, {0x0cae, '\ud584'}, {0x0caf, '\ud585'}, {0x0cb0, '\ud587'}, {0x0cb1, '\ud588'}, {0x0cb2, '\ud589'}, {0x0cb3, '\ud590'}, {0x0cb4, '\ud5a5'}, {0x0cb5, '\ud5c8'}, {0x0cb6, '\ud5c9'}, {0x0cb7, '\ud5cc'}, {0x0cb8, '\ud5d0'}, {0x0cb9, '\ud5d2'}, {0x0cba, '\ud5d8'}, {0x0cbb, '\ud5d9'}, {0x0cbc, '\ud5db'}, {0x0cbd, '\ud5dd'}, {0x0cbe, '\ud5e4'}, {0x0cbf, '\ud5e5'}, {0x0cc0, '\ud5e8'}, {0x0cc1, '\ud5ec'}, {0x0cc2, '\ud5f4'}, {0x0cc3, '\ud5f5'}, {0x0cc4, '\ud5f7'}, {0x0cc5, '\ud5f9'}, {0x0cc6, '\ud600'}, {0x0cc7, '\ud601'}, {0x0cc8, '\ud604'}, {0x0cc9, '\ud608'}, {0x0cca, '\ud610'}, {0x0ccb, '\ud611'}, {0x0ccc, '\ud613'}, {0x0ccd, '\ud614'}, {0x0cce, '\ud615'}, {0x0ccf, '\ud61c'}, {0x0cd0, '\ud620'}, {0x0cd1, '\ud624'}, {0x0cd2, '\ud62d'}, {0x0cd3, '\ud638'}, {0x0cd4, '\ud639'}, {0x0cd5, '\ud63c'}, {0x0cd6, '\ud640'}, {0x0cd7, '\ud645'}, {0x0cd8, '\ud648'}, {0x0cd9, '\ud649'}, {0x0cda, '\ud64b'}, {0x0cdb, '\ud64d'}, {0x0cdc, '\ud651'}, {0x0cdd, '\ud654'}, {0x0cde, '\ud655'}, {0x0cdf, '\ud658'}, {0x0ce0, '\ud65c'}, {0x0ce1, '\ud667'}, {0x0ce2, '\ud669'}, {0x0ce3, '\ud670'}, {0x0ce4, '\ud671'}, {0x0ce5, '\ud674'}, {0x0ce6, '\ud683'}, {0x0ce7, '\ud685'}, {0x0ce8, '\ud68c'}, {0x0ce9, '\ud68d'}, {0x0cea, '\ud690'}, {0x0ceb, '\ud694'}, {0x0cec, '\ud69d'}, {0x0ced, '\ud69f'}, {0x0cee, '\ud6a1'}, {0x0cef, '\ud6a8'}, {0x0cf0, '\ud6ac'}, {0x0cf1, '\ud6b0'}, {0x0cf2, '\ud6b9'}, {0x0cf3, '\ud6bb'}, {0x0cf4, '\ud6c4'}, {0x0cf5, '\ud6c5'}, {0x0cf6, '\ud6c8'}, {0x0cf7, '\ud6cc'}, {0x0cf8, '\ud6d1'}, {0x0cf9, '\ud6d4'}, {0x0cfa, '\ud6d7'}, {0x0cfb, '\ud6d9'}, {0x0cfc, '\ud6e0'}, {0x0cfd, '\ud6e4'}, {0x0cfe, '\ud6e8'}, {0x0cff, '\ud6f0'}, {0x0d00, '\ud6f5'}, {0x0d01, '\ud6fc'}, {0x0d02, '\ud6fd'}, {0x0d03, '\ud700'}, {0x0d04, '\ud704'}, {0x0d05, '\ud711'}, {0x0d06, '\ud718'}, {0x0d07, '\ud719'}, {0x0d08, '\ud71c'}, {0x0d09, '\ud720'}, {0x0d0a, '\ud728'}, {0x0d0b, '\ud729'}, {0x0d0c, '\ud72b'}, {0x0d0d, '\ud72d'}, {0x0d0e, '\ud734'}, {0x0d0f, '\ud735'}, {0x0d10, '\ud738'}, {0x0d11, '\ud73c'}, {0x0d12, '\ud744'}, {0x0d13, '\ud747'}, {0x0d14, '\ud749'}, {0x0d15, '\ud750'}, {0x0d16, '\ud751'}, {0x0d17, '\ud754'}, {0x0d18, '\ud756'}, {0x0d19, '\ud757'}, {0x0d1a, '\ud758'}, {0x0d1b, '\ud759'}, {0x0d1c, '\ud760'}, {0x0d1d, '\ud761'}, {0x0d1e, '\ud763'}, {0x0d1f, '\ud765'}, {0x0d20, '\ud769'}, {0x0d21, '\ud76c'}, {0x0d22, '\ud770'}, {0x0d23, '\ud774'}, {0x0d24, '\ud77c'}, {0x0d25, '\ud77d'}, {0x0d26, '\ud781'}, {0x0d27, '\ud788'}, {0x0d28, '\ud789'}, {0x0d29, '\ud78c'}, {0x0d2a, '\ud790'}, {0x0d2b, '\ud798'}, {0x0d2c, '\ud799'}, {0x0d2d, '\ud79b'}, {0x0d2e, '\ud79d'}, {0x0d31, '\u1100'}, {0x0d32, '\u1101'}, {0x0d33, '\u1102'}, {0x0d34, '\u1103'}, {0x0d35, '\u1104'}, {0x0d36, '\u1105'}, {0x0d37, '\u1106'}, {0x0d38, '\u1107'}, {0x0d39, '\u1108'}, {0x0d3a, '\u1109'}, {0x0d3b, '\u110a'}, {0x0d3c, '\u110b'}, {0x0d3d, '\u110c'}, {0x0d3e, '\u110d'}, {0x0d3f, '\u110e'}, {0x0d40, '\u110f'}, {0x0d41, '\u1110'}, {0x0d42, '\u1111'}, {0x0d43, '\u1112'}, {0x0d44, '\u1161'}, {0x0d45, '\u1162'}, {0x0d46, '\u1163'}, {0x0d47, '\u1164'}, {0x0d48, '\u1165'}, {0x0d49, '\u1166'}, {0x0d4a, '\u1167'}, {0x0d4b, '\u1168'}, {0x0d4c, '\u1169'}, {0x0d4d, '\u116d'}, {0x0d4e, '\u116e'}, {0x0d4f, '\u1172'}, {0x0d50, '\u1173'}, {0x0d51, '\u1175'}, {0x0d61, '\ub894'}, {0x0d62, '\uc330'}, {0x0d63, '\uc3bc'}, {0x0d64, '\uc4d4'}, {0x0d65, '\ucb2c'}, }; } } ================================================ FILE: library/Support/EncodedString5.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace PkmnFoundations.Support { public class EncodedString5 : EncodedStringBase { /// /// Instances an EncodedString5 from its binary representation. /// /// This buffer is copied. public EncodedString5(byte[] data) : base(data) { } /// /// Instances an EncodedString5 from its binary representation. /// /// Buffer to copy from /// Offset in buffer /// Number of bytes (not chars) to copy public EncodedString5(byte[] data, int start, int length) : base(data, start, length) { } /// /// Instances an EncodedString5 from a Unicode string. /// /// text /// Length of encoded buffer in bytes (not chars) public EncodedString5(string text, int length) : base(text, length) { } // todo: Use pointers for both of these public static string DecodeString_impl(byte[] data, int start, int count) { if (data.Length < start + count) throw new ArgumentOutOfRangeException("count"); if (count < 0) throw new ArgumentOutOfRangeException("count"); StringBuilder sb = new StringBuilder(); for (int i = start; i < start + count * 2; i += 2) { ushort gamecode = BitConverter.ToUInt16(data, i); if (gamecode == 0xffff) { break; } char ch = Generation5TextLookupTable.ContainsKey(gamecode) ? Generation5TextLookupTable[gamecode] : (char)gamecode; sb.Append(ch); } return sb.ToString(); } public static string DecodeString_impl(byte[] data) { return DecodeString_impl(data, 0, data.Length >> 1); } public static byte[] EncodeString_impl(string str, int size) { int actualLength = (size >> 1) - 1; if (str.Length > actualLength) throw new ArgumentOutOfRangeException("size"); byte[] result = new byte[size]; MemoryStream m = new MemoryStream(result); foreach (char c in str.ToCharArray()) { m.Write(BitConverter.GetBytes(LookupReverse.ContainsKey(c) ? LookupReverse[c] : c), 0, 2); } m.WriteByte(0xff); m.WriteByte(0xff); return result; } protected override string DecodeString(byte[] data, int start, int count) { return DecodeString_impl(data, start, count); } protected override byte[] EncodeString(string str, int size) { return EncodeString_impl(str, size); } public override string ToString() { return Text; } public EncodedString5 Clone() { return new EncodedString5(RawData); } private static Dictionary m_lookup_reverse = null; private static Dictionary LookupReverse { get { if (m_lookup_reverse == null) { Dictionary reverse = new Dictionary(Generation5TextLookupTable.Count); foreach (KeyValuePair pair in Generation5TextLookupTable) { //if (!reverse.ContainsKey(pair.Value)) reverse.Add(pair.Value, pair.Key); } m_lookup_reverse = reverse; } return m_lookup_reverse; } } private static Dictionary Generation5TextLookupTable = new Dictionary { {0x2467, '\u00d7'}, {0x2468, '\u00f7'}, {0x246c, '\u2026'}, {0x246d, '\u2642'}, {0x246e, '\u2640'}, {0x246f, '\u2660'}, {0x2470, '\u2663'}, {0x2471, '\u2665'}, {0x2472, '\u2666'}, {0x2473, '\u2605'}, {0x2474, '\u25ce'}, {0x2475, '\u25cb'}, {0x2476, '\u25a1'}, {0x2477, '\u25b3'}, {0x2478, '\u25c7'}, {0x2479, '\u266a'}, {0x247a, '\u2600'}, {0x247b, '\u2601'}, {0x247d, '\u2602'}, }; } } ================================================ FILE: library/Support/EncodedStringBase.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PkmnFoundations.Support { public abstract class EncodedStringBase { public EncodedStringBase() { } public EncodedStringBase(byte[] data) : this() { RawData = data; } /// /// Instances an EncodedString from its binary representation. /// /// Buffer to copy from /// Offset in buffer /// Number of bytes (not chars) to copy public EncodedStringBase(byte[] data, int start, int length) { if (length < 2) throw new ArgumentOutOfRangeException("length"); if (data.Length < start + length) throw new ArgumentOutOfRangeException("length"); if (length % 2 != 0) throw new ArgumentException("length"); Size = length; byte[] trim = new byte[length]; Array.Copy(data, start, trim, 0, length); AssignData(trim); } /// /// Instances an EncodedString from a Unicode string. /// /// text /// Length of encoded buffer in bytes (not chars) public EncodedStringBase(string text, int length) { if (length < 2) throw new ArgumentOutOfRangeException("length"); if (length % 2 != 0) throw new ArgumentException("length"); Size = length; Text = text; } // todo: move more of the encoded string implementation over here for DRY reasons private byte[] m_raw_data; private string m_text; public virtual string Text { get { if (m_text == null && m_raw_data == null) return null; if (m_text == null) m_text = DecodeString(m_raw_data, 0, m_raw_data.Length >> 1); return m_text; } set { int actualLength = (Size >> 1) - 1; if (value.Length > actualLength) throw new ArgumentException(); AssignText(value); } } public virtual byte[] RawData { get { if (m_raw_data == null && m_text == null) return null; if (m_raw_data == null) m_raw_data = EncodeString(m_text, Size); return m_raw_data.ToArray(); } set { int size = value.Length; if (size < 2) throw new ArgumentException(); if (size % 2 != 0) throw new ArgumentException(); Size = size; AssignData(value.ToArray()); } } // lazy evaluate these conversions since they're slow protected virtual void AssignData(byte[] data) { m_raw_data = data; m_text = null; } protected virtual void AssignText(string text) { m_text = text; m_raw_data = null; } protected abstract string DecodeString(byte[] data, int start, int count); protected abstract byte[] EncodeString(string str, int size); public override string ToString() { return Text; } public virtual int Size { get; protected set; } public virtual bool IsValid { get { return true; } } } } ================================================ FILE: library/Support/EnumerableExtender.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PkmnFoundations.Support { public static class EnumerableExtender { public static IEnumerable OrderByLambda(this IEnumerable arg, Func comparer) { // xxx: Should be using Comparer.Create but we need .NET 4.5 for it. and are still targeting 3.5. return arg.OrderBy(k => k, new LambdaComparer(comparer)); } private class LambdaComparer : IComparer { public LambdaComparer(Func comparer) { m_comparer = comparer; } private readonly Func m_comparer; public int Compare(T first, T second) { return m_comparer(first, second); } } public static IEnumerable DrawWithoutReplacement(this IEnumerable source, Random rng) { var working = source.ToList(); for (int i = working.Count; i > 0; i--) { int rand = rng.Next(i); yield return working[rand]; working[rand] = working[i - 1]; } } } } ================================================ FILE: library/Support/GameSyncUtils.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PkmnFoundations.Support { public static class GameSyncUtils { private static ushort GameSyncCrc16(int val) { var table = new ushort[] { // xxx: I suspect this lut is actually a baked crc polynomial 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0 }; int crc16 = 0xffff; for (int i = 0; i < 4; i++) { crc16 = (crc16 << 8) ^ table[((crc16 >> 8) ^ (val & 0xff)) & 0xff]; val >>= 8; } return (ushort)crc16; } public static string PidToGsid(int pid) { return Base32Encode((long)pid | ((long)GameSyncCrc16(pid) << 32)); } public static int GsidToPid(string gsid) { return (int)Base32Decode(gsid); } // todo: add PidToFc and FcToPid methods. // Algo: https://www.caitsith2.com/ds/fc.php.txt private const string charset = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // Not the entire alphabet, be careful public static string Base32Encode(long value) { StringBuilder result = new StringBuilder(10); for (int i = 0; i < 10; i++) { result.Append(charset[(int)(value & 0x1f)]); value >>= 5; } return result.ToString(); } public static long Base32Decode(string value) { long result = 0; // xxx: we don't need to reverse this if we shift the other way and fill in starting at the MSB foreach (char c in value.ToUpperInvariant().Reverse()) { result <<= 5; if (charset.Contains(c)) result |= (long)charset.IndexOf(c); else throw new FormatException("Base32 string contains invalid characters"); } return result; } } } ================================================ FILE: library/Support/Indexer1d.cs ================================================ using System; using System.Collections.Generic; using System.Text; namespace PkmnFoundations.Support { /// /// Helper class to aid with the implementation of non-default indexers /// /// public class Indexer1d : IReadOnlyIndexer1d, IWriteOnlyIndexer1d { public Indexer1d(Getter1d getter, Setter1d setter) { m_getter = getter; m_setter = setter; } private Getter1d m_getter; private Setter1d m_setter; public TValue this[TKey index] { get { return m_getter(index); } set { m_setter(index, value); } } } public class ReadOnlyIndexer1d : IReadOnlyIndexer1d { public ReadOnlyIndexer1d(Getter1d getter) { m_getter = getter; } private Getter1d m_getter; public TValue this[TKey index] { get { return m_getter(index); } } } public interface IReadOnlyIndexer1d { TValue this[TKey index] { get; } } public interface IWriteOnlyIndexer1d { TValue this[TKey index] { set; } } public delegate TValue Getter1d(TKey index); public delegate void Setter1d(TKey index, TValue value); } ================================================ FILE: library/Support/LazyKeyValuePair.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PkmnFoundations.Support { public class LazyKeyValuePair : ILazyKeyValuePair { public LazyKeyValuePair(Func evaluator, Func key_evaluator) { m_evaluator = evaluator; m_key_evaluator = key_evaluator; m_has_key = true; m_has_value = false; } private TKey m_key; private bool m_has_key; private Func m_evaluator; public TKey Key { get { EvaluateKey(); return m_key; } set { m_key = value; m_has_key = true; m_has_value = false; } } private TValue m_value; private bool m_has_value; private Func m_key_evaluator; public TValue Value { get { Evaluate(); return m_value; } set { m_value = value; m_has_value = true; m_has_key = false; } } public void EvaluateKey() { #if DEBUG AssertHelper.Assert(m_has_key || m_has_value); #endif if (!m_has_key) m_key = m_key_evaluator(m_value); m_has_key = true; } public void Evaluate() { #if DEBUG AssertHelper.Assert(m_has_key || m_has_value); #endif if (!m_has_value) m_value = m_evaluator(m_key); m_has_value = true; } /// /// Causes the Key to be lost so it will be recomputed from the Value. /// public void InvalidateKey() { if (!m_has_value) throw new InvalidOperationException(); m_has_key = false; } /// /// Causes the Value to be lost so it will be recomputed from the Key. /// public void Invalidate() { if (!m_has_key) throw new InvalidOperationException(); m_has_value = false; } } public interface ILazyKeyValuePair { TKey Key { get; } TValue Value { get; } void EvaluateKey(); void Evaluate(); } } ================================================ FILE: library/Support/LocalizedString.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace PkmnFoundations.Support { public class LocalizedString : Dictionary { public LocalizedString() { } public string ToString(string lang) { if (Count == 0) return null; lang = lang.ToUpperInvariant(); try { return this[lang]; } catch (KeyNotFoundException) { } try { return this["EN"]; } catch (KeyNotFoundException) { } return Values.First(); } public override string ToString() { return ToString(Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName); } } } ================================================ FILE: library/Support/LogHelper.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; namespace PkmnFoundations.Support { public static class LogHelper { static LogHelper() { Type = EventLogTypes.StandardError; } public static void Write(String message, EventLogEntryType type, int eventID, ushort category, byte[] rawData) { switch (Type) { case EventLogTypes.StandardOutput: Console.WriteLine(message); break; case EventLogTypes.StandardError: Console.Error.WriteLine(message); break; case EventLogTypes.File: try { using (FileStream fs = File.Open(m_filename, FileMode.Append)) { StreamWriter sw = new StreamWriter(fs); sw.Write("{0}\t{1}\n", DateTime.Now, message); sw.Close(); } } catch (Exception ex) { Console.WriteLine("Can't open logfile at {0}.\nException: {1}\nMessage: {2}", m_filename, ex.Message, message); } break; case EventLogTypes.Windows: m_event_log.WriteEntry(message, type, eventID, (short)category, rawData); break; } } public static void Write(String message, EventLogEntryType type) { Write(message, type, 0, 0, null); } public static void Write(String message) { Write(message, EventLogEntryType.Information, 0, 0, null); } public static void UseStandardOutput() { Type = EventLogTypes.StandardOutput; m_event_log = null; } public static void UseStandardError() { Type = EventLogTypes.StandardError; m_event_log = null; } public static void UseFile(String filename) { if (filename == null) throw new ArgumentNullException("filename"); Type = EventLogTypes.File; m_filename = filename; m_event_log = null; } public static void UseEventLog(EventLog event_log) { if (event_log == null) throw new ArgumentNullException("event_log"); Type = EventLogTypes.Windows; m_event_log = event_log; } public static EventLogTypes Type { get; private set; } private static String m_filename; private static EventLog m_event_log; } public enum EventLogTypes { StandardOutput, StandardError, File, Windows } } ================================================ FILE: library/Support/StreamExtender.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace PkmnFoundations.Support { public static class StreamExtender { /// /// Reads bytes from a stream and blocks until it can read them all. /// /// Stream /// Buffer to dump data into /// Offset in buffer /// Desired number of bytes /// Number of bytes obtained. Should only be less than count /// if eof was reached. public static int ReadBlock(this Stream s, byte[] buffer, int offset, int count) { int readBytes = 0; while (readBytes < count) { int x = s.Read(buffer, offset + readBytes, count - readBytes); if (x == 0) return readBytes; readBytes += x; } return readBytes; } /// /// Reads bytes from a stream and blocks until it can read them all. /// /// Stream, encapsulated in a BinaryReader /// Buffer to dump data into /// Offset in buffer /// Desired number of bytes /// Number of bytes obtained. Should only be less than count /// if eof was reached. public static int ReadBlock(this BinaryReader r, byte[] buffer, int offset, int count) { int readBytes = 0; while (readBytes < count) { int x = r.Read(buffer, offset + readBytes, count - readBytes); if (x == 0) return readBytes; readBytes += x; } return readBytes; } public static void CompatibleCopyTo(this Stream src, Stream dest) { const int BUFFER_LENGTH = 256; byte[] buffer = new byte[BUFFER_LENGTH]; int lastProgress; while ((lastProgress = src.Read(buffer, 0, BUFFER_LENGTH)) > 0) dest.Write(buffer, 0, lastProgress); } public static void WriteBytes(this Stream s, byte[] buffer) { // Lack of a Stream.Write overload that just writes the whole array // seems like a huge omission to me. s.Write(buffer, 0, buffer.Length); } } } ================================================ FILE: library/Support/StringHelper.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace PkmnFoundations.Support { public static class StringHelper { public static String BytesToString(byte[] data, Encoding encoding) { MemoryStream ms = new MemoryStream(data); StreamReader sr = new StreamReader(ms, encoding); return sr.ReadToEnd(); } public static String BytesToString(byte[] data, int start, int length, Encoding encoding) { MemoryStream ms = new MemoryStream(data, start, length); StreamReader sr = new StreamReader(ms, encoding); return sr.ReadToEnd(); } } } ================================================ FILE: library/Support/TrendyPhrase4.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PkmnFoundations.Support { public class TrendyPhrase4 : TrendyPhraseBase { public TrendyPhrase4(byte[] data) : base(data) { } public TrendyPhrase4(ushort mood, ushort index, ushort word1, ushort word2) : base(Pack(mood, index, word1, word2)) { } public override string Render(string wordFormat) { return RenderPhrase(Data, wordFormat); } public static string RenderPhrase(byte[] data, string wordFormat) { if (data == null) throw new ArgumentNullException(); if (data.Length != 8) throw new ArgumentException(); ushort mood = BitConverter.ToUInt16(data, 0); ushort index = BitConverter.ToUInt16(data, 2); ushort word1 = BitConverter.ToUInt16(data, 4); ushort word2 = BitConverter.ToUInt16(data, 6); if (mood >= 5) return ""; if (index >= 20) return ""; return string.Format(PHRASES[mood, index], string.Format(wordFormat, RenderWord(word1)), string.Format(wordFormat, RenderWord(word2)) ); } public static string RenderWord(ushort word) { if (word < 496) return WORDS_POKEMON[word]; if (word < 964) return WORDS_MOVES[word - 496]; if (word < 982) return WORDS_TYPES[word - 964]; if (word < 1106) return WORDS_ABILITIES[word - 982]; if (word < 1144) return WORDS_TRAINER[word - 1106]; if (word < 1182) return WORDS_PEOPLE[word - 1144]; if (word < 1289) return WORDS_GREETINGS[word - 1182]; if (word < 1393) return WORDS_LIFESTYLE[word - 1289]; if (word < 1440) return WORDS_FEELINGS[word - 1393]; if (word < 1472) return WORDS_TOUGH[word - 1440]; if (word < 1495) return WORDS_UNION[word - 1472]; return ""; } public TrendyPhrase4 Clone() { return new TrendyPhrase4(Data); } #region String tables // Special thanks to http://projectpokemon.org/rawdb/diamond/msg.php // for their string table dumps. // msg.narc/395 through /399 private static string[,] PHRASES = new string[,] { { // Mood 0: Start of battle "Please!\n{0}!", // 0 "Go! {0}!", // 1 "I’ll battle with\n{0}!", // 2 "It’s {0}!", // 3 "{0}, I’m going\nwith {1}!", // 4 "Look at {0}!", // 5 "I’ll show you {0}!", // 6 "Now!\n{0}!", // 7 "I’ll show you my\n{0} strategy!", // 8 "I’ll {0}!", // 9 "I’ll shock you with\n{0}!", // 10 "This is the beginning\nof {0}!", // 11 "This battle is\n{0}!", // 12 "I don’t think I’ll\never lose at {0}!", // 13 "Team {0} is here!", // 14 "You think you can beat\n{0}?", // 15 "{0}!\n{1} power!", // 16 "This is the {0}\nPokémon!", // 17 "{0} won’t lose!", // 18 "Please {0}!\n{1}!" // 19 }, { // Mood 1: Victory "I win!\n{0}!", // 0 "I won!\nI won with {0}!", // 1 "{0} is strong,\nisn’t it?", // 2 "It’s {0}\n{1} after all!", // 3 "{0}, yay!", // 4 "Yay, {0}!\n{1}!", // 5 "Sorry, it’s {0}\n{1}.", // 6 "{0}!\nThank you!", // 7 "The way I feel now is\n{0}!", // 8 "I wanted people to look at\nmy {0}!", // 9 "It’s all thanks to\n{0}.", // 10 "I might have won with\n{0}!", // 11 "I get the happiest with\n{0}!", // 12 "{0} secured\nthe victory!", // 13 "This {0}\nwas really good!", // 14 "{0}\nwas fun, wasn’t it?", // 15 "Huh?\n{0}?!", // 16 "{0} is the toughest!", // 17 "Happy!\n{0} happy!", // 18 "How’s that?!\n{0}!" // 19 }, { // Mood 2: Defeat "You win...\n{0}", // 0 "{0} was the one\nthing I wanted to avoid...", // 1 "Waaah!\n{0}!", // 2 "I want to go home with\n{0}...", // 3 "{0}!\n{1}!", // 4 "Could it be...?\n{0}...?", // 5 "{0}!\nHow awful!", // 6 "I was confident about\n{0}, too.", // 7 "You're {0},\naren’t you?", // 8 "{0}!\nCan’t be anything else but.", // 9 "I feel so helplessly angry...\nIt’s {0}!", // 10 "{0} makes me sad...", // 11 "I feel sorry for\n{0}!", // 12 "The way I feel now is\n{0}...", // 13 "I lost, but I won at\n{0}!", // 14 "I would’ve won if this\nwere {0}...", // 15 "My head’s filled with only\n{0} now!", // 16 "The way I lost...\nIt’s like {0}...", // 17 "Isn’t {0}\n{1}?", // 18 "Aww... That’s really\n{0}..." // 19 }, { // Mood 3: Other "Hello!\n{0}!", // 0 "I love {0}!", // 1 "I love {0}!\nI love {1}, too!", // 2 "This {0} is\n{1}, isn’t it?", // 3 "I can do anything for\n{0}!", // 4 "This {0} is\n{1}!", // 5 "{0} is the real\n{1}!", // 6 "It might be {0}...", // 7 "There’s only {0}\nleft!", // 8 "It’s {0}!\nIt’s {1}!", // 9 "I prefer {0}\nafter all!", // 10 "Is {0}\n{1}?", // 11 "Do you like {0}?", // 12 "What do you think of\n{0}?", // 13 "{0} is so\n{1}!", // 14 "{0} are\n{1}!", // 15 "{0}, right?", // 16 "Did you know {0}?\nIt’s {1}!", // 17 "Excuse me...\nIt’s {0}!", // 18 "{0}, right?\n{1}!" // 19 }, { // Mood 4: Multiplay "{0}!\nHello!", // 0 "Glad to meet you!\nI love {0}!", // 1 "I’m a {0} Trainer!\nPlease battle me!", // 2 "Please trade!\nI’m offering {0}!", // 3 "Please trade!\nI want a {0}!", // 4 "I’ve entered the Union Room.", // 5 "Let’s draw! I want to draw\n{0}!", // 6 "I’ve got to go!\n{0}!", // 7 "Please leave me alone...", // 8 "Anyone want to\n{0}?", // 9 "Let’s {0}!", // 10 "Want to {0}?", // 11 "I want to {0}!", // 12 "OK!", // 13 "I don’t want to\n{0}.", // 14 "I’ll go wait at the Colosseum\nnow.", // 15 "Please talk to me!", // 16 "Do you know where I am?", // 17 "I want to trade my {0}.\nPlease talk to me.", // 18 "I want a {0} battle!\nPlease talk to me!" // 19 } }; // 0-495: msg.narc/362 Pokemon // 496-963: msg.narc/589 Attacks // 964-981: msg.narc/565 Types // 982-1105: msg.narc/553 Abilities // 1106-1143: msg.narc/388 "Trainer" // 1144-1181: msg.narc/389 "People" // 1182-1288: msg.narc/390 "Greetings" // 1289-1392: msg.narc/391 "Lifestyle" // 1393-1439: msg.narc/392 "Feelings" // 1440-1471: msg.narc/393 "Tough words" // 1472-1494: msg.narc/394 "Union" private static string[] WORDS_POKEMON = new string[] { "-----","BULBASAUR","IVYSAUR","VENUSAUR", // 0 "CHARMANDER","CHARMELEON","CHARIZARD","SQUIRTLE", "WARTORTLE","BLASTOISE","CATERPIE","METAPOD", "BUTTERFREE","WEEDLE","KAKUNA","BEEDRILL", "PIDGEY","PIDGEOTTO","PIDGEOT","RATTATA", "RATICATE","SPEAROW","FEAROW","EKANS", "ARBOK","PIKACHU","RAICHU","SANDSHREW", "SANDSLASH","NIDORAN♀","NIDORINA","NIDOQUEEN", "NIDORAN♂","NIDORINO","NIDOKING","CLEFAIRY", "CLEFABLE","VULPIX","NINETALES","JIGGLYPUFF", "WIGGLYTUFF","ZUBAT","GOLBAT","ODDISH", "GLOOM","VILEPLUME","PARAS","PARASECT", "VENONAT","VENOMOTH","DIGLETT","DUGTRIO", "MEOWTH","PERSIAN","PSYDUCK","GOLDUCK", "MANKEY","PRIMEAPE","GROWLITHE","ARCANINE", "POLIWAG","POLIWHIRL","POLIWRATH","ABRA", "KADABRA","ALAKAZAM","MACHOP","MACHOKE", "MACHAMP","BELLSPROUT","WEEPINBELL","VICTREEBEL", "TENTACOOL","TENTACRUEL","GEODUDE","GRAVELER", "GOLEM","PONYTA","RAPIDASH","SLOWPOKE", "SLOWBRO","MAGNEMITE","MAGNETON","FARFETCH’D", "DODUO","DODRIO","SEEL","DEWGONG", "GRIMER","MUK","SHELLDER","CLOYSTER", "GASTLY","HAUNTER","GENGAR","ONIX", "DROWZEE","HYPNO","KRABBY","KINGLER", "VOLTORB","ELECTRODE","EXEGGCUTE","EXEGGUTOR", "CUBONE","MAROWAK","HITMONLEE","HITMONCHAN", "LICKITUNG","KOFFING","WEEZING","RHYHORN", "RHYDON","CHANSEY","TANGELA","KANGASKHAN", "HORSEA","SEADRA","GOLDEEN","SEAKING", "STARYU","STARMIE","MR. MIME","SCYTHER", "JYNX","ELECTABUZZ","MAGMAR","PINSIR", "TAUROS","MAGIKARP","GYARADOS","LAPRAS", "DITTO","EEVEE","VAPOREON","JOLTEON", "FLAREON","PORYGON","OMANYTE","OMASTAR", "KABUTO","KABUTOPS","AERODACTYL","SNORLAX", "ARTICUNO","ZAPDOS","MOLTRES","DRATINI", "DRAGONAIR","DRAGONITE","MEWTWO","MEW", "CHIKORITA","BAYLEEF","MEGANIUM","CYNDAQUIL", "QUILAVA","TYPHLOSION","TOTODILE","CROCONAW", "FERALIGATR","SENTRET","FURRET","HOOTHOOT", "NOCTOWL","LEDYBA","LEDIAN","SPINARAK", "ARIADOS","CROBAT","CHINCHOU","LANTURN", "PICHU","CLEFFA","IGGLYBUFF","TOGEPI", "TOGETIC","NATU","XATU","MAREEP", "FLAAFFY","AMPHAROS","BELLOSSOM","MARILL", "AZUMARILL","SUDOWOODO","POLITOED","HOPPIP", "SKIPLOOM","JUMPLUFF","AIPOM","SUNKERN", "SUNFLORA","YANMA","WOOPER","QUAGSIRE", "ESPEON","UMBREON","MURKROW","SLOWKING", "MISDREAVUS","UNOWN","WOBBUFFET","GIRAFARIG", "PINECO","FORRETRESS","DUNSPARCE","GLIGAR", "STEELIX","SNUBBULL","GRANBULL","QWILFISH", "SCIZOR","SHUCKLE","HERACROSS","SNEASEL", "TEDDIURSA","URSARING","SLUGMA","MAGCARGO", "SWINUB","PILOSWINE","CORSOLA","REMORAID", "OCTILLERY","DELIBIRD","MANTINE","SKARMORY", "HOUNDOUR","HOUNDOOM","KINGDRA","PHANPY", "DONPHAN","PORYGON2","STANTLER","SMEARGLE", "TYROGUE","HITMONTOP","SMOOCHUM","ELEKID", "MAGBY","MILTANK","BLISSEY","RAIKOU", "ENTEI","SUICUNE","LARVITAR","PUPITAR", "TYRANITAR","LUGIA","HO-OH","CELEBI", "TREECKO","GROVYLE","SCEPTILE","TORCHIC", "COMBUSKEN","BLAZIKEN","MUDKIP","MARSHTOMP", "SWAMPERT","POOCHYENA","MIGHTYENA","ZIGZAGOON", "LINOONE","WURMPLE","SILCOON","BEAUTIFLY", "CASCOON","DUSTOX","LOTAD","LOMBRE", "LUDICOLO","SEEDOT","NUZLEAF","SHIFTRY", "TAILLOW","SWELLOW","WINGULL","PELIPPER", "RALTS","KIRLIA","GARDEVOIR","SURSKIT", "MASQUERAIN","SHROOMISH","BRELOOM","SLAKOTH", "VIGOROTH","SLAKING","NINCADA","NINJASK", "SHEDINJA","WHISMUR","LOUDRED","EXPLOUD", "MAKUHITA","HARIYAMA","AZURILL","NOSEPASS", "SKITTY","DELCATTY","SABLEYE","MAWILE", "ARON","LAIRON","AGGRON","MEDITITE", "MEDICHAM","ELECTRIKE","MANECTRIC","PLUSLE", "MINUN","VOLBEAT","ILLUMISE","ROSELIA", "GULPIN","SWALOT","CARVANHA","SHARPEDO", "WAILMER","WAILORD","NUMEL","CAMERUPT", "TORKOAL","SPOINK","GRUMPIG","SPINDA", "TRAPINCH","VIBRAVA","FLYGON","CACNEA", "CACTURNE","SWABLU","ALTARIA","ZANGOOSE", "SEVIPER","LUNATONE","SOLROCK","BARBOACH", "WHISCASH","CORPHISH","CRAWDAUNT","BALTOY", "CLAYDOL","LILEEP","CRADILY","ANORITH", "ARMALDO","FEEBAS","MILOTIC","CASTFORM", "KECLEON","SHUPPET","BANETTE","DUSKULL", "DUSCLOPS","TROPIUS","CHIMECHO","ABSOL", "WYNAUT","SNORUNT","GLALIE","SPHEAL", "SEALEO","WALREIN","CLAMPERL","HUNTAIL", "GOREBYSS","RELICANTH","LUVDISC","BAGON", "SHELGON","SALAMENCE","BELDUM","METANG", "METAGROSS","REGIROCK","REGICE","REGISTEEL", "LATIAS","LATIOS","KYOGRE","GROUDON", "RAYQUAZA","JIRACHI","DEOXYS","TURTWIG", "GROTLE","TORTERRA","CHIMCHAR","MONFERNO", "INFERNAPE","PIPLUP","PRINPLUP","EMPOLEON", "STARLY","STARAVIA","STARAPTOR","BIDOOF", "BIBAREL","KRICKETOT","KRICKETUNE","SHINX", "LUXIO","LUXRAY","BUDEW","ROSERADE", "CRANIDOS","RAMPARDOS","SHIELDON","BASTIODON", "BURMY","WORMADAM","MOTHIM","COMBEE", "VESPIQUEN","PACHIRISU","BUIZEL","FLOATZEL", "CHERUBI","CHERRIM","SHELLOS","GASTRODON", "AMBIPOM","DRIFLOON","DRIFBLIM","BUNEARY", "LOPUNNY","MISMAGIUS","HONCHKROW","GLAMEOW", "PURUGLY","CHINGLING","STUNKY","SKUNTANK", "BRONZOR","BRONZONG","BONSLY","MIME JR.", "HAPPINY","CHATOT","SPIRITOMB","GIBLE", "GABITE","GARCHOMP","MUNCHLAX","RIOLU", "LUCARIO","HIPPOPOTAS","HIPPOWDON","SKORUPI", "DRAPION","CROAGUNK","TOXICROAK","CARNIVINE", "FINNEON","LUMINEON","MANTYKE","SNOVER", "ABOMASNOW","WEAVILE","MAGNEZONE","LICKILICKY", "RHYPERIOR","TANGROWTH","ELECTIVIRE","MAGMORTAR", "TOGEKISS","YANMEGA","LEAFEON","GLACEON", "GLISCOR","MAMOSWINE","PORYGON-Z","GALLADE", "PROBOPASS","DUSKNOIR","FROSLASS","ROTOM", "UXIE","MESPRIT","AZELF","DIALGA", "PALKIA","HEATRAN","REGIGIGAS","GIRATINA", "CRESSELIA","PHIONE","MANAPHY","DARKRAI", "SHAYMIN","ARCEUS","Egg","Bad Egg" }; private static string[] WORDS_MOVES = new string[] { "-","POUND","KARATE CHOP","DOUBLESLAP", // 496 "COMET PUNCH","MEGA PUNCH","PAY DAY","FIRE PUNCH", "ICE PUNCH","THUNDERPUNCH","SCRATCH","VICEGRIP", "GUILLOTINE","RAZOR WIND","SWORDS DANCE","CUT", "GUST","WING ATTACK","WHIRLWIND","FLY", "BIND","SLAM","VINE WHIP","STOMP", "DOUBLE KICK","MEGA KICK","JUMP KICK","ROLLING KICK", "SAND-ATTACK","HEADBUTT","HORN ATTACK","FURY ATTACK", "HORN DRILL","TACKLE","BODY SLAM","WRAP", "TAKE DOWN","THRASH","DOUBLE-EDGE","TAIL WHIP", "POISON STING","TWINEEDLE","PIN MISSILE","LEER", "BITE","GROWL","ROAR","SING", "SUPERSONIC","SONICBOOM","DISABLE","ACID", "EMBER","FLAMETHROWER","MIST","WATER GUN", "HYDRO PUMP","SURF","ICE BEAM","BLIZZARD", "PSYBEAM","BUBBLEBEAM","AURORA BEAM","HYPER BEAM", "PECK","DRILL PECK","SUBMISSION","LOW KICK", "COUNTER","SEISMIC TOSS","STRENGTH","ABSORB", "MEGA DRAIN","LEECH SEED","GROWTH","RAZOR LEAF", "SOLARBEAM","POISONPOWDER","STUN SPORE","SLEEP POWDER", "PETAL DANCE","STRING SHOT","DRAGON RAGE","FIRE SPIN", "THUNDERSHOCK","THUNDERBOLT","THUNDER WAVE","THUNDER", "ROCK THROW","EARTHQUAKE","FISSURE","DIG", "TOXIC","CONFUSION","PSYCHIC","HYPNOSIS", "MEDITATE","AGILITY","QUICK ATTACK","RAGE", "TELEPORT","NIGHT SHADE","MIMIC","SCREECH", "DOUBLE TEAM","RECOVER","HARDEN","MINIMIZE", "SMOKESCREEN","CONFUSE RAY","WITHDRAW","DEFENSE CURL", "BARRIER","LIGHT SCREEN","HAZE","REFLECT", "FOCUS ENERGY","BIDE","METRONOME","MIRROR MOVE", "SELFDESTRUCT","EGG BOMB","LICK","SMOG", "SLUDGE","BONE CLUB","FIRE BLAST","WATERFALL", "CLAMP","SWIFT","SKULL BASH","SPIKE CANNON", "CONSTRICT","AMNESIA","KINESIS","SOFTBOILED", "HI JUMP KICK","GLARE","DREAM EATER","POISON GAS", "BARRAGE","LEECH LIFE","LOVELY KISS","SKY ATTACK", "TRANSFORM","BUBBLE","DIZZY PUNCH","SPORE", "FLASH","PSYWAVE","SPLASH","ACID ARMOR", "CRABHAMMER","EXPLOSION","FURY SWIPES","BONEMERANG", "REST","ROCK SLIDE","HYPER FANG","SHARPEN", "CONVERSION","TRI ATTACK","SUPER FANG","SLASH", "SUBSTITUTE","STRUGGLE","SKETCH","TRIPLE KICK", "THIEF","SPIDER WEB","MIND READER","NIGHTMARE", "FLAME WHEEL","SNORE","CURSE","FLAIL", "CONVERSION 2","AEROBLAST","COTTON SPORE","REVERSAL", "SPITE","POWDER SNOW","PROTECT","MACH PUNCH", "SCARY FACE","FAINT ATTACK","SWEET KISS","BELLY DRUM", "SLUDGE BOMB","MUD-SLAP","OCTAZOOKA","SPIKES", "ZAP CANNON","FORESIGHT","DESTINY BOND","PERISH SONG", "ICY WIND","DETECT","BONE RUSH","LOCK-ON", "OUTRAGE","SANDSTORM","GIGA DRAIN","ENDURE", "CHARM","ROLLOUT","FALSE SWIPE","SWAGGER", "MILK DRINK","SPARK","FURY CUTTER","STEEL WING", "MEAN LOOK","ATTRACT","SLEEP TALK","HEAL BELL", "RETURN","PRESENT","FRUSTRATION","SAFEGUARD", "PAIN SPLIT","SACRED FIRE","MAGNITUDE","DYNAMICPUNCH", "MEGAHORN","DRAGONBREATH","BATON PASS","ENCORE", "PURSUIT","RAPID SPIN","SWEET SCENT","IRON TAIL", "METAL CLAW","VITAL THROW","MORNING SUN","SYNTHESIS", "MOONLIGHT","HIDDEN POWER","CROSS CHOP","TWISTER", "RAIN DANCE","SUNNY DAY","CRUNCH","MIRROR COAT", "PSYCH UP","EXTREMESPEED","ANCIENTPOWER","SHADOW BALL", "FUTURE SIGHT","ROCK SMASH","WHIRLPOOL","BEAT UP", "FAKE OUT","UPROAR","STOCKPILE","SPIT UP", "SWALLOW","HEAT WAVE","HAIL","TORMENT", "FLATTER","WILL-O-WISP","MEMENTO","FACADE", "FOCUS PUNCH","SMELLINGSALT","FOLLOW ME","NATURE POWER", "CHARGE","TAUNT","HELPING HAND","TRICK", "ROLE PLAY","WISH","ASSIST","INGRAIN", "SUPERPOWER","MAGIC COAT","RECYCLE","REVENGE", "BRICK BREAK","YAWN","KNOCK OFF","ENDEAVOR", "ERUPTION","SKILL SWAP","IMPRISON","REFRESH", "GRUDGE","SNATCH","SECRET POWER","DIVE", "ARM THRUST","CAMOUFLAGE","TAIL GLOW","LUSTER PURGE", "MIST BALL","FEATHERDANCE","TEETER DANCE","BLAZE KICK", "MUD SPORT","ICE BALL","NEEDLE ARM","SLACK OFF", "HYPER VOICE","POISON FANG","CRUSH CLAW","BLAST BURN", "HYDRO CANNON","METEOR MASH","ASTONISH","WEATHER BALL", "AROMATHERAPY","FAKE TEARS","AIR CUTTER","OVERHEAT", "ODOR SLEUTH","ROCK TOMB","SILVER WIND","METAL SOUND", "GRASSWHISTLE","TICKLE","COSMIC POWER","WATER SPOUT", "SIGNAL BEAM","SHADOW PUNCH","EXTRASENSORY","SKY UPPERCUT", "SAND TOMB","SHEER COLD","MUDDY WATER","BULLET SEED", "AERIAL ACE","ICICLE SPEAR","IRON DEFENSE","BLOCK", "HOWL","DRAGON CLAW","FRENZY PLANT","BULK UP", "BOUNCE","MUD SHOT","POISON TAIL","COVET", "VOLT TACKLE","MAGICAL LEAF","WATER SPORT","CALM MIND", "LEAF BLADE","DRAGON DANCE","ROCK BLAST","SHOCK WAVE", "WATER PULSE","DOOM DESIRE","PSYCHO BOOST","ROOST", "GRAVITY","MIRACLE EYE","WAKE-UP SLAP","HAMMER ARM", "GYRO BALL","HEALING WISH","BRINE","NATURAL GIFT", "FEINT","PLUCK","TAILWIND","ACUPRESSURE", "METAL BURST","U-TURN","CLOSE COMBAT","PAYBACK", "ASSURANCE","EMBARGO","FLING","PSYCHO SHIFT", "TRUMP CARD","HEAL BLOCK","WRING OUT","POWER TRICK", "GASTRO ACID","LUCKY CHANT","ME FIRST","COPYCAT", "POWER SWAP","GUARD SWAP","PUNISHMENT","LAST RESORT", "WORRY SEED","SUCKER PUNCH","TOXIC SPIKES","HEART SWAP", "AQUA RING","MAGNET RISE","FLARE BLITZ","FORCE PALM", "AURA SPHERE","ROCK POLISH","POISON JAB","DARK PULSE", "NIGHT SLASH","AQUA TAIL","SEED BOMB","AIR SLASH", "X-SCISSOR","BUG BUZZ","DRAGON PULSE","DRAGON RUSH", "POWER GEM","DRAIN PUNCH","VACUUM WAVE","FOCUS BLAST", "ENERGY BALL","BRAVE BIRD","EARTH POWER","SWITCHEROO", "GIGA IMPACT","NASTY PLOT","BULLET PUNCH","AVALANCHE", "ICE SHARD","SHADOW CLAW","THUNDER FANG","ICE FANG", "FIRE FANG","SHADOW SNEAK","MUD BOMB","PSYCHO CUT", "ZEN HEADBUTT","MIRROR SHOT","FLASH CANNON","ROCK CLIMB", "DEFOG","TRICK ROOM","DRACO METEOR","DISCHARGE", "LAVA PLUME","LEAF STORM","POWER WHIP","ROCK WRECKER", "CROSS POISON","GUNK SHOT","IRON HEAD","MAGNET BOMB", "STONE EDGE","CAPTIVATE","STEALTH ROCK","GRASS KNOT", "CHATTER","JUDGMENT","BUG BITE","CHARGE BEAM", "WOOD HAMMER","AQUA JET","ATTACK ORDER","DEFEND ORDER", "HEAL ORDER","HEAD SMASH","DOUBLE HIT","ROAR OF TIME", "SPACIAL REND","LUNAR DANCE","CRUSH GRIP","MAGMA STORM", "DARK VOID","SEED FLARE","OMINOUS WIND","SHADOW FORCE" }; private static string[] WORDS_TYPES = new string[] { "NORMAL","FIGHTING","FLYING","POISON", // 964 "GROUND","ROCK","BUG","GHOST", "STEEL","???","FIRE","WATER", "GRASS","ELECTRIC","PSYCHIC","ICE", "DRAGON","DARK" }; private static string[] WORDS_ABILITIES = new string[] { "-","STENCH","DRIZZLE","SPEED BOOST", // 982 "BATTLE ARMOR","STURDY","DAMP","LIMBER", "SAND VEIL","STATIC","VOLT ABSORB","WATER ABSORB", "OBLIVIOUS","CLOUD NINE","COMPOUNDEYES","INSOMNIA", "COLOR CHANGE","IMMUNITY","FLASH FIRE","SHIELD DUST", "OWN TEMPO","SUCTION CUPS","INTIMIDATE","SHADOW TAG", "ROUGH SKIN","WONDER GUARD","LEVITATE","EFFECT SPORE", "SYNCHRONIZE","CLEAR BODY","NATURAL CURE","LIGHTNINGROD", "SERENE GRACE","SWIFT SWIM","CHLOROPHYLL","ILLUMINATE", "TRACE","HUGE POWER","POISON POINT","INNER FOCUS", "MAGMA ARMOR","WATER VEIL","MAGNET PULL","SOUNDPROOF", "RAIN DISH","SAND STREAM","PRESSURE","THICK FAT", "EARLY BIRD","FLAME BODY","RUN AWAY","KEEN EYE", "HYPER CUTTER","PICKUP","TRUANT","HUSTLE", "CUTE CHARM","PLUS","MINUS","FORECAST", "STICKY HOLD","SHED SKIN","GUTS","MARVEL SCALE", "LIQUID OOZE","OVERGROW","BLAZE","TORRENT", "SWARM","ROCK HEAD","DROUGHT","ARENA TRAP", "VITAL SPIRIT","WHITE SMOKE","PURE POWER","SHELL ARMOR", "AIR LOCK","TANGLED FEET","MOTOR DRIVE","RIVALRY", "STEADFAST","SNOW CLOAK","GLUTTONY","ANGER POINT", "UNBURDEN","HEATPROOF","SIMPLE","DRY SKIN", "DOWNLOAD","IRON FIST","POISON HEAL","ADAPTABILITY", "SKILL LINK","HYDRATION","SOLAR POWER","QUICK FEET", "NORMALIZE","SNIPER","MAGIC GUARD","NO GUARD", "STALL","TECHNICIAN","LEAF GUARD","KLUTZ", "MOLD BREAKER","SUPER LUCK","AFTERMATH","ANTICIPATION", "FOREWARN","UNAWARE","TINTED LENS","FILTER", "SLOW START","SCRAPPY","STORM DRAIN","ICE BODY", "SOLID ROCK","SNOW WARNING","HONEY GATHER","FRISK", "RECKLESS","MULTITYPE","FLOWER GIFT","BAD DREAMS" }; private static string[] WORDS_TRAINER = new string[] { "MATCH UP","NO. 1","PREPARATION","WINS", // 1106 "NO MATCH","SPIRIT","ACE CARD","COME ON", "ATTACK","SURRENDER","COURAGE","TALENT", "STRATEGY","MATCH","VICTORY","SENSE", "VERSUS","FIGHTS","POWER","CHALLENGE", "STRONG","TAKE IT EASY","FOE","GENIUS", "LEGEND","BATTLE","FIGHT","REVIVE", "POINTS","SERIOUS","LOSS","PARTNER", "INVINCIBLE","EASY","WEAK","EASY WIN", "MOVE","TRAINER" }; private static string[] WORDS_PEOPLE = new string[] { "OPPONENT","I","YOU","MOTHER", // 1144 "GRANDFATHER","UNCLE","FATHER","BOY", "ADULT","BROTHER","SISTER","GRANDMOTHER", "AUNT","PARENT","OLD MAN","ME", "GIRL","GAL","FAMILY","HER", "HIM","YOU","SIBLINGS","KIDS", "MR.","MS.","MYSELF","WHO", "FRIEND","ALLY","PERSON","KIDS", "I","EVERYONE","RIVAL","I", "I","BABY" }; private static string[] WORDS_GREETINGS = new string[] { "KONNICHIWA","HELLO","BONJOUR","CIAO", // 1182 "HALLO","HOLA","OH WELL","AAH", "AHAHA","HUH","THANKS","NO PROBLEM", "NOPE","YES","HERE GOES","LET’S GO", "HERE I COME","YEAH","WELCOME","URGH", "LET ME THINK","HMM","WHOA","WROOOAAR!", "WOW","SNICKER","CUTE LAUGH","UNBELIEVABLE", "CRIES","OK","AGREE","EH?", "BOO-HOO","HEHEHE","HEY","OH, YEAH", "OH WOW!","HEEEY","GREETINGS","OOPS", "WELL DONE","OH MY","EEK","YAAAH", "GIGGLE","GIVE ME","GWAHAHAHA","UGH", "SORRY","FORGIVE ME","I’M SORRY","HEY!", "GOOD-BYE","THANK YOU","I’VE ARRIVED","WEEP", "PARDON ME","SO SORRY","SEE YA","EXCUSE ME", "OKAY THEN","TUT","BLUSH","GO AHEAD", "CHEERS","HEY?","WHAT’S UP?","HUH?", "NO","SIGH","HI","YEP", "YEAH, YEAH","BYE-BYE","MEET YOU","HAHAHA", "AIYEEH","HIYAH","MUHAHAHA","LOL", "SNORT","HUMPH","HEY","HE-HE-HE", "HEH","HOHOHO","THERE YOU GO","OH, DEAR", "BYE FOR NOW","ANGRY","MUFUFU","MMM", "HELLO?","HI THERE","NO WAY","YAHOO", "YO","WELCOME","OK","REGARDS", "LALALA","YAY","WAIL","WOW", "BOO!","WAHAHA","..." }; private static string[] WORDS_LIFESTYLE = new string[] { "IDOL","TOMORROW","PLAYING","ANIME", // 1289 "JOB","SONG","HOME","MOVIE", "SWEETS","MONEY","POCKET MONEY","CHIT-CHAT", "TALK","BATH","PLAY HOUSE","TOYS", "MUSIC","CARDS","SHOPPING","CONVERSATION", "SCHOOL","CAMERA","VIEWING","SPECTATE", "ANNIVERSARY","YESTERDAY","TODAY","HABIT", "GROUP","GOURMET","GAME","WORD", "COLLECTION","STORE","COMPLETE","SERVICE", "MAGAZINE","WALK","WORK","SYSTEM", "BICYCLE","TRAINING","CLASS","LESSONS", "HOBBY","INFORMATION","SPORTS","DAILY LIFE", "TEACHER","SOFTWARE","SONGS","DIET", "TOURNAMENT","TREASURE","TRAVEL","BIRTHDAY", "DANCE","CHANNEL","FISHING","DATE", "LETTER","EVENT","DESIGN","DIGITAL", "TEST","DEPT. STORE","TELEVISION","TRAIN", "PHONE","ITEM","NAME","NEWS", "POPULARITY","STUFFED TOY","PARTY","COMPUTER", "FLOWERS","HERO","NAP","HEROINE", "FASHION","STUDY","ADVENTURE","BOARD", "BALL","BOOK","MACHINE","FESTIVAL", "COMICS","MAIL","MESSAGE","STORY", "PROMISE","HOLIDAY","DREAM","KINDERGARTEN", "PLANS","LIFE","RADIO","CRAZE", "VACATION","LOOKS","RENTAL","WORLD" }; private static string[] WORDS_FEELINGS = new string[] { "BEAUTY","DELIGHT","STRANGENESS","CLEVERNESS", // 1393 "DISAPPOINTED","COOLNESS","SADNESS","CUTENESS", "ANGER","HEALTHY","REGRET","HAPPINESS", "DEPRESSED","INCREDIBLE","LIKES","DISLIKE", "BORED","IMPORTANT","ALL RIGHT","ADORE", "TOUGHNESS","ENJOYMENT","USELESS","DROOLING", "EXCITED","SKILLFUL","TEARS","HATE", "ROFL","HAPPY","ENERGETIC","SURPRISE", "NERVOUS","WANT","SATISFIED","RARE", "MESSED UP","NO WAY","DANGER","LOVEY-DOVEY", "ANTICIPATION","SMILE","SUBTLE","RECOMMEND", "SIMPLE","NICE","DIFFICULT" }; private static string[] WORDS_TOUGH = new string[] { "EARTH TONES","IMPLANT","GOLDEN RATIO","OMNIBUS", // 1440 "STARBOARD","MONEY RATE","RESOLUTION","CADENZA", "EDUCATION","CUBISM","CROSS-STITCH","ARTERY", "BONE DENSITY","GOMMAGE","STREAMING","CONDUCTIVITY", "COPYRIGHT","TWO-STEP","CONTOUR","NEUTRINO", "HOWLING","SPREADSHEET","GMT","IRRITABILITY", "FRACTALS","FLAMBE","STOCK PRICES","PH BALANCE", "VECTOR","POLYPHENOL","UBIQUITOUS","REM SLEEP" }; private static string[] WORDS_UNION = new string[] { "SINGLE","DOUBLE","MIX BATTLE","MULTI BATTLE", // 1472 "LEVEL 50","LEVEL 100","COLOSSEUM","POKéMON", "DRAWING","RECORD","GOTCHA","CHAT", "FRIEND CODE","CONNECTION","VOICE CHAT","WI-FI", "UNDERGROUND","UNION","POFFIN","CONTEST", "BATTLE TOWER","GTS","SECRET BASE" }; #endregion } } ================================================ FILE: library/Support/TrendyPhrase5.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PkmnFoundations.Support { public class TrendyPhrase5 : TrendyPhraseBase { public TrendyPhrase5(byte[] data) : base(data) { } public TrendyPhrase5(ushort mood, ushort index, ushort word1, ushort word2) : base(Pack(mood, index, word1, word2)) { } public override string Render(string wordFormat) { return RenderPhrase(Data, wordFormat); } public static string RenderPhrase(byte[] data, string wordFormat) { // todo: move me to TrendyPhraseBase, make RenderWord virtual if (data == null) throw new ArgumentNullException(); if (data.Length != 8) throw new ArgumentException(); ushort mood = BitConverter.ToUInt16(data, 0); ushort index = BitConverter.ToUInt16(data, 2); ushort word1 = BitConverter.ToUInt16(data, 4); ushort word2 = BitConverter.ToUInt16(data, 6); // moods higher than 6 seem to say "no answer" but indexes higher than 20 are blank. if (mood >= 7) return ""; if (index >= 21) return ""; return string.Format(PHRASES[mood, index], string.Format(wordFormat, RenderWord(word1)), string.Format(wordFormat, RenderWord(word2)) ); } public static string RenderWord(ushort word) { // todo: There's a certain list of banned spoiler words like // attacks from BW2 which should be turned into POKÉMON. if (word < 652) return WORDS_POKEMON[word]; if (word < 1212) return WORDS_MOVES[word - 652]; if (word < 1229) return WORDS_TYPES[word - 1212]; if (word < 1394) return WORDS_ABILITIES[word - 1229]; if (word < 1438) return WORDS_TRAINER[word - 1394]; if (word < 1476) return WORDS_PEOPLE[word - 1438]; if (word < 1524) return WORDS_GREETINGS[word - 1476]; if (word < 1627) return WORDS_LIFESTYLE[word - 1524]; if (word < 1674) return WORDS_FEELINGS[word - 1627]; if (word < 1706) return WORDS_TERM[word - 1674]; if (word < 1732) return WORDS_CONNECTION[word - 1706]; if (word < 1742) return WORDS_ANIMATED[word - 1732]; if (word < 1803) return WORDS_VOICE[word - 1742]; if (word == 65535) return ""; // special case for unfilled in word = blank return "POKÉMON"; } public TrendyPhrase5 Clone() { return new TrendyPhrase5(Data); } #region String tables // todo: i18n // Special thanks to http://projectpokemon.org/rawdb/black2/msg.php // for their string table dumps. // a/0/0/2/170 through /176 private static string[,] PHRASES = new string[,] { { // Mood 0: Other /171 "Hello!\n{0}!", // 0 "I am {0}!\nI'm pleased to meet you.", // 1 "I love {0}!\nI love {1}, too!", // 2 "My favorite {0} is\n{1}!", // 3 "What's your favorite\n{0}?", // 4 "I can do anything for\n{0}!", // 5 "Is {0}\n{1}?", // 6 "What do you think of\n{0}?", // 7 "Do you think {0}\ncan {1}?", // 8 "{0} is so\n{1}!", // 9 "{0} bothers me.", // 10 "After all, it's {0},\nisn't it?", // 11 "{0} is the real\n{1}!", // 12 "Did you know that {0}\nis {1}?", // 13 "{0} is the reason\nfor {1}.", // 14 "Have you heard of\n{0}?", // 15 "{0} is actually\n{1}.", // 16 "Recently, {0}\nseems {1}.", // 17 "I wonder if\n{0} is yummy...", // 18 "I never miss {0}.\nIt's part of what I do every day.", // 19 "", }, { // Mood 1: Start of battle /173 "Please!\n{0}", // 0 "Go! {0}!", // 1 "I'll battle with\n{0}!", // 2 "{0} is\n{1}, right?", // 3 "{0}, I'm going\nwith {1}!", // 4 "In comes {0}.", // 5 "Watch my {0} power\ntake care of {1}!", // 6 "Now {0}\nbegins!", // 7 "I'll show you my\n{0} strategy!", // 8 "I'll shock you with\n{0}!", // 9 "{0}, I see...\nGo, {1}!", // 10 "Ta-da!\nHere comes {0}!", // 11 "I don't think I'll\never lose to {0}!", // 12 "{0}!\n{1} is here!", // 13 "Good luck,\n{0}!", // 14 "Behold my {0}\n{1}!", // 15 "The power of {0}!\nLet me show you!", // 16 "You'll choose {0}\nif I choose {1}, right?", // 17 "I beg you, {0}.\nPlease go with {1}!", // 18 "May {0} safely\nland on {0}!", // 19 "", }, { // Mood 2: Victory /176 "I win!\n{0}!", // 0 "I owe my victory\nto {0}!", // 1 "{0} is strong,\nisn't it?", // 2 "It's {0}\n{1} after all!", // 3 "When it comes to {0},\nmy choice is always {1}!", // 4 "Victory in a\n{0} battle!", // 5 "Yay, {0}!\n{1}!", // 6 "Sorry, it's {0}\n{1}.", // 7 "{0}!\nThank you!", // 8 "The way I feel now is\n{0}!", // 9 "{0} sure is\n{1}!", // 10 "It's all thanks to\n{0}.", // 11 "{0} is the toughest!", // 12 "{0}?\nWow, I'm so glad!", // 13 "{0}?\nThat sounds good!", // 14 "I have no trouble\ndealing with {0}.", // 15 "{0} is so much fun.", // 16 "Huh?\n{0}?!", // 17 "The power of {0}\nis awesome!", // 18 "Everyone!\n{0}!", // 19 "", }, { // Mood 3: Defeat /170 "You win...\n{0}!", // 0 "{0} is\nreally impressive.", // 1 "Waaah! {0}!", // 2 "I want to go home with\n{0}...", // 3 "{0}!\n{1}!", // 4 "I see {0}\nright in front of me!", // 5 "{0}?\nI didn't see that coming!", // 6 "I was confident about\n{0}, too.", // 7 "You're {0},\naren't you?", // 8 "{0}!\nCan't be anything else but.", // 9 "I want to be like {0}!", // 10 "It might be\n{0} already...", // 11 "I think {0}\nshould do.", // 12 "The way I feel now is\n{0}...", // 13 "{0} won't work!", // 14 "Nothing beats {0}!", // 15 "My head's filled with only\n{0} now!", // 16 "Is it because {0}\nwas lacking?", // 17 "Isn't {0}\n{1}?", // 18 "Aww... That's really\n{0}...", // 19 "", }, { // Mood 4: Other /175 "Yo!\nI'm {1}.", // 0 "Glad to meet you!\nI love {0}!", // 1 "Do you like {0}?", // 2 "Let's draw! I want to draw\n{0}!", // 3 "Let's battle!\nI say {0}!", // 4 "I'm a {0} Trainer!\nPlease battle me!", // 5 "Let's have a chat!\nHow about {0}?", // 6 "Please trade!\nI want a {0}!", // 7 "Please trade!\nI'm offering {0}!", // 8 "Want to trade {0}?\nHere's a hint: {1}!", // 9 "Will you join me\nfor {0}?", // 10 "Anyone want to\n{0}?", // 11 "I want to {0}\nwith {1}!", // 12 "Let's go to {0}\nby {1}!", // 13 "OK!", // 14 "{0}?\nI got it!", // 15 "{0}?\nHold on!", // 16 "I don't want to\n{0}...", // 17 "That was fun! I hope we can\n{0} again sometime.", // 18 "See ya!\n{0}!", // 19 "", }, { // Mood 5: Greetings /172 New to GenV. Seems to be locked by default? "Glad to meet you!\nI am {0}!", // 0 "I'm a {0}-loving\n{1} Trainer.", // 1 "Let's {0} sometime.\nKeep in touch!", // 2 "{0} is the best!\nI love it!", // 3 "It's great because it's\n{0}. Don't you agree?", // 4 "Tell me your favorite\n{0}.", // 5 "Hi!\nDo you know {0}?", // 6 "It's very {0}\nand {1}!", // 7 "Let's {0} soon!", // 8 "Thank you for taking your time\nwith {0}.", // 9 "It was so {0}.\nI was moved!", // 10 "What do you think of\n{0}?", // 11 "It's {0},\nif you ask me.", // 12 "It bothers us, doesn't it?\nI'm talking about {0}.", // 13 "Do you know what\nthey call {0}?", // 14 "This {0} is\nsurprisingly {1}!", // 15 "{0} sure is something.\nYou should try it!", // 16 "Thank you for taking your time\nwith {0}.", // 17 "{0} is\n{1}, don't you think?", // 18 "That means {0}.\nThanks!", // 19 "We should {0} together\nagain. {1}!", // 20 }, { // Mood 6: Placeholder to hold a single trendy word "{0}", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", }, }; private static string[] WORDS_POKEMON = new string[] { "POKÉMON","BULBASAUR","IVYSAUR","VENUSAUR", // 0 "CHARMANDER","CHARMELEON","CHARIZARD","SQUIRTLE", "WARTORTLE","BLASTOISE","CATERPIE","METAPOD", "BUTTERFREE","WEEDLE","KAKUNA","BEEDRILL", "PIDGEY","PIDGEOTTO","PIDGEOT","RATTATA", "RATICATE","SPEAROW","FEAROW","EKANS", "ARBOK","PIKACHU","RAICHU","SANDSHREW", "SANDSLASH","NIDORAN♀","NIDORINA","NIDOQUEEN", "NIDORAN♂","NIDORINO","NIDOKING","CLEFAIRY", "CLEFABLE","VULPIX","NINETALES","JIGGLYPUFF", "WIGGLYTUFF","ZUBAT","GOLBAT","ODDISH", "GLOOM","VILEPLUME","PARAS","PARASECT", "VENONAT","VENOMOTH","DIGLETT","DUGTRIO", "MEOWTH","PERSIAN","PSYDUCK","GOLDUCK", "MANKEY","PRIMEAPE","GROWLITHE","ARCANINE", "POLIWAG","POLIWHIRL","POLIWRATH","ABRA", "KADABRA","ALAKAZAM","MACHOP","MACHOKE", "MACHAMP","BELLSPROUT","WEEPINBELL","VICTREEBEL", "TENTACOOL","TENTACRUEL","GEODUDE","GRAVELER", "GOLEM","PONYTA","RAPIDASH","SLOWPOKE", "SLOWBRO","MAGNEMITE","MAGNETON","FARFETCH'D", "DODUO","DODRIO","SEEL","DEWGONG", "GRIMER","MUK","SHELLDER","CLOYSTER", "GASTLY","HAUNTER","GENGAR","ONIX", "DROWZEE","HYPNO","KRABBY","KINGLER", "VOLTORB","ELECTRODE","EXEGGCUTE","EXEGGUTOR", "CUBONE","MAROWAK","HITMONLEE","HITMONCHAN", "LICKITUNG","KOFFING","WEEZING","RHYHORN", "RHYDON","CHANSEY","TANGELA","KANGASKHAN", "HORSEA","SEADRA","GOLDEEN","SEAKING", "STARYU","STARMIE","MR. MIME","SCYTHER", "JYNX","ELECTABUZZ","MAGMAR","PINSIR", "TAUROS","MAGIKARP","GYARADOS","LAPRAS", "DITTO","EEVEE","VAPOREON","JOLTEON", "FLAREON","PORYGON","OMANYTE","OMASTAR", "KABUTO","KABUTOPS","AERODACTYL","SNORLAX", "ARTICUNO","ZAPDOS","MOLTRES","DRATINI", "DRAGONAIR","DRAGONITE","MEWTWO","MEW", "CHIKORITA","BAYLEEF","MEGANIUM","CYNDAQUIL", "QUILAVA","TYPHLOSION","TOTODILE","CROCONAW", "FERALIGATR","SENTRET","FURRET","HOOTHOOT", "NOCTOWL","LEDYBA","LEDIAN","SPINARAK", "ARIADOS","CROBAT","CHINCHOU","LANTURN", "PICHU","CLEFFA","IGGLYBUFF","TOGEPI", "TOGETIC","NATU","XATU","MAREEP", "FLAAFFY","AMPHAROS","BELLOSSOM","MARILL", "AZUMARILL","SUDOWOODO","POLITOED","HOPPIP", "SKIPLOOM","JUMPLUFF","AIPOM","SUNKERN", "SUNFLORA","YANMA","WOOPER","QUAGSIRE", "ESPEON","UMBREON","MURKROW","SLOWKING", "MISDREAVUS","UNOWN","WOBBUFFET","GIRAFARIG", "PINECO","FORRETRESS","DUNSPARCE","GLIGAR", "STEELIX","SNUBBULL","GRANBULL","QWILFISH", "SCIZOR","SHUCKLE","HERACROSS","SNEASEL", "TEDDIURSA","URSARING","SLUGMA","MAGCARGO", "SWINUB","PILOSWINE","CORSOLA","REMORAID", "OCTILLERY","DELIBIRD","MANTINE","SKARMORY", "HOUNDOUR","HOUNDOOM","KINGDRA","PHANPY", "DONPHAN","PORYGON2","STANTLER","SMEARGLE", "TYROGUE","HITMONTOP","SMOOCHUM","ELEKID", "MAGBY","MILTANK","BLISSEY","RAIKOU", "ENTEI","SUICUNE","LARVITAR","PUPITAR", "TYRANITAR","LUGIA","HO-OH","CELEBI", "TREECKO","GROVYLE","SCEPTILE","TORCHIC", "COMBUSKEN","BLAZIKEN","MUDKIP","MARSHTOMP", "SWAMPERT","POOCHYENA","MIGHTYENA","ZIGZAGOON", "LINOONE","WURMPLE","SILCOON","BEAUTIFLY", "CASCOON","DUSTOX","LOTAD","LOMBRE", "LUDICOLO","SEEDOT","NUZLEAF","SHIFTRY", "TAILLOW","SWELLOW","WINGULL","PELIPPER", "RALTS","KIRLIA","GARDEVOIR","SURSKIT", "MASQUERAIN","SHROOMISH","BRELOOM","SLAKOTH", "VIGOROTH","SLAKING","NINCADA","NINJASK", "SHEDINJA","WHISMUR","LOUDRED","EXPLOUD", "MAKUHITA","HARIYAMA","AZURILL","NOSEPASS", "SKITTY","DELCATTY","SABLEYE","MAWILE", "ARON","LAIRON","AGGRON","MEDITITE", "MEDICHAM","ELECTRIKE","MANECTRIC","PLUSLE", "MINUN","VOLBEAT","ILLUMISE","ROSELIA", "GULPIN","SWALOT","CARVANHA","SHARPEDO", "WAILMER","WAILORD","NUMEL","CAMERUPT", "TORKOAL","SPOINK","GRUMPIG","SPINDA", "TRAPINCH","VIBRAVA","FLYGON","CACNEA", "CACTURNE","SWABLU","ALTARIA","ZANGOOSE", "SEVIPER","LUNATONE","SOLROCK","BARBOACH", "WHISCASH","CORPHISH","CRAWDAUNT","BALTOY", "CLAYDOL","LILEEP","CRADILY","ANORITH", "ARMALDO","FEEBAS","MILOTIC","CASTFORM", "KECLEON","SHUPPET","BANETTE","DUSKULL", "DUSCLOPS","TROPIUS","CHIMECHO","ABSOL", "WYNAUT","SNORUNT","GLALIE","SPHEAL", "SEALEO","WALREIN","CLAMPERL","HUNTAIL", "GOREBYSS","RELICANTH","LUVDISC","BAGON", "SHELGON","SALAMENCE","BELDUM","METANG", "METAGROSS","REGIROCK","REGICE","REGISTEEL", "LATIAS","LATIOS","KYOGRE","GROUDON", "RAYQUAZA","JIRACHI","DEOXYS","TURTWIG", "GROTLE","TORTERRA","CHIMCHAR","MONFERNO", "INFERNAPE","PIPLUP","PRINPLUP","EMPOLEON", "STARLY","STARAVIA","STARAPTOR","BIDOOF", "BIBAREL","KRICKETOT","KRICKETUNE","SHINX", "LUXIO","LUXRAY","BUDEW","ROSERADE", "CRANIDOS","RAMPARDOS","SHIELDON","BASTIODON", "BURMY","WORMADAM","MOTHIM","COMBEE", "VESPIQUEN","PACHIRISU","BUIZEL","FLOATZEL", "CHERUBI","CHERRIM","SHELLOS","GASTRODON", "AMBIPOM","DRIFLOON","DRIFBLIM","BUNEARY", "LOPUNNY","MISMAGIUS","HONCHKROW","GLAMEOW", "PURUGLY","CHINGLING","STUNKY","SKUNTANK", "BRONZOR","BRONZONG","BONSLY","MIME JR.", "HAPPINY","CHATOT","SPIRITOMB","GIBLE", "GABITE","GARCHOMP","MUNCHLAX","RIOLU", "LUCARIO","HIPPOPOTAS","HIPPOWDON","SKORUPI", "DRAPION","CROAGUNK","TOXICROAK","CARNIVINE", "FINNEON","LUMINEON","MANTYKE","SNOVER", "ABOMASNOW","WEAVILE","MAGNEZONE","LICKILICKY", "RHYPERIOR","TANGROWTH","ELECTIVIRE","MAGMORTAR", "TOGEKISS","YANMEGA","LEAFEON","GLACEON", "GLISCOR","MAMOSWINE","PORYGON-Z","GALLADE", "PROBOPASS","DUSKNOIR","FROSLASS","ROTOM", "UXIE","MESPRIT","AZELF","DIALGA", "PALKIA","HEATRAN","REGIGIGAS","GIRATINA", "CRESSELIA","PHIONE","MANAPHY","DARKRAI", "SHAYMIN","ARCEUS","VICTINI","SNIVY", "SERVINE","SERPERIOR","TEPIG","PIGNITE", "EMBOAR","OSHAWOTT","DEWOTT","SAMUROTT", "PATRAT","WATCHOG","LILLIPUP","HERDIER", "STOUTLAND","PURRLOIN","LIEPARD","PANSAGE", "SIMISAGE","PANSEAR","SIMISEAR","PANPOUR", "SIMIPOUR","MUNNA","MUSHARNA","PIDOVE", "TRANQUILL","UNFEZANT","BLITZLE","ZEBSTRIKA", "ROGGENROLA","BOLDORE","GIGALITH","WOOBAT", "SWOOBAT","DRILBUR","EXCADRILL","AUDINO", "TIMBURR","GURDURR","CONKELDURR","TYMPOLE", "PALPITOAD","SEISMITOAD","THROH","SAWK", "SEWADDLE","SWADLOON","LEAVANNY","VENIPEDE", "WHIRLIPEDE","SCOLIPEDE","COTTONEE","WHIMSICOTT", "PETILIL","LILLIGANT","BASCULIN","SANDILE", "KROKOROK","KROOKODILE","DARUMAKA","DARMANITAN", "MARACTUS","DWEBBLE","CRUSTLE","SCRAGGY", "SCRAFTY","SIGILYPH","YAMASK","COFAGRIGUS", "TIRTOUGA","CARRACOSTA","ARCHEN","ARCHEOPS", "TRUBBISH","GARBODOR","ZORUA","ZOROARK", "MINCCINO","CINCCINO","GOTHITA","GOTHORITA", "GOTHITELLE","SOLOSIS","DUOSION","REUNICLUS", "DUCKLETT","SWANNA","VANILLITE","VANILLISH", "VANILLUXE","DEERLING","SAWSBUCK","EMOLGA", "KARRABLAST","ESCAVALIER","FOONGUS","AMOONGUSS", "FRILLISH","JELLICENT","ALOMOMOLA","JOLTIK", "GALVANTULA","FERROSEED","FERROTHORN","KLINK", "KLANG","KLINKLANG","TYNAMO","EELEKTRIK", "EELEKTROSS","ELGYEM","BEHEEYEM","LITWICK", "LAMPENT","CHANDELURE","AXEW","FRAXURE", "HAXORUS","CUBCHOO","BEARTIC","CRYOGONAL", "SHELMET","ACCELGOR","STUNFISK","MIENFOO", "MIENSHAO","DRUDDIGON","GOLETT","GOLURK", "PAWNIARD","BISHARP","BOUFFALANT","RUFFLET", "BRAVIARY","VULLABY","MANDIBUZZ","HEATMOR", "DURANT","DEINO","ZWEILOUS","HYDREIGON", "LARVESTA","VOLCARONA","COBALION","TERRAKION", "VIRIZION","TORNADUS","THUNDURUS","RESHIRAM", "ZEKROM","LANDORUS","KYUREM","KELDEO", "MELOETTA","GENESECT","EGG","BAD EGG" }; private static string[] WORDS_MOVES = new[] { "-----","POUND","KARATE CHOP","DOUBLESLAP", // 652 "COMET PUNCH","MEGA PUNCH","PAY DAY","FIRE PUNCH", "ICE PUNCH","THUNDERPUNCH","SCRATCH","VICEGRIP", "GUILLOTINE","RAZOR WIND","SWORDS DANCE","CUT", "GUST","WING ATTACK","WHIRLWIND","FLY", "BIND","SLAM","VINE WHIP","STOMP", "DOUBLE KICK","MEGA KICK","JUMP KICK","ROLLING KICK", "SAND-ATTACK","HEADBUTT","HORN ATTACK","FURY ATTACK", "HORN DRILL","TACKLE","BODY SLAM","WRAP", "TAKE DOWN","THRASH","DOUBLE-EDGE","TAIL WHIP", "POISON STING","TWINEEDLE","PIN MISSILE","LEER", "BITE","GROWL","ROAR","SING", "SUPERSONIC","SONICBOOM","DISABLE","ACID", "EMBER","FLAMETHROWER","MIST","WATER GUN", "HYDRO PUMP","SURF","ICE BEAM","BLIZZARD", "PSYBEAM","BUBBLEBEAM","AURORA BEAM","HYPER BEAM", "PECK","DRILL PECK","SUBMISSION","LOW KICK", "COUNTER","SEISMIC TOSS","STRENGTH","ABSORB", "MEGA DRAIN","LEECH SEED","GROWTH","RAZOR LEAF", "SOLARBEAM","POISONPOWDER","STUN SPORE","SLEEP POWDER", "PETAL DANCE","STRING SHOT","DRAGON RAGE","FIRE SPIN", "THUNDERSHOCK","THUNDERBOLT","THUNDER WAVE","THUNDER", "ROCK THROW","EARTHQUAKE","FISSURE","DIG", "TOXIC","CONFUSION","PSYCHIC","HYPNOSIS", "MEDITATE","AGILITY","QUICK ATTACK","RAGE", "TELEPORT","NIGHT SHADE","MIMIC","SCREECH", "DOUBLE TEAM","RECOVER","HARDEN","MINIMIZE", "SMOKESCREEN","CONFUSE RAY","WITHDRAW","DEFENSE CURL", "BARRIER","LIGHT SCREEN","HAZE","REFLECT", "FOCUS ENERGY","BIDE","METRONOME","MIRROR MOVE", "SELFDESTRUCT","EGG BOMB","LICK","SMOG", "SLUDGE","BONE CLUB","FIRE BLAST","WATERFALL", "CLAMP","SWIFT","SKULL BASH","SPIKE CANNON", "CONSTRICT","AMNESIA","KINESIS","SOFTBOILED", "HI JUMP KICK","GLARE","DREAM EATER","POISON GAS", "BARRAGE","LEECH LIFE","LOVELY KISS","SKY ATTACK", "TRANSFORM","BUBBLE","DIZZY PUNCH","SPORE", "FLASH","PSYWAVE","SPLASH","ACID ARMOR", "CRABHAMMER","EXPLOSION","FURY SWIPES","BONEMERANG", "REST","ROCK SLIDE","HYPER FANG","SHARPEN", "CONVERSION","TRI ATTACK","SUPER FANG","SLASH", "SUBSTITUTE","STRUGGLE","SKETCH","TRIPLE KICK", "THIEF","SPIDER WEB","MIND READER","NIGHTMARE", "FLAME WHEEL","SNORE","CURSE","FLAIL", "CONVERSION 2","AEROBLAST","COTTON SPORE","REVERSAL", "SPITE","POWDER SNOW","PROTECT","MACH PUNCH", "SCARY FACE","FAINT ATTACK","SWEET KISS","BELLY DRUM", "SLUDGE BOMB","MUD-SLAP","OCTAZOOKA","SPIKES", "ZAP CANNON","FORESIGHT","DESTINY BOND","PERISH SONG", "ICY WIND","DETECT","BONE RUSH","LOCK-ON", "OUTRAGE","SANDSTORM","GIGA DRAIN","ENDURE", "CHARM","ROLLOUT","FALSE SWIPE","SWAGGER", "MILK DRINK","SPARK","FURY CUTTER","STEEL WING", "MEAN LOOK","ATTRACT","SLEEP TALK","HEAL BELL", "RETURN","PRESENT","FRUSTRATION","SAFEGUARD", "PAIN SPLIT","SACRED FIRE","MAGNITUDE","DYNAMICPUNCH", "MEGAHORN","DRAGONBREATH","BATON PASS","ENCORE", "PURSUIT","RAPID SPIN","SWEET SCENT","IRON TAIL", "METAL CLAW","VITAL THROW","MORNING SUN","SYNTHESIS", "MOONLIGHT","HIDDEN POWER","CROSS CHOP","TWISTER", "RAIN DANCE","SUNNY DAY","CRUNCH","MIRROR COAT", "PSYCH UP","EXTREMESPEED","ANCIENTPOWER","SHADOW BALL", "FUTURE SIGHT","ROCK SMASH","WHIRLPOOL","BEAT UP", "FAKE OUT","UPROAR","STOCKPILE","SPIT UP", "SWALLOW","HEAT WAVE","HAIL","TORMENT", "FLATTER","WILL-O-WISP","MEMENTO","FACADE", "FOCUS PUNCH","SMELLINGSALT","FOLLOW ME","NATURE POWER", "CHARGE","TAUNT","HELPING HAND","TRICK", "ROLE PLAY","WISH","ASSIST","INGRAIN", "SUPERPOWER","MAGIC COAT","RECYCLE","REVENGE", "BRICK BREAK","YAWN","KNOCK OFF","ENDEAVOR", "ERUPTION","SKILL SWAP","IMPRISON","REFRESH", "GRUDGE","SNATCH","SECRET POWER","DIVE", "ARM THRUST","CAMOUFLAGE","TAIL GLOW","LUSTER PURGE", "MIST BALL","FEATHERDANCE","TEETER DANCE","BLAZE KICK", "MUD SPORT","ICE BALL","NEEDLE ARM","SLACK OFF", "HYPER VOICE","POISON FANG","CRUSH CLAW","BLAST BURN", "HYDRO CANNON","METEOR MASH","ASTONISH","WEATHER BALL", "AROMATHERAPY","FAKE TEARS","AIR CUTTER","OVERHEAT", "ODOR SLEUTH","ROCK TOMB","SILVER WIND","METAL SOUND", "GRASSWHISTLE","TICKLE","COSMIC POWER","WATER SPOUT", "SIGNAL BEAM","SHADOW PUNCH","EXTRASENSORY","SKY UPPERCUT", "SAND TOMB","SHEER COLD","MUDDY WATER","BULLET SEED", "AERIAL ACE","ICICLE SPEAR","IRON DEFENSE","BLOCK", "HOWL","DRAGON CLAW","FRENZY PLANT","BULK UP", "BOUNCE","MUD SHOT","POISON TAIL","COVET", "VOLT TACKLE","MAGICAL LEAF","WATER SPORT","CALM MIND", "LEAF BLADE","DRAGON DANCE","ROCK BLAST","SHOCK WAVE", "WATER PULSE","DOOM DESIRE","PSYCHO BOOST","ROOST", "GRAVITY","MIRACLE EYE","WAKE-UP SLAP","HAMMER ARM", "GYRO BALL","HEALING WISH","BRINE","NATURAL GIFT", "FEINT","PLUCK","TAILWIND","ACUPRESSURE", "METAL BURST","U-TURN","CLOSE COMBAT","PAYBACK", "ASSURANCE","EMBARGO","FLING","PSYCHO SHIFT", "TRUMP CARD","HEAL BLOCK","WRING OUT","POWER TRICK", "GASTRO ACID","LUCKY CHANT","ME FIRST","COPYCAT", "POWER SWAP","GUARD SWAP","PUNISHMENT","LAST RESORT", "WORRY SEED","SUCKER PUNCH","TOXIC SPIKES","HEART SWAP", "AQUA RING","MAGNET RISE","FLARE BLITZ","FORCE PALM", "AURA SPHERE","ROCK POLISH","POISON JAB","DARK PULSE", "NIGHT SLASH","AQUA TAIL","SEED BOMB","AIR SLASH", "X-SCISSOR","BUG BUZZ","DRAGON PULSE","DRAGON RUSH", "POWER GEM","DRAIN PUNCH","VACUUM WAVE","FOCUS BLAST", "ENERGY BALL","BRAVE BIRD","EARTH POWER","SWITCHEROO", "GIGA IMPACT","NASTY PLOT","BULLET PUNCH","AVALANCHE", "ICE SHARD","SHADOW CLAW","THUNDER FANG","ICE FANG", "FIRE FANG","SHADOW SNEAK","MUD BOMB","PSYCHO CUT", "ZEN HEADBUTT","MIRROR SHOT","FLASH CANNON","ROCK CLIMB", "DEFOG","TRICK ROOM","DRACO METEOR","DISCHARGE", "LAVA PLUME","LEAF STORM","POWER WHIP","ROCK WRECKER", "CROSS POISON","GUNK SHOT","IRON HEAD","MAGNET BOMB", "STONE EDGE","CAPTIVATE","STEALTH ROCK","GRASS KNOT", "CHATTER","JUDGMENT","BUG BITE","CHARGE BEAM", "WOOD HAMMER","AQUA JET","ATTACK ORDER","DEFEND ORDER", "HEAL ORDER","HEAD SMASH","DOUBLE HIT","ROAR OF TIME", "SPACIAL REND","LUNAR DANCE","CRUSH GRIP","MAGMA STORM", "DARK VOID","SEED FLARE","OMINOUS WIND","SHADOW FORCE", "HONE CLAWS","WIDE GUARD","GUARD SPLIT","POWER SPLIT", "WONDER ROOM","PSYSHOCK","VENOSHOCK","AUTOTOMIZE", "RAGE POWDER","TELEKINESIS","MAGIC ROOM","SMACK DOWN", "STORM THROW","FLAME BURST","SLUDGE WAVE","QUIVER DANCE", "HEAVY SLAM","SYNCHRONOISE","ELECTRO BALL","SOAK", "FLAME CHARGE","COIL","LOW SWEEP","ACID SPRAY", "FOUL PLAY","SIMPLE BEAM","ENTRAINMENT","AFTER YOU", "ROUND","ECHOED VOICE","CHIP AWAY","CLEAR SMOG", "STORED POWER","QUICK GUARD","ALLY SWITCH","SCALD", "SHELL SMASH","HEAL PULSE","HEX","SKY DROP", "SHIFT GEAR","CIRCLE THROW","INCINERATE","QUASH", "ACROBATICS","REFLECT TYPE","RETALIATE","FINAL GAMBIT", "BESTOW","INFERNO","WATER PLEDGE","FIRE PLEDGE", "GRASS PLEDGE","VOLT SWITCH","STRUGGLE BUG","BULLDOZE", "FROST BREATH","DRAGON TAIL","WORK UP","ELECTROWEB", "WILD CHARGE","DRILL RUN","DUAL CHOP","HEART STAMP", "HORN LEECH","SACRED SWORD","RAZOR SHELL","HEAT CRASH", "LEAF TORNADO","STEAMROLLER","COTTON GUARD","NIGHT DAZE", "PSYSTRIKE","TAIL SLAP","HURRICANE","HEAD CHARGE", "GEAR GRIND","SEARING SHOT","TECHNO BLAST","RELIC SONG", "SECRET SWORD","GLACIATE","BOLT STRIKE","BLUE FLARE", "FIERY DANCE","FREEZE SHOCK","ICE BURN","SNARL", "ICICLE CRASH","V-CREATE","FUSION FLARE","FUSION BOLT" }; private static string[] WORDS_TYPES = new string[] { "NORMAL","FIGHTING","FLYING","POISON", // 1212 "GROUND","ROCK","BUG","GHOST", "STEEL","FIRE","WATER","GRASS", "ELECTRIC","PSYCHIC","ICE","DRAGON", "DARK" }; private static string[] WORDS_ABILITIES = new string[] { "-","STENCH","DRIZZLE","SPEED BOOST", // 1229 "BATTLE ARMOR","STURDY","DAMP","LIMBER", "SAND VEIL","STATIC","VOLT ABSORB","WATER ABSORB", "OBLIVIOUS","CLOUD NINE","COMPOUNDEYES","INSOMNIA", "COLOR CHANGE","IMMUNITY","FLASH FIRE","SHIELD DUST", "OWN TEMPO","SUCTION CUPS","INTIMIDATE","SHADOW TAG", "ROUGH SKIN","WONDER GUARD","LEVITATE","EFFECT SPORE", "SYNCHRONIZE","CLEAR BODY","NATURAL CURE","LIGHTNINGROD", "SERENE GRACE","SWIFT SWIM","CHLOROPHYLL","ILLUMINATE", "TRACE","HUGE POWER","POISON POINT","INNER FOCUS", "MAGMA ARMOR","WATER VEIL","MAGNET PULL","SOUNDPROOF", "RAIN DISH","SAND STREAM","PRESSURE","THICK FAT", "EARLY BIRD","FLAME BODY","RUN AWAY","KEEN EYE", "HYPER CUTTER","PICKUP","TRUANT","HUSTLE", "CUTE CHARM","PLUS","MINUS","FORECAST", "STICKY HOLD","SHED SKIN","GUTS","MARVEL SCALE", "LIQUID OOZE","OVERGROW","BLAZE","TORRENT", "SWARM","ROCK HEAD","DROUGHT","ARENA TRAP", "VITAL SPIRIT","WHITE SMOKE","PURE POWER","SHELL ARMOR", "AIR LOCK","TANGLED FEET","MOTOR DRIVE","RIVALRY", "STEADFAST","SNOW CLOAK","GLUTTONY","ANGER POINT", "UNBURDEN","HEATPROOF","SIMPLE","DRY SKIN", "DOWNLOAD","IRON FIST","POISON HEAL","ADAPTABILITY", "SKILL LINK","HYDRATION","SOLAR POWER","QUICK FEET", "NORMALIZE","SNIPER","MAGIC GUARD","NO GUARD", "STALL","TECHNICIAN","LEAF GUARD","KLUTZ", "MOLD BREAKER","SUPER LUCK","AFTERMATH","ANTICIPATION", "FOREWARN","UNAWARE","TINTED LENS","FILTER", "SLOW START","SCRAPPY","STORM DRAIN","ICE BODY", "SOLID ROCK","SNOW WARNING","HONEY GATHER","FRISK", "RECKLESS","MULTITYPE","FLOWER GIFT","BAD DREAMS", "PICKPOCKET","SHEER FORCE","CONTRARY","UNNERVE", "DEFIANT","DEFEATIST","CURSED BODY","HEALER", "FRIEND GUARD","WEAK ARMOR","HEAVY METAL","LIGHT METAL", "MULTISCALE","TOXIC BOOST","FLARE BOOST","HARVEST", "TELEPATHY","MOODY","OVERCOAT","POISON TOUCH", "REGENERATOR","BIG PECKS","SAND RUSH","WONDER SKIN", "ANALYTIC","ILLUSION","IMPOSTER","INFILTRATOR", "MUMMY","MOXIE","JUSTIFIED","RATTLED", "MAGIC BOUNCE","SAP SIPPER","PRANKSTER","SAND FORCE", "IRON BARBS","ZEN MODE","VICTORY STAR","TURBOBLAZE", "TERAVOLT" }; private static string[] WORDS_TRAINER = new string[] { "MATCH UP","NO. 1","BAD MATCHUP","PREPARATION", // 1394 "WINS","NO MATCH","SPIRIT","CRITICAL HIT", "ACE CARD","COME ON","NO EFFECT","ATTACK", "SURRENDER","COURAGE","TALENT","STRATEGY", "MATCH","VICTORY","SENSE","VERSUS", "FIGHTS","POWER","CHALLENGE","CHAMPION", "STRONG","TAKE IT EASY","FOE","GENIUS", "LEGEND","TRAINER","GOOD MATCHUP","BATTLE", "EMERGENCY","FIGHT","REVIVE","POINTS", "SERIOUS","LOSS","PARTNER","INVINCIBLE", "EASY","WEAK","EASY WIN","MOVE" }; private static string[] WORDS_PEOPLE = new string[] { "OPPONENT","I","YOU","MOTHER", // 1438 "GRANDFATHER","UNCLE","FATHER","BOY", "ADULT","BROTHER","SISTER","GRANDMOTHER", "AUNT","PARENT","OLD MAN","ME", "GIRL","GAL","FAMILY","HER", "HIM","YOU","SIBLINGS","KIDS", "MR.","MS.","MYSELF","WHO", "FRIEND","ALLY","PERSON","BABY", "KIDS","I","EVERYONE","RIVAL", "I","I" }; private static string[] WORDS_GREETINGS = new string[] { "こんにちは","HELLO","BONJOUR","CIAO", // 1476 "HALLO","HOLA","안녕하세요","HELLO", "...","THANKS","NO PROBLEM","NOPE", "YES","HERE GOES","LET'S GO","HERE I COME", "WELCOME","GREETINGS","WELL DONE","GIVE ME", "SORRY","FORGIVE ME","I'M SORRY","GOOD-BYE", "THANK YOU","I'VE ARRIVED","PARDON ME","SO SORRY", "SEE YA","EXCUSE ME","OK THEN","GO AHEAD", "CHEERS","WHAT'S UP?","NO","HI", "YEP","YEAH, YEAH","BYE-BYE","MEET YOU", "BYE FOR NOW","HELLO?","HI THERE","NO WAY", "YAHOO","YO","WELCOME","REGARDS" }; private static string[] WORDS_LIFESTYLE = new string[] { "IDOL","AUTUMN","TOMORROW","PLAYING", // 1524 "ANIME","JOB","SONG","HOME", "MOVIE","SWEETS","MONEY","POCKET MONEY", "CHIT-CHAT","TALK","BATH","PLAY HOUSE", "TOYS","MUSIC","CARDS","SHOPPING", "CONVERSATION","SCIENCE","SCHOOL","CAMERA", "VIEWING","SPECTATE","ANNIVERSARY","YESTERDAY", "TODAY","HABIT","GOURMET","GAME", "WORD","STORE","SERVICE","MAGAZINE", "WALK","WORK","BICYCLE","GYM", "TRAINING","CLASS","LESSONS","HOBBY", "INFORMATION","SHOP","SPORTS","DAILY LIFE", "TEACHER","SOFTWARE","SONGS","DIET", "TOURNAMENT","TREASURE","TRAVEL","BIRTHDAY", "DANCE","CHANNEL","FISHING","DATE", "LETTER","EVENT","TEST","DEPT. STORE", "TELEVISION","TRAIN","PHONE","ITEM", "SUMMER","NAME","NEWS","POPULARITY", "STUFFED TOY","PARTY","COMPUTER","FLOWERS", "SPRING","HERO","NAP","HEROINE", "FASHION","WINTER","STUDY","ADVENTURE", "BOARD","BALL","BOOK","MACHINE", "FESTIVAL","COMICS","STORY","PROMISE", "HOLIDAY","FAIRGROUND","DREAM","KINDERGARTEN", "PLANS","LIFE","RADIO","CRAZE", "VACATION","LOOKS","WORLD" }; private static string[] WORDS_FEELINGS = new string[] { "BEAUTY","DELIGHT","STRANGENESS","RECOMMEND", // 1627 "CLEVERNESS","DISAPPOINTED","COOLNESS","SADNESS", "CUTENESS","SIMPLE","ANGER","HEALTHY", "REGRET","HAPPINESS","DEPRESSED","INCREDIBLE", "LIKES","DISLIKE","BORED","IMPORTANT", "ALL RIGHT","ADORE","TOUGHNESS","ENJOYMENT", "USELESS","DROOLING","EXCITED","SKILLFUL", "NICE","TEARS","HATE","ROFL", "HAPPY","ENERGETIC","SURPRISE","SUBTLE", "NERVOUS","WANT","SATISFIED","DIFFICULT", "RARE","MESSED UP","NO WAY","DANGER", "LOVEY-DOVEY","ANTICIPATION","SMILE" }; private static string[] WORDS_TERM = new string[] { "C-GEAR","PASS POWER","ELEGANT","CUTE", // 1674 "COOL","GROUP","GOTCHA","COLLECTION", "COMPLETE","SYSTEM","LAUNCHER","NATURE", "DOWSING","TOWN MAP","DESIGN","DIGITAL", "HALL OF FAME","INSTITUTE","BADGE","BATTLE TEST", "BATTLE BOX","PASS ORB","⒆⒇ CENTER","POKÉMON", // todo: Fix PkMn CENTER encoding issue "MISSION","MAIL","MESSAGE","ENTREE", "UNIQUE","LEVEL","RENTAL","TM" }; private static string[] WORDS_CONNECTION = new string[] { "PGL","GTS","POKÉMON DW","Wi-Fi", // 1706 "SPIN","GAME SYNC","COLOSSEUM","SUBWAY", "GEONET","SINGLE","INFRARED","DOUBLE", "CHAT","CONNECTION","FRIEND CODE","TRIPLE", "ENTRALINK","BATTLE VIDEOS","VOICE CHAT","POKÉ TRANSFER", "MULTI BATTLE","MUSICAL","UNION","TAG LOG", "ROTATION","WIRELESS" }; // todo: We need to substitute words in this range with gifs, but only // when rendering to the web. // Maybe we can nicen their display in ToString() somehow too. private static string[] WORDS_ANIMATED = new string[] { "絵_GOOD DAY!","絵_HELLO!","絵_I LOVE IT!","絵_GOOD LUCK!", // 1732 "絵_IT'S FUN!","絵_HAPPY!","絵_THANK YOU!","絵_SUPER! ♪", "絵_SORRY...","絵_BYE-BYE!" }; private static string[] WORDS_VOICE = new string[] { "OH WELL","AAH","AHAHA","HUH?", // 1742 "YEAH","URGH","LET ME THINK","HMM", "WHOA","ROOOAAR!","WOW","SNICKER", "CUTE LAUGH","UNBELIEVABLE","CRIES","OK", "AGREE","EH?","BOO-HOO","HEHEHE", "HEY","OH, YEAH","OH WOW!","HEEEY", "OOPS","OH MY","EEK","YAAAH", "GIGGLE","GWAHAHAHA","UGH","HEY!", "WEEP","TUT","BLUSH","HEY?", "HUH?","SIGH","HAHAHA","AIYEEH", "HIYAH","MUHAHAHA","LOL","SNORT", "HUMPH","HEY","HE-HE-HE","HEH", "HOHOHO","THERE YOU GO","OH, DEAR","ANGRY", "MUFUFU","MMM","OK","LALALA", "YAY","WAIL","WOW","BOO!", "WAHAHA" }; // 1803+ is out of range. #endregion } } ================================================ FILE: library/Support/TrendyPhraseBase.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PkmnFoundations.Support { public abstract class TrendyPhraseBase { public TrendyPhraseBase(byte[] data) { Data = data; } private byte[] m_data; public byte[] Data { get { return m_data; } set { if (m_data == value) return; if (value == null) { m_data = null; return; } if (value.Length != 8) throw new ArgumentException("Trendy phrase data must be 8 bytes."); m_data = value.ToArray(); } } public override string ToString() { return Render("{0}"); } public abstract string Render(string wordFormat); internal static byte[] Pack(ushort mood, ushort index, ushort word1, ushort word2) { byte[] result = new byte[8]; Array.Copy(BitConverter.GetBytes(mood), 0, result, 0, 2); Array.Copy(BitConverter.GetBytes(index), 0, result, 2, 2); Array.Copy(BitConverter.GetBytes(word1), 0, result, 4, 2); Array.Copy(BitConverter.GetBytes(word2), 0, result, 6, 2); return result; } public ushort Mood { get { return BitConverter.ToUInt16(Data, 0); } set { Array.Copy(BitConverter.GetBytes(value), 0, Data, 0, 2); } } public ushort Index { get { return BitConverter.ToUInt16(Data, 2); } set { Array.Copy(BitConverter.GetBytes(value), 0, Data, 2, 2); } } public ushort Word1 { get { return BitConverter.ToUInt16(Data, 4); } set { Array.Copy(BitConverter.GetBytes(value), 0, Data, 4, 2); } } public ushort Word2 { get { return BitConverter.ToUInt16(Data, 6); } set { Array.Copy(BitConverter.GetBytes(value), 0, Data, 6, 2); } } } } ================================================ FILE: library/Support/ValidationSummary.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PkmnFoundations.Support { public struct ValidationSummary { public bool IsValid { get; set; } // todo: Put reasons validation failed here, such as out-of-range values, bad egg, EVs > 510, etc. // public bool TooMuchEvs {get; set;} } } ================================================ FILE: library/Wfc/BanStatus.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PkmnFoundations.Wfc { public class BanStatus { public BanStatus() { } public BanStatus(BanLevels level, string reason, DateTime ? expires) { Level = level; Reason = reason; Expires = expires; } public BanLevels Level { get; set; } public string Reason { get; set; } public DateTime ? Expires { get; set; } } public enum BanLevels { None = 0, Restricted = 1, Banned = 2, IAmATotalPieceOfShit = 9, } } ================================================ FILE: library/Wfc/BattleSubwayPokemon5.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using PkmnFoundations.Structures; using PkmnFoundations.Support; namespace PkmnFoundations.Wfc { public class BattleSubwayPokemon5 : BattleTowerPokemonBase { public BattleSubwayPokemon5(Pokedex.Pokedex pokedex) : base(pokedex) { } public BattleSubwayPokemon5(Pokedex.Pokedex pokedex, int species, byte form, ushort held_item, ushort[] moveset, uint ot, uint personality, uint ivs, byte[] evs, byte pp_ups, Languages language, byte ability, byte happiness, EncodedString5 nickname, uint unknown2) : base(pokedex) { if (moveset == null) throw new ArgumentNullException("moveset"); if (moveset.Length != 4) throw new ArgumentException("moveset"); if (evs == null) throw new ArgumentNullException("evs"); if (evs.Length != 6) throw new ArgumentException("evs"); if (nickname == null) throw new ArgumentNullException("nickname"); if (nickname.Size != 22) throw new ArgumentException("nickname"); SpeciesID = species; FormID = form; HeldItemID = held_item; GetMovesFromArray(Moves, pokedex, moveset, pp_ups); TrainerID = ot; Personality = personality; IVs = new IvStatValues((int)ivs & 0x3fffffff); IvFlags = ivs & 0xc0000000u; EVs = new ByteStatValues(evs); Language = language; AbilityID = ability; Happiness = happiness; NicknameEncoded = nickname; // todo: clone Unknown2 = unknown2; } public BattleSubwayPokemon5(Pokedex.Pokedex pokedex, int species, byte form, ushort held_item, ushort move1, ushort move2, ushort move3, ushort move4, uint ot, uint personality, uint ivs, byte[] evs, byte pp_ups, Languages language, byte ability, byte happiness, EncodedString5 nickname, uint unknown2) : this(pokedex, species, form, held_item, new ushort[] { move1, move2, move3, move4 }, ot, personality, ivs, evs, pp_ups, language, ability, happiness, nickname, unknown2) { } public BattleSubwayPokemon5(Pokedex.Pokedex pokedex, BinaryReader data) : base(pokedex) { Load(data); } public BattleSubwayPokemon5(Pokedex.Pokedex pokedex, byte[] data) : base(pokedex) { Load(data); } public BattleSubwayPokemon5(Pokedex.Pokedex pokedex, byte[] data, int offset) : base(pokedex) { Load(data, offset); } public EncodedString5 NicknameEncoded; public uint Unknown2; public override string Nickname { get { return (NicknameEncoded == null) ? null : NicknameEncoded.Text; } set { // xxx: This comes straight from Pokemon4. What we logically need here is an inheritance diamond. if (Nickname == value) return; if (NicknameEncoded == null) NicknameEncoded = new EncodedString5(value, 22); else NicknameEncoded.Text = value; } } protected override void Save(BinaryWriter writer) { writer.Write(CombineSpeciesForm(SpeciesID, FormID)); writer.Write((ushort)HeldItemID); ushort[] moveset = GetArrayFromMoves(Moves); for (int i = 0; i < 4; i++) { writer.Write(moveset[i]); } writer.Write(TrainerID); writer.Write(Personality); writer.Write(IVs.ToInt32() | (int)IvFlags); writer.Write(EVs.ToArray(), 0, 6); writer.Write(GetPpUpsFromMoves(Moves)); writer.Write((byte)Language); writer.Write((byte)AbilityID); writer.Write(Happiness); writer.Write(NicknameEncoded.RawData, 0, 22); writer.Write(Unknown2); // new to G5 writer.Flush(); } protected override void Load(BinaryReader reader) { ushort species_form = reader.ReadUInt16(); SpeciesID = GetSpeciesFromCombined(species_form); FormID = GetFormFromCombined(species_form); HeldItemID = reader.ReadUInt16(); ushort[] moveset = new ushort[4]; for (int i = 0; i < 4; i++) { moveset[i] = reader.ReadUInt16(); } TrainerID = reader.ReadUInt32(); Personality = reader.ReadUInt32(); uint ivs = reader.ReadUInt32(); IVs = new IvStatValues((int)ivs & 0x3fffffff); IvFlags = ivs & 0xc0000000u; EVs = new ByteStatValues(reader.ReadBytes(6)); byte ppUps = reader.ReadByte(); GetMovesFromArray(Moves, m_pokedex, moveset, ppUps); Language = (Languages)reader.ReadByte(); AbilityID = reader.ReadByte(); Happiness = reader.ReadByte(); NicknameEncoded = new EncodedString5(reader.ReadBytes(22)); Unknown2 = reader.ReadUInt32(); // new to G5 } public BattleSubwayPokemon5 Clone() { uint ivsField = (uint)(IVs.ToInt32() & 0x3fffffffu) | (IvFlags & 0xc0000000u); ushort[] moveset = GetArrayFromMoves(Moves); byte ppUps = GetPpUpsFromMoves(Moves); BattleSubwayPokemon5 result = new BattleSubwayPokemon5(m_pokedex, SpeciesID, FormID, (ushort)HeldItemID, moveset, TrainerID, Personality, ivsField, EVs.ToArray(), ppUps, Language, (byte)AbilityID, Happiness, NicknameEncoded, Unknown2); return result; } public override Generations Generation { get { return Generations.Generation5; } } public override int Size { get { return 60; } } } } ================================================ FILE: library/Wfc/BattleSubwayProfile5.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using PkmnFoundations.Structures; using PkmnFoundations.Support; namespace PkmnFoundations.Wfc { public class BattleSubwayProfile5 : BattleTowerProfileBase { public BattleSubwayProfile5() { } public BattleSubwayProfile5(byte[] data) { Load(data, 0); } public BattleSubwayProfile5(byte[] data, int start) { Load(data, start); } public BattleSubwayProfile5(EncodedString5 name, Versions version, Languages language, byte country, byte region, uint ot, TrendyPhrase5 phrase_leader, byte gender, byte unknown) { if (name == null) throw new ArgumentNullException("name"); if (name.Size != 16) throw new ArgumentException("name"); if (phrase_leader == null) throw new ArgumentNullException("phrase_leader"); Name = name; // todo: clone Version = version; Language = language; Country = country; Region = region; OT = ot; PhraseLeader = phrase_leader; // todo: clone Gender = gender; Unknown = unknown; } public EncodedString5 Name; public Versions Version; public Languages Language; public byte Country; public byte Region; public uint OT; public TrendyPhrase5 PhraseLeader; // Different from GTS, 0 = male, 2 = female, 1 = Plato???? public byte Gender; public byte Unknown; // Probably trainer class. public byte[] Save() { byte[] data = new byte[0x22]; MemoryStream ms = new MemoryStream(data); BinaryWriter writer = new BinaryWriter(ms); writer.Write(Name.RawData, 0, 16); writer.Write((byte)Version); writer.Write((byte)Language); writer.Write(Country); writer.Write(Region); writer.Write(OT); writer.Write(PhraseLeader.Data, 0, 8); writer.Write(Gender); writer.Write(Unknown); writer.Flush(); ms.Flush(); return data; } public void Load(byte[] data, int start) { if (start + 0x22 > data.Length) throw new ArgumentOutOfRangeException("start"); Name = new EncodedString5(data, start, 0x10); Version = (Versions)data[0x10 + start]; Language = (Languages)data[0x11 + start]; Country = data[0x12 + start]; Region = data[0x13 + start]; OT = BitConverter.ToUInt32(data, 0x14 + start); byte[] trendyPhrase = new byte[8]; Array.Copy(data, 0x18 + start, trendyPhrase, 0, 8); PhraseLeader = new TrendyPhrase5(trendyPhrase); Gender = data[0x20 + start]; Unknown = data[0x21 + start]; } } } ================================================ FILE: library/Wfc/BattleSubwayRecord5.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using PkmnFoundations.Support; namespace PkmnFoundations.Wfc { public class BattleSubwayRecord5 : BattleTowerRecordBase { public BattleSubwayRecord5(Pokedex.Pokedex pokedex) { Pokedex = pokedex; } public BattleSubwayRecord5(Pokedex.Pokedex pokedex, byte[] data) { Pokedex = pokedex; Load(data, 0); } public BattleSubwayRecord5(Pokedex.Pokedex pokedex, byte[] data, int start) { Pokedex = pokedex; Load(data, start); } public Pokedex.Pokedex Pokedex { get; set; } private BattleSubwayPokemon5[] m_party; private BattleSubwayProfile5 m_profile; private TrendyPhrase5 m_phrase_challenged; private TrendyPhrase5 m_phrase_won; private TrendyPhrase5 m_phrase_lost; public override IList Party { get { return m_party; } set { if (!(value is BattleSubwayPokemon5[])) throw new ArgumentException("value must be BattleSubwayPokemon5[]"); BattleSubwayPokemon5[] party = (BattleSubwayPokemon5[])value; if (party.Length != 3) throw new ArgumentException("value must have length 3"); m_party = party; } } public override BattleTowerProfileBase Profile { get { return m_profile; } set { m_profile = (BattleSubwayProfile5)value; } } public override TrendyPhraseBase PhraseChallenged { get { return m_phrase_challenged; } set { m_phrase_challenged = (TrendyPhrase5)value; } } public override TrendyPhraseBase PhraseWon { get { return m_phrase_won; } set { m_phrase_won = (TrendyPhrase5)value; } } public override TrendyPhraseBase PhraseLost { get { return m_phrase_lost; } set { m_phrase_lost = (TrendyPhrase5)value; } } public ushort Unknown3; public byte Rank; public byte RoomNum; public byte BattlesWon; public byte[] Unknown4; // 5 bytes, appears to always be 00 00 00 00 00? public ulong Unknown5; // Appears to be zero on AdmiralCurtiss's scraped data, but is very big ints on data being uploaded. public int PID; public byte[] Save() { byte[] data = new byte[0xf0]; MemoryStream ms = new MemoryStream(data); BinaryWriter writer = new BinaryWriter(ms); for (int x = 0; x < 3; x++) { writer.Write(Party[x].Save()); } writer.Write(((BattleSubwayProfile5)Profile).Save()); writer.Write(PhraseChallenged.Data); writer.Write(PhraseWon.Data); writer.Write(PhraseLost.Data); writer.Write(Unknown3); writer.Flush(); ms.Flush(); return data; } public void Load(byte[] data, int start) { if (start + 0xf0 > data.Length) throw new ArgumentOutOfRangeException("start"); Party = new BattleSubwayPokemon5[3]; for (int x = 0; x < 3; x++) { Party[x] = new BattleSubwayPokemon5(Pokedex, data, start + x * 0x3c); } Profile = new BattleSubwayProfile5(data, 0xb4 + start); byte[] trendyPhrase = new byte[8]; Array.Copy(data, 0xd6 + start, trendyPhrase, 0, 8); PhraseChallenged = new TrendyPhrase5(trendyPhrase); trendyPhrase = new byte[8]; Array.Copy(data, 0xde + start, trendyPhrase, 0, 8); PhraseWon = new TrendyPhrase5(trendyPhrase); trendyPhrase = new byte[8]; Array.Copy(data, 0xe6 + start, trendyPhrase, 0, 8); PhraseLost = new TrendyPhrase5(trendyPhrase); Unknown3 = BitConverter.ToUInt16(data, 0xee + start); } } } ================================================ FILE: library/Wfc/BattleTowerPokemon4.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using PkmnFoundations.Structures; using PkmnFoundations.Support; namespace PkmnFoundations.Wfc { public class BattleTowerPokemon4 : BattleTowerPokemonBase { public BattleTowerPokemon4(Pokedex.Pokedex pokedex) : base(pokedex) { } public BattleTowerPokemon4(Pokedex.Pokedex pokedex, int species, byte form, ushort held_item, ushort[] moveset, uint ot, uint personality, uint ivs, byte[] evs, byte pp_ups, Languages language, byte ability, byte happiness, EncodedString4 nickname) : base(pokedex) { if (moveset == null) throw new ArgumentNullException("moveset"); if (moveset.Length != 4) throw new ArgumentException("moveset"); if (evs == null) throw new ArgumentNullException("evs"); if (evs.Length != 6) throw new ArgumentException("evs"); if (nickname == null) throw new ArgumentNullException("nickname"); if (nickname.Size != 22) throw new ArgumentException("nickname"); SpeciesID = species; FormID = form; HeldItemID = held_item; GetMovesFromArray(Moves, pokedex, moveset, pp_ups); TrainerID = ot; Personality = personality; IVs = new IvStatValues((int)ivs & 0x3fffffff); IvFlags = ivs & 0xc0000000u; EVs = new ByteStatValues(evs); Language = language; AbilityID = ability; Happiness = happiness; NicknameEncoded = nickname; // todo: clone } public BattleTowerPokemon4(Pokedex.Pokedex pokedex, int species, byte form, ushort held_item, ushort move1, ushort move2, ushort move3, ushort move4, uint ot, uint personality, uint ivs, byte[] evs, byte pp_ups, Languages language, byte ability, byte happiness, EncodedString4 nickname) : this(pokedex, species, form, held_item, new ushort[] { move1, move2, move3, move4 }, ot, personality, ivs, evs, pp_ups, language, ability, happiness, nickname) { } public BattleTowerPokemon4(Pokedex.Pokedex pokedex, BinaryReader data) : base(pokedex) { Load(data); } public BattleTowerPokemon4(Pokedex.Pokedex pokedex, byte[] data) : base(pokedex) { Load(data); } public BattleTowerPokemon4(Pokedex.Pokedex pokedex, byte[] data, int offset) : base(pokedex) { Load(data, offset); } public EncodedString4 NicknameEncoded; public override string Nickname { get { return (NicknameEncoded == null) ? null : NicknameEncoded.Text; } set { // xxx: This comes straight from Pokemon4. What we logically need here is an inheritance diamond. if (Nickname == value) return; if (NicknameEncoded == null) NicknameEncoded = new EncodedString4(value, 22); else NicknameEncoded.Text = value; } } protected override void Save(BinaryWriter writer) { writer.Write(CombineSpeciesForm(SpeciesID, FormID)); writer.Write((ushort)HeldItemID); ushort[] moveset = GetArrayFromMoves(Moves); for (int i = 0; i < 4; i++) { writer.Write(moveset[i]); } writer.Write(TrainerID); writer.Write(Personality); writer.Write(IVs.ToInt32() | (int)IvFlags); writer.Write(EVs.ToArray(), 0, 6); writer.Write(GetPpUpsFromMoves(Moves)); writer.Write((byte)Language); writer.Write((byte)AbilityID); writer.Write(Happiness); writer.Write(NicknameEncoded.RawData, 0, 22); writer.Flush(); } protected override void Load(BinaryReader reader) { ushort species_form = reader.ReadUInt16(); SpeciesID = GetSpeciesFromCombined(species_form); FormID = GetFormFromCombined(species_form); HeldItemID = reader.ReadUInt16(); ushort[] moveset = new ushort[4]; for (int i = 0; i < 4; i++) { moveset[i] = reader.ReadUInt16(); } TrainerID = reader.ReadUInt32(); Personality = reader.ReadUInt32(); uint ivs = reader.ReadUInt32(); IVs = new IvStatValues((int)ivs & 0x3fffffff); IvFlags = ivs & 0xc0000000u; EVs = new ByteStatValues(reader.ReadBytes(6)); byte ppUps = reader.ReadByte(); GetMovesFromArray(Moves, m_pokedex, moveset, ppUps); Language = (Languages)reader.ReadByte(); AbilityID = reader.ReadByte(); Happiness = reader.ReadByte(); NicknameEncoded = new EncodedString4(reader.ReadBytes(22)); } public BattleTowerPokemon4 Clone() { uint ivsField = (uint)(IVs.ToInt32() & 0x3fffffffu) | (IvFlags & 0xc0000000u); ushort[] moveset = GetArrayFromMoves(Moves); byte ppUps = GetPpUpsFromMoves(Moves); BattleTowerPokemon4 result = new BattleTowerPokemon4(m_pokedex, SpeciesID, FormID, (ushort)HeldItemID, moveset, TrainerID, Personality, ivsField, EVs.ToArray(), ppUps, Language, (byte)AbilityID, Happiness, NicknameEncoded); return result; } public override Generations Generation { get { return Generations.Generation4; } } public override int Size { get { return 56; } } } } ================================================ FILE: library/Wfc/BattleTowerPokemonBase.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using PkmnFoundations.Pokedex; using PkmnFoundations.Structures; using PkmnFoundations.Support; namespace PkmnFoundations.Wfc { public abstract class BattleTowerPokemonBase : PokemonBase { public BattleTowerPokemonBase(Pokedex.Pokedex pokedex) : base(pokedex) { } // In the main PKM structure, the remaining 2 bits on the IVs field // represents whether it's nicknamed and if it's an egg. Clearly, eggs // shouldn't be brought into Battle Tower. public uint IvFlags; public override byte Level { get { // todo: fact check that everything's lv50? return 50; } set { throw new NotSupportedException(); } } protected static ushort CombineSpeciesForm(int species, byte form) { if (species > 0x7ff || species < 0) throw new ArgumentOutOfRangeException("species"); if (form > 0x1f) throw new ArgumentOutOfRangeException("form"); return (ushort)(species & 0x7ff | form << 11); } protected static int GetSpeciesFromCombined(ushort combined) { return combined & 0x7ff; } protected static byte GetFormFromCombined(ushort combined) { return (byte)(combined >> 11); } internal static void GetMovesFromArray(IList result, Pokedex.Pokedex pokedex, ushort[] moves, byte ppUps) { if (moves.Length != 4) throw new ArgumentException("moves"); if (result.Count != 4) throw new ArgumentException("movesOut"); for (int i = 0; i < 4; i++) { result[i] = MoveFromValues(pokedex, moves[i], (byte)(ppUps & 0x03)); ppUps >>= 2; } } internal static MoveSlot MoveFromValues(Pokedex.Pokedex pokedex, ushort move, byte ppUps) { MoveSlot result = new MoveSlot(pokedex, move, ppUps, 0); result.RemainingPP = (byte)result.PP; return result; } internal static ushort[] GetArrayFromMoves(IList moves) { if (moves.Count != 4) throw new ArgumentException("moves"); ushort[] result = new ushort[4]; for (int i = 0; i < 4; i++) { result[i] = (ushort)moves[i].MoveID; } return result; } internal static byte GetPpUpsFromMoves(IList moves) { // The first move uses the least significant bits, moving up from there. // [1, 3, 0, 0] -> 0x0d byte ppUps = 0; for (int i = 0; i < 4; i++) { ppUps |= (byte)(moves[i].PPUps << (i * 2)); } return ppUps; } public ushort[] GetMoveIds() { return GetArrayFromMoves(Moves); } public byte GetPpUps() { return GetPpUpsFromMoves(Moves); } } } ================================================ FILE: library/Wfc/BattleTowerProfile4.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using PkmnFoundations.Structures; using PkmnFoundations.Support; namespace PkmnFoundations.Wfc { public class BattleTowerProfile4 : BattleTowerProfileBase { public BattleTowerProfile4() { } public BattleTowerProfile4(EncodedString4 name, Versions version, Languages language, byte country, byte region, uint ot, TrendyPhrase4 phrase_leader, byte gender, byte unknown) { if (name == null) throw new ArgumentNullException("name"); if (name.Size != 16) throw new ArgumentException("name"); if (phrase_leader == null) throw new ArgumentNullException("phrase_leader"); Name = name; // todo: clone Version = version; Language = language; Country = country; Region = region; OT = ot; PhraseLeader = phrase_leader; // todo: clone Gender = gender; Unknown = unknown; } public BattleTowerProfile4(byte[] data) { Load(data, 0); } public BattleTowerProfile4(byte[] data, int start) { Load(data, start); } public EncodedString4 Name; public Versions Version; public Languages Language; public byte Country; public byte Region; public uint OT; public TrendyPhrase4 PhraseLeader; // Different from GTS, 0 = male, 2 = female, 1 = Plato???? public byte Gender; // 3: Lass // 6: Bug Catcher // 10: Battle Girl // 14: Black Belt // 18: Cowgirl // 24: Ace Trainer M // 25: Ace Trainer F // 32: Rich Boy // 33: Lady // 35: Socialite F // 36: Beauty // 48: Ruin Maniac // 49: Psychic M // 57: Roughneck // 60: School Kid M // 85: Idol public byte Unknown; // Probably trainer class. public byte[] Save() { byte[] data = new byte[0x22]; MemoryStream ms = new MemoryStream(data); BinaryWriter writer = new BinaryWriter(ms); writer.Write(Name.RawData, 0, 16); writer.Write((byte)Version); writer.Write((byte)Language); writer.Write(Country); writer.Write(Region); writer.Write(OT); writer.Write(PhraseLeader.Data, 0, 8); writer.Write(Gender); writer.Write(Unknown); writer.Flush(); ms.Flush(); return data; } public void Load(byte[] data, int start) { if (start + 0x22 > data.Length) throw new ArgumentOutOfRangeException("start"); Name = new EncodedString4(data, start, 0x10); Version = (Versions)data[0x10 + start]; Language = (Languages)data[0x11 + start]; Country = data[0x12 + start]; Region = data[0x13 + start]; OT = BitConverter.ToUInt32(data, 0x14 + start); byte[] trendyPhrase = new byte[8]; Array.Copy(data, 0x18 + start, trendyPhrase, 0, 8); PhraseLeader = new TrendyPhrase4(trendyPhrase); Gender = data[0x20 + start]; Unknown = data[0x21 + start]; } } } ================================================ FILE: library/Wfc/BattleTowerProfileBase.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PkmnFoundations.Wfc { public abstract class BattleTowerProfileBase { // todo: move much of implementation in here from derived classes } } ================================================ FILE: library/Wfc/BattleTowerRecord4.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using PkmnFoundations.Support; namespace PkmnFoundations.Wfc { public class BattleTowerRecord4 : BattleTowerRecordBase { public BattleTowerRecord4(Pokedex.Pokedex pokedex) { Pokedex = pokedex; } public BattleTowerRecord4(Pokedex.Pokedex pokedex, byte[] data) { Pokedex = pokedex; Load(data, 0); } public BattleTowerRecord4(Pokedex.Pokedex pokedex, byte[] data, int start) { Pokedex = pokedex; Load(data, start); } public Pokedex.Pokedex Pokedex { get; set; } private BattleTowerPokemon4[] m_party; private BattleTowerProfile4 m_profile; private TrendyPhrase4 m_phrase_challenged; private TrendyPhrase4 m_phrase_won; private TrendyPhrase4 m_phrase_lost; public override IList Party { get { return m_party; } set { if (!(value is BattleTowerPokemon4[])) throw new ArgumentException("value must be BattleTowerPokemon4[]"); BattleTowerPokemon4[] party = (BattleTowerPokemon4[])value; if (party.Length != 3) throw new ArgumentException("value must have length 3"); m_party = party; } } public override BattleTowerProfileBase Profile { get { return m_profile; } set { m_profile = (BattleTowerProfile4)value; } } public override TrendyPhraseBase PhraseChallenged { get { return m_phrase_challenged; } set { m_phrase_challenged = (TrendyPhrase4)value; } } public override TrendyPhraseBase PhraseWon { get { return m_phrase_won; } set { m_phrase_won = (TrendyPhrase4)value; } } public override TrendyPhraseBase PhraseLost { get { return m_phrase_lost; } set { m_phrase_lost = (TrendyPhrase4)value; } } public ushort Unknown3; // Seems to be some sort of Elo rating. Goes up to about 8000. public byte Rank; public byte RoomNum; public byte BattlesWon; public ulong Unknown5; // Appears to be zero on AdmiralCurtiss's scraped data, but is very big ints on data being uploaded. public int PID; public byte[] Save() { byte[] data = new byte[0xe4]; MemoryStream ms = new MemoryStream(data); BinaryWriter writer = new BinaryWriter(ms); for (int x = 0; x < 3; x++) { writer.Write(Party[x].Save()); } writer.Write(((BattleTowerProfile4)Profile).Save()); writer.Write(PhraseChallenged.Data); writer.Write(PhraseWon.Data); writer.Write(PhraseLost.Data); writer.Write(Unknown3); writer.Flush(); ms.Flush(); return data; } public void Load(byte[] data, int start) { if (start + 0xe4 > data.Length) throw new ArgumentOutOfRangeException("start"); m_party = new BattleTowerPokemon4[3]; for (int x = 0; x < 3; x++) { Party[x] = new BattleTowerPokemon4(Pokedex, data, start + x * 0x38); } Profile = new BattleTowerProfile4(data, 0xa8 + start); byte[] trendyPhrase = new byte[8]; Array.Copy(data, 0xca + start, trendyPhrase, 0, 8); PhraseChallenged = new TrendyPhrase4(trendyPhrase); trendyPhrase = new byte[8]; Array.Copy(data, 0xd2 + start, trendyPhrase, 0, 8); PhraseWon = new TrendyPhrase4(trendyPhrase); trendyPhrase = new byte[8]; Array.Copy(data, 0xda + start, trendyPhrase, 0, 8); PhraseLost = new TrendyPhrase4(trendyPhrase); Unknown3 = BitConverter.ToUInt16(data, 0xe2 + start); } } } ================================================ FILE: library/Wfc/BattleTowerRecordBase.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using PkmnFoundations.Support; namespace PkmnFoundations.Wfc { public abstract class BattleTowerRecordBase { // todo: move much of implementation in here from derived classes public abstract IList Party { get; set; } public abstract BattleTowerProfileBase Profile { get; set; } public abstract TrendyPhraseBase PhraseChallenged { get; set; } public abstract TrendyPhraseBase PhraseWon { get; set; } public abstract TrendyPhraseBase PhraseLost { get; set; } } } ================================================ FILE: library/Wfc/BattleVideoHeader4.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PkmnFoundations.Wfc { public class BattleVideoHeader4 { public BattleVideoHeader4() { } public BattleVideoHeader4(int pid, ulong serial_number, byte[] data) { if (data.Length != 228) throw new ArgumentException("Battle video header data must be 228 bytes."); PID = pid; SerialNumber = serial_number; Data = data; } // todo: encapsulate these so calculated fields are always correct public int PID; public ulong SerialNumber; public byte[] Data; public ushort Streak { get { return BitConverter.ToUInt16(Data, 0xa4); } } public ushort[] Party { get { ushort[] result = new ushort[12]; for (int x = 0; x < result.Length; x++) { result[x] = BitConverter.ToUInt16(Data, 0x80 + x * 2); } return result; } } public byte[] TrainerName { get { byte[] result = new byte[16]; Array.Copy(Data, 0, result, 0, 16); return result; } } public BattleVideoMetagames4 Metagame { get { return (BattleVideoMetagames4)Data[0xa6]; } } public byte Country { get { return Data[0x17]; } } public byte Region { get { return Data[0x18]; } } public BattleVideoHeader4 Clone() { return new BattleVideoHeader4(PID, SerialNumber, Data.ToArray()); } #region ID number calculation // Generating battle video IDs: // // STEP 1: Prepping the Template: // Start with an auto-incrementing primary key. Treat as a string of 12 // decimal digits. Pad with 0s. We call this the Key. // // The ones place (rightmost) is used to select one of ten fixed // Templates. A Template has 12 (11 useful) digits. They are basically // hardcoded random-looking numbers. The rightmost digit of each // template is undefined/unused. The leftmost digit is never 0. // // The Key’s tens place and hundreds place are added together mod-10 to // get a constant which is used to roll each of the digits in the // Template by. Here, rolling means adding in mod-10. // // The Template’s leftmost digit is rolled in mod-9 instead of 10. // (While rolling, skip the number 0.) If the value in the // second-leftmost digit wraps around to or past 0, this leftmost digit // is rolled one less time than it would be otherwise. // // Note: There is probably a better way to represent this algorithm // that doesn't require special handling for the leftmost digit based // on what the second one is doing. It would involve choosing different // Template constants and using a different roll formula. // // STEP 2: Prepping the Key: // Remove the tens place from the Key, then shift all the digits // EXCEPT the leftmost and rightmost one place to the right to fill the // gap. The second leftmost digit is filled with a constant 0. // (Example: 123333345678 becomes 102333334568) // // Note: This handling of the left two digits is an extrapolation on // my part. It gives us the maximum possible range of 10-00000-00000 // through to 99-99999-99999 in a 1:1 mapping. // // STEP 3: Putting it together: // Overwrite the rightmost digit of the Template with the Key’s ones // place digit. // // For each remaining digit, roll the Template *backwards* a number of // times equal to the Key’s digit in that place. private static byte[][] m_templates = new byte[][]{ new byte[]{6, 9, 3, 6, 1, 2, 7, 5, 2, 2, 4, 0}, new byte[]{8, 0, 7, 2, 6, 2, 4, 9, 1, 4, 4, 1}, new byte[]{1, 4, 9, 7, 3, 8, 5, 7, 6, 4, 7, 2}, new byte[]{9, 4, 1, 7, 6, 3, 9, 6, 2, 7, 5, 3}, new byte[]{4, 6, 4, 2, 9, 9, 7, 3, 4, 6, 1, 4}, new byte[]{9, 5, 1, 0, 9, 7, 8, 6, 6, 3, 5, 5}, new byte[]{8, 8, 7, 4, 4, 4, 3, 4, 6, 2, 9, 6}, new byte[]{6, 3, 7, 7, 5, 6, 7, 6, 1, 9, 5, 7}, new byte[]{2, 6, 7, 2, 3, 2, 4, 5, 8, 9, 7, 8}, new byte[]{2, 1, 9, 1, 7, 9, 9, 1, 6, 5, 6, 9} }; /// /// Converts a primary key (auto incrementing) into a Battle Video ID. /// public static ulong KeyToSerial(ulong key) { if (key > 899999999999L || key < 0L) throw new ArgumentOutOfRangeException(); byte[] keyDigits = LongToDigits(key); byte[] serialDigits = m_templates[keyDigits[11]].ToArray(); byte valueShift = 0; valueShift += keyDigits[9]; valueShift += keyDigits[10]; valueShift %= 10; if (valueShift + serialDigits[1] > 9) serialDigits[0]--; for (int x = 0; x < 11; x++) { serialDigits[x] += valueShift; } serialDigits[0] += 9; serialDigits[0] -= keyDigits[0]; serialDigits[0] %= 9; if (serialDigits[0] == 0) serialDigits[0] = 9; serialDigits[1] %= 10; for (int x = 1; x < 10; x++) { serialDigits[x + 1] += 10; serialDigits[x + 1] -= keyDigits[x]; serialDigits[x + 1] %= 10; } return DigitsToLong(serialDigits); } /// /// Converts Battle Video ID back into a primary key. /// public static ulong SerialToKey(ulong serial) { if (serial > 999999999999L || serial < 100000000000L) throw new ArgumentOutOfRangeException(); byte[] serialDigits = LongToDigits(serial); byte[] templateDigits = m_templates[serialDigits[11]]; serialDigits[0] = (byte)(10 + templateDigits[0] - serialDigits[0]); for (int x = 1; x < 11; x++) { serialDigits[x] = (byte)(10 + templateDigits[x] - serialDigits[x]); } byte valueShift = (byte)(serialDigits[1] % 10); if (templateDigits[1] - valueShift >= 0) serialDigits[0]--; serialDigits[0] += (byte)(9 - valueShift); serialDigits[0] %= 9; for (int x = 1; x < 11; x++) { serialDigits[x] += (byte)(10 - valueShift); serialDigits[x] %= 10; } for (int x = 1; x < 10; x++) { serialDigits[x] = serialDigits[x + 1]; } serialDigits[10] = (byte)((20 - valueShift - serialDigits[9]) % 10); return DigitsToLong(serialDigits); } private static byte[] LongToDigits(ulong value) { if (value > 999999999999L || value < 0L) throw new ArgumentException(); byte[] result = new byte[12]; for (int x = 11; x >= 0; x--) { result[x] = (byte)(value % 10); value /= 10; } return result; } private static ulong DigitsToLong(byte[] digits) { if (digits.Length != 12) throw new ArgumentException(); ulong result = 0; ulong pow = 1; for (int x = 11; x >= 0; x--) { if (digits[x] > 9) throw new ArgumentException(); result += digits[x] * pow; pow *= 10; } return result; } #endregion public static String FormatSerial(ulong serial) { String number = serial.ToString("D12"); String[] split = new String[3]; split[0] = number.Substring(0, number.Length - 10); split[1] = number.Substring(number.Length - 10, 5); split[2] = number.Substring(number.Length - 5, 5); return String.Join("-", split); } } public enum BattleVideoMetagames4 : byte { ColosseumSingleNoRestrictions = 0x00, ColosseumSingleStandardCup = 0x01, ColosseumSingleFancyCup = 0x02, ColosseumSingleLittleCup = 0x03, ColosseumSingleLightCup = 0x04, ColosseumSingleDoubleCup = 0x05, ColosseumSingleOtherCup = 0x06, ColosseumDoubleNoRestrictions = 0x07, ColosseumDoubleStandardCup = 0x08, ColosseumDoubleFancyCup = 0x09, ColosseumDoubleLittleCup = 0x0a, ColosseumDoubleLightCup = 0x0b, ColosseumDoubleDoubleCup = 0x0c, ColosseumDoubleOtherCup = 0x0d, ColosseumMulti = 0x0e, BattleTowerSingle = 0x0f, BattleTowerDouble = 0x10, BattleTowerMulti = 0x11, BattleFactoryLv50Single = 0x12, BattleFactoryLv50Double = 0x13, BattleFactoryLv50Multi = 0x14, BattleFactoryOpenSingle = 0x15, BattleFactoryOpenDouble = 0x16, BattleFactoryOpenMulti = 0x17, BattleHallSingle = 0x18, BattleHallDouble = 0x19, BattleHallMulti = 0x1a, BattleCastleSingle = 0x1b, BattleCastleDouble = 0x1c, BattleCastleMulti = 0x1d, BattleArcadeSingle = 0x1e, BattleArcadeDouble = 0x1f, BattleArcadeMulti = 0x20, SearchColosseumSingleNoRestrictions = 0xfa, SearchColosseumSingleCupMatch = 0xfb, SearchColosseumDoubleNoRestrictions = 0xfc, SearchColosseumDoubleCupMatch = 0xfd, SearchNoBattleFrontier = 0xfe, SearchLatest30 = 0xff, } public enum BattleVideoRankings4 : uint { None = 0x00000000, Colosseum = 0x00000001, BattleFrontier = 0x00000002, } } ================================================ FILE: library/Wfc/BattleVideoHeader5.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PkmnFoundations.Wfc { public class BattleVideoHeader5 { public BattleVideoHeader5() { } public BattleVideoHeader5(int pid, ulong serial_number, byte[] data) { if (data.Length != 196) throw new ArgumentException("Battle video header data must be 196 bytes."); PID = pid; SerialNumber = serial_number; Data = data; } // todo: encapsulate these so calculated fields are always correct public int PID; public ulong SerialNumber; public byte[] Data; public ushort Streak { get { return BitConverter.ToUInt16(Data, 0xa4); } } public ushort[] Party { get { ushort[] result = new ushort[12]; for (int x = 0; x < result.Length; x++) { result[x] = BitConverter.ToUInt16(Data, 0x80 + x * 2); } return result; } } public byte[] TrainerName { get { byte[] result = new byte[16]; Array.Copy(Data, 0, result, 0, 16); return result; } } public BattleVideoMetagames5 Metagame { get { return (BattleVideoMetagames5)Data[0xa6]; } } public byte Country { get { return Data[0x17]; } } public byte Region { get { return Data[0x18]; } } public BattleVideoHeader5 Clone() { return new BattleVideoHeader5(PID, SerialNumber, Data.ToArray()); } } public enum BattleVideoMetagames5 : byte { ColosseumSingleNoLauncher = 0x18, ColosseumDoubleNoLauncher = 0x19, ColosseumTripleNoLauncher = 0x1a, ColosseumRotationNoLauncher = 0x1b, ColosseumMultiNoLauncher = 0x1c, ColosseumSingleLauncher = 0x98, ColosseumDoubleLauncher = 0x99, ColosseumTripleLauncher = 0x9a, ColosseumRotationLauncher = 0x9b, ColosseumMultiLauncher = 0x9c, BattleSubwaySingle = 0x00, BattleSubwayDouble = 0x01, BattleSubwayMulti = 0x04, RandomMatchupSingle = 0x28, RandomMatchupDouble = 0x29, RandomMatchupTriple = 0x2a, RandomMatchupRotation = 0x2b, RandomMatchupLauncher = 0xaa, RatingSingle = 0x68, RatingDouble = 0x69, RatingTriple = 0x6a, RatingRotation = 0x6b, BattleCompetitionSingle = 0x38, BattleCompetitionDouble = 0x39, BattleCompetitionTriple = 0x3a, BattleCompetitionRotation = 0x3b, SearchBattleCompetition = 0x38, // This is not a legal value in either a search or a record. // I'm using it to indicate that no search is being done // (byte 0x148 in the search is 0). // Otherwise, the value 00 collides with Battle Subway Single // which is a legitimate search. SearchNone = 0xff, } public enum BattleVideoRankings5 : uint { None = 0x00000000, Newest30 = 0x00000001, LinkBattles = 0x00000003, SubwayBattles = 0x00000002, } } ================================================ FILE: library/Wfc/BattleVideoRecord4.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PkmnFoundations.Wfc { public class BattleVideoRecord4 { public BattleVideoRecord4() { } public BattleVideoRecord4(int pid, ulong serial_number, byte[] data) { if (data.Length != 7500) throw new ArgumentException("Battle video data must be 7500 bytes."); byte[] data_head = new byte[228]; byte[] data_main = new byte[7272]; Array.Copy(data, 0, data_head, 0, 228); Array.Copy(data, 228, data_main, 0, 7272); PID = pid; SerialNumber = serial_number; Header = new BattleVideoHeader4(pid, serial_number, data_head); Data = data_main; } public BattleVideoRecord4(int pid, ulong serial_number, BattleVideoHeader4 header, byte[] data_main) { if (data_main.Length != 7272) throw new ArgumentException("Battle video main data must be 7272 bytes."); PID = pid; SerialNumber = serial_number; Header = header; Data = data_main; } public int PID; public ulong SerialNumber; public BattleVideoHeader4 Header; public byte[] Data; public BattleVideoRecord4 Clone() { return new BattleVideoRecord4(PID, SerialNumber, Header.Clone(), Data.ToArray()); } public byte[] Save() { byte[] result = new byte[7500]; Array.Copy(Header.Data, 0, result, 0, 228); Array.Copy(Data, 228, result, 0, 7272); return result; } } } ================================================ FILE: library/Wfc/BattleVideoRecord5.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PkmnFoundations.Wfc { public class BattleVideoRecord5 { public BattleVideoRecord5() { } public BattleVideoRecord5(int pid, ulong serial_number, byte[] data) { if (data.Length != 6308) throw new ArgumentException("Battle video data must be 6308 bytes."); byte[] data_head = new byte[196]; byte[] data_main = new byte[6112]; Array.Copy(data, 0, data_head, 0, 196); Array.Copy(data, 196, data_main, 0, 6112); PID = pid; SerialNumber = serial_number; Header = new BattleVideoHeader5(pid, serial_number, data_head); Data = data_main; } public BattleVideoRecord5(int pid, ulong serial_number, BattleVideoHeader5 header, byte[] data_main) { if (data_main.Length != 6112) throw new ArgumentException("Battle video main data must be 6112 bytes."); PID = pid; SerialNumber = serial_number; Header = header; Data = data_main; } public int PID; public ulong SerialNumber; public BattleVideoHeader5 Header; public byte[] Data; public BattleVideoRecord5 Clone() { return new BattleVideoRecord5(PID, SerialNumber, Header.Clone(), Data.ToArray()); } public byte[] Save() { byte[] result = new byte[6308]; Array.Copy(Header.Data, 0, result, 0, 196); Array.Copy(Data, 196, result, 0, 6112); return result; } } } ================================================ FILE: library/Wfc/BoxRecord4.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using PkmnFoundations.Support; namespace PkmnFoundations.Wfc { public class BoxRecord4 : BinarySerializableBase { public BoxRecord4() { } public BoxRecord4(int pid, BoxLabels4 label, ulong serial_number, BinaryReader data) : base() { PID = pid; Label = label; SerialNumber = serial_number; Load(data); } public BoxRecord4(int pid, BoxLabels4 label, ulong serial_number, byte[] data) : base() { PID = pid; Label = label; SerialNumber = serial_number; Load(data); } public BoxRecord4(int pid, BoxLabels4 label, ulong serial_number, byte[] data, int offset) : base() { PID = pid; Label = label; SerialNumber = serial_number; Load(data, offset); } public int PID { get; set; } public BoxLabels4 Label { get; set; } public ulong SerialNumber { get; set; } private byte[] m_data; public byte[] Data { get { return m_data; } set { if (m_data == value) return; if (value == null) { m_data = null; return; } if (value.Length != 540) throw new ArgumentException("Box data must be 540 bytes."); m_data = value.ToArray(); } } public override int Size { get { return 540; } } protected override void Load(System.IO.BinaryReader reader) { m_data = reader.ReadBytes(540); } protected override void Save(System.IO.BinaryWriter writer) { writer.Write(m_data); } public BoxRecord4 Clone() { return new BoxRecord4(PID, Label, SerialNumber, Data); } } public enum BoxLabels4 : int { Favorite = 0x00, Cool = 0x01, Cute = 0x02, Suggested = 0x03, Fun = 0x04, Select = 0x05 } } ================================================ FILE: library/Wfc/DressupRecord4.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using PkmnFoundations.Support; namespace PkmnFoundations.Wfc { public class DressupRecord4 : BinarySerializableBase { public DressupRecord4() { } public DressupRecord4(int pid, ulong serial_number, BinaryReader data) : base() { PID = pid; SerialNumber = serial_number; Load(data); } public DressupRecord4(int pid, ulong serial_number, byte[] data) : base() { PID = pid; SerialNumber = serial_number; Load(data); } public DressupRecord4(int pid, ulong serial_number, byte[] data, int offset) : base() { PID = pid; SerialNumber = serial_number; Load(data, offset); } public int PID { get; set; } public ulong SerialNumber { get; set; } // todo: Document this data structure. // List of decorations: https://projectpokemon.org/rawdb/diamond/msg/338.php private byte[] m_data; public byte[] Data { get { return m_data; } set { if (m_data == value) return; if (value == null) { m_data = null; return; } if (value.Length != 224) throw new ArgumentException("Dressup data must be 224 bytes."); m_data = value.ToArray(); } } public ushort Species { get { return BitConverter.ToUInt16(Data, 0x8c); } } public override int Size { get { return 224; } } protected override void Load(System.IO.BinaryReader reader) { m_data = reader.ReadBytes(224); } protected override void Save(System.IO.BinaryWriter writer) { writer.Write(m_data); } public DressupRecord4 Clone() { return new DressupRecord4(PID, SerialNumber, Data); } } } ================================================ FILE: library/Wfc/GtsRecord4.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; using System.IO; using PkmnFoundations.Structures; using PkmnFoundations.Support; using System.Collections.ObjectModel; namespace PkmnFoundations.Wfc { /// /// Structure used to represent Pokémon on the GTS in Generation IV. /// Includes a Pokémon box structure and metadata related to the trainer /// and request. /// public class GtsRecord4 : GtsRecordBase, IEquatable { public GtsRecord4(Pokedex.Pokedex pokedex) : base(pokedex) { Initialize(); } public GtsRecord4(Pokedex.Pokedex pokedex, BinaryReader data) : base(pokedex) { Initialize(); Load(data); } public GtsRecord4(Pokedex.Pokedex pokedex, byte[] data) : base(pokedex) { Initialize(); Load(data); } public GtsRecord4(Pokedex.Pokedex pokedex, byte[] data, int offset) : base(pokedex) { Initialize(); Load(data, offset); } private void Initialize() { } /// /// Obfuscated Pokémon (pkm) data. 236 bytes /// public IList Data { get { return m_data_readonly; } set { DataActual = value.ToArray(); } } private byte[] DataActual { get { return m_data; } set { if (value == null) { m_data = null; m_data_readonly = null; m_pokemon = null; return; } if (value.Length != 0xEC) throw new ArgumentException("PKM length is incorrect"); m_data = value; m_data_readonly = new ReadOnlyCollection(m_data); m_pokemon = null; } } private byte[] m_data; private ReadOnlyCollection m_data_readonly; private PokemonParty4 m_pokemon; public override PokemonPartyBase Pokemon { get { if (DataActual == null || m_pokedex == null) return null; if (m_pokemon == null) m_pokemon = new PokemonParty4(m_pokedex, DataActual); return m_pokemon; } } public byte Unknown1; public byte Unknown2; /// /// 16 bytes /// public EncodedString4 TrainerNameEncoded; public override string TrainerName { get { if (TrainerNameEncoded == null) return null; return TrainerNameEncoded.Text; } set { if (TrainerNameEncoded == null) TrainerNameEncoded = new EncodedString4(value, 16); else TrainerNameEncoded.Text = value; } } public ushort TrainerOT; protected override void Save(BinaryWriter writer) { // todo: enclose in properties and validate these when assigning. if (TrainerNameEncoded.RawData.Length != 0x10) throw new FormatException("Trainer name length is incorrect"); writer.Write(DataActual, 0, 0xec); // 0000 writer.Write(Species); // 00EC writer.Write((byte)Gender); // 00EE writer.Write(Level); // 00EF writer.Write(RequestedSpecies); // 00F0 writer.Write((byte)RequestedGender); // 00F2 writer.Write(RequestedMinLevel); // 00F3 writer.Write(RequestedMaxLevel); // 00F4 writer.Write(Unknown1); // 00F5 writer.Write((byte)TrainerGender); // 00F6 writer.Write(Unknown2); // 00F7 writer.Write(DateToTimestamp(TimeDeposited)); // 00F8 writer.Write(DateToTimestamp(TimeExchanged)); // 0100 writer.Write(PID); // 0108 writer.Write(TrainerNameEncoded.RawData, 0, 0x10); // 010C writer.Write(TrainerOT); // 011C writer.Write(TrainerCountry); // 011E writer.Write(TrainerRegion); // 011F writer.Write(TrainerClass); // 0120 writer.Write(IsExchanged); // 0121 writer.Write((byte)TrainerVersion); // 0122 writer.Write((byte)TrainerLanguage); // 0123 } protected override void Load(BinaryReader reader) { DataActual = reader.ReadBytes(0xec); // 0000 Species = reader.ReadUInt16(); // 00EC Gender = (Genders)reader.ReadByte(); // 00EE Level = reader.ReadByte(); // 00EF RequestedSpecies = reader.ReadUInt16(); // 00F0 RequestedGender = (Genders)reader.ReadByte(); // 00F2 RequestedMinLevel = reader.ReadByte(); // 00F3 RequestedMaxLevel = reader.ReadByte(); // 00F4 Unknown1 = reader.ReadByte(); // 00F5 TrainerGender = (TrainerGenders)reader.ReadByte(); // 00F6 Unknown2 = reader.ReadByte(); // 00F7 TimeDeposited = TimestampToDate(reader.ReadUInt64()); // 00F8 TimeExchanged = TimestampToDate(reader.ReadUInt64()); // 0100 PID = reader.ReadInt32(); // 0108 TrainerNameEncoded = new EncodedString4(reader.ReadBytes(0x10)); // 010C TrainerOT = reader.ReadUInt16(); // 011C TrainerCountry = reader.ReadByte(); // 011E TrainerRegion = reader.ReadByte(); // 011F TrainerClass = reader.ReadByte(); // 0120 IsExchanged = reader.ReadByte(); // 0121 TrainerVersion = (Versions)reader.ReadByte(); // 0122 TrainerLanguage = (Languages)reader.ReadByte(); // 0123 } public override int Size { get { return 292; } } public GtsRecord4 Clone() { // todo: I am not very efficient return new GtsRecord4(m_pokedex, Save()); } public override bool Validate() { if (!base.Validate()) return false; // Forbid ball capsules. Credit: Gannio if (((PokemonParty4)Pokemon).CapsuleIndex != 0) return false; if (!TrainerNameEncoded.IsValid) return false; return true; } public bool CanTrade(GtsRecord4 other) { if (IsExchanged != 0 || other.IsExchanged != 0) return false; if (Species != other.RequestedSpecies) return false; if (other.RequestedGender != Genders.Either && Gender != other.RequestedGender) return false; if (!CheckLevels(other.RequestedMinLevel, other.RequestedMaxLevel, Level)) return false; if (RequestedSpecies != other.Species) return false; if (RequestedGender != Genders.Either && other.Gender != RequestedGender) return false; if (!CheckLevels(RequestedMinLevel, RequestedMaxLevel, other.Level)) return false; return true; } public void FlagTraded(GtsRecord4 other) { Species = other.Species; Gender = other.Gender; Level = other.Level; RequestedSpecies = other.RequestedSpecies; RequestedGender = other.RequestedGender; RequestedMinLevel = other.RequestedMinLevel; RequestedMaxLevel = other.RequestedMaxLevel; TimeDeposited = other.TimeDeposited; TimeExchanged = DateTime.UtcNow; PID = other.PID; IsExchanged = 0x01; } public override TrainerProfileBase ExtrapolateProfile() { TrainerProfile4 result = new TrainerProfile4(); result.PID = PID; result.Version = TrainerVersion; result.Language = TrainerLanguage; result.Country = TrainerCountry; result.Region = TrainerRegion; result.OT = TrainerOT; result.Name = TrainerNameEncoded.Clone(); return result; } public static bool operator ==(GtsRecord4 a, GtsRecord4 b) { if ((object)a == null && (object)b == null) return true; if ((object)a == null || (object)b == null) return false; // todo: optimize me return a.Save().SequenceEqual(b.Save()); } public static bool operator !=(GtsRecord4 a, GtsRecord4 b) { return !(a == b); } public override bool Equals(object obj) { return this.Equals(obj as GtsRecord4); } public bool Equals(GtsRecord4 other) { return this == other; } public override int GetHashCode() { return ((int)DateToBinary(TimeDeposited) + (int)DateToBinary(TimeExchanged)) ^ PID; } internal static long DateToBinary(DateTime ? dt) { if (dt == null) return 0L; return ((DateTime)dt).ToBinary(); } } } ================================================ FILE: library/Wfc/GtsRecord5.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; using System.IO; using PkmnFoundations.Structures; using PkmnFoundations.Support; using System.Collections.ObjectModel; namespace PkmnFoundations.Wfc { /// /// Structure used to represent Pokémon on the GTS in Generation V. /// Includes a Pokémon box structure and metadata related to the trainer /// and request. /// public class GtsRecord5 : GtsRecordBase, IEquatable { public GtsRecord5(Pokedex.Pokedex pokedex) : base(pokedex) { Initialize(); } public GtsRecord5(Pokedex.Pokedex pokedex, BinaryReader data) : base(pokedex) { Initialize(); Load(data); } public GtsRecord5(Pokedex.Pokedex pokedex, byte[] data) : base(pokedex) { Initialize(); Load(data); } public GtsRecord5(Pokedex.Pokedex pokedex, byte[] data, int offset) : base(pokedex) { Initialize(); Load(data, offset); } private void Initialize() { } /// /// Obfuscated Pokémon (pkm) data. 236 bytes /// public IList Data { get { return m_data_readonly; } set { DataActual = value.ToArray(); } } private byte[] DataActual { get { return m_data; } set { if (value == null) { m_data = null; m_data_readonly = null; m_pokemon = null; return; } if (value.Length != 0xEC) throw new ArgumentException("PKM length is incorrect"); m_data = value; m_data_readonly = new ReadOnlyCollection(m_data); m_pokemon = null; } } private byte[] m_data; private ReadOnlyCollection m_data_readonly; private PokemonParty5 m_pokemon; public override PokemonPartyBase Pokemon { get { if (DataActual == null || m_pokedex == null) return null; if (m_pokemon == null) m_pokemon = new PokemonParty5(m_pokedex, DataActual); return m_pokemon; } } public byte Unknown1; public byte Unknown2; public uint TrainerOT; /// /// 16 bytes /// public EncodedString5 TrainerNameEncoded; public override string TrainerName { get { if (TrainerNameEncoded == null) return null; return TrainerNameEncoded.Text; } set { if (TrainerNameEncoded == null) TrainerNameEncoded = new EncodedString5(value, 16); else TrainerNameEncoded.Text = value; } } public byte TrainerBadges; // speculative. Usually 8. public byte TrainerUnityTower; protected override void Save(BinaryWriter writer) { // todo: enclose in properties and validate these when assigning. if (TrainerNameEncoded.RawData.Length != 0x10) throw new FormatException("Trainer name length is incorrect"); writer.Write(DataActual, 0, 0xEC); // 0000 writer.Write(Species); // 00EC writer.Write((byte)Gender); // 00EE writer.Write(Level); // 00EF writer.Write(RequestedSpecies); // 00F0 writer.Write((byte)RequestedGender); // 00F2 writer.Write(RequestedMinLevel); // 00F3 writer.Write(RequestedMaxLevel); // 00F4 writer.Write(Unknown1); // 00F5 writer.Write((byte)TrainerGender); // 00F6 writer.Write(Unknown2); // 00F7 writer.Write(DateToTimestamp(TimeDeposited)); // 00F8 writer.Write(DateToTimestamp(TimeExchanged)); // 0100 writer.Write(PID); // 0108 writer.Write(TrainerOT); // 010C writer.Write(TrainerNameEncoded.RawData, 0, 0x10); // 0110 writer.Write(TrainerCountry); // 0120 writer.Write(TrainerRegion); // 0121 writer.Write(TrainerClass); // 0122 writer.Write(IsExchanged); // 0123 writer.Write((byte)TrainerVersion); // 0124 writer.Write((byte)TrainerLanguage); // 0125 writer.Write(TrainerBadges); // 0126 writer.Write(TrainerUnityTower); // 0127 } protected override void Load(BinaryReader reader) { DataActual = reader.ReadBytes(0xEC); // 0000 Species = reader.ReadUInt16(); // 00EC Gender = (Genders)reader.ReadByte(); // 00EE Level = reader.ReadByte(); // 00EF RequestedSpecies = reader.ReadUInt16(); // 00F0 RequestedGender = (Genders)reader.ReadByte(); // 00F2 RequestedMinLevel = reader.ReadByte(); // 00F3 RequestedMaxLevel = reader.ReadByte(); // 00F4 Unknown1 = reader.ReadByte(); // 00F5 TrainerGender = (TrainerGenders)reader.ReadByte(); // 00F6 Unknown2 = reader.ReadByte(); // 00F7 TimeDeposited = TimestampToDate(reader.ReadUInt64()); // 00F8 TimeExchanged = TimestampToDate(reader.ReadUInt64()); // 0100 PID = reader.ReadInt32(); // 0108 TrainerOT = reader.ReadUInt32(); // 010C TrainerNameEncoded = new EncodedString5(reader.ReadBytes(0x10)); // 0110 TrainerCountry = reader.ReadByte(); // 0120 TrainerRegion = reader.ReadByte(); // 0121 TrainerClass = reader.ReadByte(); // 0122 IsExchanged = reader.ReadByte(); // 0123 TrainerVersion = (Versions)reader.ReadByte(); // 0124 TrainerLanguage = (Languages)reader.ReadByte(); // 0125 TrainerBadges = reader.ReadByte(); // 0126 TrainerUnityTower = reader.ReadByte(); // 0127 } public override int Size { get { return 296; } } public GtsRecord5 Clone() { // todo: I am not very efficient return new GtsRecord5(m_pokedex, Save()); } public override bool Validate() { if (!base.Validate()) return false; if (!TrainerNameEncoded.IsValid) return false; return true; } public bool CanTrade(GtsRecord5 other) { if (IsExchanged != 0 || other.IsExchanged != 0) return false; if (Species != other.RequestedSpecies) return false; if (other.RequestedGender != Genders.Either && Gender != other.RequestedGender) return false; if (!CheckLevels(other.RequestedMinLevel, other.RequestedMaxLevel, Level)) return false; if (RequestedSpecies != other.Species) return false; if (RequestedGender != Genders.Either && other.Gender != RequestedGender) return false; if (!CheckLevels(RequestedMinLevel, RequestedMaxLevel, other.Level)) return false; return true; } public void FlagTraded(GtsRecord5 other) { Species = other.Species; Gender = other.Gender; Level = other.Level; RequestedSpecies = other.RequestedSpecies; RequestedGender = other.RequestedGender; RequestedMinLevel = other.RequestedMinLevel; RequestedMaxLevel = other.RequestedMaxLevel; TimeDeposited = other.TimeDeposited; TimeExchanged = DateTime.UtcNow; PID = other.PID; IsExchanged = 0x01; } public override TrainerProfileBase ExtrapolateProfile() { TrainerProfile5 result = new TrainerProfile5(); result.PID = PID; result.Version = TrainerVersion; result.Language = TrainerLanguage; result.Country = TrainerCountry; result.Region = TrainerRegion; result.OT = TrainerOT; result.Name = TrainerNameEncoded.Clone(); return result; } public static bool operator ==(GtsRecord5 a, GtsRecord5 b) { if ((object)a == null && (object)b == null) return true; if ((object)a == null || (object)b == null) return false; // todo: optimize me return a.Save().SequenceEqual(b.Save()); } public static bool operator !=(GtsRecord5 a, GtsRecord5 b) { return !(a == b); } public override bool Equals(object obj) { return this.Equals(obj as GtsRecord5); } public bool Equals(GtsRecord5 other) { return this == other; } public override int GetHashCode() { return ((int)GtsRecord4.DateToBinary(TimeDeposited) + (int)GtsRecord4.DateToBinary(TimeExchanged)) ^ PID; } } } ================================================ FILE: library/Wfc/GtsRecordBase.cs ================================================ using PkmnFoundations.Support; using System; using System.Collections.Generic; using System.Linq; using System.Text; using PkmnFoundations.Structures; namespace PkmnFoundations.Wfc { public abstract class GtsRecordBase : BinarySerializableBase { public GtsRecordBase(Pokedex.Pokedex pokedex) : base() { m_pokedex = pokedex; } protected Pokedex.Pokedex m_pokedex; public Pokedex.Pokedex Pokedex { get { return m_pokedex; } set { m_pokedex = value; } } public abstract PokemonPartyBase Pokemon { get; } /// /// National Dex species number /// public ushort Species; /// /// Pokémon gender /// public Genders Gender; /// /// Pokémon level /// public byte Level; /// /// Requested National Dex species number /// public ushort RequestedSpecies; public Genders RequestedGender; public byte RequestedMinLevel; public byte RequestedMaxLevel; public TrainerGenders TrainerGender; public DateTime? TimeDeposited; public DateTime? TimeExchanged; /// /// User ID of the player (not Personality Value) /// public int PID; public byte TrainerCountry; public byte TrainerRegion; public byte TrainerClass; public abstract string TrainerName { get; set; } public byte IsExchanged; public Versions TrainerVersion; public Languages TrainerLanguage; public ulong TradeId; public virtual bool Validate() { // note that IsExchanged only becomes true after FlagTraded is // called, which currently happens right as the exchanged record // is written to the database. So both post.asp and exchange.asp // validation is with IsExchanged == 0. bool isExchanged = IsExchanged != 0; ushort species = isExchanged ? RequestedSpecies : Species; Genders gender = isExchanged ? RequestedGender : Gender; byte minLevel = isExchanged ? RequestedMinLevel : Level; byte maxLevel = isExchanged ? RequestedMaxLevel : Level; PokemonPartyBase thePokemon = Pokemon; if (thePokemon.IsEgg) return false; if (thePokemon.SpeciesID != species) return false; if (gender != Genders.Either && thePokemon.Gender != gender) return false; if (!CheckLevels(minLevel, maxLevel, thePokemon.Level)) return false; // todo: move these checks to PokemonBase.Validate() if (thePokemon.IsBadEgg) return false; if (thePokemon.Level > 100) return false; if (thePokemon.EVs.ToArray().Select(i => (int)i).Sum() > 510) return false; ValidationSummary summary = Pokemon.Validate(); if (!summary.IsValid) return false; // pkhex check: // https://github.com/mm201/pkmn-classic-framework/pull/71 //var decrypted = PKX.DecryptArray45(DataActual); //var la = new LegalityAnalysis(decrypted); //report = la.Report(); //if (report != "Legal!") return false; return true; } public abstract TrainerProfileBase ExtrapolateProfile(); public static bool CheckLevels(byte min, byte max, byte other) { if (max == 0) max = 255; return other >= min && other <= max; } public static ulong DateToTimestamp(DateTime? date) { if (date == null) return 0; DateTime date2 = (DateTime)date; return (ulong)(date2.Year & 0xffff) << 0x30 | (ulong)(date2.Month & 0xff) << 0x28 | (ulong)(date2.Day & 0xff) << 0x20 | (ulong)(date2.Hour & 0xff) << 0x18 | (ulong)(date2.Minute & 0xff) << 0x10 | (ulong)(date2.Second & 0xff) << 0x08; } public static DateTime? TimestampToDate(ulong timestamp) { if (timestamp == 0) return null; ushort year = (ushort)((timestamp >> 0x30) & 0xffff); byte month = (byte)((timestamp >> 0x28) & 0xff); byte day = (byte)((timestamp >> 0x20) & 0xff); byte hour = (byte)((timestamp >> 0x18) & 0xff); byte minute = (byte)((timestamp >> 0x10) & 0xff); byte second = (byte)((timestamp >> 0x08) & 0xff); //byte fractional = (byte)(timestamp & 0xff); // always 0 try { return new DateTime(year, month, day, hour, minute, second); } catch (ArgumentOutOfRangeException) { return null; } } } } ================================================ FILE: library/Wfc/MusicalRecord5.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using PkmnFoundations.Support; namespace PkmnFoundations.Wfc { public class MusicalRecord5 : BinarySerializableBase { public MusicalRecord5() { } public MusicalRecord5(int pid, ulong serial_number, BinaryReader data) : base() { PID = pid; SerialNumber = serial_number; Load(data); } public MusicalRecord5(int pid, ulong serial_number, byte[] data) : base() { PID = pid; SerialNumber = serial_number; Load(data); } public MusicalRecord5(int pid, ulong serial_number, byte[] data, int offset) : base() { PID = pid; SerialNumber = serial_number; Load(data, offset); } // todo: encapsulate these so calculated fields are always correct public int PID { get; set; } public ulong SerialNumber { get; set; } private byte[] m_data; public byte[] Data { get { // fixme: Participants don't update if the consumer modifies this array directly. return m_data; } set { if (m_data == value) return; if (value == null) { m_data = null; return; } if (value.Length != 560) throw new ArgumentException("Musical data must be 560 bytes."); m_data = value.ToArray(); UpdateParticipants(); } } private MusicalParticipant5[] m_participants; public MusicalParticipant5[] Participants { get { // fixme: Data doesn't update if the consumer modifies this array. // todo: Split out participants from main data. return m_participants; } } public void UpdateParticipants() { if (m_data == null) { m_participants = null; return; } m_participants = new MusicalParticipant5[4]; for (int x = 0; x < 4; x++) { Participants[x] = new MusicalParticipant5(m_data, x * 0x58 + 0x84); } } public override int Size { get { return 560; } } protected override void Load(System.IO.BinaryReader reader) { m_data = reader.ReadBytes(560); UpdateParticipants(); } protected override void Save(System.IO.BinaryWriter writer) { writer.Write(m_data); } public MusicalRecord5 Clone() { return new MusicalRecord5(PID, SerialNumber, Data); } } public class MusicalParticipant5 : BinarySerializableBase { public MusicalParticipant5() { } public MusicalParticipant5(BinaryReader data) : base() { Load(data); } public MusicalParticipant5(byte[] data) : base() { Load(data); } public MusicalParticipant5(byte[] data, int offset) : base() { Load(data, offset); } private byte[] m_data; public byte[] Data { get { return m_data; } set { if (m_data == value) return; if (value == null) { m_data = null; return; } if (value.Length != 88) throw new ArgumentException("Musical Participant data must be 88 bytes."); m_data = value.ToArray(); } } public ushort Species { get { return BitConverter.ToUInt16(Data, 0); } } public override int Size { get { return 88; } } protected override void Load(System.IO.BinaryReader reader) { m_data = reader.ReadBytes(88); } protected override void Save(System.IO.BinaryWriter writer) { writer.Write(m_data); } public MusicalParticipant5 Clone() { return new MusicalParticipant5(Data); } } } ================================================ FILE: library/Wfc/PlazaQuestionnaire.cs ================================================ using System; using System.IO; namespace PkmnFoundations.Wfc { public class PlazaQuestionnaire { public PlazaQuestion CurrentQuestion; public PlazaQuestion LastWeeksQuestion; private int[] lastWeeksResults; public byte[] Unk; public PlazaQuestionnaire(PlazaQuestion currentQuestion, PlazaQuestion lastQuestion, int[] results, byte[] unk) { CurrentQuestion = currentQuestion; LastWeeksQuestion = lastQuestion; LastWeeksResults = results; Unk = unk; } public int[] LastWeeksResults { get { return lastWeeksResults; } set { if (value.Length != 3) { throw new ArgumentException("Results must be 3 integers! which represent the total count of each answer!"); } lastWeeksResults = value; } } public byte[] Save() { byte[] serialized = new byte[728]; MemoryStream ms = new MemoryStream(serialized); // BinaryWriter uses little endian which is what we want. BinaryWriter writer = new BinaryWriter(ms); writer.Write(CurrentQuestion.Save()); writer.Write(LastWeeksQuestion.Save()); foreach (int answer in LastWeeksResults) { writer.Write(answer); } writer.Write(Unk); writer.Flush(); ms.Flush(); return serialized; } public static PlazaQuestionnaire Load(byte[] data, int start) { PlazaQuestion question = PlazaQuestion.Load(data, start); PlazaQuestion lastWeeksQuestion = PlazaQuestion.Load(data, start + 352); int[] lastResults = new int[3]; int dataIdx = 704; for (byte idx = 0; idx < 3; ++idx) { lastResults[idx] = BitConverter.ToInt32(data, start + dataIdx); dataIdx += 4; } return new PlazaQuestionnaire( question, lastWeeksQuestion, lastResults, new byte[] { data[start + dataIdx], data[start + dataIdx + 1], data[start + dataIdx + 2], data[start + dataIdx + 3], data[start + dataIdx + 4], data[start + dataIdx + 5], data[start + dataIdx + 6], data[start + dataIdx + 7], data[start + dataIdx + 8], data[start + dataIdx + 9], data[start + dataIdx + 10], data[start + dataIdx + 11], }); } } /// /// A question that can be sent to a client for answering within the Wifi-Plaza. /// public class PlazaQuestion { /// /// Seems to be an internal ID as it's much higher than the week number should too the device /// from the responses we have captured. /// /// For us we just keep the IDs the same. /// /// The ID needs to be bigger than 1000 to show 'custom user text'. /// Otherwise, it overwrites the answers /// public int ID; /// The public ID, or week number shown to devices. public int PublicID; /// /// The sentence of the question, to actually show. /// /// Although the final question can't be more than 220 bytes encoded (110 characters since it's UTF-16). /// Although in reality, each line can only be 35 characters before needing a 'new line', spanned across /// two lines. /// /// Extra newlines are ignored. /// private string QuestionSentence; /// /// The three answers to the question. /// /// Each answer should be 36 bytes encoded (18 characters since it's UTF-16). /// If there is an unprintable character, they repeat the last printable character. /// Answers should not have newlines otherwise they can overwrite other lines. /// private string[] QuestionAnswers; /// A series of unknown bytes. public byte[] Unk; /// If the question is a 'special' question, and the man in the plaza will say so. public bool IsSpecial; public PlazaQuestion(int id, string sentence, string[] answers, byte[] unk, bool isSpecial) { ID = id; PublicID = id; Unk = unk; Sentence = sentence; Answers = answers; IsSpecial = isSpecial; } private PlazaQuestion(int id, int publicID, string sentence, string[] answers, byte[] unk, bool isSpecial) { ID = id; PublicID = publicID; Unk = unk; QuestionSentence = sentence; QuestionAnswers = answers; IsSpecial = isSpecial; } public string Sentence { get { return QuestionSentence; } set { // TODO add some validation on max length here. QuestionSentence = value; } } public string[] Answers { get { return QuestionAnswers; } set { if (value.Length != 3) { throw new ArgumentException("You MUST supply 3 answers for a particular question!"); } // TODO validate encoded size QuestionAnswers = value; } } public byte[] Save() { byte[] serialized = new byte[352]; MemoryStream ms = new MemoryStream(serialized); // BinaryWriter uses little endian which is what we want. BinaryWriter writer = new BinaryWriter(ms); writer.Write(ID); writer.Write(PublicID); byte[] encodedQuestion = Support.EncodedString4.EncodeString_impl(QuestionSentence, 220); writer.Write(encodedQuestion); foreach (string answer in QuestionAnswers) { byte[] encodedAnswer = Support.EncodedString4.EncodeString_impl(answer, 36); writer.Write(encodedAnswer); } writer.Write(Unk); writer.Write((int)(IsSpecial ? 1 : 0)); writer.Flush(); ms.Flush(); return serialized; } public static PlazaQuestion Load(byte[] data, int start) { int internalID = BitConverter.ToInt32(data, start); int publicID = BitConverter.ToInt32(data, start + 4); byte[] questionBytes = new byte[220]; Array.Copy(data, 8 + start, questionBytes, 0, 220); string question = Support.EncodedString4.DecodeString_impl(questionBytes); string[] answers = new string[3]; int dataIdx = 228 + start; for (byte idx = 0; idx < 3; idx++) { byte[] answerBytes = new byte[36]; Array.Copy(data, dataIdx, answerBytes, 0, 36); answers[idx] = Support.EncodedString4.DecodeString_impl(answerBytes); dataIdx += 36; } byte[] unk = new byte[] { data[start + 336], data[start + 337], data[start + 338], data[start + 339], data[start + 340], data[start + 341], data[start + 342], data[start + 343], data[start + 344], data[start + 345], data[start + 346], data[start + 347], }; bool isSpecial = BitConverter.ToInt32(data, start + 348) != 0; return new PlazaQuestion(internalID, publicID, question, answers, unk, isSpecial); } } public class SubmittedQuestionnaire { public int ID; public int PublicID; private int answerNo; public uint OT; public Structures.TrainerGenders TrainerGender; public uint Country; public uint Region; public SubmittedQuestionnaire(int id, int publicID, int answerNumber, uint ot, Structures.TrainerGenders gender, uint country, uint region) { ID = id; PublicID = publicID; AnswerNumber = answerNumber; OT = ot; TrainerGender = gender; Country = country; Region = region; } public int AnswerNumber { get { return answerNo; } set { if (value > 3 || value < 0) { throw new ArgumentException("Answer can only be 0-3!"); } answerNo = value; } } public byte[] Save() { byte[] serialized = new byte[24]; MemoryStream ms = new MemoryStream(serialized); // BinaryWriter uses little endian which is what we want. BinaryWriter writer = new BinaryWriter(ms); writer.Write(ID); writer.Write(PublicID); writer.Write(answerNo); writer.Write(OT); writer.Write((int)TrainerGender); writer.Write(Country); writer.Write(Region); writer.Flush(); ms.Flush(); return serialized; } public static SubmittedQuestionnaire Load(byte[] data, int start) { int id = BitConverter.ToInt32(data, start); int publicId = BitConverter.ToInt32(data, start + 4); int answerNo = BitConverter.ToInt32(data, start + 8); uint ot = BitConverter.ToUInt32(data, start + 12); int genderNum = BitConverter.ToInt32(data, start + 16); ushort country = BitConverter.ToUInt16(data, start + 20); ushort region = BitConverter.ToUInt16(data, start + 22); return new SubmittedQuestionnaire(id, publicId, answerNo, ot, (Structures.TrainerGenders)genderNum, country, region); } } } ================================================ FILE: library/Wfc/PlazaSchedule.cs ================================================ using PkmnFoundations.Support; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace PkmnFoundations.Wfc { public class PlazaSchedule : BinarySerializableBase { public PlazaSchedule() { } public PlazaSchedule(uint duration, int unknown1, PlazaFootprintOptions footprintOptions, PlazaRoomTypes roomType, PlazaSeasons season, PlazaScheduleEntry[] schedule) { Duration = duration; Unknown1 = unknown1; FootprintOptions = footprintOptions; RoomType = roomType; Season = season; Schedule = schedule; } public PlazaSchedule(byte[] data) { Load(data); } public uint Duration; // Duration the room remains open for (seconds) public int Unknown1; // Unknown, Mythra thinks it may be a random seed public PlazaFootprintOptions FootprintOptions; public PlazaRoomTypes RoomType; public PlazaSeasons Season; public PlazaScheduleEntry[] Schedule; protected override void Load(BinaryReader reader) { Duration = reader.ReadUInt32(); Unknown1 = reader.ReadInt32(); FootprintOptions = (PlazaFootprintOptions)reader.ReadInt32(); RoomType = (PlazaRoomTypes)reader.ReadByte(); Season = (PlazaSeasons)reader.ReadByte(); ushort schedLength = reader.ReadUInt16(); Schedule = new PlazaScheduleEntry[schedLength]; for (int i = 0; i < schedLength; i++) { Schedule[i] = new PlazaScheduleEntry(reader.ReadBytes(8)); } } protected override void Save(BinaryWriter writer) { writer.Write(Duration); writer.Write(Unknown1); writer.Write((int)FootprintOptions); writer.Write((byte)RoomType); writer.Write((byte)Season); var schedule = Schedule; writer.Write((ushort)schedule.Length); foreach (var entry in schedule) { writer.Write(entry.Save()); } } public override int Size { get { return 16 + (Schedule?.Length ?? 0) * 8; } } } public class PlazaScheduleEntry : BinarySerializableBase { public PlazaScheduleEntry() { } public PlazaScheduleEntry(int time, PlazaEventTypes eventType) { Time = time; EventType = eventType; } public PlazaScheduleEntry(byte[] data) { Load(data); } protected override void Load(BinaryReader reader) { Time = reader.ReadInt32(); EventType = (PlazaEventTypes)reader.ReadInt32(); } protected override void Save(BinaryWriter writer) { writer.Write(Time); writer.Write((int)EventType); } public override int Size { get { return 8; } } public int Time; public PlazaEventTypes EventType; } public enum PlazaFootprintOptions : int { Normal = 0, Arceus = 1, } public enum PlazaRoomTypes : byte { Fire = 0, Water = 1, Electric = 2, Grass = 3, Mew = 4, } public enum PlazaSeasons : byte { None = 0, Spring = 1, Summer = 2, Fall = 3, Winter = 4, } public enum PlazaEventTypes : int { // todo: Catalogue all of these and identify which ones are valid when. } } ================================================ FILE: library/Wfc/TrainerProfile4.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using PkmnFoundations.Support; namespace PkmnFoundations.Wfc { public class TrainerProfile4 : TrainerProfileBase { public TrainerProfile4() : base() { } public TrainerProfile4(int pid, byte[] data, string ip_address) : base(pid, data, ip_address) { } public EncodedString4 Name { get { return new EncodedString4(Data, 8, 16); } set { Array.Copy(value.RawData, 0, Data, 8, 16); } } public TrainerProfile4 Clone() { return new TrainerProfile4(PID, Data.ToArray(), IpAddress); } } } ================================================ FILE: library/Wfc/TrainerProfile5.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using PkmnFoundations.Support; namespace PkmnFoundations.Wfc { public class TrainerProfile5 : TrainerProfileBase { public TrainerProfile5() : base() { } public TrainerProfile5(int pid, byte[] data, string ip_address) : base(pid, data, ip_address) { } public EncodedString5 Name { get { return new EncodedString5(Data, 8, 16); } set { Array.Copy(value.RawData, 0, Data, 8, 16); } } public TrainerProfile5 Clone() { return new TrainerProfile5(PID, Data.ToArray(), IpAddress); } } } ================================================ FILE: library/Wfc/TrainerProfileBase.cs ================================================ using PkmnFoundations.Structures; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace PkmnFoundations.Wfc { public abstract class TrainerProfileBase { protected TrainerProfileBase() { } protected TrainerProfileBase(int pid, byte[] data, string ip_address) { if (data == null) throw new ArgumentNullException("data"); if (data.Length != 100) throw new ArgumentException("Profile data must be 100 bytes."); PID = pid; Data = data; IpAddress = ip_address; } // todo: encapsulate these so calculated fields are always correct public int PID; public byte[] Data; // 100 bytes public string IpAddress; public Versions Version { get { return (Versions)Data[0]; } set { Data[0] = (byte)value; } } public Languages Language { get { return (Languages)Data[1]; } set { Data[1] = (byte)value; } } public byte Country { get { return Data[2]; } set { Data[2] = value; } } public byte Region { get { return Data[3]; } set { Data[3] = value; } } public uint OT { get { return BitConverter.ToUInt32(Data, 4); } set { Array.Copy(BitConverter.GetBytes(value), 0, Data, 4, 4); } } /* // xxx: This would require C# 9 covariant return types to work. https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/covariant-returns public abstract EncodedStringBase Name { get; } */ public byte[] MacAddress { get { byte[] result = new byte[6]; Array.Copy(Data, 28, result, 0, 6); return result; } } public string Email { get { StreamReader br = new StreamReader(new MemoryStream(Data, 36, 56), Encoding.UTF8); string result = br.ReadToEnd().TrimEnd('\0'); br.Close(); return result; } } public bool HasNotifications { get { return Data[92] != 0; } } public short ClientSecret { get { return BitConverter.ToInt16(Data, 96); } } public short MailSecret { get { return BitConverter.ToInt16(Data, 98); } } } } ================================================ FILE: library/Wfc/TrainerProfilePlaza.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using PkmnFoundations.Structures; using PkmnFoundations.Support; namespace PkmnFoundations.Wfc { public class TrainerProfilePlaza { public TrainerProfilePlaza() { } public TrainerProfilePlaza(int pid, byte[] data) { if (data.Length != 164) throw new ArgumentException("Profile data must be 164 bytes."); PID = pid; Data = data; } // todo: encapsulate these so calculated fields are always correct public int PID; public byte[] Data; // 164 bytes // todo: Add more fields public Versions Version { get { return (Versions)Data[0x02]; } } public Languages Language { get { return (Languages)Data[0x03]; } } public byte[] MacAddress { get { byte[] result = new byte[6]; Array.Copy(Data, 0x04, result, 0, 0x06); return result; } } public uint OT { get { return BitConverter.ToUInt32(Data, 0x14); } } public EncodedString4 Name { get { return new EncodedString4(Data, 0x18, 0x10); } } // todo: favourite pokemon public TrainerGenders Gender { get { return (TrainerGenders)Data[0x48]; } } public byte Country { get { return Data[0x4c]; } } public byte Region { get { return Data[0x4e]; } } public TrainerProfilePlaza Clone() { return new TrainerProfilePlaza(PID, Data.ToArray()); } } } ================================================ FILE: library/Wfc/TrainerRankings.cs ================================================ using PkmnFoundations.Structures; using PkmnFoundations.Support; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace PkmnFoundations.Wfc { public class TrainerRankingsReport { public TrainerRankingsReport(DateTime start_date, DateTime end_date, TrainerRankingsLeaderboardGroup[] leaderboards) { StartDate = start_date; EndDate = end_date; Leaderboards = leaderboards; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public TrainerRankingsLeaderboardGroup[] Leaderboards { get; set; } public void PadResults() { foreach (var group in Leaderboards) { group.PadResults(StartDate); } } } public class TrainerRankingsLeaderboardGroup { public TrainerRankingsLeaderboardGroup(TrainerRankingsRecordTypes record_type, TrainerRankingsLeaderboard leaderboard_trainer_class, TrainerRankingsLeaderboard leaderboard_birth_month, TrainerRankingsLeaderboard leaderboard_favourite_pokemon) { RecordType = record_type; LeaderboardTrainerClass = leaderboard_trainer_class; LeaderboardBirthMonth = leaderboard_birth_month; LeaderboardFavouritePokemon = leaderboard_favourite_pokemon; } public TrainerRankingsRecordTypes RecordType { get; set; } public TrainerRankingsLeaderboard LeaderboardTrainerClass { get; set; } public TrainerRankingsLeaderboard LeaderboardBirthMonth { get; set; } public TrainerRankingsLeaderboard LeaderboardFavouritePokemon { get; set; } public void PadResults(DateTime startDate) { LeaderboardTrainerClass.PadResults(startDate, 16, 0, 16); LeaderboardBirthMonth.PadResults(startDate, 12, 1, 12); LeaderboardFavouritePokemon.PadResults(startDate, 20, 1, 493); } } public class TrainerRankingsLeaderboard { public TrainerRankingsLeaderboard(TrainerRankingsTeamCategories team_category, TrainerRankingsLeaderboardEntry[] entries) { TeamCategory = team_category; Entries = entries; } public TrainerRankingsTeamCategories TeamCategory { get; set; } public TrainerRankingsLeaderboardEntry[] Entries { get; set; } public void PadResults(DateTime startDate, int entryCount, int minTeam, int teamCount) { IEnumerable working = Entries; if (Entries.Length < teamCount) { var unusedValues = Enumerable.Range(minTeam, teamCount) .DrawWithoutReplacement(new Random((int)startDate.Ticks + 69420)) .Take(entryCount) .Where(i => !Entries.Select(e => e.Team).Contains(i)); working = Entries.Concat(unusedValues.Select(i => new TrainerRankingsLeaderboardEntry(i, 0))); } // todo: shuffle ties maybe... Entries = working.Take(entryCount).ToArray(); } } public class TrainerRankingsLeaderboardEntry { public TrainerRankingsLeaderboardEntry(int team, long score) { Team = team; Score = score; } public int Team { get; set; } public long Score { get; set; } } public enum TrainerRankingsRecordTypes : int { // todo: document these //Invalid = 0x00, // Seems to trigger a 'there is no data' if used. HallOfFameEntries = 0x01, //Blank02 = 0x02, //Blank03 = 0x03, //Blank04 = 0x04, //BattleTowerSingleBattleWinStreak = 0x05, // crashes when asked for //Blank06 = 0x06, // crashes when asked for //BattleTowerDoubleBattleWinStreak = 0x07, // crashes when asked for //Blank08 = 0x08, // crashes when asked for //BattleTowerMultiBattleWinStreak = 0x09, // crashes when asked for //Blank0a = 0x0a, // crashes when asked for //BattleTowerPartneredMultiBattleWinStreak = 0x0b, // crashes when asked for //Blank0c = 0x0c, // crashes when asked for //WiFiBattleTowerWinStreak = 0x0d, // crashes when asked for //Blank0e = 0x0e, // crashes when asked for ContestsEnteredAlone = 0x0f, ContestsEnteredWithFriends = 0x10, ContestsEnteredAloneAndWon = 0x11, ContestsEnteredWithFriendsAndWon = 0x12, //Blank13 = 0x13, //Blank14 = 0x14, //Blank15 = 0x15, //Blank16 = 0x16, //Blank17 = 0x17, TimesWildPokemonFled = 0x18, //Blank19 = 0x19, BerriesPlanted = 0x1a, StepsWalked = 0x1b, TimesBattledWildPokemon = 0x1c, TrainerBattlesExcludingUnionRoomAndFrontier = 0x1d, PokemonCaught = 0x1e, PokemonCaughtFishing = 0x1f, EggsHatched = 0x20, TimesOwnPokemonEvolved = 0x21, GameCornerSlotJackpots = 0x22, BattleTowerChallenges = 0x23, // seems to say Frontier on Platinum but Tower on HGSS //Blank24 = 0x24, //Blank25 = 0x25, //Blank26 = 0x26, //Blank27 = 0x27, CompletedGtsPokemonTrades = 0x28, BattlesWonOverNintendoWiFiConnection = 0x29, //Blank2a = 0x2a, BattlesTiedOverNintendoWiFiConnection = 0x2b, BattlesWonAtTheBattleTower = 0x2c, TotalMoneySpentShopping = 0x2d, PokemonLeftWithTheDayCare = 0x2e, PokemonDefeated = 0x2f, PokemonOfferedOnGts = 0x30, TimesPokemonWereTradedWithFriendsAtTheWiFiClub = 0x31, TimesYouSignedYourTrainerCard = 0x32, PokemonExtractedFromFossils = 0x33, TimesFootprintsWereCheckedByDrFootstep = 0x34, TimesMailWasSent = 0x35, WildPokemonLuredUsingHoney = 0x36, TimesYouTalkedToSomeoneInTheWiFiPlaza = 0x37, NumberOfSpheresBuriedInTheUnderground = 0x38, TimesWatchedTv = 0x39, TimesPokemonWereGivenNicknames = 0x3a, PremierBallsReceived = 0x3b, ItemsFoundByPokemonInAmitySquare = 0x3c, PoffinsCookedAlone = 0x3d, PoffinsCookedWithFriends = 0x3e, PokemonDressUpDataPhotosTaken = 0x3f, BouldersPushedUsingTheHiddenMoveStrength = 0x40, TimesMiredInASwamp = 0x41, MatchesAgainstYourRivalAndGymLeadersAtTheBattleground = 0x42, FacilitiesChallengedAtTheBattleFrontier = 0x43, TimesYouMetTheFrontierBrains = 0x44, WinsAtTheBattleFactory = 0x45, WinsAtTheBattleCastle = 0x46, WinsAtTheBattleHall = 0x47, WinsAtTheBattleArcade = 0x48, PokemonTradesAtTheBattleFactory = 0x49, TotalCastlePointsEarnedAtTheBattleCastle = 0x4a, WinsOverRank10PokemonAtTheBattleHall = 0x4b, BattlePointsEarnedFromTheBattleArcadeGameBoard = 0x4c, TotalBattlePointsWon = 0x4d, TotalBattlePointsSpent = 0x4e, WiFiPlazaGamesPlayed = 0x4f, EggsTradedUsingSpinTrade = 0x50, StarPiecesTradedAtTheFuegoIronworks = 0x51, //BattlePointsEarnedFromTheBattleArcadeGameBoard52 = 0x52, // crashes when asked for //ItemsAndBerriesEarnedFromTheBattleArcadeGameBoard53 = 0x53, // crashes when asked for //TotalBattlePointsWon54 = 0x54, // crashes when asked for //TotalBattlePointsSpent55 = 0x55, // crashes when asked for //WinsInWiFiPlazaGames = 0x56, // crashes when asked for //EggsTradedUsingSpinTrade57 = 0x57, // crashes when asked for //Blank58 = 0x58, // crashes when asked for //Blank59 = 0x59, // crashes when asked for //Blank5a = 0x5a, // crashes when asked for //BlueScreen = 0x5b } public enum TrainerClass : int { SchoolKidMale = 0x00, BugCatcher = 0x01, AceTrainerMale = 0x02, Roughneck = 0x03, RuinManiac = 0x04, BlackBelt = 0x05, RichBoy = 0x06, PsychicMale = 0x07, Lass = 0x08, BattleGirl = 0x09, Beauty = 0x0a, AceTrainerFemale = 0x0b, Idol = 0x0c, Socialite = 0x0d, Cowgirl = 0x0e, Lady = 0x0f, // Plato = 0x10, // ??? o_O // 0x11 and up blue screen } public enum TrainerRankingsTeamCategories { BirthMonth, TrainerClass, FavouritePokemon } public class TrainerRankingsSubmission : BinarySerializableBase { public TrainerRankingsSubmission(int pid, Versions version, Languages language, byte birth_month, byte trainer_class, ushort favourite_pokemon, ushort unknown1, ushort unknown2, ushort unknown3, TrainerRankingsSubmissionEntry[] entries) { PID = pid; Version = version; Language = language; BirthMonth = birth_month; TrainerClass = trainer_class; FavouritePokemon = favourite_pokemon; Unknown1 = unknown1; // usually 0 but I've seen the occasional 1. Unknown2 = unknown2; // seems to max at 999. Probably play time in hours Unknown3 = unknown3; // seems to max around 15163. Entries = entries; } public TrainerRankingsSubmission(int pid, byte[] data, int offset) { PID = pid; Load(data, offset); } public TrainerRankingsSubmission(int pid, byte[] data) { PID = pid; Load(data); } public TrainerRankingsSubmission(int pid, BinaryReader reader) { PID = pid; Load(reader); } protected override void Load(BinaryReader reader) { // AdmiralCurtiss's request: // 0140: 0c02050900000000 1800303b01000000 // 0150: 0100000028000000 0000000043000000 // 0160: 00000000 // Hikari's request: // Platinum EN July [I forget] Gallade // 0140: 0c02070bdb010000 e200350f01000000 // 0150: 0300000028000000 0800000043000000 // 0160: 28000000 // 140: Version // 141: Language // 142: Birth Month // 143: Trainer Class // 144-145: Favourite Pokémon // 146-14b: Unknown // 14c-163: Three record records // Record record contains 4 bytes of category and 4 bytes of my score in the category. Version = (Versions)reader.ReadByte(); // 00-00 Language = (Languages)reader.ReadByte(); // 01-01 BirthMonth = reader.ReadByte(); // 02-02 TrainerClass = reader.ReadByte(); // 03-03 FavouritePokemon = reader.ReadUInt16(); // 04-05 Unknown1 = reader.ReadUInt16(); // 06-07 Unknown2 = reader.ReadUInt16(); // 08-09 Unknown3 = reader.ReadUInt16(); // 0a-0b var entries = new TrainerRankingsSubmissionEntry[3]; entries[0] = new TrainerRankingsSubmissionEntry(reader); // 0c-13 entries[1] = new TrainerRankingsSubmissionEntry(reader); // 14-1b entries[2] = new TrainerRankingsSubmissionEntry(reader); // 1c-23 Entries = entries; } protected override void Save(BinaryWriter writer) { writer.Write((byte)Version); // 00-00 writer.Write((byte)Language); // 01-01 writer.Write(BirthMonth); // 02-02 writer.Write(TrainerClass); // 03-03 writer.Write(FavouritePokemon); // 04-05 writer.Write(Unknown1); // 06-07 writer.Write(Unknown2); // 08-09 writer.Write(Unknown3); // 0a-0b writer.Write(Entries[0].Save()); // 0c-13 writer.Write(Entries[1].Save()); // 14-1b writer.Write(Entries[2].Save()); // 1c-23 } public override int Size { get { return 36; } } public int PID { get; set; } public Versions Version { get; set; } public Languages Language { get; set; } public byte BirthMonth { get; set; } public byte TrainerClass { get; set; } public ushort FavouritePokemon { get; set; } public ushort Unknown1 { get; set; } public ushort Unknown2 { get; set; } public ushort Unknown3 { get; set; } private TrainerRankingsSubmissionEntry[] m_entries; public TrainerRankingsSubmissionEntry[] Entries { get { return m_entries; } set { if (value == null) throw new ArgumentNullException(); if (value.Length != 3) throw new ArgumentException("TrainerRankingsSubmission must have exactly 3 entries."); m_entries = value; } } } public class TrainerRankingsSubmissionEntry : BinarySerializableBase { public TrainerRankingsSubmissionEntry(TrainerRankingsRecordTypes record_type, uint score) { RecordType = record_type; Score = score; } public TrainerRankingsSubmissionEntry(byte[] data, int offset) { Load(data, offset); } public TrainerRankingsSubmissionEntry(byte[] data) { Load(data); } public TrainerRankingsSubmissionEntry(BinaryReader reader) { Load(reader); } protected override void Load(BinaryReader reader) { RecordType = (TrainerRankingsRecordTypes)reader.ReadInt32(); // 00 Score = reader.ReadUInt32(); // 04 } protected override void Save(BinaryWriter writer) { writer.Write((int)RecordType); // 00 writer.Write(Score); // 04 } public override int Size { get { return 8; } } public TrainerRankingsRecordTypes RecordType { get; set; } public uint Score { get; set; } } } ================================================ FILE: library/Wfc/VipRecord.cs ================================================ using PkmnFoundations.Support; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace PkmnFoundations.Wfc { public class VipRecord : BinarySerializableBase { public VipRecord() { Pid = 0; WordPartA = 0; WordPartB = 0; WordPartC = 0; WordPartD = 0; } public VipRecord(uint pid) { Pid = pid; WordPartA = 0; WordPartB = 0; WordPartC = 0; WordPartD = 0; } public VipRecord(uint pid, byte wordA, byte wordB, byte wordC, byte wordD) { Pid = pid; WordPartA = wordA; WordPartB = wordB; WordPartC = wordC; WordPartD = wordD; } public VipRecord(byte[] data) { Load(data); } public uint Pid; // Profile id of the user who is a VIP. public byte WordPartA; // D + A creates first word, A + B creates second word. public byte WordPartB; // A + B creates second word, B + C creates third word. public byte WordPartC; // B + C creates third word, C + D creates fourth word. public byte WordPartD; // D + A creates first word, C + D creates fourth word. protected override void Load(BinaryReader reader) { Pid = reader.ReadUInt32(); WordPartA = reader.ReadByte(); WordPartB = reader.ReadByte(); WordPartC = reader.ReadByte(); WordPartD = reader.ReadByte(); } protected override void Save(BinaryWriter writer) { writer.Write(Pid); writer.Write(WordPartA); writer.Write(WordPartB); writer.Write(WordPartC); writer.Write(WordPartD); } public override int Size { get { return 8; } } } } ================================================ FILE: library/app.config ================================================  ================================================ FILE: library/database.sql ================================================ -- -------------------------------------------------------- -- Host: 127.0.0.1 -- Server version: 10.5.16-MariaDB - mariadb.org binary distribution -- Server OS: Win64 -- HeidiSQL Version: 12.1.0.6537 -- -------------------------------------------------------- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET NAMES utf8 */; /*!50503 SET NAMES utf8mb4 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- Dumping structure for table gts.BattleVideoCrawlQueue CREATE TABLE IF NOT EXISTS `BattleVideoCrawlQueue` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `SerialNumber` bigint(11) unsigned DEFAULT NULL, `Timestamp` datetime DEFAULT NULL, `Complete` bit(1) DEFAULT b'0', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.BattleVideoCrawlQueue5 CREATE TABLE IF NOT EXISTS `BattleVideoCrawlQueue5` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `SerialNumber` bigint(11) unsigned DEFAULT NULL, `Timestamp` datetime DEFAULT NULL, `Complete` bit(1) DEFAULT b'0', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.BattleVideoSearchHistory CREATE TABLE IF NOT EXISTS `BattleVideoSearchHistory` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `Metagame` int(11) DEFAULT NULL, `Species` int(11) DEFAULT NULL, `Country` int(11) DEFAULT NULL, `Region` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.BattleVideoSearchHistory5 CREATE TABLE IF NOT EXISTS `BattleVideoSearchHistory5` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `Metagame` int(11) DEFAULT NULL, `Species` int(11) DEFAULT NULL, `Country` int(11) DEFAULT NULL, `Region` int(11) DEFAULT NULL, `Special` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.GtsBattleSubway5 CREATE TABLE IF NOT EXISTS `GtsBattleSubway5` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `pid` int(11) NOT NULL, `Name` binary(16) DEFAULT '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0', `Version` tinyint(3) unsigned DEFAULT NULL, `Language` tinyint(3) unsigned DEFAULT NULL, `Country` tinyint(3) unsigned DEFAULT NULL, `Region` tinyint(3) unsigned DEFAULT NULL, `TrainerID` int(10) unsigned DEFAULT NULL, `PhraseLeader` binary(8) DEFAULT NULL, `Gender` tinyint(3) unsigned DEFAULT NULL, `Unknown2` tinyint(3) unsigned DEFAULT NULL, `PhraseChallenged` binary(8) DEFAULT NULL, `PhraseWon` binary(8) DEFAULT NULL, `PhraseLost` binary(8) DEFAULT NULL, `Unknown3` smallint(5) unsigned DEFAULT NULL, `Unknown4` binary(5) DEFAULT NULL, `Unknown5` bigint(20) DEFAULT NULL, `ParseVersion` int(10) unsigned DEFAULT NULL, `Rank` tinyint(3) unsigned DEFAULT NULL, `RoomNum` tinyint(3) unsigned NOT NULL DEFAULT 0, `BattlesWon` tinyint(3) unsigned DEFAULT NULL, `Position` int(10) unsigned DEFAULT NULL, `TimeAdded` datetime DEFAULT NULL, `TimeUpdated` datetime DEFAULT NULL, PRIMARY KEY (`id`), KEY `RoomNum` (`RoomNum`,`Rank`,`Position`), KEY `pid` (`pid`,`RoomNum`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.GtsBattleSubwayLeaders5 CREATE TABLE IF NOT EXISTS `GtsBattleSubwayLeaders5` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `pid` int(11) NOT NULL DEFAULT 0, `Name` binary(16) DEFAULT NULL, `Version` tinyint(3) unsigned DEFAULT NULL, `Language` tinyint(3) unsigned DEFAULT NULL, `Country` tinyint(3) unsigned DEFAULT NULL, `Region` tinyint(3) unsigned DEFAULT NULL, `TrainerID` int(10) unsigned DEFAULT NULL, `PhraseLeader` binary(8) DEFAULT NULL, `Gender` tinyint(3) unsigned DEFAULT NULL, `Unknown2` tinyint(3) unsigned DEFAULT NULL, `ParseVersion` int(10) unsigned DEFAULT NULL, `Rank` tinyint(3) unsigned DEFAULT NULL, `RoomNum` tinyint(3) unsigned NOT NULL DEFAULT 0, `TimeAdded` datetime DEFAULT NULL, `TimeUpdated` datetime DEFAULT NULL, PRIMARY KEY (`id`), KEY `RoomNum` (`RoomNum`,`Rank`,`TimeAdded`), KEY `pid` (`pid`,`RoomNum`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.GtsBattleSubwayPokemon5 CREATE TABLE IF NOT EXISTS `GtsBattleSubwayPokemon5` ( `party_id` bigint(20) unsigned NOT NULL, `Slot` tinyint(3) unsigned NOT NULL, `Species` smallint(5) unsigned DEFAULT NULL, `Form` smallint(5) unsigned DEFAULT NULL, `HeldItem` smallint(5) unsigned DEFAULT NULL, `Move1` smallint(5) unsigned DEFAULT NULL, `Move2` smallint(5) unsigned DEFAULT NULL, `Move3` smallint(5) unsigned DEFAULT NULL, `Move4` smallint(5) unsigned DEFAULT NULL, `TrainerID` int(10) unsigned DEFAULT NULL, `Personality` int(10) unsigned DEFAULT NULL, `IVs` int(10) unsigned DEFAULT NULL, `EVs` binary(6) DEFAULT NULL, `Unknown1` tinyint(3) unsigned DEFAULT NULL, `Language` tinyint(3) unsigned DEFAULT NULL, `Ability` tinyint(3) unsigned DEFAULT NULL, `Happiness` tinyint(3) unsigned DEFAULT NULL, `Nickname` binary(22) DEFAULT NULL, `Unknown2` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`party_id`,`Slot`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.GtsBattleTower4 CREATE TABLE IF NOT EXISTS `GtsBattleTower4` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `pid` int(11) NOT NULL, `Name` binary(16) DEFAULT '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0', `Version` tinyint(3) unsigned DEFAULT NULL, `Language` tinyint(3) unsigned DEFAULT NULL, `Country` tinyint(3) unsigned DEFAULT NULL, `Region` tinyint(3) unsigned DEFAULT NULL, `TrainerID` int(10) unsigned DEFAULT NULL, `PhraseLeader` binary(8) DEFAULT NULL, `Gender` tinyint(3) unsigned DEFAULT NULL, `Unknown2` tinyint(3) unsigned DEFAULT NULL, `PhraseChallenged` binary(8) DEFAULT NULL, `PhraseWon` binary(8) DEFAULT NULL, `PhraseLost` binary(8) DEFAULT NULL, `Unknown3` smallint(5) unsigned DEFAULT NULL, `Unknown5` bigint(20) DEFAULT NULL, `ParseVersion` int(10) unsigned DEFAULT NULL, `Rank` tinyint(3) unsigned DEFAULT NULL, `RoomNum` tinyint(3) unsigned NOT NULL DEFAULT 0, `BattlesWon` tinyint(3) unsigned DEFAULT NULL, `Position` int(10) unsigned DEFAULT NULL, `TimeAdded` datetime DEFAULT NULL, `TimeUpdated` datetime DEFAULT NULL, PRIMARY KEY (`id`), KEY `RoomNum` (`RoomNum`,`Rank`,`Position`), KEY `pid` (`pid`,`RoomNum`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.GtsBattleTowerLeaders4 CREATE TABLE IF NOT EXISTS `GtsBattleTowerLeaders4` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `pid` int(11) NOT NULL DEFAULT 0, `Name` binary(16) DEFAULT NULL, `Version` tinyint(3) unsigned DEFAULT NULL, `Language` tinyint(3) unsigned DEFAULT NULL, `Country` tinyint(3) unsigned DEFAULT NULL, `Region` tinyint(3) unsigned DEFAULT NULL, `TrainerID` int(10) unsigned DEFAULT NULL, `PhraseLeader` binary(8) DEFAULT NULL, `Gender` tinyint(3) unsigned DEFAULT NULL, `Unknown2` tinyint(3) unsigned DEFAULT NULL, `ParseVersion` int(10) unsigned DEFAULT NULL, `Rank` tinyint(3) unsigned DEFAULT NULL, `RoomNum` tinyint(3) unsigned NOT NULL DEFAULT 0, `TimeAdded` datetime DEFAULT NULL, `TimeUpdated` datetime DEFAULT NULL, PRIMARY KEY (`id`), KEY `RoomNum` (`RoomNum`,`Rank`,`TimeAdded`), KEY `pid` (`pid`,`RoomNum`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.GtsBattleTowerPokemon4 CREATE TABLE IF NOT EXISTS `GtsBattleTowerPokemon4` ( `party_id` bigint(20) unsigned NOT NULL, `Slot` tinyint(3) unsigned NOT NULL, `Species` smallint(5) unsigned DEFAULT NULL, `Form` smallint(5) unsigned DEFAULT NULL, `HeldItem` smallint(5) unsigned DEFAULT NULL, `Move1` smallint(5) unsigned DEFAULT NULL, `Move2` smallint(5) unsigned DEFAULT NULL, `Move3` smallint(5) unsigned DEFAULT NULL, `Move4` smallint(5) unsigned DEFAULT NULL, `TrainerID` int(10) unsigned DEFAULT NULL, `Personality` int(10) unsigned DEFAULT NULL, `IVs` int(10) unsigned DEFAULT NULL, `EVs` binary(6) DEFAULT NULL, `Unknown1` tinyint(3) unsigned DEFAULT NULL, `Language` tinyint(3) unsigned DEFAULT NULL, `Ability` tinyint(3) unsigned DEFAULT NULL, `Happiness` tinyint(3) unsigned DEFAULT NULL, `Nickname` binary(22) DEFAULT NULL, PRIMARY KEY (`party_id`,`Slot`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.GtsHistory4 CREATE TABLE IF NOT EXISTS `GtsHistory4` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `trade_id` bigint(20) unsigned DEFAULT NULL, `Data` blob NOT NULL, `Species` smallint(5) unsigned NOT NULL, `Gender` tinyint(3) unsigned NOT NULL, `Level` tinyint(3) unsigned NOT NULL, `RequestedSpecies` smallint(5) unsigned NOT NULL, `RequestedGender` tinyint(3) unsigned NOT NULL, `RequestedMinLevel` tinyint(3) unsigned NOT NULL, `RequestedMaxLevel` tinyint(3) unsigned NOT NULL, `Unknown1` tinyint(3) unsigned NOT NULL, `TrainerGender` tinyint(3) unsigned NOT NULL, `Unknown2` tinyint(3) unsigned NOT NULL, `TimeDeposited` datetime DEFAULT NULL, `TimeExchanged` datetime DEFAULT NULL, `pid` int(11) NOT NULL, `TrainerName` binary(16) NOT NULL DEFAULT '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0', `TrainerOT` smallint(5) unsigned NOT NULL, `TrainerCountry` tinyint(3) unsigned NOT NULL, `TrainerRegion` tinyint(3) unsigned NOT NULL, `TrainerClass` tinyint(3) unsigned NOT NULL, `IsExchanged` tinyint(3) unsigned NOT NULL, `TrainerVersion` tinyint(3) unsigned NOT NULL, `TrainerLanguage` tinyint(3) unsigned NOT NULL, `ParseVersion` int(11) unsigned DEFAULT NULL, `TimeWithdrawn` datetime DEFAULT NULL, `partner_pid` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `pid` (`pid`), KEY `Species` (`Species`), KEY `Gender` (`Gender`), KEY `Level` (`Level`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.GtsHistory5 CREATE TABLE IF NOT EXISTS `GtsHistory5` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `trade_id` bigint(20) unsigned DEFAULT NULL, `Data` blob NOT NULL, `Unknown0` blob NOT NULL, `Species` smallint(5) unsigned NOT NULL, `Gender` tinyint(3) unsigned NOT NULL, `Level` tinyint(3) unsigned NOT NULL, `RequestedSpecies` smallint(5) unsigned NOT NULL, `RequestedGender` tinyint(3) unsigned NOT NULL, `RequestedMinLevel` tinyint(3) unsigned NOT NULL, `RequestedMaxLevel` tinyint(3) unsigned NOT NULL, `Unknown1` tinyint(3) unsigned NOT NULL, `TrainerGender` tinyint(3) unsigned NOT NULL, `Unknown2` tinyint(3) unsigned NOT NULL, `TimeDeposited` datetime DEFAULT NULL, `TimeExchanged` datetime DEFAULT NULL, `pid` int(11) NOT NULL, `TrainerOT` int(11) unsigned NOT NULL, `TrainerName` binary(16) NOT NULL DEFAULT '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0', `TrainerCountry` tinyint(3) unsigned NOT NULL, `TrainerRegion` tinyint(3) unsigned NOT NULL, `TrainerClass` tinyint(3) unsigned NOT NULL, `IsExchanged` tinyint(3) unsigned NOT NULL, `TrainerVersion` tinyint(3) unsigned NOT NULL, `TrainerLanguage` tinyint(3) unsigned NOT NULL, `TrainerBadges` tinyint(3) unsigned NOT NULL, `TrainerUnityTower` tinyint(3) unsigned NOT NULL, `ParseVersion` int(10) unsigned DEFAULT NULL, `TimeWithdrawn` datetime DEFAULT NULL, `partner_pid` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `pid` (`pid`), KEY `Species` (`Species`), KEY `Gender` (`Gender`), KEY `Level` (`Level`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.GtsPokemon4 CREATE TABLE IF NOT EXISTS `GtsPokemon4` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `Data` blob NOT NULL, `Species` smallint(5) unsigned NOT NULL, `Gender` tinyint(3) unsigned NOT NULL, `Level` tinyint(3) unsigned NOT NULL, `RequestedSpecies` smallint(5) unsigned NOT NULL, `RequestedGender` tinyint(3) unsigned NOT NULL, `RequestedMinLevel` tinyint(3) unsigned NOT NULL, `RequestedMaxLevel` tinyint(3) unsigned NOT NULL, `Unknown1` tinyint(3) unsigned NOT NULL, `TrainerGender` tinyint(3) unsigned NOT NULL, `Unknown2` tinyint(3) unsigned NOT NULL, `TimeDeposited` datetime DEFAULT NULL, `TimeExchanged` datetime DEFAULT NULL, `pid` int(11) NOT NULL, `TrainerName` binary(16) NOT NULL DEFAULT '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0', `TrainerOT` smallint(5) unsigned NOT NULL, `TrainerCountry` tinyint(3) unsigned NOT NULL, `TrainerRegion` tinyint(3) unsigned NOT NULL, `TrainerClass` tinyint(3) unsigned NOT NULL, `IsExchanged` tinyint(3) unsigned NOT NULL, `TrainerVersion` tinyint(3) unsigned NOT NULL, `TrainerLanguage` tinyint(3) unsigned NOT NULL, `ParseVersion` int(10) unsigned DEFAULT NULL, `LockedBy` int(11) DEFAULT NULL, `LockedUntil` datetime DEFAULT NULL, PRIMARY KEY (`id`), KEY `pid` (`pid`), KEY `Species` (`Species`), KEY `Gender` (`Gender`), KEY `Level` (`Level`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.GtsPokemon5 CREATE TABLE IF NOT EXISTS `GtsPokemon5` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `Data` blob NOT NULL, `Unknown0` blob NOT NULL, `Species` smallint(5) unsigned NOT NULL, `Gender` tinyint(3) unsigned NOT NULL, `Level` tinyint(3) unsigned NOT NULL, `RequestedSpecies` smallint(5) unsigned NOT NULL, `RequestedGender` tinyint(3) unsigned NOT NULL, `RequestedMinLevel` tinyint(3) unsigned NOT NULL, `RequestedMaxLevel` tinyint(3) unsigned NOT NULL, `Unknown1` tinyint(3) unsigned NOT NULL, `TrainerGender` tinyint(3) unsigned NOT NULL, `Unknown2` tinyint(3) unsigned NOT NULL, `TimeDeposited` datetime DEFAULT NULL, `TimeExchanged` datetime DEFAULT NULL, `pid` int(11) NOT NULL, `TrainerOT` int(11) unsigned NOT NULL, `TrainerName` binary(16) NOT NULL DEFAULT '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0', `TrainerCountry` tinyint(3) unsigned NOT NULL, `TrainerRegion` tinyint(3) unsigned NOT NULL, `TrainerClass` tinyint(3) unsigned NOT NULL, `IsExchanged` tinyint(3) unsigned NOT NULL, `TrainerVersion` tinyint(3) unsigned NOT NULL, `TrainerLanguage` tinyint(3) unsigned NOT NULL, `TrainerBadges` tinyint(3) unsigned NOT NULL, `TrainerUnityTower` tinyint(3) unsigned NOT NULL, `ParseVersion` int(10) unsigned DEFAULT NULL, `LockedBy` int(11) DEFAULT NULL, `LockedUntil` datetime DEFAULT NULL, PRIMARY KEY (`id`), KEY `pid` (`pid`), KEY `Species` (`Species`), KEY `Gender` (`Gender`), KEY `Level` (`Level`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.GtsProfiles4 CREATE TABLE IF NOT EXISTS `GtsProfiles4` ( `pid` int(11) NOT NULL, `Data` blob DEFAULT NULL, `Version` tinyint(3) unsigned DEFAULT NULL, `Language` tinyint(3) unsigned DEFAULT NULL, `Country` tinyint(3) unsigned DEFAULT NULL, `Region` tinyint(3) unsigned DEFAULT NULL, `OT` int(10) unsigned DEFAULT NULL, `Name` binary(16) DEFAULT NULL, `MacAddress` binary(6) DEFAULT NULL, `Email` varchar(64) DEFAULT NULL, `HasNotifications` bit(1) DEFAULT NULL, `ClientSecret` smallint(6) DEFAULT NULL, `MailSecret` smallint(6) DEFAULT NULL, `ParseVersion` int(10) unsigned DEFAULT NULL, `TimeAdded` datetime NOT NULL, `TimeUpdated` datetime NOT NULL, `TimeLastSearch` datetime DEFAULT NULL, `IpAddress` varchar(64) DEFAULT NULL, PRIMARY KEY (`pid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.GtsProfiles5 CREATE TABLE IF NOT EXISTS `GtsProfiles5` ( `pid` int(11) NOT NULL, `Data` blob DEFAULT NULL, `Version` tinyint(3) unsigned DEFAULT NULL, `Language` tinyint(3) unsigned DEFAULT NULL, `Country` tinyint(3) unsigned DEFAULT NULL, `Region` tinyint(3) unsigned DEFAULT NULL, `OT` int(10) unsigned DEFAULT NULL, `Name` binary(16) DEFAULT NULL, `MacAddress` binary(6) DEFAULT NULL, `Email` varchar(64) DEFAULT NULL, `HasNotifications` bit(1) DEFAULT NULL, `ClientSecret` smallint(6) DEFAULT NULL, `MailSecret` smallint(6) DEFAULT NULL, `ParseVersion` int(10) unsigned DEFAULT NULL, `TimeAdded` datetime NOT NULL, `TimeUpdated` datetime NOT NULL, `TimeLastSearch` datetime DEFAULT NULL, `IpAddress` varchar(64) DEFAULT NULL, PRIMARY KEY (`pid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_gamestats_bans_ip CREATE TABLE IF NOT EXISTS `pkmncf_gamestats_bans_ip` ( `IpAddress` varchar(64) NOT NULL, `Level` int(11) NOT NULL, `Reason` text DEFAULT NULL, `Expires` datetime DEFAULT NULL, PRIMARY KEY (`IpAddress`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_gamestats_bans_ipv4_range CREATE TABLE IF NOT EXISTS `pkmncf_gamestats_bans_ipv4_range` ( `IpAddressMin` int(10) unsigned NOT NULL, `IpAddressMax` int(10) unsigned NOT NULL, `Level` int(11) NOT NULL, `Reason` text DEFAULT NULL, `Expires` datetime DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_gamestats_bans_mac CREATE TABLE IF NOT EXISTS `pkmncf_gamestats_bans_mac` ( `MacAddress` binary(6) NOT NULL, `Level` int(11) NOT NULL, `Reason` text DEFAULT NULL, `Expires` datetime DEFAULT NULL, PRIMARY KEY (`MacAddress`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_gamestats_bans_pid CREATE TABLE IF NOT EXISTS `pkmncf_gamestats_bans_pid` ( `pid` int(11) NOT NULL, `Level` int(11) NOT NULL, `Reason` text DEFAULT NULL, `Expires` datetime DEFAULT NULL, PRIMARY KEY (`pid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_gamestats_bans_savefile CREATE TABLE IF NOT EXISTS `pkmncf_gamestats_bans_savefile` ( `Version` tinyint(3) unsigned NOT NULL, `Language` tinyint(3) unsigned NOT NULL, `OT` int(10) unsigned NOT NULL, `Name` binary(16) NOT NULL, `Level` int(11) NOT NULL, `Reason` text DEFAULT NULL, `Expires` datetime DEFAULT NULL, PRIMARY KEY (`Version`,`Language`,`OT`,`Name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_plaza_profiles CREATE TABLE IF NOT EXISTS `pkmncf_plaza_profiles` ( `pid` int(11) NOT NULL, `Data` blob DEFAULT NULL, `Version` tinyint(3) unsigned DEFAULT NULL, `Language` tinyint(3) unsigned DEFAULT NULL, `Country` tinyint(3) unsigned DEFAULT NULL, `Region` tinyint(3) unsigned DEFAULT NULL, `OT` int(10) unsigned DEFAULT NULL, `Name` binary(16) DEFAULT NULL, `ParseVersion` int(10) unsigned DEFAULT NULL, `TimeAdded` datetime NOT NULL, `TimeUpdated` datetime NOT NULL, PRIMARY KEY (`pid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_pokedex_abilities CREATE TABLE IF NOT EXISTS `pkmncf_pokedex_abilities` ( `Value` int(10) unsigned NOT NULL AUTO_INCREMENT, `Name_JA` varchar(30) DEFAULT '', `Name_EN` varchar(30) DEFAULT NULL, `Name_FR` varchar(30) DEFAULT NULL, `Name_IT` varchar(30) DEFAULT NULL, `Name_DE` varchar(30) DEFAULT NULL, `Name_ES` varchar(30) DEFAULT NULL, `Name_KO` varchar(30) DEFAULT NULL, PRIMARY KEY (`Value`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_pokedex_countries CREATE TABLE IF NOT EXISTS `pkmncf_pokedex_countries` ( `id` int(10) unsigned NOT NULL DEFAULT 0, `Value4` tinyint(3) unsigned DEFAULT 0, `Value5` tinyint(3) unsigned DEFAULT NULL, `iso-3166-1` char(2) DEFAULT NULL, `Name_JA` varchar(30) DEFAULT '', `Name_EN` varchar(30) DEFAULT NULL, `Name_FR` varchar(30) DEFAULT NULL, `Name_IT` varchar(30) DEFAULT NULL, `Name_DE` varchar(30) DEFAULT NULL, `Name_ES` varchar(30) DEFAULT NULL, `Name_KO` varchar(30) DEFAULT NULL, PRIMARY KEY (`id`), KEY `Name` (`Name_JA`), KEY `Value4` (`Value4`), KEY `Value5` (`Value5`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_pokedex_country_regions CREATE TABLE IF NOT EXISTS `pkmncf_pokedex_country_regions` ( `id` int(10) unsigned NOT NULL DEFAULT 0, `country_id` int(10) unsigned NOT NULL DEFAULT 0, `Value4` tinyint(3) unsigned NOT NULL DEFAULT 0, `Value5` tinyint(3) unsigned DEFAULT NULL, `iso-3166-2` varchar(4) DEFAULT NULL, `Name_JA` varchar(30) DEFAULT '', `Name_EN` varchar(30) DEFAULT NULL, `Name_FR` varchar(30) DEFAULT NULL, `Name_IT` varchar(30) DEFAULT NULL, `Name_DE` varchar(30) DEFAULT NULL, `Name_ES` varchar(30) DEFAULT NULL, `Name_KO` varchar(30) DEFAULT NULL, PRIMARY KEY (`id`), KEY `country_id` (`country_id`), KEY `country_id_2` (`country_id`,`Value4`), KEY `country_id_3` (`country_id`,`Value5`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_pokedex_encounters_random CREATE TABLE IF NOT EXISTS `pkmncf_pokedex_encounters_random` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `room_id` int(10) unsigned NOT NULL, `Version` int(10) unsigned NOT NULL, `Method` int(10) unsigned NOT NULL, `EncounterSlot` tinyint(3) unsigned NOT NULL, `form_id` int(10) unsigned NOT NULL, `MinLevel` tinyint(3) unsigned NOT NULL, `MaxLevel` tinyint(3) unsigned NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_pokedex_items CREATE TABLE IF NOT EXISTS `pkmncf_pokedex_items` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `Value3` int(10) unsigned DEFAULT NULL, `Value4` int(10) unsigned DEFAULT NULL, `Value5` int(10) unsigned DEFAULT NULL, `Value6` int(10) unsigned DEFAULT NULL, `PokeballValue` int(10) unsigned DEFAULT NULL, `Name_JA` varchar(30) DEFAULT '', `Name_EN` varchar(30) DEFAULT NULL, `Name_FR` varchar(30) DEFAULT NULL, `Name_IT` varchar(30) DEFAULT NULL, `Name_DE` varchar(30) DEFAULT NULL, `Name_ES` varchar(30) DEFAULT NULL, `Name_KO` varchar(30) DEFAULT NULL, `Price` int(10) unsigned DEFAULT NULL, `HoldGeneration` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `Value3` (`Value3`), KEY `Value4` (`Value4`), KEY `Value5` (`Value5`), KEY `Value6` (`Value6`), KEY `ValueBall` (`PokeballValue`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_pokedex_locations CREATE TABLE IF NOT EXISTS `pkmncf_pokedex_locations` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `region_id` int(11) unsigned NOT NULL, `Name_JA` varchar(30) DEFAULT NULL, `Name_EN` varchar(30) DEFAULT NULL, `Name_FR` varchar(30) DEFAULT NULL, `Name_IT` varchar(30) DEFAULT NULL, `Name_DE` varchar(30) DEFAULT NULL, `Name_ES` varchar(30) DEFAULT NULL, `Name_KO` varchar(30) DEFAULT NULL, `Value3` int(11) unsigned DEFAULT NULL, `Value_Colo` int(11) unsigned DEFAULT NULL, `Value_XD` int(11) unsigned DEFAULT NULL, `Value4` int(11) unsigned DEFAULT NULL, `Value5` int(11) unsigned DEFAULT NULL, `Value6` int(11) unsigned DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_pokedex_moves CREATE TABLE IF NOT EXISTS `pkmncf_pokedex_moves` ( `Value` int(10) unsigned NOT NULL AUTO_INCREMENT, `type_id` int(10) unsigned DEFAULT NULL, `DamageClass` tinyint(3) unsigned NOT NULL, `Name_JA` varchar(30) DEFAULT '', `Name_EN` varchar(30) DEFAULT NULL, `Name_FR` varchar(30) DEFAULT NULL, `Name_IT` varchar(30) DEFAULT NULL, `Name_DE` varchar(30) DEFAULT NULL, `Name_ES` varchar(30) DEFAULT NULL, `Name_KO` varchar(30) DEFAULT NULL, `Damage` int(11) DEFAULT NULL, `PP` int(11) DEFAULT NULL, `Accuracy` int(11) DEFAULT NULL, `Priority` int(11) DEFAULT NULL, `Target` int(11) DEFAULT NULL, PRIMARY KEY (`Value`), KEY `Type` (`type_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_pokedex_pokemon CREATE TABLE IF NOT EXISTS `pkmncf_pokedex_pokemon` ( `NationalDex` int(10) unsigned NOT NULL, `family_id` int(10) unsigned NOT NULL, `Name_JA` varchar(36) DEFAULT '', `Name_EN` varchar(36) DEFAULT NULL, `Name_FR` varchar(36) DEFAULT NULL, `Name_IT` varchar(36) DEFAULT NULL, `Name_DE` varchar(36) DEFAULT NULL, `Name_ES` varchar(36) DEFAULT NULL, `Name_KO` varchar(36) DEFAULT NULL, `GrowthRate` int(10) unsigned NOT NULL, `GenderRatio` tinyint(3) unsigned NOT NULL, `EggGroup1` tinyint(3) unsigned NOT NULL, `EggGroup2` tinyint(3) unsigned NOT NULL, `EggSteps` int(10) unsigned NOT NULL, `GenderVariations` bit(1) DEFAULT NULL, PRIMARY KEY (`NationalDex`), KEY `family_id` (`family_id`), KEY `EggGroup1` (`EggGroup1`), KEY `EggGroup2` (`EggGroup2`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_pokedex_pokemon_families CREATE TABLE IF NOT EXISTS `pkmncf_pokedex_pokemon_families` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `BasicMale` int(10) unsigned NOT NULL, `BasicFemale` int(10) unsigned NOT NULL, `BabyMale` int(10) unsigned DEFAULT NULL, `BabyFemale` int(10) unsigned DEFAULT NULL, `Incense` int(10) unsigned DEFAULT NULL, `GenderRatio` tinyint(3) unsigned NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_pokedex_pokemon_forms CREATE TABLE IF NOT EXISTS `pkmncf_pokedex_pokemon_forms` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `NationalDex` int(11) unsigned NOT NULL, `FormValue` tinyint(3) unsigned NOT NULL, `Name_JA` varchar(30) DEFAULT NULL, `Name_EN` varchar(30) DEFAULT NULL, `Name_FR` varchar(30) DEFAULT NULL, `Name_IT` varchar(30) DEFAULT NULL, `Name_DE` varchar(30) DEFAULT NULL, `Name_ES` varchar(30) DEFAULT NULL, `Name_KO` varchar(30) DEFAULT NULL, `FormSuffix` varchar(30) DEFAULT NULL, `Height` int(10) unsigned DEFAULT NULL, `Weight` int(10) unsigned DEFAULT NULL, `Experience` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`id`), KEY `NationalDex` (`NationalDex`), KEY `FormValue` (`FormValue`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_pokedex_pokemon_form_abilities CREATE TABLE IF NOT EXISTS `pkmncf_pokedex_pokemon_form_abilities` ( `form_id` int(10) unsigned NOT NULL, `MinGeneration` int(10) unsigned NOT NULL, `Ability1` int(10) unsigned DEFAULT NULL, `Ability2` int(10) unsigned DEFAULT NULL, `HiddenAbility1` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`form_id`,`MinGeneration`), KEY `Ability1` (`Ability1`), KEY `Ability2` (`Ability2`), KEY `HiddenAbility1` (`HiddenAbility1`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_pokedex_pokemon_form_stats CREATE TABLE IF NOT EXISTS `pkmncf_pokedex_pokemon_form_stats` ( `form_id` int(10) unsigned NOT NULL, `MinGeneration` int(10) unsigned NOT NULL, `Type1` int(10) unsigned DEFAULT NULL, `Type2` int(10) unsigned DEFAULT NULL, `BaseHP` int(11) DEFAULT NULL, `BaseAttack` int(11) DEFAULT NULL, `BaseDefense` int(11) DEFAULT NULL, `BaseSpeed` int(11) DEFAULT NULL, `BaseSpAttack` int(11) DEFAULT NULL, `BaseSpDefense` int(11) DEFAULT NULL, `RewardHP` tinyint(3) unsigned DEFAULT NULL, `RewardAttack` tinyint(3) unsigned DEFAULT NULL, `RewardDefense` tinyint(3) unsigned DEFAULT NULL, `RewardSpeed` tinyint(3) unsigned DEFAULT NULL, `RewardSpAttack` tinyint(3) unsigned DEFAULT NULL, `RewardSpDefense` tinyint(3) unsigned DEFAULT NULL, PRIMARY KEY (`form_id`,`MinGeneration`), KEY `form_id` (`form_id`,`MinGeneration`), KEY `Type1` (`Type1`), KEY `Type2` (`Type2`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_pokedex_regions CREATE TABLE IF NOT EXISTS `pkmncf_pokedex_regions` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `Name_JA` varchar(30) DEFAULT NULL, `Name_EN` varchar(30) DEFAULT NULL, `Name_FR` varchar(30) DEFAULT NULL, `Name_IT` varchar(30) DEFAULT NULL, `Name_DE` varchar(30) DEFAULT NULL, `Name_ES` varchar(30) DEFAULT NULL, `Name_KO` varchar(30) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_pokedex_ribbons CREATE TABLE IF NOT EXISTS `pkmncf_pokedex_ribbons` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `Position3` int(10) unsigned DEFAULT NULL, `Position4` int(10) unsigned DEFAULT NULL, `Position5` int(10) unsigned DEFAULT NULL, `Position6` int(10) unsigned DEFAULT NULL, `Value3` int(10) unsigned DEFAULT NULL, `Value4` int(10) unsigned DEFAULT NULL, `Value5` int(10) unsigned DEFAULT NULL, `Value6` int(10) unsigned DEFAULT NULL, `Name_JA` varchar(30) DEFAULT NULL, `Name_EN` varchar(30) DEFAULT NULL, `Name_FR` varchar(30) DEFAULT NULL, `Name_IT` varchar(30) DEFAULT NULL, `Name_DE` varchar(30) DEFAULT NULL, `Name_ES` varchar(30) DEFAULT NULL, `Name_KO` varchar(30) DEFAULT NULL, `Description_JA` varchar(300) DEFAULT NULL, `Description_EN` varchar(300) DEFAULT NULL, `Description_FR` varchar(300) DEFAULT NULL, `Description_IT` varchar(300) DEFAULT NULL, `Description_DE` varchar(300) DEFAULT NULL, `Description_ES` varchar(300) DEFAULT NULL, `Description_KO` varchar(300) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_pokedex_rooms CREATE TABLE IF NOT EXISTS `pkmncf_pokedex_rooms` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `location_id` int(11) unsigned NOT NULL, `Comment` varchar(300) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_pokedex_types CREATE TABLE IF NOT EXISTS `pkmncf_pokedex_types` ( `id` int(10) unsigned NOT NULL, `Name_JA` varchar(30) DEFAULT '', `Name_EN` varchar(30) DEFAULT NULL, `Name_FR` varchar(30) DEFAULT NULL, `Name_IT` varchar(30) DEFAULT NULL, `Name_DE` varchar(30) DEFAULT NULL, `Name_ES` varchar(30) DEFAULT NULL, `Name_KO` varchar(30) DEFAULT NULL, `DamageClass` tinyint(3) unsigned DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for procedure gts.pkmncf_terminal_proc_create_leaderboards_for_record DELIMITER // CREATE PROCEDURE `pkmncf_terminal_proc_create_leaderboards_for_record`( IN `_report_id` INT, IN `_record_type` INT ) SQL SECURITY INVOKER BEGIN SELECT @start_date := StartDate FROM pkmncf_terminal_trainer_rankings_reports WHERE report_id = _report_id; INSERT INTO pkmncf_terminal_trainer_rankings_leaderboards_class SELECT _report_id AS report_id, TrainerClass, _record_type AS RecordType, SUM(Score) AS Score FROM pkmncf_terminal_trainer_rankings_records INNER JOIN pkmncf_terminal_trainer_rankings_teams ON pkmncf_terminal_trainer_rankings_records.pid = pkmncf_terminal_trainer_rankings_teams.pid WHERE pkmncf_terminal_trainer_rankings_records.LastUpdated >= @start_date AND RecordType = _record_type GROUP BY TrainerClass; INSERT INTO pkmncf_terminal_trainer_rankings_leaderboards_month SELECT _report_id AS report_id, BirthMonth, _record_type AS RecordType, SUM(Score) AS Score FROM pkmncf_terminal_trainer_rankings_records INNER JOIN pkmncf_terminal_trainer_rankings_teams ON pkmncf_terminal_trainer_rankings_records.pid = pkmncf_terminal_trainer_rankings_teams.pid WHERE pkmncf_terminal_trainer_rankings_records.LastUpdated >= @start_date AND RecordType = _record_type GROUP BY BirthMonth; INSERT INTO pkmncf_terminal_trainer_rankings_leaderboards_pokemon SELECT _report_id AS report_id, FavouritePokemon, _record_type AS RecordType, SUM(Score) AS Score FROM pkmncf_terminal_trainer_rankings_records INNER JOIN pkmncf_terminal_trainer_rankings_teams ON pkmncf_terminal_trainer_rankings_records.pid = pkmncf_terminal_trainer_rankings_teams.pid WHERE pkmncf_terminal_trainer_rankings_records.LastUpdated >= @start_date AND RecordType = _record_type GROUP BY FavouritePokemon; END// DELIMITER ; -- Dumping structure for procedure gts.pkmncf_terminal_proc_create_leaderboards_for_report DELIMITER // CREATE PROCEDURE `pkmncf_terminal_proc_create_leaderboards_for_report`( IN `_report_id` INT ) SQL SECURITY INVOKER BEGIN SELECT @record_type_1 := RecordType1, @record_type_2 := RecordType2, @record_type_3 := RecordType3 FROM pkmncf_terminal_trainer_rankings_reports WHERE report_id = _report_id; DELETE FROM pkmncf_terminal_trainer_rankings_leaderboards_class WHERE report_id = _report_id; DELETE FROM pkmncf_terminal_trainer_rankings_leaderboards_month WHERE report_id = _report_id; DELETE FROM pkmncf_terminal_trainer_rankings_leaderboards_pokemon WHERE report_id = _report_id; CALL pkmncf_terminal_proc_create_leaderboards_for_record(_report_id, @record_type_1); CALL pkmncf_terminal_proc_create_leaderboards_for_record(_report_id, @record_type_2); CALL pkmncf_terminal_proc_create_leaderboards_for_record(_report_id, @record_type_3); END// DELIMITER ; -- Dumping structure for table gts.pkmncf_terminal_trainer_rankings_leaderboards_class CREATE TABLE IF NOT EXISTS `pkmncf_terminal_trainer_rankings_leaderboards_class` ( `report_id` int(11) NOT NULL, `TrainerClass` int(11) NOT NULL, `RecordType` int(11) NOT NULL, `Score` bigint(20) NOT NULL DEFAULT 0, PRIMARY KEY (`report_id`,`TrainerClass`,`RecordType`) USING BTREE, KEY `leaderboard_id` (`report_id`) USING BTREE, CONSTRAINT `FK_pkmncf_terminal_trainer_rankings_byclass4_reports` FOREIGN KEY (`report_id`) REFERENCES `pkmncf_terminal_trainer_rankings_reports` (`report_id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_terminal_trainer_rankings_leaderboards_month CREATE TABLE IF NOT EXISTS `pkmncf_terminal_trainer_rankings_leaderboards_month` ( `report_id` int(11) NOT NULL, `Month` int(11) NOT NULL, `RecordType` int(11) NOT NULL, `Score` bigint(20) NOT NULL DEFAULT 0, PRIMARY KEY (`report_id`,`Month`,`RecordType`) USING BTREE, KEY `leaderboard_id` (`report_id`) USING BTREE, CONSTRAINT `FK_pkmncf_terminal_trainer_rankings_bymonth4_reports` FOREIGN KEY (`report_id`) REFERENCES `pkmncf_terminal_trainer_rankings_reports` (`report_id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_terminal_trainer_rankings_leaderboards_pokemon CREATE TABLE IF NOT EXISTS `pkmncf_terminal_trainer_rankings_leaderboards_pokemon` ( `report_id` int(11) NOT NULL, `pokemon_id` int(11) NOT NULL, `RecordType` int(11) NOT NULL, `Score` bigint(20) NOT NULL, PRIMARY KEY (`report_id`,`pokemon_id`,`RecordType`) USING BTREE, KEY `leaderboard_id` (`report_id`) USING BTREE, CONSTRAINT `FK_pkmncf_terminal_trainer_rankings_bypokemon4_reports` FOREIGN KEY (`report_id`) REFERENCES `pkmncf_terminal_trainer_rankings_reports` (`report_id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_terminal_trainer_rankings_records CREATE TABLE IF NOT EXISTS `pkmncf_terminal_trainer_rankings_records` ( `pid` int(11) NOT NULL, `RecordType` int(11) NOT NULL, `Score` bigint(20) NOT NULL DEFAULT 0, `LastUpdated` datetime NOT NULL, PRIMARY KEY (`pid`,`RecordType`), KEY `LastUpdated` (`LastUpdated`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_terminal_trainer_rankings_reports CREATE TABLE IF NOT EXISTS `pkmncf_terminal_trainer_rankings_reports` ( `report_id` int(11) NOT NULL AUTO_INCREMENT, `StartDate` datetime NOT NULL, `EndDate` datetime NOT NULL, `RecordType1` int(11) NOT NULL, `RecordType2` int(11) NOT NULL, `RecordType3` int(11) NOT NULL, PRIMARY KEY (`report_id`) USING BTREE, KEY `StartDate` (`StartDate`), KEY `EndDate` (`EndDate`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_terminal_trainer_rankings_teams CREATE TABLE IF NOT EXISTS `pkmncf_terminal_trainer_rankings_teams` ( `pid` int(11) NOT NULL, `TrainerClass` int(11) NOT NULL, `BirthMonth` int(11) NOT NULL, `FavouritePokemon` int(11) NOT NULL, `Unknown1` smallint(5) unsigned NOT NULL DEFAULT 0, `Unknown2` smallint(5) unsigned NOT NULL DEFAULT 0, `Unknown3` smallint(5) unsigned NOT NULL DEFAULT 0, `LastUpdated` datetime NOT NULL, PRIMARY KEY (`pid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.pkmncf_web_news CREATE TABLE IF NOT EXISTS `pkmncf_web_news` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.TerminalBattleVideoPokemon4 CREATE TABLE IF NOT EXISTS `TerminalBattleVideoPokemon4` ( `video_id` bigint(20) unsigned NOT NULL, `Slot` tinyint(3) unsigned NOT NULL, `Species` smallint(5) unsigned NOT NULL, PRIMARY KEY (`video_id`,`Slot`), KEY `Species` (`Species`), CONSTRAINT `terminalbattlevideopokemon4_ibfk_1` FOREIGN KEY (`video_id`) REFERENCES `TerminalBattleVideos4` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.TerminalBattleVideoPokemon5 CREATE TABLE IF NOT EXISTS `TerminalBattleVideoPokemon5` ( `video_id` bigint(20) unsigned NOT NULL, `Slot` tinyint(3) unsigned NOT NULL, `Species` smallint(5) unsigned NOT NULL, PRIMARY KEY (`video_id`,`Slot`), KEY `Species` (`Species`), CONSTRAINT `terminalbattlevideopokemon5_ibfk_1` FOREIGN KEY (`video_id`) REFERENCES `TerminalBattleVideos5` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.TerminalBattleVideos4 CREATE TABLE IF NOT EXISTS `TerminalBattleVideos4` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `pid` int(11) NOT NULL, `SerialNumber` bigint(20) unsigned DEFAULT NULL, `Header` blob NOT NULL, `Data` blob NOT NULL, `md5` binary(16) NOT NULL DEFAULT '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0', `TimeAdded` datetime NOT NULL, `ParseVersion` int(10) unsigned NOT NULL, `TrainerName` binary(16) NOT NULL DEFAULT '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0', `Streak` smallint(5) unsigned DEFAULT NULL, `Metagame` tinyint(3) unsigned NOT NULL, `Country` tinyint(3) unsigned NOT NULL, `Region` tinyint(3) unsigned NOT NULL, `Views` int(10) unsigned NOT NULL DEFAULT 0, `Saves` int(10) unsigned NOT NULL DEFAULT 0, `Hype` double DEFAULT 0, `HypeTimestamp` datetime DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `SerialNumber` (`SerialNumber`), KEY `TimeAdded` (`TimeAdded`), KEY `Metagame` (`Metagame`), KEY `pid` (`pid`), KEY `Country` (`Country`,`Region`), KEY `md5` (`md5`), KEY `Hype` (`Hype`), KEY `HypeTimestamp` (`HypeTimestamp`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.TerminalBattleVideos5 CREATE TABLE IF NOT EXISTS `TerminalBattleVideos5` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `pid` int(11) NOT NULL, `SerialNumber` bigint(20) unsigned DEFAULT NULL, `Header` blob NOT NULL, `Data` blob NOT NULL, `md5` binary(16) NOT NULL DEFAULT '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0', `TimeAdded` datetime NOT NULL, `ParseVersion` int(10) unsigned NOT NULL, `TrainerName` binary(16) NOT NULL DEFAULT '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0', `Streak` smallint(5) unsigned DEFAULT NULL, `Metagame` tinyint(3) unsigned NOT NULL, `Country` tinyint(3) unsigned NOT NULL, `Region` tinyint(3) unsigned NOT NULL, `Views` int(10) unsigned NOT NULL DEFAULT 0, `Saves` int(10) unsigned NOT NULL DEFAULT 0, `Hype` double DEFAULT 0, `HypeTimestamp` datetime DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `SerialNumber` (`SerialNumber`), KEY `TimeAdded` (`TimeAdded`), KEY `Metagame` (`Metagame`), KEY `pid` (`pid`), KEY `Country` (`Country`,`Region`), KEY `md5` (`md5`), KEY `Hype` (`Hype`), KEY `HypeTimestamp` (`HypeTimestamp`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.TerminalBoxes4 CREATE TABLE IF NOT EXISTS `TerminalBoxes4` ( `pid` int(11) NOT NULL, `SerialNumber` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `Data` blob NOT NULL, `md5` binary(16) NOT NULL DEFAULT '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0', `TimeAdded` datetime NOT NULL, `ParseVersion` int(11) unsigned NOT NULL, `Label` int(11) unsigned NOT NULL, PRIMARY KEY (`SerialNumber`), KEY `md5` (`md5`), KEY `Label` (`Label`), KEY `TimeAdded` (`TimeAdded`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.TerminalDressup4 CREATE TABLE IF NOT EXISTS `TerminalDressup4` ( `pid` int(11) NOT NULL, `SerialNumber` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `Data` blob NOT NULL, `md5` binary(16) NOT NULL DEFAULT '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0', `TimeAdded` datetime NOT NULL, `ParseVersion` int(11) unsigned NOT NULL, `Species` smallint(5) unsigned NOT NULL, PRIMARY KEY (`SerialNumber`), KEY `md5` (`md5`), KEY `Species` (`Species`), KEY `TimeAdded` (`TimeAdded`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.TerminalMusicalPokemon5 CREATE TABLE IF NOT EXISTS `TerminalMusicalPokemon5` ( `musical_id` bigint(20) unsigned NOT NULL, `Slot` tinyint(3) unsigned NOT NULL, `Species` smallint(6) unsigned NOT NULL, PRIMARY KEY (`musical_id`,`Slot`), KEY `Species` (`Species`), CONSTRAINT `terminalmusicalpokemon5_ibfk_1` FOREIGN KEY (`musical_id`) REFERENCES `TerminalMusicals5` (`SerialNumber`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. -- Dumping structure for table gts.TerminalMusicals5 CREATE TABLE IF NOT EXISTS `TerminalMusicals5` ( `pid` int(11) NOT NULL, `SerialNumber` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `Data` blob NOT NULL, `md5` binary(16) NOT NULL DEFAULT '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0', `TimeAdded` datetime NOT NULL, `ParseVersion` int(11) unsigned NOT NULL, PRIMARY KEY (`SerialNumber`), KEY `md5` (`md5`), KEY `TimeAdded` (`TimeAdded`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Data exporting was unselected. /*!40103 SET TIME_ZONE=IFNULL(@OLD_TIME_ZONE, 'system') */; /*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */; /*!40014 SET FOREIGN_KEY_CHECKS=IFNULL(@OLD_FOREIGN_KEY_CHECKS, 1) */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40111 SET SQL_NOTES=IFNULL(@OLD_SQL_NOTES, 1) */; ================================================ FILE: library/lib/SQLite.Designer.xml ================================================ SQLite.Designer Required designer variable. Clean up any resources being used. true if managed resources should be disposed; otherwise, false. Required method for Designer support - do not modify the contents of this method with the code editor. Required designer variable. Clean up any resources being used. true if managed resources should be disposed; otherwise, false. Required method for Designer support - do not modify the contents of this method with the code editor. Required designer variable. Clean up any resources being used. true if managed resources should be disposed; otherwise, false. Required method for Designer support - do not modify the contents of this method with the code editor. Required designer variable. Clean up any resources being used. true if managed resources should be disposed; otherwise, false. Required method for Designer support - do not modify the contents of this method with the code editor. The purpose of this class is to provide context menus and event support when designing a SQLite DataSet. Most of the functionality is implemented by MS's VSDesigner object which we instantiate through reflection since I don't really have a design-time reference to the object and many of the objects in VSDesigner are internal. Empty constructor Initialize the designer by creating a SqlDataAdapterDesigner and delegating most of our functionality to it. We extend support for DbDataAdapter-derived objects The object wanting to be extended Whether or not we extend that object Forwards to the SqlDataAdapterDesigner object Forwards to the SqlDataAdapterDesigner object This object provides a designer for a SQLiteCommand. The reason we provide an additional CommandDesignTimeVisible property is because certain MS designer components will look for it and fail if its not there. Initialize the instance with the given SQLiteCommand component Add our designtimevisible attribute to the attributes for the item Provide a get method for the CommandDesignTimeVisible provided property The SQLiteCommand we're designing for True or false if the object is visible in design mode Provide a set method for our supplied CommandDesignTimeVisible property The SQLiteCommand to set The new designtime visible property to assign to the command We extend any DbCommand The object being tested True if the object derives from DbCommand This method executes a specified command, potentially based on parameters passed in from the data view support XML. Provides rudimentary connectionproperties support This class provides connectionstring editing support in the properties window when using a SQLiteConnection as a toolbox component on a form (for example). In order to provide the dropdown list, unless someone knows a better way, I have to use the internal VsConnectionManager class since it utilizes some interfaces in the designer that are internal to the VSDesigner object. We instantiate it and utilize it through reflection. Provides a UI to edit/create SQLite database connections Required designer variable. Clean up any resources being used. true if managed resources should be disposed; otherwise, false. Required method for Designer support - do not modify the contents of this method with the code editor. Provides a toolboxitem for a SQLiteDataAdapter. This is required in order for us to pop up the connection wizard when you drop the tool on a form, and to create the hidden commands that are assigned to the data adapter and keep them hidden. The hiding at runtime of the controls is accomplished both here during the creation of the components and in the SQLiteCommandDesigner which provides properties to hide the objects when they're supposed to be hidden. The connection wizard is instantiated in the VSDesigner through reflection. Creates the necessary components associated with this data adapter instance The designer host The components created by this toolbox item Generates a unique name for the given object The container where we're being instantiated The core name of the object to create a unique instance of A unique name within the given container This class creates many of the DDEX components when asked for by the server explorer. This class is used to build identifier arrays and contract them. Typically they are passed to SQLiteConnection.GetSchema() or are contracted for display on the screen or in the properties window. Strips out the schema, which we don't really support but has to be there for certain operations internal to MS's designer implementation. The type of identifier to contract The full identifier array A contracted identifier array GetSite does not need to be implemented since DDEX only calls SetSite to site the object. Doesn't do much other than provide the DataObjectSupport base object with a location where the XML resource can be found. Provides basic DataSourceInformation about the underlying connection Provides DataViewSupport with a location where the XML file is for the Server Explorer's view. Ideally we'd be a package provider, but the VS Express Editions don't support us, so this class exists so that in the future we can perhaps work with the Express Editions. For a package-based provider, this factory creates instances of the main objects we support Required designer variable. Clean up any resources being used. true if managed resources should be disposed; otherwise, false. Required method for Designer support - do not modify the contents of this method with the code editor. A strongly-typed resource class, for looking up localized strings, etc. Returns the cached ResourceManager instance used by this class. Overrides the current thread's CurrentUICulture property for all resource lookups using this strongly typed resource class. Looks up a localized string similar to RZE1PAAIMRZRE2CKM3CIRRIREIJQR1PTAEHTRHKTCPP1KKRRJQK9CTM9ZHMRETI9E9J8REKEA1MER9PDKQDIH8HMRRH2DIACHIP1KHK2IAZKM8R0EZRTKDHADII9ICCH. Looks up a localized string similar to The database and its metadata will be un-encrypted. No password will be required to open the database and view its contents.. Looks up a localized string similar to The database and its metadata will be encrypted using the supplied password as a hash.. Looks up a localized string similar to The database and its metadata will be re-encrypted using the supplied password as a hash.. Looks up a localized string similar to [SQLite] System.Data.SQLite.SQLiteConnection, System.Data.SQLite System.Data.SQLite.SQLiteDataAdapter, System.Data.SQLite System.Data.SQLite.SQLiteCommand, System.Data.SQLite . ================================================ FILE: library/lib/System.Data.SQLite.Linq.xml ================================================ System.Data.SQLite.Linq A strongly-typed resource class, for looking up localized strings, etc. Returns the cached ResourceManager instance used by this class. Overrides the current thread's CurrentUICulture property for all resource lookups using this strongly typed resource class. Looks up a localized string similar to CREATE TEMP VIEW SCHEMACONSTRAINTCOLUMNS AS SELECT CONSTRAINT_CATALOG, NULL AS CONSTRAINT_SCHEMA, CONSTRAINT_NAME, TABLE_CATALOG, NULL AS TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME FROM TEMP.SCHEMAINDEXCOLUMNS UNION SELECT CONSTRAINT_CATALOG, NULL, CONSTRAINT_NAME, TABLE_CATALOG, NULL, TABLE_NAME, FKEY_FROM_COLUMN FROM TEMP.SCHEMAFOREIGNKEYS;. Looks up a localized string similar to CREATE TEMP VIEW SCHEMACONSTRAINTS AS SELECT INDEX_CATALOG AS CONSTRAINT_CATALOG, NULL AS CONSTRAINT_SCHEMA, INDEX_NAME AS CONSTRAINT_NAME, TABLE_CATALOG, NULL AS TABLE_SCHEMA, TABLE_NAME, 'PRIMARY KEY' AS CONSTRAINT_TYPE, 0 AS IS_DEFERRABLE, 0 AS INITIALLY_DEFERRED, NULL AS CHECK_CLAUSE FROM TEMP.SCHEMAINDEXES WHERE PRIMARY_KEY = 1 UNION SELECT INDEX_CATALOG, NULL, INDEX_NAME, TABLE_CATALOG, NULL, TABLE_NAME, 'UNIQUE', 0, 0, NULL FROM TEMP.SCHEMAINDEXES WHERE PRIMARY_KEY = 0 AND [UNIQUE] = 1 UNION [rest of string was truncated]";. Class generating SQL for a DML command tree. Generates SQL fragment returning server-generated values. Requires: translator knows about member values so that we can figure out how to construct the key predicate. Sample SQL: select IdentityValue from dbo.MyTable where @@ROWCOUNT > 0 and IdentityValue = scope_identity() or select TimestamptValue from dbo.MyTable where @@ROWCOUNT > 0 and Id = 1 Note that we filter on rowcount to ensure no rows are returned if no rows were modified. Builder containing command text Modification command tree Translator used to produce DML SQL statement for the tree Returning expression. If null, the method returns immediately without producing a SELECT statement. Lightweight expression translator for DML expression trees, which have constrained scope and support. Initialize a new expression translator populating the given string builder with command text. Command text builder and command tree must not be null. Command text with which to populate commands Command tree generating SQL Indicates whether the translator should preserve member values while compiling t-SQL (only needed for server generation) Call this method to register a property value pair so the translator "remembers" the values for members of the row being modified. These values can then be used to form a predicate for server-generation (based on the key of the row) DbExpression containing the column reference (property expression). DbExpression containing the value of the column. Represents the sql fragment for any node in the query tree. The nodes in a query tree produce various kinds of sql A select statement. A reference to an extent. (symbol) A raw string. We have this interface to allow for a common return type for the methods in the expression visitor At the end of translation, the sql fragments are converted into real strings. Write the string represented by this fragment into the stream. The stream that collects the strings. Context information used for renaming. The global lists are used to generated new names without collisions. A Join symbol is a special kind of Symbol. It has to carry additional information ColumnList for the list of columns in the select clause if this symbol represents a sql select statement. This is set by . ExtentList is the list of extents in the select clause. FlattenedExtentList - if the Join has multiple extents flattened at the top level, we need this information to ensure that extent aliases are renamed correctly in NameToExtent has all the extents in ExtentList as a dictionary. This is used by to flatten record accesses. IsNestedJoin - is used to determine whether a JoinSymbol is an ordinary join symbol, or one that has a corresponding SqlSelectStatement. All the lists are set exactly once, and then used for lookups/enumerated. This class represents an extent/nested select statement, or a column. The important fields are Name, Type and NewName. NewName starts off the same as Name, and is then modified as necessary. The rest are used by special symbols. e.g. NeedsRenaming is used by columns to indicate that a new name must be picked for the column in the second phase of translation. IsUnnest is used by symbols for a collection expression used as a from clause. This allows to add the column list after the alias. Write this symbol out as a string for sql. This is just the new name of the symbol (which could be the same as the old name). We rename columns here if necessary. A set of static helpers for type metadata Name of the Nullable Facet Cast the EdmType of the given type usage to the given TEdmType Gets the TypeUsage of the elment if the given type is a collection type Retrieves the properties of in the EdmType underlying the input type usage, if that EdmType is a structured type (EntityType, RowType). Retrieves the properties of the given EdmType, if it is a structured type (EntityType, RowType). Is the given type usage over a collection type Is the given type a collection type Is the given type usage over a primitive type Is the given type a primitive type Is the given type usage over a row type Is the given type a row type Gets the type of the given type usage if it is a primitive type Gets the value for the metadata property with the given name Name of the MaxLength Facet Name of the Unicode Facet Name of the FixedLength Facet Name of the PreserveSeconds Facet Name of the Precision Facet Name of the Scale Facet Name of the DefaultValue Facet Get the value specified on the given type usage for the given facet name. If the faces does not have a value specifid or that value is null returns the default value for that facet. Given a facet name and an EdmType, tries to get that facet's description. SkipClause represents the a SKIP expression in a SqlSelectStatement. It has a count property, which indicates how many rows should be skipped. Creates a SkipClause with the given skipCount. Creates a SkipClause with the given skipCount. Write out the SKIP part of sql select statement It basically writes OFFSET (X). How many rows should be skipped. This class is like StringBuilder. While traversing the tree for the first time, we do not know all the strings that need to be appended e.g. things that need to be renamed, nested select statements etc. So, we use a builder that can collect all kinds of sql fragments. Add an object to the list - we do not verify that it is a proper sql fragment since this is an internal method. This is to pretty print the SQL. The writer needs to know about new lines so that it can add the right amount of indentation at the beginning of lines. We delegate the writing of the fragment to the appropriate type. Whether the builder is empty. This is used by the to determine whether a sql statement can be reused. Translates the command object into a SQL string that can be executed on SQLite. The translation is implemented as a visitor over the query tree. It makes a single pass over the tree, collecting the sql fragments for the various nodes in the tree . The major operations are Select statement minimization. Multiple nodes in the query tree that can be part of a single SQL select statement are merged. e.g. a Filter node that is the input of a Project node can typically share the same SQL statement. Alpha-renaming. As a result of the statement minimization above, there could be name collisions when using correlated subqueries Filter( b = Project( c.x c = Extent(foo) ) exists ( Filter( c = Extent(foo) b.x = c.x ) ) ) The first Filter, Project and Extent will share the same SQL select statement. The alias for the Project i.e. b, will be replaced with c. If the alias c for the Filter within the exists clause is not renamed, we will get c.x = c.x, which is incorrect. Instead, the alias c within the second filter should be renamed to c1, to give c.x = c1.x i.e. b is renamed to c, and c is renamed to c1. Join flattening. In the query tree, a list of join nodes is typically represented as a tree of Join nodes, each with 2 children. e.g. a = Join(InnerJoin b = Join(CrossJoin c = Extent(foo) d = Extent(foo) ) e = Extent(foo) on b.c.x = e.x ) If translated directly, this will be translated to FROM ( SELECT c.*, d.* FROM foo as c CROSS JOIN foo as d) as b INNER JOIN foo as e on b.x' = e.x It would be better to translate this as FROM foo as c CROSS JOIN foo as d INNER JOIN foo as e on c.x = e.x This allows the optimizer to choose an appropriate join ordering for evaluation. Select * and column renaming. In the example above, we noticed that in some cases we add SELECT * FROM ... to complete the SQL statement. i.e. there is no explicit PROJECT list. In this case, we enumerate all the columns available in the FROM clause This is particularly problematic in the case of Join trees, since the columns from the extents joined might have the same name - this is illegal. To solve this problem, we will have to rename columns if they are part of a SELECT * for a JOIN node - we do not need renaming in any other situation. . Renaming issues. When rows or columns are renamed, we produce names that are unique globally with respect to the query. The names are derived from the original names, with an integer as a suffix. e.g. CustomerId will be renamed to CustomerId1, CustomerId2 etc. Since the names generated are globally unique, they will not conflict when the columns of a JOIN SELECT statement are joined with another JOIN. Record flattening. SQL server does not have the concept of records. However, a join statement produces records. We have to flatten the record accesses into a simple alias.column form. Building the SQL. There are 2 phases Traverse the tree, producing a sql builder Write the SqlBuilder into a string, renaming the aliases and columns as needed. In the first phase, we traverse the tree. We cannot generate the SQL string right away, since The WHERE clause has to be visited before the from clause. extent aliases and column aliases need to be renamed. To minimize renaming collisions, all the names used must be known, before any renaming choice is made. To defer the renaming choices, we use symbols . These are renamed in the second phase. Since visitor methods cannot transfer information to child nodes through parameters, we use some global stacks, A stack for the current SQL select statement. This is needed by to create a list of free variables used by a select statement. This is needed for alias renaming. A stack for the join context. When visiting a , we need to know whether we are inside a join or not. If we are inside a join, we do not create a new SELECT statement. Global state. To enable renaming, we maintain The set of all extent aliases used. The set of all column aliases used. Finally, we have a symbol table to lookup variable references. All references to the same extent have the same symbol. Sql select statement sharing. Each of the relational operator nodes Project Filter GroupBy Sort/OrderBy can add its non-input (e.g. project, predicate, sort order etc.) to the SQL statement for the input, or create a new SQL statement. If it chooses to reuse the input's SQL statement, we play the following symbol table trick to accomplish renaming. The symbol table entry for the alias of the current node points to the symbol for the input in the input's SQL statement. Project(b.x b = Filter( c = Extent(foo) c.x = 5) ) The Extent node creates a new SqlSelectStatement. This is added to the symbol table by the Filter as {c, Symbol(c)}. Thus, c.x is resolved to Symbol(c).x. Looking at the project node, we add {b, Symbol(c)} to the symbol table if the SQL statement is reused, and {b, Symbol(b)}, if there is no reuse. Thus, b.x is resolved to Symbol(c).x if there is reuse, and to Symbol(b).x if there is no reuse. Every relational node has to pass its SELECT statement to its children This allows them (DbVariableReferenceExpression eventually) to update the list of outer extents (free variables) used by this select statement. Nested joins and extents need to know whether they should create a new Select statement, or reuse the parent's. This flag indicates whether the parent is a join or not. VariableReferenceExpressions are allowed only as children of DbPropertyExpression or MethodExpression. The cheapest way to ensure this is to set the following property in DbVariableReferenceExpression and reset it in the allowed parent expressions. All special built-in functions and their handlers All special non-aggregate canonical functions and their handlers Valid datepart values Initializes the mapping from functions to T-SQL operators for all functions that translate to T-SQL operators Basic constructor. General purpose static function that can be called from System.Data assembly command tree Parameters to add to the command tree corresponding to constants in the command tree. Used only in ModificationCommandTrees. The string representing the SQL to be executed. Translate a command tree to a SQL string. The input tree could be translated to either a SQL SELECT statement or a SELECT expression. This choice is made based on the return type of the expression CollectionType => select statement non collection type => select expression The string representing the SQL to be executed. Translate a function command tree to a SQL string. Convert the SQL fragments to a string. We have to setup the Stream for writing. A string representing the SQL to be executed. Translate(left) AND Translate(right) A . An apply is just like a join, so it shares the common join processing in A . For binary expressions, we delegate to . We handle the other expressions directly. A If the ELSE clause is null, we do not write it out. A The parser generates Not(Equals(...)) for <>. A . Constants will be send to the store as part of the generated TSQL, not as parameters A . Strings are wrapped in single quotes and escaped. Numbers are written literally. is illegal at this stage The DISTINCT has to be added to the beginning of SqlSelectStatement.Select, but it might be too late for that. So, we use a flag on SqlSelectStatement instead, and add the "DISTINCT" in the second phase. A An element expression returns a scalar - so it is translated to ( Select ... ) Only concrete expression types will be visited. If we are in a Join context, returns a with the extent name, otherwise, a new with the From field set. Gets escaped TSql identifier describing this entity set. The bodies of , , , are similar. Each does the following. Visit the input expression Determine if the input's SQL statement can be reused, or a new one must be created. Create a new symbol table scope Push the Sql statement onto a stack, so that children can update the free variable list. Visit the non-input expression. Cleanup A Lambda functions are not supported. The functions supported are: Canonical Functions - We recognize these by their dataspace, it is DataSpace.CSpace Store Functions - We recognize these by the BuiltInAttribute and not being Canonical User-defined Functions - All the rest except for Lambda functions We handle Canonical and Store functions the same way: If they are in the list of functions that need special handling, we invoke the appropriate handler, otherwise we translate them to FunctionName(arg1, arg2, ..., argn). We translate user-defined functions to NamespaceName.FunctionName(arg1, arg2, ..., argn). A is illegal at this stage is illegal at this stage for general details. We modify both the GroupBy and the Select fields of the SqlSelectStatement. GroupBy gets just the keys without aliases, and Select gets the keys and the aggregates with aliases. Whenever there exists at least one aggregate with an argument that is not is not a simple over , we create a nested query in which we alias the arguments to the aggregates. That is due to the following two limitations of Sql Server: If an expression being aggregated contains an outer reference, then that outer reference must be the only column referenced in the expression Sql Server cannot perform an aggregate function on an expression containing an aggregate or a subquery. The default translation, without inner query is: SELECT kexp1 AS key1, kexp2 AS key2,... kexpn AS keyn, aggf1(aexpr1) AS agg1, .. aggfn(aexprn) AS aggn FROM input AS a GROUP BY kexp1, kexp2, .. kexpn When we inject an innner query, the equivalent translation is: SELECT key1 AS key1, key2 AS key2, .. keyn AS keys, aggf1(agg1) AS agg1, aggfn(aggn) AS aggn FROM ( SELECT kexp1 AS key1, kexp2 AS key2,... kexpn AS keyn, aexpr1 AS agg1, .. aexprn AS aggn FROM input AS a ) as a GROUP BY key1, key2, keyn A Not(IsEmpty) has to be handled specially, so we delegate to . A . [NOT] EXISTS( ... ) Not(IsNull) is handled specially, so we delegate to A IS [NOT] NULL is illegal at this stage A A . A . A Translates to TOP expression. A DbNewInstanceExpression is allowed as a child of DbProjectExpression only. If anyone else is the parent, we throw. We also perform special casing for collections - where we could convert them into Unions for the actual implementation. The Not expression may cause the translation of its child to change. These children are NOT(Not(x)) becomes x NOT EXISTS becomes EXISTS IS NULL becomes IS NOT NULL = becomes<> A is illegal at this stage A A A for the general ideas. A This method handles record flattening, which works as follows. consider an expression Prop(y, Prop(x, Prop(d, Prop(c, Prop(b, Var(a))))) where a,b,c are joins, d is an extent and x and y are fields. b has been flattened into a, and has its own SELECT statement. c has been flattened into b. d has been flattened into c. We visit the instance, so we reach Var(a) first. This gives us a (join)symbol. Symbol(a).b gives us a join symbol, with a SELECT statement i.e. Symbol(b). From this point on , we need to remember Symbol(b) as the source alias, and then try to find the column. So, we use a SymbolPair. We have reached the end when the symbol no longer points to a join symbol. A if we have not reached the first Join node that has a SELECT statement. A if we have seen the JoinNode, and it has a SELECT statement. A with {Input}.propertyName otherwise. Any(input, x) => Exists(Filter(input,x)) All(input, x) => Not Exists(Filter(input, not(x)) is illegal at this stage is illegal at this stage For Sql9 it translates to: SELECT Y.x1, Y.x2, ..., Y.xn FROM ( SELECT X.x1, X.x2, ..., X.xn, row_number() OVER (ORDER BY sk1, sk2, ...) AS [row_number] FROM input as X ) as Y WHERE Y.[row_number] > count ORDER BY sk1, sk2, ... A A is illegal at this stage A This code is shared by and Since the left and right expression may not be Sql select statements, we must wrap them up to look like SQL select statements. This method determines whether an extent from an outer scope(free variable) is used in the CurrentSelectStatement. An extent in an outer scope, if its symbol is not in the FromExtents of the CurrentSelectStatement. A . Aggregates are not visited by the normal visitor walk. The aggreate to be translated The translated aggregate argument This is called by the relational nodes. It does the following If the input is not a SqlSelectStatement, it assumes that the input is a collection expression, and creates a new SqlSelectStatement A and the main fromSymbol for this select statement. Was the parent a DbNotExpression? Translate a NewInstance(Element(X)) expression into "select top(1) * from X" Was the parent a DbNotExpression? This handles the processing of join expressions. The extents on a left spine are flattened, while joins not on the left spine give rise to new nested sub queries. Joins work differently from the rest of the visiting, in that the parent (i.e. the join node) creates the SqlSelectStatement for the children to use. The "parameter" IsInJoinContext indicates whether a child extent should add its stuff to the existing SqlSelectStatement, or create a new SqlSelectStatement By passing true, we ask the children to add themselves to the parent join, by passing false, we ask the children to create new Select statements for themselves. This method is called from and . A This is called from . This is responsible for maintaining the symbol table after visiting a child of a join expression. The child's sql statement may need to be completed. The child's result could be one of The same as the parent's - this is treated specially. A sql select statement, which may need to be completed An extent - just copy it to the from clause Anything else (from a collection-valued expression) - unnest and copy it. If the input was a Join, we need to create a new join symbol, otherwise, we create a normal symbol. We then call AddFromSymbol to add the AS clause, and update the symbol table. If the child's result was the same as the parent's, we have to clean up the list of symbols in the FromExtents list, since this contains symbols from the children of both the parent and the child. The happens when the child visited is a Join, and is the leftmost child of the parent. We assume that this is only called as a child of a Project. This replaces , since we do not allow DbNewInstanceExpression as a child of any node other than DbProjectExpression. We write out the translation of each of the columns in the record. A Determines whether the given function is a built-in function that requires special handling Determines whether the given function is a canonical function that requires special handling Default handling for functions Translates them to FunctionName(arg1, arg2, ..., argn) Default handling for functions with a given name. Translates them to functionName(arg1, arg2, ..., argn) Default handling on function arguments Appends the list of arguments to the given result If the function is niladic it does not append anything, otherwise it appends (arg1, arg2, ..., argn) Handler for special built in functions Handler for special canonical functions Dispatches the special function processing to the appropriate handler Handles functions that are translated into TSQL operators. The given function should have one or two arguments. Functions with one arguemnt are translated into op arg Functions with two arguments are translated into arg0 op arg1 Also, the arguments can be optionaly enclosed in parethesis Whether the arguments should be enclosed in parethesis Handles special case in which datepart 'type' parameter is present. all the functions handles here have *only* the 1st parameter as datepart. datepart value is passed along the QP as string and has to be expanded as TSQL keyword. DateAdd(datetime, secondsToAdd) -> DATEADD ( seconds , number, date) DateSubtract(datetime1, datetime2) -> DATEDIFF ( seconds , startdate , enddate ) Handler for canonical functions for extracting date parts. For example: Year(date) -> DATEPART( year, date) Function rename IndexOf -> CHARINDEX Function rename NewGuid -> NEWID Length(arg) -> LEN(arg + '.') - LEN('.') Round(numericExpression) -> Round(numericExpression, 0); TRIM(string) -> LTRIM(RTRIM(string)) LEFT(string, length) -> SUBSTR(string, 1, length) RIGHT(string, length) -> SUBSTR(string, -(length), length) Function rename ToLower -> LOWER Function rename ToUpper -> UPPER Add the column names from the referenced extent/join to the select statement. If the symbol is a JoinSymbol, we recursively visit all the extents, halting at real extents and JoinSymbols that have an associated SqlSelectStatement. The column names for a real extent can be derived from its type. The column names for a Join Select statement can be got from the list of columns that was created when the Join's select statement was created. We do the following for each column. Add the SQL string for each column to the SELECT clause Add the column to the list of columns - so that it can become part of the "type" of a JoinSymbol Check if the column name collides with a previous column added to the same select statement. Flag both the columns for renaming if true. Add the column to a name lookup dictionary for collision detection. The select statement that started off as SELECT * The symbol containing the type information for the columns to be added. Columns that have been added to the Select statement. This is created in . A dictionary of the columns above. Comma or nothing, depending on whether the SELECT clause is empty. Expands Select * to "select the_list_of_columns" If the columns are taken from an extent, they are written as {original_column_name AS Symbol(original_column)} to allow renaming. If the columns are taken from a Join, they are written as just {original_column_name}, since there cannot be a name collision. We concatenate the columns from each of the inputs to the select statement. Since the inputs may be joins that are flattened, we need to recurse. The inputs are inferred from the symbols in FromExtents. This method is called after the input to a relational node is visited. and There are 2 scenarios The fromSymbol is new i.e. the select statement has just been created, or a join extent has been added. The fromSymbol is old i.e. we are reusing a select statement. If we are not reusing the select statement, we have to complete the FROM clause with the alias -- if the input was an extent FROM = [SchemaName].[TableName] -- if the input was a Project FROM = (SELECT ... FROM ... WHERE ...) These become -- if the input was an extent FROM = [SchemaName].[TableName] AS alias -- if the input was a Project FROM = (SELECT ... FROM ... WHERE ...) AS alias and look like valid FROM clauses. Finally, we have to add the alias to the global list of aliases used, and also to the current symbol table. The alias to be used. Translates a list of SortClauses. Used in the translation of OrderBy The SqlBuilder to which the sort keys should be appended A new select statement, with the old one as the from clause. This is called after a relational node's input has been visited, and the input's sql statement cannot be reused. When the input's sql statement cannot be reused, we create a new sql statement, with the old one as the from clause of the new statement. The old statement must be completed i.e. if it has an empty select list, the list of columns must be projected out. If the old statement being completed has a join symbol as its from extent, the new statement must have a clone of the join symbol as its extent. We cannot reuse the old symbol, but the new select statement must behave as though it is working over the "join" record. A new select statement, with the old one as the from clause. Before we embed a string literal in a SQL string, we should convert all ' to '', and enclose the whole string in single quotes. The escaped sql string. Returns the sql primitive/native type name. It will include size, precision or scale depending on type information present in the type facets Handles the expression represending DbLimitExpression.Limit and DbSkipExpression.Count. If it is a constant expression, it simply does to string thus avoiding casting it to the specific value (which would be done if is called) This is used to determine if a particular expression is an Apply operation. This is only the case when the DbExpressionKind is CrossApply or OuterApply. This is used to determine if a particular expression is a Join operation. This is true for DbCrossJoinExpression and DbJoinExpression, the latter of which may have one of several different ExpressionKinds. This is used to determine if a calling expression needs to place round brackets around the translation of the expression e. Constants, parameters and properties do not require brackets, everything else does. true, if the expression needs brackets Determine if the owner expression can add its unique sql to the input's SqlSelectStatement The SqlSelectStatement of the input to the relational node. The kind of the expression node(not the input's) We use the normal box quotes for SQL server. We do not deal with ANSI quotes i.e. double quotes. Simply calls with addDefaultColumns set to true This is called from and nodes which require a select statement as an argument e.g. , . SqlGenerator needs its child to have a proper alias if the child is just an extent or a join. The normal relational nodes result in complete valid SQL statements. For the rest, we need to treat them as there was a dummy -- originally {expression} -- change that to SELECT * FROM {expression} as c DbLimitExpression needs to start the statement but not add the default columns This method is called by and This is passed from in the All(...) case. If the sql fragment for an input expression is not a SqlSelect statement or other acceptable form (e.g. an extent as a SqlBuilder), we need to wrap it in a form acceptable in a FROM clause. These are primarily the The set operation expressions - union all, intersect, except TVFs, which are conceptually similar to tables Is this a builtin function (ie) does it have the builtinAttribute specified? Helper method for the Group By visitor Returns true if at least one of the aggregates in the given list has an argument that is not a over Determines whether the given expression is a over The top of the stack The top of the stack A SqlSelectStatement represents a canonical SQL SELECT statement. It has fields for the 5 main clauses SELECT FROM WHERE GROUP BY ORDER BY We do not have HAVING, since it does not correspond to anything in the DbCommandTree. Each of the fields is a SqlBuilder, so we can keep appending SQL strings or other fragments to build up the clause. We have a IsDistinct property to indicate that we want distict columns. This is given out of band, since the input expression to the select clause may already have some columns projected out, and we use append-only SqlBuilders. The DISTINCT is inserted when we finally write the object into a string. Also, we have a Top property, which is non-null if the number of results should be limited to certain number. It is given out of band for the same reasons as DISTINCT. The FromExtents contains the list of inputs in use for the select statement. There is usually just one element in this - Select statements for joins may temporarily have more than one. If the select statement is created by a Join node, we maintain a list of all the extents that have been flattened in the join in AllJoinExtents in J(j1= J(a,b), c) FromExtents has 2 nodes JoinSymbol(name=j1, ...) and Symbol(name=c) AllJoinExtents has 3 nodes Symbol(name=a), Symbol(name=b), Symbol(name=c) If any expression in the non-FROM clause refers to an extent in a higher scope, we add that extent to the OuterExtents list. This list denotes the list of extent aliases that may collide with the aliases used in this select statement. It is set by . An extent is an outer extent if it is not one of the FromExtents. Write out a SQL select statement as a string. We have to Check whether the aliases extents we use in this statement have to be renamed. We first create a list of all the aliases used by the outer extents. For each of the FromExtents( or AllJoinExtents if it is non-null), rename it if it collides with the previous list. Write each of the clauses (if it exists) as a string Do we need to add a DISTINCT at the beginning of the SELECT This extends StringWriter primarily to add the ability to add an indent to each line that is written out. Reset atBeginningofLine if we detect the newline string. Add as many tabs as the value of indent if we are at the beginning of a line. The number of tabs to be added at the beginning of each new line. The SymbolPair exists to solve the record flattening problem. Consider a property expression D(v, "j3.j2.j1.a.x") where v is a VarRef, j1, j2, j3 are joins, a is an extent and x is a columns. This has to be translated eventually into {j'}.{x'} The source field represents the outermost SqlStatement representing a join expression (say j2) - this is always a Join symbol. The column field keeps moving from one join symbol to the next, until it stops at a non-join symbol. This is returned by , but never makes it into a SqlBuilder. The symbol table is quite primitive - it is a stack with a new entry for each scope. Lookups search from the top of the stack to the bottom, until an entry is found. The symbols are of the following kinds represents tables (extents/nested selects/unnests) represents Join nodes columns. Symbols represent names to be resolved, or things to be renamed. TopClause represents the a TOP expression in a SqlSelectStatement. It has a count property, which indicates how many TOP rows should be selected and a boolen WithTies property. Creates a TopClause with the given topCount and withTies. Creates a TopClause with the given topCount and withTies. Write out the TOP part of sql select statement It basically writes LIMIT (X). Do we need to add a WITH_TIES to the top statement How many top rows should be selected. SQLite implementation of . Static instance member which returns an instanced class. Constructs a new instance. Creates and returns a new object. The new object. Creates and returns a new object. The new object. Creates and returns a new object. The new object. Creates and returns a new object. The new object. Creates and returns a new object. The new object. Creates and returns a new object. The new object. The Provider Manifest for SQL Server Constructs the provider manifest. We pass the token as a DateTimeFormat enum text, because all the datetime functions are vastly different depending on how the user is opening the connection A token used to infer the capabilities of the store Returns manifest information for the provider The name of the information to be retrieved. An XmlReader at the begining of the information requested. This method takes a type and a set of facets and returns the best mapped equivalent type in EDM. A TypeUsage encapsulating a store type and a set of facets A TypeUsage encapsulating an EDM type and a set of facets This method takes a type and a set of facets and returns the best mapped equivalent type A TypeUsage encapsulating an EDM type and a set of facets A TypeUsage encapsulating a store type and a set of facets Creates a SQLiteParameter given a name, type, and direction Determines DbType for the given primitive type. Extracts facet information as well. Determines preferred value for SqlParameter.Size. Returns null where there is no preference. Chooses the appropriate DbType for the given string type. Chooses the appropriate DbType for the given binary type. Creates temporary tables on the connection so schema information can be queried There's a lot of work involved in getting schema information out of SQLite, but LINQ expects to be able to query on schema tables. Therefore we need to "fake" it by generating temporary tables filled with the schema of the current connection. We get away with making this information static because schema information seems to always be queried on a new connection object, so the schema is always fresh. The connection upon which to build the schema tables Turn a datatable into a table in the temporary database for the connection The connection to make the temporary table in The table to write out The temporary table name to write to ================================================ FILE: library/lib/System.Data.SQLite.dll.config ================================================ ================================================ FILE: library/lib/System.Data.SQLite.xml ================================================ System.Data.SQLite Defines a source code identifier custom attribute for an assembly manifest. Constructs an instance of this attribute class using the specified source code identifier value. The source code identifier value to use. Gets the source code identifier value. Defines a source code time-stamp custom attribute for an assembly manifest. Constructs an instance of this attribute class using the specified source code time-stamp value. The source code time-stamp value to use. Gets the source code time-stamp value. This is the method signature for the SQLite core library logging callback function for use with sqlite3_log() and the SQLITE_CONFIG_LOG. WARNING: This delegate is used more-or-less directly by native code, do not modify its type signature. The extra data associated with this message, if any. The error code associated with this message. The message string to be logged. This class implements SQLiteBase completely, and is the guts of the code that interop's SQLite with .NET This internal class provides the foundation of SQLite support. It defines all the abstract members needed to implement a SQLite data provider, and inherits from SQLiteConvert which allows for simple translations of string to and from SQLite. This base class provides datatype conversion services for the SQLite provider. The format string for DateTime values when using the InvariantCulture or CurrentCulture formats. The value for the Unix epoch (e.g. January 1, 1970 at midnight, in UTC). The value of the OLE Automation epoch represented as a Julian day. An array of ISO-8601 DateTime formats that we support parsing. The internal default format for UTC DateTime values when converting to a string. The internal default format for local DateTime values when converting to a string. An UTF-8 Encoding instance, so we can convert strings to and from UTF-8 The default DateTime format for this instance. The default DateTimeKind for this instance. The default DateTime format string for this instance. Initializes the conversion class The default date/time format to use for this instance The DateTimeKind to use. The DateTime format string to use. Converts a string to a UTF-8 encoded byte array sized to include a null-terminating character. The string to convert to UTF-8 A byte array containing the converted string plus an extra 0 terminating byte at the end of the array. Convert a DateTime to a UTF-8 encoded, zero-terminated byte array. This function is a convenience function, which first calls ToString() on the DateTime, and then calls ToUTF8() with the string result. The DateTime to convert. The UTF-8 encoded string, including a 0 terminating byte at the end of the array. Converts a UTF-8 encoded IntPtr of the specified length into a .NET string The pointer to the memory where the UTF-8 string is encoded The number of bytes to decode A string containing the translated character(s) Converts a UTF-8 encoded IntPtr of the specified length into a .NET string The pointer to the memory where the UTF-8 string is encoded The number of bytes to decode A string containing the translated character(s) Converts a string into a DateTime, using the DateTimeFormat, DateTimeKind, and DateTimeFormatString specified for the connection when it was opened. Acceptable ISO8601 DateTime formats are: THHmmssK THHmmK HH:mm:ss.FFFFFFFK HH:mm:ssK HH:mmK yyyy-MM-dd HH:mm:ss.FFFFFFFK yyyy-MM-dd HH:mm:ssK yyyy-MM-dd HH:mmK yyyy-MM-ddTHH:mm:ss.FFFFFFFK yyyy-MM-ddTHH:mmK yyyy-MM-ddTHH:mm:ssK yyyyMMddHHmmssK yyyyMMddHHmmK yyyyMMddTHHmmssFFFFFFFK THHmmss THHmm HH:mm:ss.FFFFFFF HH:mm:ss HH:mm yyyy-MM-dd HH:mm:ss.FFFFFFF yyyy-MM-dd HH:mm:ss yyyy-MM-dd HH:mm yyyy-MM-ddTHH:mm:ss.FFFFFFF yyyy-MM-ddTHH:mm yyyy-MM-ddTHH:mm:ss yyyyMMddHHmmss yyyyMMddHHmm yyyyMMddTHHmmssFFFFFFF yyyy-MM-dd yyyyMMdd yy-MM-dd If the string cannot be matched to one of the above formats -OR- the DateTimeFormatString if one was provided, an exception will be thrown. The string containing either a long integer number of 100-nanosecond units since System.DateTime.MinValue, a Julian day double, an integer number of seconds since the Unix epoch, a culture-independent formatted date and time string, a formatted date and time string in the current culture, or an ISO8601-format string. A DateTime value Converts a string into a DateTime, using the specified DateTimeFormat, DateTimeKind and DateTimeFormatString. Acceptable ISO8601 DateTime formats are: THHmmssK THHmmK HH:mm:ss.FFFFFFFK HH:mm:ssK HH:mmK yyyy-MM-dd HH:mm:ss.FFFFFFFK yyyy-MM-dd HH:mm:ssK yyyy-MM-dd HH:mmK yyyy-MM-ddTHH:mm:ss.FFFFFFFK yyyy-MM-ddTHH:mmK yyyy-MM-ddTHH:mm:ssK yyyyMMddHHmmssK yyyyMMddHHmmK yyyyMMddTHHmmssFFFFFFFK THHmmss THHmm HH:mm:ss.FFFFFFF HH:mm:ss HH:mm yyyy-MM-dd HH:mm:ss.FFFFFFF yyyy-MM-dd HH:mm:ss yyyy-MM-dd HH:mm yyyy-MM-ddTHH:mm:ss.FFFFFFF yyyy-MM-ddTHH:mm yyyy-MM-ddTHH:mm:ss yyyyMMddHHmmss yyyyMMddHHmm yyyyMMddTHHmmssFFFFFFF yyyy-MM-dd yyyyMMdd yy-MM-dd If the string cannot be matched to one of the above formats -OR- the DateTimeFormatString if one was provided, an exception will be thrown. The string containing either a long integer number of 100-nanosecond units since System.DateTime.MinValue, a Julian day double, an integer number of seconds since the Unix epoch, a culture-independent formatted date and time string, a formatted date and time string in the current culture, or an ISO8601-format string. The SQLiteDateFormats to use. The DateTimeKind to use. The DateTime format string to use. A DateTime value Converts a julianday value into a DateTime The value to convert A .NET DateTime Converts a julianday value into a DateTime The value to convert The DateTimeKind to use. A .NET DateTime Converts the specified number of seconds from the Unix epoch into a value. The number of whole seconds since the Unix epoch. Either Utc or Local time. The new value. Converts the specified number of ticks since the epoch into a value. The number of whole ticks since the epoch. Either Utc or Local time. The new value. Converts a DateTime struct to a JulianDay double The DateTime to convert The JulianDay value the Datetime represents Converts a DateTime struct to the whole number of seconds since the Unix epoch. The DateTime to convert The whole number of seconds since the Unix epoch Returns the DateTime format string to use for the specified DateTimeKind. If is not null, it will be returned verbatim. The DateTimeKind to use. The DateTime format string to use. The DateTime format string to use for the specified DateTimeKind. Converts a string into a DateTime, using the DateTimeFormat, DateTimeKind, and DateTimeFormatString specified for the connection when it was opened. The DateTime value to convert Either a string containing the long integer number of 100-nanosecond units since System.DateTime.MinValue, a Julian day double, an integer number of seconds since the Unix epoch, a culture-independent formatted date and time string, a formatted date and time string in the current culture, or an ISO8601-format date/time string. Internal function to convert a UTF-8 encoded IntPtr of the specified length to a DateTime. This is a convenience function, which first calls ToString() on the IntPtr to convert it to a string, then calls ToDateTime() on the string to return a DateTime. A pointer to the UTF-8 encoded string The length in bytes of the string The parsed DateTime value Smart method of splitting a string. Skips quoted elements, removes the quotes. This split function works somewhat like the String.Split() function in that it breaks apart a string into pieces and returns the pieces as an array. The primary differences are: Only one character can be provided as a separator character Quoted text inside the string is skipped over when searching for the separator, and the quotes are removed. Thus, if splitting the following string looking for a comma:
One,Two, "Three, Four", Five

The resulting array would contain
[0] One
[1] Two
[2] Three, Four
[3] Five

Note that the leading and trailing spaces were removed from each item during the split.
Source string to split apart Separator character A string array of the split up elements
Splits the specified string into multiple strings based on a separator and returns the result as an array of strings. The string to split into pieces based on the separator character. If this string is null, null will always be returned. If this string is empty, an array of zero strings will always be returned. The character used to divide the original string into sub-strings. This character cannot be a backslash or a double-quote; otherwise, no work will be performed and null will be returned. If this parameter is non-zero, all double-quote characters will be retained in the returned list of strings; otherwise, they will be dropped. Upon failure, this parameter will be modified to contain an appropriate error message. The new array of strings or null if the input string is null -OR- the separator character is a backslash or a double-quote -OR- the string contains an unbalanced backslash or double-quote character. Queries and returns the string representation for an object, using the specified (or current) format provider. The object instance to return the string representation for. The format provider to use -OR- null if the current format provider for the thread should be used instead. The string representation for the object instance -OR- null if the object instance is also null. Convert a value to true or false. A string or number representing true or false Convert a string to true or false. A string representing true or false "yes", "no", "y", "n", "0", "1", "on", "off" as well as Boolean.FalseString and Boolean.TrueString will all be converted to a proper boolean value. Converts a SQLiteType to a .NET Type object The SQLiteType to convert Returns a .NET Type object For a given intrinsic type, return a DbType The native type to convert The corresponding (closest match) DbType Returns the ColumnSize for the given DbType The DbType to get the size of Determines the type name for the given database value type. The connection context for custom type mappings, if any. The database value type. The flags associated with the parent connection object. The type name or an empty string if it cannot be determined. Convert a DbType to a Type The DbType to convert from The closest-match .NET type For a given type, return the closest-match SQLite TypeAffinity, which only understands a very limited subset of types. The type to evaluate The SQLite type affinity for that type. Builds and returns a map containing the database column types recognized by this provider. A map containing the database column types recognized by this provider. For a given type name, return a closest-match .NET type The connection context for custom type mappings, if any. The name of the type to match The flags associated with the parent connection object. The .NET DBType the text evaluates to. The error code used for logging exceptions caught in user-provided code. Sets the status of the memory usage tracking subsystem in the SQLite core library. By default, this is enabled. If this is disabled, memory usage tracking will not be performed. This is not really a per-connection value, it is global to the process. Non-zero to enable memory usage tracking, zero otherwise. A standard SQLite return code (i.e. zero for success and non-zero for failure). Attempts to free as much heap memory as possible for the database connection. A standard SQLite return code (i.e. zero for success and non-zero for failure). Shutdown the SQLite engine so that it can be restarted with different config options. We depend on auto initialization to recover. Determines if the associated native connection handle is open. Non-zero if a database connection is open. Opens a database. Implementers should call SQLiteFunction.BindFunctions() and save the array after opening a connection to bind all attributed user-defined functions and collating sequences to the new connection. The filename of the database to open. SQLite automatically creates it if it doesn't exist. The flags associated with the parent connection object The open flags to use when creating the connection The maximum size of the pool for the given filename If true, the connection can be pulled from the connection pool Closes the currently-open database. After the database has been closed implemeters should call SQLiteFunction.UnbindFunctions() to deallocate all interop allocated memory associated with the user-defined functions and collating sequences tied to the closed connection. Non-zero if the operation is allowed to throw exceptions, zero otherwise. Sets the busy timeout on the connection. SQLiteCommand will call this before executing any command. The number of milliseconds to wait before returning SQLITE_BUSY Returns the text of the last error issued by SQLite Returns the text of the last error issued by SQLite -OR- the specified default error text if none is available from the SQLite core library. The error text to return in the event that one is not available from the SQLite core library. The error text. When pooling is enabled, force this connection to be disposed rather than returned to the pool When pooling is enabled, returns the number of pool entries matching the current file name. The number of pool entries matching the current file name. Prepares a SQL statement for execution. The source connection preparing the command. Can be null for any caller except LINQ The SQL command text to prepare The previous statement in a multi-statement command, or null if no previous statement exists The timeout to wait before aborting the prepare The remainder of the statement that was not processed. Each call to prepare parses the SQL up to to either the end of the text or to the first semi-colon delimiter. The remaining text is returned here for a subsequent call to Prepare() until all the text has been processed. Returns an initialized SQLiteStatement. Steps through a prepared statement. The SQLiteStatement to step through True if a row was returned, False if not. Resets a prepared statement so it can be executed again. If the error returned is SQLITE_SCHEMA, transparently attempt to rebuild the SQL statement and throw an error if that was not possible. The statement to reset Returns -1 if the schema changed while resetting, 0 if the reset was sucessful or 6 (SQLITE_LOCKED) if the reset failed due to a lock Attempts to interrupt the query currently executing on the associated native database connection. This function binds a user-defined functions to the connection. The object instance containing the metadata for the function to be bound. The object instance that implements the function to be bound. The flags associated with the parent connection object. Calls the native SQLite core library in order to create a disposable module containing the implementation of a virtual table. The module object to be used when creating the native disposable module. The flags for the associated object instance. Calls the native SQLite core library in order to cleanup the resources associated with a module containing the implementation of a virtual table. The module object previously passed to the method. The flags for the associated object instance. Calls the native SQLite core library in order to declare a virtual table in response to a call into the or virtual table methods. The virtual table module that is to be responsible for the virtual table being declared. The string containing the SQL statement describing the virtual table to be declared. Upon success, the contents of this parameter are undefined. Upon failure, it should contain an appropriate error message. A standard SQLite return code. Calls the native SQLite core library in order to declare a virtual table function in response to a call into the or virtual table methods. The virtual table module that is to be responsible for the virtual table function being declared. The number of arguments to the function being declared. The name of the function being declared. Upon success, the contents of this parameter are undefined. Upon failure, it should contain an appropriate error message. A standard SQLite return code. Enables or disabled extension loading by SQLite. True to enable loading of extensions, false to disable. Loads a SQLite extension library from the named file. The name of the dynamic link library file containing the extension. The name of the exported function used to initialize the extension. If null, the default "sqlite3_extension_init" will be used. Enables or disabled extened result codes returned by SQLite true to enable extended result codes, false to disable. Returns the numeric result code for the most recent failed SQLite API call associated with the database connection. Result code Returns the extended numeric result code for the most recent failed SQLite API call associated with the database connection. Extended result code Add a log message via the SQLite sqlite3_log interface. Error code to be logged with the message. String to be logged. Unlike the SQLite sqlite3_log() interface, this should be pre-formatted. Consider using the String.Format() function. Checks if the SQLite core library has been initialized in the current process. Non-zero if the SQLite core library has been initialized in the current process, zero otherwise. Creates a new SQLite backup object based on the provided destination database connection. The source database connection is the one associated with this object. The source and destination database connections cannot be the same. The destination database connection. The destination database name. The source database name. The newly created backup object. Copies up to N pages from the source database to the destination database associated with the specified backup object. The backup object to use. The number of pages to copy or negative to copy all remaining pages. Set to true if the operation needs to be retried due to database locking issues. True if there are more pages to be copied, false otherwise. Returns the number of pages remaining to be copied from the source database to the destination database associated with the specified backup object. The backup object to check. The number of pages remaining to be copied. Returns the total number of pages in the source database associated with the specified backup object. The backup object to check. The total number of pages in the source database. Destroys the backup object, rolling back any backup that may be in progess. The backup object to destroy. Returns the error message for the specified SQLite return code using the internal static lookup table. The SQLite return code. The error message or null if it cannot be found. Returns the error message for the specified SQLite return code using the sqlite3_errstr() function, falling back to the internal lookup table if necessary. The SQLite return code. The error message or null if it cannot be found. Returns a string representing the active version of SQLite Returns an integer representing the active version of SQLite Returns the rowid of the most recent successful INSERT into the database from this connection. Returns the number of changes the last executing insert/update caused. Returns the amount of memory (in bytes) currently in use by the SQLite core library. This is not really a per-connection value, it is global to the process. Returns the maximum amount of memory (in bytes) used by the SQLite core library since the high-water mark was last reset. This is not really a per-connection value, it is global to the process. Returns non-zero if the underlying native connection handle is owned by this instance. Returns non-zero if the given database connection is in autocommit mode. Autocommit mode is on by default. Autocommit mode is disabled by a BEGIN statement. Autocommit mode is re-enabled by a COMMIT or ROLLBACK. The opaque pointer returned to us by the sqlite provider The user-defined functions registered on this connection The modules created using this connection. Constructs the object used to interact with the SQLite core library using the UTF-8 text encoding. The DateTime format to be used when converting string values to a DateTime and binding DateTime parameters. The to be used when creating DateTime values. The format string to be used when parsing and formatting DateTime values. The native handle to be associated with the database connection. The fully qualified file name associated with . Non-zero if the newly created object instance will need to dispose of when it is no longer needed. This method attempts to dispose of all the derived object instances currently associated with the native database connection. Attempts to interrupt the query currently executing on the associated native database connection. This function binds a user-defined function to the connection. The object instance containing the metadata for the function to be bound. The object instance that implements the function to be bound. The flags associated with the parent connection object. Attempts to free as much heap memory as possible for the database connection. A standard SQLite return code (i.e. zero for success and non-zero for failure). Attempts to free N bytes of heap memory by deallocating non-essential memory allocations held by the database library. Memory used to cache database pages to improve performance is an example of non-essential memory. This is a no-op returning zero if the SQLite core library was not compiled with the compile-time option SQLITE_ENABLE_MEMORY_MANAGEMENT. Optionally, attempts to reset and/or compact the Win32 native heap, if applicable. The requested number of bytes to free. Non-zero to attempt a heap reset. Non-zero to attempt heap compaction. The number of bytes actually freed. This value may be zero. This value will be non-zero if the heap reset was successful. The size of the largest committed free block in the heap, in bytes. This value will be zero unless heap compaction is enabled. A standard SQLite return code (i.e. zero for success and non-zero for failure). Shutdown the SQLite engine so that it can be restarted with different configuration options. We depend on auto initialization to recover. Returns a standard SQLite result code. Shutdown the SQLite engine so that it can be restarted with different configuration options. We depend on auto initialization to recover. Non-zero to reset the database and temporary directories to their default values, which should be null for both. This parameter has no effect on non-Windows operating systems. Returns a standard SQLite result code. Determines if the associated native connection handle is open. Non-zero if the associated native connection handle is open. Calls the native SQLite core library in order to create a disposable module containing the implementation of a virtual table. The module object to be used when creating the native disposable module. The flags for the associated object instance. Calls the native SQLite core library in order to cleanup the resources associated with a module containing the implementation of a virtual table. The module object previously passed to the method. The flags for the associated object instance. Calls the native SQLite core library in order to declare a virtual table in response to a call into the or virtual table methods. The virtual table module that is to be responsible for the virtual table being declared. The string containing the SQL statement describing the virtual table to be declared. Upon success, the contents of this parameter are undefined. Upon failure, it should contain an appropriate error message. A standard SQLite return code. Calls the native SQLite core library in order to declare a virtual table function in response to a call into the or virtual table methods. The virtual table module that is to be responsible for the virtual table function being declared. The number of arguments to the function being declared. The name of the function being declared. Upon success, the contents of this parameter are undefined. Upon failure, it should contain an appropriate error message. A standard SQLite return code. Enables or disabled extension loading by SQLite. True to enable loading of extensions, false to disable. Loads a SQLite extension library from the named file. The name of the dynamic link library file containing the extension. The name of the exported function used to initialize the extension. If null, the default "sqlite3_extension_init" will be used. Enables or disabled extended result codes returned by SQLite Gets the last SQLite error code Gets the last SQLite extended error code Add a log message via the SQLite sqlite3_log interface. Add a log message via the SQLite sqlite3_log interface. Allows the setting of a logging callback invoked by SQLite when a log event occurs. Only one callback may be set. If NULL is passed, the logging callback is unregistered. The callback function to invoke. Returns a result code Creates a new SQLite backup object based on the provided destination database connection. The source database connection is the one associated with this object. The source and destination database connections cannot be the same. The destination database connection. The destination database name. The source database name. The newly created backup object. Copies up to N pages from the source database to the destination database associated with the specified backup object. The backup object to use. The number of pages to copy, negative to copy all remaining pages. Set to true if the operation needs to be retried due to database locking issues; otherwise, set to false. True if there are more pages to be copied, false otherwise. Returns the number of pages remaining to be copied from the source database to the destination database associated with the specified backup object. The backup object to check. The number of pages remaining to be copied. Returns the total number of pages in the source database associated with the specified backup object. The backup object to check. The total number of pages in the source database. Destroys the backup object, rolling back any backup that may be in progess. The backup object to destroy. Determines if the SQLite core library has been initialized for the current process. A boolean indicating whether or not the SQLite core library has been initialized for the current process. Determines if the SQLite core library has been initialized for the current process. A boolean indicating whether or not the SQLite core library has been initialized for the current process. Helper function to retrieve a column of data from an active statement. The statement being step()'d through The flags associated with the connection. The column index to retrieve The type of data contained in the column. If Uninitialized, this function will retrieve the datatype information. Returns the data in the column Returns non-zero if the underlying native connection handle is owned by this instance. Alternate SQLite3 object, overriding many text behaviors to support UTF-16 (Unicode) Constructs the object used to interact with the SQLite core library using the UTF-8 text encoding. The DateTime format to be used when converting string values to a DateTime and binding DateTime parameters. The to be used when creating DateTime values. The format string to be used when parsing and formatting DateTime values. The native handle to be associated with the database connection. The fully qualified file name associated with . Non-zero if the newly created object instance will need to dispose of when it is no longer needed. Overrides SQLiteConvert.ToString() to marshal UTF-16 strings instead of UTF-8 A pointer to a UTF-16 string The length (IN BYTES) of the string A .NET string Represents a single SQL backup in SQLite. The underlying SQLite object this backup is bound to. The actual backup handle. The destination database for the backup. The destination database name for the backup. The source database for the backup. The source database name for the backup. The last result from the StepBackup method of the SQLite3 class. This is used to determine if the call to the FinishBackup method of the SQLite3 class should throw an exception when it receives a non-Ok return code from the core SQLite library. Initializes the backup. The base SQLite object. The backup handle. The destination database for the backup. The destination database name for the backup. The source database for the backup. The source database name for the backup. Disposes and finalizes the backup. The extra behavioral flags that can be applied to a connection. No extra flags. Enable logging of all SQL statements to be prepared. Enable logging of all bound parameter types and raw values. Enable logging of all bound parameter strongly typed values. Enable logging of all exceptions caught from user-provided managed code called from native code via delegates. Enable logging of backup API errors. Skip adding the extension functions provided by the native interop assembly. When binding parameter values with the type, use the interop method that accepts an value. When binding parameter values, always bind them as though they were plain text (i.e. no numeric, date/time, or other conversions should be attempted). When returning column values, always return them as though they were plain text (i.e. no numeric, date/time, or other conversions should be attempted). Prevent this object instance from loading extensions. Prevent this object instance from creating virtual table modules. Skip binding any functions provided by other managed assemblies when opening the connection. Skip setting the logging related properties of the object instance that was passed to the method. Enable logging of all virtual table module errors seen by the method. Enable logging of certain virtual table module exceptions that cannot be easily discovered via other means. Enable tracing of potentially important [non-fatal] error conditions that cannot be easily reported through other means. When binding parameter values, always use the invariant culture when converting their values from strings. When binding parameter values, always use the invariant culture when converting their values to strings. Disable using the connection pool by default. If the "Pooling" connection string property is specified, its value will override this flag. The precise outcome of combining this flag with the flag is unspecified; however, one of the flags will be in effect. Enable using the connection pool by default. If the "Pooling" connection string property is specified, its value will override this flag. The precise outcome of combining this flag with the flag is unspecified; however, one of the flags will be in effect. Enable using per-connection mappings between type names and values. Also see the , , and methods. These per-connection mappings, when present, override the corresponding global mappings. Disable using global mappings between type names and values. This may be useful in some very narrow cases; however, if there are no per-connection type mappings, the fallback defaults will be used for both type names and their associated values. Therefore, use of this flag is not recommended. When binding parameter values or returning column values, always treat them as though they were plain text (i.e. no numeric, date/time, or other conversions should be attempted). When binding parameter values, always use the invariant culture when converting their values to strings or from strings. When binding parameter values or returning column values, always treat them as though they were plain text (i.e. no numeric, date/time, or other conversions should be attempted) and always use the invariant culture when converting their values to strings. When binding parameter values or returning column values, always treat them as though they were plain text (i.e. no numeric, date/time, or other conversions should be attempted) and always use the invariant culture when converting their values to strings or from strings. Enable all logging. The default extra flags for new connections. SQLite implementation of DbCommand. The default connection string to be used when creating a temporary connection to execute a command via the static or methods. The command text this command is based on The connection the command is associated with The version of the connection the command is associated with Indicates whether or not a DataReader is active on the command. The timeout for the command, kludged because SQLite doesn't support per-command timeout values Designer support Used by DbDataAdapter to determine updating behavior The collection of parameters for the command The SQL command text, broken into individual SQL statements as they are executed Unprocessed SQL text that has not been executed Transaction associated with this command Constructs a new SQLiteCommand Default constructor Initializes the command with the given command text The SQL command text Initializes the command with the given SQL command text and attach the command to the specified connection. The SQL command text The connection to associate with the command Initializes the command and associates it with the specified connection. The connection to associate with the command Initializes a command with the given SQL, connection and transaction The SQL command text The connection to associate with the command The transaction the command should be associated with Disposes of the command and clears all member variables Whether or not the class is being explicitly or implicitly disposed This method attempts to query the flags associated with the database connection in use. If the database connection is disposed, the default flags will be returned. The command containing the databse connection to query the flags from. The connection flags value. Clears and destroys all statements currently prepared Builds an array of prepared statements for each complete SQL statement in the command text Not implemented Forwards to the local CreateParameter() function Create a new parameter This function ensures there are no active readers, that we have a valid connection, that the connection is open, that all statements are prepared and all parameters are assigned in preparation for allocating a data reader. Creates a new SQLiteDataReader to execute/iterate the array of SQLite prepared statements The behavior the data reader should adopt Returns a SQLiteDataReader object This method creates a new connection, executes the query using the given execution type, closes the connection, and returns the results. If the connection string is null, a temporary in-memory database connection will be used. The text of the command to be executed. The execution type for the command. This is used to determine which method of the command object to call, which then determines the type of results returned, if any. The connection string to the database to be opened, used, and closed. If this parameter is null, a temporary in-memory databse will be used. The SQL parameter values to be used when building the command object to be executed, if any. The results of the query -OR- null if no results were produced from the given execution type. This method creates a new connection, executes the query using the given execution type and command behavior, closes the connection, and returns the results. If the connection string is null, a temporary in-memory database connection will be used. The text of the command to be executed. The execution type for the command. This is used to determine which method of the command object to call, which then determines the type of results returned, if any. The command behavior flags for the command. The connection string to the database to be opened, used, and closed. If this parameter is null, a temporary in-memory databse will be used. The SQL parameter values to be used when building the command object to be executed, if any. The results of the query -OR- null if no results were produced from the given execution type. Overrides the default behavior to return a SQLiteDataReader specialization class The flags to be associated with the reader. A SQLiteDataReader Overrides the default behavior of DbDataReader to return a specialized SQLiteDataReader class A SQLiteDataReader Called by the SQLiteDataReader when the data reader is closed. Execute the command and return the number of rows inserted/updated affected by it. The number of rows inserted/updated affected by it. Execute the command and return the number of rows inserted/updated affected by it. The flags to be associated with the reader. The number of rows inserted/updated affected by it. Execute the command and return the first column of the first row of the resultset (if present), or null if no resultset was returned. The first column of the first row of the first resultset from the query. Execute the command and return the first column of the first row of the resultset (if present), or null if no resultset was returned. The flags to be associated with the reader. The first column of the first row of the first resultset from the query. Does nothing. Commands are prepared as they are executed the first time, and kept in prepared state afterwards. Clones a command, including all its parameters A new SQLiteCommand with the same commandtext, connection and parameters The SQL command text associated with the command The amount of time to wait for the connection to become available before erroring out The type of the command. SQLite only supports CommandType.Text The connection associated with this command Forwards to the local Connection property Returns the SQLiteParameterCollection for the given command Forwards to the local Parameters property The transaction associated with this command. SQLite only supports one transaction per connection, so this property forwards to the command's underlying connection. Forwards to the local Transaction property Sets the method the SQLiteCommandBuilder uses to determine how to update inserted or updated rows in a DataTable. Determines if the command is visible at design time. Defaults to True. SQLite implementation of DbCommandBuilder. Default constructor Initializes the command builder and associates it with the specified data adapter. Minimal amount of parameter processing. Primarily sets the DbType for the parameter equal to the provider type in the schema The parameter to use in applying custom behaviors to a row The row to apply the parameter to The type of statement Whether the application of the parameter is part of a WHERE clause Returns a valid named parameter The name of the parameter Error Returns a named parameter for the given ordinal The i of the parameter Error Returns a placeholder character for the specified parameter i. The index of the parameter to provide a placeholder for Returns a named parameter Sets the handler for receiving row updating events. Used by the DbCommandBuilder to autogenerate SQL statements that may not have previously been generated. A data adapter to receive events on. Returns the automatically-generated SQLite command to delete rows from the database Returns the automatically-generated SQLite command to delete rows from the database Returns the automatically-generated SQLite command to update rows in the database Returns the automatically-generated SQLite command to update rows in the database Returns the automatically-generated SQLite command to insert rows into the database Returns the automatically-generated SQLite command to insert rows into the database Places brackets around an identifier The identifier to quote The bracketed identifier Removes brackets around an identifier The quoted (bracketed) identifier The undecorated identifier Override helper, which can help the base command builder choose the right keys for the given query Gets/sets the DataAdapter for this CommandBuilder Overridden to hide its property from the designer Overridden to hide its property from the designer Overridden to hide its property from the designer Overridden to hide its property from the designer Overridden to hide its property from the designer Event data for connection event handlers. The type of event being raised. The associated with this event, if any. The transaction associated with this event, if any. The command associated with this event, if any. The data reader associated with this event, if any. The critical handle associated with this event, if any. Command or message text associated with this event, if any. Extra data associated with this event, if any. Constructs the object. The type of event being raised. The base associated with this event, if any. The transaction associated with this event, if any. The command associated with this event, if any. The data reader associated with this event, if any. The critical handle associated with this event, if any. The command or message text, if any. The extra data, if any. Raised when an event pertaining to a connection occurs. The connection involved. Extra information about the event. SQLite implentation of DbConnection. The property can contain the following parameter(s), delimited with a semi-colon: Parameter Values Required Default Data Source This may be a file name, the string ":memory:", or any supported URI (starting with SQLite 3.7.7). Starting with release 1.0.86.0, in order to use more than one consecutive backslash (e.g. for a UNC path), each of the adjoining backslash characters must be doubled (e.g. "\\Network\Share\test.db" would become "\\\\Network\Share\test.db"). Y Version 3 N 3 UseUTF16Encoding True
False
N False
DateTimeFormat Ticks - Use the value of DateTime.Ticks.
ISO8601 - Use the ISO-8601 format. Uses the "yyyy-MM-dd HH:mm:ss.FFFFFFFK" format for UTC DateTime values and "yyyy-MM-dd HH:mm:ss.FFFFFFF" format for local DateTime values).
JulianDay - The interval of time in days and fractions of a day since January 1, 4713 BC.
UnixEpoch - The whole number of seconds since the Unix epoch (January 1, 1970).
InvariantCulture - Any culture-independent string value that the .NET Framework can interpret as a valid DateTime.
CurrentCulture - Any string value that the .NET Framework can interpret as a valid DateTime using the current culture.
N ISO8601
DateTimeKind Unspecified - Not specified as either UTC or local time.
Utc - The time represented is UTC.
Local - The time represented is local time.
N Unspecified
DateTimeFormatString The exact DateTime format string to use for all formatting and parsing of all DateTime values for this connection. N null BaseSchemaName Some base data classes in the framework (e.g. those that build SQL queries dynamically) assume that an ADO.NET provider cannot support an alternate catalog (i.e. database) without supporting alternate schemas as well; however, SQLite does not fit into this model. Therefore, this value is used as a placeholder and removed prior to preparing any SQL statements that may contain it. N sqlite_default_schema BinaryGUID True - Store GUID columns in binary form
False - Store GUID columns as text
N True
Cache Size {size in bytes} N 2000 Synchronous Normal - Normal file flushing behavior
Full - Full flushing after all writes
Off - Underlying OS flushes I/O's
N Full
Page Size {size in bytes} N 1024 Password {password} - Using this parameter requires that the CryptoAPI based codec be enabled at compile-time for both the native interop assembly and the core managed assemblies; otherwise, using this parameter may result in an exception being thrown when attempting to open the connection. N HexPassword {hexPassword} - Must contain a sequence of zero or more hexadecimal encoded byte values without a leading "0x" prefix. Using this parameter requires that the CryptoAPI based codec be enabled at compile-time for both the native interop assembly and the core managed assemblies; otherwise, using this parameter may result in an exception being thrown when attempting to open the connection. N Enlist Y - Automatically enlist in distributed transactions
N - No automatic enlistment
N Y
Pooling True - Use connection pooling.
False - Do not use connection pooling.

WARNING: When using the default connection pool implementation, setting this property to True should be avoided by applications that make use of COM (either directly or indirectly) due to possible deadlocks that can occur during the finalization of some COM objects.
N False
FailIfMissing True - Don't create the database if it does not exist, throw an error instead
False - Automatically create the database if it does not exist
N False
Max Page Count {size in pages} - Limits the maximum number of pages (limits the size) of the database N 0 Legacy Format True - Use the more compatible legacy 3.x database format
False - Use the newer 3.3x database format which compresses numbers more effectively
N False
Default Timeout {time in seconds}
The default command timeout
N 30
Journal Mode Delete - Delete the journal file after a commit
Persist - Zero out and leave the journal file on disk after a commit
Off - Disable the rollback journal entirely
N Delete
Read Only True - Open the database for read only access
False - Open the database for normal read/write access
N False
Max Pool Size The maximum number of connections for the given connection string that can be in the connection pool N 100 Default IsolationLevel The default transaciton isolation level N Serializable Foreign Keys Enable foreign key constraints N False Flags Extra behavioral flags for the connection. See the enumeration for possible values. N Default SetDefaults True - Apply the default connection settings to the opened database.
False - Skip applying the default connection settings to the opened database.
N True
ToFullPath True - Attempt to expand the data source file name to a fully qualified path before opening.
False - Skip attempting to expand the data source file name to a fully qualified path before opening.
N True
The default "stub" (i.e. placeholder) base schema name to use when returning column schema information. Used as the initial value of the BaseSchemaName property. This should start with "sqlite_*" because those names are reserved for use by SQLite (i.e. they cannot be confused with the names of user objects). The managed assembly containing this type. Object used to synchronize access to the static instance data for this class. State of the current connection The connection string Nesting level of the transactions open on the connection If set, then the connection is currently being disposed. The default isolation level for new transactions Whether or not the connection is enlisted in a distrubuted transaction The per-connection mappings between type names and values. These mappings override the corresponding global mappings. The base SQLite object to interop with The database filename minus path and extension Temporary password storage, emptied after the database has been opened The "stub" (i.e. placeholder) base schema name to use when returning column schema information. The extra behavioral flags for this connection, if any. See the enumeration for a list of possible values. Default command timeout Non-zero if the built-in (i.e. framework provided) connection string parser should be used when opening the connection. Constructs a new SQLiteConnection object Default constructor Initializes the connection with the specified connection string. The connection string to use. Initializes the connection with a pre-existing native connection handle. This constructor overload is intended to be used only by the private method. The native connection handle to use. The file name corresponding to the native connection handle. Non-zero if this instance owns the native connection handle and should dispose of it when it is no longer needed. Initializes the connection with the specified connection string. The connection string to use. Non-zero to parse the connection string using the built-in (i.e. framework provided) parser when opening the connection. Clones the settings and connection string from an existing connection. If the existing connection is already open, this function will open its own connection, enumerate any attached databases of the original connection, and automatically attach to them. The connection to copy the settings from. Raises the event. The connection associated with this event. If this parameter is not null and the specified connection cannot raise events, then the registered event handlers will not be invoked. A that contains the event data. Creates and returns a new managed database connection handle. This method is intended to be used by implementations of the interface only. In theory, it could be used by other classes; however, that usage is not supported. This must be a native database connection handle returned by the SQLite core library and it must remain valid and open during the entire duration of the calling method. The new managed database connection handle or null if it cannot be created. Backs up the database, using the specified database connection as the destination. The destination database connection. The destination database name. The source database name. The number of pages to copy or negative to copy all remaining pages. The method to invoke between each step of the backup process. This parameter may be null (i.e. no callbacks will be performed). The number of milliseconds to sleep after encountering a locking error during the backup process. A value less than zero means that no sleep should be performed. Clears the per-connection type mappings. The total number of per-connection type mappings cleared. Returns the per-connection type mappings. The per-connection type mappings -OR- null if they are unavailable. Adds a per-connection type mapping, possibly replacing one or more that already exist. The case-insensitive database type name (e.g. "MYDATE"). The value of this parameter cannot be null. Using an empty string value (or a string value consisting entirely of whitespace) for this parameter is not recommended. The value that should be associated with the specified type name. Non-zero if this mapping should be considered to be the primary one for the specified . A negative value if nothing was done. Zero if no per-connection type mappings were replaced (i.e. it was a pure add operation). More than zero if some per-connection type mappings were replaced. Attempts to bind the specified object instance to this connection. The object instance containing the metadata for the function to be bound. The object instance that implements the function to be bound. Creates a clone of the connection. All attached databases and user-defined functions are cloned. If the existing connection is open, the cloned connection will also be opened. Creates a database file. This just creates a zero-byte file which SQLite will turn into a database when the file is opened properly. The file to create Raises the state change event when the state of the connection changes The new connection state. If this is different from the previous state, the event is raised. The event data created for the raised event, if it was actually raised. Determines and returns the fallback default isolation level when one cannot be obtained from an existing connection instance. The fallback default isolation level for this connection instance -OR- if it cannot be determined. Determines and returns the default isolation level for this connection instance. The default isolation level for this connection instance -OR- if it cannot be determined. OBSOLETE. Creates a new SQLiteTransaction if one isn't already active on the connection. This parameter is ignored. When TRUE, SQLite defers obtaining a write lock until a write operation is requested. When FALSE, a writelock is obtained immediately. The default is TRUE, but in a multi-threaded multi-writer environment, one may instead choose to lock the database immediately to avoid any possible writer deadlock. Returns a SQLiteTransaction object. OBSOLETE. Creates a new SQLiteTransaction if one isn't already active on the connection. When TRUE, SQLite defers obtaining a write lock until a write operation is requested. When FALSE, a writelock is obtained immediately. The default is false, but in a multi-threaded multi-writer environment, one may instead choose to lock the database immediately to avoid any possible writer deadlock. Returns a SQLiteTransaction object. Creates a new if one isn't already active on the connection. Supported isolation levels are Serializable, ReadCommitted and Unspecified. Unspecified will use the default isolation level specified in the connection string. If no isolation level is specified in the connection string, Serializable is used. Serializable transactions are the default. In this mode, the engine gets an immediate lock on the database, and no other threads may begin a transaction. Other threads may read from the database, but not write. With a ReadCommitted isolation level, locks are deferred and elevated as needed. It is possible for multiple threads to start a transaction in ReadCommitted mode, but if a thread attempts to commit a transaction while another thread has a ReadCommitted lock, it may timeout or cause a deadlock on both threads until both threads' CommandTimeout's are reached. Returns a SQLiteTransaction object. Creates a new if one isn't already active on the connection. Returns the new transaction object. Forwards to the local function Supported isolation levels are Unspecified, Serializable, and ReadCommitted This method is not implemented; however, the event will still be raised. When the database connection is closed, all commands linked to this connection are automatically reset. Clears the connection pool associated with the connection. Any other active connections using the same database file will be discarded instead of returned to the pool when they are closed. Clears all connection pools. Any active connections will be discarded instead of sent to the pool when they are closed. Create a new and associate it with this connection. Returns a new command object already assigned to this connection. Forwards to the local function. Parses the connection string into component parts using the custom connection string parser. The connection string to parse An array of key-value pairs representing each parameter of the connection string Parses a connection string using the built-in (i.e. framework provided) connection string parser class and returns the key/value pairs. An exception may be thrown if the connection string is invalid or cannot be parsed. When compiled for the .NET Compact Framework, the custom connection string parser is always used instead because the framework provided one is unavailable there. The connection string to parse. Non-zero to throw an exception if any connection string values are not of the type. The list of key/value pairs. Manual distributed transaction enlistment support The distributed transaction to enlist in Looks for a key in the array of key/values of the parameter string. If not found, return the specified default value The list to look in The key to find The default value to return if the key is not found The value corresponding to the specified key, or the default value if not found. Attempts to convert the string value to an enumerated value of the specified type. The enumerated type to convert the string value to. The string value to be converted. Non-zero to make the conversion case-insensitive. The enumerated value upon success or null upon error. Attempts to convert an input string into a byte value. The string value to be converted. The number styles to use for the conversion. Upon sucess, this will contain the parsed byte value. Upon failure, the value of this parameter is undefined. Non-zero upon success; zero on failure. Enables or disabled extension loading. True to enable loading of extensions, false to disable. Loads a SQLite extension library from the named dynamic link library file. The name of the dynamic link library file containing the extension. Loads a SQLite extension library from the named dynamic link library file. The name of the dynamic link library file containing the extension. The name of the exported function used to initialize the extension. If null, the default "sqlite3_extension_init" will be used. Creates a disposable module containing the implementation of a virtual table. The module object to be used when creating the disposable module. Parses a string containing a sequence of zero or more hexadecimal encoded byte values and returns the resulting byte array. The "0x" prefix is not allowed on the input string. The input string containing zero or more hexadecimal encoded byte values. A byte array containing the parsed byte values or null if an error was encountered. Creates and returns a string containing the hexadecimal encoded byte values from the input array. The input array of bytes. The resulting string or null upon failure. Parses a string containing a sequence of zero or more hexadecimal encoded byte values and returns the resulting byte array. The "0x" prefix is not allowed on the input string. The input string containing zero or more hexadecimal encoded byte values. Upon failure, this will contain an appropriate error message. A byte array containing the parsed byte values or null if an error was encountered. This method figures out what the default connection pool setting should be based on the connection flags. When present, the "Pooling" connection string property value always overrides the value returned by this method. Non-zero if the connection pool should be enabled by default; otherwise, zero. Opens the connection using the parameters found in the . Opens the connection using the parameters found in the and then returns it. The current connection object. This method causes any pending database operation to abort and return at its earliest opportunity. This routine is typically called in response to a user action such as pressing "Cancel" or Ctrl-C where the user wants a long query operation to halt immediately. It is safe to call this routine from any thread. However, it is not safe to call this routine with a database connection that is closed or might close before this method returns. Returns various global memory statistics for the SQLite core library via a dictionary of key/value pairs. Currently, only the "MemoryUsed" and "MemoryHighwater" keys are returned and they have values that correspond to the values that could be obtained via the and connection properties. This dictionary will be populated with the global memory statistics. It will be created if necessary. Attempts to free as much heap memory as possible for this database connection. Attempts to free N bytes of heap memory by deallocating non-essential memory allocations held by the database library. Memory used to cache database pages to improve performance is an example of non-essential memory. This is a no-op returning zero if the SQLite core library was not compiled with the compile-time option SQLITE_ENABLE_MEMORY_MANAGEMENT. Optionally, attempts to reset and/or compact the Win32 native heap, if applicable. The requested number of bytes to free. Non-zero to attempt a heap reset. Non-zero to attempt heap compaction. The number of bytes actually freed. This value may be zero. This value will be non-zero if the heap reset was successful. The size of the largest committed free block in the heap, in bytes. This value will be zero unless heap compaction is enabled. A standard SQLite return code (i.e. zero for success and non-zero for failure). Sets the status of the memory usage tracking subsystem in the SQLite core library. By default, this is enabled. If this is disabled, memory usage tracking will not be performed. This is not really a per-connection value, it is global to the process. Non-zero to enable memory usage tracking, zero otherwise. A standard SQLite return code (i.e. zero for success and non-zero for failure). Passes a shutdown request to the SQLite core library. Does not throw an exception if the shutdown request fails. A standard SQLite return code (i.e. zero for success and non-zero for failure). Passes a shutdown request to the SQLite core library. Throws an exception if the shutdown request fails and the no-throw parameter is non-zero. Non-zero to reset the database and temporary directories to their default values, which should be null for both. When non-zero, throw an exception if the shutdown request fails. Enables or disabled extended result codes returned by SQLite Enables or disabled extended result codes returned by SQLite Enables or disabled extended result codes returned by SQLite Add a log message via the SQLite sqlite3_log interface. Add a log message via the SQLite sqlite3_log interface. Change the password (or assign a password) to an open database. No readers or writers may be active for this process. The database must already be open and if it already was password protected, the existing password must already have been supplied. The new password to assign to the database Change the password (or assign a password) to an open database. No readers or writers may be active for this process. The database must already be open and if it already was password protected, the existing password must already have been supplied. The new password to assign to the database Sets the password for a password-protected database. A password-protected database is unusable for any operation until the password has been set. The password for the database Sets the password for a password-protected database. A password-protected database is unusable for any operation until the password has been set. The password for the database Queries or modifies the number of retries or the retry interval (in milliseconds) for certain I/O operations that may fail due to anti-virus software. The number of times to retry the I/O operation. A negative value will cause the current count to be queried and replace that negative value. The number of milliseconds to wait before retrying the I/O operation. This number is multiplied by the number of retry attempts so far to come up with the final number of milliseconds to wait. A negative value will cause the current interval to be queried and replace that negative value. Zero for success, non-zero for error. Removes one set of surrounding single -OR- double quotes from the string value and returns the resulting string value. If the string is null, empty, or contains quotes that are not balanced, nothing is done and the original string value will be returned. The string value to process. The string value, modified to remove one set of surrounding single -OR- double quotes, if applicable. Expand the filename of the data source, resolving the |DataDirectory| macro as appropriate. The database filename to expand Non-zero if the returned file name should be converted to a full path (except when using the .NET Compact Framework). The expanded path and filename of the filename The following commands are used to extract schema information out of the database. Valid schema types are: MetaDataCollections DataSourceInformation Catalogs Columns ForeignKeys Indexes IndexColumns Tables Views ViewColumns Returns the MetaDataCollections schema A DataTable of the MetaDataCollections schema Returns schema information of the specified collection The schema collection to retrieve A DataTable of the specified collection Retrieves schema information using the specified constraint(s) for the specified collection The collection to retrieve The restrictions to impose A DataTable of the specified collection Builds a MetaDataCollections schema datatable DataTable Builds a DataSourceInformation datatable DataTable Build a Columns schema The catalog (attached database) to query, can be null The table to retrieve schema information for, must not be null The column to retrieve schema information for, can be null DataTable Returns index information for the given database and catalog The catalog (attached database) to query, can be null The name of the index to retrieve information for, can be null The table to retrieve index information for, can be null DataTable Retrieves table schema information for the database and catalog The catalog (attached database) to retrieve tables on The table to retrieve, can be null The table type, can be null DataTable Retrieves view schema information for the database The catalog (attached database) to retrieve views on The view name, can be null DataTable Retrieves catalog (attached databases) schema information for the database The catalog to retrieve, can be null DataTable Returns the base column information for indexes in a database The catalog to retrieve indexes for (can be null) The table to restrict index information by (can be null) The index to restrict index information by (can be null) The source column to restrict index information by (can be null) A DataTable containing the results Returns detailed column information for a specified view The catalog to retrieve columns for (can be null) The view to restrict column information by (can be null) The source column to restrict column information by (can be null) A DataTable containing the results Retrieves foreign key information from the specified set of filters An optional catalog to restrict results on An optional table to restrict results on An optional foreign key name to restrict results on A DataTable with the results of the query Static variable to store the connection event handlers to call. This event is raised whenever the database is opened or closed. This event is raised when events related to the lifecycle of a SQLiteConnection object occur. This property is used to obtain or set the custom connection pool implementation to use, if any. Setting this property to null will cause the default connection pool implementation to be used. Returns the number of pool entries for the file name associated with this connection. The connection string containing the parameters for the connection Parameter Values Required Default Data Source This may be a file name, the string ":memory:", or any supported URI (starting with SQLite 3.7.7). Starting with release 1.0.86.0, in order to use more than one consecutive backslash (e.g. for a UNC path), each of the adjoining backslash characters must be doubled (e.g. "\\Network\Share\test.db" would become "\\\\Network\Share\test.db"). Y Version 3 N 3 UseUTF16Encoding True
False
N False
DateTimeFormat Ticks - Use the value of DateTime.Ticks.
ISO8601 - Use the ISO-8601 format. Uses the "yyyy-MM-dd HH:mm:ss.FFFFFFFK" format for UTC DateTime values and "yyyy-MM-dd HH:mm:ss.FFFFFFF" format for local DateTime values).
JulianDay - The interval of time in days and fractions of a day since January 1, 4713 BC.
UnixEpoch - The whole number of seconds since the Unix epoch (January 1, 1970).
InvariantCulture - Any culture-independent string value that the .NET Framework can interpret as a valid DateTime.
CurrentCulture - Any string value that the .NET Framework can interpret as a valid DateTime using the current culture.
N ISO8601
DateTimeKind Unspecified - Not specified as either UTC or local time.
Utc - The time represented is UTC.
Local - The time represented is local time.
N Unspecified
DateTimeFormatString The exact DateTime format string to use for all formatting and parsing of all DateTime values for this connection. N null BaseSchemaName Some base data classes in the framework (e.g. those that build SQL queries dynamically) assume that an ADO.NET provider cannot support an alternate catalog (i.e. database) without supporting alternate schemas as well; however, SQLite does not fit into this model. Therefore, this value is used as a placeholder and removed prior to preparing any SQL statements that may contain it. N sqlite_default_schema BinaryGUID True - Store GUID columns in binary form
False - Store GUID columns as text
N True
Cache Size {size in bytes} N 2000 Synchronous Normal - Normal file flushing behavior
Full - Full flushing after all writes
Off - Underlying OS flushes I/O's
N Full
Page Size {size in bytes} N 1024 Password {password} - Using this parameter requires that the CryptoAPI based codec be enabled at compile-time for both the native interop assembly and the core managed assemblies; otherwise, using this parameter may result in an exception being thrown when attempting to open the connection. N HexPassword {hexPassword} - Must contain a sequence of zero or more hexadecimal encoded byte values without a leading "0x" prefix. Using this parameter requires that the CryptoAPI based codec be enabled at compile-time for both the native interop assembly and the core managed assemblies; otherwise, using this parameter may result in an exception being thrown when attempting to open the connection. N Enlist Y - Automatically enlist in distributed transactions
N - No automatic enlistment
N Y
Pooling True - Use connection pooling.
False - Do not use connection pooling.

WARNING: When using the default connection pool implementation, setting this property to True should be avoided by applications that make use of COM (either directly or indirectly) due to possible deadlocks that can occur during the finalization of some COM objects.
N False
FailIfMissing True - Don't create the database if it does not exist, throw an error instead
False - Automatically create the database if it does not exist
N False
Max Page Count {size in pages} - Limits the maximum number of pages (limits the size) of the database N 0 Legacy Format True - Use the more compatible legacy 3.x database format
False - Use the newer 3.3x database format which compresses numbers more effectively
N False
Default Timeout {time in seconds}
The default command timeout
N 30
Journal Mode Delete - Delete the journal file after a commit
Persist - Zero out and leave the journal file on disk after a commit
Off - Disable the rollback journal entirely
N Delete
Read Only True - Open the database for read only access
False - Open the database for normal read/write access
N False
Max Pool Size The maximum number of connections for the given connection string that can be in the connection pool N 100 Default IsolationLevel The default transaciton isolation level N Serializable Foreign Keys Enable foreign key constraints N False Flags Extra behavioral flags for the connection. See the enumeration for possible values. N Default SetDefaults True - Apply the default connection settings to the opened database.
False - Skip applying the default connection settings to the opened database.
N True
ToFullPath True - Attempt to expand the data source file name to a fully qualified path before opening.
False - Skip attempting to expand the data source file name to a fully qualified path before opening.
N True
Returns the data source file name without extension or path. Returns the string "main". Gets/sets the default command timeout for newly-created commands. This is especially useful for commands used internally such as inside a SQLiteTransaction, where setting the timeout is not possible. This can also be set in the ConnectionString with "Default Timeout" Non-zero if the built-in (i.e. framework provided) connection string parser should be used when opening the connection. Gets/sets the extra behavioral flags for this connection. See the enumeration for a list of possible values. Returns non-zero if the underlying native connection handle is owned by this instance. Returns the version of the underlying SQLite database engine Returns the rowid of the most recent successful INSERT into the database from this connection. Returns the number of rows changed by the last INSERT, UPDATE, or DELETE statement executed on this connection. Returns non-zero if the given database connection is in autocommit mode. Autocommit mode is on by default. Autocommit mode is disabled by a BEGIN statement. Autocommit mode is re-enabled by a COMMIT or ROLLBACK. Returns the amount of memory (in bytes) currently in use by the SQLite core library. Returns the maximum amount of memory (in bytes) used by the SQLite core library since the high-water mark was last reset. Returns a string containing the define constants (i.e. compile-time options) used to compile the core managed assembly, delimited with spaces. Returns the version of the underlying SQLite core library. This method returns the string whose value is the same as the SQLITE_SOURCE_ID C preprocessor macro used when compiling the SQLite core library. Returns a string containing the compile-time options used to compile the SQLite core native library, delimited with spaces. This method returns the version of the interop SQLite assembly used. If the SQLite interop assembly is not in use or the necessary information cannot be obtained for any reason, a null value may be returned. This method returns the string whose value contains the unique identifier for the source checkout used to build the interop assembly. If the SQLite interop assembly is not in use or the necessary information cannot be obtained for any reason, a null value may be returned. Returns a string containing the compile-time options used to compile the SQLite interop assembly, delimited with spaces. This method returns the version of the managed components used to interact with the SQLite core library. If the necessary information cannot be obtained for any reason, a null value may be returned. This method returns the string whose value contains the unique identifier for the source checkout used to build the managed components currently executing. If the necessary information cannot be obtained for any reason, a null value may be returned. Returns the state of the connection. This event is raised whenever SQLite encounters an action covered by the authorizer during query preparation. Changing the value of the property will determine if the specific action will be allowed, ignored, or denied. For the entire duration of the event, the associated connection and statement objects must not be modified, either directly or indirectly, by the called code. This event is raised whenever SQLite makes an update/delete/insert into the database on this connection. It only applies to the given connection. This event is raised whenever SQLite is committing a transaction. Return non-zero to trigger a rollback. This event is raised whenever SQLite statement first begins executing on this connection. It only applies to the given connection. This event is raised whenever SQLite is rolling back a transaction. Returns the instance. The I/O file cache flushing behavior for the connection Normal file flushing at critical sections of the code Full file flushing after every write operation Use the default operating system's file flushing, SQLite does not explicitly flush the file buffers after writing Raised when authorization is required to perform an action contained within a SQL query. The connection performing the action. A that contains the event data. Raised when a transaction is about to be committed. To roll back a transaction, set the rollbackTrans boolean value to true. The connection committing the transaction Event arguments on the transaction Raised when data is inserted, updated and deleted on a given connection The connection committing the transaction The event parameters which triggered the event Raised when a statement first begins executing on a given connection The connection executing the statement Event arguments of the trace Raised between each backup step. The source database connection. The source database name. The destination database connection. The destination database name. The number of pages copied with each step. The number of pages remaining to be copied. The total number of pages in the source database. Set to true if the operation needs to be retried due to database locking issues; otherwise, set to false. True to continue with the backup process or false to halt the backup process, rolling back any changes that have been made so far. The data associated with a call into the authorizer. The user-defined native data associated with this event. Currently, this will always contain the value of . The action code responsible for the current call into the authorizer. The first string argument for the current call into the authorizer. The exact value will vary based on the action code, see the enumeration for possible values. The second string argument for the current call into the authorizer. The exact value will vary based on the action code, see the enumeration for possible values. The database name for the current call into the authorizer, if applicable. The name of the inner-most trigger or view that is responsible for the access attempt or a null value if this access attempt is directly from top-level SQL code. The return code for the current call into the authorizer. Constructs an instance of this class with default property values. Constructs an instance of this class with specific property values. The user-defined native data associated with this event. The authorizer action code. The first authorizer argument. The second authorizer argument. The database name, if applicable. The name of the inner-most trigger or view that is responsible for the access attempt or a null value if this access attempt is directly from top-level SQL code. The authorizer return code. Whenever an update event is triggered on a connection, this enum will indicate exactly what type of operation is being performed. A row is being deleted from the given database and table A row is being inserted into the table. A row is being updated in the table. Passed during an Update callback, these event arguments detail the type of update operation being performed on the given connection. The name of the database being updated (usually "main" but can be any attached or temporary database) The name of the table being updated The type of update being performed (insert/update/delete) The RowId affected by this update. Event arguments raised when a transaction is being committed Set to true to abort the transaction and trigger a rollback Passed during an Trace callback, these event arguments contain the UTF-8 rendering of the SQL statement text SQL statement text as the statement first begins executing This interface represents a custom connection pool implementation usable by System.Data.SQLite. Counts the number of pool entries matching the specified file name. The file name to match or null to match all files. The pool entry counts for each matching file. The total number of connections successfully opened from any pool. The total number of connections successfully closed from any pool. The total number of pool entries for all matching files. Disposes of all pooled connections associated with the specified database file name. The database file name. Disposes of all pooled connections. Adds a connection to the pool of those associated with the specified database file name. The database file name. The database connection handle. The connection pool version at the point the database connection handle was received from the connection pool. This is also the connection pool version that the database connection handle was created under. Removes a connection from the pool of those associated with the specified database file name with the intent of using it to interact with the database. The database file name. The new maximum size of the connection pool for the specified database file name. The connection pool version associated with the returned database connection handle, if any. The database connection handle associated with the specified database file name or null if it cannot be obtained. This default method implementations in this class should not be used by applications that make use of COM (either directly or indirectly) due to possible deadlocks that can occur during finalization of some COM objects. This field is used to synchronize access to the private static data in this class. When this field is non-null, it will be used to provide the implementation of all the connection pool methods; otherwise, the default method implementations will be used. The dictionary of connection pools, based on the normalized file name of the SQLite database. The default version number new pools will get. The number of connections successfully opened from any pool. This value is incremented by the Remove method. The number of connections successfully closed from any pool. This value is incremented by the Add method. Counts the number of pool entries matching the specified file name. The file name to match or null to match all files. The pool entry counts for each matching file. The total number of connections successfully opened from any pool. The total number of connections successfully closed from any pool. The total number of pool entries for all matching files. Disposes of all pooled connections associated with the specified database file name. The database file name. Disposes of all pooled connections. Adds a connection to the pool of those associated with the specified database file name. The database file name. The database connection handle. The connection pool version at the point the database connection handle was received from the connection pool. This is also the connection pool version that the database connection handle was created under. Removes a connection from the pool of those associated with the specified database file name with the intent of using it to interact with the database. The database file name. The new maximum size of the connection pool for the specified database file name. The connection pool version associated with the returned database connection handle, if any. The database connection handle associated with the specified database file name or null if it cannot be obtained. This method is used to obtain a reference to the custom connection pool implementation currently in use, if any. The custom connection pool implementation or null if the default connection pool implementation should be used. This method is used to set the reference to the custom connection pool implementation to use, if any. The custom connection pool implementation to use or null if the default connection pool implementation should be used. We do not have to thread-lock anything in this function, because it is only called by other functions above which already take the lock. The pool queue to resize. If a function intends to add to the pool, this is true, which forces the resize to take one more than it needs from the pool. Keeps track of connections made on a specified file. The PoolVersion dictates whether old objects get returned to the pool or discarded when no longer in use. The queue of weak references to the actual database connection handles. This pool version associated with the database connection handles in this pool queue. The maximum size of this pool queue. Constructs a connection pool queue using the specified version and maximum size. Normally, all the database connection handles in this pool are associated with a single database file name. The initial pool version for this connection pool queue. The initial maximum size for this connection pool queue. SQLite implementation of DbConnectionStringBuilder. Properties of this class Constructs a new instance of the class Default constructor Constructs a new instance of the class using the specified connection string. The connection string to parse Private initializer, which assigns the connection string and resets the builder The connection string to assign Helper function for retrieving values from the connectionstring The keyword to retrieve settings for The resulting parameter value Returns true if the value was found and returned Fallback method for MONO, which doesn't implement DbConnectionStringBuilder.GetProperties() The hashtable to fill with property descriptors Gets/Sets the default version of the SQLite engine to instantiate. Currently the only valid value is 3, indicating version 3 of the sqlite library. Gets/Sets the synchronization mode (file flushing) of the connection string. Default is "Normal". Gets/Sets the encoding for the connection string. The default is "False" which indicates UTF-8 encoding. Gets/Sets whether or not to use connection pooling. The default is "False" Gets/Sets whethor not to store GUID's in binary format. The default is True which saves space in the database. Gets/Sets the filename to open on the connection string. An alternate to the data source property An alternate to the data source property that uses the SQLite URI syntax. Gets/sets the default command timeout for newly-created commands. This is especially useful for commands used internally such as inside a SQLiteTransaction, where setting the timeout is not possible. Determines whether or not the connection will automatically participate in the current distributed transaction (if one exists) If set to true, will throw an exception if the database specified in the connection string does not exist. If false, the database will be created automatically. If enabled, uses the legacy 3.xx format for maximum compatibility, but results in larger database sizes. When enabled, the database will be opened for read-only access and writing will be disabled. Gets/sets the database encryption password Gets/sets the database encryption hexadecimal password Gets/Sets the page size for the connection. Gets/Sets the maximum number of pages the database may hold Gets/Sets the cache size for the connection. Gets/Sets the DateTime format for the connection. Gets/Sets the DateTime kind for the connection. Gets/sets the DateTime format string used for formatting and parsing purposes. Gets/Sets the placeholder base schema name used for .NET Framework compatibility purposes. Determines how SQLite handles the transaction journal file. Sets the default isolation level for transactions on the connection. If enabled, use foreign key constraints Gets/Sets the extra behavioral flags. If enabled, apply the default connection settings to opened databases. If enabled, attempt to resolve the provided data source file name to a full path before opening. SQLite has very limited types, and is inherently text-based. The first 5 types below represent the sum of all types SQLite understands. The DateTime extension to the spec is for internal use only. Not used All integers in SQLite default to Int64 All floating point numbers in SQLite default to double The default data type of SQLite is text Typically blob types are only seen when returned from a function Null types can be returned from functions Used internally by this provider Used internally by this provider These are the event types associated with the delegate (and its corresponding event) and the class. Not used. Not used. The connection is being opened. The connection string has been parsed. The connection was opened. The method was called on the connection. A transaction was created using the connection. The connection was enlisted into a transaction. A command was created using the connection. A data reader was created using the connection. An instance of a derived class has been created to wrap a native resource. The connection is being closed. The connection was closed. This implementation of SQLite for ADO.NET can process date/time fields in databases in one of six formats. ISO8601 format is more compatible, readable, fully-processable, but less accurate as it does not provide time down to fractions of a second. JulianDay is the numeric format the SQLite uses internally and is arguably the most compatible with 3rd party tools. It is not readable as text without post-processing. Ticks less compatible with 3rd party tools that query the database, and renders the DateTime field unreadable as text without post-processing. UnixEpoch is more compatible with Unix systems. InvariantCulture allows the configured format for the invariant culture format to be used and is human readable. CurrentCulture allows the configured format for the current culture to be used and is also human readable. The preferred order of choosing a DateTime format is JulianDay, ISO8601, and then Ticks. Ticks is mainly present for legacy code support. Use the value of DateTime.Ticks. This value is not recommended and is not well supported with LINQ. Use the ISO-8601 format. Uses the "yyyy-MM-dd HH:mm:ss.FFFFFFFK" format for UTC DateTime values and "yyyy-MM-dd HH:mm:ss.FFFFFFF" format for local DateTime values). The interval of time in days and fractions of a day since January 1, 4713 BC. The whole number of seconds since the Unix epoch (January 1, 1970). Any culture-independent string value that the .NET Framework can interpret as a valid DateTime. Any string value that the .NET Framework can interpret as a valid DateTime using the current culture. The default format for this provider. This enum determines how SQLite treats its journal file. By default SQLite will create and delete the journal file when needed during a transaction. However, for some computers running certain filesystem monitoring tools, the rapid creation and deletion of the journal file can cause those programs to fail, or to interfere with SQLite. If a program or virus scanner is interfering with SQLite's journal file, you may receive errors like "unable to open database file" when starting a transaction. If this is happening, you may want to change the default journal mode to Persist. The default mode, this causes SQLite to use the existing journaling mode for the database. SQLite will create and destroy the journal file as-needed. When this is set, SQLite will keep the journal file even after a transaction has completed. It's contents will be erased, and the journal re-used as often as needed. If it is deleted, it will be recreated the next time it is needed. This option disables the rollback journal entirely. Interrupted transactions or a program crash can cause database corruption in this mode! SQLite will truncate the journal file to zero-length instead of deleting it. SQLite will store the journal in volatile RAM. This saves disk I/O but at the expense of database safety and integrity. If the application using SQLite crashes in the middle of a transaction when the MEMORY journaling mode is set, then the database file will very likely go corrupt. SQLite uses a write-ahead log instead of a rollback journal to implement transactions. The WAL journaling mode is persistent; after being set it stays in effect across multiple database connections and after closing and reopening the database. A database in WAL journaling mode can only be accessed by SQLite version 3.7.0 or later. Possible values for the "synchronous" database setting. This setting determines how often the database engine calls the xSync method of the VFS. Use the default "synchronous" database setting. Currently, this should be the same as using the FULL mode. The database engine continues without syncing as soon as it has handed data off to the operating system. If the application running SQLite crashes, the data will be safe, but the database might become corrupted if the operating system crashes or the computer loses power before that data has been written to the disk surface. The database engine will still sync at the most critical moments, but less often than in FULL mode. There is a very small (though non-zero) chance that a power failure at just the wrong time could corrupt the database in NORMAL mode. The database engine will use the xSync method of the VFS to ensure that all content is safely written to the disk surface prior to continuing. This ensures that an operating system crash or power failure will not corrupt the database. FULL synchronous is very safe, but it is also slower. The requested command execution type. This controls which method of the object will be called. Do nothing. No method will be called. The command is not expected to return a result -OR- the result is not needed. The or method will be called. The command is expected to return a scalar result -OR- the result should be limited to a scalar result. The or method will be called. The command is expected to return result. The or method will be called. Use the default command execution type. Using this value is the same as using the value. The action code responsible for the current call into the authorizer. No action is being performed. This value should not be used from external code. No longer used. An index will be created. The action-specific arguments are the index name and the table name. A table will be created. The action-specific arguments are the table name and a null value. A temporary index will be created. The action-specific arguments are the index name and the table name. A temporary table will be created. The action-specific arguments are the table name and a null value. A temporary trigger will be created. The action-specific arguments are the trigger name and the table name. A temporary view will be created. The action-specific arguments are the view name and a null value. A trigger will be created. The action-specific arguments are the trigger name and the table name. A view will be created. The action-specific arguments are the view name and a null value. A DELETE statement will be executed. The action-specific arguments are the table name and a null value. An index will be dropped. The action-specific arguments are the index name and the table name. A table will be dropped. The action-specific arguments are the tables name and a null value. A temporary index will be dropped. The action-specific arguments are the index name and the table name. A temporary table will be dropped. The action-specific arguments are the table name and a null value. A temporary trigger will be dropped. The action-specific arguments are the trigger name and the table name. A temporary view will be dropped. The action-specific arguments are the view name and a null value. A trigger will be dropped. The action-specific arguments are the trigger name and the table name. A view will be dropped. The action-specific arguments are the view name and a null value. An INSERT statement will be executed. The action-specific arguments are the table name and a null value. A PRAGMA statement will be executed. The action-specific arguments are the name of the PRAGMA and the new value or a null value. A table column will be read. The action-specific arguments are the table name and the column name. A SELECT statement will be executed. The action-specific arguments are both null values. A transaction will be started, committed, or rolled back. The action-specific arguments are the name of the operation (BEGIN, COMMIT, or ROLLBACK) and a null value. An UPDATE statement will be executed. The action-specific arguments are the table name and the column name. A database will be attached to the connection. The action-specific arguments are the database file name and a null value. A database will be detached from the connection. The action-specific arguments are the database name and a null value. The schema of a table will be altered. The action-specific arguments are the database name and the table name. An index will be deleted and then recreated. The action-specific arguments are the index name and a null value. A table will be analyzed to gathers statistics about it. The action-specific arguments are the table name and a null value. A virtual table will be created. The action-specific arguments are the table name and the module name. A virtual table will be dropped. The action-specific arguments are the table name and the module name. A SQL function will be called. The action-specific arguments are a null value and the function name. A savepoint will be created, released, or rolled back. The action-specific arguments are the name of the operation (BEGIN, RELEASE, or ROLLBACK) and the savepoint name. A recursive query will be executed. The action-specific arguments are two null values. The return code for the current call into the authorizer. The action will be allowed. The overall action will be disallowed and an error message will be returned from the query preparation method. The specific action will be disallowed; however, the overall action will continue. The exact effects of this return code vary depending on the specific action, please refer to the SQLite core library documentation for futher details. Class used internally to determine the datatype of a column in a resultset The DbType of the column, or DbType.Object if it cannot be determined The affinity of a column, used for expressions or when Type is DbType.Object SQLite implementation of DbDataAdapter. This class is just a shell around the DbDataAdapter. Nothing from DbDataAdapter is overridden here, just a few constructors are defined. Default constructor. Constructs a data adapter using the specified select command. The select command to associate with the adapter. Constructs a data adapter with the supplied select command text and associated with the specified connection. The select command text to associate with the data adapter. The connection to associate with the select command. Constructs a data adapter with the specified select command text, and using the specified database connection string. The select command text to use to construct a select command. A connection string suitable for passing to a new SQLiteConnection, which is associated with the select command. Constructs a data adapter with the specified select command text, and using the specified database connection string. The select command text to use to construct a select command. A connection string suitable for passing to a new SQLiteConnection, which is associated with the select command. Non-zero to parse the connection string using the built-in (i.e. framework provided) parser when opening the connection. Raised by the underlying DbDataAdapter when a row is being updated The event's specifics Raised by DbDataAdapter after a row is updated The event's specifics Row updating event handler Row updated event handler Gets/sets the select command for this DataAdapter Gets/sets the insert command for this DataAdapter Gets/sets the update command for this DataAdapter Gets/sets the delete command for this DataAdapter SQLite implementation of DbDataReader. Underlying command this reader is attached to Index of the current statement in the command being processed Current statement being Read() State of the current statement being processed. -1 = First Step() executed, so the first Read() will be ignored 0 = Actively reading 1 = Finished reading 2 = Non-row-returning statement, no records Number of records affected by the insert/update statements executed on the command Count of fields (columns) in the row-returning statement currently being processed Maps the field (column) names to their corresponding indexes within the results. Datatypes of active fields (columns) in the current statement, used for type-restricting data The behavior of the datareader If set, then dispose of the command object when the reader is finished If set, then raise an exception when the object is accessed after being disposed. An array of rowid's for the active statement if CommandBehavior.KeyInfo is specified Matches the version of the connection. The "stub" (i.e. placeholder) base schema name to use when returning column schema information. Matches the base schema name used by the associated connection. Internal constructor, initializes the datareader and sets up to begin executing statements The SQLiteCommand this data reader is for The expected behavior of the data reader Dispose of all resources used by this datareader. Closes the datareader, potentially closing the connection as well if CommandBehavior.CloseConnection was specified. Throw an error if the datareader is closed Throw an error if a row is not loaded Enumerator support Returns a DbEnumerator object. SQLite is inherently un-typed. All datatypes in SQLite are natively strings. The definition of the columns of a table and the affinity of returned types are all we have to go on to type-restrict data in the reader. This function attempts to verify that the type of data being requested of a column matches the datatype of the column. In the case of columns that are not backed into a table definition, we attempt to match up the affinity of a column (int, double, string or blob) to a set of known types that closely match that affinity. It's not an exact science, but its the best we can do. This function throws an InvalidTypeCast() exception if the requested type doesn't match the column's definition or affinity. The index of the column to type-check The type we want to get out of the column Retrieves the column as a boolean value The index of the column to retrieve bool Retrieves the column as a single byte value The index of the column to retrieve byte Retrieves a column as an array of bytes (blob) The index of the column to retrieve The zero-based index of where to begin reading the data The buffer to write the bytes into The zero-based index of where to begin writing into the array The number of bytes to retrieve The actual number of bytes written into the array To determine the number of bytes in the column, pass a null value for the buffer. The total length will be returned. Returns the column as a single character The index of the column to retrieve char Retrieves a column as an array of chars (blob) The index of the column to retrieve The zero-based index of where to begin reading the data The buffer to write the characters into The zero-based index of where to begin writing into the array The number of bytes to retrieve The actual number of characters written into the array To determine the number of characters in the column, pass a null value for the buffer. The total length will be returned. Retrieves the name of the back-end datatype of the column The index of the column to retrieve string Retrieve the column as a date/time value The index of the column to retrieve DateTime Retrieve the column as a decimal value The index of the column to retrieve decimal Returns the column as a double The index of the column to retrieve double Returns the .NET type of a given column The index of the column to retrieve Type Returns a column as a float value The index of the column to retrieve float Returns the column as a Guid The index of the column to retrieve Guid Returns the column as a short The index of the column to retrieve Int16 Retrieves the column as an int The index of the column to retrieve Int32 Retrieves the column as a long The index of the column to retrieve Int64 Retrieves the name of the column The index of the column to retrieve string Retrieves the i of a column, given its name The name of the column to retrieve The int i of the column Schema information in SQLite is difficult to map into .NET conventions, so a lot of work must be done to gather the necessary information so it can be represented in an ADO.NET manner. Returns a DataTable containing the schema information for the active SELECT statement being processed. Retrieves the column as a string The index of the column to retrieve string Retrieves the column as an object corresponding to the underlying datatype of the column The index of the column to retrieve object Retreives the values of multiple columns, up to the size of the supplied array The array to fill with values from the columns in the current resultset The number of columns retrieved Returns a collection containing all the column names and values for the current row of data in the current resultset, if any. If there is no current row or no current resultset, an exception may be thrown. The collection containing the column name and value information for the current row of data in the current resultset or null if this information cannot be obtained. Returns True if the specified column is null The index of the column to retrieve True or False Moves to the next resultset in multiple row-returning SQL command. True if the command was successful and a new resultset is available, False otherwise. This method attempts to query the database connection associated with the data reader in use. If the underlying command or connection is unavailable, a null value will be returned. The connection object -OR- null if it is unavailable. This method attempts to query the flags associated with the database connection in use. If the database connection is disposed, the default flags will be returned. The data reader containing the databse connection to query the flags from. The connection flags value. Retrieves the SQLiteType for a given column, and caches it to avoid repetetive interop calls. The index of the column to retrieve A SQLiteType structure Reads the next row from the resultset True if a new row was successfully loaded and is ready for processing Not implemented. Returns 0 Returns the number of columns in the current resultset Returns the number of visible fields in the current resultset Returns True if the resultset has rows that can be fetched Returns True if the data reader is closed Retrieve the count of records affected by an update/insert command. Only valid once the data reader is closed! Indexer to retrieve data from a column given its name The name of the column to retrieve data for The value contained in the column Indexer to retrieve data from a column given its i The index of the column to retrieve The value contained in the column SQLite exception class. Private constructor for use with serialization. Holds the serialized object data about the exception being thrown. Contains contextual information about the source or destination. Public constructor for generating a SQLite exception given the error code and message. The SQLite return code to report. Message text to go along with the return code message text. Public constructor that uses the base class constructor for the error message. Error message text. Public constructor that uses the default base class constructor. Public constructor that uses the base class constructor for the error message and inner exception. Error message text. The original (inner) exception. Adds extra information to the serialized object data specific to this class type. This is only used for serialization. Holds the serialized object data about the exception being thrown. Contains contextual information about the source or destination. Returns the error message for the specified SQLite return code. The SQLite return code. The error message or null if it cannot be found. Returns the composite error message based on the SQLite return code and the optional detailed error message. The SQLite return code. Optional detailed error message. Error message text for the return code. Gets the associated SQLite result code for this exception as a . This property returns the same underlying value as the property. Gets the associated SQLite return code for this exception as an . For desktop versions of the .NET Framework, this property overrides the property of the same name within the class. This property returns the same underlying value as the property. SQLite error codes. Actually, this enumeration represents a return code, which may also indicate success in one of several ways (e.g. SQLITE_OK, SQLITE_ROW, and SQLITE_DONE). Therefore, the name of this enumeration is something of a misnomer. The error code is unknown. This error code is only used by the managed wrapper itself. Successful result SQL error or missing database Internal logic error in SQLite Access permission denied Callback routine requested an abort The database file is locked A table in the database is locked A malloc() failed Attempt to write a readonly database Operation terminated by sqlite3_interrupt() Some kind of disk I/O error occurred The database disk image is malformed Unknown opcode in sqlite3_file_control() Insertion failed because database is full Unable to open the database file Database lock protocol error Database is empty The database schema changed String or BLOB exceeds size limit Abort due to constraint violation Data type mismatch Library used incorrectly Uses OS features not supported on host Authorization denied Auxiliary database format error 2nd parameter to sqlite3_bind out of range File opened that is not a database file Notifications from sqlite3_log() Warnings from sqlite3_log() sqlite3_step() has another row ready sqlite3_step() has finished executing Used to mask off extended result codes SQLite implementation of . SQLite implementation of . Constructs a new instance. Static instance member which returns an instanced class. Creates and returns a new object. The new object. Creates and returns a new object. The new object. Creates and returns a new object. The new object. Creates and returns a new object. The new object. Creates and returns a new object. The new object. Creates and returns a new object. The new object. Will provide a object in .NET 3.5. The class or interface type to query for. This event is raised whenever SQLite raises a logging event. Note that this should be set as one of the first things in the application. This event is provided for backward compatibility only. New code should use the class instead. This abstract class is designed to handle user-defined functions easily. An instance of the derived class is made for each connection to the database. Although there is one instance of a class derived from SQLiteFunction per database connection, the derived class has no access to the underlying connection. This is necessary to deter implementers from thinking it would be a good idea to make database calls during processing. It is important to distinguish between a per-connection instance, and a per-SQL statement context. One instance of this class services all SQL statements being stepped through on that connection, and there can be many. One should never store per-statement information in member variables of user-defined function classes. For aggregate functions, always create and store your per-statement data in the contextData object on the 1st step. This data will be automatically freed for you (and Dispose() called if the item supports IDisposable) when the statement completes. The base connection this function is attached to Internal array used to keep track of aggregate function context data The connection flags associated with this object (this should be the same value as the flags associated with the parent connection object). Holds a reference to the callback function for user functions Holds a reference to the callbakc function for stepping in an aggregate function Holds a reference to the callback function for finalizing an aggregate function Holds a reference to the callback function for collation sequences Current context of the current callback. Only valid during a callback This static list contains all the user-defined functions declared using the proper attributes. Internal constructor, initializes the function's internal variables. Constructs an instance of this class using the specified data-type conversion parameters. The DateTime format to be used when converting string values to a DateTime and binding DateTime parameters. The to be used when creating DateTime values. The format string to be used when parsing and formatting DateTime values. Non-zero to create a UTF-16 data-type conversion context; otherwise, a UTF-8 data-type conversion context will be created. Disposes of any active contextData variables that were not automatically cleaned up. Sometimes this can happen if someone closes the connection while a DataReader is open. Placeholder for a user-defined disposal routine True if the object is being disposed explicitly Scalar functions override this method to do their magic. Parameters passed to functions have only an affinity for a certain data type, there is no underlying schema available to force them into a certain type. Therefore the only types you will ever see as parameters are DBNull.Value, Int64, Double, String or byte[] array. The arguments for the command to process You may return most simple types as a return value, null or DBNull.Value to return null, DateTime, or you may return an Exception-derived class if you wish to return an error to SQLite. Do not actually throw the error, just return it! Aggregate functions override this method to do their magic. Typically you'll be updating whatever you've placed in the contextData field and returning as quickly as possible. The arguments for the command to process The 1-based step number. This is incrememted each time the step method is called. A placeholder for implementers to store contextual data pertaining to the current context. Aggregate functions override this method to finish their aggregate processing. If you implemented your aggregate function properly, you've been recording and keeping track of your data in the contextData object provided, and now at this stage you should have all the information you need in there to figure out what to return. NOTE: It is possible to arrive here without receiving a previous call to Step(), in which case the contextData will be null. This can happen when no rows were returned. You can either return null, or 0 or some other custom return value if that is the case. Your own assigned contextData, provided for you so you can return your final results. You may return most simple types as a return value, null or DBNull.Value to return null, DateTime, or you may return an Exception-derived class if you wish to return an error to SQLite. Do not actually throw the error, just return it! User-defined collation sequences override this method to provide a custom string sorting algorithm. The first string to compare The second strnig to compare 1 if param1 is greater than param2, 0 if they are equal, or -1 if param1 is less than param2 Converts an IntPtr array of context arguments to an object array containing the resolved parameters the pointers point to. Parameters passed to functions have only an affinity for a certain data type, there is no underlying schema available to force them into a certain type. Therefore the only types you will ever see as parameters are DBNull.Value, Int64, Double, String or byte[] array. The number of arguments A pointer to the array of arguments An object array of the arguments once they've been converted to .NET values Takes the return value from Invoke() and Final() and figures out how to return it to SQLite's context. The context the return value applies to The parameter to return to SQLite Internal scalar callback function, which wraps the raw context pointer and calls the virtual Invoke() method. WARNING: Must not throw exceptions. A raw context pointer Number of arguments passed in A pointer to the array of arguments Internal collation sequence function, which wraps up the raw string pointers and executes the Compare() virtual function. WARNING: Must not throw exceptions. Not used Length of the string pv1 Pointer to the first string to compare Length of the string pv2 Pointer to the second string to compare Returns -1 if the first string is less than the second. 0 if they are equal, or 1 if the first string is greater than the second. Returns 0 if an exception is caught. Internal collation sequence function, which wraps up the raw string pointers and executes the Compare() virtual function. WARNING: Must not throw exceptions. Not used Length of the string pv1 Pointer to the first string to compare Length of the string pv2 Pointer to the second string to compare Returns -1 if the first string is less than the second. 0 if they are equal, or 1 if the first string is greater than the second. Returns 0 if an exception is caught. The internal aggregate Step function callback, which wraps the raw context pointer and calls the virtual Step() method. WARNING: Must not throw exceptions. This function takes care of doing the lookups and getting the important information put together to call the Step() function. That includes pulling out the user's contextData and updating it after the call is made. We use a sorted list for this so binary searches can be done to find the data. A raw context pointer Number of arguments passed in A pointer to the array of arguments An internal aggregate Final function callback, which wraps the context pointer and calls the virtual Final() method. WARNING: Must not throw exceptions. A raw context pointer Using reflection, enumerate all assemblies in the current appdomain looking for classes that have a SQLiteFunctionAttribute attribute, and registering them accordingly. Manual method of registering a function. The type must still have the SQLiteFunctionAttributes in order to work properly, but this is a workaround for the Compact Framework where enumerating assemblies is not currently supported. The type of the function to register Called by SQLiteBase derived classes, this function binds all user-defined functions to a connection. It is done this way so that all user-defined functions will access the database using the same encoding scheme as the connection (UTF-8 or UTF-16). The wrapper functions that interop with SQLite will create a unique cookie value, which internally is a pointer to all the wrapped callback functions. The interop function uses it to map CDecl callbacks to StdCall callbacks. The base object on which the functions are to bind The flags associated with the parent connection object Returns a logical list of functions which the connection should retain until it is closed. This function binds a user-defined functions to a connection. The object instance associated with the that the function should be bound to. The object instance containing the metadata for the function to be bound. The object instance that implements the function to be bound. The flags associated with the parent connection object. Returns a reference to the underlying connection's SQLiteConvert class, which can be used to convert strings and DateTime's into the current connection's encoding schema. Extends SQLiteFunction and allows an inherited class to obtain the collating sequence associated with a function call. User-defined functions can call the GetCollationSequence() method in this class and use it to compare strings and char arrays. Obtains the collating sequence in effect for the given function. The type of user-defined function to declare Scalar functions are designed to be called and return a result immediately. Examples include ABS(), Upper(), Lower(), etc. Aggregate functions are designed to accumulate data until the end of a call and then return a result gleaned from the accumulated data. Examples include SUM(), COUNT(), AVG(), etc. Collation sequences are used to sort textual data in a custom manner, and appear in an ORDER BY clause. Typically text in an ORDER BY is sorted using a straight case-insensitive comparison function. Custom collating sequences can be used to alter the behavior of text sorting in a user-defined manner. An internal callback delegate declaration. Raw native context pointer for the user function. Total number of arguments to the user function. Raw native pointer to the array of raw native argument pointers. An internal final callback delegate declaration. Raw context pointer for the user function Internal callback delegate for implementing collation sequences Not used Length of the string pv1 Pointer to the first string to compare Length of the string pv2 Pointer to the second string to compare Returns -1 if the first string is less than the second. 0 if they are equal, or 1 if the first string is greater than the second. The type of collating sequence The built-in BINARY collating sequence The built-in NOCASE collating sequence The built-in REVERSE collating sequence A custom user-defined collating sequence The encoding type the collation sequence uses The collation sequence is UTF8 The collation sequence is UTF16 little-endian The collation sequence is UTF16 big-endian A struct describing the collating sequence a function is executing in The name of the collating sequence The type of collating sequence The text encoding of the collation sequence Context of the function that requested the collating sequence Calls the base collating sequence to compare two strings The first string to compare The second string to compare -1 if s1 is less than s2, 0 if s1 is equal to s2, and 1 if s1 is greater than s2 Calls the base collating sequence to compare two character arrays The first array to compare The second array to compare -1 if c1 is less than c2, 0 if c1 is equal to c2, and 1 if c1 is greater than c2 A simple custom attribute to enable us to easily find user-defined functions in the loaded assemblies and initialize them in SQLite as connections are made. Default constructor, initializes the internal variables for the function. Constructs an instance of this class. The name of the function, as seen by the SQLite core library. The number of arguments that the function will accept. The type of function being declared. This will either be Scalar, Aggregate, or Collation. The function's name as it will be used in SQLite command text. The number of arguments this function expects. -1 if the number of arguments is variable. The type of function this implementation will be. The object instance that describes the class containing the implementation for the associated function. This class provides key info for a given SQLite statement. Providing key information for a given statement is non-trivial :( This function does all the nasty work at determining what keys need to be returned for a given statement. Make sure all the subqueries are open and ready and sync'd with the current rowid of the table they're supporting Release any readers on any subqueries Append all the columns we've added to the original query to the schema How many additional columns of keyinfo we're holding Used to support CommandBehavior.KeyInfo A single sub-query for a given table/database. Event data for logging event handlers. The error code. The type of this object value should be or . SQL statement text as the statement first begins executing Extra data associated with this event, if any. Constructs the object. Should be null. The error code. The type of this object value should be or . The error message, if any. The extra data, if any. Raised when a log event occurs. The current connection Event arguments of the trace Manages the SQLite custom logging functionality and the associated callback for the whole process. Object used to synchronize access to the static instance data for this class. Member variable to store the AppDomain.DomainUnload event handler. The default log event handler. The log callback passed to native SQLite engine. This must live as long as the SQLite library has a pointer to it. The base SQLite object to interop with. This will be non-zero if logging is currently enabled. Initializes the SQLite logging facilities. Handles the AppDomain being unloaded. Should be null. The data associated with this event. Log a message to all the registered log event handlers without going through the SQLite library. The message to be logged. Log a message to all the registered log event handlers without going through the SQLite library. The SQLite error code. The message to be logged. Log a message to all the registered log event handlers without going through the SQLite library. The integer error code. The message to be logged. Log a message to all the registered log event handlers without going through the SQLite library. The error code. The type of this object value should be System.Int32 or SQLiteErrorCode. The message to be logged. Creates and initializes the default log event handler. Adds the default log event handler to the list of handlers. Removes the default log event handler from the list of handlers. Internal proxy function that calls any registered application log event handlers. WARNING: This method is used more-or-less directly by native code, do not modify its type signature. The extra data associated with this message, if any. The error code associated with this message. The message string to be logged. Default logger. Currently, uses the Trace class (i.e. sends events to the current trace listeners, if any). Should be null. The data associated with this event. Member variable to store the application log handler to call. This event is raised whenever SQLite raises a logging event. Note that this should be set as one of the first things in the application. If this property is true, logging is enabled; otherwise, logging is disabled. When logging is disabled, no logging events will fire. MetaDataCollections specific to SQLite Returns a list of databases attached to the connection Returns column information for the specified table Returns index information for the optionally-specified table Returns base columns for the given index Returns the tables in the given catalog Returns user-defined views in the given catalog Returns underlying column information on the given view Returns foreign key information for the given catalog Returns the triggers on the database SQLite implementation of DbParameter. The data type of the parameter The version information for mapping the parameter The value of the data in the parameter The source column for the parameter The column name The data size, unused by SQLite Default constructor Constructs a named parameter given the specified parameter name The parameter name Constructs a named parameter given the specified parameter name and initial value The parameter name The initial value of the parameter Constructs a named parameter of the specified type The parameter name The datatype of the parameter Constructs a named parameter of the specified type and source column reference The parameter name The data type The source column Constructs a named parameter of the specified type, source column and row version The parameter name The data type The source column The row version information Constructs an unnamed parameter of the specified data type The datatype of the parameter Constructs an unnamed parameter of the specified data type and sets the initial value The datatype of the parameter The initial value of the parameter Constructs an unnamed parameter of the specified data type and source column The datatype of the parameter The source column Constructs an unnamed parameter of the specified data type, source column and row version The data type The source column The row version information Constructs a named parameter of the specified type and size The parameter name The data type The size of the parameter Constructs a named parameter of the specified type, size and source column The name of the parameter The data type The size of the parameter The source column Constructs a named parameter of the specified type, size, source column and row version The name of the parameter The data type The size of the parameter The source column The row version information Constructs a named parameter of the specified type, size, source column and row version The name of the parameter The data type The size of the parameter Only input parameters are supported in SQLite Ignored Ignored Ignored The source column The row version information The initial value to assign the parameter Constructs a named parameter, yet another flavor The name of the parameter The data type The size of the parameter Only input parameters are supported in SQLite Ignored Ignored The source column The row version information Whether or not this parameter is for comparing NULL's The intial value to assign the parameter Constructs an unnamed parameter of the specified type and size The data type The size of the parameter Constructs an unnamed parameter of the specified type, size, and source column The data type The size of the parameter The source column Constructs an unnamed parameter of the specified type, size, source column and row version The data type The size of the parameter The source column The row version information Resets the DbType of the parameter so it can be inferred from the value Clones a parameter A new, unassociated SQLiteParameter Whether or not the parameter can contain a null value Returns the datatype of the parameter Supports only input parameters Returns the parameter name Returns the size of the parameter Gets/sets the source column Used by DbCommandBuilder to determine the mapping for nullable fields Gets and sets the row version Gets and sets the parameter value. If no datatype was specified, the datatype will assume the type from the value given. SQLite implementation of DbParameterCollection. The underlying command to which this collection belongs The internal array of parameters in this collection Determines whether or not all parameters have been bound to their statement(s) Initializes the collection The command to which the collection belongs Retrieves an enumerator for the collection An enumerator for the underlying array Adds a parameter to the collection The parameter name The data type The size of the value The source column A SQLiteParameter object Adds a parameter to the collection The parameter name The data type The size of the value A SQLiteParameter object Adds a parameter to the collection The parameter name The data type A SQLiteParameter object Adds a parameter to the collection The parameter to add A zero-based index of where the parameter is located in the array Adds a parameter to the collection The parameter to add A zero-based index of where the parameter is located in the array Adds a named/unnamed parameter and its value to the parameter collection. Name of the parameter, or null to indicate an unnamed parameter The initial value of the parameter Returns the SQLiteParameter object created during the call. Adds an array of parameters to the collection The array of parameters to add Adds an array of parameters to the collection The array of parameters to add Clears the array and resets the collection Determines if the named parameter exists in the collection The name of the parameter to check True if the parameter is in the collection Determines if the parameter exists in the collection The SQLiteParameter to check True if the parameter is in the collection Not implemented Retrieve a parameter by name from the collection The name of the parameter to fetch A DbParameter object Retrieves a parameter by its index in the collection The index of the parameter to retrieve A DbParameter object Returns the index of a parameter given its name The name of the parameter to find -1 if not found, otherwise a zero-based index of the parameter Returns the index of a parameter The parameter to find -1 if not found, otherwise a zero-based index of the parameter Inserts a parameter into the array at the specified location The zero-based index to insert the parameter at The parameter to insert Removes a parameter from the collection The parameter to remove Removes a parameter from the collection given its name The name of the parameter to remove Removes a parameter from the collection given its index The zero-based parameter index to remove Re-assign the named parameter to a new parameter object The name of the parameter to replace The new parameter Re-assign a parameter at the specified index The zero-based index of the parameter to replace The new parameter Un-binds all parameters from their statements This function attempts to map all parameters in the collection to all statements in a Command. Since named parameters may span multiple statements, this function makes sure all statements are bound to the same named parameter. Unnamed parameters are bound in sequence. Returns false Returns false Returns false Returns null Returns a count of parameters in the collection Overloaded to specialize the return value of the default indexer Name of the parameter to get/set The specified named SQLite parameter Overloaded to specialize the return value of the default indexer The index of the parameter to get/set The specified SQLite parameter Represents a single SQL statement in SQLite. The underlying SQLite object this statement is bound to The command text of this SQL statement The actual statement pointer An index from which unnamed parameters begin Names of the parameters as SQLite understands them to be Parameters for this statement Command this statement belongs to (if any) The flags associated with the parent connection object. Initializes the statement and attempts to get all information about parameters in the statement The base SQLite object The flags associated with the parent connection object The statement The command text for this statement The previous command in a multi-statement command Disposes and finalizes the statement If the underlying database connection is open, fetches the number of changed rows resulting from the most recent query; otherwise, does nothing. The number of changes when true is returned. Undefined if false is returned. Non-zero if the number of changed rows was fetched. Called by SQLiteParameterCollection, this function determines if the specified parameter name belongs to this statement, and if so, keeps a reference to the parameter so it can be bound later. The parameter name to map The parameter to assign it Bind all parameters, making sure the caller didn't miss any Attempts to convert an arbitrary object to the Boolean data type. Null object values are converted to false. Throws a SQLiteException upon failure. The object value to convert. The format provider to use. The converted boolean value. Perform the bind operation for an individual parameter The index of the parameter to bind The parameter we're binding SQLite implementation of DbTransaction. The connection to which this transaction is bound Constructs the transaction object, binding it to the supplied connection The connection to open a transaction on TRUE to defer the writelock, or FALSE to lock immediately Disposes the transaction. If it is currently active, any changes are rolled back. Commits the current transaction. Rolls back the active transaction. Returns the underlying connection to which this transaction applies. Forwards to the local Connection property Gets the isolation level of the transaction. SQLite only supports Serializable transactions. A strongly-typed resource class, for looking up localized strings, etc. Returns the cached ResourceManager instance used by this class. Overrides the current thread's CurrentUICulture property for all resource lookups using this strongly typed resource class. Looks up a localized string similar to <?xml version="1.0" standalone="yes"?> <DocumentElement> <DataTypes> <TypeName>smallint</TypeName> <ProviderDbType>10</ProviderDbType> <ColumnSize>5</ColumnSize> <DataType>System.Int16</DataType> <CreateFormat>smallint</CreateFormat> <IsAutoIncrementable>false</IsAutoIncrementable> <IsCaseSensitive>false</IsCaseSensitive> <IsFixedLength>true</IsFixedLength> <IsFixedPrecisionScale>true</IsFixedPrecisionScale> <IsLong>false</IsLong> <IsNullable>true</ [rest of string was truncated]";. Looks up a localized string similar to ALL,ALTER,AND,AS,AUTOINCREMENT,BETWEEN,BY,CASE,CHECK,COLLATE,COMMIT,CONSTRAINT,CREATE,CROSS,DEFAULT,DEFERRABLE,DELETE,DISTINCT,DROP,ELSE,ESCAPE,EXCEPT,FOREIGN,FROM,FULL,GROUP,HAVING,IN,INDEX,INNER,INSERT,INTERSECT,INTO,IS,ISNULL,JOIN,LEFT,LIMIT,NATURAL,NOT,NOTNULL,NULL,ON,OR,ORDER,OUTER,PRIMARY,REFERENCES,RIGHT,ROLLBACK,SELECT,SET,TABLE,THEN,TO,TRANSACTION,UNION,UNIQUE,UPDATE,USING,VALUES,WHEN,WHERE. Looks up a localized string similar to <?xml version="1.0" encoding="utf-8" ?> <DocumentElement> <MetaDataCollections> <CollectionName>MetaDataCollections</CollectionName> <NumberOfRestrictions>0</NumberOfRestrictions> <NumberOfIdentifierParts>0</NumberOfIdentifierParts> </MetaDataCollections> <MetaDataCollections> <CollectionName>DataSourceInformation</CollectionName> <NumberOfRestrictions>0</NumberOfRestrictions> <NumberOfIdentifierParts>0</NumberOfIdentifierParts> </MetaDataCollections> <MetaDataC [rest of string was truncated]";. The file extension used for dynamic link libraries. The file extension used for the XML configuration file. This is the name of the XML configuration file specific to the System.Data.SQLite assembly. This lock is used to protect the static _SQLiteNativeModuleFileName, _SQLiteNativeModuleHandle, and processorArchitecturePlatforms fields. This dictionary stores the mappings between processor architecture names and platform names. These mappings are now used for two purposes. First, they are used to determine if the assembly code base should be used instead of the location, based upon whether one or more of the named sub-directories exist within the assembly code base. Second, they are used to assist in loading the appropriate SQLite interop assembly into the current process. For now, this method simply calls the Initialize method. Attempts to initialize this class by pre-loading the native SQLite library for the processor architecture of the current process. Queries and returns the XML configuration file name for the assembly containing the managed System.Data.SQLite components. The XML configuration file name -OR- null if it cannot be determined or does not exist. Queries and returns the value of the specified setting, using the XML configuration file and/or the environment variables for the current process and/or the current system, when available. The name of the setting. The value to be returned if the setting has not been set explicitly or cannot be determined. The value of the setting -OR- the default value specified by if it has not been set explicitly or cannot be determined. By default, all references to existing environment variables will be expanded to their corresponding values within the value to be returned unless either the "No_Expand" or "No_Expand_" environment variable is set [to anything]. Queries and returns the directory for the assembly currently being executed. The directory for the assembly currently being executed -OR- null if it cannot be determined. The name of the environment variable containing the processor architecture of the current process. This is the P/Invoke method that wraps the native Win32 LoadLibrary function. See the MSDN documentation for full details on what it does. The name of the executable library. The native module handle upon success -OR- IntPtr.Zero on failure. The native module file name for the native SQLite library or null. The native module handle for the native SQLite library or the value IntPtr.Zero. Searches for the native SQLite library in the directory containing the assembly currently being executed as well as the base directory for the current application domain. Upon success, this parameter will be modified to refer to the base directory containing the native SQLite library. Upon success, this parameter will be modified to refer to the name of the immediate directory (i.e. the offset from the base directory) containing the native SQLite library. Non-zero (success) if the native SQLite library was found; otherwise, zero (failure). Queries and returns the base directory of the current application domain. The base directory for the current application domain -OR- null if it cannot be determined. Determines if the dynamic link library file name requires a suffix and adds it if necessary. The original dynamic link library file name to inspect. The dynamic link library file name, possibly modified to include an extension. Queries and returns the processor architecture of the current process. The processor architecture of the current process -OR- null if it cannot be determined. Given the processor architecture, returns the name of the platform. The processor architecture to be translated to a platform name. The platform name for the specified processor architecture -OR- null if it cannot be determined. Attempts to load the native SQLite library based on the specified directory and processor architecture. The base directory to use, null for default (the base directory of the current application domain). This directory should contain the processor architecture specific sub-directories. The requested processor architecture, null for default (the processor architecture of the current process). This caller should almost always specify null for this parameter. The candidate native module file name to load will be stored here, if necessary. The native module handle as returned by LoadLibrary will be stored here, if necessary. This value will be IntPtr.Zero if the call to LoadLibrary fails. Non-zero if the native module was loaded successfully; otherwise, zero. This class represents a context from the SQLite core library that can be passed to the sqlite3_result_*() and associated functions. This interface represents a native handle provided by the SQLite core library. The native handle value. The native context handle. Constructs an instance of this class using the specified native context handle. The native context handle to use. Sets the context result to NULL. Sets the context result to the specified value. The value to use. Sets the context result to the specified value. The value to use. Sets the context result to the specified value. The value to use. Sets the context result to the specified value. The value to use. This value will be converted to the UTF-8 encoding prior to being used. Sets the context result to the specified value containing an error message. The value containing the error message text. This value will be converted to the UTF-8 encoding prior to being used. Sets the context result to the specified value. The value to use. Sets the context result to contain the error code SQLITE_TOOBIG. Sets the context result to contain the error code SQLITE_NOMEM. Sets the context result to the specified array value. The array value to use. Sets the context result to a BLOB of zeros of the specified size. The number of zero bytes to use for the BLOB context result. Sets the context result to the specified . The to use. Returns the underlying SQLite native handle associated with this object instance. This class represents a value from the SQLite core library that can be passed to the sqlite3_value_*() and associated functions. The native value handle. Constructs an instance of this class using the specified native value handle. The native value handle to use. Invalidates the native value handle, thereby preventing further access to it from this object instance. Converts a logical array of native pointers to native sqlite3_value structures into a managed array of object instances. The number of elements in the logical array of native sqlite3_value structures. The native pointer to the logical array of native sqlite3_value structures to convert. The managed array of object instances or null upon failure. Gets and returns the type affinity associated with this value. The type affinity associated with this value. Gets and returns the number of bytes associated with this value, if it refers to a UTF-8 encoded string. The number of bytes associated with this value. The returned value may be zero. Gets and returns the associated with this value. The associated with this value. Gets and returns the associated with this value. The associated with this value. Gets and returns the associated with this value. The associated with this value. Gets and returns the associated with this value. The associated with this value. The value is converted from the UTF-8 encoding prior to being returned. Gets and returns the array associated with this value. The array associated with this value. Uses the native value handle to obtain and store the managed value for this object instance, thus saving it for later use. The type of the managed value is determined by the type affinity of the native value. If the type affinity is not recognized by this method, no work is done and false is returned. Non-zero if the native value was persisted successfully. Returns the underlying SQLite native handle associated with this object instance. Returns non-zero if the native SQLite value has been successfully persisted as a managed value within this object instance (i.e. the property may then be read successfully). If the managed value for this object instance is available (i.e. it has been previously persisted via the ) method, that value is returned; otherwise, an exception is thrown. The returned value may be null. These are the allowed values for the operators that are part of a constraint term in the WHERE clause of a query that uses a virtual table. This value represents the equality operator. This value represents the greater than operator. This value represents the less than or equal to operator. This value represents the less than operator. This value represents the greater than or equal to operator. This value represents the MATCH operator. This class represents the native sqlite3_index_constraint structure from the SQLite core library. Constructs an instance of this class using the specified native sqlite3_index_constraint structure. The native sqlite3_index_constraint structure to use. Constructs an instance of this class using the specified field values. Column on left-hand side of constraint. Constraint operator (). True if this constraint is usable. Used internally - should ignore. Column on left-hand side of constraint. Constraint operator (). True if this constraint is usable. Used internally - should ignore. This class represents the native sqlite3_index_orderby structure from the SQLite core library. Constructs an instance of this class using the specified native sqlite3_index_orderby structure. The native sqlite3_index_orderby structure to use. Constructs an instance of this class using the specified field values. Column number. True for DESC. False for ASC. Column number. True for DESC. False for ASC. This class represents the native sqlite3_index_constraint_usage structure from the SQLite core library. Constructs an instance of this class using the specified native sqlite3_index_constraint_usage structure. The native sqlite3_index_constraint_usage structure to use. Constructs an instance of this class using the specified field values. If greater than 0, constraint is part of argv to xFilter. Do not code a test for this constraint. If greater than 0, constraint is part of argv to xFilter. Do not code a test for this constraint. This class represents the various inputs provided by the SQLite core library to the method. Constructs an instance of this class. The number of instances to pre-allocate space for. The number of instances to pre-allocate space for. An array of object instances, each containing information supplied by the SQLite core library. An array of object instances, each containing information supplied by the SQLite core library. This class represents the various outputs provided to the SQLite core library by the method. Constructs an instance of this class. The number of instances to pre-allocate space for. Determines if the native estimatedRows field can be used, based on the available version of the SQLite core library. Non-zero if the property is supported by the SQLite core library. An array of object instances, each containing information to be supplied to the SQLite core library. Number used to help identify the selected index. This value will later be provided to the method. String used to help identify the selected index. This value will later be provided to the method. Non-zero if the index string must be freed by the SQLite core library. True if output is already ordered. Estimated cost of using this index. Using a null value here indicates that a default estimated cost value should be used. Estimated number of rows returned. Using a null value here indicates that a default estimated rows value should be used. This class represents the various inputs and outputs used with the method. Constructs an instance of this class. The number of (and ) instances to pre-allocate space for. The number of instances to pre-allocate space for. Converts a native pointer to a native sqlite3_index_info structure into a new object instance. The native pointer to the native sqlite3_index_info structure to convert. Upon success, this parameter will be modified to contain the newly created object instance. Populates the outputs of a pre-allocated native sqlite3_index_info structure using an existing object instance. The existing object instance containing the output data to use. The native pointer to the pre-allocated native sqlite3_index_info structure. The object instance containing the inputs to the method. The object instance containing the outputs from the method. This class represents a managed virtual table implementation. It is not sealed and should be used as the base class for any user-defined virtual table classes implemented in managed code. The index within the array of strings provided to the and methods containing the name of the module implementing this virtual table. The index within the array of strings provided to the and methods containing the name of the database containing this virtual table. The index within the array of strings provided to the and methods containing the name of the virtual table. Constructs an instance of this class. The original array of strings provided to the and methods. This method should normally be used by the method in order to perform index selection based on the constraints provided by the SQLite core library. The object instance containing all the data for the inputs and outputs relating to index selection. Non-zero upon success. Attempts to record the renaming of the virtual table associated with this object instance. The new name for the virtual table. Non-zero upon success. Disposes of this object instance. Throws an if this object instance has been disposed. Disposes of this object instance. Non-zero if this method is being called from the method. Zero if this method is being called from the finalizer. Finalizes this object instance. The original array of strings provided to the and methods. The name of the module implementing this virtual table. The name of the database containing this virtual table. The name of the virtual table. The object instance containing all the data for the inputs and outputs relating to the most recent index selection. Returns the underlying SQLite native handle associated with this object instance. This class represents a managed virtual table cursor implementation. It is not sealed and should be used as the base class for any user-defined virtual table cursor classes implemented in managed code. This value represents an invalid integer row sequence number. The field holds the integer row sequence number for the current row pointed to by this cursor object instance. Constructs an instance of this class. The object instance associated with this object instance. Constructs an instance of this class. Attempts to persist the specified object instances in order to make them available after the method returns. The array of object instances to be persisted. The number of object instances that were successfully persisted. This method should normally be used by the method in order to perform filtering of the result rows and/or to record the filtering criteria provided by the SQLite core library. Number used to help identify the selected index. String used to help identify the selected index. The values corresponding to each column in the selected index. Determines the integer row sequence number for the current row. The integer row sequence number for the current row -OR- zero if it cannot be determined. Adjusts the integer row sequence number so that it refers to the next row. Disposes of this object instance. Throws an if this object instance has been disposed. Disposes of this object instance. Non-zero if this method is being called from the method. Zero if this method is being called from the finalizer. Finalizes this object instance. The object instance associated with this object instance. Number used to help identify the selected index. This value will be set via the method. String used to help identify the selected index. This value will be set via the method. The values used to filter the rows returned via this cursor object instance. This value will be set via the method. Returns the underlying SQLite native handle associated with this object instance. This interface represents a virtual table implementation written in native code. This method is called to create a new instance of a virtual table in response to a CREATE VIRTUAL TABLE statement. The db parameter is a pointer to the SQLite database connection that is executing the CREATE VIRTUAL TABLE statement. The pAux argument is the copy of the client data pointer that was the fourth argument to the sqlite3_create_module() or sqlite3_create_module_v2() call that registered the virtual table module. The argv parameter is an array of argc pointers to null terminated strings. The first string, argv[0], is the name of the module being invoked. The module name is the name provided as the second argument to sqlite3_create_module() and as the argument to the USING clause of the CREATE VIRTUAL TABLE statement that is running. The second, argv[1], is the name of the database in which the new virtual table is being created. The database name is "main" for the primary database, or "temp" for TEMP database, or the name given at the end of the ATTACH statement for attached databases. The third element of the array, argv[2], is the name of the new virtual table, as specified following the TABLE keyword in the CREATE VIRTUAL TABLE statement. If present, the fourth and subsequent strings in the argv[] array report the arguments to the module name in the CREATE VIRTUAL TABLE statement. The job of this method is to construct the new virtual table object (an sqlite3_vtab object) and return a pointer to it in *ppVTab. As part of the task of creating a new sqlite3_vtab structure, this method must invoke sqlite3_declare_vtab() to tell the SQLite core about the columns and datatypes in the virtual table. The sqlite3_declare_vtab() API has the following prototype: int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable) The first argument to sqlite3_declare_vtab() must be the same database connection pointer as the first parameter to this method. The second argument to sqlite3_declare_vtab() must a zero-terminated UTF-8 string that contains a well-formed CREATE TABLE statement that defines the columns in the virtual table and their data types. The name of the table in this CREATE TABLE statement is ignored, as are all constraints. Only the column names and datatypes matter. The CREATE TABLE statement string need not to be held in persistent memory. The string can be deallocated and/or reused as soon as the sqlite3_declare_vtab() routine returns. The native database connection handle. The original native pointer value that was provided to the sqlite3_create_module(), sqlite3_create_module_v2() or sqlite3_create_disposable_module() functions. The number of arguments from the CREATE VIRTUAL TABLE statement. The array of string arguments from the CREATE VIRTUAL TABLE statement. Upon success, this parameter must be modified to point to the newly created native sqlite3_vtab derived structure. Upon failure, this parameter must be modified to point to the error message, with the underlying memory having been obtained from the sqlite3_malloc() function. A standard SQLite return code. The xConnect method is very similar to xCreate. It has the same parameters and constructs a new sqlite3_vtab structure just like xCreate. And it must also call sqlite3_declare_vtab() like xCreate. The difference is that xConnect is called to establish a new connection to an existing virtual table whereas xCreate is called to create a new virtual table from scratch. The xCreate and xConnect methods are only different when the virtual table has some kind of backing store that must be initialized the first time the virtual table is created. The xCreate method creates and initializes the backing store. The xConnect method just connects to an existing backing store. As an example, consider a virtual table implementation that provides read-only access to existing comma-separated-value (CSV) files on disk. There is no backing store that needs to be created or initialized for such a virtual table (since the CSV files already exist on disk) so the xCreate and xConnect methods will be identical for that module. Another example is a virtual table that implements a full-text index. The xCreate method must create and initialize data structures to hold the dictionary and posting lists for that index. The xConnect method, on the other hand, only has to locate and use an existing dictionary and posting lists that were created by a prior xCreate call. The xConnect method must return SQLITE_OK if it is successful in creating the new virtual table, or SQLITE_ERROR if it is not successful. If not successful, the sqlite3_vtab structure must not be allocated. An error message may optionally be returned in *pzErr if unsuccessful. Space to hold the error message string must be allocated using an SQLite memory allocation function like sqlite3_malloc() or sqlite3_mprintf() as the SQLite core will attempt to free the space using sqlite3_free() after the error has been reported up to the application. The xConnect method is required for every virtual table implementation, though the xCreate and xConnect pointers of the sqlite3_module object may point to the same function the virtual table does not need to initialize backing store. The native database connection handle. The original native pointer value that was provided to the sqlite3_create_module(), sqlite3_create_module_v2() or sqlite3_create_disposable_module() functions. The number of arguments from the CREATE VIRTUAL TABLE statement. The array of string arguments from the CREATE VIRTUAL TABLE statement. Upon success, this parameter must be modified to point to the newly created native sqlite3_vtab derived structure. Upon failure, this parameter must be modified to point to the error message, with the underlying memory having been obtained from the sqlite3_malloc() function. A standard SQLite return code. SQLite uses the xBestIndex method of a virtual table module to determine the best way to access the virtual table. The xBestIndex method has a prototype like this: int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); The SQLite core communicates with the xBestIndex method by filling in certain fields of the sqlite3_index_info structure and passing a pointer to that structure into xBestIndex as the second parameter. The xBestIndex method fills out other fields of this structure which forms the reply. The sqlite3_index_info structure looks like this: struct sqlite3_index_info { /* Inputs */ const int nConstraint; /* Number of entries in aConstraint */ const struct sqlite3_index_constraint { int iColumn; /* Column on left-hand side of * constraint */ unsigned char op; /* Constraint operator */ unsigned char usable; /* True if this constraint is usable */ int iTermOffset; /* Used internally - xBestIndex should * ignore */ } *const aConstraint; /* Table of WHERE clause constraints */ const int nOrderBy; /* Number of terms in the ORDER BY * clause */ const struct sqlite3_index_orderby { int iColumn; /* Column number */ unsigned char desc; /* True for DESC. False for ASC. */ } *const aOrderBy; /* The ORDER BY clause */ /* Outputs */ struct sqlite3_index_constraint_usage { int argvIndex; /* if greater than zero, constraint is * part of argv to xFilter */ unsigned char omit; /* Do not code a test for this * constraint */ } *const aConstraintUsage; int idxNum; /* Number used to identify the index */ char *idxStr; /* String, possibly obtained from * sqlite3_malloc() */ int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if * true */ int orderByConsumed; /* True if output is already ordered */ double estimatedCost; /* Estimated cost of using this index */ }; In addition, there are some defined constants: #define SQLITE_INDEX_CONSTRAINT_EQ 2 #define SQLITE_INDEX_CONSTRAINT_GT 4 #define SQLITE_INDEX_CONSTRAINT_LE 8 #define SQLITE_INDEX_CONSTRAINT_LT 16 #define SQLITE_INDEX_CONSTRAINT_GE 32 #define SQLITE_INDEX_CONSTRAINT_MATCH 64 The SQLite core calls the xBestIndex method when it is compiling a query that involves a virtual table. In other words, SQLite calls this method when it is running sqlite3_prepare() or the equivalent. By calling this method, the SQLite core is saying to the virtual table that it needs to access some subset of the rows in the virtual table and it wants to know the most efficient way to do that access. The xBestIndex method replies with information that the SQLite core can then use to conduct an efficient search of the virtual table. While compiling a single SQL query, the SQLite core might call xBestIndex multiple times with different settings in sqlite3_index_info. The SQLite core will then select the combination that appears to give the best performance. Before calling this method, the SQLite core initializes an instance of the sqlite3_index_info structure with information about the query that it is currently trying to process. This information derives mainly from the WHERE clause and ORDER BY or GROUP BY clauses of the query, but also from any ON or USING clauses if the query is a join. The information that the SQLite core provides to the xBestIndex method is held in the part of the structure that is marked as "Inputs". The "Outputs" section is initialized to zero. The information in the sqlite3_index_info structure is ephemeral and may be overwritten or deallocated as soon as the xBestIndex method returns. If the xBestIndex method needs to remember any part of the sqlite3_index_info structure, it should make a copy. Care must be take to store the copy in a place where it will be deallocated, such as in the idxStr field with needToFreeIdxStr set to 1. Note that xBestIndex will always be called before xFilter, since the idxNum and idxStr outputs from xBestIndex are required inputs to xFilter. However, there is no guarantee that xFilter will be called following a successful xBestIndex. The xBestIndex method is required for every virtual table implementation. 2.3.1 Inputs The main thing that the SQLite core is trying to communicate to the virtual table is the constraints that are available to limit the number of rows that need to be searched. The aConstraint[] array contains one entry for each constraint. There will be exactly nConstraint entries in that array. Each constraint will correspond to a term in the WHERE clause or in a USING or ON clause that is of the form column OP EXPR Where "column" is a column in the virtual table, OP is an operator like "=" or "<", and EXPR is an arbitrary expression. So, for example, if the WHERE clause contained a term like this: a = 5 Then one of the constraints would be on the "a" column with operator "=" and an expression of "5". Constraints need not have a literal representation of the WHERE clause. The query optimizer might make transformations to the WHERE clause in order to extract as many constraints as it can. So, for example, if the WHERE clause contained something like this: x BETWEEN 10 AND 100 AND 999>y The query optimizer might translate this into three separate constraints: x >= 10 x <= 100 y < 999 For each constraint, the aConstraint[].iColumn field indicates which column appears on the left-hand side of the constraint. The first column of the virtual table is column 0. The rowid of the virtual table is column -1. The aConstraint[].op field indicates which operator is used. The SQLITE_INDEX_CONSTRAINT_* constants map integer constants into operator values. Columns occur in the order they were defined by the call to sqlite3_declare_vtab() in the xCreate or xConnect method. Hidden columns are counted when determining the column index. The aConstraint[] array contains information about all constraints that apply to the virtual table. But some of the constraints might not be usable because of the way tables are ordered in a join. The xBestIndex method must therefore only consider constraints that have an aConstraint[].usable flag which is true. In addition to WHERE clause constraints, the SQLite core also tells the xBestIndex method about the ORDER BY clause. (In an aggregate query, the SQLite core might put in GROUP BY clause information in place of the ORDER BY clause information, but this fact should not make any difference to the xBestIndex method.) If all terms of the ORDER BY clause are columns in the virtual table, then nOrderBy will be the number of terms in the ORDER BY clause and the aOrderBy[] array will identify the column for each term in the order by clause and whether or not that column is ASC or DESC. 2.3.2 Outputs Given all of the information above, the job of the xBestIndex method it to figure out the best way to search the virtual table. The xBestIndex method fills the idxNum and idxStr fields with information that communicates an indexing strategy to the xFilter method. The information in idxNum and idxStr is arbitrary as far as the SQLite core is concerned. The SQLite core just copies the information through to the xFilter method. Any desired meaning can be assigned to idxNum and idxStr as long as xBestIndex and xFilter agree on what that meaning is. The idxStr value may be a string obtained from an SQLite memory allocation function such as sqlite3_mprintf(). If this is the case, then the needToFreeIdxStr flag must be set to true so that the SQLite core will know to call sqlite3_free() on that string when it has finished with it, and thus avoid a memory leak. If the virtual table will output rows in the order specified by the ORDER BY clause, then the orderByConsumed flag may be set to true. If the output is not automatically in the correct order then orderByConsumed must be left in its default false setting. This will indicate to the SQLite core that it will need to do a separate sorting pass over the data after it comes out of the virtual table. The estimatedCost field should be set to the estimated number of disk access operations required to execute this query against the virtual table. The SQLite core will often call xBestIndex multiple times with different constraints, obtain multiple cost estimates, then choose the query plan that gives the lowest estimate. The aConstraintUsage[] array contains one element for each of the nConstraint constraints in the inputs section of the sqlite3_index_info structure. The aConstraintUsage[] array is used by xBestIndex to tell the core how it is using the constraints. The xBestIndex method may set aConstraintUsage[].argvIndex entries to values greater than one. Exactly one entry should be set to 1, another to 2, another to 3, and so forth up to as many or as few as the xBestIndex method wants. The EXPR of the corresponding constraints will then be passed in as the argv[] parameters to xFilter. For example, if the aConstraint[3].argvIndex is set to 1, then when xFilter is called, the argv[0] passed to xFilter will have the EXPR value of the aConstraint[3] constraint. By default, the SQLite core double checks all constraints on each row of the virtual table that it receives. If such a check is redundant, the xBestFilter method can suppress that double-check by setting aConstraintUsage[].omit. The native pointer to the sqlite3_vtab derived structure. The native pointer to the sqlite3_index_info structure. A standard SQLite return code. This method releases a connection to a virtual table. Only the sqlite3_vtab object is destroyed. The virtual table is not destroyed and any backing store associated with the virtual table persists. This method undoes the work of xConnect. This method is a destructor for a connection to the virtual table. Contrast this method with xDestroy. The xDestroy is a destructor for the entire virtual table. The xDisconnect method is required for every virtual table implementation, though it is acceptable for the xDisconnect and xDestroy methods to be the same function if that makes sense for the particular virtual table. The native pointer to the sqlite3_vtab derived structure. A standard SQLite return code. This method releases a connection to a virtual table, just like the xDisconnect method, and it also destroys the underlying table implementation. This method undoes the work of xCreate. The xDisconnect method is called whenever a database connection that uses a virtual table is closed. The xDestroy method is only called when a DROP TABLE statement is executed against the virtual table. The xDestroy method is required for every virtual table implementation, though it is acceptable for the xDisconnect and xDestroy methods to be the same function if that makes sense for the particular virtual table. The native pointer to the sqlite3_vtab derived structure. A standard SQLite return code. The xOpen method creates a new cursor used for accessing (read and/or writing) a virtual table. A successful invocation of this method will allocate the memory for the sqlite3_vtab_cursor (or a subclass), initialize the new object, and make *ppCursor point to the new object. The successful call then returns SQLITE_OK. For every successful call to this method, the SQLite core will later invoke the xClose method to destroy the allocated cursor. The xOpen method need not initialize the pVtab field of the sqlite3_vtab_cursor structure. The SQLite core will take care of that chore automatically. A virtual table implementation must be able to support an arbitrary number of simultaneously open cursors. When initially opened, the cursor is in an undefined state. The SQLite core will invoke the xFilter method on the cursor prior to any attempt to position or read from the cursor. The xOpen method is required for every virtual table implementation. The native pointer to the sqlite3_vtab derived structure. Upon success, this parameter must be modified to point to the newly created native sqlite3_vtab_cursor derived structure. A standard SQLite return code. The xClose method closes a cursor previously opened by xOpen. The SQLite core will always call xClose once for each cursor opened using xOpen. This method must release all resources allocated by the corresponding xOpen call. The routine will not be called again even if it returns an error. The SQLite core will not use the sqlite3_vtab_cursor again after it has been closed. The xClose method is required for every virtual table implementation. The native pointer to the sqlite3_vtab_cursor derived structure. A standard SQLite return code. This method begins a search of a virtual table. The first argument is a cursor opened by xOpen. The next two argument define a particular search index previously chosen by xBestIndex. The specific meanings of idxNum and idxStr are unimportant as long as xFilter and xBestIndex agree on what that meaning is. The xBestIndex function may have requested the values of certain expressions using the aConstraintUsage[].argvIndex values of the sqlite3_index_info structure. Those values are passed to xFilter using the argc and argv parameters. If the virtual table contains one or more rows that match the search criteria, then the cursor must be left point at the first row. Subsequent calls to xEof must return false (zero). If there are no rows match, then the cursor must be left in a state that will cause the xEof to return true (non-zero). The SQLite engine will use the xColumn and xRowid methods to access that row content. The xNext method will be used to advance to the next row. This method must return SQLITE_OK if successful, or an sqlite error code if an error occurs. The xFilter method is required for every virtual table implementation. The native pointer to the sqlite3_vtab_cursor derived structure. Number used to help identify the selected index. The native pointer to the UTF-8 encoded string containing the string used to help identify the selected index. The number of native pointers to sqlite3_value structures specified in . An array of native pointers to sqlite3_value structures containing filtering criteria for the selected index. A standard SQLite return code. The xNext method advances a virtual table cursor to the next row of a result set initiated by xFilter. If the cursor is already pointing at the last row when this routine is called, then the cursor no longer points to valid data and a subsequent call to the xEof method must return true (non-zero). If the cursor is successfully advanced to another row of content, then subsequent calls to xEof must return false (zero). This method must return SQLITE_OK if successful, or an sqlite error code if an error occurs. The xNext method is required for every virtual table implementation. The native pointer to the sqlite3_vtab_cursor derived structure. A standard SQLite return code. The xEof method must return false (zero) if the specified cursor currently points to a valid row of data, or true (non-zero) otherwise. This method is called by the SQL engine immediately after each xFilter and xNext invocation. The xEof method is required for every virtual table implementation. The native pointer to the sqlite3_vtab_cursor derived structure. Non-zero if no more rows are available; zero otherwise. The SQLite core invokes this method in order to find the value for the N-th column of the current row. N is zero-based so the first column is numbered 0. The xColumn method may return its result back to SQLite using one of the following interface: sqlite3_result_blob() sqlite3_result_double() sqlite3_result_int() sqlite3_result_int64() sqlite3_result_null() sqlite3_result_text() sqlite3_result_text16() sqlite3_result_text16le() sqlite3_result_text16be() sqlite3_result_zeroblob() If the xColumn method implementation calls none of the functions above, then the value of the column defaults to an SQL NULL. To raise an error, the xColumn method should use one of the result_text() methods to set the error message text, then return an appropriate error code. The xColumn method must return SQLITE_OK on success. The xColumn method is required for every virtual table implementation. The native pointer to the sqlite3_vtab_cursor derived structure. The native pointer to the sqlite3_context structure to be used for returning the specified column value to the SQLite core library. The zero-based index corresponding to the column containing the value to be returned. A standard SQLite return code. A successful invocation of this method will cause *pRowid to be filled with the rowid of row that the virtual table cursor pCur is currently pointing at. This method returns SQLITE_OK on success. It returns an appropriate error code on failure. The xRowid method is required for every virtual table implementation. The native pointer to the sqlite3_vtab_cursor derived structure. Upon success, this parameter must be modified to contain the unique integer row identifier for the current row for the specified cursor. A standard SQLite return code. All changes to a virtual table are made using the xUpdate method. This one method can be used to insert, delete, or update. The argc parameter specifies the number of entries in the argv array. The value of argc will be 1 for a pure delete operation or N+2 for an insert or replace or update where N is the number of columns in the table. In the previous sentence, N includes any hidden columns. Every argv entry will have a non-NULL value in C but may contain the SQL value NULL. In other words, it is always true that argv[i]!=0 for i between 0 and argc-1. However, it might be the case that sqlite3_value_type(argv[i])==SQLITE_NULL. The argv[0] parameter is the rowid of a row in the virtual table to be deleted. If argv[0] is an SQL NULL, then no deletion occurs. The argv[1] parameter is the rowid of a new row to be inserted into the virtual table. If argv[1] is an SQL NULL, then the implementation must choose a rowid for the newly inserted row. Subsequent argv[] entries contain values of the columns of the virtual table, in the order that the columns were declared. The number of columns will match the table declaration that the xConnect or xCreate method made using the sqlite3_declare_vtab() call. All hidden columns are included. When doing an insert without a rowid (argc>1, argv[1] is an SQL NULL), the implementation must set *pRowid to the rowid of the newly inserted row; this will become the value returned by the sqlite3_last_insert_rowid() function. Setting this value in all the other cases is a harmless no-op; the SQLite engine ignores the *pRowid return value if argc==1 or argv[1] is not an SQL NULL. Each call to xUpdate will fall into one of cases shown below. Note that references to argv[i] mean the SQL value held within the argv[i] object, not the argv[i] object itself. argc = 1 The single row with rowid equal to argv[0] is deleted. No insert occurs. argc > 1 argv[0] = NULL A new row is inserted with a rowid argv[1] and column values in argv[2] and following. If argv[1] is an SQL NULL, the a new unique rowid is generated automatically. argc > 1 argv[0] ? NULL argv[0] = argv[1] The row with rowid argv[0] is updated with new values in argv[2] and following parameters. argc > 1 argv[0] ? NULL argv[0] ? argv[1] The row with rowid argv[0] is updated with rowid argv[1] and new values in argv[2] and following parameters. This will occur when an SQL statement updates a rowid, as in the statement: UPDATE table SET rowid=rowid+1 WHERE ...; The xUpdate method must return SQLITE_OK if and only if it is successful. If a failure occurs, the xUpdate must return an appropriate error code. On a failure, the pVTab->zErrMsg element may optionally be replaced with error message text stored in memory allocated from SQLite using functions such as sqlite3_mprintf() or sqlite3_malloc(). If the xUpdate method violates some constraint of the virtual table (including, but not limited to, attempting to store a value of the wrong datatype, attempting to store a value that is too large or too small, or attempting to change a read-only value) then the xUpdate must fail with an appropriate error code. There might be one or more sqlite3_vtab_cursor objects open and in use on the virtual table instance and perhaps even on the row of the virtual table when the xUpdate method is invoked. The implementation of xUpdate must be prepared for attempts to delete or modify rows of the table out from other existing cursors. If the virtual table cannot accommodate such changes, the xUpdate method must return an error code. The xUpdate method is optional. If the xUpdate pointer in the sqlite3_module for a virtual table is a NULL pointer, then the virtual table is read-only. The native pointer to the sqlite3_vtab derived structure. The number of new or modified column values contained in . The array of native pointers to sqlite3_value structures containing the new or modified column values, if any. Upon success, this parameter must be modified to contain the unique integer row identifier for the row that was inserted, if any. A standard SQLite return code. This method begins a transaction on a virtual table. This is method is optional. The xBegin pointer of sqlite3_module may be NULL. This method is always followed by one call to either the xCommit or xRollback method. Virtual table transactions do not nest, so the xBegin method will not be invoked more than once on a single virtual table without an intervening call to either xCommit or xRollback. Multiple calls to other methods can and likely will occur in between the xBegin and the corresponding xCommit or xRollback. The native pointer to the sqlite3_vtab derived structure. A standard SQLite return code. This method signals the start of a two-phase commit on a virtual table. This is method is optional. The xSync pointer of sqlite3_module may be NULL. This method is only invoked after call to the xBegin method and prior to an xCommit or xRollback. In order to implement two-phase commit, the xSync method on all virtual tables is invoked prior to invoking the xCommit method on any virtual table. If any of the xSync methods fail, the entire transaction is rolled back. The native pointer to the sqlite3_vtab derived structure. A standard SQLite return code. This method causes a virtual table transaction to commit. This is method is optional. The xCommit pointer of sqlite3_module may be NULL. A call to this method always follows a prior call to xBegin and xSync. The native pointer to the sqlite3_vtab derived structure. A standard SQLite return code. This method causes a virtual table transaction to rollback. This is method is optional. The xRollback pointer of sqlite3_module may be NULL. A call to this method always follows a prior call to xBegin. The native pointer to the sqlite3_vtab derived structure. A standard SQLite return code. This method provides notification that the virtual table implementation that the virtual table will be given a new name. If this method returns SQLITE_OK then SQLite renames the table. If this method returns an error code then the renaming is prevented. The xRename method is required for every virtual table implementation. The native pointer to the sqlite3_vtab derived structure. The number of arguments to the function being sought. The name of the function being sought. Upon success, this parameter must be modified to contain the delegate responsible for implementing the specified function. Upon success, this parameter must be modified to contain the native user-data pointer associated with . Non-zero if the specified function was found; zero otherwise. This method provides notification that the virtual table implementation that the virtual table will be given a new name. If this method returns SQLITE_OK then SQLite renames the table. If this method returns an error code then the renaming is prevented. The xRename method is required for every virtual table implementation. The native pointer to the sqlite3_vtab derived structure. The native pointer to the UTF-8 encoded string containing the new name for the virtual table. A standard SQLite return code. These methods provide the virtual table implementation an opportunity to implement nested transactions. They are always optional and will only be called in SQLite version 3.7.7 and later. When xSavepoint(X,N) is invoked, that is a signal to the virtual table X that it should save its current state as savepoint N. A subsequent call to xRollbackTo(X,R) means that the state of the virtual table should return to what it was when xSavepoint(X,R) was last called. The call to xRollbackTo(X,R) will invalidate all savepoints with N>R; none of the invalided savepoints will be rolled back or released without first being reinitialized by a call to xSavepoint(). A call to xRelease(X,M) invalidates all savepoints where N>=M. None of the xSavepoint(), xRelease(), or xRollbackTo() methods will ever be called except in between calls to xBegin() and either xCommit() or xRollback(). The native pointer to the sqlite3_vtab derived structure. This is an integer identifier under which the the current state of the virtual table should be saved. A standard SQLite return code. These methods provide the virtual table implementation an opportunity to implement nested transactions. They are always optional and will only be called in SQLite version 3.7.7 and later. When xSavepoint(X,N) is invoked, that is a signal to the virtual table X that it should save its current state as savepoint N. A subsequent call to xRollbackTo(X,R) means that the state of the virtual table should return to what it was when xSavepoint(X,R) was last called. The call to xRollbackTo(X,R) will invalidate all savepoints with N>R; none of the invalided savepoints will be rolled back or released without first being reinitialized by a call to xSavepoint(). A call to xRelease(X,M) invalidates all savepoints where N>=M. None of the xSavepoint(), xRelease(), or xRollbackTo() methods will ever be called except in between calls to xBegin() and either xCommit() or xRollback(). The native pointer to the sqlite3_vtab derived structure. This is an integer used to indicate that any saved states with an identifier greater than or equal to this should be deleted by the virtual table. A standard SQLite return code. These methods provide the virtual table implementation an opportunity to implement nested transactions. They are always optional and will only be called in SQLite version 3.7.7 and later. When xSavepoint(X,N) is invoked, that is a signal to the virtual table X that it should save its current state as savepoint N. A subsequent call to xRollbackTo(X,R) means that the state of the virtual table should return to what it was when xSavepoint(X,R) was last called. The call to xRollbackTo(X,R) will invalidate all savepoints with N>R; none of the invalided savepoints will be rolled back or released without first being reinitialized by a call to xSavepoint(). A call to xRelease(X,M) invalidates all savepoints where N>=M. None of the xSavepoint(), xRelease(), or xRollbackTo() methods will ever be called except in between calls to xBegin() and either xCommit() or xRollback(). The native pointer to the sqlite3_vtab derived structure. This is an integer identifier used to specify a specific saved state for the virtual table for it to restore itself back to, which should also have the effect of deleting all saved states with an integer identifier greater than this one. A standard SQLite return code. This interface represents a virtual table implementation written in managed code. This method is called in response to the method. The object instance associated with the virtual table. The native user-data pointer associated with this module, as it was provided to the SQLite core library when the native module instance was created. The module name, database name, virtual table name, and all other arguments passed to the CREATE VIRTUAL TABLE statement. Upon success, this parameter must be modified to contain the object instance associated with the virtual table. Upon failure, this parameter must be modified to contain an error message. A standard SQLite return code. This method is called in response to the method. The object instance associated with the virtual table. The native user-data pointer associated with this module, as it was provided to the SQLite core library when the native module instance was created. The module name, database name, virtual table name, and all other arguments passed to the CREATE VIRTUAL TABLE statement. Upon success, this parameter must be modified to contain the object instance associated with the virtual table. Upon failure, this parameter must be modified to contain an error message. A standard SQLite return code. This method is called in response to the method. The object instance associated with this virtual table. The object instance containing all the data for the inputs and outputs relating to index selection. A standard SQLite return code. This method is called in response to the method. The object instance associated with this virtual table. A standard SQLite return code. This method is called in response to the method. The object instance associated with this virtual table. A standard SQLite return code. This method is called in response to the method. The object instance associated with this virtual table. Upon success, this parameter must be modified to contain the object instance associated with the newly opened virtual table cursor. A standard SQLite return code. This method is called in response to the method. The object instance associated with the previously opened virtual table cursor to be used. A standard SQLite return code. This method is called in response to the method. The object instance associated with the previously opened virtual table cursor to be used. Number used to help identify the selected index. String used to help identify the selected index. The values corresponding to each column in the selected index. A standard SQLite return code. This method is called in response to the method. The object instance associated with the previously opened virtual table cursor to be used. A standard SQLite return code. This method is called in response to the method. The object instance associated with the previously opened virtual table cursor to be used. Non-zero if no more rows are available; zero otherwise. This method is called in response to the method. The object instance associated with the previously opened virtual table cursor to be used. The object instance to be used for returning the specified column value to the SQLite core library. The zero-based index corresponding to the column containing the value to be returned. A standard SQLite return code. This method is called in response to the method. The object instance associated with the previously opened virtual table cursor to be used. Upon success, this parameter must be modified to contain the unique integer row identifier for the current row for the specified cursor. A standard SQLite return code. This method is called in response to the method. The object instance associated with this virtual table. The array of object instances containing the new or modified column values, if any. Upon success, this parameter must be modified to contain the unique integer row identifier for the row that was inserted, if any. A standard SQLite return code. This method is called in response to the method. The object instance associated with this virtual table. A standard SQLite return code. This method is called in response to the method. The object instance associated with this virtual table. A standard SQLite return code. This method is called in response to the method. The object instance associated with this virtual table. A standard SQLite return code. This method is called in response to the method. The object instance associated with this virtual table. A standard SQLite return code. This method is called in response to the method. The object instance associated with this virtual table. The number of arguments to the function being sought. The name of the function being sought. Upon success, this parameter must be modified to contain the object instance responsible for implementing the specified function. Upon success, this parameter must be modified to contain the native user-data pointer associated with . Non-zero if the specified function was found; zero otherwise. This method is called in response to the method. The object instance associated with this virtual table. The new name for the virtual table. A standard SQLite return code. This method is called in response to the method. The object instance associated with this virtual table. This is an integer identifier under which the the current state of the virtual table should be saved. A standard SQLite return code. This method is called in response to the method. The object instance associated with this virtual table. This is an integer used to indicate that any saved states with an identifier greater than or equal to this should be deleted by the virtual table. A standard SQLite return code. This method is called in response to the method. The object instance associated with this virtual table. This is an integer identifier used to specify a specific saved state for the virtual table for it to restore itself back to, which should also have the effect of deleting all saved states with an integer identifier greater than this one. A standard SQLite return code. Returns non-zero if the schema for the virtual table has been declared. Returns the name of the module as it was registered with the SQLite core library. This class contains static methods that are used to allocate, manipulate, and free native memory provided by the SQLite core library. Allocates at least the specified number of bytes of native memory via the SQLite core library sqlite3_malloc() function and returns the resulting native pointer. The number of bytes to allocate. The native pointer that points to a block of memory of at least the specified size -OR- if the memory could not be allocated. Gets and returns the actual size of the specified memory block that was previously obtained from the method. The native pointer to the memory block previously obtained from the method. The actual size, in bytes, of the memory block specified via the native pointer. Frees a memory block previously obtained from the method. The native pointer to the memory block previously obtained from the method. This class contains static methods that are used to deal with native UTF-8 string pointers to be used with the SQLite core library. This is the maximum possible length for the native UTF-8 encoded strings used with the SQLite core library. This is the object instance used to handle conversions from/to UTF-8. Converts the specified managed string into the UTF-8 encoding and returns the array of bytes containing its representation in that encoding. The managed string to convert. The array of bytes containing the representation of the managed string in the UTF-8 encoding or null upon failure. Converts the specified array of bytes representing a string in the UTF-8 encoding and returns a managed string. The array of bytes to convert. The managed string or null upon failure. Probes a native pointer to a string in the UTF-8 encoding for its terminating NUL character, within the specified length limit. The native NUL-terminated string pointer. The maximum length of the native string, in bytes. The length of the native string, in bytes -OR- zero if the length could not be determined. Converts the specified native NUL-terminated UTF-8 string pointer into a managed string. The native NUL-terminated UTF-8 string pointer. The managed string or null upon failure. Converts the specified native UTF-8 string pointer of the specified length into a managed string. The native UTF-8 string pointer. The length of the native string, in bytes. The managed string or null upon failure. Converts the specified managed string into a native NUL-terminated UTF-8 string pointer using memory obtained from the SQLite core library. The managed string to convert. The native NUL-terminated UTF-8 string pointer or upon failure. Converts a logical array of native NUL-terminated UTF-8 string pointers into an array of managed strings. The number of elements in the logical array of native NUL-terminated UTF-8 string pointers. The native pointer to the logical array of native NUL-terminated UTF-8 string pointers to convert. The array of managed strings or null upon failure. Converts an array of managed strings into an array of native NUL-terminated UTF-8 string pointers. The array of managed strings to convert. The array of native NUL-terminated UTF-8 string pointers or null upon failure. This class contains static methods that are used to deal with native pointers to memory blocks that logically contain arrays of bytes to be used with the SQLite core library. Converts a native pointer to a logical array of bytes of the specified length into a managed byte array. The native pointer to the logical array of bytes to convert. The length, in bytes, of the logical array of bytes to convert. The managed byte array or null upon failure. Converts a managed byte array into a native pointer to a logical array of bytes. The managed byte array to convert. The native pointer to a logical byte array or null upon failure. This class contains static methods that are used to perform several low-level data marshalling tasks between native and managed code. Returns a new object instance based on the specified object instance and an integer offset. The object instance representing the base memory location. The integer offset from the base memory location that the new object instance should point to. The new object instance. Rounds up an integer size to the next multiple of the alignment. The size, in bytes, to be rounded up. The required alignment for the return value. The size, in bytes, rounded up to the next multiple of the alignment. This value may end up being the same as the original size. Determines the offset, in bytes, of the next structure member. The offset, in bytes, of the current structure member. The size, in bytes, of the current structure member. The alignment, in bytes, of the next structure member. The offset, in bytes, of the next structure member. Reads a value from the specified memory location. The object instance representing the base memory location. The integer offset from the base memory location where the value to be read is located. The value at the specified memory location. Reads a value from the specified memory location. The object instance representing the base memory location. The integer offset from the base memory location where the to be read is located. The value at the specified memory location. Reads an value from the specified memory location. The object instance representing the base memory location. The integer offset from the base memory location where the value to be read is located. The value at the specified memory location. Writes an value to the specified memory location. The object instance representing the base memory location. The integer offset from the base memory location where the value to be written is located. The value to write. Writes an value to the specified memory location. The object instance representing the base memory location. The integer offset from the base memory location where the value to be written is located. The value to write. Writes a value to the specified memory location. The object instance representing the base memory location. The integer offset from the base memory location where the value to be written is located. The value to write. Writes a value to the specified memory location. The object instance representing the base memory location. The integer offset from the base memory location where the value to be written is located. The value to write. Generates a hash code value for the object. The object instance used to calculate the hash code. Non-zero if different object instances with the same value should generate different hash codes, where applicable. This parameter has no effect on the .NET Compact Framework. The hash code value -OR- zero if the object is null. This class represents a managed virtual table module implementation. It is not sealed and must be used as the base class for any user-defined virtual table module classes implemented in managed code. The default version of the native sqlite3_module structure in use. This field is used to store the native sqlite3_module structure associated with this object instance. This field is used to store the destructor delegate to be passed to the SQLite core library via the sqlite3_create_disposable_module() function. This field is used to store a pointer to the native sqlite3_module structure returned by the sqlite3_create_disposable_module function. This field is used to store the virtual table instances associated with this module. The native pointer to the sqlite3_vtab derived structure is used to key into this collection. This field is used to store the virtual table cursor instances associated with this module. The native pointer to the sqlite3_vtab_cursor derived structure is used to key into this collection. This field is used to store the virtual table function instances associated with this module. The case-insensitive function name and the number of arguments (with -1 meaning "any") are used to construct the string that is used to key into this collection. Constructs an instance of this class. The name of the module. This parameter cannot be null. Calls the native SQLite core library in order to create a new disposable module containing the implementation of a virtual table. The native database connection pointer to use. Non-zero upon success. This method is called by the SQLite core library when the native module associated with this object instance is being destroyed due to its parent connection being closed. It may also be called by the "vtshim" module if/when the sqlite3_dispose_module() function is called. The native user-data pointer associated with this module, as it was provided to the SQLite core library when the native module instance was created. Creates and returns the native sqlite_module structure using the configured (or default) interface implementation. The native sqlite_module structure using the configured (or default) interface implementation. Creates and returns the native sqlite_module structure using the specified interface implementation. The interface implementation to use. The native sqlite_module structure using the specified interface implementation. Creates a copy of the specified object instance, using default implementations for the contained delegates when necessary. The object instance to copy. The new object instance. Calls one of the virtual table initialization methods. Non-zero to call the method; otherwise, the method will be called. The native database connection handle. The original native pointer value that was provided to the sqlite3_create_module(), sqlite3_create_module_v2() or sqlite3_create_disposable_module() functions. The number of arguments from the CREATE VIRTUAL TABLE statement. The array of string arguments from the CREATE VIRTUAL TABLE statement. Upon success, this parameter must be modified to point to the newly created native sqlite3_vtab derived structure. Upon failure, this parameter must be modified to point to the error message, with the underlying memory having been obtained from the sqlite3_malloc() function. A standard SQLite return code. Calls one of the virtual table finalization methods. Non-zero to call the method; otherwise, the method will be called. The native pointer to the sqlite3_vtab derived structure. A standard SQLite return code. Arranges for the specified error message to be placed into the zErrMsg field of a sqlite3_vtab derived structure, freeing the existing error message, if any. The object instance to be used. The native pointer to the sqlite3_vtab derived structure. Non-zero if this error message should also be logged using the class. Non-zero if caught exceptions should be logged using the class. The error message. Non-zero upon success. Arranges for the specified error message to be placed into the zErrMsg field of a sqlite3_vtab derived structure, freeing the existing error message, if any. The object instance to be used. The object instance used to lookup the native pointer to the sqlite3_vtab derived structure. Non-zero if this error message should also be logged using the class. Non-zero if caught exceptions should be logged using the class. The error message. Non-zero upon success. Arranges for the specified error message to be placed into the zErrMsg field of a sqlite3_vtab derived structure, freeing the existing error message, if any. The object instance to be used. The native pointer to the sqlite3_vtab_cursor derived structure used to get the native pointer to the sqlite3_vtab derived structure. Non-zero if this error message should also be logged using the class. Non-zero if caught exceptions should be logged using the class. The error message. Non-zero upon success. Arranges for the specified error message to be placed into the zErrMsg field of a sqlite3_vtab derived structure, freeing the existing error message, if any. The object instance to be used. The object instance used to lookup the native pointer to the sqlite3_vtab derived structure. Non-zero if this error message should also be logged using the class. Non-zero if caught exceptions should be logged using the class. The error message. Non-zero upon success. Gets and returns the interface implementation to be used when creating the native sqlite3_module structure. Derived classes may override this method to supply an alternate implementation for the interface. The interface implementation to be used when populating the native sqlite3_module structure. If the returned value is null, the private methods provided by the class and relating to the interface will be used to create the necessary delegates. Creates and returns the interface implementation corresponding to the current object instance. The interface implementation corresponding to the current object instance. Allocates a native sqlite3_vtab derived structure and returns a native pointer to it. A native pointer to a native sqlite3_vtab derived structure. Zeros out the fields of a native sqlite3_vtab derived structure. The native pointer to the native sqlite3_vtab derived structure to zero. Frees a native sqlite3_vtab structure using the provided native pointer to it. A native pointer to a native sqlite3_vtab derived structure. Allocates a native sqlite3_vtab_cursor derived structure and returns a native pointer to it. A native pointer to a native sqlite3_vtab_cursor derived structure. Frees a native sqlite3_vtab_cursor structure using the provided native pointer to it. A native pointer to a native sqlite3_vtab_cursor derived structure. Reads and returns the native pointer to the sqlite3_vtab derived structure based on the native pointer to the sqlite3_vtab_cursor derived structure. The object instance to be used. The native pointer to the sqlite3_vtab_cursor derived structure from which to read the native pointer to the sqlite3_vtab derived structure. The native pointer to the sqlite3_vtab derived structure -OR- if it cannot be determined. Reads and returns the native pointer to the sqlite3_vtab derived structure based on the native pointer to the sqlite3_vtab_cursor derived structure. The native pointer to the sqlite3_vtab_cursor derived structure from which to read the native pointer to the sqlite3_vtab derived structure. The native pointer to the sqlite3_vtab derived structure -OR- if it cannot be determined. Looks up and returns the object instance based on the native pointer to the sqlite3_vtab derived structure. The native pointer to the sqlite3_vtab derived structure. The object instance or null if the corresponding one cannot be found. Allocates and returns a native pointer to a sqlite3_vtab derived structure and creates an association between it and the specified object instance. The object instance to be used when creating the association. The native pointer to a sqlite3_vtab derived structure or if the method fails for any reason. Looks up and returns the object instance based on the native pointer to the sqlite3_vtab_cursor derived structure. The native pointer to the sqlite3_vtab derived structure. The native pointer to the sqlite3_vtab_cursor derived structure. The object instance or null if the corresponding one cannot be found. Allocates and returns a native pointer to a sqlite3_vtab_cursor derived structure and creates an association between it and the specified object instance. The object instance to be used when creating the association. The native pointer to a sqlite3_vtab_cursor derived structure or if the method fails for any reason. Deterimines the key that should be used to identify and store the object instance for the virtual table (i.e. to be returned via the method). The number of arguments to the virtual table function. The name of the virtual table function. The object instance associated with this virtual table function. The string that should be used to identify and store the virtual table function instance. This method cannot return null. If null is returned from this method, the behavior is undefined. Attempts to declare the schema for the virtual table using the specified database connection. The object instance to use when declaring the schema of the virtual table. This parameter may not be null. The string containing the CREATE TABLE statement that completely describes the schema for the virtual table. This parameter may not be null. Upon failure, this parameter must be modified to contain an error message. A standard SQLite return code. Calls the native SQLite core library in order to declare a virtual table function in response to a call into the or virtual table methods. The object instance to use when declaring the schema of the virtual table. The number of arguments to the function being declared. The name of the function being declared. Upon success, the contents of this parameter are undefined. Upon failure, it should contain an appropriate error message. A standard SQLite return code. Arranges for the specified error message to be placed into the zErrMsg field of a sqlite3_vtab derived structure, freeing the existing error message, if any. The native pointer to the sqlite3_vtab derived structure. The error message. Non-zero upon success. Arranges for the specified error message to be placed into the zErrMsg field of a sqlite3_vtab derived structure, freeing the existing error message, if any. The object instance used to lookup the native pointer to the sqlite3_vtab derived structure. The error message. Non-zero upon success. Arranges for the specified error message to be placed into the zErrMsg field of a sqlite3_vtab derived structure, freeing the existing error message, if any. The object instance used to lookup the native pointer to the sqlite3_vtab derived structure. The error message. Non-zero upon success. Modifies the specified object instance to contain the specified estimated cost. The object instance to modify. The estimated cost value to use. Using a null value means that the default value provided by the SQLite core library should be used. Non-zero upon success. Modifies the specified object instance to contain the default estimated cost. The object instance to modify. Non-zero upon success. Modifies the specified object instance to contain the specified estimated rows. The object instance to modify. The estimated rows value to use. Using a null value means that the default value provided by the SQLite core library should be used. Non-zero upon success. Modifies the specified object instance to contain the default estimated rows. The object instance to modify. Non-zero upon success. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. This method is called in response to the method. The object instance associated with the virtual table. The native user-data pointer associated with this module, as it was provided to the SQLite core library when the native module instance was created. The module name, database name, virtual table name, and all other arguments passed to the CREATE VIRTUAL TABLE statement. Upon success, this parameter must be modified to contain the object instance associated with the virtual table. Upon failure, this parameter must be modified to contain an error message. A standard SQLite return code. This method is called in response to the method. The object instance associated with the virtual table. The native user-data pointer associated with this module, as it was provided to the SQLite core library when the native module instance was created. The module name, database name, virtual table name, and all other arguments passed to the CREATE VIRTUAL TABLE statement. Upon success, this parameter must be modified to contain the object instance associated with the virtual table. Upon failure, this parameter must be modified to contain an error message. A standard SQLite return code. This method is called in response to the method. The object instance associated with this virtual table. The object instance containing all the data for the inputs and outputs relating to index selection. A standard SQLite return code. This method is called in response to the method. The object instance associated with this virtual table. A standard SQLite return code. This method is called in response to the method. The object instance associated with this virtual table. A standard SQLite return code. This method is called in response to the method. The object instance associated with this virtual table. Upon success, this parameter must be modified to contain the object instance associated with the newly opened virtual table cursor. A standard SQLite return code. This method is called in response to the method. The object instance associated with the previously opened virtual table cursor to be used. A standard SQLite return code. This method is called in response to the method. The object instance associated with the previously opened virtual table cursor to be used. Number used to help identify the selected index. String used to help identify the selected index. The values corresponding to each column in the selected index. A standard SQLite return code. This method is called in response to the method. The object instance associated with the previously opened virtual table cursor to be used. A standard SQLite return code. This method is called in response to the method. The object instance associated with the previously opened virtual table cursor to be used. Non-zero if no more rows are available; zero otherwise. This method is called in response to the method. The object instance associated with the previously opened virtual table cursor to be used. The object instance to be used for returning the specified column value to the SQLite core library. The zero-based index corresponding to the column containing the value to be returned. A standard SQLite return code. This method is called in response to the method. The object instance associated with the previously opened virtual table cursor to be used. Upon success, this parameter must be modified to contain the unique integer row identifier for the current row for the specified cursor. A standard SQLite return code. This method is called in response to the method. The object instance associated with this virtual table. The array of object instances containing the new or modified column values, if any. Upon success, this parameter must be modified to contain the unique integer row identifier for the row that was inserted, if any. A standard SQLite return code. This method is called in response to the method. The object instance associated with this virtual table. A standard SQLite return code. This method is called in response to the method. The object instance associated with this virtual table. A standard SQLite return code. This method is called in response to the method. The object instance associated with this virtual table. A standard SQLite return code. This method is called in response to the method. The object instance associated with this virtual table. A standard SQLite return code. This method is called in response to the method. The object instance associated with this virtual table. The number of arguments to the function being sought. The name of the function being sought. Upon success, this parameter must be modified to contain the object instance responsible for implementing the specified function. Upon success, this parameter must be modified to contain the native user-data pointer associated with . Non-zero if the specified function was found; zero otherwise. This method is called in response to the method. The object instance associated with this virtual table. The new name for the virtual table. A standard SQLite return code. This method is called in response to the method. The object instance associated with this virtual table. This is an integer identifier under which the the current state of the virtual table should be saved. A standard SQLite return code. This method is called in response to the method. The object instance associated with this virtual table. This is an integer used to indicate that any saved states with an identifier greater than or equal to this should be deleted by the virtual table. A standard SQLite return code. This method is called in response to the method. The object instance associated with this virtual table. This is an integer identifier used to specify a specific saved state for the virtual table for it to restore itself back to, which should also have the effect of deleting all saved states with an integer identifier greater than this one. A standard SQLite return code. Disposes of this object instance. Throws an if this object instance has been disposed. Disposes of this object instance. Non-zero if this method is being called from the method. Zero if this method is being called from the finalizer. Finalizes this object instance. Returns or sets a boolean value indicating whether virtual table errors should be logged using the class. Returns or sets a boolean value indicating whether exceptions caught in the method, the method, the method, the method, and the method should be logged using the class. Returns or sets a boolean value indicating whether virtual table errors should be logged using the class. Returns or sets a boolean value indicating whether exceptions caught in the method, method, and the method should be logged using the class. Returns non-zero if the schema for the virtual table has been declared. Returns the name of the module as it was registered with the SQLite core library. This class implements the interface by forwarding those method calls to the object instance it contains. If the contained object instance is null, all the methods simply generate an error. This is the value that is always used for the "logErrors" parameter to the various static error handling methods provided by the class. This is the value that is always used for the "logExceptions" parameter to the various static error handling methods provided by the class. This is the error message text used when the contained object instance is not available for any reason. The object instance used to provide an implementation of the interface. Constructs an instance of this class. The object instance used to provide an implementation of the interface. Sets the table error message to one that indicates the native module implementation is not available. The native pointer to the sqlite3_vtab derived structure. The value of . Sets the table error message to one that indicates the native module implementation is not available. The native pointer to the sqlite3_vtab_cursor derived structure. The value of . See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. Disposes of this object instance. Throws an if this object instance has been disposed. Disposes of this object instance. Non-zero if this method is being called from the method. Zero if this method is being called from the finalizer. Finalizes this object instance. This class represents a virtual table cursor to be used with the class. It is not sealed and may be used as the base class for any user-defined virtual table cursor class that wraps an object instance. The instance provided when this cursor was created. This value will be non-zero if false has been returned from the method. Constructs an instance of this class. The object instance associated with this object instance. The instance to expose as a virtual table cursor. Advances to the next row of the virtual table cursor using the method of the object instance. Non-zero if the current row is valid; zero otherwise. If zero is returned, no further rows are available. Resets the virtual table cursor position, also invalidating the current row, using the method of the object instance. Closes the virtual table cursor. This method must not throw any exceptions. Throws an if the virtual table cursor has been closed. Throws an if this object instance has been disposed. Disposes of this object instance. Non-zero if this method is being called from the method. Zero if this method is being called from the finalizer. Returns the value for the current row of the virtual table cursor using the property of the object instance. Returns non-zero if the end of the virtual table cursor has been seen (i.e. no more rows are available, including the current one). Returns non-zero if the virtual table cursor is open. This class implements a virtual table module that exposes an object instance as a read-only virtual table. It is not sealed and may be used as the base class for any user-defined virtual table class that wraps an object instance. The following short example shows it being used to treat an array of strings as a table data source: public static class Sample { public static void Main() { using (SQLiteConnection connection = new SQLiteConnection( "Data Source=:memory:;")) { connection.Open(); connection.CreateModule(new SQLiteModuleEnumerable( "sampleModule", new string[] { "one", "two", "three" })); using (SQLiteCommand command = connection.CreateCommand()) { command.CommandText = "CREATE VIRTUAL TABLE t1 USING sampleModule;"; command.ExecuteNonQuery(); } using (SQLiteCommand command = connection.CreateCommand()) { command.CommandText = "SELECT * FROM t1;"; using (SQLiteDataReader dataReader = command.ExecuteReader()) { while (dataReader.Read()) Console.WriteLine(dataReader[0].ToString()); } } connection.Close(); } } } This class implements a virtual table module that does nothing by providing "empty" implementations for all of the interface methods. The result codes returned by these "empty" method implementations may be controlled on a per-method basis by using and/or overriding the , , , , and methods from within derived classes. This field is used to store the values to return, on a per-method basis, for all methods that are part of the interface. Constructs an instance of this class. The name of the module. This parameter cannot be null. Determines the default value to be returned by methods of the interface that lack an overridden implementation in all classes derived from the class. The value that should be returned by all interface methods unless a more specific result code has been set for that interface method. Converts a value into a boolean return value for use with the method. The value to convert. The value. Converts a value into a boolean return value for use with the method. The value to convert. The value. Determines the value that should be returned by the specified interface method if it lack an overridden implementation. If no specific value is available (or set) for the specified method, the value returned by the method will be returned instead. The name of the method. Currently, this method must be part of the interface. The value that should be returned by the interface method. Sets the value that should be returned by the specified interface method if it lack an overridden implementation. The name of the method. Currently, this method must be part of the interface. The value that should be returned by the interface method. Non-zero upon success. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. Throws an if this object instance has been disposed. Disposes of this object instance. Non-zero if this method is being called from the method. Zero if this method is being called from the finalizer. The CREATE TABLE statement used to declare the schema for the virtual table. The instance containing the backing data for the virtual table. Non-zero if different object instances with the same value should generate different row identifiers, where applicable. This has no effect on the .NET Compact Framework. Constructs an instance of this class. The name of the module. This parameter cannot be null. The instance to expose as a virtual table. This parameter cannot be null. Constructs an instance of this class. The name of the module. This parameter cannot be null. The instance to expose as a virtual table. This parameter cannot be null. Non-zero if different object instances with the same value should generate different row identifiers, where applicable. This parameter has no effect on the .NET Compact Framework. Determines the SQL statement used to declare the virtual table. This method should be overridden in derived classes if they require a custom virtual table schema. The SQL statement used to declare the virtual table -OR- null if it cannot be determined. Sets the table error message to one that indicates the virtual table cursor is of the wrong type. The object instance. The value of . Sets the table error message to one that indicates the virtual table cursor has no current row. The object instance. The value of . Determines the string to return as the column value for the object instance value. The object instance associated with the previously opened virtual table cursor to be used. The object instance to return a string representation for. The string representation of the specified object instance or null upon failure. Constructs an unique row identifier from two values. The first value must contain the row sequence number for the current row and the second value must contain the hash code of the enumerator value for the current row. The integer row sequence number for the current row. The hash code of the enumerator value for the current row. The unique row identifier or zero upon failure. Determines the unique row identifier for the current row. The object instance associated with the previously opened virtual table cursor to be used. The object instance to return a unique row identifier for. The unique row identifier or zero upon failure. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. Throws an if this object instance has been disposed. Disposes of this object instance. Non-zero if this method is being called from the method. Zero if this method is being called from the finalizer. This class represents a virtual table cursor to be used with the class. It is not sealed and may be used as the base class for any user-defined virtual table cursor class that wraps an object instance. The instance provided when this cursor was created. Constructs an instance of this class. The object instance associated with this object instance. The instance to expose as a virtual table cursor. Closes the virtual table cursor. This method must not throw any exceptions. Throws an if this object instance has been disposed. Disposes of this object instance. Non-zero if this method is being called from the method. Zero if this method is being called from the finalizer. Returns the value for the current row of the virtual table cursor using the property of the object instance. This class implements a virtual table module that exposes an object instance as a read-only virtual table. It is not sealed and may be used as the base class for any user-defined virtual table class that wraps an object instance. The instance containing the backing data for the virtual table. Constructs an instance of this class. The name of the module. This parameter cannot be null. The instance to expose as a virtual table. This parameter cannot be null. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. See the method. Throws an if this object instance has been disposed. Disposes of this object instance. Non-zero if this method is being called from the method. Zero if this method is being called from the finalizer.
================================================ FILE: library/packages.config ================================================  ================================================ FILE: pkmn-classic-framework.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.32126.315 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Library", "library\Library.csproj", "{408EFC7E-C6B0-4160-8628-2679E34385CE}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "gts", "gts\gts.csproj", "{2EEAF2A8-68B7-4DB5-8818-36285D5CF9B3}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "bvCrawler4", "bvCrawler4\bvCrawler4.csproj", "{04E4EB3B-166B-4D8B-86AA-2178F2A927D5}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "bvCrawler5", "bvCrawler5\bvCrawler5.csproj", "{BEA49E66-2204-4C10-8ED6-17F58018C2BD}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GlobalTerminalService", "GlobalTerminalService\GlobalTerminalService.csproj", "{7AB1A65F-3AD1-4356-94E7-F1A669BF4CE0}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "bvRestorer4", "bvRestorer4\bvRestorer4.csproj", "{5174CBF0-2A5D-466B-BC32-CE53B9AC4EAF}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "bvRestorer5", "bvRestorer5\bvRestorer5.csproj", "{9F2A0A44-B90E-4B30-8DFF-2B5E273F5BEC}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "towerRestorer", "towerRestorer4\towerRestorer.csproj", "{750A0BFD-7258-4B32-A4F9-60EEEB0BA64A}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GamestatsBase", "GamestatsBase\GamestatsBase\GamestatsBase.csproj", "{2D667F5B-F10D-44E2-93F6-DD555D9EE7DF}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VeekunImport", "VeekunImport\VeekunImport.csproj", "{2A761C4F-00C2-45D5-B4CA-C41558CEB2DF}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MakeBaseStatTables", "MakeBaseStatTables\MakeBaseStatTables.csproj", "{99FCBB1C-D94F-458D-ABD2-8800FBDC65DA}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "web", "web\web.csproj", "{3DE4D97F-57A8-4324-B5B8-164B45E2DF9A}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RenameImages", "RenameImages\RenameImages.csproj", "{D8787475-2D21-4E60-9320-13FA55C979AC}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{A0D01A86-7F0C-44C4-9B44-8E45C116590B}" ProjectSection(SolutionItems) = preProject .gitignore = .gitignore LICENSE.md = LICENSE.md README.md = README.md Roadmap.md = Roadmap.md EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|Mixed Platforms = Debug|Mixed Platforms Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU Release|Mixed Platforms = Release|Mixed Platforms Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {408EFC7E-C6B0-4160-8628-2679E34385CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {408EFC7E-C6B0-4160-8628-2679E34385CE}.Debug|Any CPU.Build.0 = Debug|Any CPU {408EFC7E-C6B0-4160-8628-2679E34385CE}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {408EFC7E-C6B0-4160-8628-2679E34385CE}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {408EFC7E-C6B0-4160-8628-2679E34385CE}.Debug|x86.ActiveCfg = Debug|Any CPU {408EFC7E-C6B0-4160-8628-2679E34385CE}.Release|Any CPU.ActiveCfg = Release|Any CPU {408EFC7E-C6B0-4160-8628-2679E34385CE}.Release|Any CPU.Build.0 = Release|Any CPU {408EFC7E-C6B0-4160-8628-2679E34385CE}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {408EFC7E-C6B0-4160-8628-2679E34385CE}.Release|Mixed Platforms.Build.0 = Release|Any CPU {408EFC7E-C6B0-4160-8628-2679E34385CE}.Release|x86.ActiveCfg = Release|Any CPU {2EEAF2A8-68B7-4DB5-8818-36285D5CF9B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2EEAF2A8-68B7-4DB5-8818-36285D5CF9B3}.Debug|Any CPU.Build.0 = Debug|Any CPU {2EEAF2A8-68B7-4DB5-8818-36285D5CF9B3}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {2EEAF2A8-68B7-4DB5-8818-36285D5CF9B3}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {2EEAF2A8-68B7-4DB5-8818-36285D5CF9B3}.Debug|x86.ActiveCfg = Debug|Any CPU {2EEAF2A8-68B7-4DB5-8818-36285D5CF9B3}.Release|Any CPU.ActiveCfg = Release|Any CPU {2EEAF2A8-68B7-4DB5-8818-36285D5CF9B3}.Release|Any CPU.Build.0 = Release|Any CPU {2EEAF2A8-68B7-4DB5-8818-36285D5CF9B3}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {2EEAF2A8-68B7-4DB5-8818-36285D5CF9B3}.Release|Mixed Platforms.Build.0 = Release|Any CPU {2EEAF2A8-68B7-4DB5-8818-36285D5CF9B3}.Release|x86.ActiveCfg = Release|Any CPU {04E4EB3B-166B-4D8B-86AA-2178F2A927D5}.Debug|Any CPU.ActiveCfg = Debug|x86 {04E4EB3B-166B-4D8B-86AA-2178F2A927D5}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 {04E4EB3B-166B-4D8B-86AA-2178F2A927D5}.Debug|Mixed Platforms.Build.0 = Debug|x86 {04E4EB3B-166B-4D8B-86AA-2178F2A927D5}.Debug|x86.ActiveCfg = Debug|x86 {04E4EB3B-166B-4D8B-86AA-2178F2A927D5}.Debug|x86.Build.0 = Debug|x86 {04E4EB3B-166B-4D8B-86AA-2178F2A927D5}.Release|Any CPU.ActiveCfg = Release|x86 {04E4EB3B-166B-4D8B-86AA-2178F2A927D5}.Release|Mixed Platforms.ActiveCfg = Release|x86 {04E4EB3B-166B-4D8B-86AA-2178F2A927D5}.Release|Mixed Platforms.Build.0 = Release|x86 {04E4EB3B-166B-4D8B-86AA-2178F2A927D5}.Release|x86.ActiveCfg = Release|x86 {04E4EB3B-166B-4D8B-86AA-2178F2A927D5}.Release|x86.Build.0 = Release|x86 {BEA49E66-2204-4C10-8ED6-17F58018C2BD}.Debug|Any CPU.ActiveCfg = Debug|x86 {BEA49E66-2204-4C10-8ED6-17F58018C2BD}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 {BEA49E66-2204-4C10-8ED6-17F58018C2BD}.Debug|Mixed Platforms.Build.0 = Debug|x86 {BEA49E66-2204-4C10-8ED6-17F58018C2BD}.Debug|x86.ActiveCfg = Debug|x86 {BEA49E66-2204-4C10-8ED6-17F58018C2BD}.Debug|x86.Build.0 = Debug|x86 {BEA49E66-2204-4C10-8ED6-17F58018C2BD}.Release|Any CPU.ActiveCfg = Release|x86 {BEA49E66-2204-4C10-8ED6-17F58018C2BD}.Release|Mixed Platforms.ActiveCfg = Release|x86 {BEA49E66-2204-4C10-8ED6-17F58018C2BD}.Release|Mixed Platforms.Build.0 = Release|x86 {BEA49E66-2204-4C10-8ED6-17F58018C2BD}.Release|x86.ActiveCfg = Release|x86 {BEA49E66-2204-4C10-8ED6-17F58018C2BD}.Release|x86.Build.0 = Release|x86 {7AB1A65F-3AD1-4356-94E7-F1A669BF4CE0}.Debug|Any CPU.ActiveCfg = Debug|x86 {7AB1A65F-3AD1-4356-94E7-F1A669BF4CE0}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 {7AB1A65F-3AD1-4356-94E7-F1A669BF4CE0}.Debug|Mixed Platforms.Build.0 = Debug|x86 {7AB1A65F-3AD1-4356-94E7-F1A669BF4CE0}.Debug|x86.ActiveCfg = Debug|x86 {7AB1A65F-3AD1-4356-94E7-F1A669BF4CE0}.Debug|x86.Build.0 = Debug|x86 {7AB1A65F-3AD1-4356-94E7-F1A669BF4CE0}.Release|Any CPU.ActiveCfg = Release|x86 {7AB1A65F-3AD1-4356-94E7-F1A669BF4CE0}.Release|Mixed Platforms.ActiveCfg = Release|x86 {7AB1A65F-3AD1-4356-94E7-F1A669BF4CE0}.Release|Mixed Platforms.Build.0 = Release|x86 {7AB1A65F-3AD1-4356-94E7-F1A669BF4CE0}.Release|x86.ActiveCfg = Release|x86 {7AB1A65F-3AD1-4356-94E7-F1A669BF4CE0}.Release|x86.Build.0 = Release|x86 {5174CBF0-2A5D-466B-BC32-CE53B9AC4EAF}.Debug|Any CPU.ActiveCfg = Debug|x86 {5174CBF0-2A5D-466B-BC32-CE53B9AC4EAF}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 {5174CBF0-2A5D-466B-BC32-CE53B9AC4EAF}.Debug|Mixed Platforms.Build.0 = Debug|x86 {5174CBF0-2A5D-466B-BC32-CE53B9AC4EAF}.Debug|x86.ActiveCfg = Debug|x86 {5174CBF0-2A5D-466B-BC32-CE53B9AC4EAF}.Debug|x86.Build.0 = Debug|x86 {5174CBF0-2A5D-466B-BC32-CE53B9AC4EAF}.Release|Any CPU.ActiveCfg = Release|x86 {5174CBF0-2A5D-466B-BC32-CE53B9AC4EAF}.Release|Mixed Platforms.ActiveCfg = Release|x86 {5174CBF0-2A5D-466B-BC32-CE53B9AC4EAF}.Release|Mixed Platforms.Build.0 = Release|x86 {5174CBF0-2A5D-466B-BC32-CE53B9AC4EAF}.Release|x86.ActiveCfg = Release|x86 {5174CBF0-2A5D-466B-BC32-CE53B9AC4EAF}.Release|x86.Build.0 = Release|x86 {9F2A0A44-B90E-4B30-8DFF-2B5E273F5BEC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9F2A0A44-B90E-4B30-8DFF-2B5E273F5BEC}.Debug|Any CPU.Build.0 = Debug|Any CPU {9F2A0A44-B90E-4B30-8DFF-2B5E273F5BEC}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {9F2A0A44-B90E-4B30-8DFF-2B5E273F5BEC}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {9F2A0A44-B90E-4B30-8DFF-2B5E273F5BEC}.Debug|x86.ActiveCfg = Debug|Any CPU {9F2A0A44-B90E-4B30-8DFF-2B5E273F5BEC}.Release|Any CPU.ActiveCfg = Release|Any CPU {9F2A0A44-B90E-4B30-8DFF-2B5E273F5BEC}.Release|Any CPU.Build.0 = Release|Any CPU {9F2A0A44-B90E-4B30-8DFF-2B5E273F5BEC}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {9F2A0A44-B90E-4B30-8DFF-2B5E273F5BEC}.Release|Mixed Platforms.Build.0 = Release|Any CPU {9F2A0A44-B90E-4B30-8DFF-2B5E273F5BEC}.Release|x86.ActiveCfg = Release|Any CPU {750A0BFD-7258-4B32-A4F9-60EEEB0BA64A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {750A0BFD-7258-4B32-A4F9-60EEEB0BA64A}.Debug|Any CPU.Build.0 = Debug|Any CPU {750A0BFD-7258-4B32-A4F9-60EEEB0BA64A}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {750A0BFD-7258-4B32-A4F9-60EEEB0BA64A}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {750A0BFD-7258-4B32-A4F9-60EEEB0BA64A}.Debug|x86.ActiveCfg = Debug|Any CPU {750A0BFD-7258-4B32-A4F9-60EEEB0BA64A}.Release|Any CPU.ActiveCfg = Release|Any CPU {750A0BFD-7258-4B32-A4F9-60EEEB0BA64A}.Release|Any CPU.Build.0 = Release|Any CPU {750A0BFD-7258-4B32-A4F9-60EEEB0BA64A}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {750A0BFD-7258-4B32-A4F9-60EEEB0BA64A}.Release|Mixed Platforms.Build.0 = Release|Any CPU {750A0BFD-7258-4B32-A4F9-60EEEB0BA64A}.Release|x86.ActiveCfg = Release|Any CPU {2D667F5B-F10D-44E2-93F6-DD555D9EE7DF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2D667F5B-F10D-44E2-93F6-DD555D9EE7DF}.Debug|Any CPU.Build.0 = Debug|Any CPU {2D667F5B-F10D-44E2-93F6-DD555D9EE7DF}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {2D667F5B-F10D-44E2-93F6-DD555D9EE7DF}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {2D667F5B-F10D-44E2-93F6-DD555D9EE7DF}.Debug|x86.ActiveCfg = Debug|Any CPU {2D667F5B-F10D-44E2-93F6-DD555D9EE7DF}.Release|Any CPU.ActiveCfg = Release|Any CPU {2D667F5B-F10D-44E2-93F6-DD555D9EE7DF}.Release|Any CPU.Build.0 = Release|Any CPU {2D667F5B-F10D-44E2-93F6-DD555D9EE7DF}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {2D667F5B-F10D-44E2-93F6-DD555D9EE7DF}.Release|Mixed Platforms.Build.0 = Release|Any CPU {2D667F5B-F10D-44E2-93F6-DD555D9EE7DF}.Release|x86.ActiveCfg = Release|Any CPU {2A761C4F-00C2-45D5-B4CA-C41558CEB2DF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2A761C4F-00C2-45D5-B4CA-C41558CEB2DF}.Debug|Any CPU.Build.0 = Debug|Any CPU {2A761C4F-00C2-45D5-B4CA-C41558CEB2DF}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {2A761C4F-00C2-45D5-B4CA-C41558CEB2DF}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {2A761C4F-00C2-45D5-B4CA-C41558CEB2DF}.Debug|x86.ActiveCfg = Debug|Any CPU {2A761C4F-00C2-45D5-B4CA-C41558CEB2DF}.Release|Any CPU.ActiveCfg = Release|Any CPU {2A761C4F-00C2-45D5-B4CA-C41558CEB2DF}.Release|Any CPU.Build.0 = Release|Any CPU {2A761C4F-00C2-45D5-B4CA-C41558CEB2DF}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {2A761C4F-00C2-45D5-B4CA-C41558CEB2DF}.Release|Mixed Platforms.Build.0 = Release|Any CPU {2A761C4F-00C2-45D5-B4CA-C41558CEB2DF}.Release|x86.ActiveCfg = Release|Any CPU {99FCBB1C-D94F-458D-ABD2-8800FBDC65DA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {99FCBB1C-D94F-458D-ABD2-8800FBDC65DA}.Debug|Any CPU.Build.0 = Debug|Any CPU {99FCBB1C-D94F-458D-ABD2-8800FBDC65DA}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {99FCBB1C-D94F-458D-ABD2-8800FBDC65DA}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {99FCBB1C-D94F-458D-ABD2-8800FBDC65DA}.Debug|x86.ActiveCfg = Debug|Any CPU {99FCBB1C-D94F-458D-ABD2-8800FBDC65DA}.Release|Any CPU.ActiveCfg = Release|Any CPU {99FCBB1C-D94F-458D-ABD2-8800FBDC65DA}.Release|Any CPU.Build.0 = Release|Any CPU {99FCBB1C-D94F-458D-ABD2-8800FBDC65DA}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {99FCBB1C-D94F-458D-ABD2-8800FBDC65DA}.Release|Mixed Platforms.Build.0 = Release|Any CPU {99FCBB1C-D94F-458D-ABD2-8800FBDC65DA}.Release|x86.ActiveCfg = Release|Any CPU {3DE4D97F-57A8-4324-B5B8-164B45E2DF9A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {3DE4D97F-57A8-4324-B5B8-164B45E2DF9A}.Debug|Any CPU.Build.0 = Debug|Any CPU {3DE4D97F-57A8-4324-B5B8-164B45E2DF9A}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {3DE4D97F-57A8-4324-B5B8-164B45E2DF9A}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {3DE4D97F-57A8-4324-B5B8-164B45E2DF9A}.Debug|x86.ActiveCfg = Debug|Any CPU {3DE4D97F-57A8-4324-B5B8-164B45E2DF9A}.Release|Any CPU.ActiveCfg = Release|Any CPU {3DE4D97F-57A8-4324-B5B8-164B45E2DF9A}.Release|Any CPU.Build.0 = Release|Any CPU {3DE4D97F-57A8-4324-B5B8-164B45E2DF9A}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {3DE4D97F-57A8-4324-B5B8-164B45E2DF9A}.Release|Mixed Platforms.Build.0 = Release|Any CPU {3DE4D97F-57A8-4324-B5B8-164B45E2DF9A}.Release|x86.ActiveCfg = Release|Any CPU {D8787475-2D21-4E60-9320-13FA55C979AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D8787475-2D21-4E60-9320-13FA55C979AC}.Debug|Any CPU.Build.0 = Debug|Any CPU {D8787475-2D21-4E60-9320-13FA55C979AC}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {D8787475-2D21-4E60-9320-13FA55C979AC}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {D8787475-2D21-4E60-9320-13FA55C979AC}.Debug|x86.ActiveCfg = Debug|Any CPU {D8787475-2D21-4E60-9320-13FA55C979AC}.Debug|x86.Build.0 = Debug|Any CPU {D8787475-2D21-4E60-9320-13FA55C979AC}.Release|Any CPU.ActiveCfg = Release|Any CPU {D8787475-2D21-4E60-9320-13FA55C979AC}.Release|Any CPU.Build.0 = Release|Any CPU {D8787475-2D21-4E60-9320-13FA55C979AC}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {D8787475-2D21-4E60-9320-13FA55C979AC}.Release|Mixed Platforms.Build.0 = Release|Any CPU {D8787475-2D21-4E60-9320-13FA55C979AC}.Release|x86.ActiveCfg = Release|Any CPU {D8787475-2D21-4E60-9320-13FA55C979AC}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {B86878C4-9F17-469B-B51C-4CB1030489AA} EndGlobalSection EndGlobal ================================================ FILE: pokedex/Shiny lock generations.txt ================================================ NatDex Name No ribbon including Wiimmfi events No ribbon full legal Any including ribbons 251 Celebi 7 7 7 493 Arceus 4 8 6 494 Victini x x x 643 Reshiram 6 6 6 644 Zekrom 6 6 6 647 Keldeo x x x 648 Meloetta x x x 649 Genesect x x 5 716 Xerneas 7 7 6 717 Yveltal 7 7 6 718 Zygarde 8 8 7 719 Diancie x x 6 720 Hoopa x x x 721 Volcanion x x x 785 Tapu Koko 8 8 7 786 Tapu Lele 8 8 7 787 Tapu Bulu 8 8 7 788 Tapu Fini 8 8 7 789 Cosmog x x x 790 Cosmoem x x x 791 Solgaleo 8 8 7 792 Lunala 8 8 7 800 Necrozma 8 8 7 801 Magearna x x 8 802 Marshadow x x x 807 Zeraora x x 8 Cap pikas other than Partner Cap are shiny locked. Ash Greninja is shiny locked. Event Vivillons are shiny locked until Fancy in SV. ================================================ FILE: towerRestorer4/App.config ================================================ ================================================ FILE: towerRestorer4/Program.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using PkmnFoundations.Data; using PkmnFoundations.Pokedex; using PkmnFoundations.Structures; using PkmnFoundations.Support; using PkmnFoundations.Wfc; namespace towerRestorer { class Program { static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Usage: towerRestorer4 "); Console.WriteLine("Attempts to insert files in "); Console.WriteLine("into the database in app configuration."); Console.WriteLine("Only inserts files whose names match the naming pattern:"); Console.WriteLine("g*_pid*_rank*_room*"); Console.WriteLine("Rank and room number are taken from the filename."); return; } Database db = Database.Instance; String[] filenames = Directory.GetFiles(args[0]); int successCount = 0; int failureCount = 0; int opponentSuccessCount = 0; int opponentFailureCount = 0; int leaderSuccessCount = 0; int leaderFailureCount = 0; Pokedex pokedex = new Pokedex(db, false); foreach (String s in filenames) { String filename = s; int slashIndex = filename.LastIndexOf(Path.DirectorySeparatorChar); if (slashIndex >= 0) { filename = filename.Substring(slashIndex + 1); } int dotIndex = filename.LastIndexOf('.'); if (dotIndex >= 0) { filename = filename.Substring(0, dotIndex); } String[] split = filename.Split('_'); byte rank, room; if (split.Length != 4 || (split[0] != "g4" && split[0] != "g5") || split[2].Substring(0, 4) != "rank" || !Byte.TryParse(split[2].Substring(4), out rank) || split[3].Substring(0, 4) != "room" || !Byte.TryParse(split[3].Substring(4), out room) ) { Console.WriteLine("{0}: Filename pattern does not match, skipped.", filename); failureCount++; continue; } int gen = Convert.ToInt32(split[0].Substring(1)); rank--; room--; switch (gen) { case 4: { FileStream fs = File.OpenRead(s); if (fs.Length != 0xa38) { Console.WriteLine("{0}: file size is wrong, skipped.", filename); failureCount++; continue; } byte[] data = new byte[0xa38]; fs.ReadBlock(data, 0, 0xa38); fs.Close(); // battletower/download.asp response: 2616 bytes // 00-63b: BattleTowerRecord objects x7 // 63c-a37: BattleTowerTrainerProfile objects x30 for (int x = 0; x < 7; x++) { try { BattleTowerRecord4 record = new BattleTowerRecord4(pokedex, data, 0xe4 * x); record.PID = 0; record.Rank = rank; record.RoomNum = room; record.BattlesWon = 7; db.BattleTowerUpdateRecord4(record); opponentSuccessCount++; } catch (Exception ex) { Console.WriteLine(ex.Message); opponentFailureCount++; } } for (int x = 0; x < 30; x++) { try { BattleTowerProfile4 profile = new BattleTowerProfile4(data, 0x63c + 0x22 * x); BattleTowerRecord4 record = new BattleTowerRecord4(pokedex); record.Profile = profile; record.PID = 0; record.Rank = rank; record.RoomNum = room; db.BattleTowerAddLeader4(record); leaderSuccessCount++; } catch (Exception ex) { Console.WriteLine(ex.Message); leaderFailureCount++; } } } break; case 5: { FileStream fs = File.OpenRead(s); if (fs.Length != 0xab4) { Console.WriteLine("{0}: file size is wrong, skipped.", filename); failureCount++; continue; } byte[] data = new byte[0xab4]; fs.ReadBlock(data, 0, 0xab4); fs.Close(); //web/battletower/download.asp response: 2700 bytes //00-68f: BattleSubwayRecord objects x7 //690-a8b: BattleSubwayTrainerProfile objects x30 for (int x = 0; x < 7; x++) { try { BattleSubwayRecord5 record = new BattleSubwayRecord5(pokedex, data, 0xf0 * x); record.PID = 0; record.Rank = rank; record.RoomNum = room; record.BattlesWon = 7; record.Unknown4 = new byte[5]; db.BattleSubwayUpdateRecord5(record); opponentSuccessCount++; } catch (Exception ex) { Console.WriteLine(ex.Message); opponentFailureCount++; } } for (int x = 0; x < 30; x++) { try { BattleSubwayProfile5 profile = new BattleSubwayProfile5(data, 0x690 + 0x22 * x); BattleSubwayRecord5 record = new BattleSubwayRecord5(pokedex); record.Profile = profile; record.PID = 0; record.Rank = rank; record.RoomNum = room; db.BattleSubwayAddLeader5(record); leaderSuccessCount++; } catch (Exception ex) { Console.WriteLine(ex.Message); leaderFailureCount++; } } } break; } Console.WriteLine("{0} complete", s); } Console.WriteLine("Added {0} files, {1} opponents, {2} leaders.", successCount, opponentSuccessCount, leaderSuccessCount); Console.WriteLine("Failed: {0} files, {1} opponents, {2} leaders.", failureCount, opponentFailureCount, leaderFailureCount); Console.ReadKey(); } } } ================================================ FILE: towerRestorer4/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("towerRestorer4")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("towerRestorer4")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f2a9df2e-eed3-49fb-948c-f6cf46914f51")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: towerRestorer4/towerRestorer.csproj ================================================  Debug AnyCPU {750A0BFD-7258-4B32-A4F9-60EEEB0BA64A} Exe Properties towerRestorer towerRestorer v3.5 512 AnyCPU true full false bin\Debug\ DEBUG;TRACE prompt 4 AnyCPU pdbonly true bin\Release\ TRACE prompt 4 {408efc7e-c6b0-4160-8628-2679e34385ce} Library ================================================ FILE: web/Default.aspx ================================================ <%@ Page Title="Poké Classic Network" Language="C#" MasterPageFile="~/masters/MasterPage.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PkmnFoundations.GTS.Default" %> <%@ Register TagPrefix="pf" Namespace="PkmnFoundations.Web" Assembly="PkmnFoundations.Web" %> <%@ Register TagPrefix="pf" TagName="LabelTextBox" Src="~/controls/LabelTextBox.ascx" %> <%@ Register TagPrefix="pf" TagName="DnsAddress" Src="~/controls/DnsAddress.ascx" %> <%--  
%--%>

About

Poké Classic Network provides GTS, battle videos, and other related services for Generation IV and V games. It runs in combination with Wiimmfi and Kaeru WFC which provide general purpose NWFC emulation and SSL offloading, respectively. (For reasons beyond my control, I cannot guarantee compatibility with AltWFC servers at this time.)

Getting started

All you need to do is change the primary DNS to on your DS. Make sure the secondary DNS is either 0.0.0.0 or otherwise the same as the primary. Failure to follow these instructions may lead to connection instability and communication errors.

================================================ FILE: web/Default.aspx.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using PkmnFoundations.GTS; using System.Text; namespace PkmnFoundations.GTS { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } } } ================================================ FILE: web/Default.aspx.designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace PkmnFoundations.GTS { public partial class Default { /// /// HeaderColour1 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::PkmnFoundations.Web.HeaderColour HeaderColour1; } } ================================================ FILE: web/Global.asax ================================================ <%@ Application Codebehind="Global.asax.cs" Inherits="PkmnFoundations.Web.Global" Language="C#" %> ================================================ FILE: web/Global.asax.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; using System.Web.SessionState; using PkmnFoundations.Data; namespace PkmnFoundations.Web { public class Global : System.Web.HttpApplication { void Application_Start(object sender, EventArgs e) { // Code that runs on application startup Application["pkmncfPokedex"] = new Pokedex.Pokedex(Database.Instance, false); } void Application_End(object sender, EventArgs e) { // Code that runs on application shutdown } void Application_Error(object sender, EventArgs e) { // Code that runs when an unhandled error occurs } void Session_Start(object sender, EventArgs e) { // Code that runs when a new session is started } void Session_End(object sender, EventArgs e) { // Code that runs when a session ends. // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web.config file. If session mode is set to StateServer // or SQLServer, the event is not raised. } void Application_BeginRequest(object sender, EventArgs e) { String pathInfo, query; String targetUrl = RewriteUrl(Request.Url.PathAndQuery, out pathInfo, out query); if (targetUrl != null) { Context.RewritePath(targetUrl, pathInfo, query, false); } } void Application_EndRequest(object sender, EventArgs e) { } public static String RewriteUrl(String url, out String pathInfo, out String query) { int q = url.IndexOf('?'); String path; pathInfo = ""; if (q < 0) { path = url; query = ""; } else { path = url.Substring(0, q); query = url.Substring(q + 1); } // todo: optimize and extend url pattern matching // fixme: this doesn't work if the application isn't mounted at root String[] split = path.Split('/'); if (split[0].Length > 0) return null; return null; } } } ================================================ FILE: web/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("web")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("web")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3dd50bf8-64a1-4ca9-89fc-a3b120e08442")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: web/Properties/PublishProfiles/Public.pubxml ================================================ MSDeploy Release Any CPU https://pkmnclassic.net True False False WMSVC True <_SavePWD>False ================================================ FILE: web/RoomLeaders.aspx ================================================ <%@ Page Title="" Language="C#" MasterPageFile="~/masters/MasterPage.master" AutoEventWireup="true" CodeBehind="RoomLeaders.aspx.cs" Inherits="PkmnFoundations.GTS.RoomLeaders" %>

Enter the rank and room number to get leader info:

Rank:
Room number:
Generation:
================================================ FILE: web/RoomLeaders.aspx.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using PkmnFoundations.Data; using PkmnFoundations.Structures; using PkmnFoundations.Support; using PkmnFoundations.Web; using PkmnFoundations.Wfc; namespace PkmnFoundations.GTS { public partial class RoomLeaders : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnGet_Click(object sender, EventArgs e) { byte rank; byte room; if (!Byte.TryParse(txtRank.Text, out rank) || !Byte.TryParse(txtRoom.Text, out room)) { litResults.Text = "Please type numbers."; return; } if (rank > 10 || rank < 1) { litResults.Text = "Rank must be 1-10."; } if (room > 50 || rank < 1) { litResults.Text = "Room must be 1-50."; } rank--; room--; Pokedex.Pokedex pokedex = AppStateHelper.Pokedex(Context.Application); switch (rbGeneration.SelectedValue) { case "4": { BattleTowerProfile4[] results = Database.Instance.BattleTowerGetLeaders4(pokedex, rank, room); StringBuilder builder = new StringBuilder(); builder.Append("

Leaders:

    "); foreach (BattleTowerProfile4 profile in results) { builder.Append("
  • "); TrendyPhrase4 tp = profile.PhraseLeader; builder.Append(tp.Render("{0}")); builder.Append("
  • "); } builder.Append("

Opponents:

    "); BattleTowerRecord4[] opponents = Database.Instance.BattleTowerGetOpponents4(pokedex, -1, rank, room); foreach (BattleTowerRecord4 record in opponents) { builder.Append("
  • "); builder.Append(record.PhraseChallenged.Render("{0}")); builder.Append("
    "); builder.Append(record.PhraseWon.Render("{0}")); builder.Append("
    "); builder.Append(record.PhraseLost.Render("{0}")); builder.Append("
  • "); } litResults.Text = builder.ToString(); } break; case "5": { BattleSubwayProfile5[] results = Database.Instance.BattleSubwayGetLeaders5(pokedex, rank, room); StringBuilder builder = new StringBuilder(); builder.Append("

    Leaders:

      "); foreach (BattleSubwayProfile5 profile in results) { builder.Append("
    • "); TrendyPhrase5 tp = profile.PhraseLeader; builder.Append(tp.Render("{0}")); builder.Append("
    • "); } builder.Append("

    Opponents:

      "); BattleSubwayRecord5[] opponents = Database.Instance.BattleSubwayGetOpponents5(pokedex, -1, rank, room); foreach (BattleSubwayRecord5 record in opponents) { builder.Append("
    • "); builder.Append(record.PhraseChallenged.Render("{0}")); builder.Append("
      "); builder.Append(record.PhraseWon.Render("{0}")); builder.Append("
      "); builder.Append(record.PhraseLost.Render("{0}")); builder.Append("
    • "); } litResults.Text = builder.ToString(); } break; } } } } ================================================ FILE: web/RoomLeaders.aspx.designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace PkmnFoundations.GTS { public partial class RoomLeaders { /// /// theForm control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.HtmlControls.HtmlForm theForm; /// /// txtRank control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox txtRank; /// /// txtRoom control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox txtRoom; /// /// rbGeneration control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.RadioButtonList rbGeneration; /// /// btnGet control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Button btnGet; /// /// litResults control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litResults; } } ================================================ FILE: web/Web.Public.config ================================================ ================================================ FILE: web/Web.config ================================================  ================================================ FILE: web/admin/AddBoxes.aspx ================================================ <%@ Page Title="" Language="C#" MasterPageFile="~/masters/MasterPage.master" AutoEventWireup="true" CodeBehind="AddBoxes.aspx.cs" Inherits="PkmnFoundations.GTS.admin.AddBoxes" %> <%@ Register TagPrefix="pf" Namespace="PkmnFoundations.Web" Assembly="PkmnFoundations.Web" %>

      Upload a wiresharked box search response here to add it to the database:

      ================================================ FILE: web/admin/AddBoxes.aspx.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using PkmnFoundations.Structures; using PkmnFoundations.Data; using PkmnFoundations.Web; using PkmnFoundations.Wfc; namespace PkmnFoundations.GTS.admin { public partial class AddBoxes : System.Web.UI.Page { protected void Page_Init(object sender, EventArgs e) { litMessage.Text = ""; } protected void Page_Load(object sender, EventArgs e) { } protected void btnSend_Click(object sender, EventArgs e) { byte[] data = fuBox.FileBytes; if (data.Length < 0xf8) { Fail(); return; } Common.CryptMessage(data); if (data[0x04] != 0x09 || data[0x05] != 0x52 || data[0x06] != 0x00 || data[0x07] != 0x00) { Fail(); return; } int results = BitConverter.ToInt32(data, 0x08); if (data.Length != 12 + 556 * results) { Fail(); return; } int added = 0; for (int x = 0; x < results; x++) { int pid = BitConverter.ToInt32(data, 12 + 556 * x); BoxLabels4 label = (BoxLabels4)BitConverter.ToInt32(data, 16 + 556 * x); ulong serial = BitConverter.ToUInt64(data, 20 + 556 * x); if (serial == 0) continue; byte[] result = new byte[540]; Array.Copy(data, 28 + 556 * x, result, 0, 540); BoxRecord4 record = new BoxRecord4(pid, label, serial, result); if (Database.Instance.BoxUpload4(record) != 0) added++; } litMessage.Text = "Added " + added.ToString() + " boxes to the database."; } private void Fail() { litMessage.Text = "There was an error with the data."; } } } ================================================ FILE: web/admin/AddBoxes.aspx.designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace PkmnFoundations.GTS.admin { public partial class AddBoxes { /// /// HeaderColour1 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::PkmnFoundations.Web.HeaderColour HeaderColour1; /// /// theForm control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.HtmlControls.HtmlForm theForm; /// /// fuBox control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.FileUpload fuBox; /// /// btnSend control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Button btnSend; /// /// litMessage control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litMessage; } } ================================================ FILE: web/admin/AddDressup.aspx ================================================ <%@ Page Title="" Language="C#" MasterPageFile="~/masters/MasterPage.master" AutoEventWireup="true" CodeBehind="AddDressup.aspx.cs" Inherits="PkmnFoundations.GTS.test.AddDressup" %> <%@ Register TagPrefix="pf" Namespace="PkmnFoundations.Web" Assembly="PkmnFoundations.Web" %>

      Upload a wiresharked Dressup search response here to add it to the database:

      ================================================ FILE: web/admin/AddDressup.aspx.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; using PkmnFoundations.Structures; using PkmnFoundations.Data; using PkmnFoundations.Web; using PkmnFoundations.Wfc; namespace PkmnFoundations.GTS.test { public partial class AddDressup : System.Web.UI.Page { protected void Page_Init(object sender, EventArgs e) { litMessage.Text = ""; } protected void Page_Load(object sender, EventArgs e) { } protected void btnSend_Click(object sender, EventArgs e) { byte[] data = fuBox.FileBytes; if (data.Length < 0xf8) { Fail(); return; } Common.CryptMessage(data); if (data[0x04] != 0x21 || data[0x05] != 0x4e || data[0x06] != 0x00 || data[0x07] != 0x00) { Fail(); return; } int results = BitConverter.ToInt32(data, 0x08); if (data.Length != 12 + 236 * results) { Fail(); return; } int added = 0; for (int x = 0; x < results; x++) { int pid = BitConverter.ToInt32(data, 12 + 236 * x); ulong serial = BitConverter.ToUInt64(data, 16 + 236 * x); if (serial == 0) continue; byte[] result = new byte[224]; Array.Copy(data, 24 + 236 * x, result, 0, 224); DressupRecord4 record = new DressupRecord4(pid, serial, result); if (Database.Instance.DressupUpload4(record) != 0) added++; } litMessage.Text = "Added " + added.ToString() + " dressup photos to the database."; } private void Fail() { litMessage.Text = "There was an error with the data."; } } } ================================================ FILE: web/admin/AddDressup.aspx.designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace PkmnFoundations.GTS.test { public partial class AddDressup { /// /// HeaderColour1 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::PkmnFoundations.Web.HeaderColour HeaderColour1; /// /// theForm control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.HtmlControls.HtmlForm theForm; /// /// fuBox control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.FileUpload fuBox; /// /// btnSend control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Button btnSend; /// /// litMessage control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litMessage; } } ================================================ FILE: web/admin/AddMusical.aspx ================================================ <%@ Page Title="" Language="C#" MasterPageFile="~/masters/MasterPage.master" AutoEventWireup="true" CodeBehind="AddMusical.aspx.cs" Inherits="PkmnFoundations.GTS.admin.AddMusical" %> <%@ Register TagPrefix="pf" Namespace="PkmnFoundations.Web" Assembly="PkmnFoundations.Web" %>

      Upload a wiresharked Musical search response here to add it to the database:

      ================================================ FILE: web/admin/AddMusical.aspx.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using PkmnFoundations.Data; using PkmnFoundations.Structures; using PkmnFoundations.Wfc; namespace PkmnFoundations.GTS.admin { public partial class AddMusical : System.Web.UI.Page { protected void Page_Init(object sender, EventArgs e) { litMessage.Text = ""; } protected void Page_Load(object sender, EventArgs e) { } protected void btnSend_Click(object sender, EventArgs e) { byte[] data = fuBox.FileBytes; if (data.Length < 0x248) { Fail(); return; } if (data[0x04] != 0x09 || data[0x05] != 0x52 || data[0x06] != 0x00 || data[0x07] != 0x00) { Fail(); return; } int results = BitConverter.ToInt32(data, 0x08); if (data.Length != 12 + 572 * results) { Fail(); return; } int added = 0; for (int x = 0; x < results; x++) { int pid = BitConverter.ToInt32(data, 12 + 572 * x); ulong serial = BitConverter.ToUInt64(data, 16 + 572 * x); if (serial == 0) continue; byte[] result = new byte[560]; Array.Copy(data, 24 + 572 * x, result, 0, 560); MusicalRecord5 record = new MusicalRecord5(pid, serial, result); if (Database.Instance.MusicalUpload5(record) != 0) added++; } litMessage.Text = "Added " + added.ToString() + " musical photos to the database."; } private void Fail() { litMessage.Text = "There was an error with the data."; } } } ================================================ FILE: web/admin/AddMusical.aspx.designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace PkmnFoundations.GTS.admin { public partial class AddMusical { /// /// HeaderColour1 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::PkmnFoundations.Web.HeaderColour HeaderColour1; /// /// theForm control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.HtmlControls.HtmlForm theForm; /// /// fuBox control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.FileUpload fuBox; /// /// btnSend control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Button btnSend; /// /// litMessage control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litMessage; } } ================================================ FILE: web/admin/Web.Debug.config ================================================ ================================================ FILE: web/admin/Web.Release.config ================================================ ================================================ FILE: web/admin/Web.config ================================================  ================================================ FILE: web/battlevideo/Default.aspx ================================================ <%@ Page Title="" Language="C#" MasterPageFile="~/masters/MasterPage.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PkmnFoundations.GTS.BattleVideo" %> <%@ Register TagPrefix="pf" Namespace="PkmnFoundations.Web" Assembly="PkmnFoundations.Web" %>

      Battle videos

      Since the official Battle Video server has gone offline, you can no longer queue your battle videos for retrieval. You can still type your battle video ID into one of the below forms to check if I have it backed up. If not, you can try Pokécheck. If it’s not there, your video is gone. If it’s still on your game cartridge, you can reupload it to fGTS under a new ID.

      Generation IV (Platinum, Heart Gold, Soul Silver)

      videos saved in total.

      Generation V (Black, White, Black 2, White 2)

      videos saved in total.
      ================================================ FILE: web/battlevideo/Default.aspx.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using MySql.Data.MySqlClient; using System.Configuration; using PkmnFoundations.Data; namespace PkmnFoundations.GTS { public partial class BattleVideo : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { ulong bvCount4, bvCount5; if (Cache["BattleVideoCount4"] == null || Cache["BattleVideoCount5"] == null) { bvCount4 = Database.Instance.BattleVideoCount4(); bvCount5 = Database.Instance.BattleVideoCount5(); Cache.Insert("BattleVideoCount4", bvCount4, null, DateTime.Now.AddMinutes(1), System.Web.Caching.Cache.NoSlidingExpiration); Cache.Insert("BattleVideoCount5", bvCount5, null, DateTime.Now.AddMinutes(1), System.Web.Caching.Cache.NoSlidingExpiration); } else { bvCount4 = Convert.ToUInt64(Cache["BattleVideoCount4"]); bvCount5 = Convert.ToUInt64(Cache["BattleVideoCount5"]); } litMessage4.Text = ""; litMessage5.Text = ""; litTotal4.Text = HttpUtility.HtmlEncode(bvCount4.ToString()); litTotal5.Text = HttpUtility.HtmlEncode(bvCount5.ToString()); } protected void btnSend4_Click(object sender, EventArgs e) { ulong id; UInt64.TryParse(txtBattleVideo4.Text.Replace('-', ' ').Replace(" ", ""), out id); if (id == 0) { litMessage4.Text = "The battle video ID could not be read. Please enter a battle video ID in the format, xx-xxxxx-xxxxx, and try again."; return; } using (MySqlConnection db = CreateConnection()) { db.Open(); QueueVideoId4(db, id); db.Close(); } } private void QueueVideoId4(MySqlConnection db, ulong id) { long count = (long)db.ExecuteScalar("SELECT Count(*) FROM TerminalBattleVideos4 " + "WHERE SerialNumber = @serial_number", new MySqlParameter("@serial_number", id)); if (count > 0) { litMessage4.Text = "This battle video has been saved."; return; } litMessage4.Text = "This battle video is lost."; } protected void btnSend5_Click(object sender, EventArgs e) { ulong id; UInt64.TryParse(txtBattleVideo5.Text.Replace('-', ' ').Replace(" ", ""), out id); if (id == 0) { litMessage5.Text = "The battle video ID could not be read. Please enter a battle video ID in the format, xx-xxxxx-xxxxx, and try again."; return; } using (MySqlConnection db = CreateConnection()) { db.Open(); QueueVideoId5(db, id); db.Close(); } } private void QueueVideoId5(MySqlConnection db, ulong id) { long count = (long)db.ExecuteScalar("SELECT Count(*) FROM TerminalBattleVideos5 " + "WHERE SerialNumber = @serial_number", new MySqlParameter("@serial_number", id)); if (count > 0) { litMessage5.Text = "This battle video has been saved."; return; } litMessage5.Text = "This battle video is lost."; } public static MySqlConnection CreateConnection() { return new MySqlConnection(ConfigurationManager.ConnectionStrings["pkmnFoundationsConnectionString"].ConnectionString); } } } ================================================ FILE: web/battlevideo/Default.aspx.designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace PkmnFoundations.GTS { public partial class BattleVideo { /// /// HeaderColour1 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::PkmnFoundations.Web.HeaderColour HeaderColour1; /// /// theForm control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.HtmlControls.HtmlForm theForm; /// /// txtBattleVideo4 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox txtBattleVideo4; /// /// btnSend4 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Button btnSend4; /// /// litMessage4 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litMessage4; /// /// litTotal4 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litTotal4; /// /// txtBattleVideo5 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox txtBattleVideo5; /// /// btnSend5 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Button btnSend5; /// /// litMessage5 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litMessage5; /// /// litTotal5 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litTotal5; } } ================================================ FILE: web/controls/DnsAddress.ascx ================================================ <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="DnsAddress.ascx.cs" Inherits="PkmnFoundations.Web.controls.DnsAddress" %> 178.62.43.212 (Kaeru WFC) ================================================ FILE: web/controls/DnsAddress.ascx.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace PkmnFoundations.Web.controls { public partial class DnsAddress : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { } public bool ShowAttribution { get { return phAttribution.Visible; } set { phAttribution.Visible = value; } } } } ================================================ FILE: web/controls/DnsAddress.ascx.designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace PkmnFoundations.Web.controls { public partial class DnsAddress { /// /// phAttribution control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.PlaceHolder phAttribution; } } ================================================ FILE: web/controls/ForeignLookup.ascx ================================================ <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ForeignLookup.ascx.cs" Inherits="PkmnFoundations.Web.controls.ForeignLookup" %> <%@ Register TagPrefix="pf" Namespace="PkmnFoundations.Web" Assembly="PkmnFoundations.Web" %>
      ================================================ FILE: web/controls/ForeignLookup.ascx.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace PkmnFoundations.Web.controls { public partial class ForeignLookup : System.Web.UI.UserControl { protected void Page_Init(object sender, EventArgs e) { } protected void Page_Load(object sender, EventArgs e) { if (SourceUrl != null) { String url = ResolveUrl(SourceUrl); //url = url + (url.Contains('?') ? "&lang=" : "?lang=") + ((BasePage)Page).Language; String _params = "\'" + this.ClientID + "', '" + txtInput.ClientID + "', '" + results.ClientID + "', '" + MaxRows.ToString() + "', '" + url + "\'"; main.Attributes["onfocus"] = "pfHandleLookupKeypress(" + _params + ")"; main.Attributes["onblur"] = "pfHideLookupResults('" + results.ClientID + "')"; txtInput.Attributes["onfocus"] = "pfHandleLookupKeypress(" + _params + ")"; txtInput.Attributes["onkeypress"] = "return pfHandleLookupKeypress2(" + _params + ", event)"; txtInput.Attributes["onkeyup"] = "return pfHandleLookupKeypress3(" + _params + ")"; txtInput.Attributes["onchange"] = "pfHandleLookupKeypress(" + _params + ")"; txtInput.Attributes["onblur"] = "setTimeout(function(){pfHideLookupResults('" + results.ClientID + "')},100)"; hdSelectedValue.Attributes["onchange"] = OnClientValueChanged; } } public String Value { get { return hdSelectedValue.Value; } set { hdSelectedValue.Value = value; } } public String Text { get { return txtInput.Text; } set { txtInput.Text = value; } } public String SourceUrl { get; set; } public int MaxRows { get; set; } public String OnClientValueChanged { get; set; } public String HiddenClientID { get { return hdSelectedValue.ClientID; } } public String TextClientID { get { return txtInput.ClientID; } } private String m_css_class; public String CssClass { get { return m_css_class; } set { m_css_class = value; main.Attributes["class"] = "pfLookup " + Common.HtmlEncode(m_css_class); } } protected override void LoadViewState(object savedState) { ForeignLookupViewState viewstate = (ForeignLookupViewState)savedState; base.LoadViewState(viewstate.UserControlViewState); SourceUrl = viewstate.SourceUrl; MaxRows = viewstate.MaxRows; OnClientValueChanged = viewstate.OnClientValueChanged; CssClass = viewstate.CssClass; } protected override object SaveViewState() { ForeignLookupViewState viewstate = new ForeignLookupViewState(); viewstate.UserControlViewState = base.SaveViewState(); viewstate.SourceUrl = SourceUrl; viewstate.MaxRows = MaxRows; viewstate.OnClientValueChanged = OnClientValueChanged; viewstate.CssClass = CssClass; return viewstate; } [Serializable()] private struct ForeignLookupViewState { public object UserControlViewState; public String SourceUrl; public int MaxRows; public String OnClientValueChanged; public String CssClass; } } } ================================================ FILE: web/controls/ForeignLookup.ascx.designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace PkmnFoundations.Web.controls { public partial class ForeignLookup { /// /// main control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.HtmlControls.HtmlGenericControl main; /// /// txtInput control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox txtInput; /// /// results control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.HtmlControls.HtmlGenericControl results; /// /// imgLoading control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::PkmnFoundations.Web.RetinaImage imgLoading; /// /// hdSelectedValue control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.HtmlControls.HtmlInputHidden hdSelectedValue; } } ================================================ FILE: web/controls/LabelTextBox.ascx ================================================ <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="LabelTextBox.ascx.cs" Inherits="PkmnFoundations.GTS.controls.LabelTextBox" %> <%@ Register TagPrefix="pf" Namespace="PkmnFoundations.Web" Assembly="PkmnFoundations.Web" %>
      ================================================ FILE: web/controls/LabelTextBox.ascx.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace PkmnFoundations.GTS.controls { public partial class LabelTextBox : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { } public String Text { get { return theTextBox.Text; } set { theTextBox.Text = value; } } public String Label { get { return theLabel.Text; } set { theLabel.Text = value; } } public TextBoxMode TextMode { get { return theTextBox.TextMode; } set { theTextBox.TextMode = value; } } } } ================================================ FILE: web/controls/LabelTextBox.ascx.designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace PkmnFoundations.GTS.controls { public partial class LabelTextBox { /// /// theLabel control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label theLabel; /// /// theTextBox control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox theTextBox; } } ================================================ FILE: web/controls/PokemonPicker.ascx ================================================ <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="PokemonPicker.ascx.cs" Inherits="PkmnFoundations.Web.controls.PokemonPicker" %> <%@ Register TagPrefix="pf" TagName="ForeignLookup" Src="~/controls/ForeignLookup.ascx" %> ================================================ FILE: web/controls/PokemonPicker.ascx.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using PkmnFoundations.Structures; namespace PkmnFoundations.Web.controls { public partial class PokemonPicker : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { } public int ? Value { get { String value = theLookup.Value; return String.IsNullOrEmpty(value) ? null : (int ?)Convert.ToInt32(value); } set { if (value == null) theLookup.Value = null; theLookup.Value = value.ToString(); } } private Generations m_max_generation; public Generations MaxGeneration { get { return m_max_generation; } set { m_max_generation = value; theLookup.SourceUrl = "~/controls/PokemonSource.ashx?limit=" + Pokedex.Pokedex.SpeciesAtGeneration(value).ToString(); } } } } ================================================ FILE: web/controls/PokemonPicker.ascx.designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace PkmnFoundations.Web.controls { public partial class PokemonPicker { /// /// theLookup control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::PkmnFoundations.Web.controls.ForeignLookup theLookup; } } ================================================ FILE: web/controls/PokemonSource.ashx ================================================ <%@ WebHandler Language="C#" CodeBehind="PokemonSource.ashx.cs" Class="PkmnFoundations.Web.controls.PokemonSource" %> ================================================ FILE: web/controls/PokemonSource.ashx.cs ================================================ using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using PkmnFoundations.Pokedex; using PkmnFoundations.Structures; namespace PkmnFoundations.Web.controls { /// /// Summary description for PokemonSource /// public class PokemonSource : ForeignLookupSource { protected override System.Data.DataTable GetData(HttpContext context, String query, int rows, Structures.Languages lang) { Pokedex.Pokedex pokedex = AppStateHelper.Pokedex(context.Application); String iso = Format.ToIso639_1(lang); query = query.ToLowerInvariant(); int natDex = 0; Int32.TryParse(query, out natDex); int limit = 0; if (context.Request.QueryString["limit"] != null) { limit = Convert.ToInt32(context.Request.QueryString["limit"]); if (natDex > limit) return null; } Func, bool> filter; if (natDex > 0) filter = pair => pair.Key == natDex; else filter = pair => pair.Key <= limit && pair.Value.Name[iso].ToLowerInvariant().Contains(query); IEnumerable data; data = pokedex.Species.Where(filter).OrderBy(pair => pair.Key).Take(rows).Select(pair => pair.Value); DataTable dt = new DataTable(); dt.Columns.Add("Text", typeof(String)); dt.Columns.Add("Value", typeof(int)); dt.Columns.Add("html", typeof(String)); foreach (Species s in data) { String name = s.Name[iso]; String html = "\""" + String.Format("{0} (#{1})", Common.HtmlEncode(name), s.NationalDex); dt.Rows.Add(name, s.NationalDex, html); } return dt; } } } ================================================ FILE: web/css/form.css ================================================ input[type=text], input[type=password], select, textarea { border: 1px solid #999999; background-color: white; box-shadow: 0 1px 2px 0 rgba(0,0,0,0.1) inset; height: 14px; padding: 3px 2px; font-size: 10pt; font-family: Arial,Helvetica,sans-serif; border-radius: 2px; } input[type=text]:focus, input[type=password]:focus, select, textarea:focus, input[type=text]:focus, input[type=password]:focus, select, textarea:focus { } input[type=submit], button, .ui-button { border-radius: 2px; background-color: #008fc4; background-image: -moz-linear-gradient(top, #008fc4 0%, #00749f 100%); /* FF3.6+ */ background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#008fc4), color-stop(100%,#00749f)); /* Chrome,Safari4+ */ background-image: -webkit-linear-gradient(top, #008fc4 0%,#00749f 100%); /* Chrome10+,Safari5.1+ */ background-image: -o-linear-gradient(top, #008fc4 0%,#00749f 100%); /* Opera 11.10+ */ background-image: -ms-linear-gradient(top, #008fc4 0%,#00749f 100%); /* IE10+ */ background-image: linear-gradient(to bottom, #008fc4 0%,#00749f 100%); /* W3C */ background-size: 100%; box-shadow: 0 2px 1px -1px #89b4d5 inset, 0 1px 2px 0 rgba(0,0,0,0.1); border: 1px solid; border-color: #bcd1e4 #00749f #004a68 #89b4d5; color: white; text-shadow: 0 1px 0 #004a68; font-family: Lato,Candara,'Meiryo UI',Arial,sans-serif; font-weight: bold; } a.ui-button { color: white; } input[type=submit], button { height: 28px; margin-bottom: 4px; cursor: pointer; } input[type=submit].large, button.large { width: 236px; } .pfLabelTextBox { position: relative; background-color: white; font-family: Arial,Helvetica,sans-serif; display: inline-block; margin: 0; padding: 0; margin-bottom: 4px; vertical-align: top; border-radius: 2px; } .pfLabelTextBox label { display: block; height: 0; overflow: visible; position: relative; top: 3px; left: 3px; color: #cccccc; } .pfLabelTextBox input { display: block; background-color: transparent; position: relative; margin-bottom: 0; } .pfLabelTextBox input:focus, .pfLabelTextBox input.hasContent { background-color: white; } .pfColGroup { position: relative; overflow: hidden; } .pfColumn { float: left; position: relative; } .gtsBox .pfColumn { margin: 16px; } .pfFormSubmit { position: absolute; bottom: 12px; right: 16px; } .pfFormGroup { border-spacing: 0; height: 100%; } .gtsBox .pfFormGroup { border-radius: 4px; } .pfFormKey, .pfFormValue { margin: 0; padding: 4px 8px; border-bottom: 1px solid rgba(0,0,0,0.3); height: 18px; background-image: -moz-linear-gradient(top, transparent 0%, rgba(0,0,0,0.05) 100%); /* FF3.6+ */ background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%,transparent), color-stop(100%,rgba(0,0,0,0.05))); /* Chrome,Safari4+ */ background-image: -webkit-linear-gradient(top, transparent 0%,rgba(0,0,0,0.05) 100%); /* Chrome10+,Safari5.1+ */ background-image: -o-linear-gradient(top, transparent 0%,rgba(0,0,0,0.05) 100%); /* Opera 11.10+ */ background-image: -ms-linear-gradient(top, transparent 0%,rgba(0,0,0,0.05) 100%); /* IE10+ */ background-image: linear-gradient(to bottom, transparent 0%,rgba(0,0,0,0.05) 100%); /* W3C */ } .pfFormKey { color: white; text-align: left; text-shadow: 0 1px 0 rgba(0,0,0,0.3); } .pfFormKey { background-color: #82d2e0; } .pfFormValue { } .home .pfFormKey {background-color: #ff8063;} .gts .pfFormKey {background-color: #43c4ff;} .bv .pfFormKey {background-color: #9761e9;} .dw .pfFormKey {background-color: #fa79d4;} .dex .pfFormKey {background-color: #2dd350;} .stat .pfFormKey {background-color: #ffc321;} .test .pfFormKey {background-color: #82d2e0;} .admin .pfFormKey {background-color: #555555;} .pfFormValue { background-color: #f2f2f2; } .pfRadListItem { display: block; margin: 4px 0; } .pfRadListItem * { vertical-align: middle; } .pfRadListItem:first-child { margin-top: 0; } .pfRadListItem:last-child { margin-bottom: 0; } .ui-spinner { display: inline-block; position: relative; padding-right: 18px; } .ui-spinner-input, input.ui-spinner-input { border-radius: 2px 0 0 2px; border-right: none; } .ui-spinner-button { position: absolute; display: block; width: 16px; height: calc(50% - 2px); right: 0; font-size: 8px; text-align: center; line-height: 9px; cursor: pointer; border-radius: 0; } .ui-spinner-up { top: 0; border-top-right-radius: 2px; } .ui-spinner-down { bottom: 0; border-bottom-right-radius: 2px; } .pfLookup { position: relative; } .pfLookup input { } .pfLookup .results { position: absolute; z-index: 1; left: 0; right: 0; overflow: auto; background-color: white; border: 1px solid #999; box-shadow: 0 1px 2px 0 rgba(0,0,0,0.1); margin-top: -1px; border-radius: 0 0 2px 2px; } .pfLookup .results_inner { overflow: hidden; } .pfLookup .results .result { } .pfLookup .results .result.default, .pfLookup .results:hover .result:hover, .pfLookup .results:hover .result.default:hover { background-color: #ddd; } .pfLookup .results:hover .result.default { background-color: white; } .pfPokemonPicker .result { padding: 4px; height: 20px; white-space: nowrap; } .pfPokemonPicker .result img.speciesSmall { margin: -6px -4px -10px -10px; } ================================================ FILE: web/css/login.css ================================================ .gtsLogin { width: 236px; } ================================================ FILE: web/css/main.css ================================================ @import url(//fonts.googleapis.com/css?family=Lato:400,700,400italic&subset=latin,latin-ext); @import url(//fonts.googleapis.com/css?family=Nunito:700); body { margin: 0; padding: 0; font-family: Lato,Candara,'Segoe UI','Hiragino Sans','Meiryo','Arial Unicode MS','Yu Gothic UI',Arial,sans-serif; font-size: 10pt; font-weight: 400; background-color: #666666; } h1, h2, h3, h4, strong { font-weight: 700; } hr { margin: 16px 0; border: 1px solid #cccccc; border-width: 1px 0 0; } a { color: #00749f; } a:hover { color: #004a68; } a:visited { color: #7e3bd0; } a:visited:hover { color: #512489; } li { margin: 4px 0; } .setWidth { width: 980px; position: relative; margin: 0 auto; } .clear { clear: both; height: 0; overflow: hidden; } .github-contain { position: absolute; overflow: hidden; top: 0; right: 0; width: 160px; height: 160px; } .github, a.github, a.github:hover { width: 300px; height: 20px; color: white; background-color: black; position: absolute; top: 60px; right: -80px; text-align: center; display: block; margin: 0; padding: 0; text-decoration: none; transform: rotate(45deg); -webkit-transform: rotate(45deg); } .rightFloat { float: right; margin-left: 16px; } .code { font-family: Consolas,'Andale Mono',monospace } .gtsBox { box-shadow: 0 3px 8px 0 rgba(0,0,0,0.05), 0 -4px 3px -3px rgba(0,0,0,0.1) inset; background-color: #f8f8f8; background-image: -moz-linear-gradient(top, #fcfcfc 0%, #f8f8f8 100%); /* FF3.6+ */ background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#fcfcfc), color-stop(100%,#f8f8f8)); /* Chrome,Safari4+ */ background-image: -webkit-linear-gradient(top, #fcfcfc 0%,#f8f8f8 100%); /* Chrome10+,Safari5.1+ */ background-image: -o-linear-gradient(top, #fcfcfc 0%,#f8f8f8 100%); /* Opera 11.10+ */ background-image: -ms-linear-gradient(top, #fcfcfc 0%,#f8f8f8 100%); /* IE10+ */ background-image: linear-gradient(to bottom, #fcfcfc 0%,#f8f8f8 100%); /* W3C */ background-size: 100%; border-radius: 12px; border: 1px solid #cccccc; margin: 8px; } .pfBoxThin { box-shadow: 0 3px 8px 0 rgba(0,0,0,0.05); background-color: #f8f8f8; background-image: -moz-linear-gradient(top, #fcfcfc 0%, #f8f8f8 100%); /* FF3.6+ */ background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#fcfcfc), color-stop(100%,#f8f8f8)); /* Chrome,Safari4+ */ background-image: -webkit-linear-gradient(top, #fcfcfc 0%,#f8f8f8 100%); /* Chrome10+,Safari5.1+ */ background-image: -o-linear-gradient(top, #fcfcfc 0%,#f8f8f8 100%); /* Opera 11.10+ */ background-image: -ms-linear-gradient(top, #fcfcfc 0%,#f8f8f8 100%); /* IE10+ */ background-image: linear-gradient(to bottom, #fcfcfc 0%,#f8f8f8 100%); /* W3C */ background-size: 100%; border-radius: 4px; } .pfToolTip { border-bottom: 1px dotted #999; margin-bottom: -1px; cursor: help; } .gtsNav, .gtsNav ul, .gtsNav li { margin: 0; padding: 0; } .gtsNav li { float: left; } .gtsNav li a { display: block; } .gtsInfo { margin-left: 40px; position: relative; min-height: 32px; } .gtsInfo::before { width: 24px; height: 0; padding: 12px 0; position: absolute; left: -40px; top: calc(50% - 16px); content: 'i'; border: 4px solid #999999; color: #999999; font-family: Arial,Helvetica,sans-serif; line-height: 0; vertical-align: middle; border-radius: 100%; font-size: 24px; font-weight: bold; text-align: center; display: block; } .gtsProgress { border: 1px solid #777777; height: 2px; border-radius: 2px; } .gtsProgress .progress { background-color: #2dd350; height: 2px; } #gtsHeader { padding-top: 16px; background-color: #ff8063; color: white; background-image: url('../images/heading-backdrop.png'); background-size: 32px 8px; overflow: hidden; font-size: 12pt; position: relative; } #gtsHeader a, #gtsHeader a:visited { color: white; } #gtsHeader #gtsLogo { width: 276px; margin-right: 16px; float: left; text-shadow: 0 1px 1px rgba(0,0,0,0.2); text-align: left; } #gtsHeader #gtsLogo a { text-decoration: none; } #gtsHeader #gtsLogo .gtsLogoImage, #gtsHeader #gtsLogo .gtsLogoWord { display: block; } #gtsHeader #gtsLogo .gtsLogoImage { float: left; margin-bottom: 4px; } #gtsHeader #gtsLogo .gtsLogoWords { font-family: Nunito,Calibri,sans-serif; font-weight: 700; font-size: 24px; line-height: 32px; letter-spacing: 2px; color: white; } #gtsHeader #gtsLogo .gtsLogoWord { margin-left: 112px; } #gtsHeader #gtsHeadMain { width: 400px; float: left; margin-right: 16px; margin-top: 9px; text-shadow: 0 1px 1px rgba(0,0,0,0.2); } #gtsHeader #gtsLogin { width: 240px; float: left; color: black; background-color: #eeeeee; background-color: rgba(255,255,255,0.9); padding: 16px; border-radius: 16px; box-shadow: 0 4px 8px 2px rgba(0,0,0,0.2); } #gtsHeader .gtsHeadContent { list-style-type: circle; margin-top: 0; margin-left: 16px; padding-left: 0; } #gtsHeader .gtsNav { height: 32px; margin: 16px 0 0 0; padding: 0; font-size: 12pt; width: 1000px; } #gtsHeader .gtsNav li { display: block; margin: 0; padding: 0; } #gtsHeader .gtsNav li a { width: 148px; height: 18px; margin-right: 8px; padding-top: 14px; padding-left: 8px; border: 1px solid #cccccc; border-style: solid; border-color: #cccccc #bbbbbb #aaaaaa #bbbbbb; border-bottom: none; box-shadow: 0 -2px 12px -4px rgba(0,0,0,0.5); border-radius: 6px 6px 0 0; background-color: #f8f8f8; color: black; text-decoration: none; font-weight: bold; line-height: 0; vertical-align: middle; position: relative; z-index: 0; top: 2px; transition: top 0.1s ease-out, background-color 0.1s ease-out; } #gtsHeader .gtsNav li a:hover { top: 0; background-color: #fcfcfc; } .home #gtsHeader .gtsNav li.home a, .gts #gtsHeader .gtsNav li.gts a, .bv #gtsHeader .gtsNav li.bv a, .dw #gtsHeader .gtsNav li.dw a, .dex #gtsHeader .gtsNav li.dex a, .stat #gtsHeader .gtsNav li.stat a {z-index: 2; top: 0; background-color: #fcfcfc;} #gtsHeader .gtsNav li.home a, .home #gtsSubMenu.bv, .home .gtsNav li a {color: #ff8063;} #gtsHeader .gtsNav li.gts a, .gts #gtsSubMenu, .gts .gtsNav li a {color: #43c4ff;} #gtsHeader .gtsNav li.bv a, .bv #gtsSubMenu, .bv .gtsNav li a {color: #9761e9;} #gtsHeader .gtsNav li.dw a, .dw #gtsSubMenu, .dw .gtsNav li a {color: #fa79d4;} #gtsHeader .gtsNav li.dex a, .dex #gtsSubMenu, .dex .gtsNav li a {color: #2dd350;} #gtsHeader .gtsNav li.stat a, .stat #gtsSubMenu, .stat .gtsNav li a {color: #ffc321;} #gtsHeader .gtsNav li.test a, .test #gtsSubMenu, .test .gtsNav li a {color: #82d2e0;} #gtsHeader .gtsNav li.admin a, .admin #gtsSubMenu, .admin .gtsNav li a {color: #555555;} .home #gtsHeader, .home #gtsSubNav .gtsNav li a:hover .inner {background-color: #ff8063;} .gts #gtsHeader, .gts #gtsSubNav .gtsNav li a:hover .inner {background-color: #43c4ff;} .bv #gtsHeader, .bv #gtsSubNav .gtsNav li a:hover .inner {background-color: #9761e9;} .dw #gtsHeader, .dw #gtsSubNav .gtsNav li a:hover .inner {background-color: #fa79d4;} .dex #gtsHeader, .dex #gtsSubNav .gtsNav li a:hover .inner {background-color: #2dd350;} .stat #gtsHeader, .stat #gtsSubNav .gtsNav li a:hover .inner {background-color: #ffc321;} .test #gtsHeader, .test #gtsSubNav .gtsNav li a:hover .inner {background-color: #82d2e0;} .admin #gtsHeader, .admin #gtsSubNav .gtsNav li a:hover .inner {background-color: #555555;} #gtsMain { background-color: white; margin: 0; padding: 16px 0; min-height: 300px; color: #111111; } #gtsMain .gtsHeaderArea { clear: both; } #gtsMain .gtsColumn { width: 236px; } #gtsMain .gtsLeftColumn { float: left; margin-right: 16px; } #gtsMain .gtsRightColumn { float: right; } #gtsMain .gtsMainColumn { float: left; } #gtsMain .gtsMainColumnThree { width: 476px; } #gtsMain .gtsMainColumnTwo { width: 728px; } #gtsMain .gtsColumn .gtsSection { margin-bottom: 16px; } #gtsSubNav { border: 1px solid #cccccc; border-width: 1px 0; box-shadow: 0 -12px 12px -12px rgba(0,0,0,0.5), 0 3px 8px 0 rgba(0,0,0,0.05), 0 -4px 3px -3px rgba(0,0,0,0.1) inset; background-color: #f8f8f8; color: #ff8063; height: 32px; padding: 0; position: relative; z-index: 1; margin-top: -1px; background-image: -moz-linear-gradient(top, #fcfcfc 0%, #f8f8f8 100%); /* FF3.6+ */ background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#fcfcfc), color-stop(100%,#f8f8f8)); /* Chrome,Safari4+ */ background-image: -webkit-linear-gradient(top, #fcfcfc 0%,#f8f8f8 100%); /* Chrome10+,Safari5.1+ */ background-image: -o-linear-gradient(top, #fcfcfc 0%,#f8f8f8 100%); /* Opera 11.10+ */ background-image: -ms-linear-gradient(top, #fcfcfc 0%,#f8f8f8 100%); /* IE10+ */ background-image: linear-gradient(to bottom, #fcfcfc 0%,#f8f8f8 100%); /* W3C */ background-size: 100%; } #gtsSubNav .gtsNav { margin: 0; padding: 6px 0; margin-left: 0; font-size: 12pt; } #gtsSubNav .gtsNav li { height: 20px; display: block; margin: 0; padding: 0; border-left: 1px solid #cccccc; } #gtsSubNav .gtsNav li a { height: 24px; padding: 0 12px; margin: 0; text-decoration: none; font-weight: bold; line-height: 0; vertical-align: middle; position: relative; top: -2px; z-index: 0; } #gtsSubNav .gtsNav li a .inner { display: block; line-height: 0; height: 12px; padding: 12px 6px 0 6px; border-radius: 12px; } #gtsSubNav .gtsNav li a:hover { color: white; text-shadow: 0 2px 2px rgba(0,0,0,0.2); } #gtsSubNav .gtsNav li a:hover .inner { box-shadow: 0 2px 2px 0 rgba(0,0,0,0.2) inset; } #gtsSubNav .gtsNav li:first-child { border-left: none; } #gtsSubNav .gtsNav li:first-child a { padding-left: 3px; } #gtsFooter { color: white; font-size: 9pt; padding: 16px 0; text-shadow: 0 1px 1px rgba(0,0,0,0.5); box-shadow: 0 12px 12px -12px rgba(0,0,0,0.5) inset; text-align: center; } #gtsFooter a { color: white; text-decoration: none; } #gtsFooter a:hover { text-decoration: underline; } #gtsFooter .gtsFooterNav { list-style-type: none; margin-left: 0; padding-left: 0; } #gtsFooter .gtsFooterNav li { display: inline; } #gtsFooter .gtsFooterNav li::after { content: ' • '; } #gtsFooter .gtsFooterNav li:last-child::after { content: none; } #gtsFooter *:first-child * { margin-top: 0; } .pfChoiceGroup { position: relative; overflow: hidden; margin: 0 -8px; } .pfChoice { float: left; width: 180px; height: 80px; border: 2px solid #eeeeee; background-color: white; cursor: pointer; margin: 4px 8px 4px 0; position: relative; display: table; border-spacing: 8px; } .pfChoiceGroupVersions .pfChoice { width: 128px; height: 48px; } .pfChoice .pfChoiceIcon { display: table-cell; vertical-align: middle; width: 0; } .pfChoice .pfChoiceLabel { display: table-cell; vertical-align: middle; text-align: left; } .pfChoice:hover { background-color: #f6f6f6; border-color: #dddddd; } .pfChoiceActive { border-color: #ff8063; } .home .pfChoiceActive {border-color: #ff8063;} .gts .pfChoiceActive {border-color: #43c4ff;} .bv .pfChoiceActive {border-color: #9761e9;} .dw .pfChoiceActive {border-color: #fa79d4;} .dex .pfChoiceActive {border-color: #2dd350;} .stat .pfChoiceActive {border-color: #ffc321;} .test .pfChoiceActive {border-color: #82d2e0;} .admin .pfChoiceActive {border-color: #555555;} .pfSplitList { margin-top: 0; margin-bottom: 0; } .pfRight { float: right; margin-left: 16px; } @media (min--moz-device-pixel-ratio: 1.01), (-o-min-device-pixel-ratio: 97/96), (-webkit-min-device-pixel-ratio: 1.01), (min-device-pixel-ratio: 1.01), (min-resolution: 97dpi) { #gtsHeader { background-image: url('../images/heading-backdrop@2x.png'); } } @media (min--moz-device-pixel-ratio: 2), (-o-min-device-pixel-ratio: 2/1), (-webkit-min-device-pixel-ratio: 2), (min-device-pixel-ratio: 2), (min-resolution: 192dpi) { .sprite { image-rendering: optimizeSpeed; image-rendering: -moz-crisp-edges; image-rendering: -o-crisp-edges; image-rendering: -webkit-optimize-contrast; image-rendering: -webkit-crisp-edges; image-rendering: crisp-edges; -ms-interpolation-mode: bicubic; } } @media (print), (min--moz-device-pixel-ratio: 2.01), (-o-min-device-pixel-ratio: 193/96), (-webkit-min-device-pixel-ratio: 2.01), (min-device-pixel-ratio: 2.01), (min-resolution: 193dpi) { #gtsHeader { background-image: url('../images/heading-backdrop@3x.png'); } .sprite { image-rendering: optimizeQuality; } } @media (min--moz-device-pixel-ratio: 3), (-o-min-device-pixel-ratio: 3/1), (-webkit-min-device-pixel-ratio: 3), (min-device-pixel-ratio: 3), (min-resolution: 288dpi) { .sprite { image-rendering: optimizeSpeed; image-rendering: -moz-crisp-edges; image-rendering: -o-crisp-edges; image-rendering: -webkit-optimize-contrast; image-rendering: -webkit-crisp-edges; image-rendering: crisp-edges; -ms-interpolation-mode: bicubic; } } ================================================ FILE: web/css/pkmnstats.css ================================================ .gtsPokemonSummary .row { position: relative; } .gtsPokemonSummary .nickname { font-size: 12pt; font-weight: bold; color: black; margin-bottom: 4px; } .gtsPokemonSummary .portrait, .gtsPokemonSummary li.portrait { width: 96px; height: 96px; padding: 4px; border-radius: 20px; background-color: white; } .gtsPokemonSummary .pokeball { } .gtsPokemonSummary .marks, .gtsPokemonSummary li.marks { width: 104px; color: #e0e0e0; color: rgba(128,128,128,0.2); font-family: 'Meiryo UI',sans-serif; } .gtsOffer .colPortrait, .gtsOffer .pfFormValue.colPortrait { width: 104px; padding-top: 8px; } .colPortrait ul { width: 104px; white-space: nowrap; } .marks .m { color: #808080; } .specialFlags, li.specialFlags { width: 104px; } .shiny { font-weight: bold; vertical-align: middle; color: #ee0000; } .pkrs, .pkrs_cure { font-weight: bold; vertical-align: middle; color: white; background-color: #9761e9; font-size: 8px; padding: 1px 5px 1px 5px; border-radius: 5px; } .gtsPokemonSummary ul, .gtsPokemonSummary li { list-style-type: none; margin: 0; padding: 0; } .gtsPokemonSummary li { margin-bottom: 4px; } .gtsPokemonSummary img.item, .gtsPokemonSummary img.speciesSmall { vertical-align: middle; position: relative; } .gtsPokemonSummary img.item { margin: -5px 0 -3px -4px; } .gtsPokemonSummary img.speciesSmall { margin: -10px -3px -4px -10px; } .pfFormGroup.pfGroupMoves { margin-top: 16px; overflow: hidden; border-radius: 4px; } .pfFormGroup .type { border-bottom: none; background-color: #f2f2f2; width: 64px; } .gtsPokemonSummary .pfFormKey { width: 64px; } .gtsPokemonSummary .pfFormValue { width: 180px; } .gtsPokemonSummary .pfColumn.colBasic1 { width: 104px; } .gtsPokemonSummary .nextIn { display: inline; position: absolute; right: 8px; font-size: 8pt; margin-top: 3px; } .pfFormGroup .type { } .pfFormGroup .move .type { height: auto; display: table-cell; border-radius: 0; text-align: left; padding: 4px 8px; } .pfFormGroup .move .pp { float: right; } .gtsProgress.hpBar .progress { background-color: #2dd350; } .gtsProgress.health50 .progress { background-color: #ffc321; } .gtsProgress.health25 .progress { background-color: #ff8063; } .gtsProgress.expBar .progress { background-color: #43c4ff; } .gtsOffer { margin: 8px 0; width: 672px; } .gtsOffer .pfColumn { } ================================================ FILE: web/css/types.css ================================================ .type.normal { background-color: #b0b098; } .type.fighting { background-color: #c03028; } .type.flying { background-color: #b0a0ff; } .type.poison { background-color: #a828a8; } .type.ground { background-color: #e8c870; } .type.rock { background-color: #b89848; } .type.bug { background-color: #b0d028; } .type.ghost { background-color: #705898; } .type.steel { background-color: #c0c0d8; } .type.fire { background-color: #ff8038; } .type.water { background-color: #6898f8; } .type.grass { background-color: #58c820; } .type.electric { background-color: #ffc800; } .type.psychic { background-color: #f858a0; } .type.ice { background-color: #70e0e0; } .type.dragon { background-color: #7038f8; } .type.dark { background-color: #705848; } .type.question { background-color: #68a090; } .type.shadow { background-color: #305858; } .type.fairy { background-color: #ff98d8; } .type { display: inline-block; font-size: 13px; line-height: 0; vertical-align: middle; padding: 10px 0; width: 64px; height: 0; color: white; font-weight: bold; text-align: center; text-shadow: 0 1px 0 rgba(0,0,0,0.3); box-shadow: 0 -1px 0 0 rgba(0,0,0,0.3) inset; border-radius: 7px; background-color: #f2f2f2; background-image: -moz-linear-gradient(top, transparent 0%, rgba(0,0,0,0.1) 100%); /* FF3.6+ */ background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%,transparent), color-stop(100%,rgba(0,0,0,0.1))); /* Chrome,Safari4+ */ background-image: -webkit-linear-gradient(top, transparent 0%,rgba(0,0,0,0.1) 100%); /* Chrome10+,Safari5.1+ */ background-image: -o-linear-gradient(top, transparent 0%,rgba(0,0,0,0.1) 100%); /* Opera 11.10+ */ background-image: -ms-linear-gradient(top, transparent 0%,rgba(0,0,0,0.1) 100%); /* IE10+ */ background-image: linear-gradient(to bottom, transparent 0%,rgba(0,0,0,0.1) 100%); /* W3C */ } ================================================ FILE: web/gts/Default.aspx ================================================ <%@ Page Title="" Language="C#" MasterPageFile="~/masters/MasterPage.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PkmnFoundations.GTS.AllPokemon" %> <%@ Register TagPrefix="pf" Namespace="PkmnFoundations.Web" Assembly="PkmnFoundations.Web" %> <%@ Register TagPrefix="pf" TagName="PokemonPicker" Src="~/controls/PokemonPicker.ascx" %>
      Species <%-- todo: limit pokemon to gen4 when gen4 is checked --%> Version
      Level to
      Gender

      No Pokémon were found matching these terms.

      • <%# CreateOfferImage(Container.DataItem) %>
      • <%# CreatePokeball(Container.DataItem) %> Lv. <%# CreateLevel(Container.DataItem) %> <%# CreateGender(Container.DataItem) %> <%# CreatePokerus(Container.DataItem) %>
      • <%# CreateAdminLinks(Container.DataItem) %>
      Name <%# CreateNickname(Container.DataItem) %> Offered by <%# CreateTrainer(Container.DataItem) %>
      Species <%# CreateSpecies(Container.DataItem) %> (#<%# CreatePokedex(Container.DataItem) %>)
      Held item <%# CreateHeldItem(Container.DataItem) %> Wanted <%# CreateWantedSpecies(Container.DataItem) %>
      Nature <%# CreateNature(Container.DataItem) %> <%# CreateWantedGender(Container.DataItem) %> <%# CreateWantedLevel(Container.DataItem) %>
      Ability <%# CreateAbility(Container.DataItem) %> Date <%# CreateDate(Container.DataItem) %>
      ================================================ FILE: web/gts/Default.aspx.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using PkmnFoundations.Data; using PkmnFoundations.Pokedex; using PkmnFoundations.Structures; using PkmnFoundations.Web; using PkmnFoundations.Wfc; namespace PkmnFoundations.GTS { public partial class AllPokemon : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Pokedex.Pokedex pokedex = AppStateHelper.Pokedex(Application); int species = ppSpecies.Value ?? 0; int minLevel = Convert.ToInt32(txtLevelMin.Text); int maxLevel = Convert.ToInt32(txtLevelMax.Text); Genders gender = Genders.Either; if (chkMale.Checked && !chkFemale.Checked) gender = Genders.Male; if (chkFemale.Checked && !chkMale.Checked) gender = Genders.Female; if (rbGen4.Checked) { GtsRecord4[] records4 = Database.Instance.GtsSearch4(pokedex, 0, (ushort)species, gender, (byte)minLevel, (byte)maxLevel, 0, -1); rptPokemon.DataSource = records4; rptPokemon.DataBind(); phNone.Visible = records4.Length == 0; } else if (rbGen5.Checked) { GtsRecord5[] records5 = Database.Instance.GtsSearch5(pokedex, 0, (ushort)species, gender, (byte)minLevel, (byte)maxLevel, 0, -1); rptPokemon.DataSource = records5; rptPokemon.DataBind(); phNone.Visible = records5.Length == 0; } txtLevelMin.Attributes["onchange"] = "changedMin(\'" + txtLevelMin.ClientID + "\', \'" + txtLevelMax.ClientID + "\');"; txtLevelMax.Attributes["onchange"] = "changedMax(\'" + txtLevelMin.ClientID + "\', \'" + txtLevelMax.ClientID + "\');"; } private string FormatLevels(byte min, byte max) { if (min == 0 && max == 0) { return "Any level"; } else if (min == 0) { return String.Format("Lv. {0} and under", max); } else if (max == 0) { return String.Format("Lv. {0} and up", min); } else if (min == max) { return String.Format("Lv. {0}", min); } else { return String.Format("Lv. {0} to {1}", min, max); } } protected string CreateOfferImage(object DataItem) { try { GtsRecordBase record = (GtsRecordBase)DataItem; return "\"""; } catch { return "???"; } } protected string CreatePokeball(object DataItem) { try { GtsRecordBase record = (GtsRecordBase)DataItem; // Hide pokeballs with incorrect numbers until we catalog them. if (record.Pokemon.Pokeball == null) return ""; string itemName = Common.HtmlEncode(record.Pokemon.Pokeball.Name.ToString()); return "\"""; } catch { return "???"; } } protected string CreatePokerus(object DataItem) { try { GtsRecordBase record = (GtsRecordBase)DataItem; switch (record.Pokemon.Pokerus) { case Pokerus.Infected: return "PKRS"; case Pokerus.Cured: case Pokerus.None: default: return ""; } } catch { return ""; } } protected string CreateLevel(object DataItem) { GtsRecordBase record = (GtsRecordBase)DataItem; return record.Level.ToString(); } protected string CreateGender(object DataItem) { GtsRecordBase record = (GtsRecordBase)DataItem; return Format.GenderSymbol(record.Gender); } protected string CreateNickname(object DataItem) { try { GtsRecordBase record = (GtsRecordBase)DataItem; return Common.HtmlEncode(record.Pokemon.Nickname); } catch { return "???"; } } protected string CreateSpecies(object DataItem) { try { Pokedex.Pokedex pokedex = AppStateHelper.Pokedex(Application); GtsRecordBase record = (GtsRecordBase)DataItem; return Common.HtmlEncode(pokedex.Species[record.Species].Name.ToString()); } catch { return "???"; } } protected string CreatePokedex(object DataItem) { try { GtsRecordBase record = (GtsRecordBase)DataItem; return Common.HtmlEncode(record.Species.ToString()); } catch { return "???"; } } protected string CreateHeldItem(object DataItem) { try { GtsRecordBase record = (GtsRecordBase)DataItem; if (record.Pokemon.HeldItem == null) return ""; string itemName = Common.HtmlEncode(record.Pokemon.HeldItem.Name.ToString()); return "\""" + itemName; } catch { return "???"; } } protected string CreateNature(object DataItem) { try { GtsRecordBase record = (GtsRecordBase)DataItem; return Common.HtmlEncode(record.Pokemon.Nature.ToString()); } catch { return "???"; } } protected string CreateAbility(object DataItem) { try { GtsRecordBase record = (GtsRecordBase)DataItem; return Common.HtmlEncode(record.Pokemon.Ability.Name.ToString()); } catch { return "???"; } } protected string CreateTrainer(object DataItem) { GtsRecordBase record = (GtsRecordBase)DataItem; return Common.HtmlEncode(record.TrainerName); } protected string CreateWantedSpecies(object DataItem) { Pokedex.Pokedex pokedex = AppStateHelper.Pokedex(Application); GtsRecordBase record = (GtsRecordBase)DataItem; Species species = pokedex.Species[record.RequestedSpecies]; return "\""" + String.Format("{0} (#{1})", Common.HtmlEncode(species.Name.ToString()), record.RequestedSpecies); } protected string CreateWantedGender(object DataItem) { GtsRecordBase record = (GtsRecordBase)DataItem; return Format.GenderSymbol(record.RequestedGender); } protected string CreateWantedLevel(object DataItem) { GtsRecordBase record = (GtsRecordBase)DataItem; return FormatLevels(record.RequestedMinLevel, record.RequestedMaxLevel); } protected string CreateDate(object DataItem) { GtsRecordBase record = (GtsRecordBase)DataItem; if (record.TimeDeposited == null) return ""; return Common.HtmlEncode(((DateTime)record.TimeDeposited).ToString("f")); } protected string CreateAdminLinks(object DataItem) { #if DEBUG GtsRecordBase record = (GtsRecordBase)DataItem; StringBuilder result = new StringBuilder(); result.Append("
    • Details
    • "); return result.ToString(); #else return ""; #endif } } } ================================================ FILE: web/gts/Default.aspx.designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace PkmnFoundations.GTS { public partial class AllPokemon { /// /// HeaderColour1 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::PkmnFoundations.Web.HeaderColour HeaderColour1; /// /// theForm control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.HtmlControls.HtmlForm theForm; /// /// ppSpecies control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::PkmnFoundations.Web.controls.PokemonPicker ppSpecies; /// /// rbGen4 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.RadioButton rbGen4; /// /// lblGen4 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblGen4; /// /// rbGen5 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.RadioButton rbGen5; /// /// lblGen5 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblGen5; /// /// btnSearch control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Button btnSearch; /// /// txtLevelMin control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox txtLevelMin; /// /// txtLevelMax control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox txtLevelMax; /// /// chkMale control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.CheckBox chkMale; /// /// chkFemale control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.CheckBox chkFemale; /// /// phNone control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.PlaceHolder phNone; /// /// rptPokemon control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Repeater rptPokemon; } } ================================================ FILE: web/gts/Pokemon.aspx ================================================ <%@ Page Title="" Language="C#" MasterPageFile="~/masters/MasterPage.master" AutoEventWireup="true" CodeBehind="Pokemon.aspx.cs" Inherits="PkmnFoundations.Web.gts.Pokemon" %> <%@ Register TagPrefix="pf" Namespace="PkmnFoundations.Web" Assembly="PkmnFoundations.Web" %> <%@ Import Namespace="PkmnFoundations.Pokedex" %> <%@ Import Namespace="PkmnFoundations.Structures" %>
      • <%-- todo: use images for pkrs status --%> PKRS CURED  
      • Lv.

      Species
      Pokédex #
      Type  
      OT
      ID No.
      Exp.
      Held item
      Nature
      Ability
      Version
      Hax check
      Offerer pid
      IV EV Stat
      HP /
      Attack
      Defense
      Sp. Atk
      Sp. Def
      Speed
      ">
      "> <%# ((MoveSlot)Container.DataItem).Move == null ? "" : ((MoveSlot)Container.DataItem).Move.Type.Name.ToString() %> <%# ((MoveSlot)Container.DataItem).Move == null ? " " : ((MoveSlot)Container.DataItem).Move.Name.ToString() %> <%# ((MoveSlot)Container.DataItem).Move == null ? "" : ((MoveSlot)Container.DataItem).RemainingPP.ToString() + " / " %> <%# ((MoveSlot)Container.DataItem).Move == null ? "" : ((MoveSlot)Container.DataItem).PP.ToString() %>
      Unknown ribbon in position <%# ((int)Container.DataItem).ToString() %>.
      ================================================ FILE: web/gts/Pokemon.aspx.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using PkmnFoundations.Data; using PkmnFoundations.Pokedex; using PkmnFoundations.Structures; using PkmnFoundations.Support; using PkmnFoundations.Wfc; namespace PkmnFoundations.Web.gts { public partial class Pokemon : System.Web.UI.Page { protected void Page_Init(object sender, EventArgs e) { #if !DEBUG throw new WebException(403); #endif } protected void Page_Load(object sender, EventArgs e) { Pokedex.Pokedex pokedex = AppStateHelper.Pokedex(Application); GtsRecordBase record = null; PokemonPartyBase pkmn = null; if (Request.QueryString.Count == 0 || Request.QueryString.Count > 2) throw new WebException(400); if (Request.QueryString["offer"] != null || Request.QueryString["exchange"] != null) { String generation = Request.QueryString["g"]; if (generation == null || Request.QueryString.Count != 2) throw new WebException(400); int tradeId; bool isExchanged; if (Request.QueryString["offer"] != null) { tradeId = Convert.ToInt32(Request.QueryString["offer"]); isExchanged = false; } else if (Request.QueryString["exchange"] != null) { tradeId = Convert.ToInt32(Request.QueryString["exchange"]); isExchanged = true; } else { AssertHelper.Unreachable(); throw new WebException(400); } // todo: when userprofiles are ready, add checks that they allow viewing their GTS history switch (generation) { case "4": { record = Database.Instance.GtsGetRecord4(pokedex, tradeId, isExchanged, true); if (record != null) pkmn = record.Pokemon; } break; case "5": { record = Database.Instance.GtsGetRecord5(pokedex, tradeId, isExchanged, true); if (record != null) pkmn = record.Pokemon; } break; default: throw new WebException(400); } } else if (Request.QueryString["check"] != null) { int checkId = Convert.ToInt32(Request.QueryString["check"]); throw new NotImplementedException(); } else throw new WebException(400); if (pkmn == null) throw new WebException(403); Bind(record); } private void Bind(GtsRecordBase record) { PokemonPartyBase pkmn = record.Pokemon; litNickname.Text = pkmn.Nickname; bool shiny = pkmn.IsShiny; imgPokemon.ImageUrl = WebFormat.PokemonImageLarge(pkmn); imgPokemon.AlternateText = pkmn.Species.Name.ToString(); phShiny.Visible = shiny; litMarks.Text = WebFormat.Markings(pkmn.Markings); imgPokeball.ImageUrl = WebFormat.ItemImage(pkmn.Pokeball); imgPokeball.AlternateText = pkmn.Pokeball.Name.ToString(); imgPokeball.ToolTip = pkmn.Pokeball.Name.ToString(); litLevel.Text = pkmn.Level.ToString(); litGender.Text = WebFormat.Gender(pkmn.Gender); litTrainerMemo.Text = pkmn.TrainerMemo.ToString(); litCharacteristic.Text = pkmn.Characteristic.ToString(); litSpecies.Text = pkmn.Species.Name.ToString(); litPokedex.Text = pkmn.SpeciesID.ToString("000"); FormStats fs = pkmn.Form.BaseStats(pkmn.Generation); litType1.Text = fs.Type1 == null ? "" : WebFormat.RenderType(fs.Type1); litType2.Text = fs.Type2 == null ? "" : WebFormat.RenderType(fs.Type2); litOtName.Text = Common.HtmlEncode(pkmn.TrainerName); litTrainerId.Text = (pkmn.TrainerID & 0xffff).ToString("00000"); litExperience.Text = pkmn.Experience.ToString(); if (pkmn.Level < 100) { int expCurrLevel = PokemonBase.ExperienceAt(pkmn.Level, pkmn.Species.GrowthRate); int expNextLevel = PokemonBase.ExperienceAt(pkmn.Level + 1, pkmn.Species.GrowthRate); int progress = pkmn.Experience - expCurrLevel; int nextIn = expNextLevel - pkmn.Experience; litExperienceNext.Text = String.Format("next in {0}", nextIn); litExpProgress.Text = WebFormat.RenderProgress(progress, expNextLevel - expCurrLevel); } else { litExperienceNext.Text = ""; litExpProgress.Text = WebFormat.RenderProgress(0, 1); } if (pkmn.HeldItem != null) { imgHeldItem.Visible = true; imgHeldItem.ImageUrl = WebFormat.ItemImage(pkmn.HeldItem); litHeldItem.Text = pkmn.HeldItem.Name.ToString(); } else { imgHeldItem.Visible = false; litHeldItem.Text = ""; } litNature.Text = pkmn.Nature.ToString(); // todo: i18n litAbility.Text = pkmn.Ability == null ? "" : pkmn.Ability.Name.ToString(); litVersion.Text = pkmn.Version.ToString(); litHaxCheck.Text = pkmn.Validate().IsValid ? "Pass" : "Fail"; litOffererPid.Text = record.PID.ToString(); // xxx: loop litHpCurr.Text = pkmn.HP.ToString(); litHp.Text = pkmn.Stats[Stats.Hp].ToString(); litHpProgress.Text = WebFormat.RenderProgress(pkmn.HP, pkmn.Stats[Stats.Hp]); litAtk.Text = pkmn.Stats[Stats.Attack].ToString(); litDef.Text = pkmn.Stats[Stats.Defense].ToString(); litSAtk.Text = pkmn.Stats[Stats.SpecialAttack].ToString(); litSDef.Text = pkmn.Stats[Stats.SpecialDefense].ToString(); litSpeed.Text = pkmn.Stats[Stats.Speed].ToString(); litHpIv.Text = pkmn.IVs[Stats.Hp].ToString(); litAtkIv.Text = pkmn.IVs[Stats.Attack].ToString(); litDefIv.Text = pkmn.IVs[Stats.Defense].ToString(); litSAtkIv.Text = pkmn.IVs[Stats.SpecialAttack].ToString(); litSDefIv.Text = pkmn.IVs[Stats.SpecialDefense].ToString(); litSpeedIv.Text = pkmn.IVs[Stats.Speed].ToString(); litHpEv.Text = pkmn.EVs[Stats.Hp].ToString(); litAtkEv.Text = pkmn.EVs[Stats.Attack].ToString(); litDefEv.Text = pkmn.EVs[Stats.Defense].ToString(); litSAtkEv.Text = pkmn.EVs[Stats.SpecialAttack].ToString(); litSDefEv.Text = pkmn.EVs[Stats.SpecialDefense].ToString(); litSpeedEv.Text = pkmn.EVs[Stats.Speed].ToString(); phPkrs.Visible = pkmn.Pokerus == Pokerus.Infected; phPkrsCured.Visible = pkmn.Pokerus == Pokerus.Cured; rptMoves.DataSource = pkmn.Moves; rptMoves.DataBind(); rptRibbons.DataSource = pkmn.Ribbons; rptRibbons.DataBind(); rptUnknownRibbons.DataSource = pkmn.UnknownRibbons; rptUnknownRibbons.DataBind(); } } } ================================================ FILE: web/gts/Pokemon.aspx.designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace PkmnFoundations.Web.gts { public partial class Pokemon { /// /// phSummary control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.PlaceHolder phSummary; /// /// litNickname control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litNickname; /// /// imgPokemon control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Image imgPokemon; /// /// phShiny control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.PlaceHolder phShiny; /// /// phPkrs control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.PlaceHolder phPkrs; /// /// phPkrsCured control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.PlaceHolder phPkrsCured; /// /// litMarks control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litMarks; /// /// imgPokeball control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Image imgPokeball; /// /// litLevel control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litLevel; /// /// litGender control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litGender; /// /// litTrainerMemo control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litTrainerMemo; /// /// litCharacteristic control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litCharacteristic; /// /// litSpecies control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litSpecies; /// /// litPokedex control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litPokedex; /// /// litType1 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litType1; /// /// litType2 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litType2; /// /// litOtName control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litOtName; /// /// litTrainerId control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litTrainerId; /// /// litExperience control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litExperience; /// /// litExperienceNext control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litExperienceNext; /// /// litExpProgress control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litExpProgress; /// /// imgHeldItem control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Image imgHeldItem; /// /// litHeldItem control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litHeldItem; /// /// litNature control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litNature; /// /// litAbility control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litAbility; /// /// litVersion control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litVersion; /// /// litHaxCheck control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litHaxCheck; /// /// litOffererPid control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litOffererPid; /// /// litHpIv control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litHpIv; /// /// litHpEv control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litHpEv; /// /// litHpCurr control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litHpCurr; /// /// litHp control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litHp; /// /// litHpProgress control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litHpProgress; /// /// litAtkIv control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litAtkIv; /// /// litAtkEv control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litAtkEv; /// /// litAtk control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litAtk; /// /// litDefIv control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litDefIv; /// /// litDefEv control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litDefEv; /// /// litDef control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litDef; /// /// litSAtkIv control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litSAtkIv; /// /// litSAtkEv control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litSAtkEv; /// /// litSAtk control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litSAtk; /// /// litSDefIv control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litSDefIv; /// /// litSDefEv control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litSDefEv; /// /// litSDef control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litSDef; /// /// litSpeedIv control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litSpeedIv; /// /// litSpeedEv control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litSpeedEv; /// /// litSpeed control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litSpeed; /// /// rptMoves control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Repeater rptMoves; /// /// rptRibbons control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Repeater rptRibbons; /// /// rptUnknownRibbons control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Repeater rptUnknownRibbons; } } ================================================ FILE: web/masters/LeftColumn.master ================================================ <%@ Master Language="C#" MasterPageFile="~/masters/MasterPage.master" AutoEventWireup="true" CodeBehind="ThreeColumn.master.cs" Inherits="PkmnFoundations.GTS.ThreeColumn" %>
      ================================================ FILE: web/masters/LeftColumn.master.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace PkmnFoundations.GTS.masters { public partial class LeftColumn : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { } } } ================================================ FILE: web/masters/LeftColumn.master.designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace PkmnFoundations.GTS.masters { public partial class LeftColumn { } } ================================================ FILE: web/masters/MasterPage.master ================================================ <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.master.cs" Inherits="PkmnFoundations.GTS.MasterPage" %> <%@ Register TagPrefix="pf" Namespace="PkmnFoundations.Web" Assembly="PkmnFoundations.Web" %> <%@ Register TagPrefix="pf" TagName="DnsAddress" Src="~/controls/DnsAddress.ascx" %> Poké Classic Network
      • DNS:
      • Pokémon available for offer.
      • battle videos.
      login
      • Main
      • GTS
      • Battle Videos
      • Dream World
      • Pokédex
      • My Profile
      <% switch (HeaderCssClass) { case "home": %>
      • Home
      <% break; case "gts": %>
      • Available Pokémon
      <% break; } %>

      Maintenance periods are Thursdays at UTC 0300.

      Pokémon is © 1995-2022 Nintendo / Creatures / GAME FREAK. This service is not affiliated with Nintendo or GAME FREAK in any way.

      ================================================ FILE: web/masters/MasterPage.master.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using PkmnFoundations.Data; namespace PkmnFoundations.GTS { public partial class MasterPage : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { int avail4, avail5; ulong bvCount4, bvCount5; // todo: move this to a CacheManager sort of class if (Cache["pkmncfPokemonCount4"] == null) { avail4 = Database.Instance.GtsAvailablePokemon4(); Cache.Insert("pkmncfPokemonCount4", avail4, null, DateTime.Now.AddMinutes(1), System.Web.Caching.Cache.NoSlidingExpiration); } else avail4 = Convert.ToInt32(Cache["pkmncfPokemonCount4"]); if (Cache["pkmncfPokemonCount5"] == null) { avail5 = Database.Instance.GtsAvailablePokemon5(); Cache.Insert("pkmncfPokemonCount5", avail5, null, DateTime.Now.AddMinutes(1), System.Web.Caching.Cache.NoSlidingExpiration); } else avail5 = Convert.ToInt32(Cache["pkmncfPokemonCount5"]); if (Cache["pkmncfBattleVideoCount4"] == null) { bvCount4 = Database.Instance.BattleVideoCount4(); Cache.Insert("pkmncfBattleVideoCount4", bvCount4, null, DateTime.Now.AddMinutes(1), System.Web.Caching.Cache.NoSlidingExpiration); } else bvCount4 = Convert.ToUInt64(Cache["pkmncfBattleVideoCount4"]); if (Cache["pkmncfBattleVideoCount5"] == null) { bvCount5 = Database.Instance.BattleVideoCount5(); Cache.Insert("pkmncfBattleVideoCount5", bvCount5, null, DateTime.Now.AddMinutes(1), System.Web.Caching.Cache.NoSlidingExpiration); } else bvCount5 = Convert.ToUInt64(Cache["pkmncfBattleVideoCount5"]); litPokemon.Text = (avail4 + avail5).ToString(); litVideos.Text = (bvCount4 + bvCount5).ToString(); } public String HeaderCssClass { get { return litHeaderCssClassKeep.Text; } set { litHeaderCssClassKeep.Text = value; } } } } ================================================ FILE: web/masters/MasterPage.master.designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace PkmnFoundations.GTS { public partial class MasterPage { /// /// HeaderColour1 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::PkmnFoundations.Web.HeaderColour HeaderColour1; /// /// cpHead control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.ContentPlaceHolder cpHead; /// /// litHeaderCssClassKeep control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litHeaderCssClassKeep; /// /// hlLogl control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.HyperLink hlLogl; /// /// imgLogo control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::PkmnFoundations.Web.RetinaImage imgLogo; /// /// litPokemon control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litPokemon; /// /// litVideos control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litVideos; /// /// hlMain control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.HyperLink hlMain; /// /// hlGts control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.HyperLink hlGts; /// /// hlBattleVideos control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.HyperLink hlBattleVideos; /// /// hlDreamWorld control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.HyperLink hlDreamWorld; /// /// hlPokedex control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.HyperLink hlPokedex; /// /// hlStat control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.HyperLink hlStat; /// /// hlMain_Home control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.HyperLink hlMain_Home; /// /// hlGts_Offers control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.HyperLink hlGts_Offers; /// /// cpMain control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.ContentPlaceHolder cpMain; /// /// hlFooterGithub control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.HyperLink hlFooterGithub; /// /// hlFooterTwitter control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.HyperLink hlFooterTwitter; /// /// hlFooterDiscord control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.HyperLink hlFooterDiscord; /// /// hlWiimmfi control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.HyperLink hlWiimmfi; /// /// hlKaeru control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.HyperLink hlKaeru; } } ================================================ FILE: web/masters/ThreeColumn.master ================================================ <%@ Master Language="C#" MasterPageFile="~/masters/MasterPage.master" AutoEventWireup="true" CodeBehind="ThreeColumn.master.cs" Inherits="PkmnFoundations.GTS.ThreeColumn" %>
      ================================================ FILE: web/masters/ThreeColumn.master.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace PkmnFoundations.GTS { public partial class ThreeColumn : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { } } } ================================================ FILE: web/masters/ThreeColumn.master.designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace PkmnFoundations.GTS { public partial class ThreeColumn { /// /// cpHead control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.ContentPlaceHolder cpHead; /// /// cpHeadingArea control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.ContentPlaceHolder cpHeadingArea; /// /// cpLeft control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.ContentPlaceHolder cpLeft; /// /// cpMain control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.ContentPlaceHolder cpMain; /// /// cpRight control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.ContentPlaceHolder cpRight; } } ================================================ FILE: web/packages.config ================================================  ================================================ FILE: web/scripts/form.js ================================================ function labelTextBox_Change() { if (this.value.length > 0) $(this).addClass("hasContent"); else $(this).removeClass("hasContent"); } $(document).ready(function () { $("input").change(labelTextBox_Change); $("input").each(labelTextBox_Change); }) // foreign lookup function pfHandleLookupKeypress(id_outer, id_value, id_results, count, url) { if (pfShowLookupResults(id_value, id_results)) { pfHandleLookup(id_outer, id_value, id_results, count, url); } } // keyup function pfHandleLookupKeypress3(id_outer, id_value, id_results, count, url) { var ctrl_text = document.getElementById(id_value); if (ctrl_text.prevValue && ctrl_text.prevValue == ctrl_text.value) { ctrl_text.prevValue = ctrl_text.value; return; } ctrl_text.prevValue = ctrl_text.value; var ctrl_value = document.getElementById(id_outer + "_hdSelectedValue"); ctrl_value.value = ""; if (ctrl_value.onchange) ctrl_value.onchange(); pfHandleLookupKeypress(id_outer, id_value, id_results, count, url); } // keypress function pfHandleLookupKeypress2(id_outer, id_value, id_results, count, url, event) { var ctrl_value = document.getElementById(id_outer + "_hdSelectedValue"); var ctrl_text = document.getElementById(id_value); if (event && pfLookupResultsVisible(id_results) && (event.keyCode == 13 || event.keyCode == 9)) { var ctrl_result1 = document.getElementById(id_outer + "_result1"); if (ctrl_result1) { ctrl_value.value = ctrl_result1.getAttribute("data-value"); if (ctrl_value.onchange) ctrl_value.onchange(); ctrl_text.value = ctrl_result1.getAttribute("data-text"); } pfHideLookupResults(id_results); ctrl_text.prevValue = ctrl_text.value; return false; } else if (event && (event.keyCode == 27)) { pfHideLookupResults(id_results); ctrl_text.prevValue = ctrl_text.value; return true; } else if (event) { pfHandleLookupKeypress(id_outer, id_value, id_results, count, url); return true; } else { return true; } } function pfHandleLookup(id_outer, id_value, id_results, count, url) { var ctrl_value = document.getElementById(id_value); if (ctrl_value.value.length > 1) { var ctrl_results = document.getElementById(id_results); if (ctrl_results.pfLookupBlocked == undefined) ctrl_results.pfLookupBlocked = false; if (ctrl_results.pfLastLookup == undefined) ctrl_results.pfLastLookup = ""; var search = encodeURIComponent(ctrl_value.value); if (ctrl_results.pfLastLookup == search) return; if (ctrl_results.pfLookupBlocked) return; // todo: timeout this to deal with slow server performance ctrl_results.pfLastLookup = search; var request = $.ajax(url, { complete: function (response, status, xhr) { pfReceiveLookupResults(response.responseText, response.status, id_outer, id_value, id_results, count, url); }, data: { n: count, q: search, c: id_outer }, method: "POST" }) ctrl_results.pfLookupBlocked = true; } } function pfShowLookupResults(id_value, id_results) { if (document.getElementById(id_value).value.length > 1) { document.getElementById(id_results).style.visibility = "visible"; return true; } else { document.getElementById(id_results).style.visibility = "hidden"; return false; } } function pfReceiveLookupResults(response, status, id_outer, id_value, id_results, count, url) { var ctrl_results = document.getElementById(id_results); if (ctrl_results.pfLastLookup == undefined) ctrl_results.pfLastLookup = ""; ctrl_results.pfLookupBlocked = false; if (status == "200") { ctrl_results.innerHTML = "
      " + response + "
      "; } else { ctrl_results.innerHTML = "server error"; } var search = encodeURIComponent(document.getElementById(id_value).value); if (ctrl_results.pfLastLookup != search) pfHandleLookup(id_outer, id_value, id_results, count, url); } function pfHideLookupResults(id) { document.getElementById(id).style.visibility = "hidden"; } function pfSelectLookupResult(id_main, id_value, value, id_text, text) { document.getElementById(id_value).value = value; document.getElementById(id_text).value = text; document.getElementById(id_main).blur(); var ctrl_value = document.getElementById(id_value); if (ctrl_value.onchange) ctrl_value.onchange(); } function pfLookupResultsVisible(id) { return document.getElementById(id).style.visibility == "visible"; } ================================================ FILE: web/scripts/retina.js ================================================ function setPixelRatioCookie(scale) { var expires = new Date(); expires.setDate(expires.getDate() + 21); document.cookie = "pixelRatio=" + scale + ";path=/;expires=" + expires; } setPixelRatioCookie(getPixelRatio()); function getPixelRatio() { if (window.devicePixelRatio != undefined) return window.devicePixelRatio; else if (window.screen.deviceXDPI != undefined) return window.screen.deviceXDPI / 96.0; else if (window.matchMedia != undefined) return bisectScale(1.0, 2.0, 0.005); else return 1.0; } function matchScale(scale) { var dpi = scale * 96.0; var dpi_int = Math.ceil(dpi); // ceil to get mathmatically correct results for non-int dpi return window.matchMedia("(min--moz-device-pixel-ratio: " + scale.toString() + ")").matches || // firefox 8-15 window.matchMedia("(-o-min-device-pixel-ratio: " + dpi_int.toString() + "/96)").matches || window.matchMedia("(-webkit-min-device-pixel-ratio: " + scale.toString() + ")").matches || window.matchMedia("(min-resolution: " + dpi.toString() + "dpi)").matches || window.matchMedia("(min-resolution: " + dpi_int.toString() + "dpi)").matches // firefox 7- doesn't understand non-int dpi units } function bisectScale(min, max, tolerance) { if (min + tolerance > max) return min; if (matchScale(max)) return max; if (!matchScale(min)) return min; if (matchScale((min + max) * 0.5)) return bisectScale((min + max) * 0.5, max, tolerance); return bisectScale(min, (min + max) * 0.5, tolerance); } function checkRetina(element, scale) { try { var data_design_width = element.getAttribute("data-design-width"); var data_design_height = element.getAttribute("data-design-height"); if (data_design_width !== null && data_design_height !== null) { var scaleX = $(element).width() / parseFloat(data_design_width); var scaleY = $(element).height() / parseFloat(data_design_height); scale *= Math.max(scaleX, scaleY); } else if (data_design_width !== null) { scale *= $(element).width() / parseFloat(data_design_width); } else if (data_design_height !== null) { scale *= $(element).height() / parseFloat(data_design_height); } var sizes = new Array(); var x = 0; for (x in element.attributes) { var attrName = element.attributes[x].name; if (attrName != undefined && attrName.length > 11 && attrName.substring(0, 11).toLowerCase() == "data-hires-") { sizes.push(parseFloat(attrName.substring(11))); } } sizes.sort(); var best = 0.0; for (x in sizes) { var f = sizes[x]; if (f === undefined) continue; if (best > 0.0 && f > scale && best >= scale) break; best = f; } if ($(element).hasClass("keephr") && element.retinaActiveScale && element.retinaActiveScale >= best) return; element.src = element.getAttribute("data-hires-" + best.toString()); element.retinaActiveScale = best; } catch (err) { } } function checkAllRetina() { var scale = getPixelRatio(); $(".retina").each(function () { checkRetina(this, scale); }); setPixelRatioCookie(scale); } function checkRetinaIn(element) { var scale = getPixelRatio(); $(".retina", element).each(function () { checkRetina(this, scale); }); } function handleBeforePrint() { window.rjsPrinting = true; checkAllRetina(); } function handleAfterPrint() { window.rjsPrinting = false; checkAllRetina(); } function handlePrintListener(mql) { window.rjsPrinting = mql.matches; checkAllRetina(); } window.rjsPrinting = false; if (document.addEventListener) document.addEventListener("DOMContentLoaded", checkAllRetina, false); else if (document.attachEvent) document.attachEvent("DOMContentLoaded", checkAllRetina, false); if (window.addEventListener) window.addEventListener("resize", checkAllRetina, false); else if (window.attachEvent) window.attachEvent("resize", checkAllRetina, false); if (window.addEventListener) window.addEventListener("beforeprint", handleBeforePrint, false); else if (window.attachEvent) window.attachEvent("beforeprint", handleBeforePrint, false); if (window.addEventListener) window.addEventListener("afterprint", handleAfterPrint, false); else if (window.attachEvent) window.attachEvent("afterprint", handleAfterPrint, false); if (window.matchMedia) window.matchMedia("print").addListener(handlePrintListener); ================================================ FILE: web/src/AppStateHelper.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using PkmnFoundations.Data; namespace PkmnFoundations.Web { public static class AppStateHelper { public static Pokedex.Pokedex Pokedex(HttpApplicationState application) { return GetTypedApplicationObject(application, "pkmncfPokedex", () => new Pokedex.Pokedex(Database.Instance, false)); } public static T GetTypedApplicationObject(HttpApplicationState application, String key, Func initializer) where T : class { object o = application[key]; T t = o as T; if (t == null) { t = initializer(); application.Add(key, t); } return t; } } } ================================================ FILE: web/src/Common.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; using MySql.Data.MySqlClient; using System.Configuration; using System.Text; namespace PkmnFoundations.Web { public static class Common { public static string HtmlEncode(string s) { return HttpUtility.HtmlEncode(s); } public static String JsEncode(String s) { StringBuilder result = new StringBuilder(); foreach (char c in s.ToCharArray()) { if (c == '\r') { result.Append("\\r"); } else if (c == '\n') { result.Append("\\n"); } else if (c == '\t') { result.Append("\\t"); } else if (Convert.ToUInt16(c) < 32) { } else if (NeedsJsEscape(c)) { result.Append('\\'); result.Append(c); } else result.Append(c); } return result.ToString(); } private static bool NeedsJsEscape(char c) { if (Convert.ToUInt16(c) < 32) return true; switch (c) { case '\"': case '\'': case '\\': return true; default: return false; // utf8 de OK } } public static string FormatReturns(string text, string ending) { return text.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", ending); } private static byte[] m_pad = null; /// /// Encode and decode Gen4 pkgdsprod requests/responses /// /// public static void CryptMessage(byte[] message) { if (m_pad == null) { m_pad = new byte[256]; FileStream s = File.Open(HttpContext.Current.Server.MapPath("~/pad.bin"), FileMode.Open); s.Read(m_pad, 0, m_pad.Length); s.Close(); } if (message.Length < 5) return; byte padOffset = (byte)(message[0] + message[4]); // encrypt and decrypt are the same operation... for (int x = 5; x < message.Length; x++) message[x] ^= m_pad[(x + padOffset) & 0xff]; } public static String ResolveUrl(String url) { url = url.Trim(); if (!(url[0] == '~')) return url; try { if (VirtualPathUtility.IsAppRelative(url)) return VirtualPathUtility.ToAbsolute(url); return url; } catch (HttpException) { return url; } } #region File extensions public static String GetExtension(String filename) { int Dot = filename.LastIndexOf('.') + 1; if (Dot < 1) return null; return filename.Substring(Dot, filename.Length - Dot).ToLowerInvariant(); } public static String GetExtension(String filename, out String namepart) { int Dot = filename.LastIndexOf('.') + 1; if (Dot < 1) { namepart = filename; return null; } namepart = filename.Substring(0, Dot - 1); return filename.Substring(Dot, filename.Length - Dot).ToLowerInvariant(); } public static MySqlConnection CreateConnection() { return new MySqlConnection(ConfigurationManager.ConnectionStrings["pkmnFoundationsConnectionString"].ConnectionString); } #endregion } } ================================================ FILE: web/src/DependencyNode.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; namespace PkmnFoundations.Web { internal class DependencyNode { public DependencyNode() { Dependencies = new HashSet(); } public DependencyNode(TKey key, TValue value) : this() { Key = key; Value = value; } public DependencyNode(TKey key, TValue value, HashSet dependencies) : this(key, value) { Dependencies = dependencies; } public TKey Key { get; set; } public TValue Value { get; set; } public HashSet Dependencies { get; private set; } public DependencyNode Clone() { return new DependencyNode(Key, Value, new HashSet(Dependencies)); } } internal class DependencyGraph { public DependencyGraph() { Graph = new List>(); } public DependencyGraph(List> graph) { Graph = graph; } public List> Graph; public Page Page = null; public List Resolve() { LinkedList> nodesList = new LinkedList>(Graph.Select(n => n.Clone())); List result = new List(nodesList.Count); // Remove inexistent keys from dependency lists. // First, obtain a complete set of existent keys. HashSet validKeys = new HashSet(); foreach (DependencyNode node in nodesList) validKeys.Add(node.Key); // Then, intersect each dependency list with this validKeys list foreach (DependencyNode node in nodesList) node.Dependencies.IntersectWith(validKeys); while (nodesList.Count > 0) { LinkedListNode> nodeLinked = nodesList.First; while (nodeLinked != null) { if (nodeLinked.Value.Dependencies.Count == 0) break; nodeLinked = nodeLinked.Next; } if (nodeLinked == null) { // we hit the end of the list without finding a dependency-less node. // this means there has to be a circular dependency. // ie. every remaining node in the list depends on some other remaining // node in the list. // todo: display the actual cycle (or an example if there's more than one) // in this exception. // algo: // Keep a collection of found nodes. // Start at the first node, adding it to the collection. // Move to the node of the first dependency of this node and add it to the collection. // Repeat until you reach a node which is already in the collection. // Output the collection of nodes, starting at the node which was already found. throw new CircularDependencyException("Circular dependency found in your links.\n" + "Keys:\n" + String.Join("\n", nodesList.Select(n => n.Key.ToString()).ToArray())); } // add this node to output, remove it as a dependency from the remaining nodes DependencyNode nodeOutput = nodeLinked.Value; nodesList.Remove(nodeLinked); foreach (DependencyNode nodeValue in nodesList) nodeValue.Dependencies.Remove(nodeOutput.Key); // fixme: possible issue: the dependencies on the output are all blank. result.Add(nodeOutput.Value); } return result; } } public class CircularDependencyException : Exception { // todo: We can keep a jagged list of all cycles found on this exception. public CircularDependencyException(String message) : base(message) { } } } ================================================ FILE: web/src/ForeignLookupSource.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Text; using Newtonsoft.Json; using PkmnFoundations.Data; using PkmnFoundations.Structures; namespace PkmnFoundations.Web { /// /// Summary description for ForeignLookupSource /// public class ForeignLookupSource : IHttpHandler, System.Web.SessionState.IRequiresSessionState { public ForeignLookupSource() { // // TODO: Add constructor logic here // } public void ProcessRequest(HttpContext context) { if (String.IsNullOrEmpty(context.Request.Form["n"]) || String.IsNullOrEmpty(context.Request.Form["q"]) || String.IsNullOrEmpty(context.Request.Form["c"])) { ServerError(context); return; } int rows = 0; if (!Int32.TryParse(context.Request.Form["n"], out rows)) { ServerError(context); return; } if (rows < 0) { ServerError(context); return; } string control_id = context.Request.Form["c"]; if (control_id.Contains('<') || control_id.Contains('>') || control_id.Contains('\"') || control_id.Contains('\'') || control_id.Contains('\\')) { ServerError(context); return; } Languages lang = Format.FromIso639_1(context.Request.QueryString["lang"] ?? "EN"); string format = context.Request.Form["f"] ?? "h"; if (!new[]{"h", "j"}.Contains(format)) { ServerError(context); return; } DataTable data; try { data = GetData(context, context.Request.Form["q"], rows, lang); } catch (Exception) { // todo: log error ServerError(context); return; } if (data == null || data.Rows.Count == 0) { EmptyResult(context, format); return; } if (!data.Columns.Contains("Text") || !data.Columns.Contains("Value")) { ServerError(context); return; } switch (format) { case "h": WriteHtml(context, data, control_id); break; case "j": WriteJson(context, data); break; default: // unreachable break; } } public bool IsReusable { get { return false; } } private void ServerError(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Write("Bad request"); context.Response.StatusCode = 400; } private void EmptyResult(HttpContext context, string format) { switch (format) { case "h": context.Response.ContentType = "text/plain"; context.Response.Write("No results"); break; case "j": context.Response.ContentType = "text/javascript"; context.Response.Write("[]"); break; default: // unreachable break; } } private void WriteHtml(HttpContext context, DataTable data, string control_id) { context.Response.ContentType = "text/plain"; StringBuilder builder = new StringBuilder(); int index = 0; bool hasHtml = data.Columns.Contains("html"); foreach (DataRow row in data.Rows) { string text = row["Text"].ToString(); // this breaks if value contains html control chars but is fine since all values will be int string value = row["Value"].ToString(); string html = hasHtml ? row["html"].ToString() : Common.HtmlEncode(text); builder.Remove(0, builder.Length); builder.Append("
      "); builder.Append(html); builder.Append("
      \n"); context.Response.Write(builder.ToString()); index++; } } private void WriteJson(HttpContext context, DataTable data) { context.Response.ContentType = "text/javascript"; ForeignLookupResult[] results = new ForeignLookupResult[data.Rows.Count]; for (int x = 0; x < results.Length; x++) { DataRow row = data.Rows[x]; results[x] = new ForeignLookupResult { t = DatabaseExtender.Cast(row["Text"]) ?? "", v = DatabaseExtender.Cast(row["Value"]) ?? 0 }; } context.Response.Write(JsonConvert.SerializeObject(results)); } protected virtual DataTable GetData(HttpContext context, string query, int rows, Languages lang) { return null; } } internal class ForeignLookupResult { public string t; public int v; } } ================================================ FILE: web/src/HeaderColour.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace PkmnFoundations.Web { public class HeaderColour : System.Web.UI.Control { public HeaderColour() { CssClass = null; this.PreRender += HeaderColour_PreRender; } private void HeaderColour_PreRender(object sender, EventArgs e) { SetHeaderCssClass(Page.Master); } private void SetHeaderCssClass(System.Web.UI.MasterPage master) { // recursively find the TOP master and set its HeaderCssClass if available. if (master == null) return; PkmnFoundations.GTS.MasterPage gtsMaster = master as PkmnFoundations.GTS.MasterPage; if (gtsMaster == null) { SetHeaderCssClass(master.Master); return; } gtsMaster.HeaderCssClass = CssClass; } protected override void LoadViewState(object savedState) { HeaderColourViewState state = (HeaderColourViewState)savedState; this.CssClass = state.CssClass; base.LoadViewState(state.ControlViewState); } protected override object SaveViewState() { HeaderColourViewState state = new HeaderColourViewState(); state.CssClass = this.CssClass; state.ControlViewState = base.SaveViewState(); return state; } public String CssClass { get; set; } [Serializable()] private struct HeaderColourViewState { public object ControlViewState; public String CssClass; } } } ================================================ FILE: web/src/OnceTemplate.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace PkmnFoundations.Web { /// /// Control which only renders once per unique key on a given page. /// public class OnceTemplate : System.Web.UI.WebControls.PlaceHolder { public OnceTemplate() : base() { } public String Key { get; set; } private HashSet m_keys = null; private HashSet Keys { get { if (m_keys != null) return m_keys; if (!Page.Items.Contains("pkmncfOnceTemplate")) { m_keys = new HashSet(); Page.Items.Add("pkmncfOnceTemplate", m_keys); } else m_keys = (HashSet)Page.Items["pkmncfOnceTemplate"]; return m_keys; } } protected override void Render(System.Web.UI.HtmlTextWriter writer) { if (Keys.Contains(Key)) return; Keys.Add(Key); base.Render(writer); } } } ================================================ FILE: web/src/RequireCss.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace PkmnFoundations.Web { public class RequireCss : RequireLinkBase { public RequireCss() : base() { } public override void RenderHeader(System.Web.UI.HtmlTextWriter writer) { writer.AddAttribute("rel", "stylesheet"); writer.AddAttribute("href", ResolveUrl(CssUrl ?? "")); writer.AddAttribute("type", "text/css"); writer.RenderBeginTag("link"); writer.RenderEndTag(); } public String CssUrl { get; set; } public override string Key { get { if (base.Key != null) return base.Key; return CssUrl; } set { base.Key = value; } } } } ================================================ FILE: web/src/RequireLinkBase.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.HtmlControls; namespace PkmnFoundations.Web { public abstract class RequireLinkBase : System.Web.UI.Control { protected RequireLinkBase() : base() { this.Init += RequireLinkBase_Init; this.Load += RequireLinkBase_Load; this.PreRender += RequireLinkBase_PreRender; } void RequireLinkBase_Init(object sender, EventArgs e) { // todo: only bind once Page.PreRender += Page_PreRender; } void RequireLinkBase_Load(object sender, EventArgs e) { } void RequireLinkBase_PreRender(object sender, EventArgs e) { DependencyGraph graph = GetDependencyGraph(); DependencyNode node = new DependencyNode(Key, this, ParseDependencies(After ?? "")); if (!graph.Graph.Any(n => n.Key == Key)) graph.Graph.Add(node); // todo: merge dependencies if it's a dupe } void Page_PreRender(object sender, EventArgs e) { DependencyGraph graph = GetDependencyGraph(); if (graph.Page == null) { Page.Header.Controls.Add(new RequireLinkRenderer(GetDependencyGraph())); graph.Page = Page; } } public virtual String Key { get; set; } public String After { get; set; } public abstract void RenderHeader(System.Web.UI.HtmlTextWriter writer); /// /// Obtain a dependency graph which is specific to the Page instance /// and the control class /// private DependencyGraph GetDependencyGraph() { Type myType = this.GetType(); Dictionary> all_graphs; if (!Page.Items.Contains("pkmncfDependencyGraphs")) { all_graphs = new Dictionary>(); Page.Items.Add("pkmncfDependencyGraphs", all_graphs); } else all_graphs = (Dictionary>)Page.Items["pkmncfDependencyGraphs"]; if (all_graphs.ContainsKey(myType)) return all_graphs[myType]; DependencyGraph myGraph = new DependencyGraph(); all_graphs.Add(myType, myGraph); return myGraph; } private HashSet ParseDependencies(String dependencies) { return new HashSet(dependencies.Split(',').Select(s => s.Trim()).Where(s => s.Length > 0)); } } internal class RequireLinkRenderer : System.Web.UI.Control { public RequireLinkRenderer(DependencyGraph graph) : base() { m_graph = graph; } private DependencyGraph m_graph; protected override void Render(System.Web.UI.HtmlTextWriter writer) { List links = m_graph.Resolve(); foreach (RequireLinkBase link in links) link.RenderHeader(writer); } } } ================================================ FILE: web/src/RequireScript.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace PkmnFoundations.Web { public class RequireScript : RequireLinkBase { public RequireScript() : base() { } public override void RenderHeader(System.Web.UI.HtmlTextWriter writer) { writer.AddAttribute("src", ResolveUrl(ScriptUrl ?? "")); writer.AddAttribute("type", Type ?? "text/javascript"); writer.RenderBeginTag("script"); writer.RenderEndTag(); } public String ScriptUrl { get; set; } public String Type { get; set; } public override string Key { get { if (base.Key != null) return base.Key; return ScriptUrl; } set { base.Key = value; } } } } ================================================ FILE: web/src/RetinaImage.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Globalization; namespace PkmnFoundations.Web { public class RetinaImage : RetinaImageBase { /// /// Image with DPI substitution. Alternate filenames are generated based on a naming pattern. /// public RetinaImage() : base() { this.FormatString = "{3}{0}@{2:#.##}x.{1}"; this.AlternateSizes = ""; this.FormatScaleFactor = 1; this.Format1x = false; } public static String ScaledImageName(String filename, String format, float scale) { // todo: handle ? querystring String namepart; String extension = Common.GetExtension(filename, out namepart); int slash = namepart.LastIndexOf('/'); String fileNamepart, directory; if (slash >= 0) { fileNamepart = namepart.Substring(slash + 1); directory = namepart.Substring(0, slash + 1); } else { fileNamepart = namepart; directory = ""; } return String.Format(format, fileNamepart, extension, scale, directory); } protected override List GetScales() { List result = new List(); String[] split = AlternateSizes.Split(','); List scales = new List(split.Length + 1); if (Format1x) result.Add(new ImageRendition(ScaledImageName(ImageUrl, FormatString, FormatScaleFactor), 1.0f)); else result.Add(new ImageRendition(ImageUrl, 1.0f)); foreach (String s in split) { float result2; if (!Single.TryParse(s, NumberStyles.Number, nfi, out result2)) continue; result.Add(new ImageRendition(ScaledImageName(ImageUrl, FormatString, result2 * FormatScaleFactor), result2)); } return result; } private static NumberFormatInfo nfi = System.Globalization.CultureInfo.InvariantCulture.NumberFormat; protected override void LoadViewState(object savedState) { RetinaImageViewState viewstate = (RetinaImageViewState)savedState; base.LoadViewState(viewstate.RetinaImageBaseViewState); FormatString = viewstate.FormatString; AlternateSizes = viewstate.AlternateSizes; } protected override object SaveViewState() { RetinaImageViewState viewstate = new RetinaImageViewState(); viewstate.RetinaImageBaseViewState = base.SaveViewState(); viewstate.FormatString = FormatString; viewstate.AlternateSizes = AlternateSizes; return viewstate; } /// /// Format string for String.Format. /// 0: filename, 1: extension, 2: scale, 3: path /// public String FormatString { get; set; } public String AlternateSizes { get; set; } /// /// Multipy DPI scale by this constant in filenames. Useful for paths like /thumb_100/ and /thumb_200/ /// public float FormatScaleFactor { get; set; } /// /// If true, 1x images go through the format string. Otherwise they use the raw ImageUrl. /// public bool Format1x { get; set; } [Serializable()] protected struct RetinaImageViewState { public object RetinaImageBaseViewState; public String FormatString; public String AlternateSizes; } } } ================================================ FILE: web/src/RetinaImageBase.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Globalization; using System.Web.UI; namespace PkmnFoundations.Web { /// /// asp:Image with retina substitution capabilities /// public abstract class RetinaImageBase : System.Web.UI.WebControls.Image { public RetinaImageBase() : base() { this.PreRender += RetinaImageBase_PreRender; this.m_css_class = base.CssClass; base.CssClass = "retina"; } protected override void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer) { WriteDataAttributes(writer); base.AddAttributesToRender(writer); } private void WriteDataAttributes(HtmlTextWriter writer) { foreach (ImageRendition r in m_scales) { writer.AddAttribute(AttributeName(r.Scale), ResolveUrl(r.ImageUrl)); } } private static NumberFormatInfo nfi = CultureInfo.InvariantCulture.NumberFormat; public static String AttributeName(float scale) { return "data-hires-" + scale.ToString(nfi); } public static float getDevicePixelRatio(Page page) { float dpr = 1.0f; if (page.Request.Cookies["pixelRatio"] == null) return 1.0f; if (!Single.TryParse(page.Request.Cookies["pixelRatio"].Value, out dpr)) return 1.0f; return dpr; } public void RetinaImageBase_PreRender(object sender, EventArgs e) { float scale = getDevicePixelRatio(Page); m_scales = GetScales(); m_scales.Sort(); ImageRendition r = new ImageRendition("", 0.0f); foreach (ImageRendition f in m_scales) { if (r.Scale > 0.0f && f.Scale > scale && r.Scale >= scale) break; r = f; } base.ImageUrl = r.ImageUrl; } private List m_scales; protected abstract List GetScales(); public new string ImageUrl { get; set; } private String m_css_class; /// /// Custom CSS class(es). A "retina" class will be appended to the start to drive jQuery selectors. /// public override string CssClass { get { return m_css_class; } set { m_css_class = value; UpdateCssClass(); } } private bool m_keep_high_res; /// /// If this is true, a high resolution image will be kept in place even /// after the image has shrunken down to the next stop. This can /// prevent unnecessary image downloads. /// public bool KeepHighRes { get { return m_keep_high_res; } set { m_keep_high_res = value; UpdateCssClass(); } } private void UpdateCssClass() { String prefix = m_keep_high_res ? "retina keephr" : "retina"; base.CssClass = m_css_class.Length > 0 ? (prefix + " " + m_css_class) : prefix; } protected override void LoadViewState(object savedState) { RetinaImageBaseViewState viewstate = (RetinaImageBaseViewState)savedState; base.LoadViewState(viewstate.ImageViewState); this.ImageUrl = viewstate.ImageUrl; m_css_class = viewstate.CssClass; m_keep_high_res = viewstate.KeepHighRes; UpdateCssClass(); } protected override object SaveViewState() { RetinaImageBaseViewState viewstate = new RetinaImageBaseViewState(); viewstate.ImageViewState = base.SaveViewState(); viewstate.ImageUrl = this.ImageUrl; viewstate.CssClass = this.CssClass; viewstate.KeepHighRes = this.KeepHighRes; return viewstate; } protected struct ImageRendition : IComparable { public String ImageUrl; public float Scale; public ImageRendition(String image_url, float scale) { ImageUrl = image_url; Scale = scale; } public int CompareTo(ImageRendition other) { return Scale.CompareTo(other.Scale); } } [Serializable()] private struct RetinaImageBaseViewState { public object ImageViewState; public String ImageUrl; public String CssClass; public bool KeepHighRes; } } } ================================================ FILE: web/src/WebException.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace PkmnFoundations.Web { public class WebException : Exception { public WebException(String message, int responseCode) : base(message) { ResponseCode = responseCode; } public WebException(String message) : this(message, 500) { } public WebException(int responseCode) : this(DefaultMessage(responseCode), responseCode) { } public WebException() : this(500) { } public int ResponseCode { get; private set; } public static String DefaultMessage(int responseCode) { switch (responseCode) { case 400: return "Bad request"; case 403: return "Forbidden"; case 404: return "Not found"; case 500: default: return "Server error"; } } } } ================================================ FILE: web/src/WebFormat.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using PkmnFoundations.Pokedex; using PkmnFoundations.Structures; namespace PkmnFoundations.Web { public static class WebFormat { public static String Markings(Markings markings) { return Format.Markings(markings, "{0}", "{0}", ""); } public static String Gender(Genders gender) { switch (gender) { case Genders.Male: return "♂"; case Genders.Female: return "♀"; default: return ""; } } public static String RenderProgress(int curr, int max) { float percent = (float)curr * 100.0f / (float)max; return "
      "; } public static String RenderType(Pokedex.Type type) { return "" + type.Name.ToString() + ""; } public static String PokemonImageLarge(PokemonPartyBase pokemon) { return (pokemon.IsShiny ? "~/images/pkmn-lg-s/" : "~/images/pkmn-lg/") + PokemonImage2(pokemon) + ".png"; } public static String PokemonImageSmall(PokemonPartyBase pokemon) { // todo: shiny minis return (pokemon.IsShiny ? "~/images/pkmn-sm/" : "~/images/pkmn-sm/") + PokemonImage2(pokemon) + ".png"; } public static String SpeciesImageLarge(Form f) { return "~/images/pkmn-lg/" + PokemonImage2(f, Genders.Male) + ".png"; } public static String SpeciesImageLarge(Species s) { return "~/images/pkmn-lg/" + PokemonImage2(s.Forms(0), Genders.Male) + ".png"; } public static String SpeciesImageSmall(Form f) { // fixme: this is appending forms to some pokemon eg. arceus, keldeo, deerling // todo: need to take gender here optionally return "~/images/pkmn-sm/" + PokemonImage2(f, Genders.Male) + ".png"; } public static String SpeciesImageSmall(Species s) { return "~/images/pkmn-sm/" + PokemonImage2(s.Forms(0), Genders.Male) + ".png"; } private static String PokemonImage2(PokemonPartyBase pokemon) { return PokemonImage2(pokemon.Form, pokemon.Gender); } private static String PokemonImage2(Form f, Genders g) { // todo: spinda StringBuilder builder = new StringBuilder(); builder.Append(f.SpeciesID); if (f.Suffix.Length > 0) { builder.Append('-'); builder.Append(f.Suffix); } if (f.Species.GenderVariations && g == Genders.Female) builder.Append("-f"); return builder.ToString(); } public static String ItemImage(Item item) { return "~/images/item-sm/" + item.ID.ToString() + ".png"; } } } ================================================ FILE: web/test/BoxUp.aspx ================================================ <%@ Page Title="" Language="C#" MasterPageFile="~/masters/MasterPage.master" AutoEventWireup="true" CodeBehind="BoxUp.aspx.cs" Inherits="PkmnFoundations.GTS.debug.BoxUp" %> <%@ Register TagPrefix="pf" Namespace="PkmnFoundations.Web" Assembly="PkmnFoundations.Web" %>

      Uplaod your Generation IV box upload, battle video, or dressup capture:

      ================================================ FILE: web/test/BoxUp.aspx.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Text; using System.IO; using GamestatsBase; namespace PkmnFoundations.GTS.debug { public partial class BoxUp : System.Web.UI.Page { protected void Page_Init(object sender, EventArgs e) { litMessage.Text = ""; } protected void Page_Load(object sender, EventArgs e) { } private static byte[] m_pad = new byte[256]; protected void btnSend_Click(object sender, EventArgs e) { phDecoded.Visible = false; byte[] data = fuBox.FileBytes; FileStream s = File.Open(Server.MapPath("~/pad.bin"), FileMode.Open); s.Read(m_pad, 0, m_pad.Length); s.Close(); CryptMessage(data); switch (rblFormat.SelectedValue) { case "hd": default: litDecoded.Text = RenderHex(data.ToHexStringLower()); break; case "ca": litDecoded.Text = RenderCArray(data.ToHexStringLower()); break; } phDecoded.Visible = true; } private string RenderHex(string hex) { StringBuilder builder = new StringBuilder(); for (int x = 0; x < hex.Length; x += 16) { if (x % 32 == 0) { builder.Append((x >> 1).ToString("x4")); builder.Append(": "); } builder.Append(hex.Substring(x, Math.Min(16, hex.Length - x))); builder.Append((x % 32 == 0) ? " " : "
      "); } return builder.ToString(); } private string RenderCArray(string hex) { StringBuilder builder = new StringBuilder(); for (int x = 0; x < hex.Length; x += 2) { if (x > 0) { builder.Append(", "); if (x % 16 == 0) builder.Append("
      \r\n"); } builder.Append("0x"); builder.Append(hex.Substring(x, Math.Min(2, hex.Length - x))); } return builder.ToString(); } private void CryptMessage(byte[] message) { if (message.Length < 5) return; byte padOffset = (byte)(message[0] + message[4]); // encrypt and decrypt are the same operation... for (int x = 5; x < message.Length; x++) message[x] ^= m_pad[(x + padOffset) & 0xff]; } } } ================================================ FILE: web/test/BoxUp.aspx.designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace PkmnFoundations.GTS.debug { public partial class BoxUp { /// /// HeaderColour1 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::PkmnFoundations.Web.HeaderColour HeaderColour1; /// /// theForm control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.HtmlControls.HtmlForm theForm; /// /// rblFormat control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.RadioButtonList rblFormat; /// /// fuBox control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.FileUpload fuBox; /// /// btnSend control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Button btnSend; /// /// litMessage control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litMessage; /// /// phDecoded control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.PlaceHolder phDecoded; /// /// litDecoded control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litDecoded; } } ================================================ FILE: web/test/Decode.aspx ================================================ <%@ Page Title="" Language="C#" MasterPageFile="~/masters/MasterPage.master" AutoEventWireup="true" CodeBehind="Decode.aspx.cs" Inherits="PkmnFoundations.GTS.debug.Decode" %> <%@ Register TagPrefix="pf" Namespace="PkmnFoundations.Web" Assembly="PkmnFoundations.Web" %>

      Enter data querystring to decode:

      Generation:

      Checksum:

      ================================================ FILE: web/test/Decode.aspx.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Text; using System.Net; using GamestatsBase; namespace PkmnFoundations.GTS.debug { public partial class Decode : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { litMessage.Text = ""; litChecksum.Text = ""; } protected void btnDecode_Click(object sender, EventArgs e) { byte[] data = null; phDecoded.Visible = false; phChecksum.Visible = false; try { GamestatsHandler gs4 = new GamestatsHandler("sAdeqWo3voLeC5r16DYv", 0x45, 0x1111, 0x80000000, 0x4a3b2c1d, "pokemondpds", GamestatsRequestVersions.Version2, GamestatsResponseVersions.Version1, true); data = gs4.DecryptData(txtData.Text); litGeneration.Text = "4"; } catch (FormatException) { } if (data == null) try { GamestatsHandler gs5 = new GamestatsHandler("HZEdGCzcGGLvguqUEKQN0001d93500002dd5000000082db842b2syachi2ds", GamestatsRequestVersions.Version3, GamestatsResponseVersions.Version2, false); data = gs5.DecryptData(txtData.Text); litGeneration.Text = "5"; } catch (FormatException) { } if (data == null) try { GamestatsHandler gsPlat = new GamestatsHandler("uLMOGEiiJogofchScpXb000244fd00006015100000005b440e7epokemondpds", GamestatsRequestVersions.Version3, GamestatsResponseVersions.Version2, true); data = gsPlat.DecryptData(txtData.Text); litGeneration.Text = "Platinum"; } catch (FormatException) { } if (data == null) try { GamestatsHandler gsDungeonWii = new GamestatsHandler("zjzrhOVXZKLHNspYpGoR0001c7850000620b0000000820556356pokedngnwii", GamestatsRequestVersions.Version3, GamestatsResponseVersions.Version2); data = gsDungeonWii.DecryptData(txtData.Text); litGeneration.Text = "Mystery Dungeon Wii"; } catch (FormatException) { } if (data == null) try { data = DecryptData(txtData.Text); int checkedsum = 0; foreach (byte b in data) checkedsum += b; litGeneration.Text = "Unknown (raw)"; litChecksum.Text = checkedsum.ToString(); phChecksum.Visible = true; } catch (FormatException) { } if (data == null) try { data = GamestatsHandler.FromUrlSafeBase64String(txtData.Text); litGeneration.Text = "Unknown (are you sure this is gamestats data?)"; litChecksum.Text = ""; phChecksum.Visible = false; } catch (FormatException) { } if (data == null) { litMessage.Text = "

      Data is not formatted correctly.

      "; } else { litDecoded.Text = RenderHex(data.ToHexStringLower()); } phDecoded.Visible = true; } public static byte[] DecryptData(String data) { byte[] data2 = GamestatsHandler.FromUrlSafeBase64String(data); if (data2.Length < 12) throw new FormatException("Data must contain at least 12 bytes."); int checksum = BitConverter.ToInt32(data2, 0); checksum = IPAddress.NetworkToHostOrder(checksum); // endian flip //checksum ^= 0x2db842b2; return data2; } private String RenderHex(String hex) { // todo: this should be moved to a user control StringBuilder builder = new StringBuilder(); for (int x = 0; x < hex.Length; x += 16) { if (x % 32 == 0) { builder.Append((x >> 1).ToString("x4")); builder.Append(": "); } builder.Append(hex.Substring(x, Math.Min(16, hex.Length - x))); builder.Append((x % 32 == 0) ? " " : "
      "); } return builder.ToString(); } } } ================================================ FILE: web/test/Decode.aspx.designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace PkmnFoundations.GTS.debug { public partial class Decode { /// /// HeaderColour1 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::PkmnFoundations.Web.HeaderColour HeaderColour1; /// /// theForm control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.HtmlControls.HtmlForm theForm; /// /// txtData control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox txtData; /// /// btnDecode control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Button btnDecode; /// /// litMessage control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litMessage; /// /// phDecoded control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.PlaceHolder phDecoded; /// /// litGeneration control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litGeneration; /// /// litDecoded control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litDecoded; /// /// phChecksum control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.PlaceHolder phChecksum; /// /// litChecksum control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litChecksum; } } ================================================ FILE: web/test/Gsid.aspx ================================================ <%@ Page Title="" Language="C#" MasterPageFile="~/masters/MasterPage.master" AutoEventWireup="true" CodeBehind="Gsid.aspx.cs" Inherits="PkmnFoundations.Web.test.Gsid" %> <%@ Register TagPrefix="pf" Namespace="PkmnFoundations.Web" Assembly="PkmnFoundations.Web" %> ================================================ FILE: web/test/Gsid.aspx.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using PkmnFoundations.Support; namespace PkmnFoundations.Web.test { public partial class Gsid : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { StringBuilder output = new StringBuilder(); var gsids = new int[] { 476518182, 330241374 }; foreach (var gsid in gsids) { string enc = GameSyncUtils.PidToGsid(gsid); int dec = (int)GameSyncUtils.GsidToPid(enc); output.AppendLine(enc); output.AppendLine(dec.ToString()); output.AppendLine(String.Format("{0} ({0:X8}) == {1} ({1:X8})? {2}", gsid, dec, gsid == dec)); output.AppendLine(); } litOutput.Text = Common.FormatReturns(Common.HtmlEncode(output.ToString()), "
      \n"); } } } ================================================ FILE: web/test/Gsid.aspx.designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace PkmnFoundations.Web.test { public partial class Gsid { /// /// HeaderColour1 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::PkmnFoundations.Web.HeaderColour HeaderColour1; /// /// litOutput control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litOutput; } } ================================================ FILE: web/test/NameDecode.aspx ================================================ <%@ Page Title="" Language="C#" MasterPageFile="~/masters/MasterPage.master" AutoEventWireup="true" CodeBehind="NameDecode.aspx.cs" Inherits="PkmnFoundations.GTS.test.NameDecode" %> <%@ Register TagPrefix="pf" Namespace="PkmnFoundations.Web" Assembly="PkmnFoundations.Web" %>
      Enter name in hex to decode:
      ================================================ FILE: web/test/NameDecode.aspx.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using PkmnFoundations.Support; using GamestatsBase; using PkmnFoundations.Web; namespace PkmnFoundations.GTS.test { public partial class NameDecode : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnSubmit_Click(object sender, EventArgs e) { byte[] data = GamestatsBase.Common.FromHexString(txtName.Text.Replace(" ", "")); EncodedString4 es = new EncodedString4(data); litName.Text = Web.Common.HtmlEncode(es.ToString()); } } } ================================================ FILE: web/test/NameDecode.aspx.designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace PkmnFoundations.GTS.test { public partial class NameDecode { /// /// HeaderColour1 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::PkmnFoundations.Web.HeaderColour HeaderColour1; /// /// theForm control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.HtmlControls.HtmlForm theForm; /// /// txtName control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox txtName; /// /// btnSubmit control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Button btnSubmit; /// /// litName control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litName; } } ================================================ FILE: web/test/NameEncode.aspx ================================================ <%@ Page Title="" Language="C#" MasterPageFile="~/masters/MasterPage.master" AutoEventWireup="true" CodeBehind="NameEncode.aspx.cs" Inherits="PkmnFoundations.Web.test.NameEncode" %> <%@ Register TagPrefix="pf" Namespace="PkmnFoundations.Web" Assembly="PkmnFoundations.Web" %>
      Enter text to encode:
      ================================================ FILE: web/test/NameEncode.aspx.cs ================================================ using PkmnFoundations.Support; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace PkmnFoundations.Web.test { public partial class NameEncode : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnSubmit_Click(object sender, EventArgs e) { string text = txtName.Text; EncodedString4 es = new EncodedString4(text, text.Length * 2 + 8); litName.Text = Common.HtmlEncode(GamestatsBase.Common.ToHexStringUpper(es.RawData)); } } } ================================================ FILE: web/test/NameEncode.aspx.designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace PkmnFoundations.Web.test { public partial class NameEncode { /// /// HeaderColour1 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::PkmnFoundations.Web.HeaderColour HeaderColour1; /// /// theForm control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.HtmlControls.HtmlForm theForm; /// /// txtName control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox txtName; /// /// btnSubmit control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Button btnSubmit; /// /// litName control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Literal litName; } } ================================================ FILE: web/test/VideoId.aspx ================================================ <%@ Page Title="" Language="C#" MasterPageFile="~/masters/MasterPage.master" AutoEventWireup="true" CodeBehind="VideoId.aspx.cs" Inherits="PkmnFoundations.GTS.test.VideoId" %> <%@ Register TagPrefix="pf" Namespace="PkmnFoundations.Web" Assembly="PkmnFoundations.Web" %>
      Battle video ID:

      Serial number:
      ================================================ FILE: web/test/VideoId.aspx.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using PkmnFoundations.Structures; using PkmnFoundations.Wfc; namespace PkmnFoundations.GTS.test { public partial class VideoId : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnToSerial_Click(object sender, EventArgs e) { ulong valueNumeric = Convert.ToUInt64(txtBattleVideo.Text.Replace("-", "")); txtSerial.Text = BattleVideoHeader4.SerialToKey(valueNumeric).ToString(); } protected void btnToVideo_Click(object sender, EventArgs e) { ulong valueNumeric = Convert.ToUInt64(txtSerial.Text.Replace("-", "")); txtBattleVideo.Text = BattleVideoHeader4.KeyToSerial(valueNumeric).ToString(); } } } ================================================ FILE: web/test/VideoId.aspx.designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace PkmnFoundations.GTS.test { public partial class VideoId { /// /// HeaderColour1 control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::PkmnFoundations.Web.HeaderColour HeaderColour1; /// /// theForm control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.HtmlControls.HtmlForm theForm; /// /// txtBattleVideo control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox txtBattleVideo; /// /// btnToSerial control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Button btnToSerial; /// /// btnToVideo control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Button btnToVideo; /// /// txtSerial control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox txtSerial; } } ================================================ FILE: web/test/Web.config ================================================  ================================================ FILE: web/web.csproj ================================================  Debug AnyCPU 2.0 {3DE4D97F-57A8-4324-B5B8-164B45E2DF9A} {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} Library Properties PkmnFoundations.Web PkmnFoundations.Web v4.0 true true full false bin\ DEBUG;TRACE prompt 4 AnyCPU pdbonly true bin\ TRACE prompt 4 ..\packages\MySql.Data.6.9.8\lib\net40\MySql.Data.dll False ..\packages\Newtonsoft.Json.6.0.8\lib\net40\Newtonsoft.Json.dll Always Web.config Web.config Designer Web.config AddBoxes.aspx ASPXCodeBehind AddBoxes.aspx AddDressup.aspx ASPXCodeBehind AddDressup.aspx AddMusical.aspx ASPXCodeBehind AddMusical.aspx Default.aspx ASPXCodeBehind Default.aspx DnsAddress.ascx ASPXCodeBehind DnsAddress.ascx ForeignLookup.ascx ASPXCodeBehind ForeignLookup.ascx ASPXCodeBehind LabelTextBox.ascx ASPXCodeBehind LabelTextBox.ascx PokemonPicker.ascx ASPXCodeBehind PokemonPicker.ascx PokemonSource.ashx Default.aspx ASPXCodeBehind Default.aspx Global.asax Default.aspx ASPXCodeBehind Default.aspx Pokemon.aspx ASPXCodeBehind Pokemon.aspx LeftColumn.master ASPXCodeBehind LeftColumn.master MasterPage.master ASPXCodeBehind MasterPage.master ThreeColumn.master ASPXCodeBehind ThreeColumn.master RoomLeaders.aspx ASPXCodeBehind RoomLeaders.aspx BoxUp.aspx ASPXCodeBehind BoxUp.aspx Decode.aspx ASPXCodeBehind Decode.aspx Gsid.aspx ASPXCodeBehind Gsid.aspx NameDecode.aspx ASPXCodeBehind NameDecode.aspx NameEncode.aspx ASPXCodeBehind NameEncode.aspx VideoId.aspx ASPXCodeBehind VideoId.aspx {2d667f5b-f10d-44e2-93f6-dd555d9ee7df} GamestatsBase {408efc7e-c6b0-4160-8628-2679e34385ce} Library 10.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) True True 50689 / http://localhost:50661/ False False False