예제 #1
0
파일: GumpInfo.cs 프로젝트: Jascen/UOSmart
		public static void Save()
		{
            try
            {
                if (!Directory.Exists(General.SavePath))
                    Directory.CreateDirectory(General.SavePath);

                GenericWriter writer = new BinaryFileWriter(Path.Combine(General.SavePath, "Gumps.bin"), true);

                writer.Write(0); // version

                writer.Write(s_ForceMenu);
                writer.Write(s_ForceInfos.Count);
                foreach (GumpInfo ginfo in s_ForceInfos.Values)
                    ginfo.Save(writer);

                ArrayList list = new ArrayList();
                GumpInfo info;

                foreach (object o in new ArrayList(s_Infos.Values))
                {
                    if (!(o is Hashtable))
                        continue;

                    foreach (object ob in new ArrayList(((Hashtable)o).Values))
                    {
                        if (!(ob is GumpInfo))
                            continue;

                        info = (GumpInfo)ob;

                        if (info.Mobile != null
                        && info.Mobile.Player
                        && !info.Mobile.Deleted
                        && info.Mobile.Account != null
                        && ((Account)info.Mobile.Account).LastLogin > DateTime.Now - TimeSpan.FromDays(30))
                            list.Add(ob);
                    }
                }

                writer.Write(list.Count);

                foreach (GumpInfo ginfo in list)
                    ginfo.Save(writer);

                writer.Close();
            }
            catch (Exception e)
            {
                Errors.Report(General.Local(199));
                Console.WriteLine(e.Message);
                Console.WriteLine(e.Source);
                Console.WriteLine(e.StackTrace);
            }
		}
예제 #2
0
		public static void SerializeMessages()
		{
			if( !Directory.Exists( SavePath ) )
				Directory.CreateDirectory( SavePath );

			BinaryFileWriter writer = new BinaryFileWriter( SaveFile, true );

			writer.Write( (int)_messageTable.Count );

			if( _messageTable.Count > 0 )
			{
				foreach( KeyValuePair<Mobile, List<ChatMessage>> kvp in _messageTable )
				{
					if( kvp.Key == null || kvp.Key.Deleted || kvp.Value == null )
					{
						writer.Write( (int)-1 );
					}
					else
					{
						writer.Write( (int)kvp.Key.Serial );

						writer.Write( (int)kvp.Value.Count );
						kvp.Value.ForEach(
							delegate( ChatMessage message )
							{
								message.Serialize( writer );
							} );
					}
				}
			}

			writer.Close();
		}
        public static void CustomSeperateSave(SeperateSaveData data)
        {
            GenericWriter writer = new BinaryFileWriter(Path.Combine(data.SaveLocation, data.SaveName + ".bin"), true);
            DirectoryCheck(data.SaveLocation);

            data.SaveMethod(writer);
            writer.Write(writer.Position);
            writer.Close();
        }
예제 #4
0
        public static void WriteEntities <I, T>(
            IIndexInfo <I> indexInfo,
            Dictionary <I, T> entities,
            List <Type> types,
            string savePath,
            out Dictionary <string, int> counts
            ) where T : class, ISerializable
        {
            counts = new Dictionary <string, int>();

            var typeName = indexInfo.TypeName;

            var path = Path.Combine(savePath, typeName);

            PathUtility.EnsureDirectory(path);

            string idxPath = Path.Combine(path, $"{typeName}.idx");
            string tdbPath = Path.Combine(path, $"{typeName}.tdb");
            string binPath = Path.Combine(path, $"{typeName}.bin");

            using var idx = new BinaryFileWriter(idxPath, false);
            using var tdb = new BinaryFileWriter(tdbPath, false);
            using var bin = new BinaryFileWriter(binPath, true);

            idx.Write(1); // Version
            idx.Write(entities.Count);
            foreach (var e in entities.Values)
            {
                long start = bin.Position;

                idx.Write(e.TypeRef);
                idx.Write(e.Serial);
                idx.Write(e.Created.Ticks);
                idx.Write(e.LastSerialized.Ticks);
                idx.Write(start);

                e.SerializeTo(bin);

                idx.Write((int)(bin.Position - start));

                var type = e.GetType().FullName;
                if (type != null)
                {
                    counts[type] = (counts.TryGetValue(type, out var count) ? count : 0) + 1;
                }
            }

            tdb.Write(types.Count);
            for (int i = 0; i < types.Count; ++i)
            {
                tdb.Write(types[i].FullName);
            }
        }
예제 #5
0
		private static void OnSave( WorldSaveEventArgs e )
		{try{

			if ( !Directory.Exists( "Saves/Gumps/" ) )
				Directory.CreateDirectory( "Saves/Gumps/" );

			GenericWriter writer = new BinaryFileWriter( Path.Combine( "Saves/Gumps/", "Gumps.bin" ), true );

			writer.Write( 0 ); // version

			ArrayList list = new ArrayList();

			GumpInfo gumpi;
			foreach( object obj in new ArrayList( s_Infos.Values ) )
			{
				if ( !(obj is Hashtable) )
					continue;

				foreach( object obje in new ArrayList( ((Hashtable)obj).Values ) )
				{
					if ( !(obje is GumpInfo ) )
						continue;

					gumpi = (GumpInfo)obje;

					if ( gumpi.Mobile != null
					&& gumpi.Mobile.Player
					&& !gumpi.Mobile.Deleted
					&& gumpi.Mobile.Account != null
					&& ((Account)gumpi.Mobile.Account).LastLogin > DateTime.Now - TimeSpan.FromDays( 30 ) )
						list.Add( obje );
				}
			}

			writer.Write( list.Count );

			foreach( GumpInfo info in list )
				info.Save( writer );

			writer.Close();

		}catch{ Errors.Report( "GumpInfo-> OnSave" ); } }
