Esempio n. 1
0
        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();
                }
            }
        }
Esempio n. 2
0
        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();
                }
            }
        }
Esempio n. 3
0
        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();
            }
        }
    }
Esempio n. 4
0
 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();
			}

		}
Esempio n. 6
0
        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();
                }
            }
        }
Esempio n. 7
0
        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();
                }
            }
        }
Esempio n. 8
0
		public ChatMessage( BinaryFileReader reader )
		{
			int version = reader.ReadInt();

			switch( version )
			{
				case 1:
				case 0:
					{
						_client = reader.ReadMobile();
						_message = reader.ReadString();
						_recipient = reader.ReadMobile();
						_timestamp = reader.ReadDateTime();

						break;
					}
			}
		}
Esempio n. 9
0
        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);
            }
        }
Esempio n. 10
0
        public GrabOptions(BinaryFileReader reader)
        {
            int version = reader.ReadInt();

            switch (version)
            {
            case 0:
            {
                int tblCount = reader.ReadInt();
                ContainerTable = new Dictionary <GrabFlag, Container>(tblCount);

                for (int i = 0; i < tblCount; i++)
                {
                    ContainerTable.Add((GrabFlag)reader.ReadInt(), (Container)reader.ReadItem());
                }

                Flags  = (GrabFlag)reader.ReadInt();
                Mobile = reader.ReadMobile();

                break;
            }
            }
        }
Esempio n. 11
0
        public LootOptions(BinaryFileReader reader)
        {
            int version = reader.ReadInt();

            switch (version)
            {
                case 0:
                    {
                        int tblCount = reader.ReadInt();
                        ContainerTable = new Dictionary<LootFlag, Container>(tblCount);

                        for (int i = 0; i < tblCount; i++)
                        {
                            ContainerTable.Add((LootFlag)reader.ReadInt(), (Container)reader.ReadItem());
                        }

                        Flags = (LootFlag)reader.ReadInt();
                        Mobile = reader.ReadMobile();

                        break;
                    }
            }
        }
Esempio n. 12
0
        private static void LoadItems(BinaryFileReader reader,
                                      ItemEntry[] entries)
        {
            for (int i = 0; i < entries.Length; ++i)
            {
                ItemEntry entry = entries[i];
                Item      item  = (Item)entry.Object;
                if (item == null)
                {
                    continue;
                }

                reader.Seek(entry.Position, SeekOrigin.Begin);

                try {
                    m_LoadingType = entry.TypeName;
                    item.Deserialize(reader);
                } catch (Exception e) {
                    log.Error(String.Format("failed to load item {0}", item),
                              e);
                    item.Delete();
                    entries[i].Clear();
                    ++m_LoadErrors;
                    continue;
                }

                if (reader.Position != entry.Position + entry.Length)
                {
                    log.ErrorFormat("Bad deserialize on item {0}, type {1}: position={2}, should be {3}",
                                    entry.Serial, entry.TypeName,
                                    reader.Position, entry.Position + entry.Length);
                    item.Delete();
                    entries[i].Clear();
                    ++m_LoadErrors;
                }
            }
        }
Esempio n. 13
0
        private static void LoadGuilds(BinaryFileReader reader,
                                       GuildEntry[] entries)
        {
            for (int i = 0; i < entries.Length; ++i)
            {
                GuildEntry entry = entries[i];
                BaseGuild  guild = (BaseGuild)entry.Object;
                if (guild == null)
                {
                    continue;
                }

                reader.Seek(entry.Position, SeekOrigin.Begin);

                try {
                    guild.Deserialize(reader);
                } catch (Exception e) {
                    log.Error(String.Format("failed to load guild", guild),
                              e);
                    BaseGuild.List.Remove(guild.Id);
                    entries[i].Clear();
                    ++m_LoadErrors;
                    continue;
                }

                if (reader.Position != entry.Position + entry.Length)
                {
                    log.ErrorFormat("Bad deserialize on guild {0}, type {1}: position={2}, should be {3}",
                                    guild.Id, guild.GetType(),
                                    reader.Position, entry.Position + entry.Length);
                    BaseGuild.List.Remove(guild.Id);
                    entries[i].Clear();
                    ++m_LoadErrors;
                }
            }
        }
        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 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 };
            }
        }
Esempio n. 16
0
		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.");
		}
