public void Load() { if (_path == null || _path == string.Empty) { return; } if (!File.Exists(_path)) { Utils.Debug("No macros to load. Creating deafult macro set"); CreateDefaultMacroSet(); return; } try { var r = new BinaryFileReader(new BinaryReader(new FileStream(_path, FileMode.Open))); if (Unserialize(r)) { Utils.Debug("Macros loaded!"); } else { Utils.Debug("Error reading macro file."); } r.Close(); r = null; } catch (Exception e) { Utils.Warning($"Error loading macros: {e.Message}"); } }
public void ReadByteTest() { File file = new File(System.IO.Path.Combine(TestDirectory, "Test1.bin")); try { BinaryFileWriter target = new BinaryFileWriter(file, Encoding.UTF32); byte b = 10; target.WriteByte(b); target.Close(); BinaryFileReader r = new BinaryFileReader(file); byte c = r.ReadByte(); Assert.AreEqual(b, c, "Should be equal"); r.Close(); } catch (Exception e) { Assert.Fail(e.ToString()); } }
public void Load() { if (s_Path == null || s_Path == string.Empty) { return; } if (!File.Exists(s_Path)) { Tracer.Debug("No macros to load. Creating deafult macro set"); CreateDefaultMacroSet(); return; } try { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(new FileStream(s_Path, FileMode.Open))); if (Unserialize(reader)) { Tracer.Debug("Macros loaded!"); } else { Tracer.Debug("Error reading macro file."); } reader.Close(); reader = null; } catch (Exception e) { Tracer.Warn(string.Format("Error loading macros: {0}", e.Message)); } }
/// <summary> /// Loads serialized data /// </summary> private static void OnWorldLoad() { if (!File.Exists(DataFile)) { return; } using (FileStream stream = new FileStream(DataFile, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(stream)); int version = reader.ReadInt(); switch (version) { case 0: int tableCount = reader.ReadInt(); PerkTable = new Dictionary <Player, Tuple <Perk, Perk> >(tableCount); Player player; Perk p1, p2; try { for (int i = 0; i < tableCount; i++) { player = reader.ReadMobile <Player>(); if (player == null || player.Deleted) { continue; } ConstructorInfo ctor = GetPerkCtor(reader.ReadString()); p1 = ctor.Invoke(new object[] { reader }) as Perk; ctor = GetPerkCtor(reader.ReadString()); p2 = ctor.Invoke(new object[] { reader }) as Perk; PerkTable[player] = Tuple.Create <Perk, Perk>(p1, p2); } } catch (Exception e) { Utilities.ExceptionManager.LogException("Perk", e); } break; } reader.Close(); } }
private static void EventSink_WorldLoad() { try { Console.Write("Loading SectorNodes..."); DateTime dt = DateTime.Now; using (FileStream fs = new FileStream("Data/SectorPathData.dat", FileMode.Open)) { using (BinaryReader br = new BinaryReader(fs)) { BinaryFileReader reader = new BinaryFileReader(br); if (reader.ReadInt() != (Map.Felucca.Width >> Map.SectorShift)) { throw new Exception("SectorNode data has different width than current map."); } if (reader.ReadInt() != (Map.Felucca.Height >> Map.SectorShift)) { throw new Exception("SectorNode data has different height than current map."); } m_Nodes = new SectorNode[Map.Felucca.Width >> Map.SectorShift, Map.Felucca.Height >> Map.SectorShift]; for (int y = 0; y < (Map.Felucca.Height >> Map.SectorShift); y++) { for (int x = 0; x < (Map.Felucca.Width >> Map.SectorShift); x++) { m_Nodes[x, y] = new SectorNode(); } } for (int y = 0; y < (Map.Felucca.Height >> Map.SectorShift); y++) { for (int x = 0; x < (Map.Felucca.Width >> Map.SectorShift); x++) { m_Nodes[x, y].Deserialize(reader); } } reader.Close(); } } Console.WriteLine("done in {0}ms.", (DateTime.Now - dt).TotalMilliseconds); } catch (Exception e) { LogHelper.LogException(e); Console.WriteLine("error:"); Console.WriteLine(e.Message); Console.WriteLine("SectorNode data must be recomputed."); m_Nodes = null; } }
public static void Load() { Console.Write("DonatorAccountSettings: Loading..."); string idxPath = Path.Combine("Saves/Donation", "DonatorAccountSettings.idx"); string binPath = Path.Combine("Saves/Donation", "DonatorAccountSettings.bin"); if (File.Exists(idxPath) && File.Exists(binPath)) { // Declare and initialize reader objects. FileStream idx = new FileStream(idxPath, FileMode.Open, FileAccess.Read, FileShare.Read); FileStream bin = new FileStream(binPath, FileMode.Open, FileAccess.Read, FileShare.Read); BinaryReader idxReader = new BinaryReader(idx); BinaryFileReader binReader = new BinaryFileReader(new BinaryReader(bin)); // Start by reading the number of duels from an index file int orderCount = idxReader.ReadInt32(); for (int i = 0; i < orderCount; ++i) { DonatorAccountSettings das = new DonatorAccountSettings(); // Read start-position and length of current order from index file long startPos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); // Point the reading stream to the proper position binReader.Seek(startPos, SeekOrigin.Begin); try { das.Deserialize(binReader); if (binReader.Position != (startPos + length)) { throw new Exception(String.Format("***** Bad serialize on DonatorAccountSettings[{0}] *****", i)); } } catch { //handle } if (das != null && das.m_Account != null) { DonatorAccountSettingsTable.Add(das.m_Account, das); } } // Remember to close the streams idxReader.Close(); binReader.Close(); } Console.WriteLine("done"); }
private static bool TestSerializeDeserialize(GearsChunk chunk, string path) { string filename = $"{Path.GetFileNameWithoutExtension(path)}.lxx"; using (BinaryFileWriter writer = new BinaryFileWriter(filename)) { chunk.Serialize(writer); writer.Close(); } using (BinaryFileReader reader = new BinaryFileReader(filename)) { bool success = GearsChunk.TryDeserialize(filename, reader, out chunk); reader.Close(); return(success); } }
public static void Load() { string basePath = Path.Combine("Saves", "CTFScore"); string idxPath = Path.Combine(basePath, "CTFLScore.idx"); string binPath = Path.Combine(basePath, "CTFLScore.bin"); if (File.Exists(idxPath) && File.Exists(binPath)) { // Declare and initialize reader objects. FileStream idx = new FileStream(idxPath, FileMode.Open, FileAccess.Read, FileShare.Read); FileStream bin = new FileStream(binPath, FileMode.Open, FileAccess.Read, FileShare.Read); BinaryReader idxReader = new BinaryReader(idx); BinaryFileReader binReader = new BinaryFileReader(new BinaryReader(bin)); // Start by reading the number of duels from an index file int playerCount = idxReader.ReadInt32(); for (int i = 0; i < playerCount; ++i) { CTFPlayer player = new CTFPlayer(); // Read start-position and length of current order from index file long startPos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); // Point the reading stream to the proper position binReader.Seek(startPos, SeekOrigin.Begin); try { player.Deserialize(binReader); if (binReader.Position != (startPos + length)) { throw new Exception(String.Format("***** Bad serialize on CTFScore[{0}] *****", i)); } } catch { //handle } if (player != null && player.Mobile != null) { Players.Add(player.Mobile, player); } } // Remember to close the streams idxReader.Close(); binReader.Close(); } }
public static void Load() { string idxPath = Path.Combine("Saves/FS Systems/FSBounty", "BountyTable.idx"); string binPath = Path.Combine("Saves/FS Systems/FSBounty", "BountyTable.bin"); if (File.Exists(idxPath) && File.Exists(binPath)) { FileStream idx = new FileStream(idxPath, FileMode.Open, FileAccess.Read, FileShare.Read); FileStream bin = new FileStream(binPath, FileMode.Open, FileAccess.Read, FileShare.Read); BinaryReader idxReader = new BinaryReader(idx); BinaryFileReader binReader = new BinaryFileReader(new BinaryReader(bin)); int orderCount = idxReader.ReadInt32(); for (int i = 0; i < orderCount; ++i) { Bounty ps = new Bounty(); long startPos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); binReader.Seek(startPos, SeekOrigin.Begin); try { ps.Deserialize(binReader); if (binReader.Position != (startPos + length)) { throw new Exception(String.Format("***** Bad serialize on Bounty[{0}] *****", i)); } } catch { } if (ps != null && ps.Wanted != null) { BountyTable.Add(ps.Wanted, ps); } } idxReader.Close(); binReader.Close(); } }
public void StartLoad(string path) { path += Name() + "/"; string idxPath = path + Name() + ".idx"; string tdbPath = path + Name() + ".tdb"; string binPath = path + Name() + ".bin"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } if (File.Exists(idxPath) && File.Exists(tdbPath) && File.Exists(binPath)) { using (FileStream idx = new FileStream(idxPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader idxReader = new BinaryReader(idx); using (FileStream tdb = new FileStream(tdbPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader tdbReader = new BinaryReader(tdb); using (FileStream bin = new FileStream(binPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader binReader = new BinaryFileReader(new BinaryReader(bin)); Console.Write(" - Loading {0}", Name()); Load(idxReader, tdbReader, binReader); idxReader.Close(); tdbReader.Close(); binReader.Close(); bin.Close(); tdb.Close(); idx.Close(); Console.WriteLine(" - Done."); } } } } }
public static bool SubRead(GenericReader reader, Action <GenericReader> deserializer) { if (reader == null) { return(false); } using (var s = new MemoryStream()) { var length = reader.ReadLong(); while (s.Length < length) { s.WriteByte(reader.ReadByte()); } if (deserializer != null) { s.Position = 0; var r = new BinaryFileReader(new BinaryReader(s)); try { deserializer(r); } catch (Exception e) { Console.WriteLine("Quest Load Failure: {0}", Utility.FormatDelegate(deserializer)); Console.WriteLine(e); return(false); } finally { r.Close(); } } } return(true); }
public void StartLoad( string path ) { path += Name()+"/"; string idxPath = path+Name()+".idx"; string tdbPath = path+Name()+".tdb"; string binPath = path+Name()+".bin"; if( !Directory.Exists( path ) ) Directory.CreateDirectory( path ); if( File.Exists( idxPath ) && File.Exists( tdbPath ) && File.Exists( binPath ) ) { using( FileStream idx = new FileStream( idxPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) { BinaryReader idxReader = new BinaryReader( idx ); using( FileStream tdb = new FileStream( tdbPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) { BinaryReader tdbReader = new BinaryReader( tdb ); using( FileStream bin = new FileStream( binPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) { BinaryFileReader binReader = new BinaryFileReader( new BinaryReader( bin ) ); Console.Write( " - Loading {0}", Name() ); Load( idxReader, tdbReader, binReader ); idxReader.Close(); tdbReader.Close(); binReader.Close(); bin.Close(); tdb.Close(); idx.Close(); Console.WriteLine( " - Done." ); } } } } }
public static void Deserialize(BinaryFileReader reader) { int version = reader.ReadInt(); if (version >= 0) { AllianceLimit = reader.ReadInt(); useXML = reader.ReadBool(); int count = reader.ReadInt(); for (int i = 1; i <= count; i++) { BaseAlliance alliance = new BaseAlliance(); alliance.Deserialize(reader); Alliances.Add(alliance); } } reader.Close(); }
public void DeserializeEntities() { if (!File.Exists(m_Repository.DataPath)) { return; } using (var bin = new FileStream(m_Repository.DataPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { var reader = new BinaryFileReader(new BinaryReader(bin)); foreach (var entry in m_EntityEntries) { var obj = entry.Object; if (obj != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { obj.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on {0} *****", obj.GetType())); } } catch (Exception e) { entry.Clear(); throw new RepositoryLoadException(this, e, obj.SerialIdentity, obj.GetType(), entry.TypeId); } } } reader.Close(); } m_EntityEntries = null; }
private static void Load() { if (!File.Exists(Path.Combine(Core.BaseDirectory, "Saves\\BugTracker\\bugs.bin"))) { return; } BinaryFileReader read = new BinaryFileReader( new BinaryReader(new FileStream(Path.Combine(Core.BaseDirectory, "Saves\\BugTracker\\bugs.bin"), FileMode.Open)) ); GenericReader reader = read; int version = reader.ReadInt(); switch (version) { case 0: { int count = reader.ReadInt(); for (int i = 0; i < count; i++) { BugEntry b = new BugEntry(); b.Deserialize(reader); if (_GlobalList == null) { _GlobalList = new List <BugEntry>(); } _GlobalList.Add(b); } break; } } read.Close(); }
public static bool LoadPluginSettings(TMPluginSave plugin) { if (pluginExists(plugin.getName())) { if (!Directory.Exists(loc)) { SkillSettings.DoTell(" -TMSS- Plugin Data directory does not exist. Plugin load cancelled."); return(false); } string FileName = plugin.getName() + ".plg"; string path = loc + FileName; Console.Write("Loading TMPlugin " + plugin.getName() + "..."); try { using (FileStream m_FileStream = new FileStream(path, FileMode.Open, FileAccess.Read)) { BinaryReader m_BinaryReader = new BinaryReader(m_FileStream); BinaryFileReader reader = new BinaryFileReader(m_BinaryReader); plugin.LoadPlugin(reader); reader.Close(); m_FileStream.Close(); } } catch (Exception e) { Console.WriteLine("failed. Exception: " + e); return(false); } return(true); } else { SkillSettings.DoTell(" Plugin " + plugin.getName() + " not registered with system. Plugin load cancelled."); return(false); } }
public void Deserialize() { //Console.WriteLine("[Vote System]: Loading Config..."); FileInfo info = new FileInfo("Data\\VoteSystem.cfg"); if (!info.Exists) { info.Create().Close(); } if (info.Length == 0) { return; } using (BinaryReader br = new BinaryReader(info.OpenRead())) { BinaryFileReader bin = new BinaryFileReader(br); int version = bin.ReadInt(); switch (version) { case 1: _DefaultGold = bin.ReadInt(); goto case 0; case 0: _DefaultName = bin.ReadString(); _DefaultURL = bin.ReadString(); _DefaultCoolDown = bin.ReadTimeSpan(); break; } bin.Close(); } //Console.WriteLine("[Vote System]: Done."); }
private static void Event_WorldLoad() { if (!File.Exists(SaveFile)) { return; } try { using (FileStream stream = new FileStream(SaveFile, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(stream)); Deserialize(reader); reader.Close(); } } catch (ArgumentException e) { Console.WriteLine("Error: Event_WorldLoad Failed in eqPvp Definition..!"); eqUtility.HandleGenericException(e); } }
private static void LoadData() { if (File.Exists(_DataPath)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(File.OpenRead(_DataPath))); int version = reader.ReadInt(); switch (version) { case 0: { break; } } reader.Close(); } if (_DuelTable == null) { _DuelTable = new Dictionary <Serial, Duel>(); } }
private static void LoadSaves() { try { if (!File.Exists(PointsFile)) { return; } BinaryFileReader read = new BinaryFileReader(new BinaryReader(new FileStream(PointsFile, FileMode.Open))); GenericReader reader = read; InternalLoad(reader); read.Close(); Console.WriteLine("Onsite Dueling System: DuelPoints loaded."); } catch (Exception e) { Console.WriteLine("Onsite Dueling System: Load failed!"); Console.WriteLine("Caught an exception: {0}", e.ToString()); m_PointsTable.Clear(); m_DeclineDuelList.Clear(); Console.WriteLine("Onsite Dueling System: Cleared potentially corrupted data."); } }
public void ReadStringUntilTest() { File file = new File(System.IO.Path.Combine(TestDirectory, "Test1")); try { BinaryFileWriter target = new BinaryFileWriter(file); string actual = "abcdefghijk;"; char ch = ';'; byte terminator = (byte)ch; int maximumLength = actual.Length; //target.writer.Write(actual); target.WriteString(actual); target.Close(); BinaryFileReader r = new BinaryFileReader(file); string expected = r.ReadStringUntil(terminator, maximumLength, true); r.Close(); Assert.AreEqual(expected, actual, "Should be equal"); } catch (Exception e) { Assert.Fail(e.ToString()); } }
public static List<Mobile> ReadMobiles() { var output = new List<Mobile>(); try { var mobiles = new List<MobileEntry>(); if (File.Exists(MobileIndexPath) && File.Exists(MobileTypesPath)) { using ( FileStream idx = new FileStream(MobileIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read) ) { BinaryReader idxReader = new BinaryReader(idx); using ( FileStream tdb = new FileStream(MobileTypesPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader tdbReader = new BinaryReader(tdb); var types = ReadTypes(tdbReader); int mobileCount = idxReader.ReadInt32(); for (int i = 0; i < mobileCount; ++i) { int typeID = idxReader.ReadInt32(); int serial = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); var objs = types[typeID]; if (objs == null) { continue; } ConstructorInfo ctor = objs.Item1; string typeName = objs.Item2; try { Mobile value; Mobile m = null; if (World.Mobiles.TryGetValue(serial, out value)) { Mobile sameSerialMob = value; BaseCreature bc = sameSerialMob as BaseCreature; // Don't use the real serial number, get a new serial number for it serial = Serial.NewMobile; m = (Mobile) (ctor.Invoke(new object[] {(Serial) serial})); // this constructor gets a new, unused serial number if (m.GetType() != sameSerialMob.GetType()) { // the serial has already been reused by a different type of mob // which means the original stabled mob is gone. Therefore add the original mob output.Add(m); World.AddMobile(m); /*LoggingCustom.Log("PetReassignedSerials.txt", "serial was previously replaced by: " + sameSerialMob.Name + "\t" + sameSerialMob.Serial + "\tDeleted:" + sameSerialMob.Deleted + "\t|new serial assigned for pet:" + m.Serial);*/ } else // it's a very safe bet that it's the same mob (though we can't be absolutely sure)... { /*LoggingCustom.Log("PetStillExists.txt", "Now Existing: " + sameSerialMob.Name + "\t" + sameSerialMob.Serial + "\tDeleted:" + sameSerialMob.Deleted);*/ // don't add mob to output } } else { // construct mob with it's original serial number... this probably won't happen much m = (Mobile) (ctor.Invoke(new object[] {(Serial) serial})); // this constructor adds this mob into the World.Mobiles dictionary at this serial World.AddMobile(m); output.Add(m); //LoggingCustom.Log("PetSameSerialRestored.txt", m.Serial + ""); } // always add it to this list regardless mobiles.Add(new MobileEntry(m, typeID, typeName, pos, length)); } catch (Exception e) { Console.WriteLine("LostStabledPetRecorder error!: " + e.Message); Console.WriteLine(e.StackTrace); } } tdbReader.Close(); } idxReader.Close(); } } else { Console.WriteLine("Lost stable files not found! Should be at " + Path.GetFullPath(MobileIndexPath)); } Serial failedSerial = Serial.Zero; if (File.Exists(MobileDataPath)) { using ( FileStream bin = new FileStream(MobileDataPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin)); for (int i = 0; i < mobiles.Count; ++i) { MobileEntry entry = mobiles[i]; Mobile m = entry.Mobile; if (m != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { if (!output.Contains(m)) { // same mob already exist in the world, but // m has been assigned a new serial number so it's ok to delete it } else { m_LoadingType = entry.TypeName; m.Deserialize(reader); m.Map = Map.Internal; if (m is Beetle || m is HordeMinion || m is PackHorse || m is PackLlama) { // pack animals: make sure they have their pack Container pack = m.Backpack; if (pack == null) { pack = new StrongBackpack {Movable = false}; m.AddItem(pack); } } if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on {0} *****", m.GetType())); } } } catch { mobiles.RemoveAt(i); Type failedType = m.GetType(); int failedTypeID = entry.TypeID; failedSerial = m.Serial; Console.WriteLine(failedType); Console.WriteLine(failedTypeID); Console.WriteLine(failedSerial); break; } } } reader.Close(); } } } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); } return output; }
public static void LoadSpawners_OnCommand(CommandEventArgs e) { int count = 0; int itemCount = 0; Hashtable m_Items; if (e.Arguments.Length == 1) { string FileName = e.Arguments[0].ToString(); string itemIdxPath = Path.Combine("Saves/Spawners/", FileName + ".idx"); string itemBinPath = Path.Combine("Saves/Spawners/", FileName + ".bin"); try { ArrayList items = new ArrayList(); if (File.Exists(itemIdxPath)) { using (FileStream idx = new FileStream(itemIdxPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader idxReader = new BinaryReader(idx); itemCount = idxReader.ReadInt32(); count = itemCount; m_Items = new Hashtable(itemCount); for (int i = 0; i < itemCount; ++i) { long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); Item item = null; try { item = new Spawner(); } catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); } if (item != null) { items.Add(new ItemEntry(item, pos, length)); World.AddItem(item); } } idxReader.Close(); } } else { e.Mobile.SendMessage("File Not Found {0}.idx", FileName); } if (File.Exists(itemBinPath)) { using (FileStream bin = new FileStream(itemBinPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin)); for (int i = 0; i < items.Count; ++i) { ItemEntry entry = (ItemEntry)items[i]; Item item = (Item)entry.Object; if (item != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { item.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on {0} *****", item.GetType())); } item.MoveToWorld(item.Location, item.Map); } catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); } } } reader.Close(); } } else { e.Mobile.SendMessage("File Not Found {0}.bin", FileName); } } catch (Exception ex) { LogHelper.LogException(ex); System.Console.WriteLine("Exception Caught in LoadSpawner code: " + ex.Message); System.Console.WriteLine(ex.StackTrace); } e.Mobile.SendMessage("{0} Spawners Loaded.", count); } else { e.Mobile.SendMessage("[Usage <FileName>"); } }
private static short FactoryLoad() { m_DODInst = new ArrayList(); m_DODGroup = new ArrayList(); string filePath = Path.Combine("Saves/AngelIsland", "RareFactory.dat"); if (!File.Exists(filePath)) { Console.WriteLine("FactoryLoad() : RareFactory.dat does not exist, assuming new factory"); return 1; // Assume new factory } using (FileStream sr = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { if (!sr.CanRead) { Console.WriteLine("FactoryLoad() : {0} is not readable but exists!!", filePath); return 0; } // This is the stream reader we will read our binary DOD data with BinaryFileReader bfr = new BinaryFileReader(new BinaryReader(sr)); bfr.Seek(0, SeekOrigin.Begin); try { // Just in case we change the save format sometime! short version = ((GenericReader)bfr).ReadShort(); int numtoload = ((GenericReader)bfr).ReadShort(); Console.WriteLine("FactoryLoad() : Loading {0} Dynamic Object Definition{1}...", numtoload, (numtoload != 1 ? "s" : "")); // Instance the DODs with the bfr pointer (the object constructor handles in file input) for (int i = 0; i < numtoload; i++) m_DODInst.Add(new DODInstance(bfr)); numtoload = ((GenericReader)bfr).ReadShort(); Console.WriteLine("FactoryLoad() : Loading {0} DOD Group{1}...", numtoload, (numtoload != 1 ? "s" : "")); for (int i = 0; i < numtoload; i++) { DODGroup dg = new DODGroup(bfr); // Save this group list m_DODGroup.Add(dg); } } catch (Exception e) { Console.WriteLine("FactoryLoad() : Caught exception trying to load DODs : {0}", e); LogHelper.LogException(e); } bfr.Close(); } // 'using' closes sr Console.WriteLine("FactoryLoad() : Complete."); return 1; }
public static bool ImportBuilding(string filename) { bool finished = false; string binpath = Path.Combine(BaseBuilding.SavePath, filename + ".bin"); if (File.Exists(binpath)) { using (FileStream bin = CustomSaving.GetFileStream(binpath)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin)); try { int count = reader.ReadInt(); for (int i = 0; i < count; i++) { string name = reader.ReadString(); int type = reader.ReadInt(); switch (type) { case 0: m_BuildingTable[name] = new BuildingEntry(reader, type); break; case 1: m_BuildingTable[name] = new ComponentEntry(reader); break; case 2: m_BuildingTable[name] = new AddonEntry(reader); break; } } finished = true; } catch (Exception error) { Console.WriteLine(error.ToString()); } finally { reader.Close(); } } } return finished; }
/// <summary> /// Loads serialized data /// </summary> private static void OnWorldLoad() { if( !File.Exists(DataFile) ) return; using( FileStream stream = new FileStream(DataFile, FileMode.Open, FileAccess.Read, FileShare.Read) ) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(stream)); int tableCount = reader.ReadInt(); EoCTable = new Dictionary<Player, EoCContext>(tableCount); for( int i = 0; i < tableCount; i++ ) { if( !reader.ReadBool() ) continue; Player pl = reader.ReadMobile<Player>(); if( pl != null && !pl.Deleted ) EoCTable[pl] = new EoCContext(reader); } int hitsCount = reader.ReadInt(); HitsTable = new Dictionary<Player, HitsTimer>(hitsCount); for( int i = 0; i < hitsCount; i++ ) { if( !reader.ReadBool() ) continue; Player player = reader.ReadMobile<Player>(); if( player == null || player.Deleted ) continue; HitsTable[player] = new HitsTimer(player); DateTime next = reader.ReadDateTime(); if( next < DateTime.Now ) next = DateTime.Now; HitsTable[player].Delay = (next - DateTime.Now); } reader.Close(); } }
public static void Load() { string idxPath = Path.Combine( "Saves/FS Systems/FSBounty", "BountyTable.idx" ); string binPath = Path.Combine( "Saves/FS Systems/FSBounty", "BountyTable.bin" ); if ( File.Exists( idxPath ) && File.Exists( binPath ) ) { FileStream idx = new FileStream( idxPath, FileMode.Open, FileAccess.Read, FileShare.Read ); FileStream bin = new FileStream( binPath, FileMode.Open, FileAccess.Read, FileShare.Read) ; BinaryReader idxReader = new BinaryReader( idx ); BinaryFileReader binReader = new BinaryFileReader( new BinaryReader( bin ) ); int orderCount = idxReader.ReadInt32(); for ( int i = 0; i < orderCount; ++i ) { Bounty ps = new Bounty(); long startPos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); binReader.Seek( startPos, SeekOrigin.Begin ); try { ps.Deserialize(binReader); if (binReader.Position != ( startPos + length ) ) throw new Exception( String.Format( "***** Bad serialize on Bounty[{0}] *****", i ) ); } catch { } if ( ps != null && ps.Wanted != null ) BountyTable.Add( ps.Wanted, ps ); } idxReader.Close(); binReader.Close(); } }
public static void LoadDuellers() { if (File.Exists(duellersBinPath)) { // Declare and initialize reader objects. FileStream bin = new FileStream(duellersBinPath, FileMode.Open, FileAccess.Read, FileShare.Read); BinaryFileReader binReader = new BinaryFileReader(new BinaryReader(bin)); try { duellers = binReader.ReadMobileList(); } catch (Exception e) { } binReader.Close(); } }
private static void LoadSaves() { try { if (!File.Exists(PointsFile)) return; BinaryFileReader read = new BinaryFileReader(new BinaryReader(new FileStream(PointsFile, FileMode.Open))); GenericReader reader = read; InternalLoad(reader); read.Close(); Console.WriteLine("Onsite Dueling System: DuelPoints loaded."); } catch (Exception e) { Console.WriteLine("Onsite Dueling System: Load failed!"); Console.WriteLine("Caught an exception: {0}", e.ToString()); m_PointsTable.Clear(); m_DeclineDuelList.Clear(); Console.WriteLine("Onsite Dueling System: Cleared potentially corrupted data."); } }
public static void Load() { string idxPath = Path.Combine( "Saves/FriendLists", "FriendLists.idx" ); string binPath = Path.Combine( "Saves/FriendLists", "FriendLists.bin" ); if (File.Exists(idxPath) && File.Exists(binPath)) { // Declare and initialize reader objects. FileStream idx = new FileStream(idxPath, FileMode.Open, FileAccess.Read, FileShare.Read); FileStream bin = new FileStream(binPath, FileMode.Open, FileAccess.Read, FileShare.Read); BinaryReader idxReader = new BinaryReader(idx); BinaryFileReader binReader = new BinaryFileReader(new BinaryReader(bin)); // Start by reading the number of duels from an index file int orderCount = idxReader.ReadInt32(); for (int i = 0; i < orderCount; ++i) { FriendList fl = new FriendList(); // Read start-position and length of current order from index file long startPos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); // Point the reading stream to the proper position binReader.Seek(startPos, SeekOrigin.Begin); try { fl.Deserialize(binReader); if (binReader.Position != (startPos + length)) throw new Exception(String.Format("***** Bad serialize on FriendList[{0}] *****", i)); } catch { //handle } if ( fl != null && fl.m_Mobile != null ) FriendLists.Add( fl.m_Mobile, fl ); } // Remember to close the streams idxReader.Close(); binReader.Close(); } }
/// <summary> /// Reads a binary STL file filtered by a provided filter. /// </summary> /// <param name="file">The mesh file.</param> /// <param name="filter">The provided filtered.</param> /// <returns>The DMTModel that obeys to the filter condition.</returns> public List <DMTModel> ReadFile(File file, IDMTModelFilter filter) { if (file.Exists == false) { throw new DMTFileException(DMTFileError.FileDoesNotExist); } var blocksIn = new List <DMTTriangleBlock>(); var blocksOut = new List <DMTTriangleBlock>(); var blockIn = new DMTTriangleBlock(); var blockOut = new DMTTriangleBlock(); var objReader = new BinaryFileReader(file); try { //Read first 80 characters (bytes) and ignore them objReader.ReadBytes(80); //Read the next 4 bytes to get an unsigned integer of number of triangles var intNoOfFacets = objReader.ReadUInteger(); //Now keep reading until the end of the file var mapPointVertexIndexBlockIn = new Dictionary <Point, int>(); var mapPointVertexIndexBlockOut = new Dictionary <Point, int>(); var point1Index = -1; var point2Index = -1; var point3Index = -1; for (uint intCounter = 0; intCounter <= intNoOfFacets - 1; intCounter++) { //Read 3 32bit floating point numbers - triangle normal // We do not keep the normals in memory, they take too much space objReader.ReadSingle(); objReader.ReadSingle(); objReader.ReadSingle(); //Read 3 32bit floating point numbers - vertex 1 X/Y/Z var objPoint1 = new Point(); objPoint1.X = objReader.ReadSingle(); objPoint1.Y = objReader.ReadSingle(); objPoint1.Z = objReader.ReadSingle(); //Read 3 32bit floating point numbers - vertex 2 X/Y/Z var objPoint2 = new Point(); objPoint2.X = objReader.ReadSingle(); objPoint2.Y = objReader.ReadSingle(); objPoint2.Z = objReader.ReadSingle(); //Read 3 32bit floating point numbers - vertex 3 X/Y/Z var objPoint3 = new Point(); objPoint3.X = objReader.ReadSingle(); objPoint3.Y = objReader.ReadSingle(); objPoint3.Z = objReader.ReadSingle(); if (filter.CanAddTriangle(objPoint1, objPoint2, objPoint3)) { AddTriangle(mapPointVertexIndexBlockIn, blockIn, objPoint1, objPoint2, objPoint3); } else { AddTriangle(mapPointVertexIndexBlockOut, blockOut, objPoint1, objPoint2, objPoint3); } //Read 16 bit number objReader.ReadUInt16(); } blockIn.DoVerticesHaveNormals = false; blockOut.DoVerticesHaveNormals = false; blocksIn.Add(blockIn); blocksOut.Add(blockOut); var modelWithinFilter = new DMTModel(); var modelOutsideFilter = new DMTModel(); modelWithinFilter.TriangleBlocks.AddRange(blocksIn); modelOutsideFilter.TriangleBlocks.AddRange(blocksOut); var result = new List <DMTModel>(); result.Add(modelWithinFilter); result.Add(modelOutsideFilter); return(result); } finally { objReader.Close(); } }
/* ID's: 101 = Button Manage System 102 = Button Import Page 103 = Button Apply Location 104 = Button Apply Category 105 = Text Name 106 = Text X 107 = Text Y 108 = Text Z 109 = Text Hue 110 = Text Cost 111 = Radio Trammel 112 = Radio Malas 113 = Radio Felucca 114 = Radio Ilshenar 115 = Radio Tokuno 116 = Check Generate 117 = Check StaffOnly 118 = Check Reds 119 = Check Charge 120 = Check Young 121 = Button Add Category 122 = Button Add Location 123 = Button Export 124 = Button Import Systems 125 = Button Import Categories 126 = Button Import Locations 300+ = Imports */ public override void OnResponse(NetState state, RelayInfo info, ACCGumpParams subParams) { if (info.ButtonID == 0 || state.Mobile.AccessLevel < ACC.GlobalMinimumAccessLevel) return; if (subParams is PGGumpParams) Params = subParams as PGGumpParams; PGGumpParams newParams = new PGGumpParams(); if (info.ButtonID == 101) newParams.Page = Pages.Manage; else if (info.ButtonID == 102) newParams.Page = Pages.Import; #region Add/Remove else if (info.ButtonID == 103 || info.ButtonID == 104 || info.ButtonID == 121 || info.ButtonID == 122) { SetFlag(EntryFlag.Generate, info.IsSwitched(116)); SetFlag(EntryFlag.StaffOnly, info.IsSwitched(117)); SetFlag(EntryFlag.Reds, info.IsSwitched(118)); SetFlag(EntryFlag.Charge, info.IsSwitched(119)); Map Map = info.IsSwitched(111) ? Map.Trammel : info.IsSwitched(112) ? Map.Malas : info.IsSwitched(113) ? Map.Felucca : info.IsSwitched(114) ? Map.Ilshenar : info.IsSwitched(115) ? Map.Tokuno : Map.Trammel; string Name = GetString(info, 105); string X = GetString(info, 106); string Y = GetString(info, 107); string Z = GetString(info, 108); string H = GetString(info, 109); string C = GetString(info, 110); if (Name == null || Name.Length == 0) { try { state.Mobile.SendMessage("Removed the entry"); if (info.ButtonID == 103) Params.SelectedCategory.Key.Locations.Remove(Params.SelectedLocation.Key); else m_CategoryList.Remove(Params.SelectedCategory.Key); } catch { Console.WriteLine("Exception caught removing entry"); } } else { if (info.ButtonID == 103 || info.ButtonID == 122) { int x, y, z, h, c = 0; Point3D Loc; int Hue; int Cost; PGLocation PGL; if (X == null || X.Length == 0 || Y == null || Y.Length == 0 || Z == null || Z.Length == 0 || H == null || H.Length == 0 || C == null || C.Length == 0) { if (info.ButtonID == 122) { Hue = 0; Loc = new Point3D(0, 0, 0); Cost = 0; PGL = new PGLocation(Name, Flags, Loc, Map, Hue, Cost); if (PGL == null) { state.Mobile.SendMessage("Error adding Location."); return; } m_CategoryList[Params.SelectedCategory.Value].Locations.Add(PGL); } state.Mobile.SendMessage("Please fill in each field."); state.Mobile.SendGump(new ACCGump(state.Mobile, this.ToString(), Params)); return; } try { x = Int32.Parse(X); y = Int32.Parse(Y); z = Int32.Parse(Z); h = Int32.Parse(H); c = Int32.Parse(C); Loc = new Point3D(x, y, z); Hue = h; Cost = c; } catch { state.Mobile.SendMessage("Please enter an integer in each of the info fields. (X, Y, Z, H, Cost)"); state.Mobile.SendGump(new ACCGump(state.Mobile, this.ToString(), Params)); return; } PGL = new PGLocation(Name, Flags, Loc, Map, Hue, Cost); if (PGL == null) { state.Mobile.SendMessage("Bad Location information, can't add!"); } else { try { if (info.ButtonID == 122) { m_CategoryList[Params.SelectedCategory.Value].Locations.Add(PGL); state.Mobile.SendMessage("Added the Location."); } else { state.Mobile.SendMessage("Changed the Location."); m_CategoryList[Params.SelectedCategory.Value].Locations[Params.SelectedLocation.Value] = PGL; } } catch { Console.WriteLine("Problem adding/changing Location!"); } } } else { if (C == null || C.Length == 0) { state.Mobile.SendMessage("Please fill in each field."); state.Mobile.SendGump(new ACCGump(state.Mobile, this.ToString(), Params)); return; } int c = 0; int Cost; try { c = Int32.Parse(C); Cost = c; } catch { state.Mobile.SendMessage("Please enter an integer for the Cost"); state.Mobile.SendGump(new ACCGump(state.Mobile, this.ToString(), Params)); return; } try { if (info.ButtonID == 121) { m_CategoryList.Add(new PGCategory(Name, Flags, Cost)); state.Mobile.SendMessage("Added the Category."); } else { m_CategoryList[Params.SelectedCategory.Value].Name = Name; m_CategoryList[Params.SelectedCategory.Value].Flags = Flags; m_CategoryList[Params.SelectedCategory.Value].Cost = Cost; state.Mobile.SendMessage("Changed the Category."); } } catch { Console.WriteLine("Problems adding/changing Category!"); } } } } #endregion //Add/Remove #region Imports/Exports #region Exports else if (info.ButtonID == 123) { if (!Directory.Exists("ACC Exports")) Directory.CreateDirectory("ACC Exports"); string fileName; string Path = "ACC Exports/"; if (Params.SelectedLocation.Key != null) fileName = String.Format("Location - {0}.pgl", Params.SelectedLocation.Key.Name); else if (Params.SelectedCategory.Key != null) fileName = String.Format("Category - {0}.pgc", Params.SelectedCategory.Key.Name); else fileName = String.Format("System - {0:yyMMdd-HHmmss}.pgs", DateTime.Now); try { using (FileStream m_FileStream = new FileStream(Path + fileName, FileMode.Create, FileAccess.Write)) { GenericWriter writer = new BinaryFileWriter(m_FileStream, true); if (Params.SelectedLocation.Key != null) { Params.SelectedLocation.Key.Serialize(writer); state.Mobile.SendMessage("Exported the Location to {0}{1}", Path, fileName); } else if (Params.SelectedCategory.Key != null) { Params.SelectedCategory.Key.Serialize(writer); state.Mobile.SendMessage("Exported the Category (and all Locations contained within) to {0}{1}", Path, fileName); } else { writer.Write((int)0); //version writer.Write(m_CategoryList.Count); for (int i = 0; i < m_CategoryList.Count; i++) { m_CategoryList[i].Serialize(writer); } state.Mobile.SendMessage("Exported the entire Public Gates System to {0}{1}", Path, fileName); } writer.Close(); m_FileStream.Close(); } } catch (Exception e) { state.Mobile.SendMessage("Problem exporting the selection. Please contact the admin."); Console.WriteLine("Error exporting PGSystem : {0}", e); } } #endregion //Exports #region Imports //Switch between import types else if (info.ButtonID == 124 || info.ButtonID == 125 || info.ButtonID == 126) { newParams.Page = Pages.Import; switch (info.ButtonID) { case 124: newParams.ImportSelection = ImportSelections.Systems; break; case 125: newParams.ImportSelection = ImportSelections.Categories; break; case 126: newParams.ImportSelection = ImportSelections.Locations; break; } } //Perform the import else if (info.ButtonID >= 300 && Dirs != null && Dirs.Length > 0) { if (!Directory.Exists("ACC Exports")) Directory.CreateDirectory("ACC Exports"); string Path = null; try { Path = Dirs[info.ButtonID - 300]; if (File.Exists(Path)) { using (FileStream m_FileStream = new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(m_FileStream)); switch ((int)Params.ImportSelection) { case (int)ImportSelections.Systems: {//Systems int version = reader.ReadInt(); int count = reader.ReadInt(); List<PGCategory> list = new List<PGCategory>(); for (int i = 0; i < count; i++) list.Add(new PGCategory(reader)); state.Mobile.CloseGump(typeof(SysChoiceGump)); state.Mobile.SendGump(new SysChoiceGump(this.ToString(), Params, list)); reader.Close(); return; } case (int)ImportSelections.Categories: {//Categories if (m_CategoryList == null) m_CategoryList = new List<PGCategory>(); m_CategoryList.Add(new PGCategory(reader)); state.Mobile.SendMessage("Added the Category."); break; } case (int)ImportSelections.Locations: {//Locations state.Mobile.CloseGump(typeof(CatSelGump)); state.Mobile.SendMessage("Please choose a Category to put this Location in."); state.Mobile.SendGump(new CatSelGump(this.ToString(), Params, new PGLocation(reader))); reader.Close(); return; } } reader.Close(); } } } catch { } } #endregion //Imports #endregion //Imports/Exports else if (info.ButtonID >= 150 && info.ButtonID < m_CategoryList.Count + 150) newParams.SelectedCategory = new KeyValuePair<PGCategory, int>(m_CategoryList[info.ButtonID - 150], info.ButtonID - 150); else if (info.ButtonID >= 200 && info.ButtonID < 200 + Params.SelectedCategory.Key.Locations.Count) { newParams.SelectedCategory = Params.SelectedCategory; newParams.SelectedLocation = new KeyValuePair<PGLocation, int>(Params.SelectedCategory.Key.Locations[info.ButtonID - 200], info.ButtonID - 200); } state.Mobile.SendGump(new ACCGump(state.Mobile, this.ToString(), newParams)); }
public static void OnLoad() { try { Console.WriteLine("KinCityManager Loading..."); string filePath = Path.Combine("Saves/AngelIsland", "KinCityManager.bin"); if (!File.Exists(filePath)) { Console.Write("Kin faction city data file not found. Generating default city data..."); foreach (int city in Enum.GetValues(typeof(KinFactionCities))) { _cityData.Add((KinFactionCities)city, new KinCityData((KinFactionCities)city)); } Console.WriteLine("done."); return; } BinaryFileReader datreader = new BinaryFileReader(new BinaryReader(new FileStream(filePath, FileMode.Open, FileAccess.Read))); int version = datreader.ReadInt(); switch (version) { case 1: { int cityCount = datreader.ReadInt(); if (cityCount > 0) { for (int i = 0; i < cityCount; ++i) { try { KinCityData data = new KinCityData(datreader); _cityData.Add(data.City, data); } catch { } } } break; } } //if any were corrupted and failed to load, create a new set of data. foreach (int city in Enum.GetValues(typeof(KinFactionCities))) { if (!_cityData.ContainsKey((KinFactionCities)city)) { Console.WriteLine("Warning: KinCityData for {0} did not load successfully, and a new blank set of data has been created.", ((KinFactionCities)city).ToString()); _cityData.Add((KinFactionCities)city, new KinCityData((KinFactionCities)city)); } } datreader.Close(); } catch (Exception ex) { System.Console.WriteLine("Error loading KinCityManager!"); Scripts.Commands.LogHelper.LogException(ex); } }
public static List <Mobile> ReadMobiles() { var output = new List <Mobile>(); try { var mobiles = new List <MobileEntry>(); if (File.Exists(MobileIndexPath) && File.Exists(MobileTypesPath)) { using ( FileStream idx = new FileStream(MobileIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read) ) { BinaryReader idxReader = new BinaryReader(idx); using ( FileStream tdb = new FileStream(MobileTypesPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader tdbReader = new BinaryReader(tdb); var types = ReadTypes(tdbReader); int mobileCount = idxReader.ReadInt32(); for (int i = 0; i < mobileCount; ++i) { int typeID = idxReader.ReadInt32(); int serial = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); var objs = types[typeID]; if (objs == null) { continue; } ConstructorInfo ctor = objs.Item1; string typeName = objs.Item2; try { Mobile value; Mobile m = null; if (World.Mobiles.TryGetValue(serial, out value)) { Mobile sameSerialMob = value; BaseCreature bc = sameSerialMob as BaseCreature; // Don't use the real serial number, get a new serial number for it serial = Serial.NewMobile; m = (Mobile)(ctor.Invoke(new object[] { (Serial)serial })); // this constructor gets a new, unused serial number if (m.GetType() != sameSerialMob.GetType()) { // the serial has already been reused by a different type of mob // which means the original stabled mob is gone. Therefore add the original mob output.Add(m); World.AddMobile(m); /*LoggingCustom.Log("PetReassignedSerials.txt", * "serial was previously replaced by: " + sameSerialMob.Name + "\t" + * sameSerialMob.Serial + "\tDeleted:" + * sameSerialMob.Deleted + "\t|new serial assigned for pet:" + m.Serial);*/ } else // it's a very safe bet that it's the same mob (though we can't be absolutely sure)... { /*LoggingCustom.Log("PetStillExists.txt", * "Now Existing: " + sameSerialMob.Name + "\t" + sameSerialMob.Serial + * "\tDeleted:" + sameSerialMob.Deleted);*/ // don't add mob to output } } else { // construct mob with it's original serial number... this probably won't happen much m = (Mobile)(ctor.Invoke(new object[] { (Serial)serial })); // this constructor adds this mob into the World.Mobiles dictionary at this serial World.AddMobile(m); output.Add(m); //LoggingCustom.Log("PetSameSerialRestored.txt", m.Serial + ""); } // always add it to this list regardless mobiles.Add(new MobileEntry(m, typeID, typeName, pos, length)); } catch (Exception e) { Console.WriteLine("LostStabledPetRecorder error!: " + e.Message); Console.WriteLine(e.StackTrace); } } tdbReader.Close(); } idxReader.Close(); } } else { Console.WriteLine("Lost stable files not found! Should be at " + Path.GetFullPath(MobileIndexPath)); } Serial failedSerial = Serial.Zero; if (File.Exists(MobileDataPath)) { using ( FileStream bin = new FileStream(MobileDataPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin)); for (int i = 0; i < mobiles.Count; ++i) { MobileEntry entry = mobiles[i]; Mobile m = entry.Mobile; if (m != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { if (!output.Contains(m)) { // same mob already exist in the world, but // m has been assigned a new serial number so it's ok to delete it } else { m_LoadingType = entry.TypeName; m.Deserialize(reader); m.Map = Map.Internal; if (m is Beetle || m is HordeMinion || m is PackHorse || m is PackLlama) { // pack animals: make sure they have their pack Container pack = m.Backpack; if (pack == null) { pack = new StrongBackpack { Movable = false }; m.AddItem(pack); } } if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on {0} *****", m.GetType())); } } } catch { mobiles.RemoveAt(i); Type failedType = m.GetType(); int failedTypeID = entry.TypeID; failedSerial = m.Serial; Console.WriteLine(failedType); Console.WriteLine(failedTypeID); Console.WriteLine(failedSerial); break; } } } reader.Close(); } } } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); } return(output); }
public static void LoadDuels() { if (File.Exists(duelIdxPath) && File.Exists(duelBinPath)) { // Declare and initialize reader objects. FileStream idx = new FileStream(duelIdxPath, FileMode.Open, FileAccess.Read, FileShare.Read); FileStream bin = new FileStream(duelBinPath, FileMode.Open, FileAccess.Read, FileShare.Read); BinaryReader idxReader = new BinaryReader(idx); BinaryFileReader binReader = new BinaryFileReader(new BinaryReader(bin)); // Start by reading the number of duels from an index file int duelCount = idxReader.ReadInt32(); for (int i = 0; i < duelCount; ++i) { DuelObject d = new DuelObject(); // Read start-position and length of current fight from index file long startPos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); // Point the reading stream to the proper position binReader.Seek(startPos, SeekOrigin.Begin); try { d.Deserialize(binReader); if (binReader.Position != (startPos + length)) throw new Exception(String.Format("***** Bad serialize on DuelObject[{0}] *****", i)); } catch (Exception e) { //handle } duels.Add(d); } // Remember to close the streams idxReader.Close(); binReader.Close(); } }
/* ID's: * 101 = Button Manage System * 102 = Button Import Page * 103 = Button Apply Location * 104 = Button Apply Category * 105 = Text Name * 106 = Text X * 107 = Text Y * 108 = Text Z * 109 = Text Hue * 110 = Text Cost * 111 = Radio Trammel * 112 = Radio Malas * 113 = Radio Felucca * 114 = Radio Ilshenar * 115 = Radio Tokuno * 116 = Check Generate * 117 = Check StaffOnly * 118 = Check Reds * 119 = Check Charge * 120 = Check Young * 121 = Button Add Category * 122 = Button Add Location * 123 = Button Export * 124 = Button Import Systems * 125 = Button Import Categories * 126 = Button Import Locations * 300+ = Imports */ public override void OnResponse(NetState state, RelayInfo info, ACCGumpParams subParams) { if (info.ButtonID == 0 || state.Mobile.AccessLevel < ACC.GlobalMinimumAccessLevel) { return; } if (subParams is PGGumpParams) { Params = subParams as PGGumpParams; } PGGumpParams newParams = new PGGumpParams(); if (info.ButtonID == 101) { newParams.Page = Pages.Manage; } else if (info.ButtonID == 102) { newParams.Page = Pages.Import; } #region Add/Remove else if (info.ButtonID == 103 || info.ButtonID == 104 || info.ButtonID == 121 || info.ButtonID == 122) { SetFlag(EntryFlag.Generate, info.IsSwitched(116)); SetFlag(EntryFlag.StaffOnly, info.IsSwitched(117)); SetFlag(EntryFlag.Reds, info.IsSwitched(118)); SetFlag(EntryFlag.Charge, info.IsSwitched(119)); Map Map = info.IsSwitched(111) ? Map.Trammel : info.IsSwitched(112) ? Map.Malas : info.IsSwitched(113) ? Map.Felucca : info.IsSwitched(114) ? Map.Ilshenar : info.IsSwitched(115) ? Map.Tokuno : Map.Trammel; string Name = GetString(info, 105); string X = GetString(info, 106); string Y = GetString(info, 107); string Z = GetString(info, 108); string H = GetString(info, 109); string C = GetString(info, 110); if (Name == null || Name.Length == 0) { try { state.Mobile.SendMessage("Removed the entry"); if (info.ButtonID == 103) { Params.SelectedCategory.Key.Locations.Remove(Params.SelectedLocation.Key); } else { m_CategoryList.Remove(Params.SelectedCategory.Key); } } catch { Console.WriteLine("Exception caught removing entry"); } } else { if (info.ButtonID == 103 || info.ButtonID == 122) { int x, y, z, h, c = 0; Point3D Loc; int Hue; int Cost; PGLocation PGL; if (X == null || X.Length == 0 || Y == null || Y.Length == 0 || Z == null || Z.Length == 0 || H == null || H.Length == 0 || C == null || C.Length == 0) { if (info.ButtonID == 122) { Hue = 0; Loc = new Point3D(0, 0, 0); Cost = 0; PGL = new PGLocation(Name, Flags, Loc, Map, Hue, Cost); if (PGL == null) { state.Mobile.SendMessage("Error adding Location."); return; } m_CategoryList[Params.SelectedCategory.Value].Locations.Add(PGL); } state.Mobile.SendMessage("Please fill in each field."); state.Mobile.SendGump(new ACCGump(state.Mobile, this.ToString(), Params)); return; } try { x = Int32.Parse(X); y = Int32.Parse(Y); z = Int32.Parse(Z); h = Int32.Parse(H); c = Int32.Parse(C); Loc = new Point3D(x, y, z); Hue = h; Cost = c; } catch { state.Mobile.SendMessage("Please enter an integer in each of the info fields. (X, Y, Z, H, Cost)"); state.Mobile.SendGump(new ACCGump(state.Mobile, this.ToString(), Params)); return; } PGL = new PGLocation(Name, Flags, Loc, Map, Hue, Cost); if (PGL == null) { state.Mobile.SendMessage("Bad Location information, can't add!"); } else { try { if (info.ButtonID == 122) { m_CategoryList[Params.SelectedCategory.Value].Locations.Add(PGL); state.Mobile.SendMessage("Added the Location."); } else { state.Mobile.SendMessage("Changed the Location."); m_CategoryList[Params.SelectedCategory.Value].Locations[Params.SelectedLocation.Value] = PGL; } } catch { Console.WriteLine("Problem adding/changing Location!"); } } } else { if (C == null || C.Length == 0) { state.Mobile.SendMessage("Please fill in each field."); state.Mobile.SendGump(new ACCGump(state.Mobile, this.ToString(), Params)); return; } int c = 0; int Cost; try { c = Int32.Parse(C); Cost = c; } catch { state.Mobile.SendMessage("Please enter an integer for the Cost"); state.Mobile.SendGump(new ACCGump(state.Mobile, this.ToString(), Params)); return; } try { if (info.ButtonID == 121) { m_CategoryList.Add(new PGCategory(Name, Flags, Cost)); state.Mobile.SendMessage("Added the Category."); } else { m_CategoryList[Params.SelectedCategory.Value].Name = Name; m_CategoryList[Params.SelectedCategory.Value].Flags = Flags; m_CategoryList[Params.SelectedCategory.Value].Cost = Cost; state.Mobile.SendMessage("Changed the Category."); } } catch { Console.WriteLine("Problems adding/changing Category!"); } } } } #endregion //Add/Remove #region Imports/Exports #region Exports else if (info.ButtonID == 123) { if (!Directory.Exists("ACC Exports")) { Directory.CreateDirectory("ACC Exports"); } string fileName; string Path = "ACC Exports/"; if (Params.SelectedLocation.Key != null) { fileName = String.Format("Location - {0}.pgl", Params.SelectedLocation.Key.Name); } else if (Params.SelectedCategory.Key != null) { fileName = String.Format("Category - {0}.pgc", Params.SelectedCategory.Key.Name); } else { fileName = String.Format("System - {0:yyMMdd-HHmmss}.pgs", DateTime.Now); } try { using (FileStream m_FileStream = new FileStream(Path + fileName, FileMode.Create, FileAccess.Write)) { GenericWriter writer = new BinaryFileWriter(m_FileStream, true); if (Params.SelectedLocation.Key != null) { Params.SelectedLocation.Key.Serialize(writer); state.Mobile.SendMessage("Exported the Location to {0}{1}", Path, fileName); } else if (Params.SelectedCategory.Key != null) { Params.SelectedCategory.Key.Serialize(writer); state.Mobile.SendMessage("Exported the Category (and all Locations contained within) to {0}{1}", Path, fileName); } else { writer.Write((int)0); //version writer.Write(m_CategoryList.Count); for (int i = 0; i < m_CategoryList.Count; i++) { m_CategoryList[i].Serialize(writer); } state.Mobile.SendMessage("Exported the entire Public Gates System to {0}{1}", Path, fileName); } writer.Close(); m_FileStream.Close(); } } catch (Exception e) { state.Mobile.SendMessage("Problem exporting the selection. Please contact the admin."); Console.WriteLine("Error exporting PGSystem : {0}", e); } } #endregion //Exports #region Imports //Switch between import types else if (info.ButtonID == 124 || info.ButtonID == 125 || info.ButtonID == 126) { newParams.Page = Pages.Import; switch (info.ButtonID) { case 124: newParams.ImportSelection = ImportSelections.Systems; break; case 125: newParams.ImportSelection = ImportSelections.Categories; break; case 126: newParams.ImportSelection = ImportSelections.Locations; break; } } //Perform the import else if (info.ButtonID >= 300 && Dirs != null && Dirs.Length > 0) { if (!Directory.Exists("ACC Exports")) { Directory.CreateDirectory("ACC Exports"); } string Path = null; try { Path = Dirs[info.ButtonID - 300]; if (File.Exists(Path)) { using (FileStream m_FileStream = new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(m_FileStream)); switch ((int)Params.ImportSelection) { case (int)ImportSelections.Systems: { //Systems int version = reader.ReadInt(); int count = reader.ReadInt(); List <PGCategory> list = new List <PGCategory>(); for (int i = 0; i < count; i++) { list.Add(new PGCategory(reader)); } state.Mobile.CloseGump(typeof(SysChoiceGump)); state.Mobile.SendGump(new SysChoiceGump(this.ToString(), Params, list)); reader.Close(); return; } case (int)ImportSelections.Categories: { //Categories if (m_CategoryList == null) { m_CategoryList = new List <PGCategory>(); } m_CategoryList.Add(new PGCategory(reader)); state.Mobile.SendMessage("Added the Category."); break; } case (int)ImportSelections.Locations: { //Locations state.Mobile.CloseGump(typeof(CatSelGump)); state.Mobile.SendMessage("Please choose a Category to put this Location in."); state.Mobile.SendGump(new CatSelGump(this.ToString(), Params, new PGLocation(reader))); reader.Close(); return; } } reader.Close(); } } } catch { } } #endregion //Imports #endregion //Imports/Exports else if (info.ButtonID >= 150 && info.ButtonID < m_CategoryList.Count + 150) { newParams.SelectedCategory = new KeyValuePair <PGCategory, int>(m_CategoryList[info.ButtonID - 150], info.ButtonID - 150); } else if (info.ButtonID >= 200 && info.ButtonID < 200 + Params.SelectedCategory.Key.Locations.Count) { newParams.SelectedCategory = Params.SelectedCategory; newParams.SelectedLocation = new KeyValuePair <PGLocation, int>(Params.SelectedCategory.Key.Locations[info.ButtonID - 200], info.ButtonID - 200); } state.Mobile.SendGump(new ACCGump(state.Mobile, this.ToString(), newParams)); }
private static short FactoryLoad() { m_DODInst = new ArrayList(); m_DODGroup = new ArrayList(); string filePath = Path.Combine("Saves/AngelIsland", "RareFactory.dat"); if (!File.Exists(filePath)) { Console.WriteLine("FactoryLoad() : RareFactory.dat does not exist, assuming new factory"); return(1); // Assume new factory } using (FileStream sr = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { if (!sr.CanRead) { Console.WriteLine("FactoryLoad() : {0} is not readable but exists!!", filePath); return(0); } // This is the stream reader we will read our binary DOD data with BinaryFileReader bfr = new BinaryFileReader(new BinaryReader(sr)); bfr.Seek(0, SeekOrigin.Begin); try { // Just in case we change the save format sometime! short version = ((GenericReader)bfr).ReadShort(); int numtoload = ((GenericReader)bfr).ReadShort(); Console.WriteLine("FactoryLoad() : Loading {0} Dynamic Object Definition{1}...", numtoload, (numtoload != 1 ? "s" : "")); // Instance the DODs with the bfr pointer (the object constructor handles in file input) for (int i = 0; i < numtoload; i++) { m_DODInst.Add(new DODInstance(bfr)); } numtoload = ((GenericReader)bfr).ReadShort(); Console.WriteLine("FactoryLoad() : Loading {0} DOD Group{1}...", numtoload, (numtoload != 1 ? "s" : "")); for (int i = 0; i < numtoload; i++) { DODGroup dg = new DODGroup(bfr); // Save this group list m_DODGroup.Add(dg); } } catch (Exception e) { Console.WriteLine("FactoryLoad() : Caught exception trying to load DODs : {0}", e); LogHelper.LogException(e); } bfr.Close(); } // 'using' closes sr Console.WriteLine("FactoryLoad() : Complete."); return(1); }
public static void Load() { string idxPath = Path.Combine("Saves/Lottery", "Lottery.idx"); string binPath = Path.Combine("Saves/Lottery", "Lottery.bin"); if (File.Exists(idxPath) && File.Exists(binPath)) { // Declare and initialize reader objects. FileStream idx = new FileStream(idxPath, FileMode.Open, FileAccess.Read, FileShare.Read); FileStream bin = new FileStream(binPath, FileMode.Open, FileAccess.Read, FileShare.Read); BinaryReader idxReader = new BinaryReader(idx); BinaryFileReader binReader = new BinaryFileReader(new BinaryReader(bin)); // Read start-position and length of current order from index file long startPos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); // Point the reading stream to the proper position binReader.Seek(startPos, SeekOrigin.Begin); try { Deserialize(binReader); if (binReader.Position != (startPos + length)) throw new Exception("***** Bad serialize on Lottery *****"); } catch { } idxReader.Close(); binReader.Close(); } }
public static void OnLoad() { try { Console.WriteLine("TownshipSettings Loading..."); string filePath = Path.Combine("Saves/AngelIsland", "Township.bin"); if (!File.Exists(filePath)) { return; } BinaryFileReader datreader = new BinaryFileReader(new BinaryReader(new FileStream(filePath, FileMode.Open, FileAccess.Read))); int version = datreader.ReadInt(); switch (version) { case 9: WallHitsDecay = datreader.ReadInt(); goto case 8; case 8: AuctioneerPayoutPercentage = datreader.ReadDouble(); goto case 7; case 7: AuctioneerCharge = datreader.ReadInt(); goto case 6; case 6: FightBrokerCharge = datreader.ReadInt(); goto case 5; case 5: WallTeleporterDistance = datreader.ReadInt(); goto case 4; case 4: InitialFunds = datreader.ReadInt(); goto case 3; case 3: TSDeedCost = datreader.ReadInt(); GuildHousePercentage = datreader.ReadDouble(); LLModifierNone = datreader.ReadDouble(); LLModifierLow = datreader.ReadDouble(); LLModifierMed = datreader.ReadDouble(); LLModifierHigh = datreader.ReadDouble(); LLModifierBoom = datreader.ReadDouble(); NPCModifierNone = datreader.ReadDouble(); NPCModifierLow = datreader.ReadDouble(); NPCModifierMed = datreader.ReadDouble(); NPCModifierHigh = datreader.ReadDouble(); NPCModifierBoom = datreader.ReadDouble(); BaseModifierNone = datreader.ReadDouble(); BaseModifierLow = datreader.ReadDouble(); BaseModifierMed = datreader.ReadDouble(); BaseModifierHigh = datreader.ReadDouble(); BaseModifierBoom = datreader.ReadDouble(); goto case 2; case 2: BaseFee = datreader.ReadInt(); ExtendedFee = datreader.ReadInt(); NoGateOutFee = datreader.ReadInt(); NoGateInFee = datreader.ReadInt(); NoRecallOutFee = datreader.ReadInt(); NoRecallInFee = datreader.ReadInt(); LawlessFee = datreader.ReadInt(); LawAuthFee = datreader.ReadInt(); NPCType1Fee = datreader.ReadInt(); NPCType2Fee = datreader.ReadInt(); NPCType3Fee = datreader.ReadInt(); LawNormCharge = datreader.ReadInt(); LawlessCharge = datreader.ReadInt(); LawAuthCharge = datreader.ReadInt(); ChangeTravelCharge = datreader.ReadInt(); UpdateEnemyCharge = datreader.ReadInt(); EmissaryCharge = datreader.ReadInt(); EvocatorCharge = datreader.ReadInt(); AlchemistCharge = datreader.ReadInt(); AnimalTrainerCharge = datreader.ReadInt(); BankerCharge = datreader.ReadInt(); InnkeeperCharge = datreader.ReadInt(); MageCharge = datreader.ReadInt(); ProvisionerCharge = datreader.ReadInt(); ArmsTrainerCharge = datreader.ReadInt(); MageTrainerCharge = datreader.ReadInt(); RogueTrainerCharge = datreader.ReadInt(); LookoutCharge = datreader.ReadInt(); TownCrierCharge = datreader.ReadInt(); goto case 1; case 1: Hue = datreader.ReadInt(); NoneToLow = datreader.ReadInt(); LowToMedium = datreader.ReadInt(); MediumToHigh = datreader.ReadInt(); HighToBooming = datreader.ReadInt(); break; } datreader.Close(); } catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); } //try to initialize informational fee stuff - not crucial as this is informational // and gets set when the activity calcs are done try { FeePercentageCalc = (double)BaseFee / 2500.0; FeeAcctInfoCount = (int)(FeePercentageCalc * 1000.0); } catch { } }
public static void Load() { if (!Directory.Exists("Saves/ACC")) { return; } string filename = "acc.sav"; string path = @"Saves/ACC/"; string pathNfile = path + filename; DateTime start = DateTime.Now; Console.WriteLine(); Console.WriteLine("----------"); Console.WriteLine("Loading ACC..."); try { using (FileStream m_FileStream = new FileStream(pathNfile, FileMode.Open, FileAccess.Read)) { BinaryReader m_BinaryReader = new BinaryReader(m_FileStream); BinaryFileReader reader = new BinaryFileReader(m_BinaryReader); if (m_RegSystems == null) { m_RegSystems = new Dictionary <string, bool>(); } int Count = reader.ReadInt(); for (int i = 0; i < Count; i++) { string system = reader.ReadString(); Type t = ScriptCompiler.FindTypeByFullName(system); bool enabled = reader.ReadBool(); if (t != null) { m_RegSystems[system] = enabled; if (m_RegSystems[system]) { ACCSystem sys = (ACCSystem)Activator.CreateInstance(t); if (sys != null) { sys.StartLoad(path); } } } } reader.Close(); m_FileStream.Close(); } Console.WriteLine("Done in {0:F1} seconds.", (DateTime.Now - start).TotalSeconds); Console.WriteLine("----------"); Console.WriteLine(); } catch (Exception e) { Console.WriteLine("Failed. Exception: " + e); } }
public static void On_RHFile(CommandEventArgs e) { if (e.Arguments.Length != 1) { e.Mobile.SendMessage("Usage: [LoadCont <filename>"); return; } try { int loaded = 0; int count; LogHelper log = new LogHelper(e.Arguments[0] + " LoadCont.log"); log.Log(LogType.Text, String.Format("Reload process initiated by {0}, with {1} as backup data.", e.Mobile, e.Arguments[0])); using (FileStream idxfs = new FileStream(e.Arguments[0] + ".idx", FileMode.Open, FileAccess.Read)) { using (FileStream binfs = new FileStream(e.Arguments[0] + ".bin", FileMode.Open, FileAccess.Read)) { GenericReader bin = new BinaryFileReader(new BinaryReader(binfs)); GenericReader idx = new BinaryFileReader(new BinaryReader(idxfs)); count = idx.ReadInt(); if (count == -1) { log.Log(LogType.Text, "No item data to reload."); // do nothing } else { ArrayList items = new ArrayList(count); log.Log(LogType.Text, String.Format("Attempting to reload {0} items.", count)); Type[] ctortypes = new Type[] { typeof(Serial) }; object[] ctorargs = new object[1]; for (int i = 0; i < count; i++) { string type = idx.ReadString(); Serial serial = (Serial)idx.ReadInt(); long position = idx.ReadLong(); int length = idx.ReadInt(); Type t = ScriptCompiler.FindTypeByFullName(type); if (t == null) { Console.WriteLine("Warning: Tried to load nonexistent type {0}. Ignoring item.", type); log.Log(String.Format("Warning: Tried to load nonexistent type {0}. Ignoring item.", type)); continue; } ConstructorInfo ctor = t.GetConstructor(ctortypes); if (ctor == null) { Console.WriteLine("Warning: Tried to load type {0} which has no serialization constructor. Ignoring item.", type); log.Log(String.Format("Warning: Tried to load type {0} which has no serialization constructor. Ignoring item.", type)); continue; } Item item = null; try { if (World.FindItem(serial) != null) { log.Log(LogType.Item, World.FindItem(serial), "Serial already in use!! Loading of saved item failed."); } else if (!World.IsReserved(serial)) { log.Log(String.Format("Serial {0} is not reserved!! Loading of saved item failed.", serial)); } else { ctorargs[0] = serial; item = (Item)(ctor.Invoke(ctorargs)); } } catch (Exception ex) { LogHelper.LogException(ex); Console.WriteLine("An exception occurred while trying to invoke {0}'s serialization constructor.", t.FullName); Console.WriteLine(ex.ToString()); log.Log(String.Format("An exception occurred while trying to invoke {0}'s serialization constructor.", t.FullName)); log.Log(ex.ToString()); } if (item != null) { World.FreeSerial(serial); World.AddItem(item); items.Add(new object[] { item, position, length }); log.Log(String.Format("Successfully created item {0}", item)); } } for (int i = 0; i < items.Count; i++) { object[] entry = (object[])items[i]; Item item = entry[0] as Item; long position = (long)entry[1]; int length = (int)entry[2]; if (item != null) { bin.Seek(position, SeekOrigin.Begin); try { item.Deserialize(bin); // take care of parent hierarchy object p = item.Parent; if (p is Item) { ((Item)p).RemoveItem(item); item.Parent = null; ((Item)p).AddItem(item); } else if (p is Mobile) { ((Mobile)p).RemoveItem(item); item.Parent = null; ((Mobile)p).AddItem(item); } else { item.Delta(ItemDelta.Update); } item.ClearProperties(); object rp = item.RootParent; if (rp is Item) { ((Item)rp).UpdateTotals(); } else if (rp is Mobile) { ((Mobile)rp).UpdateTotals(); } else { item.UpdateTotals(); } if (bin.Position != (position + length)) { throw new Exception(String.Format("Bad serialize on {0}", item)); } log.Log(LogType.Item, item, "Successfully loaded."); loaded++; } catch (Exception ex) { LogHelper.LogException(ex); Console.WriteLine("Caught exception while deserializing {0}:", item); Console.WriteLine(ex.ToString()); Console.WriteLine("Deleting item."); log.Log(String.Format("Caught exception while deserializing {0}:", item)); log.Log(ex.ToString()); log.Log("Deleting item."); item.Delete(); } } } } idx.Close(); bin.Close(); } } Console.WriteLine("Attempted to load {0} items: {1} loaded, {2} failed.", count, loaded, count - loaded); log.Log(String.Format("Attempted to load {0} items: {1} loaded, {2} failed.", count, loaded, count - loaded)); e.Mobile.SendMessage("Attempted to load {0} items: {1} loaded, {2} failed.", count, loaded, count - loaded); log.Finish(); } catch (Exception ex) { LogHelper.LogException(ex); Console.WriteLine(ex.ToString()); e.Mobile.SendMessage("Exception: {0}", ex.Message); } }
/// <summary> /// Loads serialized data /// </summary> private static void OnWorldLoad() { if (!File.Exists(DataFile)) { return; } using (FileStream stream = new FileStream(DataFile, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(stream)); int tableCount = reader.ReadInt(); EoCTable = new Dictionary <Player, EoCContext>(tableCount); for (int i = 0; i < tableCount; i++) { if (!reader.ReadBool()) { continue; } Player pl = reader.ReadMobile <Player>(); if (pl != null && !pl.Deleted) { EoCTable[pl] = new EoCContext(reader); } } int hitsCount = reader.ReadInt(); HitsTable = new Dictionary <Player, HitsTimer>(hitsCount); for (int i = 0; i < hitsCount; i++) { if (!reader.ReadBool()) { continue; } Player player = reader.ReadMobile <Player>(); if (player == null || player.Deleted) { continue; } HitsTable[player] = new HitsTimer(player); DateTime next = reader.ReadDateTime(); if (next < DateTime.Now) { next = DateTime.Now; } HitsTable[player].Delay = (next - DateTime.Now); } reader.Close(); } }
public void Deserialize() { //Console.WriteLine("[Vote System]: Loading Config..."); FileInfo info = new FileInfo("Data\\VoteSystem.cfg"); if (!info.Exists) info.Create().Close(); if (info.Length == 0) return; using (BinaryReader br = new BinaryReader(info.OpenRead())) { BinaryFileReader bin = new BinaryFileReader(br); int version = bin.ReadInt(); switch(version) { case 1: _DefaultGold = bin.ReadInt(); goto case 0; case 0: _DefaultName = bin.ReadString(); _DefaultURL = bin.ReadString(); _DefaultCoolDown = bin.ReadTimeSpan(); break; } bin.Close(); } //Console.WriteLine("[Vote System]: Done."); }
public static void Load() { Console.Write("DonatorAccountSettings: Loading..."); string idxPath = Path.Combine( "Saves/Donation", "DonatorAccountSettings.idx" ); string binPath = Path.Combine( "Saves/Donation", "DonatorAccountSettings.bin" ); if (File.Exists(idxPath) && File.Exists(binPath)) { // Declare and initialize reader objects. FileStream idx = new FileStream(idxPath, FileMode.Open, FileAccess.Read, FileShare.Read); FileStream bin = new FileStream(binPath, FileMode.Open, FileAccess.Read, FileShare.Read); BinaryReader idxReader = new BinaryReader(idx); BinaryFileReader binReader = new BinaryFileReader(new BinaryReader(bin)); // Start by reading the number of duels from an index file int orderCount = idxReader.ReadInt32(); for (int i = 0; i < orderCount; ++i) { DonatorAccountSettings das = new DonatorAccountSettings(); // Read start-position and length of current order from index file long startPos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); // Point the reading stream to the proper position binReader.Seek(startPos, SeekOrigin.Begin); try { das.Deserialize(binReader); if (binReader.Position != (startPos + length)) throw new Exception(String.Format("***** Bad serialize on DonatorAccountSettings[{0}] *****", i)); } catch { //handle } if ( das != null && das.m_Account != null ) DonatorAccountSettingsTable.Add( das.m_Account, das ); } // Remember to close the streams idxReader.Close(); binReader.Close(); } Console.WriteLine("done"); }
public static void LoadFights() { if (File.Exists(fightIdxPath) && File.Exists(fightBinPath)) { // Declare and initialize reader objects. FileStream idx = new FileStream(fightIdxPath, FileMode.Open, FileAccess.Read, FileShare.Read); FileStream bin = new FileStream(fightBinPath, FileMode.Open, FileAccess.Read, FileShare.Read); BinaryReader idxReader = new BinaryReader(idx); BinaryFileReader binReader = new BinaryFileReader(new BinaryReader(bin)); // Start by reading the number of figts from an index file int fightCount = idxReader.ReadInt32(); //Console.WriteLine("Fight objects: {0}", fightCount); bool indexSet = false; for (int i = 0; i < fightCount; ++i) { Fight fight = new Fight(); // Read start-position and length of current fight from index file long startPos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); // Point the reading stream to the proper position binReader.Seek(startPos, SeekOrigin.Begin); try { fight.Deserialize(binReader); if (binReader.Position != (startPos + length)) throw new Exception(String.Format("***** Bad serialize on Fight[{0}] *****", i)); } catch (Exception e) { //handle } fights.Add(fight); // Read data into fast-access variables // This is done to optimize perfomance // Searching through long arrays repeatedly // Could slow down the server // Add mobile to the list of active players if (fight.Winner != null && !players.Contains(fight.Winner)) players.Add(fight.Winner); if (fight.Loser != null && !players.Contains(fight.Loser)) players.Add(fight.Loser); // Adjust Honor, win and loss variables if (fight.Winner != null) { ((PlayerMobile)fight.Winner).Wins++; ((PlayerMobile)fight.Winner).Honor += fight.Gain; } if (fight.Loser != null) { ((PlayerMobile)fight.Loser).Losses++; ((PlayerMobile)fight.Loser).Honor -= fight.Loss; } // Adjust HonorChange variable and set the index of the last fight in interval if ( fight.Start > DateTime.Now - interval) { if (fight.Winner != null) ((PlayerMobile)fight.Winner).HonorChange += fight.Gain; if (fight.Loser != null) ((PlayerMobile)fight.Loser).HonorChange -= fight.Loss; if(!indexSet) { indexSet = true; lastIntervalIndex = fights.IndexOf(fight); } } } // Only old fights were found, or there was no fights to load.... so we set the index to last fight if (!indexSet && fights.Count != 0) lastIntervalIndex = fights.Count - 1; players.Sort(); // Remember to close the streams idxReader.Close(); binReader.Close(); } }