예제 #6
0
        protected void SaveData()
        {
            Dictionary <CustomSerial, SaveData> data = World.Data;

            GenericWriter indexWriter;
            GenericWriter typeWriter;
            GenericWriter dataWriter;

            indexWriter = new BinaryFileWriter(World.DataIndexPath, false);
            typeWriter  = new BinaryFileWriter(World.DataTypesPath, false);
            dataWriter  = new BinaryFileWriter(World.DataBinaryPath, true);


            indexWriter.Write(data.Count);

            foreach (SaveData saveData in data.Values)
            {
                long start = dataWriter.Position;

                indexWriter.Write(saveData._TypeID);
                indexWriter.Write((int)saveData.Serial);
                indexWriter.Write(start);

                saveData.Serialize(dataWriter);



                indexWriter.Write((int)(dataWriter.Position - start));
            }

            typeWriter.Write(World._DataTypes.Count);

            for (int i = 0; i < World._DataTypes.Count; ++i)
            {
                typeWriter.Write(World._DataTypes[i].FullName);
            }

            indexWriter.Close();
            typeWriter.Close();
            dataWriter.Close();
        }
예제 #7
0
        public virtual void Serialize(BinaryFileWriter writer)
        {
            writer.Write((int)0);

            //version 0
            writer.Write((int)ContainerTable.Count);

            if (ContainerTable.Count > 0)
            {
                foreach (KeyValuePair <GrabFlag, Container> kvp in ContainerTable)
                {
                    writer.Write((int)kvp.Key);
                    writer.Write(kvp.Value);
                }
            }

            writer.Write((int)Flags);
            writer.Write(Mobile);
        }
예제 #8
0
파일: Data.cs 프로젝트: guy489/runuot2a
        public static void SaveGlobalOptions()
        {
            CleanUpData();

            if (!Directory.Exists(General.SavePath))
                Directory.CreateDirectory(General.SavePath);

            GenericWriter writer = new BinaryFileWriter(Path.Combine(General.SavePath, "GlobalOptions.bin"), true);

            writer.Write(2); // version

            writer.Write(s_MultiPort);
            writer.Write(s_MultiServer);

            writer.Write(s_Notifications.Count);
            foreach (Notification not in s_Notifications)
                not.Save(writer);

            writer.Write(s_Filters.Count);
            foreach (string str in s_Filters)
                writer.Write(str);

            writer.Write((int)s_FilterPenalty);
            writer.Write((int)s_MacroPenalty);
            writer.Write(s_MaxMsgs);
            writer.Write(s_ChatSpam);
            writer.Write(s_MsgSpam);
            writer.Write(s_RequestSpam);
            writer.Write(s_FilterBanLength);
            writer.Write(s_FilterWarnings);
            writer.Write(s_AntiMacroDelay);
            writer.Write(s_IrcPort);
            writer.Write(s_IrcMaxAttempts);
            writer.Write(s_IrcEnabled);
            writer.Write(s_IrcAutoConnect);
            writer.Write(s_IrcAutoReconnect);
            writer.Write(s_FilterSpeech);
            writer.Write(s_FilterMsg);
            writer.Write(s_Debug);
            writer.Write(s_LogChat);
            writer.Write(s_LogPms);
            writer.Write((int)s_IrcStaffColor);
            writer.Write(s_IrcServer);
            writer.Write(s_IrcRoom);
            writer.Write(s_IrcNick);
            writer.Write(s_TotalChats+1);

            writer.Close();
        }
예제 #9
0
		public static void Save( WorldSaveEventArgs args )
		{
			if( !Directory.Exists( "Saves/ACC" ) )
				Directory.CreateDirectory( "Saves/ACC" );

			string filename = "acc.sav";
			string path =@"Saves/ACC/";
			string pathNfile = path+filename;
			DateTime start = DateTime.Now;

			Console.WriteLine();
			Console.WriteLine();
			Console.WriteLine( "----------" );
			Console.WriteLine( "Saving ACC..." );

			try
			{
				using( FileStream m_FileStream = new FileStream( pathNfile, FileMode.OpenOrCreate, FileAccess.Write ) )
				{
					BinaryFileWriter writer = new BinaryFileWriter( m_FileStream, true );

					writer.Write( (int) m_RegSystems.Count );
					foreach( DictionaryEntry de in m_RegSystems )
					{
						Type t = ScriptCompiler.FindTypeByFullName( (string)de.Key );
						if( t != null )
						{
							writer.Write( (string)de.Key );
							writer.Write( (bool)de.Value );

							if( (bool)m_RegSystems[(string)de.Key] )
							{
								ACCSystem system = (ACCSystem)Activator.CreateInstance( t );
								if( system != null )
									system.StartSave( path );
							}
						}

					}

					writer.Close();
					m_FileStream.Close();
				}

				Console.WriteLine( "Done in {0:F1} seconds.", (DateTime.Now-start).TotalSeconds );
				Console.WriteLine( "----------" );
				Console.WriteLine();
			}
			catch( Exception err )
			{
				Console.WriteLine( "Failed. Exception: "+err );
			}
		}