Esempio n. 17
0
        public static void Load()
        {
            BinaryReader    reader1;
            BinaryReader    reader2;
            int             num5;
            ArrayList       list5;
            int             num6;
            string          text1;
            Type            type1;
            ConstructorInfo info1;
            int             num7;
            int             num8;
            int             num9;
            long            num10;
            int             num11;

            object[]        objArray2;
            Mobile          mobile1;
            ConstructorInfo info2;
            string          text2;
            BinaryReader    reader3;
            BinaryReader    reader4;
            int             num12;
            ArrayList       list6;
            int             num13;
            string          text3;
            Type            type2;
            ConstructorInfo info3;
            int             num14;
            int             num15;
            int             num16;
            long            num17;
            int             num18;

            object[]             objArray3;
            Item                 item1;
            ConstructorInfo      info4;
            string               text4;
            BinaryReader         reader5;
            CreateGuildEventArgs args1;
            int              num19;
            int              num20;
            long             num21;
            int              num22;
            BaseGuild        guild1;
            BinaryReader     reader6;
            int              num23;
            int              num24;
            long             num25;
            int              num26;
            Region           region1;
            BinaryFileReader reader7;
            int              num28;
            MobileEntry      entry1;
            Mobile           mobile2;
            BinaryFileReader reader8;
            int              num29;
            ItemEntry        entry2;
            Item             item2;
            BinaryFileReader reader9;
            int              num30;
            GuildEntry       entry3;
            BaseGuild        guild2;
            BinaryFileReader reader10;
            int              num31;
            RegionEntry      entry4;
            Region           region2;
            int              num32;
            int              num33;
            int              num34;
            object           obj1;

            object[] objArray4;
            if (World.m_Loaded)
            {
                return;
            }
            World.m_Loaded      = true;
            World.m_LoadingType = null;
            Console.Write("World: Loading...");
            DateTime time1 = DateTime.Now;

            World.m_Loading    = true;
            World.m_DeleteList = new ArrayList();
            int num1 = 0;
            int num2 = 0;
            int num3 = 0;
            int num4 = 0;

            object[] objArray1  = new object[1];
            Type[]   typeArray2 = new Type[1];
            typeArray2[0] = typeof(Serial);
            Type[]    typeArray1 = typeArray2;
            ArrayList list1      = new ArrayList();
            ArrayList list2      = new ArrayList();
            ArrayList list3      = new ArrayList();
            ArrayList list4      = new ArrayList();

            if (File.Exists(World.mobIdxPath) && File.Exists(World.mobTdbPath))
            {
                using (FileStream stream1 = new FileStream(World.mobIdxPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    reader1 = new BinaryReader(stream1);
                    using (FileStream stream2 = new FileStream(World.mobTdbPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        reader2 = new BinaryReader(stream2);
                        num5    = reader2.ReadInt32();
                        list5   = new ArrayList(num5);
                        num6    = 0;
                        while ((num6 < num5))
                        {
                            text1 = reader2.ReadString();
                            type1 = ScriptCompiler.FindTypeByFullName(text1);
                            if (type1 == null)
                            {
                                Console.WriteLine("failed");
                                Console.WriteLine("Error: Type \'{0}\' was not found. Delete all of those types? (y/n)", text1);
                                if (Console.ReadLine() == "y")
                                {
                                    list5.Add(null);
                                    Console.Write("World: Loading...");
                                    goto Label_018C;
                                }
                                Console.WriteLine("Types will not be deleted. An exception will be thrown when you press return");
                                throw new Exception(string.Format("Bad type \'{0}\'", text1));
                            }
                            info1 = type1.GetConstructor(typeArray1);
                            if (info1 != null)
                            {
                                objArray4    = new object[2];
                                objArray4[0] = info1;
                                list5.Add(objArray4);
                            }
                            else
                            {
                                throw new Exception(string.Format("Type \'{0}\' does not have a serialization constructor", type1));
                            }
Label_018C:
                            ++num6;
                        }
                        num1            = reader1.ReadInt32();
                        World.m_Mobiles = new Hashtable(num1);
                        for (num7 = 0; (num7 < num1); ++num7)
                        {
                            num8      = reader1.ReadInt32();
                            num9      = reader1.ReadInt32();
                            num10     = reader1.ReadInt64();
                            num11     = reader1.ReadInt32();
                            objArray2 = ((object[])list5[num8]);
                            if (objArray2 != null)
                            {
                                mobile1 = null;
                                info2   = ((ConstructorInfo)objArray2[0]);
                                text2   = ((string)objArray2[1]);
                                try
                                {
                                    objArray1[0] = Serial.op_Implicit(num9);
                                    mobile1      = ((Mobile)info2.Invoke(objArray1));
                                }
                                catch
                                {
                                }
                                if (mobile1 != null)
                                {
                                    list2.Add(new MobileEntry(mobile1, num8, text2, num10, num11));
                                    World.AddMobile(mobile1);
                                }
                            }
                        }
                        goto Label_0282;
                    }
                    goto Label_0282;
                }
            }
            World.m_Mobiles = new Hashtable();
Label_0282:
            if (File.Exists(World.itemIdxPath) && File.Exists(World.itemTdbPath))
            {
                using (FileStream stream3 = new FileStream(World.itemIdxPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    reader3 = new BinaryReader(stream3);
                    using (FileStream stream4 = new FileStream(World.itemTdbPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        reader4 = new BinaryReader(stream4);
                        num12   = reader4.ReadInt32();
                        list6   = new ArrayList(num12);
                        num13   = 0;
                        while ((num13 < num12))
                        {
                            text3 = reader4.ReadString();
                            type2 = ScriptCompiler.FindTypeByFullName(text3);
                            if (type2 == null)
                            {
                                Console.WriteLine("failed");
                                Console.WriteLine("Error: Type \'{0}\' was not found. Delete all of those types? (y/n)", text3);
                                if (Console.ReadLine() == "y")
                                {
                                    list6.Add(null);
                                    Console.Write("World: Loading...");
                                    goto Label_0399;
                                }
                                Console.WriteLine("Types will not be deleted. An exception will be thrown when you press return");
                                throw new Exception(string.Format("Bad type \'{0}\'", text3));
                            }
                            info3 = type2.GetConstructor(typeArray1);
                            if (info3 != null)
                            {
                                objArray4    = new object[2];
                                objArray4[0] = info3;
                                objArray4[1] = text3;
                                list6.Add(objArray4);
                            }
                            else
                            {
                                throw new Exception(string.Format("Type \'{0}\' does not have a serialization constructor", type2));
                            }
Label_0399:
                            ++num13;
                        }
                        num2          = reader3.ReadInt32();
                        World.m_Items = new Hashtable(num2);
                        for (num14 = 0; (num14 < num2); ++num14)
                        {
                            num15     = reader3.ReadInt32();
                            num16     = reader3.ReadInt32();
                            num17     = reader3.ReadInt64();
                            num18     = reader3.ReadInt32();
                            objArray3 = ((object[])list6[num15]);
                            if (objArray3 != null)
                            {
                                item1 = null;
                                info4 = ((ConstructorInfo)objArray3[0]);
                                text4 = ((string)objArray3[1]);
                                try
                                {
                                    objArray1[0] = Serial.op_Implicit(num16);
                                    item1        = ((Item)info4.Invoke(objArray1));
                                }
                                catch
                                {
                                }
                                if (item1 != null)
                                {
                                    list1.Add(new ItemEntry(item1, num15, text4, num17, num18));
                                    World.AddItem(item1);
                                }
                            }
                        }
                        goto Label_048F;
                    }
                    goto Label_048F;
                }
            }
            World.m_Items = new Hashtable();
Label_048F:
            if (File.Exists(World.guildIdxPath))
            {
                using (FileStream stream5 = new FileStream(World.guildIdxPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    reader5 = new BinaryReader(stream5);
                    num3    = reader5.ReadInt32();
                    args1   = new CreateGuildEventArgs(-1);
                    for (num19 = 0; (num19 < num3); ++num19)
                    {
                        reader5.ReadInt32();
                        num20    = reader5.ReadInt32();
                        num21    = reader5.ReadInt64();
                        num22    = reader5.ReadInt32();
                        args1.Id = num20;
                        guild1   = EventSink.InvokeCreateGuild(args1);
                        if (guild1 != null)
                        {
                            list3.Add(new GuildEntry(guild1, num21, num22));
                        }
                    }
                }
            }
            if (File.Exists(World.regionIdxPath))
            {
                using (FileStream stream6 = new FileStream(World.regionIdxPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    reader6 = new BinaryReader(stream6);
                    num4    = reader6.ReadInt32();
                    for (num23 = 0; (num23 < num4); ++num23)
                    {
                        reader6.ReadInt32();
                        num24   = reader6.ReadInt32();
                        num25   = reader6.ReadInt64();
                        num26   = reader6.ReadInt32();
                        region1 = Region.FindByUId(num24);
                        if (region1 != null)
                        {
                            list4.Add(new RegionEntry(region1, num25, num26));
                            Region.AddRegion(region1);
                            ++num4;
                        }
                    }
                }
            }
            bool      flag1      = false;
            bool      flag2      = false;
            bool      flag3      = false;
            bool      flag4      = false;
            Type      type3      = null;
            Serial    serial1    = Serial.Zero;
            Exception exception1 = null;
            int       num27      = 0;

            if (File.Exists(World.mobBinPath))
            {
                using (FileStream stream7 = new FileStream(World.mobBinPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    reader7 = new BinaryFileReader(new BinaryReader(stream7));
                    for (num28 = 0; (num28 < list2.Count); ++num28)
                    {
                        entry1  = ((MobileEntry)list2[num28]);
                        mobile2 = ((Mobile)entry1.Object);
                        if (mobile2 != null)
                        {
                            reader7.Seek(entry1.Position, SeekOrigin.Begin);
                            try
                            {
                                World.m_LoadingType = entry1.TypeName;
                                mobile2.Deserialize(reader7);
                                if (reader7.Position != (entry1.Position + entry1.Length))
                                {
                                    throw new Exception(string.Format("***** Bad serialize on {0} *****", mobile2.GetType()));
                                }
                            }
                            catch (Exception exception2)
                            {
                                list2.RemoveAt(num28);
                                exception1 = exception2;
                                flag1      = true;
                                type3      = mobile2.GetType();
                                num27      = entry1.TypeID;
                                serial1    = mobile2.Serial;
                                goto Label_06F2;
                            }
                        }
                    }
                }
            }
Label_06F2:
            if (!flag1 && File.Exists(World.itemBinPath))
            {
                using (FileStream stream8 = new FileStream(World.itemBinPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    reader8 = new BinaryFileReader(new BinaryReader(stream8));
                    for (num29 = 0; (num29 < list1.Count); ++num29)
                    {
                        entry2 = ((ItemEntry)list1[num29]);
                        item2  = ((Item)entry2.Object);
                        if (item2 != null)
                        {
                            reader8.Seek(entry2.Position, SeekOrigin.Begin);
                            try
                            {
                                World.m_LoadingType = entry2.TypeName;
                                item2.Deserialize(reader8);
                                if (reader8.Position != (entry2.Position + entry2.Length))
                                {
                                    throw new Exception(string.Format("***** Bad serialize on {0} *****", item2.GetType()));
                                }
                            }
                            catch (Exception exception3)
                            {
                                list1.RemoveAt(num29);
                                exception1 = exception3;
                                flag2      = true;
                                type3      = item2.GetType();
                                num27      = entry2.TypeID;
                                serial1    = item2.Serial;
                                goto Label_07FA;
                            }
                        }
                    }
                }
            }
Label_07FA:
            World.m_LoadingType = null;
            if ((!flag1 && !flag2) && File.Exists(World.guildBinPath))
            {
                using (FileStream stream9 = new FileStream(World.guildBinPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    reader9 = new BinaryFileReader(new BinaryReader(stream9));
                    for (num30 = 0; (num30 < list3.Count); ++num30)
                    {
                        entry3 = ((GuildEntry)list3[num30]);
                        guild2 = ((BaseGuild)entry3.Object);
                        if (guild2 != null)
                        {
                            reader9.Seek(entry3.Position, SeekOrigin.Begin);
                            try
                            {
                                guild2.Deserialize(reader9);
                                if (reader9.Position != (entry3.Position + entry3.Length))
                                {
                                    throw new Exception(string.Format("***** Bad serialize on Guild {0} *****", guild2.Id));
                                }
                            }
                            catch (Exception exception4)
                            {
                                list3.RemoveAt(num30);
                                exception1 = exception4;
                                flag3      = true;
                                type3      = typeof(BaseGuild);
                                num27      = guild2.Id;
                                serial1    = Serial.op_Implicit(guild2.Id);
                                goto Label_0910;
                            }
                        }
                    }
                }
            }
Label_0910:
            if ((!flag1 && !flag2) && File.Exists(World.regionBinPath))
            {
                using (FileStream stream10 = new FileStream(World.regionBinPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    reader10 = new BinaryFileReader(new BinaryReader(stream10));
                    for (num31 = 0; (num31 < list4.Count); ++num31)
                    {
                        entry4  = ((RegionEntry)list4[num31]);
                        region2 = ((Region)entry4.Object);
                        if (region2 != null)
                        {
                            reader10.Seek(entry4.Position, SeekOrigin.Begin);
                            try
                            {
                                region2.Deserialize(reader10);
                                if (reader10.Position != (entry4.Position + entry4.Length))
                                {
                                    throw new Exception(string.Format("***** Bad serialize on {0} *****", region2.GetType()));
                                }
                            }
                            catch (Exception exception5)
                            {
                                list4.RemoveAt(num31);
                                exception1 = exception5;
                                flag4      = true;
                                type3      = region2.GetType();
                                num27      = entry4.TypeID;
                                serial1    = Serial.op_Implicit(region2.UId);
                                goto Label_0A1B;
                            }
                        }
                    }
                }
            }
Label_0A1B:
            if ((flag2 || flag1) || (flag3 || flag4))
            {
                Console.WriteLine("An error was encountered while loading a saved object");
                Console.WriteLine(" - Type: {0}", type3);
                Console.WriteLine(" - Serial: {0}", serial1);
                Console.WriteLine("Delete the object? (y/n)");
                if (Console.ReadLine() == "y")
                {
                    if ((type3 != typeof(BaseGuild)) && !type3.IsSubclassOf(typeof(Region)))
                    {
                        Console.WriteLine("Delete all objects of that type? (y/n)");
                        if (Console.ReadLine() == "y")
                        {
                            if (flag1)
                            {
                                for (num32 = 0; (num32 < list2.Count); ++num32)
                                {
                                    if (((MobileEntry)list2[num32]).TypeID == num27)
                                    {
                                        list2.RemoveAt(num32);
                                        continue;
                                    }
                                }
                            }
                            else if (flag2)
                            {
                                for (num33 = 0; (num33 < list1.Count); ++num33)
                                {
                                    if (((ItemEntry)list1[num33]).TypeID == num27)
                                    {
                                        list1.RemoveAt(num33);
                                        continue;
                                    }
                                }
                            }
                        }
                    }
                    World.SaveIndex(list2, World.mobIdxPath);
                    World.SaveIndex(list1, World.itemIdxPath);
                    World.SaveIndex(list3, World.guildIdxPath);
                    World.SaveIndex(list4, World.regionIdxPath);
                }
                Console.WriteLine("After pressing return an exception will be thrown and the server will terminate");
                Console.ReadLine();
                objArray4    = new object[6];
                objArray4[0] = flag2;
                objArray4[1] = flag1;
                objArray4[2] = flag3;
                objArray4[3] = flag4;
                objArray4[4] = type3;
                objArray4[5] = serial1;
                throw new Exception(string.Format("Load failed (items={0}, mobiles={1}, guilds={2}, regions={3}, type={4}, serial={5})", objArray4), exception1);
            }
            EventSink.InvokeWorldLoad();
            World.m_Loading = false;
            for (num34 = 0; (num34 < World.m_DeleteList.Count); ++num34)
            {
                obj1 = World.m_DeleteList[num34];
                if ((obj1 is Item))
                {
                    ((Item)obj1).Delete();
                }
                else if ((obj1 is Mobile))
                {
                    ((Mobile)obj1).Delete();
                }
            }
            foreach (Item item3 in World.m_Items.Values)
            {
                if (item3.Parent == null)
                {
                    item3.UpdateTotals();
                }
            }
            ArrayList list7 = new ArrayList(World.m_Mobiles.Values);

            foreach (Mobile mobile3 in list7)
            {
                mobile3.ForceRegionReEnter(true);
                mobile3.UpdateTotals();
            }
            TimeSpan span1 = ((TimeSpan)(DateTime.Now - time1));

            Console.WriteLine("done ({1} items, {2} mobiles) ({0:F1} seconds)", span1.TotalSeconds, World.m_Items.Count, World.m_Mobiles.Count);
        }
Esempio n. 18
0
		public ChatInfo( BinaryFileReader reader )
		{
			int version = reader.ReadInt();

			switch( version )
			{
				case 0:
					{
						_buddyList = reader.ReadStrongMobileList<Mobile>();
						_client = reader.ReadMobile();
						_ignoreList = reader.ReadStrongMobileList<Mobile>();
						_visible = reader.ReadBool();
						break;
					}
			}
		}
Esempio n. 19
0
        private static void Event_WorldLoad()
        {
            if (!File.Exists(SaveFile) || useXML)
                return;

            try
            {

                using (FileStream stream = new FileStream(SaveFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    BinaryFileReader reader = new BinaryFileReader(new BinaryReader(stream));

                    Deserialize(reader);
                }
            }

            catch { Console.WriteLine("Error: Event_WorldLoad Failed in Alliance Definition."); }
        }
Esempio n. 20
0
        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);
            }
        }
Esempio n. 21
0
        private static void Load()
        {
            try
            {
                string SavePath = Path.Combine( m_SavePath, "forumdata.sig" );

                using( FileStream fs = new FileStream( SavePath, FileMode.Open, FileAccess.Read, FileShare.Read ) )
                {
                    BinaryReader br = new BinaryReader( fs );
                    BinaryFileReader reader = new BinaryFileReader( br );

                    int version = reader.ReadInt();
                    switch( version )
                    {
                        case 0:
                        {
                            m_PlayerStatistics = ReadPlayerStatistics( reader );
                            int count = reader.ReadInt();
                            for( int i = 0; i < count; i++ )
                            {
                                ThreadEntry te = new ThreadEntry();
                                te.Deserialize( reader );
                                m_Threads.Add( te );
                            }
                            m_Moderators = reader.ReadMobileList();
                            m_ThreadDeleteAccessLevel = (AccessLevel)reader.ReadInt();
                            m_ThreadLockAccesLevel = ( AccessLevel )reader.ReadInt();
                            m_AutoCleanup = reader.ReadBool();
                            m_AutoCleanupDays = reader.ReadInt();
                            m_MinPostCharactersCount = reader.ReadInt();
                            m_MaxPostCharactersCount = reader.ReadInt();
                            break;
                        }
                    }                    
                }

                m_Threads.Sort( new DateSort() );
                Console.WriteLine( "done" );
                Console.WriteLine( "---------" );
            }
            catch(Exception err)
            {
                Console.WriteLine( "An error occured while loading the forums...{0}", err.ToString() );
                Console.WriteLine( "---------" );
            }
        }        
Esempio n. 22
0
		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 );
			}
		}
Esempio n. 23
0
        private static void OnLoad()
        {
            try{

            if ( !File.Exists( Path.Combine( "Saves/Commands/", "Commands.bin" ) ) )
                return;

            using ( FileStream bin = new FileStream( Path.Combine( "Saves/Commands/", "Commands.bin" ), FileMode.Open, FileAccess.Read, FileShare.Read ) )
            {
                GenericReader reader = new BinaryFileReader( new BinaryReader( bin ) );

                int version = reader.ReadInt();

                int count = reader.ReadInt();

                object[] obj;
                for( int i = 0; i < count; ++i )
                {
                    obj = new object[3];
                    obj[0] = reader.ReadString();
                    obj[1] = reader.ReadString();
                    obj[2] = reader.ReadInt();
                    s_InitInfo.Add( obj );
                }
            }
            }catch{ Errors.Report( "Commands-> OnLoad" ); }
        }
Esempio n. 24
0
        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 );
        }
        public static void Register(
            string name,
            Action <IGenericWriter> serializer,
            Action <IGenericReader> deserializer,
            int priority = Persistence.DefaultPriority
            )
        {
            BufferWriter saveBuffer = null;

            void Serialize()
            {
                saveBuffer ??= new BufferWriter(true);
                saveBuffer.Seek(0, SeekOrigin.Begin);

                serializer(saveBuffer);
            }

            void WriterSnapshot(string savePath)
            {
                var path = Path.Combine(savePath, name);

                AssemblyHandler.EnsureDirectory(path);

                string binPath = Path.Combine(path, $"{name}.bin");

                using var bin = new BinaryFileWriter(binPath, true);

                saveBuffer !.Resize((int)saveBuffer.Position);
                bin.Write(saveBuffer.Buffer);
            }

            void Deserialize(string savePath)
            {
                var path = Path.Combine(savePath, name);

                AssemblyHandler.EnsureDirectory(path);

                string binPath = Path.Combine(path, $"{name}.bin");

                if (!File.Exists(binPath))
                {
                    return;
                }

                try
                {
                    using FileStream fs = new FileStream(binPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                    using var br        = new BinaryFileReader(fs);
                    deserializer(br);
                }
                catch (Exception e)
                {
                    Utility.PushColor(ConsoleColor.Red);
                    Console.WriteLine($"***** Bad deserialize of {name} *****");
                    Console.WriteLine(e.ToString());
                    Utility.PopColor();
                }
            }

            Persistence.Register(name, Serialize, WriterSnapshot, Deserialize, priority);
        }
Esempio n. 26
0
        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.");
                }
            }

        }
Esempio n. 27
0
        public void Deserialize(BinaryFileReader reader)
        {
            int version = reader.ReadInt();

            if (version >= 0)
            {
                serialString = reader.ReadString();

                allianceLeader = reader.ReadMobile() as Player;

                int count = reader.ReadInt();

                for (int n = 1; n <= count; n++)
                {
                    membersOf.Add(reader.ReadMobile());
                }

                int guildCount = reader.ReadInt();

                for (int x = 1; x <= guildCount; x++)
                {
                    childGuilds.Add(reader.ReadGuild() as Guild);
                }

                allianceName = reader.ReadString();
                primaryHue = reader.ReadInt();
                secondaryHue = reader.ReadInt();
                mountBody = reader.ReadInt();
                mountID = reader.ReadInt();

                foreach (Mobile m in membersOf)
                {
                    if (m is Player)
                    {
                        Player p = m as Player;
                        p.CurrentAlliance = this;
                    }
                }
            }
        }
		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;
			}
		}
