private static void event_worldLoad() { if (!File.Exists(PersistenceFile)) { return; } using (FileStream stream = new FileStream(PersistenceFile, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(stream)); int count = reader.ReadInt(); for (int i = 0; i < count; i++) { int serial = reader.ReadInt(); if (serial > -1) { Mobile m = World.FindMobile(serial); GrabOptions options = new GrabOptions(reader); if (m != null && !m.Deleted) { if (options != null && !OptionsTable.ContainsKey(m)) { OptionsTable.Add(m, options); } } } } reader.Close(); } }
public static void Deserialize(FileInfo file, Action <GenericReader> deserializer, bool ensure) { file.Refresh(); if (file.Directory != null && !file.Directory.Exists) { if (!ensure) { throw new DirectoryNotFoundException(); } file.Directory.Create(); } if (!file.Exists) { if (!ensure) { throw new FileNotFoundException { Source = file.FullName }; } file.Create().Close(); } file.Refresh(); using (FileStream fs = file.OpenRead()) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(fs)); try { deserializer(reader); } catch (EndOfStreamException eos) { if (file.Length > 0) { throw new Exception(string.Format("[Persistence]: {0}", eos)); } } catch (Exception e) { Utility.WriteConsoleColor(ConsoleColor.Red, "[Persistence]: An error was encountered while loading a saved object"); throw new Exception(string.Format("[Persistence]: {0}", e)); } finally { reader.Close(); } } }
public static void Deserialize(FileInfo file, Action <GenericReader> deserializer, bool ensure) { file.Refresh(); if (file.Directory != null && !file.Directory.Exists) { if (!ensure) { throw new DirectoryNotFoundException(); } file.Directory.Create(); } if (!file.Exists) { if (!ensure) { throw new FileNotFoundException { Source = file.FullName }; } file.Create().Close(); } file.Refresh(); using (var fs = file.OpenRead()) { var reader = new BinaryFileReader(new BinaryReader(fs)); try { deserializer(reader); } catch (EndOfStreamException eos) { if (file.Length > 0) { Console.WriteLine("[Persistence]: {0}", eos); } } catch (Exception e) { Utility.PushColor(ConsoleColor.Red); Console.WriteLine("[Persistence]: {0}", e); Utility.PopColor(); } finally { reader.Close(); } } }
public static void Deserialize(FileInfo file, Action <IGenericReader> deserializer, bool ensure) { file.Refresh(); if (file.Directory?.Exists == false) { if (!ensure) { throw new DirectoryNotFoundException(); } file.Directory.Create(); } if (!file.Exists) { if (!ensure) { throw new FileNotFoundException { Source = file.FullName } } ; file.Create().Close(); } file.Refresh(); using FileStream fs = file.OpenRead(); BinaryFileReader reader = new BinaryFileReader(new BinaryReader(fs)); try { deserializer(reader); } catch (EndOfStreamException eos) { if (file.Length > 0) { Console.WriteLine("[Persistence]: {0}", eos); } } catch (Exception e) { Console.WriteLine("[Persistence]: {0}", e); } finally { reader.Close(); } } }
private static void LoadRegions(string path, RegionEntry[] entries) { using (FileStream bin = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (BinaryReader binReader = new BinaryReader(bin)) { BinaryFileReader reader = new BinaryFileReader(binReader); try { LoadRegions(reader, entries); } finally { reader.Close(); } } } }
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 Deserialize(FileInfo file, Action <GenericReader> deserializer, bool ensure) { if (file.Directory != null && !file.Directory.Exists) { if (!ensure) { throw new DirectoryNotFoundException(); } file.Directory.Create(); } bool created = false; if (!file.Exists) { if (!ensure) { throw new FileNotFoundException(); } file.Create().Close(); created = true; } using (var fs = file.OpenRead()) { var reader = new BinaryFileReader(new BinaryReader(fs)); try { deserializer(reader); } catch (EndOfStreamException eos) { if (!created) { Console.WriteLine("[Persistence]: {0}", eos); } } finally { reader.Close(); } } }
public static void Deserialize(FileInfo file, Action<GenericReader> deserializer, bool ensure) { if (file.Directory != null && !file.Directory.Exists) { if (!ensure) { throw new DirectoryNotFoundException(); } file.Directory.Create(); } bool created = false; if (!file.Exists) { if (!ensure) { throw new FileNotFoundException(); } file.Create().Close(); created = true; } using (var fs = file.OpenRead()) { var reader = new BinaryFileReader(new BinaryReader(fs)); try { deserializer(reader); } catch (EndOfStreamException eos) { if (!created) { Console.WriteLine("[Persistence]: {0}", eos); } } finally { reader.Close(); } } }
public static void DeserializeBlock(GenericReader reader, Action <GenericReader> deserializer) { if (reader.PeekInt() == 0x0C0FFEE0 && reader.ReadInt() == 0x0C0FFEE0) { int length = reader.ReadInt(); byte[] data = Array.Empty <byte>(); if (length > 0) { data = new byte[length]; } for (int i = 0; i < data.Length; i++) { data[i] = reader.ReadByte(); } if (deserializer != null) { using (MemoryStream ms = new MemoryStream(data)) { BinaryFileReader r = new BinaryFileReader(new BinaryReader(ms)); try { deserializer(r); } finally { r.Close(); } } } } else { deserializer?.Invoke(reader); } }
public static void Load() { if (m_Loaded) { return; } m_Loaded = true; m_LoadingType = null; Console.Write("World: Loading..."); DateTime start = DateTime.Now; m_Loading = true; m_DeleteList = new ArrayList(); int mobileCount = 0, itemCount = 0, guildCount = 0, regionCount = 0; object[] ctorArgs = new object[1]; Type[] ctorTypes = new Type[1] { typeof(Serial) }; ArrayList items = new ArrayList(); ArrayList mobiles = new ArrayList(); ArrayList guilds = new ArrayList(); ArrayList regions = new ArrayList(); if (File.Exists(mobIdxPath) && File.Exists(mobTdbPath)) { using (FileStream idx = new FileStream(mobIdxPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader idxReader = new BinaryReader(idx); using (FileStream tdb = new FileStream(mobTdbPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader tdbReader = new BinaryReader(tdb); int count = tdbReader.ReadInt32(); ArrayList types = new ArrayList(count); for (int i = 0; i < count; ++i) { string typeName = tdbReader.ReadString(); Type t = ScriptCompiler.FindTypeByFullName(typeName); if (t == null) { Console.WriteLine("failed"); Console.WriteLine("Error: Type '{0}' was not found. Delete all of those types? (y/n)", typeName); if (Console.ReadLine() == "y") { types.Add(null); Console.Write("World: Loading..."); continue; } Console.WriteLine("Types will not be deleted. An exception will be thrown when you press return"); throw new Exception(String.Format("Bad type '{0}'", typeName)); } ConstructorInfo ctor = t.GetConstructor(ctorTypes); if (ctor != null) { types.Add(new object[] { ctor, null }); } else { throw new Exception(String.Format("Type '{0}' does not have a serialization constructor", t)); } } mobileCount = idxReader.ReadInt32(); m_Mobiles = new Hashtable(mobileCount); for (int i = 0; i < mobileCount; ++i) { int typeID = idxReader.ReadInt32(); int serial = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); object[] objs = (object[])types[typeID]; if (objs == null) { continue; } Mobile m = null; ConstructorInfo ctor = (ConstructorInfo)objs[0]; string typeName = (string)objs[1]; try { ctorArgs[0] = (Serial)serial; m = (Mobile)(ctor.Invoke(ctorArgs)); } catch { } if (m != null) { mobiles.Add(new MobileEntry(m, typeID, typeName, pos, length)); AddMobile(m); } } tdbReader.Close(); } idxReader.Close(); } } else { m_Mobiles = new Hashtable(); } if (File.Exists(itemIdxPath) && File.Exists(itemTdbPath)) { using (FileStream idx = new FileStream(itemIdxPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader idxReader = new BinaryReader(idx); using (FileStream tdb = new FileStream(itemTdbPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader tdbReader = new BinaryReader(tdb); int count = tdbReader.ReadInt32(); ArrayList types = new ArrayList(count); for (int i = 0; i < count; ++i) { string typeName = tdbReader.ReadString(); Type t = ScriptCompiler.FindTypeByFullName(typeName); if (t == null) { Console.WriteLine("failed"); Console.WriteLine("Error: Type '{0}' was not found. Delete all of those types? (y/n)", typeName); if (Console.ReadLine() == "y") { types.Add(null); Console.Write("World: Loading..."); continue; } Console.WriteLine("Types will not be deleted. An exception will be thrown when you press return"); throw new Exception(String.Format("Bad type '{0}'", typeName)); } ConstructorInfo ctor = t.GetConstructor(ctorTypes); if (ctor != null) { types.Add(new object[] { ctor, typeName }); } else { throw new Exception(String.Format("Type '{0}' does not have a serialization constructor", t)); } } itemCount = idxReader.ReadInt32(); m_Items = new Hashtable(itemCount); for (int i = 0; i < itemCount; ++i) { int typeID = idxReader.ReadInt32(); int serial = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); object[] objs = (object[])types[typeID]; if (objs == null) { continue; } Item item = null; ConstructorInfo ctor = (ConstructorInfo)objs[0]; string typeName = (string)objs[1]; try { ctorArgs[0] = (Serial)serial; item = (Item)(ctor.Invoke(ctorArgs)); } catch { } if (item != null) { items.Add(new ItemEntry(item, typeID, typeName, pos, length)); AddItem(item); } } tdbReader.Close(); } idxReader.Close(); } } else { m_Items = new Hashtable(); } if (File.Exists(guildIdxPath)) { using (FileStream idx = new FileStream(guildIdxPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader idxReader = new BinaryReader(idx); guildCount = idxReader.ReadInt32(); CreateGuildEventArgs createEventArgs = new CreateGuildEventArgs(-1); for (int i = 0; i < guildCount; ++i) { idxReader.ReadInt32(); //no typeid for guilds int id = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); createEventArgs.Id = id; BaseGuild guild = EventSink.InvokeCreateGuild(createEventArgs); //new Guild( id ); if (guild != null) { guilds.Add(new GuildEntry(guild, pos, length)); } } idxReader.Close(); } } if (File.Exists(regionIdxPath)) { using (FileStream idx = new FileStream(regionIdxPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader idxReader = new BinaryReader(idx); regionCount = idxReader.ReadInt32(); for (int i = 0; i < regionCount; ++i) { int typeID = idxReader.ReadInt32(); int serial = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); Region r = Region.FindByUId(serial); if (r != null) { regions.Add(new RegionEntry(r, pos, length)); Region.AddRegion(r); regionCount++; } } idxReader.Close(); } } bool failedMobiles = false, failedItems = false, failedGuilds = false, failedRegions = false; Type failedType = null; Serial failedSerial = Serial.Zero; Exception failed = null; int failedTypeID = 0; if (File.Exists(mobBinPath)) { using (FileStream bin = new FileStream(mobBinPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin)); for (int i = 0; i < mobiles.Count; ++i) { MobileEntry entry = (MobileEntry)mobiles[i]; Mobile m = (Mobile)entry.Object; if (m != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { m_LoadingType = entry.TypeName; m.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on {0} *****", m.GetType())); } } catch (Exception e) { mobiles.RemoveAt(i); failed = e; failedMobiles = true; failedType = m.GetType(); failedTypeID = entry.TypeID; failedSerial = m.Serial; break; } } } reader.Close(); } } if (!failedMobiles && 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 { m_LoadingType = entry.TypeName; item.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on {0} *****", item.GetType())); } } catch (Exception e) { items.RemoveAt(i); failed = e; failedItems = true; failedType = item.GetType(); failedTypeID = entry.TypeID; failedSerial = item.Serial; break; } } } reader.Close(); } } m_LoadingType = null; if (!failedMobiles && !failedItems && File.Exists(guildBinPath)) { using (FileStream bin = new FileStream(guildBinPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin)); for (int i = 0; i < guilds.Count; ++i) { GuildEntry entry = (GuildEntry)guilds[i]; BaseGuild g = (BaseGuild)entry.Object; if (g != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { g.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on Guild {0} *****", g.Id)); } } catch (Exception e) { guilds.RemoveAt(i); failed = e; failedGuilds = true; failedType = typeof(BaseGuild); failedTypeID = g.Id; failedSerial = g.Id; break; } } } reader.Close(); } } if (!failedMobiles && !failedItems && File.Exists(regionBinPath)) { using (FileStream bin = new FileStream(regionBinPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin)); for (int i = 0; i < regions.Count; ++i) { RegionEntry entry = (RegionEntry)regions[i]; Region r = (Region)entry.Object; if (r != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { r.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on {0} *****", r.GetType())); } } catch (Exception e) { regions.RemoveAt(i); failed = e; failedRegions = true; failedType = r.GetType(); failedTypeID = entry.TypeID; failedSerial = r.UId; break; } } } reader.Close(); } } if (failedItems || failedMobiles || failedGuilds || failedRegions) { Console.WriteLine("An error was encountered while loading a saved object"); Console.WriteLine(" - Type: {0}", failedType); Console.WriteLine(" - Serial: {0}", failedSerial); Console.WriteLine("Delete the object? (y/n)"); if (Console.ReadLine() == "y") { if (failedType != typeof(BaseGuild) && !failedType.IsSubclassOf(typeof(Region))) { Console.WriteLine("Delete all objects of that type? (y/n)"); if (Console.ReadLine() == "y") { if (failedMobiles) { for (int i = 0; i < mobiles.Count;) { if (((MobileEntry)mobiles[i]).TypeID == failedTypeID) { mobiles.RemoveAt(i); } else { ++i; } } } else if (failedItems) { for (int i = 0; i < items.Count;) { if (((ItemEntry)items[i]).TypeID == failedTypeID) { items.RemoveAt(i); } else { ++i; } } } } } SaveIndex(mobiles, mobIdxPath); SaveIndex(items, itemIdxPath); SaveIndex(guilds, guildIdxPath); SaveIndex(regions, regionIdxPath); } Console.WriteLine("After pressing return an exception will be thrown and the server will terminate"); Console.ReadLine(); throw new Exception(String.Format("Load failed (items={0}, mobiles={1}, guilds={2}, regions={3}, type={4}, serial={5})", failedItems, failedMobiles, failedGuilds, failedRegions, failedType, failedSerial), failed); } EventSink.InvokeWorldLoad(); m_Loading = false; for (int i = 0; i < m_DeleteList.Count; ++i) { object o = m_DeleteList[i]; if (o is Item) { ((Item)o).Delete(); } else if (o is Mobile) { ((Mobile)o).Delete(); } } m_DeleteList.Clear(); foreach (Item item in m_Items.Values) { if (item.Parent == null) { item.UpdateTotals(); } item.ClearProperties(); } ArrayList list = new ArrayList(m_Mobiles.Values); foreach (Mobile m in list) { m.ForceRegionReEnter(true); m.UpdateTotals(); m.ClearProperties(); } Console.WriteLine("done ({1} items, {2} mobiles) ({0:F1} seconds)", (DateTime.Now - start).TotalSeconds, m_Items.Count, m_Mobiles.Count); }
private static void LoadEntities() { ItemEntry[] itemEntries = null; MobileEntry[] mobileEntries = null; GuildEntry[] guildEntries = null; RegionEntry[] regionEntries = null; if (File.Exists(mobIdxPath) && File.Exists(mobTdbPath)) { log.Debug("loading mobile index"); EntityType[] types = LoadTypes(mobTdbPath); mobileEntries = LoadMobileIndex(mobIdxPath, types); } else { m_Mobiles = new Hashtable(); } if (File.Exists(itemIdxPath) && File.Exists(itemTdbPath)) { log.Debug("loading item index"); EntityType[] types = LoadTypes(itemTdbPath); itemEntries = LoadItemIndex(itemIdxPath, types); } else { m_Items = new Hashtable(); } if (File.Exists(guildIdxPath)) { log.Debug("loading guild index"); using (FileStream idx = new FileStream(guildIdxPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader idxReader = new BinaryReader(idx); int count = idxReader.ReadInt32(); guildEntries = new GuildEntry[count]; CreateGuildEventArgs createEventArgs = new CreateGuildEventArgs(-1); for (int i = 0; i < count; ++i) { idxReader.ReadInt32(); //no typeid for guilds int id = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); createEventArgs.Id = id; BaseGuild guild = EventSink.InvokeCreateGuild(createEventArgs); //new Guild( id ); if (guild != null) { guildEntries[i] = new GuildEntry(guild, pos, length); } } idxReader.Close(); } } if (File.Exists(regionIdxPath)) { log.Debug("loading region index"); using (FileStream idx = new FileStream(regionIdxPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader idxReader = new BinaryReader(idx); int count = idxReader.ReadInt32(); regionEntries = new RegionEntry[count]; for (int i = 0; i < count; ++i) { idxReader.ReadInt32(); /* typeID */ int serial = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); Region r = Region.FindByUId(serial); if (r != null) { regionEntries[i] = new RegionEntry(r, pos, length); Region.AddRegion(r); } } idxReader.Close(); } } bool failedMobiles = false, failedItems = false, failedGuilds = false, failedRegions = false; Type failedType = null; Serial failedSerial = Serial.Zero; Exception failed = null; int failedTypeID = 0; if (File.Exists(mobBinPath)) { log.Debug("loading mobiles"); using (FileStream bin = new FileStream(mobBinPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin)); for (int i = 0; i < mobileEntries.Length; ++i) { MobileEntry entry = mobileEntries[i]; Mobile m = (Mobile)entry.Object; if (m != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { m_LoadingType = entry.TypeName; m.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on {0} *****", m.GetType())); } } catch (Exception e) { log.Error("failed to load mobile", e); mobileEntries[i].Clear(); failed = e; failedMobiles = true; failedType = m.GetType(); failedTypeID = entry.TypeID; failedSerial = m.Serial; break; } } } reader.Close(); } if (!failedMobiles) { mobileEntries = null; } } if (!failedMobiles && File.Exists(itemBinPath)) { log.Debug("loading items"); using (FileStream bin = new FileStream(itemBinPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin)); for (int i = 0; i < itemEntries.Length; ++i) { ItemEntry entry = itemEntries[i]; Item item = (Item)entry.Object; if (item != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { m_LoadingType = entry.TypeName; item.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on {0} *****", item.GetType())); } } catch (Exception e) { log.Fatal("failed to load item", e); itemEntries[i].Clear(); failed = e; failedItems = true; failedType = item.GetType(); failedTypeID = entry.TypeID; failedSerial = item.Serial; break; } } } reader.Close(); } if (!failedItems) { itemEntries = null; } } if (!failedMobiles && !failedItems && File.Exists(guildBinPath)) { log.Debug("loading guilds"); using (FileStream bin = new FileStream(guildBinPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin)); for (int i = 0; i < guildEntries.Length; ++i) { GuildEntry entry = guildEntries[i]; BaseGuild g = (BaseGuild)entry.Object; if (g != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { g.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on Guild {0} *****", g.Id)); } } catch (Exception e) { log.Fatal("failed to load guild", e); guildEntries[i].Clear(); failed = e; failedGuilds = true; failedType = typeof(BaseGuild); failedTypeID = g.Id; failedSerial = g.Id; break; } } } reader.Close(); } if (!failedGuilds) { guildEntries = null; } } if (!failedMobiles && !failedItems && File.Exists(regionBinPath)) { log.Debug("loading regions"); using (FileStream bin = new FileStream(regionBinPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin)); for (int i = 0; i < regionEntries.Length; ++i) { RegionEntry entry = regionEntries[i]; Region r = (Region)entry.Object; if (r != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { r.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on {0} *****", r.GetType())); } } catch (Exception e) { log.Fatal("failed to load region", e); regionEntries[i].Clear(); failed = e; failedRegions = true; failedType = r.GetType(); failedTypeID = entry.TypeID; failedSerial = r.UId; break; } } } reader.Close(); } if (!failedRegions) { regionEntries = null; } } if (failedItems || failedMobiles || failedGuilds || failedRegions) { Console.WriteLine("An error was encountered while loading a saved object"); Console.WriteLine(" - Type: {0}", failedType); Console.WriteLine(" - Serial: {0}", failedSerial); Console.WriteLine("Delete the object? (y/n)"); if (Console.ReadLine() == "y") { if (failedType != typeof(BaseGuild) && !failedType.IsSubclassOf(typeof(Region))) { Console.WriteLine("Delete all objects of that type? (y/n)"); if (Console.ReadLine() == "y") { if (failedMobiles) { for (int i = 0; i < mobileEntries.Length; ++i) { if (mobileEntries[i].TypeID == failedTypeID) { mobileEntries[i].Clear(); } } } else if (failedItems) { for (int i = 0; i < itemEntries.Length; ++i) { if (itemEntries[i].TypeID == failedTypeID) { itemEntries[i].Clear(); } } } } } if (mobileEntries != null) { SaveIndex(mobileEntries, mobIdxPath); } if (itemEntries != null) { SaveIndex(itemEntries, itemIdxPath); } if (guildEntries != null) { SaveIndex(guildEntries, guildIdxPath); } if (regionEntries != null) { SaveIndex(regionEntries, regionIdxPath); } } Console.WriteLine("After pressing return an exception will be thrown and the server will terminate"); Console.ReadLine(); throw new Exception(String.Format("Load failed (items={0}, mobiles={1}, guilds={2}, regions={3}, type={4}, serial={5})", failedItems, failedMobiles, failedGuilds, failedRegions, failedType, failedSerial), failed); } }
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>"); } }
public static void Load() { if ( m_Loaded ) return; m_Loaded = true; m_LoadingType = null; Console.Write( "World: Loading..." ); DateTime start = DateTime.Now; m_Loading = true; m_DeleteList = new ArrayList(); int mobileCount = 0, itemCount = 0, guildCount = 0, regionCount = 0; object[] ctorArgs = new object[1]; Type[] ctorTypes = new Type[1]{ typeof( Serial ) }; ArrayList items = new ArrayList(); ArrayList mobiles = new ArrayList(); ArrayList guilds = new ArrayList(); ArrayList regions = new ArrayList(); if ( File.Exists( mobIdxPath ) && File.Exists( mobTdbPath ) ) { using ( FileStream idx = new FileStream( mobIdxPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) { BinaryReader idxReader = new BinaryReader( idx ); using ( FileStream tdb = new FileStream( mobTdbPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) { BinaryReader tdbReader = new BinaryReader( tdb ); int count = tdbReader.ReadInt32(); ArrayList types = new ArrayList( count ); for ( int i = 0; i < count; ++i ) { string typeName = tdbReader.ReadString(); Type t = ScriptCompiler.FindTypeByFullName( typeName ); if ( t == null ) { Console.WriteLine( "failed" ); Console.WriteLine( "Error: Type '{0}' was not found. Delete all of those types? (y/n)", typeName ); if ( Console.ReadLine() == "y" ) { types.Add( null ); Console.Write( "World: Loading..." ); continue; } Console.WriteLine( "Types will not be deleted. An exception will be thrown when you press return" ); throw new Exception( String.Format( "Bad type '{0}'", typeName ) ); } ConstructorInfo ctor = t.GetConstructor( ctorTypes ); if ( ctor != null ) { types.Add( new object[]{ ctor, null } ); } else { throw new Exception( String.Format( "Type '{0}' does not have a serialization constructor", t ) ); } } mobileCount = idxReader.ReadInt32(); m_Mobiles = new Hashtable( mobileCount ); for ( int i = 0; i < mobileCount; ++i ) { int typeID = idxReader.ReadInt32(); int serial = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); object[] objs = (object[])types[typeID]; if ( objs == null ) continue; Mobile m = null; ConstructorInfo ctor = (ConstructorInfo)objs[0]; string typeName = (string)objs[1]; try { ctorArgs[0] = (Serial)serial; m = (Mobile)(ctor.Invoke( ctorArgs )); } catch { } if ( m != null ) { mobiles.Add( new MobileEntry( m, typeID, typeName, pos, length ) ); AddMobile( m ); } } tdbReader.Close(); } idxReader.Close(); } } else { m_Mobiles = new Hashtable(); } if ( File.Exists( itemIdxPath ) && File.Exists( itemTdbPath ) ) { using ( FileStream idx = new FileStream( itemIdxPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) { BinaryReader idxReader = new BinaryReader( idx ); using ( FileStream tdb = new FileStream( itemTdbPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) { BinaryReader tdbReader = new BinaryReader( tdb ); int count = tdbReader.ReadInt32(); ArrayList types = new ArrayList( count ); for ( int i = 0; i < count; ++i ) { string typeName = tdbReader.ReadString(); Type t = ScriptCompiler.FindTypeByFullName( typeName ); if ( t == null ) { Console.WriteLine( "failed" ); Console.WriteLine( "Error: Type '{0}' was not found. Delete all of those types? (y/n)", typeName ); if ( Console.ReadLine() == "y" ) { types.Add( null ); Console.Write( "World: Loading..." ); continue; } Console.WriteLine( "Types will not be deleted. An exception will be thrown when you press return" ); throw new Exception( String.Format( "Bad type '{0}'", typeName ) ); } ConstructorInfo ctor = t.GetConstructor( ctorTypes ); if ( ctor != null ) { types.Add( new object[]{ ctor, typeName } ); } else { throw new Exception( String.Format( "Type '{0}' does not have a serialization constructor", t ) ); } } itemCount = idxReader.ReadInt32(); m_Items = new Hashtable( itemCount ); for ( int i = 0; i < itemCount; ++i ) { int typeID = idxReader.ReadInt32(); int serial = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); object[] objs = (object[])types[typeID]; if ( objs == null ) continue; Item item = null; ConstructorInfo ctor = (ConstructorInfo)objs[0]; string typeName = (string)objs[1]; try { ctorArgs[0] = (Serial)serial; item = (Item)(ctor.Invoke( ctorArgs )); } catch { } if ( item != null ) { items.Add( new ItemEntry( item, typeID, typeName, pos, length ) ); AddItem( item ); } } tdbReader.Close(); } idxReader.Close(); } } else { m_Items = new Hashtable(); } if ( File.Exists( guildIdxPath ) ) { using ( FileStream idx = new FileStream( guildIdxPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) { BinaryReader idxReader = new BinaryReader( idx ); guildCount = idxReader.ReadInt32(); CreateGuildEventArgs createEventArgs = new CreateGuildEventArgs( -1 ); for ( int i = 0; i < guildCount; ++i ) { idxReader.ReadInt32();//no typeid for guilds int id = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); createEventArgs.Id = id; BaseGuild guild = EventSink.InvokeCreateGuild( createEventArgs );//new Guild( id ); if ( guild != null ) guilds.Add( new GuildEntry( guild, pos, length ) ); } idxReader.Close(); } } if ( File.Exists( regionIdxPath ) ) { using ( FileStream idx = new FileStream( regionIdxPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) { BinaryReader idxReader = new BinaryReader( idx ); regionCount = idxReader.ReadInt32(); for ( int i = 0; i < regionCount; ++i ) { int typeID = idxReader.ReadInt32(); int serial = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); Region r = Region.FindByUId( serial ); if ( r != null ) { regions.Add( new RegionEntry( r, pos, length ) ); Region.AddRegion( r ); regionCount++; } } idxReader.Close(); } } bool failedMobiles = false, failedItems = false, failedGuilds = false, failedRegions = false; Type failedType = null; Serial failedSerial = Serial.Zero; Exception failed = null; int failedTypeID = 0; if ( File.Exists( mobBinPath ) ) { using ( FileStream bin = new FileStream( mobBinPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) { BinaryFileReader reader = new BinaryFileReader( new BinaryReader( bin ) ); for ( int i = 0; i < mobiles.Count; ++i ) { MobileEntry entry = (MobileEntry)mobiles[i]; Mobile m = (Mobile)entry.Object; if ( m != null ) { reader.Seek( entry.Position, SeekOrigin.Begin ); try { m_LoadingType = entry.TypeName; m.Deserialize( reader ); if ( reader.Position != (entry.Position + entry.Length) ) throw new Exception( String.Format( "***** Bad serialize on {0} *****", m.GetType() ) ); } catch ( Exception e ) { mobiles.RemoveAt( i ); failed = e; failedMobiles = true; failedType = m.GetType(); failedTypeID = entry.TypeID; failedSerial = m.Serial; break; } } } reader.Close(); } } if ( !failedMobiles && 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 { m_LoadingType = entry.TypeName; item.Deserialize( reader ); if ( reader.Position != (entry.Position + entry.Length) ) throw new Exception( String.Format( "***** Bad serialize on {0} *****", item.GetType() ) ); } catch ( Exception e ) { items.RemoveAt( i ); failed = e; failedItems = true; failedType = item.GetType(); failedTypeID = entry.TypeID; failedSerial = item.Serial; break; } } } reader.Close(); } } m_LoadingType = null; if ( !failedMobiles && !failedItems && File.Exists( guildBinPath ) ) { using ( FileStream bin = new FileStream( guildBinPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) { BinaryFileReader reader = new BinaryFileReader( new BinaryReader( bin ) ); for ( int i = 0; i < guilds.Count; ++i ) { GuildEntry entry = (GuildEntry)guilds[i]; BaseGuild g = (BaseGuild)entry.Object; if ( g != null ) { reader.Seek( entry.Position, SeekOrigin.Begin ); try { g.Deserialize( reader ); if ( reader.Position != (entry.Position + entry.Length) ) throw new Exception( String.Format( "***** Bad serialize on Guild {0} *****", g.Id ) ); } catch ( Exception e ) { guilds.RemoveAt( i ); failed = e; failedGuilds = true; failedType = typeof( BaseGuild ); failedTypeID = g.Id; failedSerial = g.Id; break; } } } reader.Close(); } } if ( !failedMobiles && !failedItems && File.Exists( regionBinPath ) ) { using ( FileStream bin = new FileStream( regionBinPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) { BinaryFileReader reader = new BinaryFileReader( new BinaryReader( bin ) ); for ( int i = 0; i <regions.Count; ++i ) { RegionEntry entry = (RegionEntry)regions[i]; Region r = (Region)entry.Object; if ( r != null ) { reader.Seek( entry.Position, SeekOrigin.Begin ); try { r.Deserialize( reader ); if ( reader.Position != (entry.Position + entry.Length) ) throw new Exception( String.Format( "***** Bad serialize on {0} *****", r.GetType() ) ); } catch ( Exception e ) { regions.RemoveAt( i ); failed = e; failedRegions = true; failedType = r.GetType(); failedTypeID = entry.TypeID; failedSerial = r.UId; break; } } } reader.Close(); } } if ( failedItems || failedMobiles || failedGuilds || failedRegions ) { Console.WriteLine( "An error was encountered while loading a saved object" ); Console.WriteLine( " - Type: {0}", failedType ); Console.WriteLine( " - Serial: {0}", failedSerial ); Console.WriteLine( "Delete the object? (y/n)" ); if ( Console.ReadLine() == "y" ) { if ( failedType != typeof( BaseGuild ) && !failedType.IsSubclassOf( typeof( Region ) ) ) { Console.WriteLine( "Delete all objects of that type? (y/n)" ); if ( Console.ReadLine() == "y" ) { if ( failedMobiles ) { for ( int i = 0; i < mobiles.Count; ) { if ( ((MobileEntry)mobiles[i]).TypeID == failedTypeID ) mobiles.RemoveAt( i ); else ++i; } } else if ( failedItems ) { for ( int i = 0; i < items.Count; ) { if ( ((ItemEntry)items[i]).TypeID == failedTypeID ) items.RemoveAt( i ); else ++i; } } } } SaveIndex( mobiles, mobIdxPath ); SaveIndex( items, itemIdxPath ); SaveIndex( guilds, guildIdxPath ); SaveIndex( regions, regionIdxPath ); } Console.WriteLine( "After pressing return an exception will be thrown and the server will terminate" ); Console.ReadLine(); throw new Exception( String.Format( "Load failed (items={0}, mobiles={1}, guilds={2}, regions={3}, type={4}, serial={5})", failedItems, failedMobiles, failedGuilds, failedRegions, failedType, failedSerial ), failed ); } EventSink.InvokeWorldLoad(); m_Loading = false; for ( int i = 0; i < m_DeleteList.Count; ++i ) { object o = m_DeleteList[i]; if ( o is Item ) ((Item)o).Delete(); else if ( o is Mobile ) ((Mobile)o).Delete(); } m_DeleteList.Clear(); foreach ( Item item in m_Items.Values ) { if ( item.Parent == null ) item.UpdateTotals(); item.ClearProperties(); } ArrayList list = new ArrayList( m_Mobiles.Values ); foreach ( Mobile m in list ) { m.ForceRegionReEnter( true ); m.UpdateTotals(); m.ClearProperties(); } Console.WriteLine( "done ({1} items, {2} mobiles) ({0:F1} seconds)", (DateTime.Now-start).TotalSeconds, m_Items.Count, m_Mobiles.Count ); }
private static void ImportSystem( string filename ) { string folder = Path.Combine( DataPath, "Import/" ); List<Item> items = new List<Item>(); List<ItemEntry> entries = new List<ItemEntry>(); foreach( Item i in World.Items.Values ) if ( i is StargateAddon ) items.Add( i ); foreach( Item i in items ) i.Delete(); items.Clear(); string failedSerial = null; Type failedType = null; int failedTypeID = 0; Exception failed = null; Type[] itemctorTypes = new Type[]{ typeof( Serial ) }; int itemCount = 0; string idxpath = Path.Combine( folder, filename + ".idx" ); string tdbpath = Path.Combine( folder, filename + ".tdb" ); string binpath = Path.Combine( folder, filename + ".bin" ); EnsureDirectory( Directory.GetParent( binpath ).FullName ); if ( File.Exists( idxpath ) && File.Exists( tdbpath ) ) { 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 ); int count = tdbReader.ReadInt32(); ArrayList types = new ArrayList( count ); for ( int i = 0; i < count; ++i ) { string typeName = tdbReader.ReadString(); Type t = ScriptCompiler.FindTypeByFullName( typeName ); if ( t == null ) { Console.WriteLine( "Stargate Import Failure:" ); Console.WriteLine( "Error: Type '{0}' was not found. Delete all of those types? (y/n)", typeName ); if ( Console.ReadLine() == "y" ) { types.Add( null ); Console.Write( "World: Loading..." ); continue; } Console.WriteLine( "Types will not be deleted. Import of the system has been halted." ); return; } ConstructorInfo itemctor = t.GetConstructor( itemctorTypes ); if ( itemctor != null ) types.Add( new object[] {itemctor, typeName } ); else { Console.WriteLine( "Type {0} does not have a serialization constructor. Import of the system has been halted.", t ); return; } } itemCount = idxReader.ReadInt32(); for ( int i = 0; i < itemCount; ++i ) { int typeID = idxReader.ReadInt32(); object[] objs = (object[])types[typeID]; if ( objs == null ) continue; ConstructorInfo ctor = (ConstructorInfo)objs[0]; string typeName = (string)objs[1]; Item item = null; int serial = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); try { item = (Item)ctor.Invoke( new object[]{ (Serial)serial } ); } catch ( Exception exception ) { Console.WriteLine( exception ); } if ( item != null ) { entries.Add( new ItemEntry( item, typeID, typeName, pos, length ) ); World.AddItem( item ); } } tdbReader.Close(); } idxReader.Close(); } } if ( File.Exists( binpath ) ) { using ( FileStream bin = new FileStream( binpath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) { BinaryFileReader reader = new BinaryFileReader( new BinaryReader( bin ) ); for ( int i = 0; i < entries.Count; ++i ) { ItemEntry entry = entries[i]; Item item = entry.Item; if ( item != null ) { reader.Seek( entry.Position, SeekOrigin.Begin ); try { item.Deserialize( reader ); item.Delta( ItemDelta.Update ); if ( reader.Position != ( entry.Position + entry.Length ) ) { Console.WriteLine( String.Format( "Error: Bad Stargate import of {0}. Import of the system has been halted.", item.GetType() ) ); return; } } catch ( Exception e ) { items.RemoveAt( i ); failed = e; //failedItems = true; failedType = item.GetType(); failedTypeID = entry.TypeID; failedSerial = item.Serial.ToString(); break; } } } reader.Close(); } } if ( failed != null ) { Console.WriteLine( "Error: Importing a saved object" ); Console.WriteLine( " - Type: {0}", failedType ); Console.WriteLine( " - Serial: {0}", failedSerial ); Console.WriteLine( String.Format( "Load failed (type={0}, serial={1})", failedType, failedSerial ), failed ); } }
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 static void Load() { string filePath = Path.Combine("LokaiSaves/LokaiSkills", "LokaiSkills.bin"); if (!File.Exists(filePath)) { Console.WriteLine("LokaiSkills.bin did not exist so we are initializing the values."); m_LinguisticsLevel = AccessLevel.Player; m_RidingChecksEnabled = true; m_SailingChecksEnabled = true; m_LinguisticsEnabled = true; m_CommerceEnabled = true; m_ShowLokaiSkillInGump = new bool[] { true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true }; return; } BinaryFileReader reader = null; FileStream fs = null; try { fs = new FileStream(filePath, (FileMode)3, (FileAccess)1, (FileShare)1); reader = new BinaryFileReader(new BinaryReader(fs)); } catch (Exception e) { Console.WriteLine(e.ToString()); return; } if (reader != null) { int check = 0; try { int version = reader.ReadEncodedInt(); check++; m_LinguisticsLevel = (AccessLevel)reader.ReadEncodedInt(); check++; m_CommerceEnabled = reader.ReadBool(); check++; m_RidingChecksEnabled = reader.ReadBool(); check++; m_SailingChecksEnabled = reader.ReadBool(); check++; m_LinguisticsEnabled = reader.ReadBool(); check++; m_ShowLokaiSkillInGump = new bool[] { true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true }; ShowButchering = reader.ReadBool(); check++; ShowSkinning = reader.ReadBool(); check++; ShowAnimalRiding = reader.ReadBool(); check++; ShowSailing = reader.ReadBool(); check++; ShowDetectEvil = reader.ReadBool(); check++; ShowCureDisease = reader.ReadBool(); check++; ShowPickPocket = reader.ReadBool(); check++; ShowPilfering = reader.ReadBool(); check++; ShowFraming = reader.ReadBool(); check++; ShowBrickLaying = reader.ReadBool(); check++; ShowRoofing = reader.ReadBool(); check++; ShowStoneMasonry = reader.ReadBool(); check++; ShowVentriloquism = reader.ReadBool(); check++; ShowHypnotism = reader.ReadBool(); check++; ShowPreyTracking = reader.ReadBool(); check++; ShowSpeakToAnimals = reader.ReadBool(); check++; ShowWoodworking = reader.ReadBool(); check++; ShowCooperage = reader.ReadBool(); check++; ShowSpinning = reader.ReadBool(); check++; ShowWeaving = reader.ReadBool(); check++; ShowConstruction = reader.ReadBool(); check++; ShowCommerce = reader.ReadBool(); check++; ShowBrewing = reader.ReadBool(); check++; ShowHerblore = reader.ReadBool(); check++; ShowTreePicking = reader.ReadBool(); check++; ShowTreeSapping = reader.ReadBool(); check++; ShowTreeCarving = reader.ReadBool(); check++; ShowTreeDigging = reader.ReadBool(); check++; ShowTeaching = reader.ReadBool(); check++; ShowLinguistics = reader.ReadBool(); check++; reader.Close(); } catch { Console.WriteLine("Error reading .bin file at line {0}, so we are initializing the values again.", check); m_LinguisticsLevel = AccessLevel.Player; m_RidingChecksEnabled = true; m_SailingChecksEnabled = true; m_LinguisticsEnabled = true; m_CommerceEnabled = true; m_ShowLokaiSkillInGump = new bool[] { true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true }; Console.WriteLine(".bin File closed."); reader.Close(); } } else { Console.WriteLine("Reader was NULL, so we are initializing the values again."); m_LinguisticsLevel = AccessLevel.Player; m_RidingChecksEnabled = true; m_SailingChecksEnabled = true; m_LinguisticsEnabled = true; m_CommerceEnabled = true; m_ShowLokaiSkillInGump = new bool[] { true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true }; } }
public static void Load() { log.Info("Loading..."); //Console.Write("Donation: Loading..."); ms_ClaimDonationsBlocked = false; 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 orders from an index file int orderCount = idxReader.ReadInt32(); if (orderCount == 0) { log.Warn("Donations save does not contain any entries, [claimdonations deactivated."); //Console.WriteLine("Donations save does not contain any entries, [claimdonations deactivated."); ms_ClaimDonationsBlocked = true; } for (int i = 0; i < orderCount; ++i) { ClaimedOrder c = new ClaimedOrder(); // 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 { c.Deserialize(binReader); if (binReader.Position != (startPos + length)) throw new Exception(String.Format("***** Bad serialize on ClaimedOrder[{0}] *****", i)); } catch (Exception e) { log.Fatal("Error deserializing donations, [claimdonations deactivated.", e); //Console.WriteLine("Error deserializing donations, [claimdonations deactivated: {0}", e.Message); ms_ClaimDonationsBlocked = true; } m_ClaimedOrders.Add(c); } // Remember to close the streams idxReader.Close(); binReader.Close(); } else { log.Error("Error deserializing donations: idx/bin doesn't exist, [claimdonations deactivated."); //Console.WriteLine("Error deserializing donations: idx/bin doesn't exist, [claimdonations deactivated."); ms_ClaimDonationsBlocked = true; } //Console.WriteLine("done"); log.Info("done."); }
public static void Load() { if (m_Loaded) { return; } m_Loaded = true; m_LoadingType = null; Console.Write("World: Loading..."); Stopwatch watch = Stopwatch.StartNew(); m_Loading = true; _addQueue = new Queue <IEntity>(); _deleteQueue = new Queue <IEntity>(); int mobileCount = 0, itemCount = 0, guildCount = 0; object[] ctorArgs = new object[1]; List <ItemEntry> items = new List <ItemEntry>(); List <MobileEntry> mobiles = new List <MobileEntry>(); List <GuildEntry> guilds = new List <GuildEntry>(); 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); List <object[]> types = ReadTypes(tdbReader); mobileCount = idxReader.ReadInt32(); m_Mobiles = new Dictionary <Serial, Mobile>(mobileCount); for (int i = 0; i < mobileCount; ++i) { int typeID = idxReader.ReadInt32(); int serial = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); object[] objs = types[typeID]; if (objs == null) { continue; } Mobile m = null; ConstructorInfo ctor = ( ConstructorInfo )objs[0]; string typeName = ( string )objs[1]; try { ctorArgs[0] = ( Serial )serial; m = ( Mobile )(ctor.Invoke(ctorArgs)); } catch { } if (m != null) { mobiles.Add(new MobileEntry(m, typeID, typeName, pos, length)); AddMobile(m); } } tdbReader.Close(); } idxReader.Close(); } } else { m_Mobiles = new Dictionary <Serial, Mobile>(); } if (File.Exists(ItemIndexPath) && File.Exists(ItemTypesPath)) { using (FileStream idx = new FileStream(ItemIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader idxReader = new BinaryReader(idx); using (FileStream tdb = new FileStream(ItemTypesPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader tdbReader = new BinaryReader(tdb); List <object[]> types = ReadTypes(tdbReader); itemCount = idxReader.ReadInt32(); m_Items = new Dictionary <Serial, Item>(itemCount); for (int i = 0; i < itemCount; ++i) { int typeID = idxReader.ReadInt32(); int serial = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); object[] objs = types[typeID]; if (objs == null) { continue; } Item item = null; ConstructorInfo ctor = ( ConstructorInfo )objs[0]; string typeName = ( string )objs[1]; try { ctorArgs[0] = ( Serial )serial; item = ( Item )(ctor.Invoke(ctorArgs)); } catch { } if (item != null) { items.Add(new ItemEntry(item, typeID, typeName, pos, length)); AddItem(item); } } tdbReader.Close(); } idxReader.Close(); } } else { m_Items = new Dictionary <Serial, Item>(); } if (File.Exists(GuildIndexPath)) { using (FileStream idx = new FileStream(GuildIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader idxReader = new BinaryReader(idx); guildCount = idxReader.ReadInt32(); CreateGuildEventArgs createEventArgs = new CreateGuildEventArgs(-1); for (int i = 0; i < guildCount; ++i) { idxReader.ReadInt32(); //no typeid for guilds int id = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); createEventArgs.Id = id; EventSink.InvokeCreateGuild(createEventArgs); BaseGuild guild = createEventArgs.Guild; if (guild != null) { guilds.Add(new GuildEntry(guild, pos, length)); } } idxReader.Close(); } } bool failedMobiles = false, failedItems = false, failedGuilds = false; Type failedType = null; Serial failedSerial = Serial.Zero; Exception failed = null; int failedTypeID = 0; 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 { m_LoadingType = entry.TypeName; m.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on {0} *****", m.GetType())); } } catch (Exception e) { mobiles.RemoveAt(i); failed = e; failedMobiles = true; failedType = m.GetType(); failedTypeID = entry.TypeID; failedSerial = m.Serial; break; } } } reader.Close(); } } if (!failedMobiles && File.Exists(ItemDataPath)) { using (FileStream bin = new FileStream(ItemDataPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin)); for (int i = 0; i < items.Count; ++i) { ItemEntry entry = items[i]; Item item = entry.Item; if (item != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { m_LoadingType = entry.TypeName; item.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on {0} *****", item.GetType())); } } catch (Exception e) { items.RemoveAt(i); failed = e; failedItems = true; failedType = item.GetType(); failedTypeID = entry.TypeID; failedSerial = item.Serial; break; } } } reader.Close(); } } m_LoadingType = null; if (!failedMobiles && !failedItems && File.Exists(GuildDataPath)) { using (FileStream bin = new FileStream(GuildDataPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin)); for (int i = 0; i < guilds.Count; ++i) { GuildEntry entry = guilds[i]; BaseGuild g = entry.Guild; if (g != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { g.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on Guild {0} *****", g.Id)); } } catch (Exception e) { guilds.RemoveAt(i); failed = e; failedGuilds = true; failedType = typeof(BaseGuild); failedTypeID = g.Id; failedSerial = g.Id; break; } } } reader.Close(); } } if (failedItems || failedMobiles || failedGuilds) { Console.WriteLine("An error was encountered while loading a saved object"); Console.WriteLine(" - Type: {0}", failedType); Console.WriteLine(" - Serial: {0}", failedSerial); if (!Core.Service) { Console.WriteLine("Delete the object? (y/n)"); if (Console.ReadKey(true).Key == ConsoleKey.Y) { if (failedType != typeof(BaseGuild)) { Console.WriteLine("Delete all objects of that type? (y/n)"); if (Console.ReadKey(true).Key == ConsoleKey.Y) { if (failedMobiles) { for (int i = 0; i < mobiles.Count;) { if (mobiles[i].TypeID == failedTypeID) { mobiles.RemoveAt(i); } else { ++i; } } } else if (failedItems) { for (int i = 0; i < items.Count;) { if (items[i].TypeID == failedTypeID) { items.RemoveAt(i); } else { ++i; } } } } } SaveIndex <MobileEntry>(mobiles, MobileIndexPath); SaveIndex <ItemEntry>(items, ItemIndexPath); SaveIndex <GuildEntry>(guilds, GuildIndexPath); } Console.WriteLine("After pressing return an exception will be thrown and the server will terminate."); Console.ReadLine(); } else { Console.WriteLine("An exception will be thrown and the server will terminate."); } throw new Exception(String.Format("Load failed (items={0}, mobiles={1}, guilds={2}, type={3}, serial={4})", failedItems, failedMobiles, failedGuilds, failedType, failedSerial), failed); } EventSink.InvokeWorldLoad(); m_Loading = false; ProcessSafetyQueues(); foreach (Item item in m_Items.Values) { if (item.Parent == null) { item.UpdateTotals(); } item.ClearProperties(); } foreach (Mobile m in m_Mobiles.Values) { m.UpdateRegion(); // Is this really needed? m.UpdateTotals(); m.ClearProperties(); } watch.Stop(); Console.WriteLine("done ({1} items, {2} mobiles) ({0:F2} seconds)", watch.Elapsed.TotalSeconds, m_Items.Count, m_Mobiles.Count); }
public static void Load() { if (Loaded) { return; } Loaded = true; LoadingType = null; Console.Write("World: Loading..."); var watch = Stopwatch.StartNew(); Loading = true; _addQueue = new Queue <IEntity>(); _deleteQueue = new Queue <IEntity>(); int mobileCount, itemCount, guildCount; var ctorArgs = new object[1]; var items = new List <ItemEntry>(); var mobiles = new List <MobileEntry>(); var guilds = new List <GuildEntry>(); if (File.Exists(MobileIndexPath) && File.Exists(MobileTypesPath)) { using var idx = new FileStream(MobileIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read); using var idxReader = new BinaryReader(idx); using var tdb = new FileStream(MobileTypesPath, FileMode.Open, FileAccess.Read, FileShare.Read); using var tdbReader = new BinaryReader(tdb); var types = ReadTypes(tdbReader); mobileCount = idxReader.ReadInt32(); Mobiles = new Dictionary <Serial, Mobile>(mobileCount); for (var i = 0; i < mobileCount; ++i) { var typeID = idxReader.ReadInt32(); var serial = idxReader.ReadUInt32(); var pos = idxReader.ReadInt64(); var length = idxReader.ReadInt32(); var objs = types[typeID]; if (objs == null) { continue; } Mobile m = null; var ctor = objs.Item1; var typeName = objs.Item2; try { ctorArgs[0] = (Serial)serial; m = (Mobile)ctor.Invoke(ctorArgs); } catch { // ignored } if (m != null) { mobiles.Add(new MobileEntry(m, typeID, typeName, pos, length)); AddMobile(m); } } tdbReader.Close(); idxReader.Close(); } else { Mobiles = new Dictionary <Serial, Mobile>(); } if (File.Exists(ItemIndexPath) && File.Exists(ItemTypesPath)) { using var idx = new FileStream(ItemIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read); using var idxReader = new BinaryReader(idx); var tdb = new FileStream(ItemTypesPath, FileMode.Open, FileAccess.Read, FileShare.Read); using var tdbReader = new BinaryReader(tdb); var types = ReadTypes(tdbReader); itemCount = idxReader.ReadInt32(); Items = new Dictionary <Serial, Item>(itemCount); for (var i = 0; i < itemCount; ++i) { var typeID = idxReader.ReadInt32(); var serial = idxReader.ReadUInt32(); var pos = idxReader.ReadInt64(); var length = idxReader.ReadInt32(); var objs = types[typeID]; if (objs == null) { continue; } Item item = null; var ctor = objs.Item1; var typeName = objs.Item2; try { ctorArgs[0] = (Serial)serial; item = (Item)ctor.Invoke(ctorArgs); } catch { // ignored } if (item != null) { items.Add(new ItemEntry(item, typeID, typeName, pos, length)); AddItem(item); } } tdbReader.Close(); idxReader.Close(); } else { Items = new Dictionary <Serial, Item>(); } if (File.Exists(GuildIndexPath)) { using var idx = new FileStream(GuildIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read); var idxReader = new BinaryReader(idx); guildCount = idxReader.ReadInt32(); var createEventArgs = new CreateGuildEventArgs(0xFFFFFFFF); for (var i = 0; i < guildCount; ++i) { idxReader.ReadInt32(); // no typeid for guilds var id = idxReader.ReadUInt32(); var pos = idxReader.ReadInt64(); var length = idxReader.ReadInt32(); createEventArgs.Id = id; EventSink.InvokeCreateGuild(createEventArgs); var guild = createEventArgs.Guild; if (guild != null) { guilds.Add(new GuildEntry(guild, pos, length)); } } idxReader.Close(); } bool failedMobiles = false, failedItems = false, failedGuilds = false; Type failedType = null; var failedSerial = Serial.Zero; Exception failed = null; var failedTypeID = 0; if (File.Exists(MobileDataPath)) { using var bin = new FileStream(MobileDataPath, FileMode.Open, FileAccess.Read, FileShare.Read); var reader = new BinaryFileReader(new BinaryReader(bin)); for (var i = 0; i < mobiles.Count; ++i) { var entry = mobiles[i]; var m = entry.Mobile; if (m != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { LoadingType = entry.TypeName; m.Deserialize(reader); if (reader.Position != entry.Position + entry.Length) { throw new Exception($"***** Bad serialize on {m.GetType()} *****"); } } catch (Exception e) { mobiles.RemoveAt(i); failed = e; failedMobiles = true; failedType = m.GetType(); failedTypeID = entry.TypeID; failedSerial = m.Serial; break; } } } reader.Close(); } if (!failedMobiles && File.Exists(ItemDataPath)) { using var bin = new FileStream(ItemDataPath, FileMode.Open, FileAccess.Read, FileShare.Read); var reader = new BinaryFileReader(new BinaryReader(bin)); for (var i = 0; i < items.Count; ++i) { var entry = items[i]; var item = entry.Item; if (item != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { LoadingType = entry.TypeName; item.Deserialize(reader); if (reader.Position != entry.Position + entry.Length) { throw new Exception($"***** Bad serialize on {item.GetType()} *****"); } } catch (Exception e) { items.RemoveAt(i); failed = e; failedItems = true; failedType = item.GetType(); failedTypeID = entry.TypeID; failedSerial = item.Serial; break; } } } reader.Close(); } LoadingType = null; if (!failedMobiles && !failedItems && File.Exists(GuildDataPath)) { using var bin = new FileStream(GuildDataPath, FileMode.Open, FileAccess.Read, FileShare.Read); var reader = new BinaryFileReader(new BinaryReader(bin)); for (var i = 0; i < guilds.Count; ++i) { var entry = guilds[i]; var g = entry.Guild; if (g != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { g.Deserialize(reader); if (reader.Position != entry.Position + entry.Length) { throw new Exception($"***** Bad serialize on Guild {g.Serial} *****"); } } catch (Exception e) { guilds.RemoveAt(i); failed = e; failedGuilds = true; failedType = typeof(BaseGuild); failedTypeID = g.Serial.ToInt32(); failedSerial = g.Serial; break; } } } reader.Close(); } if (failedItems || failedMobiles || failedGuilds) { Console.WriteLine("An error was encountered while loading a saved object"); Console.WriteLine(" - Type: {0}", failedType); Console.WriteLine(" - Serial: {0}", failedSerial); Console.WriteLine("Delete the object? (y/n)"); if (Console.ReadKey(true).Key == ConsoleKey.Y) { if (failedType != typeof(BaseGuild)) { Console.WriteLine("Delete all objects of that type? (y/n)"); if (Console.ReadKey(true).Key == ConsoleKey.Y) { if (failedMobiles) { for (var i = 0; i < mobiles.Count;) { if (mobiles[i].TypeID == failedTypeID) { mobiles.RemoveAt(i); } else { ++i; } } } else if (failedItems) { for (var i = 0; i < items.Count;) { if (items[i].TypeID == failedTypeID) { items.RemoveAt(i); } else { ++i; } } } } } SaveIndex(mobiles, MobileIndexPath); SaveIndex(items, ItemIndexPath); SaveIndex(guilds, GuildIndexPath); } Console.WriteLine("After pressing return an exception will be thrown and the server will terminate."); Console.ReadLine(); throw new Exception( $"Load failed (items={failedItems}, mobiles={failedMobiles}, guilds={failedGuilds}, type={failedType}, serial={failedSerial})", failed ); } EventSink.InvokeWorldLoad(); Loading = false; ProcessSafetyQueues(); foreach (var item in Items.Values) { if (item.Parent == null) { item.UpdateTotals(); } item.ClearProperties(); } foreach (var m in Mobiles.Values) { m.UpdateRegion(); // Is this really needed? m.UpdateTotals(); m.ClearProperties(); } watch.Stop(); Console.WriteLine( "done ({1} items, {2} mobiles) ({0:F2} seconds)", watch.Elapsed.TotalSeconds, Items.Count, Mobiles.Count ); }
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 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)); } }
private static void LoadEntities() { ItemEntry[] itemEntries = null; MobileEntry[] mobileEntries = null; GuildEntry[] guildEntries = null; RegionEntry[] regionEntries = null; if ( File.Exists( mobIdxPath ) && File.Exists( mobTdbPath ) ) { log.Debug("loading mobile index"); EntityType[] types = LoadTypes(mobTdbPath); mobileEntries = LoadMobileIndex(mobIdxPath, types); } else { m_Mobiles = new Hashtable(); } if ( File.Exists( itemIdxPath ) && File.Exists( itemTdbPath ) ) { log.Debug("loading item index"); EntityType[] types = LoadTypes(itemTdbPath); itemEntries = LoadItemIndex(itemIdxPath, types); } else { m_Items = new Hashtable(); } if ( File.Exists( guildIdxPath ) ) { log.Debug("loading guild index"); using ( FileStream idx = new FileStream( guildIdxPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) { BinaryReader idxReader = new BinaryReader( idx ); int count = idxReader.ReadInt32(); guildEntries = new GuildEntry[count]; CreateGuildEventArgs createEventArgs = new CreateGuildEventArgs( -1 ); for ( int i = 0; i < count; ++i ) { idxReader.ReadInt32();//no typeid for guilds int id = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); createEventArgs.Id = id; BaseGuild guild = EventSink.InvokeCreateGuild( createEventArgs );//new Guild( id ); if ( guild != null ) guildEntries[i] = new GuildEntry( guild, pos, length ); } idxReader.Close(); } } if ( File.Exists( regionIdxPath ) ) { log.Debug("loading region index"); using ( FileStream idx = new FileStream( regionIdxPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) { BinaryReader idxReader = new BinaryReader( idx ); int count = idxReader.ReadInt32(); regionEntries = new RegionEntry[count]; for ( int i = 0; i < count; ++i ) { idxReader.ReadInt32(); /* typeID */ int serial = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); Region r = Region.FindByUId( serial ); if ( r != null ) { regionEntries[i] = new RegionEntry( r, pos, length ); Region.AddRegion( r ); } } idxReader.Close(); } } bool failedMobiles = false, failedItems = false, failedGuilds = false, failedRegions = false; Type failedType = null; Serial failedSerial = Serial.Zero; Exception failed = null; int failedTypeID = 0; if ( File.Exists( mobBinPath ) ) { log.Debug("loading mobiles"); using ( FileStream bin = new FileStream( mobBinPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) { BinaryFileReader reader = new BinaryFileReader( new BinaryReader( bin ) ); for ( int i = 0; i < mobileEntries.Length; ++i ) { MobileEntry entry = mobileEntries[i]; Mobile m = (Mobile)entry.Object; if ( m != null ) { reader.Seek( entry.Position, SeekOrigin.Begin ); try { m_LoadingType = entry.TypeName; m.Deserialize( reader ); if ( reader.Position != (entry.Position + entry.Length) ) throw new Exception( String.Format( "***** Bad serialize on {0} *****", m.GetType() ) ); } catch ( Exception e ) { log.Error("failed to load mobile", e); mobileEntries[i].Clear(); failed = e; failedMobiles = true; failedType = m.GetType(); failedTypeID = entry.TypeID; failedSerial = m.Serial; break; } } } reader.Close(); } if (!failedMobiles) mobileEntries = null; } if ( !failedMobiles && File.Exists( itemBinPath ) ) { log.Debug("loading items"); using ( FileStream bin = new FileStream( itemBinPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) { BinaryFileReader reader = new BinaryFileReader( new BinaryReader( bin ) ); for ( int i = 0; i < itemEntries.Length; ++i ) { ItemEntry entry = itemEntries[i]; Item item = (Item)entry.Object; if ( item != null ) { reader.Seek( entry.Position, SeekOrigin.Begin ); try { m_LoadingType = entry.TypeName; item.Deserialize( reader ); if ( reader.Position != (entry.Position + entry.Length) ) throw new Exception( String.Format( "***** Bad serialize on {0} *****", item.GetType() ) ); } catch ( Exception e ) { log.Fatal("failed to load item", e); itemEntries[i].Clear(); failed = e; failedItems = true; failedType = item.GetType(); failedTypeID = entry.TypeID; failedSerial = item.Serial; break; } } } reader.Close(); } if (!failedItems) itemEntries = null; } if ( !failedMobiles && !failedItems && File.Exists( guildBinPath ) ) { log.Debug("loading guilds"); using ( FileStream bin = new FileStream( guildBinPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) { BinaryFileReader reader = new BinaryFileReader( new BinaryReader( bin ) ); for ( int i = 0; i < guildEntries.Length; ++i ) { GuildEntry entry = guildEntries[i]; BaseGuild g = (BaseGuild)entry.Object; if ( g != null ) { reader.Seek( entry.Position, SeekOrigin.Begin ); try { g.Deserialize( reader ); if ( reader.Position != (entry.Position + entry.Length) ) throw new Exception( String.Format( "***** Bad serialize on Guild {0} *****", g.Id ) ); } catch ( Exception e ) { log.Fatal("failed to load guild", e); guildEntries[i].Clear(); failed = e; failedGuilds = true; failedType = typeof( BaseGuild ); failedTypeID = g.Id; failedSerial = g.Id; break; } } } reader.Close(); } if (!failedGuilds) guildEntries = null; } if ( !failedMobiles && !failedItems && File.Exists( regionBinPath ) ) { log.Debug("loading regions"); using ( FileStream bin = new FileStream( regionBinPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) { BinaryFileReader reader = new BinaryFileReader( new BinaryReader( bin ) ); for ( int i = 0; i < regionEntries.Length; ++i ) { RegionEntry entry = regionEntries[i]; Region r = (Region)entry.Object; if ( r != null ) { reader.Seek( entry.Position, SeekOrigin.Begin ); try { r.Deserialize( reader ); if ( reader.Position != (entry.Position + entry.Length) ) throw new Exception( String.Format( "***** Bad serialize on {0} *****", r.GetType() ) ); } catch ( Exception e ) { log.Fatal("failed to load region", e); regionEntries[i].Clear(); failed = e; failedRegions = true; failedType = r.GetType(); failedTypeID = entry.TypeID; failedSerial = r.UId; break; } } } reader.Close(); } if (!failedRegions) regionEntries = null; } if ( failedItems || failedMobiles || failedGuilds || failedRegions ) { Console.WriteLine( "An error was encountered while loading a saved object" ); Console.WriteLine( " - Type: {0}", failedType ); Console.WriteLine( " - Serial: {0}", failedSerial ); Console.WriteLine( "Delete the object? (y/n)" ); if ( Console.ReadLine() == "y" ) { if ( failedType != typeof( BaseGuild ) && !failedType.IsSubclassOf( typeof( Region ) ) ) { Console.WriteLine( "Delete all objects of that type? (y/n)" ); if ( Console.ReadLine() == "y" ) { if ( failedMobiles ) { for ( int i = 0; i < mobileEntries.Length; ++i) { if (mobileEntries[i].TypeID == failedTypeID) mobileEntries[i].Clear(); } } else if ( failedItems ) { for ( int i = 0; i < itemEntries.Length; ++i) { if (itemEntries[i].TypeID == failedTypeID) itemEntries[i].Clear(); } } } } if (mobileEntries != null) SaveIndex( mobileEntries, mobIdxPath ); if (itemEntries != null) SaveIndex( itemEntries, itemIdxPath ); if (guildEntries != null) SaveIndex( guildEntries, guildIdxPath ); if (regionEntries != null) SaveIndex( regionEntries, regionIdxPath ); } Console.WriteLine( "After pressing return an exception will be thrown and the server will terminate" ); Console.ReadLine(); throw new Exception( String.Format( "Load failed (items={0}, mobiles={1}, guilds={2}, regions={3}, type={4}, serial={5})", failedItems, failedMobiles, failedGuilds, failedRegions, failedType, failedSerial ), failed ); } }
// Loads the MobileAndSpellList file the save method creates. public static void Load() { try { if ( !Directory.Exists( "Saves/BlueMagic/" ) ) Console.WriteLine( "Blue Magic: No save file found." ); else if ( !File.Exists( "Saves/BlueMagic/MobileAndSpellList.bin" ) ) Console.WriteLine( "Blue Magic: No save file found." ); else { Console.WriteLine( " " ); Console.Write( "Blue Magic: Save file found, loading..." ); using ( BinaryReader binReader = new BinaryReader( File.Open("Saves/BlueMagic/MobileAndSpellList.bin", FileMode.Open) ) ) { BinaryFileReader reader = new BinaryFileReader( binReader ); int keycount = reader.ReadInt(); int oldspellcount = reader.ReadInt(); for( int i = 0; i < keycount; i++ ) { Serial serial = reader.ReadInt(); if ( GetMobile( serial ) == null ) continue; bool[] bools = new bool[SPELLCOUNT]; for ( int j = 0; j < oldspellcount; j++ ) { bools[j] = reader.ReadBool(); } try { BlueMageSpells.Add( serial, bools ); } catch { Console.WriteLine( "Adding serial " + serial.ToString() + " to blue spells known has failed" ); } } reader.Close(); } Console.WriteLine( "Done." ); } } catch( Exception ex ) { Console.WriteLine( "BlueMagic Load failed" ); Console.WriteLine( "The exception was: " + ex.Message ); Console.WriteLine( "Continuing normal world load." ); } }
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; } }
private static void CustomLoad() { string binpath = m_FullPath + ".bin"; string idxpath = m_FullPath + ".idx"; if (File.Exists(binpath) && File.Exists(idxpath)) { using (FileStream bin = GetFileStream(binpath)) { BinaryFileReader binreader = new BinaryFileReader(new BinaryReader(bin)); using (FileStream idx = GetFileStream(idxpath)) { BinaryFileReader idxreader = new BinaryFileReader(new BinaryReader(idx)); int loadmethodscount = idxreader.ReadInt(); for (int i = 0; i < loadmethodscount; i++) { string index = idxreader.ReadString(); long binpos = idxreader.ReadLong(); SaveData sd; if (m_DataDictionary.TryGetValue(index, out sd)) { try { binreader.Seek(binpos, SeekOrigin.Begin); sd.LoadMethod(binreader); } catch (Exception error) { HandleError(error, index, new object[] { loadmethodscount, i, idxreader }); } long finpos = idxreader.ReadLong(); if (binreader.Position != finpos) HandleError(null, index, new object[] { loadmethodscount, i, idxreader, binreader.Position > finpos }); } else { idxreader.ReadLong(); Console.WriteLine("A module failed to load, the module that could not be found was indexed under the name \"{0}\". Please Review your Save/Load methods for this module.", index); } } idxreader.Close(); } binreader.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; } }
private static void CustomSeperateLoad(SeperateSaveData data) { string binpath = Path.Combine(data.SaveLocation, data.SaveName + ".bin"); if (File.Exists(binpath)) { using (FileStream bin = GetFileStream(binpath)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin)); try { data.LoadMethod(reader); long endpos = reader.Position; reader.Seek(-8, SeekOrigin.End); if (reader.ReadLong() != endpos) HandleError(null, binpath, null); } catch (Exception error) { HandleError(error, binpath, null); } reader.Close(); } } }
public static void OnLoad() { try { Console.WriteLine("KinSystemSettings Loading..."); string filePath = Path.Combine("Saves/AngelIsland", "KinSystemSettings.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 11: A_MaxShoppers = datreader.ReadInt(); goto case 10; case 10: A_F_Visitor = datreader.ReadInt(); A_Visitor = datreader.ReadInt(); A_F_Sale = datreader.ReadInt(); A_Sale = datreader.ReadInt(); A_GPMaint = datreader.ReadInt(); A_GPHire = datreader.ReadInt(); A_GDeath = datreader.ReadInt(); A_F_Death = datreader.ReadInt(); A_Death = datreader.ReadInt(); A_GCChampLevel = datreader.ReadInt(); A_GCDeath = datreader.ReadInt(); A_MaxVisitors = datreader.ReadInt(); goto case 9; case 9: GuardChangeTimeHours = datreader.ReadInt(); goto case 8; case 8: CityGuardSlots = datreader.ReadInt(); GuardMaintMinutes = datreader.ReadInt(); GuardTypeLowSilverCost = datreader.ReadInt(); GuardTypeMediumSilverCost = datreader.ReadInt(); GuardTypeHighSilverCost = datreader.ReadInt(); GuardTypeLowSilverMaintCost = datreader.ReadInt(); GuardTypeMediumSilverMaintCost = datreader.ReadInt(); GuardTypeHighSilverMaintCost = datreader.ReadInt(); goto case 7; case 7: KinAwards = datreader.ReadBool(); goto case 6; case 6: OutputCaptureData = datreader.ReadBool(); goto case 5; case 5: CityCaptureEnabled = datreader.ReadBool(); VortexCaptureProportion = datreader.ReadDouble(); VortexMinDamagePercentage = datreader.ReadDouble(); BeneficiaryQualifyPercentage = datreader.ReadDouble(); BeneficiaryCap = datreader.ReadInt(); CaptureDefenseRange = datreader.ReadInt(); VortexExpireMinutes = datreader.ReadInt(); BaseCaptureMinutes = datreader.ReadInt(); goto case 4; case 4: KinNameHueEnabled = datreader.ReadBool(); goto case 3; case 3: ShowStatloss = datreader.ReadBool(); ShowKinSingleClick = datreader.ReadBool(); goto case 2; case 2: KinAggressionMinutes = datreader.ReadDouble(); KinBeneficialMinutes = datreader.ReadDouble(); KinHealerModifier = datreader.ReadDouble(); goto case 1; case 1: PointsEnabled = datreader.ReadBool(); StatLossEnabled = datreader.ReadBool(); StatLossPercentageSkills = datreader.ReadDouble(); StatLossPercentageStats = datreader.ReadDouble(); StatLossDurationMinutes = datreader.ReadDouble(); break; } datreader.Close(); } catch (Exception re) { System.Console.WriteLine("ERROR LOADING KinSystemSettings!"); Scripts.Commands.LogHelper.LogException(re); } }
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); } }
private static void event_worldLoad() { if( !File.Exists( PersistenceFile ) ) return; using( FileStream stream = new FileStream( PersistenceFile, FileMode.Open, FileAccess.Read, FileShare.Read ) ) { BinaryFileReader reader = new BinaryFileReader( new BinaryReader( stream ) ); int count = reader.ReadInt(); for( int i = 0; i < count; i++ ) { int serial = reader.ReadInt(); if( serial > -1 ) { Mobile m = World.FindMobile( serial ); GrabOptions options = new GrabOptions( reader ); if( m != null && !m.Deleted ) { if( options != null && !OptionsTable.ContainsKey( m ) ) OptionsTable.Add( m, options ); } } } 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(); _DefaultName = bin.ReadString(); _DefaultURL = bin.ReadString(); _DefaultCoolDown = bin.ReadTimeSpan(); bin.Close(); } //Console.WriteLine("[Vote System]: Done."); }
public bool Rehydrate() { if (!CanFreezeDry) { Console.WriteLine("Warning: Tried to rehydrate dry a non-freezable item: {0}", this); Console.WriteLine(new System.Diagnostics.StackTrace()); return false; } if (!GetFlag(ImplFlag.FreezeDried)) { Console.WriteLine("Warning: Tried to rehydrate a non-freezedried item: {0}", this); Console.WriteLine(new System.Diagnostics.StackTrace()); return false; } if (m_SerializedContentsBin == null || m_SerializedContentsIdx == null) { Console.WriteLine("Warning: Tried to rehydrate an item with no serialized data: {0}", this); Console.WriteLine(new System.Diagnostics.StackTrace()); return false; } if (World.Saving) { Console.WriteLine("Warning: Attempted to rehydrate item {0} during a world save!", this); Console.WriteLine(new System.Diagnostics.StackTrace()); return false; } GenericReader bin = new BinaryFileReader(new BinaryReader(new MemoryStream(m_SerializedContentsBin))); GenericReader idx = new BinaryFileReader(new BinaryReader(new MemoryStream(m_SerializedContentsIdx))); SetFlag(ImplFlag.FreezeDried, false); // set it here, no fatal errors from here on out and AddItem checks it TotalItems = 0; TotalWeight = 0; TotalGold = 0; bool faileditem = false; StringBuilder errlog = new StringBuilder(); int count = idx.ReadInt(); if (count == -1) m_Items = null; else { ArrayList items = new ArrayList(count); m_Items = new ArrayList(count); // set so it won't double unnecessarily 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} when rehydrating container {1}. Ignoring item.", type, this); errlog.AppendFormat("Warning: Tried to load nonexistent type {0} when rehydrating container {1}. Ignoring item.\r\n\r\n", type, this); faileditem = true; continue; } ConstructorInfo ctor = t.GetConstructor(ctortypes); if (ctor == null) { Console.WriteLine("Warning: Tried to load type {0} which has no serialization constructor when rehydrating container {1}. Ignoring item.", type, this); errlog.AppendFormat("Warning: Tried to load type {0} which has no serialization constructor when rehydrating container {1}. Ignoring item.\r\n\r\n", type, this); faileditem = true; continue; } Item item = null; try { if (World.FindItem(serial) != null) { Console.WriteLine("Warning: Serial number being rehydrated already exists in world, patching: {0}", serial); if (World.IsReserved(serial) == true) // free the old one World.FreeSerial(serial); serial = Serial.NewItem; // create a new one Console.WriteLine("Warning: Serial in use, issuing a new one: {0}", serial); World.ReserveSerial(serial); // reserve a new one // throw new Exception(String.Format("Serial number being rehydrated already exists in world: {0}", serial)); } else if (!World.IsReserved(serial)) { Console.WriteLine("Warning: Serial number being rehydrated is not reserved, patching: {0}", serial); Console.WriteLine("Warning: Serial Not being used, reusing: {0}", serial); // reserve it now World.ReserveSerial(serial); // throw new Exception(String.Format("Serial number being rehydrated is not reserved (shouldn't be FD'ed!): {0}", serial)); } ctorargs[0] = serial; item = (Item)(ctor.Invoke(ctorargs)); } catch (Exception e) { Console.WriteLine("An exception occurred while trying to invoke {0}'s serialization constructor.", t.FullName); Console.WriteLine(e.ToString()); errlog.AppendFormat("An exception occurred while trying to invoke {0}'s serialization constructor.\r\n", t.FullName); errlog.Append(e.ToString()); errlog.AppendFormat("\r\n\r\n"); faileditem = true; } if (item != null) { World.FreeSerial(serial); World.AddItem(item); items.Add(new object[] { item, position, length }); } } 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); item.Map = Map; // items will set their parent automatically, and containers will load their contents // however items in the first level will load their parent (this), but this won't add them automatically if (item.Parent == this) { item.Parent = null; AddItem(item); } item.ClearProperties(); if (bin.Position != (position + length)) throw new Exception(String.Format("Bad serialize on {0}", item.GetType().FullName)); } catch (Exception e) { Console.WriteLine("Caught exception while deserializing {0} for container {1}:", item.GetType().FullName, this); Console.WriteLine(e.ToString()); Console.WriteLine("Deleting item."); item.Delete(); errlog.AppendFormat("Caught exception while deserializing {0} for container {1}:\r\n", item.GetType().FullName, this); errlog.Append(e.ToString()); errlog.Append("\r\nDeleting item.\r\n\r\n"); faileditem = true; } } } } idx.Close(); bin.Close(); if (faileditem) { try { string failedpath = "Logs/FailedRehydrate/"; if (!Directory.Exists(failedpath)) Directory.CreateDirectory(failedpath); using (FileStream fs = new FileStream(Path.Combine(failedpath, String.Format("{0} {1}.idx", Serial, DateTime.Now.ToString("MM-dd-yyyy HH-mm-ss"))), FileMode.Create, FileAccess.Write)) { fs.Write(m_SerializedContentsIdx, 0, m_SerializedContentsIdx.Length); fs.Close(); } using (FileStream fs = new FileStream(Path.Combine(failedpath, String.Format("{0} {1}.bin", Serial, DateTime.Now.ToString("MM-dd-yyyy HH-mm-ss"))), FileMode.Create, FileAccess.Write)) { fs.Write(m_SerializedContentsBin, 0, m_SerializedContentsBin.Length); fs.Close(); } using (StreamWriter sw = new StreamWriter(Path.Combine(failedpath, String.Format("{0} {1}.log", Serial, DateTime.Now.ToString("MM-dd-yyyy HH-mm-ss"))))) { sw.WriteLine("Error log for container {0}", this); if (this.Parent is Mobile) sw.WriteLine("Parent is Mobile: {0}", Parent); else sw.WriteLine("Location: {0}", Location); sw.WriteLine(); sw.Write(errlog.ToString()); sw.Close(); } } catch (Exception e) { Console.WriteLine("Failed to dump data for failed rehydration."); Console.WriteLine("Exception: {0}", e.Message); } } m_SerializedContentsIdx = null; m_SerializedContentsBin = null; if (RootParent is Mobile) ((Mobile)RootParent).UpdateTotals(); else if (RootParent is Item) ((Item)RootParent).UpdateTotals(); else UpdateTotals(); OnRehydrate(); if (Debug) Console.WriteLine("Rehydrated {0}", this); return true; }
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 Hashtable(); 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( (bool)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 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 void Deserialize(FileInfo file, Action<GenericReader> deserializer, bool ensure) { file.Refresh(); if (file.Directory != null && !file.Directory.Exists) { if (!ensure) { throw new DirectoryNotFoundException(); } file.Directory.Create(); } if (!file.Exists) { if (!ensure) { throw new FileNotFoundException { Source = file.FullName }; } file.Create().Close(); } file.Refresh(); using (var fs = file.OpenRead()) { var reader = new BinaryFileReader(new BinaryReader(fs)); try { deserializer(reader); } catch (EndOfStreamException eos) { if (file.Length > 0) { Console.WriteLine("[Persistence]: {0}", eos); } } catch (Exception e) { Console.WriteLine("[Persistence]: {0}", e); } finally { reader.Close(); } } }