예제 #10
0
        public static void SaveBackup( Mobile mobile, ArrayList ArgsList )
        {
            MC.SetProcess( Process.SaveBackup );

            if ( !Directory.Exists( MC.BackupDirectory ) )
                Directory.CreateDirectory( MC.BackupDirectory );

            string path = Path.Combine( MC.BackupDirectory, "Backup.mbk" );

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

            MC.CheckSpawners();

            ArrayList SpawnerList = CompileSpawnerList();

            GenericWriter writer;

            try
            {
                writer = new BinaryFileWriter( path, true );
            }
            catch(Exception ex)
            {
                MC.SetProcess( Process.None );

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

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

                return;
            }

            writer.Write( SpawnerList.Count );

            try
            {
                foreach ( MegaSpawner megaSpawner in SpawnerList )
                    Serialize( megaSpawner, writer );
            }
            catch{}

            writer.Close();

            MC.SetProcess( Process.None );

            ArgsList[2] = "Create Backup File";
            ArgsList[4] = "All Mega Spawners have now been backed up to the backup file.";

            mobile.SendGump( new FileMenuGump( mobile, ArgsList ) );
        }
예제 #11
0
		public virtual void Serialize( BinaryFileWriter writer )
		{
			writer.Write( (int)0 );

			//version 0
			writer.WriteMobileList<Mobile>( _buddyList, true );
			writer.Write( _client );
			writer.WriteMobileList<Mobile>( _ignoreList, true );
			writer.Write( _visible );
		}
예제 #12
0
        public static void Save()
        {
            log.Info("Saving...");
            log.Info(String.Format("idxPath: '{0}'", idxPath));
            log.Info(String.Format("binPath: '{0}'", binPath));

            if (!Directory.Exists(Path.Combine("Saves", "Donation")))
                Directory.CreateDirectory(Path.Combine("Saves", "Donation"));

            GenericWriter idx = new BinaryFileWriter(idxPath, false);
            GenericWriter bin = new BinaryFileWriter(binPath, true);

            log.Info(String.Format("m_ClaimedOrders.Count: '{0}'", m_ClaimedOrders.Count));
            idx.Write((int)m_ClaimedOrders.Count);
            foreach (ClaimedOrder claimed in m_ClaimedOrders)
            {
                long startPos = bin.Position;
                claimed.Serialize(bin);
                idx.Write((long)startPos);
                idx.Write((int)(bin.Position - startPos));
            }
            idx.Close();
            bin.Close();
            log.Info("Saving done.");
        }
예제 #13
0
		public static void SaveSpawners_OnCommand(CommandEventArgs e)
		{

			if (e.Arguments.Length == 5)
			{
				int count = 0;
				int x1, y1, x2, y2;
				string FileName = e.Arguments[0].ToString();
				try
				{
					x1 = Int32.Parse(e.Arguments[1]);
					y1 = Int32.Parse(e.Arguments[2]);
					x2 = Int32.Parse(e.Arguments[3]);
					y2 = Int32.Parse(e.Arguments[4]);
				}
				catch
				{
					Usage(e.Mobile);
					return;
				}
				//adjust rect				
				if (x1 > x2)
				{
					int x3 = x1;
					x1 = x2;
					x2 = x3;
				}
				if (y1 > y2)
				{
					int y3 = y1;
					y1 = y2;
					y2 = y3;
				}
				string itemIdxPath = Path.Combine("Saves/Spawners/", FileName + ".idx");
				string itemBinPath = Path.Combine("Saves/Spawners/", FileName + ".bin");

				try
				{
					ArrayList list = new ArrayList();
					foreach (Item item in Server.World.Items.Values)
					{
						if (item is Spawner)
						{
							if (item.X >= x1 && item.Y >= y1 && item.X < x2 && item.Y < y2 && item.Map == e.Mobile.Map)
								list.Add(item);
						}
					}

					if (list.Count > 0)
					{
						try
						{
							string folder = Path.GetDirectoryName(itemIdxPath);

							if (!Directory.Exists(folder))
							{
								Directory.CreateDirectory(folder);
							}

						}
						catch
						{
							e.Mobile.SendMessage("An error occured while trying to create Spawner folder.");
						}

						count = list.Count;
						GenericWriter idx;
						GenericWriter bin;

						idx = new BinaryFileWriter(itemIdxPath, false);
						bin = new BinaryFileWriter(itemBinPath, true);

						idx.Write((int)list.Count);

						for (int i = 0; i < list.Count; ++i)
						{
							long start = bin.Position;
							Spawner temp = new Spawner();
							CopyProperties(temp, (Spawner)list[i]);

							idx.Write((long)start);
							//dont save template data as we cant load it back properly
							temp.TemplateItem = null;
							temp.TemplateMobile = null;
							temp.CreaturesName = ((Spawner)list[i]).CreaturesName;
							temp.Serialize(bin);

							idx.Write((int)(bin.Position - start));
							temp.Delete();
						}
						idx.Close();
						bin.Close();
					}
				}
				catch (Exception ex)
				{
					LogHelper.LogException(ex);
					System.Console.WriteLine("Exception Caught in SaveSpawner code: " + ex.Message);
					System.Console.WriteLine(ex.StackTrace);
				}

				e.Mobile.SendMessage("{0} Spawners Saved.", count);
			}
			else
			{
				Usage(e.Mobile);
			}
		}