Esempio n. 29
0
        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();
        }
Esempio n. 30
0
        private static void LoadGuilds(BinaryFileReader reader,
									   GuildEntry[] entries)
        {
            for (int i = 0; i < entries.Length; ++i) {
                GuildEntry entry = entries[i];
                BaseGuild guild = (BaseGuild)entry.Object;
                if (guild == null)
                    continue;

                reader.Seek(entry.Position, SeekOrigin.Begin);

                try {
                    guild.Deserialize(reader);
                } catch (Exception e) {
                    log.Error(String.Format("failed to load guild", guild),
                              e);
                    BaseGuild.List.Remove(guild.Id);
                    entries[i].Clear();
                    ++m_LoadErrors;
                    continue;
                }

                if (reader.Position != entry.Position + entry.Length) {
                    log.ErrorFormat("Bad deserialize on guild {0}, type {1}: position={2}, should be {3}",
                                    guild.Id, guild.GetType(),
                                    reader.Position, entry.Position + entry.Length);
                    BaseGuild.List.Remove(guild.Id);
                    entries[i].Clear();
                    ++m_LoadErrors;
                }
            }
        }
Esempio n. 31
0
		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);
			}
		}
Esempio n. 32
0
        private static void LoadRegions(BinaryFileReader reader,
										RegionEntry[] entries)
        {
            for (int i = 0; i < entries.Length; ++i) {
                RegionEntry entry = entries[i];
                Region region = (Region)entry.Object;
                if (region == null)
                    continue;

                reader.Seek(entry.Position, SeekOrigin.Begin);

                try {
                    region.Deserialize(reader);
                } catch (Exception e) {
                    log.Error(String.Format("failed to load region", region),
                              e);
                    ++m_LoadErrors;
                    continue;
                }

                if (reader.Position != entry.Position + entry.Length) {
                    log.ErrorFormat("Bad deserialize on region {0}, type {1}: position={2}, should be {3}",
                                    region.UId, region.GetType(),
                                    reader.Position, entry.Position + entry.Length);
                    ++m_LoadErrors;
                }
            }
        }
        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.");
        }
