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); } }
public static void Load() { string filePath = Path.Combine("Saves/Attachments", "Attachments.bin"); // the attachment serializations string imaPath = Path.Combine("Saves/Attachments", "Attachments.ima"); // the item/mob attachment tables string fpiPath = Path.Combine("Saves/Attachments", "Attachments.fpi"); // the file position indices if (!File.Exists(filePath)) { return; } FileStream fs = null; BinaryFileReader reader = null; FileStream imafs = null; BinaryFileReader imareader = null; FileStream fpifs = null; BinaryFileReader fpireader = null; try { fs = new FileStream(filePath, (FileMode)3, (FileAccess)1, (FileShare)1); reader = new BinaryFileReader(new BinaryReader(fs)); imafs = new FileStream(imaPath, (FileMode)3, (FileAccess)1, (FileShare)1); imareader = new BinaryFileReader(new BinaryReader(imafs)); fpifs = new FileStream(fpiPath, (FileMode)3, (FileAccess)1, (FileShare)1); fpireader = new BinaryFileReader(new BinaryReader(fpifs)); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } if (reader != null && imareader != null && fpireader != null) { // restore the current global attachment serial state try { ASerial.GlobalDeserialize(reader); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } ASerial.serialInitialized = true; // read in the serial attachment hash table information int count = 0; try { count = reader.ReadInt(); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } for (int i = 0; i < count; i++) { // read the serial ASerial serialno = null; try { serialno = new ASerial(reader.ReadInt()); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } // read the attachment type string valuetype = null; try { valuetype = reader.ReadString(); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } // read the position of the beginning of the next attachment deser within the .bin file long position = 0; try { position = fpireader.ReadLong(); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } bool skip = false; XmlAttachment o = null; try { o = (XmlAttachment)Activator.CreateInstance(Type.GetType(valuetype), new object[] { serialno }); } catch { skip = true; } if (skip) { if (!AlreadyReported(valuetype)) { Console.WriteLine("\nError deserializing attachments {0}.\nMissing a serial constructor?\n", valuetype); ReportDeserError(valuetype, "Missing a serial constructor?"); } // position the .ima file at the next deser point try { reader.Seek(position, SeekOrigin.Begin); } catch { ErrorReporter.GenerateErrorReport("Error deserializing. Attachments save file corrupted. Attachment load aborted."); return; } continue; } try { o.Deserialize(reader); } catch { skip = true; } // confirm the read position if (reader.Position != position || skip) { if (!AlreadyReported(valuetype)) { Console.WriteLine("\nError deserializing attachments {0}\n", valuetype); ReportDeserError(valuetype, "save file corruption or incorrect Serialize/Deserialize methods?"); } // position the .ima file at the next deser point try { reader.Seek(position, SeekOrigin.Begin); } catch { ErrorReporter.GenerateErrorReport("Error deserializing. Attachments save file corrupted. Attachment load aborted."); return; } continue; } // add it to the hash table try { AllAttachments.Add(serialno.Value, o); } catch { ErrorReporter.GenerateErrorReport(String.Format("\nError deserializing {0} serialno {1}. Attachments save file corrupted. Attachment load aborted.\n", valuetype, serialno.Value)); return; } } // read in the mobile attachment hash table information try { count = imareader.ReadInt(); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } for (int i = 0; i < count; i++) { Mobile key = null; try { key = imareader.ReadMobile(); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } int nattach = 0; try { nattach = imareader.ReadInt(); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } for (int j = 0; j < nattach; j++) { // and serial ASerial serialno = null; try { serialno = new ASerial(imareader.ReadInt()); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } // read the attachment type string valuetype = null; try { valuetype = imareader.ReadString(); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } // read the position of the beginning of the next attachment deser within the .bin file long position = 0; try { position = fpireader.ReadLong(); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } XmlAttachment o = FindAttachmentBySerial(serialno.Value); if (o == null || imareader.Position != position) { if (!AlreadyReported(valuetype)) { Console.WriteLine("\nError deserializing attachments of type {0}.\n", valuetype); ReportDeserError(valuetype, "save file corruption or incorrect Serialize/Deserialize methods?"); } // position the .ima file at the next deser point try { imareader.Seek(position, SeekOrigin.Begin); } catch { ErrorReporter.GenerateErrorReport("Error deserializing. Attachments save file corrupted. Attachment load aborted."); return; } continue; } // attachment successfully deserialized so attach it AttachTo(key, o, false); } } // read in the item attachment hash table information try { count = imareader.ReadInt(); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } for (int i = 0; i < count; i++) { Item key = null; try { key = imareader.ReadItem(); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } int nattach = 0; try { nattach = imareader.ReadInt(); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } for (int j = 0; j < nattach; j++) { // and serial ASerial serialno = null; try { serialno = new ASerial(imareader.ReadInt()); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } // read the attachment type string valuetype = null; try { valuetype = imareader.ReadString(); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } // read the position of the beginning of the next attachment deser within the .bin file long position = 0; try { position = fpireader.ReadLong(); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } XmlAttachment o = FindAttachmentBySerial(serialno.Value); if (o == null || imareader.Position != position) { if (!AlreadyReported(valuetype)) { Console.WriteLine("\nError deserializing attachments of type {0}.\n", valuetype); ReportDeserError(valuetype, "save file corruption or incorrect Serialize/Deserialize methods?"); } // position the .ima file at the next deser point try { imareader.Seek(position, SeekOrigin.Begin); } catch { ErrorReporter.GenerateErrorReport("Error deserializing. Attachments save file corrupted. Attachment load aborted."); return; } continue; } // attachment successfully deserialized so attach it AttachTo(key, o, false); } } if (fs != null) fs.Close(); if (imafs != null) imafs.Close(); if (fpifs != null) fpifs.Close(); if (desererror != null) { ErrorReporter.GenerateErrorReport("Error deserializing particular attachments."); } } }
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 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 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; }