예제 #14
0
        public void Serialize(BinaryFileWriter writer)
        {
            writer.Write((int)0); //Version

            writer.Write((string)serialString.ToString());
            writer.WriteMobile(allianceLeader);

            writer.Write((int)membersOf.Count);

            foreach (Mobile m in membersOf)
            {
                writer.WriteMobile(m);
            }

            writer.Write((int)childGuilds.Count);

            foreach (Guild g in childGuilds)
            {
                writer.WriteGuild(g);
            }

            writer.Write((string)allianceName);
            writer.Write((int)primaryHue);
            writer.Write((int)secondaryHue);
            writer.Write((int)mountBody);
            writer.Write((int)mountID);

        }
예제 #15
0
        private static void EventSink_WorldSave( WorldSaveEventArgs e )
        {
            DateTime start = DateTime.Now;
            Console.WriteLine( "processing additional components." );
            Console.WriteLine( "Forums: Saving..." );

            if( AutoCleanup )
                Console.Write( "Auto Cleanup is checking posts..." );
            else
                Console.Write( "Checking deletion queue..." );

            int queue = 0;
            int deleted = RemovedDeletedQueue(out queue);

            if( queue == 0 )
                Console.Write( "Empty Queue..." );
            else
                Console.Write( "{1} Queued...{0} Deleted...", deleted, queue );
            
            string SavePath = Path.Combine( m_SavePath, "forumdata.sig" );

            if( !Directory.Exists( m_SavePath ) )
                Directory.CreateDirectory( m_SavePath );

            GenericWriter bin = new BinaryFileWriter( SavePath, true );
            
            try
            {
                bin.Write( ( int )0 );//Versioning

                WritePlayerStatistics( bin );
            
                bin.Write( ( int )( m_Threads.Count ) );
                foreach( ThreadEntry te in m_Threads )
                {
                    te.Serialize( bin );
                }

                bin.WriteMobileList( m_Moderators );
                bin.Write( ( int )m_ThreadDeleteAccessLevel );
                bin.Write( ( int )m_ThreadLockAccesLevel );
                bin.Write( ( bool )m_AutoCleanup );
                bin.Write( ( int )m_AutoCleanupDays );
                bin.Write( ( int )m_MinPostCharactersCount );
                bin.Write( ( int )m_MaxPostCharactersCount );
                bin.Close();
                
                DateTime end = DateTime.Now;
                Console.WriteLine( "done in {0:F1} seconds.", ( end - start ).TotalSeconds );
                Console.Write( "World: " );
            }
            catch( Exception err )
            {
                bin.Close();

                Console.Write( "An error occurred while trying to save the forums. {0}", err.ToString());
            }
        }        
예제 #16
0
        public virtual void Serialize(BinaryFileWriter writer)
        {
            writer.Write((int)0);

            //version 0
            writer.Write((int)ContainerTable.Count);

            if (ContainerTable.Count > 0)
            {
                foreach (KeyValuePair<LootFlag, Container> kvp in ContainerTable)
                {
                    writer.Write((int)kvp.Key);
                    writer.Write(kvp.Value);
                }
            }

            writer.Write((int)Flags);
            writer.Write(Mobile);
        }
예제 #17
0
        private static void OnSave( WorldSaveEventArgs e )
        {
            try{

            if ( !Directory.Exists( "Saves/Commands/" ) )
                Directory.CreateDirectory( "Saves/Commands/" );

            GenericWriter writer = new BinaryFileWriter( Path.Combine( "Saves/Commands/", "Commands.bin" ), true );

            writer.Write( 0 ); // version

            ArrayList list = new ArrayList( s_Defaults.Values );

            writer.Write( list.Count );

            foreach( DefaultInfo info in list )
            {
                writer.Write( info.NewCommand );
                writer.Write( info.OldCommand );
                writer.Write( (int)info.NewAccess );
            }

            writer.Close();

            }catch{ Errors.Report( "Commands-> OnSave" ); }
        }