Esempio n. 34
0
        public static void LoadGlobalOptions()
        {
            if (!File.Exists(Path.Combine(General.SavePath, "GlobalOptions.bin")))
                return;

            using (FileStream bin = new FileStream(Path.Combine(General.SavePath, "GlobalOptions.bin"), FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                GenericReader reader = new BinaryFileReader(new BinaryReader(bin));

                int version = reader.ReadInt();

                if (version >= 2) s_MultiPort = reader.ReadInt();
                if (version >= 2) s_MultiServer = reader.ReadString();

                int count = 0;
                if (version >= 1)
                {
                    count = reader.ReadInt();
                    Notification not = null;
                    for (int i = 0; i < count; ++i)
                    {
                        not = new Notification();
                        not.Load(reader);
                    }
                }

                count = reader.ReadInt();
                string txt = "";
                for (int i = 0; i < count; ++i)
                {
                    txt = reader.ReadString();
                    if(!s_Filters.Contains(txt))
                        s_Filters.Add(txt);
                }

                s_FilterPenalty = (FilterPenalty)reader.ReadInt();
                if(version >= 1) s_MacroPenalty = (MacroPenalty)reader.ReadInt();
                s_MaxMsgs = reader.ReadInt();
                s_ChatSpam = reader.ReadInt();
                s_MsgSpam = reader.ReadInt();
                s_RequestSpam = reader.ReadInt();
                s_FilterBanLength = reader.ReadInt();
                s_FilterWarnings = reader.ReadInt();
                if (version >= 1) s_AntiMacroDelay = reader.ReadInt();
                s_IrcPort = reader.ReadInt();
                s_IrcMaxAttempts = reader.ReadInt();
                s_IrcEnabled = reader.ReadBool();
                s_IrcAutoConnect = reader.ReadBool();
                s_IrcAutoReconnect = reader.ReadBool();
                s_FilterSpeech = reader.ReadBool();
                s_FilterMsg = reader.ReadBool();
                s_Debug = reader.ReadBool();
                s_LogChat = reader.ReadBool();
                s_LogPms = reader.ReadBool();
                s_IrcStaffColor = (IrcColor)reader.ReadInt();
                s_IrcServer = reader.ReadString();
                s_IrcRoom = reader.ReadString();
                s_IrcNick = reader.ReadString();
                s_TotalChats = reader.ReadULong() - 1;
            }
        }
Esempio n. 35
0
        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);
        }
        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();
                }
            }
        }