예제 #18
0
		public static void Save(bool message)
		{
			if (m_Saving || AsyncWriter.ThreadCount > 0)
				return;

			// we make certain we cannot save when we are in ServerWars
			if (World.SaveType == World.SaveOption.NoSaves)
			{
				Console.WriteLine("Error: Save aborted: World.SaveType == World.SaveOption.NoSaves");
				return;
			}

			NetState.FlushAll();

			m_Saving = true;

			if (message)
				Broadcast(0x35, true, "The world is saving, please wait.");

			Console.WriteLine("World: Saving...");

			DateTime startTime = DateTime.Now;

			// Adam: see comments in the function
			PackMemory(true);

			if (!Directory.Exists("Saves/Mobiles/"))
				Directory.CreateDirectory("Saves/Mobiles/");
			if (!Directory.Exists("Saves/Items/"))
				Directory.CreateDirectory("Saves/Items/");
			if (!Directory.Exists("Saves/Guilds/"))
				Directory.CreateDirectory("Saves/Guilds/");
			if (!Directory.Exists("Saves/Regions/"))
				Directory.CreateDirectory("Saves/Regions/");

			if (m_MultiProcessor)
			{
				Thread saveThread = new Thread(new ThreadStart(SaveItems));

				saveThread.Name = "Item Save Subset";
				saveThread.Start();

				SaveMobiles();
				SaveGuilds();
				SaveRegions();

				saveThread.Join();
			}
			else
			{
				SaveMobiles();
				SaveItems();
				SaveGuilds();
				SaveRegions();
			}

			//Accounts.Save();

			try
			{
				EventSink.InvokeWorldSave(new WorldSaveEventArgs(message));
			}
			catch (Exception e)
			{
				throw new Exception("World Save event threw an exception.  Save failed!", e);
			}

			/* Adam, not currently used
			DateTime copy = DateTime.Now;
			if (Directory.Exists("Saves/Temp"))
				Directory.Delete("Saves/Temp", true);
			if (Directory.Exists("Temp"))
				CopyDirectory("Temp", "Saves/Temp");
			Console.WriteLine("Copying Temp/ took {0}ms", (DateTime.Now - copy).TotalMilliseconds);
			 */

			// take care of some World class-specific stuff
			try
			{
				BinaryFileWriter w = new BinaryFileWriter("Saves/World.dat", true);
				w.Write((int)1); // version

				// version 1
				w.Write(m_ReservedSerials.Keys.Count);
				foreach (int i in m_ReservedSerials.Keys)
					w.Write(i);

				// version 0
				w.Write((bool)m_FreezeDryEnabled);

				w.Close();
			}
			catch (Exception e)
			{
				Console.WriteLine("Error writing World.dat:");
				Console.WriteLine(e.ToString());
			}

			// Adam: final cleanup
			PackMemory(false);

			DateTime endTime = DateTime.Now;
			Console.WriteLine("done in {0:F1} seconds.", (endTime - startTime).TotalSeconds);

			if (message)
				Broadcast(0x35, true, "World save complete. The entire process took {0:F1} seconds.", (endTime - startTime).TotalSeconds);

			m_Saving = false;
		}
예제 #19
0
		public static void OnSave(WorldSaveEventArgs e)
		{
			try
			{
				Console.WriteLine("KinCityManager Saving...");
				if (!Directory.Exists("Saves/AngelIsland"))
					Directory.CreateDirectory("Saves/AngelIsland");

				string filePath = Path.Combine("Saves/AngelIsland", "KinCityManager.bin");

				GenericWriter writer;
				writer = new BinaryFileWriter(filePath, true);

				writer.Write(1); //version

				//v1 below
				//write out the city data class'
				writer.Write(_cityData.Count);
				foreach (KeyValuePair<KinFactionCities, KinCityData> pair in _cityData)
					pair.Value.Save(writer);

				writer.Close();
			}
			catch (Exception ex)
			{
				System.Console.WriteLine("Error saving KinCityManager!");
				Scripts.Commands.LogHelper.LogException(ex);
			}
		}
예제 #20
0
        public static void Save(WorldSaveEventArgs e)
        {
            if (XmlAttach.MobileAttachments == null && XmlAttach.ItemAttachments == null) return;

            CleanUp();

            if (!Directory.Exists("Saves/Attachments"))
                Directory.CreateDirectory("Saves/Attachments");

            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

            BinaryFileWriter writer = null;
            BinaryFileWriter imawriter = null;
            BinaryFileWriter fpiwriter = null;

            try
            {
                writer = new BinaryFileWriter(filePath, true);
                imawriter = new BinaryFileWriter(imaPath, true);
                fpiwriter = new BinaryFileWriter(fpiPath, true);

            }
            catch (Exception err)
            {
                ErrorReporter.GenerateErrorReport(err.ToString());
                return;
            }

            if (writer != null && imawriter != null && fpiwriter != null)
            {
                // save the current global attachment serial state
                ASerial.GlobalSerialize(writer);

                // remove all deleted attachments
                XmlAttach.FullDefrag();

                // save the attachments themselves
                if (XmlAttach.AllAttachments != null)
                {
                    writer.Write(XmlAttach.AllAttachments.Count);

                    object[] valuearray = new object[XmlAttach.AllAttachments.Count];
                    XmlAttach.AllAttachments.Values.CopyTo(valuearray, 0);

                    object[] keyarray = new object[XmlAttach.AllAttachments.Count];
                    XmlAttach.AllAttachments.Keys.CopyTo(keyarray, 0);

                    for (int i = 0; i < keyarray.Length; i++)
                    {
                        // write the key
                        writer.Write((int)keyarray[i]);

                        XmlAttachment a = valuearray[i] as XmlAttachment;

                        // write the value type
                        writer.Write((string)a.GetType().ToString());

                        // serialize the attachment itself
                        a.Serialize(writer);

                        // save the fileposition index
                        fpiwriter.Write((long)writer.Position);
                    }
                }
                else
                {
                    writer.Write((int)0);
                }

                writer.Close();

                // save the hash table info for items and mobiles
                // mobile attachments
                if (XmlAttach.MobileAttachments != null)
                {
                    imawriter.Write(XmlAttach.MobileAttachments.Count);

                    object[] valuearray = new object[XmlAttach.MobileAttachments.Count];
                    XmlAttach.MobileAttachments.Values.CopyTo(valuearray, 0);

                    object[] keyarray = new object[XmlAttach.MobileAttachments.Count];
                    XmlAttach.MobileAttachments.Keys.CopyTo(keyarray, 0);

                    for (int i = 0; i < keyarray.Length; i++)
                    {
                        // write the key
                        imawriter.Write((Mobile)keyarray[i]);

                        // write out the attachments
                        ArrayList alist = (ArrayList)valuearray[i];

                        imawriter.Write((int)alist.Count);
                        foreach (XmlAttachment a in alist)
                        {
                            // write the attachment serial
                            imawriter.Write((int)a.Serial.Value);

                            // write the value type
                            imawriter.Write((string)a.GetType().ToString());

                            // save the fileposition index
                            fpiwriter.Write((long)imawriter.Position);
                        }
                    }
                }
                else
                {
                    // no mobile attachments
                    imawriter.Write((int)0);
                }

                // item attachments
                if (XmlAttach.ItemAttachments != null)
                {
                    imawriter.Write(XmlAttach.ItemAttachments.Count);

                    object[] valuearray = new object[XmlAttach.ItemAttachments.Count];
                    XmlAttach.ItemAttachments.Values.CopyTo(valuearray, 0);

                    object[] keyarray = new object[XmlAttach.ItemAttachments.Count];
                    XmlAttach.ItemAttachments.Keys.CopyTo(keyarray, 0);

                    for (int i = 0; i < keyarray.Length; i++)
                    {
                        // write the key
                        imawriter.Write((Item)keyarray[i]);

                        // write out the attachments			             
                        ArrayList alist = (ArrayList)valuearray[i];

                        imawriter.Write((int)alist.Count);
                        foreach (XmlAttachment a in alist)
                        {
                            // write the attachment serial
                            imawriter.Write((int)a.Serial.Value);

                            // write the value type
                            imawriter.Write((string)a.GetType().ToString());

                            // save the fileposition index
                            fpiwriter.Write((long)imawriter.Position);
                        }
                    }
                }
                else
                {
                    // no item attachments
                    imawriter.Write((int)0);
                }

                imawriter.Close();
                fpiwriter.Close();
            }
        }
        public static void OnSave( WorldSaveEventArgs e )
        {
            if( !Directory.Exists( SAVE_PATH ) )
            {
                Directory.CreateDirectory( SAVE_PATH );
            }

            GenericWriter writer = new BinaryFileWriter( Path.Combine( SAVE_PATH, FILENAME ), true );

            writer.Write( 0 );

            writer.Write( GameData.Count );

            foreach( BoardGameData data in GameData )
            {
                data.Serialize( writer );
            }

            writer.Close();
        }
예제 #22
0
		public static void Save()
		{
			if (!Directory.Exists("Saves/CTFScore/"))
				Directory.CreateDirectory("Saves/CTFScore/");

			string idxPath = Path.Combine( "Saves/CTFScore", "CTFScore.idx" );
			string binPath = Path.Combine( "Saves/CTFScore", "CTFScore.bin" );

			GenericWriter idx = new BinaryFileWriter(idxPath, false);
			GenericWriter bin = new BinaryFileWriter(binPath, true);

			idx.Write( (int)Players.Values.Count );
			foreach ( CTFPlayer player in Players.Values )
			{
				long startPos = bin.Position;
				player.Serialize( bin );
				idx.Write( (long)startPos );
				idx.Write( (int)(bin.Position - startPos) );
			}
			idx.Close();
			bin.Close();
		}
예제 #23
0
        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 bin = new FileStream(binPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                    var buffer = GC.AllocateUninitializedArray <byte>((int)bin.Length);
                    bin.Read(buffer);
                    deserializer(new BufferReader(buffer));
                }
                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);
        }
예제 #24
0
        public static void Serialize(BinaryFileWriter writer)
        {
            writer.Write((int)0); //Version

            writer.Write((int)AllianceLimit);
            writer.Write((bool)useXML);
            writer.Write((int)Alliances.Count);

            foreach (BaseAlliance a in Alliances)
            {
                a.Serialize(writer);
            }

            writer.Close();
        }
		private static void OnSave( WorldSaveEventArgs args )
		{
			if ( !Directory.Exists( SavePath ) )
			{
				Directory.CreateDirectory( SavePath );
			}

			GenericWriter writer = new BinaryFileWriter( Path.Combine( SavePath, SaveFile ), true );

			writer.Write( m_LastResetTime );

			writer.Write( MobileRateInfo.Entries.Count );

			foreach ( KeyValuePair<Mobile, MobileRateInfo> kvp in MobileRateInfo.Entries )
			{
				writer.Write( (Mobile)kvp.Key );

				MobileRateInfo info = (MobileRateInfo)kvp.Value;

				info.Serialize( writer );
			}

			writer.Close();
		}
예제 #26
0
			protected override void OnTarget(Mobile from, object targeted)
			{
				if (!(targeted is Container))
				{
					from.SendMessage("Only containers can be dumped.");
					return;
				}

				Container cont = (Container)targeted;

				try
				{
					using (FileStream idxfs = new FileStream(m_Filename + ".idx", FileMode.Create, FileAccess.Write, FileShare.None))
					{
						using (FileStream binfs = new FileStream(m_Filename + ".bin", FileMode.Create, FileAccess.Write, FileShare.None))
						{
							GenericWriter idx = new BinaryFileWriter(idxfs, true);
							GenericWriter bin = new BinaryFileWriter(binfs, true);

							ArrayList items = new ArrayList();
							items.Add(cont);
							items.AddRange(cont.GetDeepItems());

							idx.Write((int)items.Count);
							foreach (Item item in items)
							{
								long start = bin.Position;

								idx.Write(item.GetType().FullName); // <--- DIFFERENT FROM WORLD SAVE FORMAT!
								idx.Write((int)item.Serial);
								idx.Write((long)start);

								item.Serialize(bin);

								idx.Write((int)(bin.Position - start));
							}


							idx.Close();
							bin.Close();
						}
					}

					from.SendMessage("Container successfully dumped to {0}.", m_Filename);
				}
				catch (Exception e)
				{
					LogHelper.LogException(e);
					Console.WriteLine(e.ToString());
					from.SendMessage("Exception: {0}", e.Message);
				}
			}