Esempio n. 37
0
		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 );
			}
		}
Esempio n. 38
0
        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
                );
        }
Esempio n. 39
0
        public static void LoadBackup( Mobile mobile, ArrayList ArgsList, string filePath )
        {
            ArrayList HideSpawnerList = (ArrayList)			ArgsList[6];
            ArrayList MSGCheckBoxesList = (ArrayList)		ArgsList[13];

            MC.SetProcess( Process.LoadBackup );

            FileStream fs;
            BinaryFileReader reader;

            mobile.SendMessage( "Loading backup file..." );

            try
            {
                fs = new FileStream( filePath, (FileMode) 3, (FileAccess) 1, (FileShare) 1 );
                reader = new BinaryFileReader( new BinaryReader( fs ) );
            }
            catch(Exception ex)
            {
                MC.SetProcess( Process.None );

                ArgsList[2] = "Load Backup File";
                ArgsList[4] = String.Format( "Exception caught:\n{0}", ex );

                mobile.SendGump( new FileBrowserGump( mobile, ArgsList ) );

                return;
            }

            int amountOfSpawners = reader.ReadInt();
            int cnt = 0;

            for ( int i = 0; i < amountOfSpawners; i++ )
            {
                if ( Deserialize( (GenericReader) reader ) )
                {
                    HideSpawnerList.Add( (bool) false );
                    MSGCheckBoxesList.Add( (bool) false );

                    cnt++;
                }
            }

            if ( fs != null )
                fs.Close();

            MC.SetProcess( Process.None );

            ArgsList[2] = "Load Backup File";
            ArgsList[4] = String.Format( "Loading of backup file complete. {0} Mega Spawner{1} been installed.", cnt, cnt == 1 ? " has" : "s have" );
            ArgsList[6] = HideSpawnerList;
            ArgsList[13] = MSGCheckBoxesList;

            mobile.SendGump( new FileMenuGump( mobile, ArgsList ) );
        }