예제 #27
0
		private static void event_worldSave( WorldSaveEventArgs args )
		{
			if( !Directory.Exists( PersistencePath ) )
				Directory.CreateDirectory( PersistencePath );

			BinaryFileWriter writer = new BinaryFileWriter( PersistenceFile, true );

			writer.Write( OptionsTable.Count );

			if( OptionsTable.Count > 0 )
			{
				foreach( KeyValuePair<Mobile, GrabOptions> kvp in OptionsTable )
				{
					if( kvp.Key == null || kvp.Key.Deleted || kvp.Value == null )
					{
						writer.Write( (int)-1 );
					}
					else
					{
						writer.Write( (int)kvp.Key.Serial );
						kvp.Value.Serialize( writer );
					}
				}
			}

			writer.Close();
		} 
예제 #28
0
		public void Serialize()
		{
			//Console.WriteLine("[Vote System]: Saving Config...");

			FileInfo info = new FileInfo("Data\\VoteSystem.cfg");

			if (!info.Exists)
				info.Create().Close();

			using(FileStream fs = info.Open(FileMode.Truncate, FileAccess.Write))
			{
				BinaryFileWriter bin = new BinaryFileWriter(fs, true);
				
				bin.Write((int)0);

				bin.Write((string)_DefaultName);
				bin.Write((string)_DefaultURL);
				bin.Write((TimeSpan)_DefaultCoolDown);

				bin.Close();
			}

			//Console.WriteLine("[Vote System]: Done.");
		}
        private static void CustomSave()
        {
            DirectoryCheck(m_FilePath);

            GenericWriter idx = new BinaryFileWriter(m_FullPath + ".idx", true);
            GenericWriter bin = new BinaryFileWriter(m_FullPath + ".bin", true);

            idx.Write(m_DataDictionary.Count);
            foreach (KeyValuePair<string, SaveData> kv in m_DataDictionary)
            {
                idx.Write(kv.Key);
                idx.Write(bin.Position);
                kv.Value.SaveMethod(bin);
                idx.Write(bin.Position);
            }

            idx.Close();
            bin.Close();
        }
예제 #30
0
		private static void ExportSectorNodeNetwork(CommandEventArgs e)
		{
			try
			{
				Console.Write("Saving SectorNodes...");
				DateTime dt = DateTime.Now;
				if (!Directory.Exists("Data"))
					Directory.CreateDirectory("Data");

				using (FileStream fs = new FileStream("Data/SectorPathData.dat", FileMode.Create))
				{
					BinaryFileWriter writer = new BinaryFileWriter(fs, false);

					writer.Write(Map.Felucca.Width >> Map.SectorShift);
					writer.Write(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].Serialize(writer);
						}
					}

					writer.Close();
				}
				Console.WriteLine("done in {0}ms.", (DateTime.Now - dt).TotalMilliseconds);
			}
			catch (Exception ex)
			{
				LogHelper.LogException(ex);
				Console.WriteLine("error:");
				Console.WriteLine(ex);
			}
		}
        private static void HandleError(Exception error, string name, object[] loadinfo)
        {
            bool sep = loadinfo == null;
            bool nerr = error == null;
            string type = sep ? "seperate savefile" : "save module";
            string placename = sep ? "the file can be found at" : "this module was indexed under the name";

            Console.WriteLine();
            if (nerr)
            {
                Console.WriteLine("The loading and saving methods of a {0} are inconsistent, {1} \"{2}\".", type, placename, name);
                if (!sep && (bool)loadinfo[3])
                    Console.WriteLine("More data was read than written.");
                else
                    Console.WriteLine("More data was written than read.");
            }
            else
            {
                Console.WriteLine("During the loading of a {0} an exception was caught, {1} \"{2}\".", type, placename, name);
                Console.WriteLine("The following error was caught:");
                Console.WriteLine(error.ToString());
            }

            Console.WriteLine("Please Review your Save/Load methods for this {0}", sep ? "file" : "module");

            if (!m_IgnoreErrors)
            {
                string str = sep ? "Do you wish to continue loading with faulty data(Y), or stop the program(N)?" : "Do you wish to remove this module and restart(Y), or continue loading with faulty data(N)?";
                Console.WriteLine(str);

                if (Console.ReadKey(true).Key == ConsoleKey.Y)
                {
                    if (!sep)
                    {
                        int oldcount = (int)loadinfo[0];
                        int location = (int)loadinfo[1];
                        BinaryFileReader idxreader = (BinaryFileReader)loadinfo[2];

                        int newcount = oldcount - 1;
                        string[] indexarray = new string[newcount];
                        long[] binposarray = new long[newcount];
                        long[] finposarray = new long[newcount];

                        idxreader.Seek(0, SeekOrigin.Begin);
                        idxreader.ReadInt();
                        int loc = 0;
                        for (int j = 0; j < oldcount; j++)
                        {
                            if (j != location)
                            {
                                indexarray[loc] = idxreader.ReadString();
                                binposarray[loc] = idxreader.ReadLong();
                                finposarray[loc] = idxreader.ReadLong();
                                loc++;
                            }
                            else
                            {
                                idxreader.ReadString();
                                idxreader.ReadLong();
                                idxreader.ReadLong();
                            }
                        }
                        idxreader.Close();
                        GenericWriter idxwriter = new BinaryFileWriter(m_FullPath + ".idx", true);

                        idxwriter.Write(newcount);
                        for (int j = 0; j < newcount; j++)
                        {
                            idxwriter.Write(indexarray[j]);
                            idxwriter.Write(binposarray[j]);
                            idxwriter.Write(finposarray[j]);
                        }
                        idxwriter.Close();

                        Process.Start(Core.ExePath, Core.Arguments);
                        Core.Process.Kill();
                    }
                }

                else if (sep)
                    Core.Process.Kill();
            }
        }