Esempio n. 40
0
		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>");
			}
		}
Esempio n. 41
0
        private static void LoadMobiles(BinaryFileReader reader,
										MobileEntry[] entries)
        {
            for (int i = 0; i < entries.Length; ++i) {
                MobileEntry entry = entries[i];
                Mobile m = (Mobile)entry.Object;
                if (m == null)
                    continue;

                reader.Seek(entry.Position, SeekOrigin.Begin);

                try {
                    m_LoadingType = entry.TypeName;
                    m.Deserialize(reader);
                } catch (Exception e) {
                    log.Error(String.Format("failed to load mobile {0}", m),
                              e);
                    m.Delete();
                    entries[i].Clear();
                    ++m_LoadErrors;
                    continue;
                }

                if (reader.Position != entry.Position + entry.Length) {
                    log.ErrorFormat("Bad deserialize on mobile {0}, type {1}: position={2}, should be {3}",
                                    entry.Serial, entry.TypeName,
                                    reader.Position, entry.Position + entry.Length);
                    m.Delete();
                    entries[i].Clear();
                    ++m_LoadErrors;
                }
            }
        }
Esempio n. 42
0
        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);
        }
Esempio n. 43
0
        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 OnLoad()
        {
            //don't load the file if it don't exist!
            if( !File.Exists( Path.Combine( SAVE_PATH, FILENAME ) ) )
            {
                return;
            }

            using( FileStream bin = new FileStream( Path.Combine( SAVE_PATH, FILENAME ), FileMode.Open, FileAccess.Read, FileShare.Read ) )
            {
                GenericReader reader = new BinaryFileReader( new BinaryReader( bin ) );

                int version = reader.ReadInt();

                int count = reader.ReadInt();

                for( int i = 0; i < count; i++ )
                {
                    GameData.Add( new BoardGameData( reader ) );
                }

                reader.End();
            }
        }
Esempio n. 45
0
        public static void LoadPlayerOptions()
        {
            if (!File.Exists(Path.Combine(General.SavePath, "PlayerOptions.bin")))
                return;

            using (FileStream bin = new FileStream(Path.Combine(General.SavePath, "PlayerOptions.bin"), FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                GenericReader reader = new BinaryFileReader(new BinaryReader(bin));

                int version = reader.ReadInt();

                Mobile m = null;
                int count = reader.ReadInt();
                for (int i = 0; i < count; ++i)
                {
                    m = reader.ReadMobile();
                    if (m != null)
                        GetData(m).LoadOptions(reader);
                    else
                        (new Data()).LoadOptions(reader);
                }
            }
        }
		private static void OnLoad()
		{
			if ( !File.Exists( Path.Combine( SavePath, SaveFile ) ) )
			{
				return;
			}

			using ( FileStream bin = new FileStream( Path.Combine( SavePath, SaveFile ), FileMode.Open, FileAccess.Read, FileShare.Read ) )
			{
				GenericReader reader = new BinaryFileReader( new BinaryReader( bin ) );

				m_LastResetTime = reader.ReadDateTime();

				int count = reader.ReadInt();

				for ( int i = 0; i < count; ++i )
				{
					Mobile mobile = reader.ReadMobile();

					MobileRateInfo info = new MobileRateInfo();

					info.Deserialize( reader );

					if ( mobile != null )
					{
						MobileRateInfo.Entries.Add( mobile, info );
					}
				}
			}
		}