예제 #32
0
파일: Data.cs 프로젝트: guy489/runuot2a
        public static void SaveGlobalListens()
        {
            if (!Directory.Exists(General.SavePath))
                Directory.CreateDirectory(General.SavePath);

            GenericWriter writer = new BinaryFileWriter(Path.Combine(General.SavePath, "GlobalListens.bin"), true);

            writer.Write(0); // version

            writer.Write(s_Datas.Count);
            foreach (Data data in s_Datas.Values)
            {
                writer.Write(data.Mobile);
                data.SaveGlobalListens(writer);
            }

            writer.Close();
        }
        public static void Save(WorldSaveEventArgs e)
        {
            if (!Directory.Exists("LokaiSaves/LokaiSkills"))
            {
                Directory.CreateDirectory("LokaiSaves/LokaiSkills");
            }
            string           filePath = Path.Combine("LokaiSaves/LokaiSkills", "LokaiSkills.bin");
            BinaryFileWriter writer   = null;

            try
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                Console.WriteLine(".bin file successfully deleted.");
            }
            catch (Exception err)
            {
                Console.WriteLine("Unable to delete the BinaryFileWriter so exiting SAVE process.");
                Console.WriteLine(err.ToString());
                return;
            }
            try
            {
                writer = new BinaryFileWriter(filePath, true);
            }
            catch
            {
                Console.WriteLine("Unable to create new BinaryFileWriter so exiting SAVE process.");
                return;
            }
            writer.WriteEncodedInt((int)0); //version

            writer.WriteEncodedInt((int)m_LinguisticsLevel);
            writer.Write(m_CommerceEnabled);
            writer.Write(m_RidingChecksEnabled);
            writer.Write(m_SailingChecksEnabled);
            writer.Write(m_LinguisticsEnabled);

            writer.Write(ShowButchering);
            writer.Write(ShowSkinning);
            writer.Write(ShowAnimalRiding);
            writer.Write(ShowSailing);
            writer.Write(ShowDetectEvil);
            writer.Write(ShowCureDisease);
            writer.Write(ShowPickPocket);
            writer.Write(ShowPilfering);
            writer.Write(ShowFraming);
            writer.Write(ShowBrickLaying);
            writer.Write(ShowRoofing);
            writer.Write(ShowStoneMasonry);
            writer.Write(ShowVentriloquism);
            writer.Write(ShowHypnotism);
            writer.Write(ShowPreyTracking);
            writer.Write(ShowSpeakToAnimals);
            writer.Write(ShowWoodworking);
            writer.Write(ShowCooperage);
            writer.Write(ShowSpinning);
            writer.Write(ShowWeaving);
            writer.Write(ShowConstruction);
            writer.Write(ShowCommerce);
            writer.Write(ShowBrewing);
            writer.Write(ShowHerblore);
            writer.Write(ShowTreePicking);
            writer.Write(ShowTreeSapping);
            writer.Write(ShowTreeCarving);
            writer.Write(ShowTreeDigging);
            writer.Write(ShowTeaching);
            writer.Write(ShowLinguistics);
            writer.Close();
            Console.WriteLine("All LokaiSkill values successfully written to .bin file. File closed.");
        }
예제 #34
0
		private void SaveTypeDatabase(string path, List<Type> types)
		{
			var bfw = new BinaryFileWriter(path, false);

			bfw.Write(types.Count);

			foreach (Type type in types)
			{
				bfw.Write(type.FullName);
			}

			bfw.Flush();
			bfw.Close();
		}
예제 #35
0
        public static void Save()
        {
            try
            {
                if (!Directory.Exists(General.SavePath))
                    Directory.CreateDirectory(General.SavePath);

                GenericWriter writer = new BinaryFileWriter(Path.Combine(General.SavePath, "Channels.bin"), true);

                writer.Write(0); // version

                writer.Write(s_Channels.Count);
                foreach (Channel c in s_Channels)
                {
                    writer.Write(c.GetType().ToString());
                    c.Save(writer);
                }

                writer.Close();
            }
            catch (Exception e)
            {
                Errors.Report(General.Local(187));
                Console.WriteLine(e.Message);
                Console.WriteLine(e.Source);
                Console.WriteLine(e.StackTrace);
            }
        }