Init() 공개 메소드

public Init ( ) : void
리턴 void
예제 #1
0
        private static void Start( string[ ] args )
        {
            //register object builder assembly
            string path = System.IO.Path.Combine( AppDomain.CurrentDomain.BaseDirectory, "SpaceEngineers.ObjectBuilders.DLL" );
            VRage.Plugins.MyPlugins.RegisterGameObjectBuildersAssemblyFile( path );

            MyObjectBuilderType.RegisterAssemblies( );

            //Setup error handling for unmanaged exceptions
            AppDomain.CurrentDomain.UnhandledException += AppDomain_UnhandledException;
            Application.ThreadException += Application_ThreadException;
            Application.SetUnhandledExceptionMode( UnhandledExceptionMode.CatchException );

            //AppDomain.CurrentDomain.ClearEventInvocations("_unhandledException");

            BaseLog.Info( "Starting SEServerExtender with {0} arguments: {1}", args.Length, string.Join( "\r\n\t", args ) );

            CommandLineArgs extenderArgs = CommandLineArgs = new CommandLineArgs
                              {
                                  ConsoleTitle = string.Empty,
                                  AutoStart = false,
                                  WorldName = string.Empty,
                                  InstanceName = string.Empty,
                                  NoGui = false,
                                  NoConsole = false,
                                  Debug = false,
                                  GamePath = new DirectoryInfo( PathManager.BasePath ).Parent.FullName,
                                  NoWcf = false,
                                  Autosave = 0,
                                  InstancePath = string.Empty,
                                  CloseOnCrash = false,
                                  RestartOnCrash = false,
                                  Args = string.Join( " ", args.Select( x => string.Format( "\"{0}\"", x ) ) )
                              };

            if ( ConfigurationManager.AppSettings[ "WCFChatMaxMessageHistoryAge" ] != null )
                if ( !int.TryParse( ConfigurationManager.AppSettings[ "WCFChatMaxMessageHistoryAge" ], out _maxChatHistoryMessageAge ) )
                {
                    ConfigurationManager.AppSettings.Add( "WCFChatMaxMessageHistoryAge", "3600" );
                }
            if ( ConfigurationManager.AppSettings[ "WCFChatMaxMessageHistoryCount" ] != null )
                if ( !int.TryParse( ConfigurationManager.AppSettings[ "WCFChatMaxMessageHistoryCount" ], out _maxChatHistoryMessageCount ) )
                {
                    ConfigurationManager.AppSettings.Add( "WCFChatMaxMessageHistoryCount", "100" );
                }

            bool logPathSet = false;
            //Process the args
            foreach ( string arg in args )
            {
                string[ ] splitAtEquals = arg.Split( '=' );
                if ( splitAtEquals.Length > 1 )
                {
                    string argName = splitAtEquals[ 0 ];
                    string argValue = splitAtEquals[ 1 ];

                    string lowerCaseArgument = argName.ToLower( );
                    if ( lowerCaseArgument.Equals( "instance" ) )
                    {
                        if ( argValue[ argValue.Length - 1 ] == '"' )
                            argValue = argValue.Substring( 1, argValue.Length - 2 );
                        extenderArgs.InstanceName = argValue;

                        //Only let this override log path if the log path wasn't already explicitly set
                        if ( !logPathSet )
                        {
                            FileTarget baseLogTarget = LogManager.Configuration.FindTargetByName( "BaseLog" ) as FileTarget;
                            if ( baseLogTarget != null )
                            {
                                baseLogTarget.FileName = baseLogTarget.FileName.Render( new LogEventInfo { TimeStamp = DateTime.Now } ).Replace( "NoInstance", argValue );
                            }
                            FileTarget chatLogTarget = LogManager.Configuration.FindTargetByName( "ChatLog" ) as FileTarget;
                            if ( chatLogTarget != null )
                            {
                                chatLogTarget.FileName = chatLogTarget.FileName.Render( new LogEventInfo { TimeStamp = DateTime.Now } ).Replace( "NoInstance", argValue );
                            }
                            FileTarget pluginLogTarget = LogManager.Configuration.FindTargetByName( "PluginLog" ) as FileTarget;
                            if ( pluginLogTarget != null )
                            {
                                pluginLogTarget.FileName = pluginLogTarget.FileName.Render( new LogEventInfo { TimeStamp = DateTime.Now } ).Replace( "NoInstance", argValue );
                            }
                        }
                    }
                    else if ( lowerCaseArgument.Equals( "gamepath" ) )
                    {
                        if ( argValue[ argValue.Length - 1 ] == '"' )
                            argValue = argValue.Substring( 1, argValue.Length - 2 );
                        extenderArgs.GamePath = argValue;
                    }
                    else if ( lowerCaseArgument.Equals( "autosave" ) )
                    {
                        if ( !int.TryParse( argValue, out extenderArgs.Autosave ) )
                            BaseLog.Warn( "Autosave parameter was not a valid integer." );
                    }
                    else if ( lowerCaseArgument.Equals( "path" ) )
                    {
                        if ( argValue[ argValue.Length - 1 ] == '"' )
                            argValue = argValue.Substring( 1, argValue.Length - 2 );
                        extenderArgs.InstancePath = argValue;
                    }
                    else if ( lowerCaseArgument.Equals( "instancepath" ) )
                    {
                        if ( argValue[ argValue.Length - 1 ] == '"' )
                            argValue = argValue.Substring( 1, argValue.Length - 2 );
                        extenderArgs.InstancePath = argValue;
                    }
                    else if (lowerCaseArgument.Equals("title") )
                    {
                        if (argValue[argValue.Length - 1] == '"')
                            argValue = argValue.Substring(1, argValue.Length - 2);
                        extenderArgs.ConsoleTitle = argValue;
                    }
                    else if ( lowerCaseArgument == "logpath" )
                    {
                        if ( argValue[ argValue.Length - 1 ] == '"' )
                            argValue = argValue.Substring( 1, argValue.Length - 2 );

                        //This argument always prevails.
                        FileTarget baseLogTarget = LogManager.Configuration.FindTargetByName( "BaseLog" ) as FileTarget;
                        if ( baseLogTarget != null )
                        {
                            Layout l = new SimpleLayout( Path.Combine( argValue, "SEServerExtenderLog-${shortdate}.log" ) );
                            baseLogTarget.FileName = l.Render( new LogEventInfo { TimeStamp = DateTime.Now } );
                            ApplicationLog.BaseLog = BaseLog;
                        }
                        FileTarget chatLogTarget = LogManager.Configuration.FindTargetByName( "ChatLog" ) as FileTarget;
                        if ( chatLogTarget != null )
                        {
                            Layout l = new SimpleLayout( Path.Combine( argValue, "ChatLog-${shortdate}.log" ) );
                            chatLogTarget.FileName = l.Render( new LogEventInfo { TimeStamp = DateTime.Now } );
                            ApplicationLog.ChatLog = ChatLog;
                        }
                        FileTarget pluginLogTarget = LogManager.Configuration.FindTargetByName( "PluginLog" ) as FileTarget;
                        if ( pluginLogTarget != null )
                        {
                            Layout l = new SimpleLayout( Path.Combine( argValue, "PluginLog-${shortdate}.log" ) );
                            pluginLogTarget.FileName = l.Render( new LogEventInfo { TimeStamp = DateTime.Now } );
                            logPathSet = true;
                            ApplicationLog.PluginLog = PluginLog;
                        }

                    }
                }
                else
                {
                    string lowerCaseArgument = arg.ToLower( );
                    if ( lowerCaseArgument.Equals( "autostart" ) )
                    {
                        extenderArgs.AutoStart = true;
                    }
                    else if ( lowerCaseArgument.Equals( "nogui" ) )
                    {
                        extenderArgs.NoGui = true;

                        //Implies autostart
                        //extenderArgs.AutoStart = true;
                    }
                    else if ( lowerCaseArgument.Equals( "noconsole" ) )
                    {
                        extenderArgs.NoConsole = true;

                        //Implies nogui and autostart
                        extenderArgs.NoGui = true;
                        extenderArgs.AutoStart = true;
                    }
                    else if ( lowerCaseArgument.Equals( "debug" ) )
                    {
                        extenderArgs.Debug = true;
                    }
                    else if ( lowerCaseArgument.Equals( "nowcf" ) )
                    {
                        extenderArgs.NoWcf = true;
                    }
                    else if ( lowerCaseArgument.Equals( "closeoncrash" ) )
                    {
                        extenderArgs.CloseOnCrash = true;
                    }
                    else if ( lowerCaseArgument.Equals( "autosaveasync" ) )
                    {
                        extenderArgs.AutoSaveSync = false;
                    }
                    else if ( lowerCaseArgument.Equals( "autosavesync" ) )
                    {
                        extenderArgs.AutoSaveSync = true;
                    }
                    else if ( lowerCaseArgument.Equals( "restartoncrash" ) )
                    {
                        extenderArgs.RestartOnCrash = true;
                    }
                    else if ( lowerCaseArgument.Equals( "wrr" ) )
                    {
                        extenderArgs.WorldRequestReplace = true;
                    }
                    else if ( lowerCaseArgument.Equals( "wrm" ) )
                    {
                        extenderArgs.WorldDataModify = true;
                    }
                    else if (lowerCaseArgument.Equals("wvm"))
                    {
                        extenderArgs.WorldVoxelModify = true;
                    }
                }
            }

            if ( !Environment.UserInteractive )
            {
                extenderArgs.NoConsole = true;
                extenderArgs.NoGui = true;
                extenderArgs.AutoStart = true;
            }

            if ( extenderArgs.Debug )
                ExtenderOptions.IsDebugging = true;

            try
            {
                bool unitTestResult = BasicUnitTestManager.Instance.Run( );
                if ( !unitTestResult )
                    ExtenderOptions.IsInSafeMode = true;

                Server = Server.Instance;
                Server.CommandLineArgs = extenderArgs;
                Server.IsWCFEnabled = !extenderArgs.NoWcf;
                Server.Init( );

                ChatManager.ChatCommand guiCommand = new ChatManager.ChatCommand( "gui", ChatCommand_GUI, false );
                ChatManager.Instance.RegisterChatCommand( guiCommand );

                if (string.IsNullOrEmpty (extenderArgs.ConsoleTitle) || string.IsNullOrWhiteSpace(extenderArgs.ConsoleTitle))
                {
                    Console.Title = "SESE";
                }
                else
                {
                    Console.Title = extenderArgs.ConsoleTitle;
                }

                if ( extenderArgs.AutoStart )
                {
                    Server.StartServer( );
                }

                if ( !extenderArgs.NoWcf )
                {
                    string uriString = string.Format( "{0}{1}", ConfigurationManager.AppSettings[ "WCFServerServiceBaseAddress" ], CommandLineArgs.InstanceName );
                    BaseLog.Info( "Opening up WCF service listener at {0}", uriString );
                    ServerServiceHost = new ServiceHost( typeof( ServerService.ServerService ), new Uri( uriString, UriKind.Absolute ) );
                    ServerServiceHost.Open( );
                    ChatManager.Instance.ChatMessage += ChatManager_ChatMessage;
                }

                if ( !extenderArgs.NoGui )
                {
                    Thread uiThread = new Thread( StartGui );
                    uiThread.SetApartmentState( ApartmentState.STA );
                    uiThread.Start( );
                }
                else if ( Environment.UserInteractive )
                    Console.ReadLine( );

            }
            catch ( AutoException eEx )
            {
                if ( !extenderArgs.NoConsole )
                    BaseLog.Info( "AutoException - {0}\n\r{1}", eEx.AdditionnalInfo, eEx.GetDebugString( ) );
                if ( !extenderArgs.NoGui )
                    MessageBox.Show( string.Format( "{0}\n\r{1}", eEx.AdditionnalInfo, eEx.GetDebugString( ) ), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error );

                if ( extenderArgs.NoConsole && extenderArgs.NoGui )
                    throw eEx.GetBaseException( );
            }
            catch ( TargetInvocationException ex )
            {
                if ( !extenderArgs.NoConsole )
                    BaseLog.Info( "TargetInvocationException - {0}\n\r{1}", ex, ex.InnerException );
                if ( !extenderArgs.NoGui )
                    MessageBox.Show( string.Format( "{0}\n\r{1}", ex, ex.InnerException ), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error );

                if ( extenderArgs.NoConsole && extenderArgs.NoGui )
                    throw;
            }
            catch ( Exception ex )
            {
                if ( !extenderArgs.NoConsole )
                    BaseLog.Info( ex, "Exception - {0}", ex );
                if ( !extenderArgs.NoGui )
                    MessageBox.Show( ex.ToString( ), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error );

                if ( extenderArgs.NoConsole && extenderArgs.NoGui )
                    throw;
            }
        }
예제 #2
0
		private static void Start( string[ ] args )
		{
			//Setup error handling for unmanaged exceptions
			AppDomain.CurrentDomain.UnhandledException += AppDomain_UnhandledException;
			Application.ThreadException += Application_ThreadException;
			Application.SetUnhandledExceptionMode( UnhandledExceptionMode.CatchException );

			//AppDomain.CurrentDomain.ClearEventInvocations("_unhandledException");

			LogManager.APILog.WriteLine( string.Format( "Starting SEServerExtender with {0} arguments ...", args.Length ) );

			CommandLineArgs extenderArgs = new CommandLineArgs
										   {
											   AutoStart = false,
											   WorldName = string.Empty,
											   InstanceName = string.Empty,
											   NoGui = false,
											   NoConsole = false,
											   Debug = false,
											   GamePath = string.Empty,
											   NoWcf = false,
											   Autosave = 0,
											   WcfPort = 0,
											   Path = string.Empty,
											   CloseOnCrash = false,
											   RestartOnCrash = false,
											   Args = string.Join( " ", args.Select( x => string.Format( "\"{0}\"", x ) ) )
										   };

			//Setup the default args

			//Process the args
			foreach ( string arg in args )
			{
				if ( arg.Split( '=' ).Length > 1 )
				{
					string argName = arg.Split( '=' )[ 0 ];
					string argValue = arg.Split( '=' )[ 1 ];

					if ( argName.ToLower( ).Equals( "instance" ) )
					{
						if ( argValue[ argValue.Length - 1 ] == '"' )
							argValue = argValue.Substring( 0, argValue.Length - 1 );
						extenderArgs.InstanceName = argValue;
					}
					else if ( argName.ToLower( ).Equals( "gamepath" ) )
					{
						if ( argValue[ argValue.Length - 1 ] == '"' )
							argValue = argValue.Substring( 0, argValue.Length - 1 );
						extenderArgs.GamePath = argValue;
					}
					else if ( argName.ToLower( ).Equals( "autosave" ) )
					{
						try
						{
							extenderArgs.Autosave = int.Parse( argValue );
						}
						catch
						{
							//Do nothing
						}
					}
					else if ( argName.ToLower( ).Equals( "wcfport" ) )
					{
						try
						{
							extenderArgs.WcfPort = ushort.Parse( argValue );
						}
						catch
						{
							//Do nothing
						}
					}
					else if ( argName.ToLower( ).Equals( "path" ) )
					{
						if ( argValue[ argValue.Length - 1 ] == '"' )
							argValue = argValue.Substring( 0, argValue.Length - 1 );
						extenderArgs.Path = argValue;
					}
				}
				else
				{
					if ( arg.ToLower( ).Equals( "autostart" ) )
					{
						extenderArgs.AutoStart = true;
					}
					if ( arg.ToLower( ).Equals( "nogui" ) )
					{
						extenderArgs.NoGui = true;

						//Implies autostart
						extenderArgs.AutoStart = true;
					}
					if ( arg.ToLower( ).Equals( "noconsole" ) )
					{
						extenderArgs.NoConsole = true;

						//Implies nogui and autostart
						extenderArgs.NoGui = true;
						extenderArgs.AutoStart = true;
					}
					if ( arg.ToLower( ).Equals( "debug" ) )
					{
						extenderArgs.Debug = true;
					}
					if ( arg.ToLower( ).Equals( "nowcf" ) )
					{
						extenderArgs.NoWcf = true;
					}
					if ( arg.ToLower( ).Equals( "closeoncrash" ) )
					{
						extenderArgs.CloseOnCrash = true;
					}
					if ( arg.ToLower( ).Equals( "autosaveasync" ) )
					{
						extenderArgs.AutoSaveSync = false;
					}
					if ( arg.ToLower( ).Equals( "autosavesync" ) )
					{
						extenderArgs.AutoSaveSync = true;
					}
					if ( arg.ToLower( ).Equals( "restartoncrash" ) )
					{
						extenderArgs.RestartOnCrash = true;
					}
					if ( arg.ToLower( ).Equals( "wrr" ) )
					{
						extenderArgs.WorldRequestReplace = true;
					}
					if ( arg.ToLower( ).Equals( "wrm" ) )
					{
						extenderArgs.WorldDataModify = true;
					}
				}
			}

			if ( extenderArgs.NoWcf )
				extenderArgs.WcfPort = 0;

			if ( !string.IsNullOrEmpty( extenderArgs.Path ) )
			{
				extenderArgs.InstanceName = string.Empty;
			}

			if ( !Environment.UserInteractive )
			{
				extenderArgs.NoConsole = true;
				extenderArgs.NoGui = true;
				extenderArgs.AutoStart = true;
			}

			if ( extenderArgs.Debug )
				SandboxGameAssemblyWrapper.IsDebugging = true;

			try
			{
				bool unitTestResult = BasicUnitTestManager.Instance.Run( );
				if ( !unitTestResult )
					SandboxGameAssemblyWrapper.IsInSafeMode = true;

				_server = Server.Instance;
				_server.CommandLineArgs = extenderArgs;
				_server.IsWCFEnabled = !extenderArgs.NoWcf;
				_server.WCFPort = extenderArgs.WcfPort;
				_server.Init( );

				ChatManager.ChatCommand guiCommand = new ChatManager.ChatCommand { Command = "gui", Callback = ChatCommand_GUI };
				ChatManager.Instance.RegisterChatCommand( guiCommand );

				if ( extenderArgs.AutoStart )
				{
					_server.StartServer( );
				}

				if ( !extenderArgs.NoGui )
				{
					Thread uiThread = new Thread( StartGui );
					uiThread.SetApartmentState( ApartmentState.STA );
					uiThread.Start( );
				}
				else if ( Environment.UserInteractive )
					Console.ReadLine( );
			}
			catch ( AutoException eEx )
			{
				if ( !extenderArgs.NoConsole )
					Console.WriteLine( "AutoException - {0}\n\r{1}", eEx.AdditionnalInfo, eEx.GetDebugString( ) );
				if ( !extenderArgs.NoGui )
					MessageBox.Show( string.Format( "{0}\n\r{1}", eEx.AdditionnalInfo, eEx.GetDebugString( ) ), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error );

				if ( extenderArgs.NoConsole && extenderArgs.NoGui )
					throw eEx.GetBaseException( );
			}
			catch ( TargetInvocationException ex )
			{
				if ( !extenderArgs.NoConsole )
					Console.WriteLine( "TargetInvocationException - {0}\n\r{1}", ex, ex.InnerException );
				if ( !extenderArgs.NoGui )
					MessageBox.Show( string.Format( "{0}\n\r{1}", ex, ex.InnerException ), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error );

				if ( extenderArgs.NoConsole && extenderArgs.NoGui )
					throw;
			}
			catch ( Exception ex )
			{
				if ( !extenderArgs.NoConsole )
					Console.WriteLine( "Exception - {0}", ex );
				if ( !extenderArgs.NoGui )
					MessageBox.Show( ex.ToString( ), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error );

				if ( extenderArgs.NoConsole && extenderArgs.NoGui )
					throw;
			}
		}
예제 #3
0
        static void Main(string[] args)
        {
            //Setup error handling for unmanaged exceptions
            AppDomain.CurrentDomain.UnhandledException += AppDomain_UnhandledException;
            Application.ThreadException += Application_ThreadException;
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            CommandLineArgs extenderArgs = new CommandLineArgs();

            //Setup the default args
            extenderArgs.autoStart = false;
            extenderArgs.worldName = "";
            extenderArgs.instanceName = "";
            extenderArgs.noGUI = false;
            extenderArgs.noConsole = false;
            extenderArgs.debug = false;
            extenderArgs.gamePath = "";
            extenderArgs.noWCF = false;
            extenderArgs.autosave = 0;
            extenderArgs.wcfPort = 0;
            extenderArgs.path = "";

            //Process the args
            foreach (string arg in args)
            {
                if (arg.Split('=').Length > 1)
                {
                    string argName = arg.Split('=')[0];
                    string argValue = arg.Split('=')[1];

                    Console.WriteLine("Name-Value Arg: name='" + argName + "' value='" + argValue + "'");

                    if (argName.ToLower().Equals("instance"))
                    {
                        if (argValue[argValue.Length - 1] == '"')
                            argValue = argValue.Substring(0, argValue.Length - 1);
                        extenderArgs.instanceName = argValue;
                    }
                    if (argName.ToLower().Equals("gamepath"))
                    {
                        if (argValue[argValue.Length - 1] == '"')
                            argValue = argValue.Substring(0, argValue.Length - 1);
                        extenderArgs.gamePath = argValue;
                    }
                    if (argName.ToLower().Equals("autosave"))
                    {
                        try
                        {
                            extenderArgs.autosave = int.Parse(argValue);
                        }
                        catch (Exception)
                        {
                            //Do nothing
                        }
                    }
                    if (argName.ToLower().Equals("wcfport"))
                    {
                        try
                        {
                            extenderArgs.wcfPort = ushort.Parse(argValue);
                        }
                        catch (Exception)
                        {
                            //Do nothing
                        }
                    }
                    if (argName.ToLower().Equals("path"))
                    {
                        if (argValue[argValue.Length - 1] == '"')
                            argValue = argValue.Substring(0, argValue.Length - 1);
                        extenderArgs.path = argValue;
                    }
                }
                else
                {
                    if (arg.ToLower().Equals("autostart"))
                    {
                        extenderArgs.autoStart = true;
                    }
                    if (arg.ToLower().Equals("nogui"))
                    {
                        extenderArgs.noGUI = true;

                        //Implies autostart
                        extenderArgs.autoStart = true;
                    }
                    if (arg.ToLower().Equals("noconsole"))
                    {
                        extenderArgs.noConsole = true;

                        //Implies nogui and autostart
                        extenderArgs.noGUI = true;
                        extenderArgs.autoStart = true;
                    }
                    if (arg.ToLower().Equals("debug"))
                    {
                        extenderArgs.debug = true;
                    }
                    if (arg.ToLower().Equals("nowcf"))
                    {
                        extenderArgs.noWCF = true;
                    }
                }
            }

            if (extenderArgs.noWCF)
                extenderArgs.wcfPort = 0;

            if (!string.IsNullOrEmpty(extenderArgs.path))
            {
                extenderArgs.instanceName = "";
            }

            if (!Environment.UserInteractive)
            {
                extenderArgs.noConsole = true;
                extenderArgs.noGUI = true;
            }

            if (extenderArgs.debug)
                SandboxGameAssemblyWrapper.IsDebugging = true;

            try
            {
                bool unitTestResult = BasicUnitTestManager.Instance.Run();
                if (!unitTestResult)
                    SandboxGameAssemblyWrapper.IsInSafeMode = true;

                m_server = Server.Instance;
                m_server.CommandLineArgs = extenderArgs;
                m_server.IsWCFEnabled = !extenderArgs.noWCF;
                m_server.Init();
                if (extenderArgs.autoStart)
                {
                    m_server.StartServer();
                }

                if (!extenderArgs.noGUI)
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    m_serverExtenderForm = new SEServerExtender(m_server);
                    Application.Run(m_serverExtenderForm);
                }
            }
            catch (AutoException eEx)
            {
                if(!extenderArgs.noConsole)
                    Console.WriteLine("AutoException - " + eEx.AdditionnalInfo + "\n\r" + eEx.GetDebugString());
                if (!extenderArgs.noGUI)
                    MessageBox.Show(eEx.AdditionnalInfo + "\n\r" + eEx.GetDebugString(), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error);

                if (extenderArgs.noConsole && extenderArgs.noGUI)
                    throw eEx.GetBaseException();
            }
            catch (TargetInvocationException ex)
            {
                if (!extenderArgs.noConsole)
                    Console.WriteLine("TargetInvocationException - " + ex.ToString() + "\n\r" + ex.InnerException.ToString());
                if (!extenderArgs.noGUI)
                    MessageBox.Show(ex.ToString() + "\n\r" + ex.InnerException.ToString(), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error);

                if (extenderArgs.noConsole && extenderArgs.noGUI)
                    throw ex;
            }
            catch (Exception ex)
            {
                if (!extenderArgs.noConsole)
                    Console.WriteLine("Exception - " + ex.ToString());
                if (!extenderArgs.noGUI)
                    MessageBox.Show(ex.ToString(), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error);

                if (extenderArgs.noConsole && extenderArgs.noGUI)
                    throw ex;
            }
        }
		private static void Start(string[] args)
		{
			//Setup error handling for unmanaged exceptions
			AppDomain.CurrentDomain.UnhandledException += AppDomain_UnhandledException;
			Application.ThreadException += Application_ThreadException;
			Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

			LogManager.APILog.WriteLine("Starting SEServerExtender with " + args.Length.ToString() + " arguments ...");

			CommandLineArgs extenderArgs = new CommandLineArgs();

			//Setup the default args
			extenderArgs.autoStart = false;
			extenderArgs.worldName = "";
			extenderArgs.instanceName = "";
			extenderArgs.noGUI = false;
			extenderArgs.noConsole = false;
			extenderArgs.debug = false;
			extenderArgs.gamePath = "";
			extenderArgs.noWCF = false;
			extenderArgs.autosave = 0;
			extenderArgs.wcfPort = 0;
			extenderArgs.path = "";

			//Process the args
			foreach (string arg in args)
			{
				if (arg.Split('=').Length > 1)
				{
					string argName = arg.Split('=')[0];
					string argValue = arg.Split('=')[1];

					if (argName.ToLower().Equals("instance"))
					{
						if (argValue[argValue.Length - 1] == '"')
							argValue = argValue.Substring(0, argValue.Length - 1);
						extenderArgs.instanceName = argValue;
					}
					else if (argName.ToLower().Equals("gamepath"))
					{
						if (argValue[argValue.Length - 1] == '"')
							argValue = argValue.Substring(0, argValue.Length - 1);
						extenderArgs.gamePath = argValue;
					}
					else if (argName.ToLower().Equals("autosave"))
					{
						try
						{
							extenderArgs.autosave = int.Parse(argValue);
						}
						catch (Exception)
						{
							//Do nothing
						}
					}
					else if (argName.ToLower().Equals("wcfport"))
					{
						try
						{
							extenderArgs.wcfPort = ushort.Parse(argValue);
						}
						catch (Exception)
						{
							//Do nothing
						}
					}
					else if (argName.ToLower().Equals("path"))
					{
						if (argValue[argValue.Length - 1] == '"')
							argValue = argValue.Substring(0, argValue.Length - 1);
						extenderArgs.path = argValue;
					}
				}
				else
				{
					if (arg.ToLower().Equals("autostart"))
					{
						extenderArgs.autoStart = true;
					}
					if (arg.ToLower().Equals("nogui"))
					{
						extenderArgs.noGUI = true;

						//Implies autostart
						extenderArgs.autoStart = true;
					}
					if (arg.ToLower().Equals("noconsole"))
					{
						extenderArgs.noConsole = true;

						//Implies nogui and autostart
						extenderArgs.noGUI = true;
						extenderArgs.autoStart = true;
					}
					if (arg.ToLower().Equals("debug"))
					{
						extenderArgs.debug = true;
					}
					if (arg.ToLower().Equals("nowcf"))
					{
						extenderArgs.noWCF = true;
					}
				}
			}

			if (extenderArgs.noWCF)
				extenderArgs.wcfPort = 0;

			if (!string.IsNullOrEmpty(extenderArgs.path))
			{
				extenderArgs.instanceName = "";
			}

			if (!Environment.UserInteractive)
			{
				extenderArgs.noConsole = true;
				extenderArgs.noGUI = true;
				extenderArgs.autoStart = true;
			}

			if (extenderArgs.debug)
				SandboxGameAssemblyWrapper.IsDebugging = true;

			try
			{
				bool unitTestResult = BasicUnitTestManager.Instance.Run();
				if (!unitTestResult)
					SandboxGameAssemblyWrapper.IsInSafeMode = true;

				m_server = Server.Instance;
				m_server.CommandLineArgs = extenderArgs;
				m_server.IsWCFEnabled = !extenderArgs.noWCF;
				m_server.WCFPort = extenderArgs.wcfPort;
				m_server.Init();

				ChatManager.ChatCommand guiCommand = new ChatManager.ChatCommand();
				guiCommand.command = "gui";
				guiCommand.callback = ChatCommand_GUI;
				ChatManager.Instance.RegisterChatCommand(guiCommand);

				if (extenderArgs.autoStart)
				{
					m_server.StartServer();
				}

				if (!extenderArgs.noGUI)
				{
					Thread uiThread = new Thread(new ThreadStart(StartGUI));
					uiThread.SetApartmentState(ApartmentState.STA);
					uiThread.Start();
				}
			}
			catch (AutoException eEx)
			{
				if (!extenderArgs.noConsole)
					Console.WriteLine("AutoException - " + eEx.AdditionnalInfo + "\n\r" + eEx.GetDebugString());
				if (!extenderArgs.noGUI)
					MessageBox.Show(eEx.AdditionnalInfo + "\n\r" + eEx.GetDebugString(), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error);

				if (extenderArgs.noConsole && extenderArgs.noGUI)
					throw eEx.GetBaseException();
			}
			catch (TargetInvocationException ex)
			{
				if (!extenderArgs.noConsole)
					Console.WriteLine("TargetInvocationException - " + ex.ToString() + "\n\r" + ex.InnerException.ToString());
				if (!extenderArgs.noGUI)
					MessageBox.Show(ex.ToString() + "\n\r" + ex.InnerException.ToString(), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error);

				if (extenderArgs.noConsole && extenderArgs.noGUI)
					throw ex;
			}
			catch (Exception ex)
			{
				if (!extenderArgs.noConsole)
					Console.WriteLine("Exception - " + ex.ToString());
				if (!extenderArgs.noGUI)
					MessageBox.Show(ex.ToString(), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error);

				if (extenderArgs.noConsole && extenderArgs.noGUI)
					throw ex;
			}
		}
예제 #5
0
        private static void Start( string[ ] args )
        {
            // SE_VERSION is a private constant. Need to use reflection to get it.
            FieldInfo field = typeof(SpaceEngineersGame).GetField("SE_VERSION", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);

            SeVersion = new Version(new MyVersion((int)field.GetValue(null)).FormattedText.ToString().Replace("_", "."));

            bool stableBuild = (bool)typeof(MyFinalBuildConstants).GetField("IS_STABLE").GetValue(null);

            ApplicationLog.BaseLog.Info($"SE version: {SeVersion}");
            ApplicationLog.BaseLog.Info( $"Extender version: {Assembly.GetExecutingAssembly().GetName().Version}" );
            if (stableBuild)
            {
                BaseLog.Info("Detected \"Stable\" branch!");
                IsStable = true;
                PluginManager.IsStable = true;

                //hide the block limit config, since it will crash in stable
                HideConfigs();
            }
            else
                BaseLog.Info("Detected \"Development\" branch!");

            InitSandbox(Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory + @"..\Content"), Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SpaceEngineers"));

            //Setup error handling for unmanaged exceptions
            AppDomain.CurrentDomain.UnhandledException += AppDomain_UnhandledException;
            Application.ThreadException += Application_ThreadException;
            Application.SetUnhandledExceptionMode( UnhandledExceptionMode.CatchException );

            //AppDomain.CurrentDomain.ClearEventInvocations("_unhandledException");

            BaseLog.Info( "Starting SEServerExtender with {0} arguments: {1}", args.Length, string.Join( "\r\n\t", args ) );

            CommandLineArgs extenderArgs = CommandLineArgs = new CommandLineArgs
                              {
                                  ConsoleTitle = string.Empty,
                                  AutoStart = false,
                                  WorldName = string.Empty,
                                  InstanceName = string.Empty,
                                  NoGui = false,
                                  NoConsole = false,
                                  Debug = false,
                                  GamePath = new DirectoryInfo( PathManager.BasePath ).Parent.FullName,
                                  //TODO: turn noWFC back to off by default whenever WCF gets fixed
                                  NoWcf = true,
                                  Autosave = 0,
                                  InstancePath = string.Empty,
                                  CloseOnCrash = false,
                                  RestartOnCrash = false,
                                  NoProfiler = false,
                                  Args = string.Join( " ", args.Select( x => string.Format( "\"{0}\"", x ) ) )
                              };

            if ( ConfigurationManager.AppSettings[ "WCFChatMaxMessageHistoryAge" ] != null )
                if ( !int.TryParse( ConfigurationManager.AppSettings[ "WCFChatMaxMessageHistoryAge" ], out _maxChatHistoryMessageAge ) )
                {
                    ConfigurationManager.AppSettings.Add( "WCFChatMaxMessageHistoryAge", "3600" );
                }
            if ( ConfigurationManager.AppSettings[ "WCFChatMaxMessageHistoryCount" ] != null )
                if ( !int.TryParse( ConfigurationManager.AppSettings[ "WCFChatMaxMessageHistoryCount" ], out _maxChatHistoryMessageCount ) )
                {
                    ConfigurationManager.AppSettings.Add( "WCFChatMaxMessageHistoryCount", "100" );
                }

            bool logPathSet = false;
            //Process the args
            foreach ( string arg in args )
            {
                string[ ] splitAtEquals = arg.Split( '=' );
                if ( splitAtEquals.Length > 1 )
                {
                    string argName = splitAtEquals[ 0 ];
                    string argValue = splitAtEquals[ 1 ];

                    string lowerCaseArgument = argName.ToLower( );
                    if ( lowerCaseArgument.Equals( "instance" ) )
                    {
                        if ( argValue[ argValue.Length - 1 ] == '"' )
                            argValue = argValue.Substring( 1, argValue.Length - 2 );
                        //sanitize input because stupid people put full paths for this argument
                        extenderArgs.InstanceName = argValue.Replace( @"\", "-" ).Replace( @":", "-" );

                        //Only let this override log path if the log path wasn't already explicitly set
                        if ( !logPathSet )
                        {
                            FileTarget baseLogTarget = LogManager.Configuration.FindTargetByName( "BaseLog" ) as FileTarget;
                            if ( baseLogTarget != null )
                            {
                                baseLogTarget.FileName = baseLogTarget.FileName.Render(new LogEventInfo { TimeStamp = DateTime.Now }).Replace("NoInstance", argValue.Replace(@"\", "-").Replace(@":", "-"));
                            }
                            FileTarget chatLogTarget = LogManager.Configuration.FindTargetByName( "ChatLog" ) as FileTarget;
                            if ( chatLogTarget != null )
                            {
                                chatLogTarget.FileName = chatLogTarget.FileName.Render(new LogEventInfo { TimeStamp = DateTime.Now }).Replace("NoInstance", argValue.Replace(@"\", "-").Replace(@":", "-"));
                            }
                            FileTarget pluginLogTarget = LogManager.Configuration.FindTargetByName( "PluginLog" ) as FileTarget;
                            if ( pluginLogTarget != null )
                            {
                                pluginLogTarget.FileName = pluginLogTarget.FileName.Render(new LogEventInfo { TimeStamp = DateTime.Now }).Replace("NoInstance", argValue.Replace(@"\", "-").Replace(@":", "-"));
                            }
                        }
                    }
                    else if ( lowerCaseArgument.Equals( "gamepath" ) )
                    {
                        if ( argValue[ argValue.Length - 1 ] == '"' )
                            argValue = argValue.Substring( 1, argValue.Length - 2 );
                        extenderArgs.GamePath = argValue;
                    }
                    else if ( lowerCaseArgument.Equals( "autosave" ) )
                    {
                        if ( !int.TryParse( argValue, out extenderArgs.Autosave ) )
                            BaseLog.Warn( "Autosave parameter was not a valid integer." );
                    }
                    else if ( lowerCaseArgument.Equals( "path" ) )
                    {
                        if ( argValue[ argValue.Length - 1 ] == '"' )
                            argValue = argValue.Substring( 1, argValue.Length - 2 );
                        extenderArgs.InstancePath = argValue;
                    }
                    else if ( lowerCaseArgument.Equals( "instancepath" ) )
                    {
                        if ( argValue[ argValue.Length - 1 ] == '"' )
                            argValue = argValue.Substring( 1, argValue.Length - 2 );
                        extenderArgs.InstancePath = argValue;
                    }
                    else if (lowerCaseArgument.Equals("title") )
                    {
                        if (argValue[argValue.Length - 1] == '"')
                            argValue = argValue.Substring(1, argValue.Length - 2);
                        extenderArgs.ConsoleTitle = argValue;
                    }
                    else if ( lowerCaseArgument == "logpath" )
                    {
                        if ( argValue[ argValue.Length - 1 ] == '"' )
                            argValue = argValue.Substring( 1, argValue.Length - 2 );

                        //This argument always prevails.
                        FileTarget baseLogTarget = LogManager.Configuration.FindTargetByName( "BaseLog" ) as FileTarget;
                        if ( baseLogTarget != null )
                        {
                            Layout l = new SimpleLayout( Path.Combine( argValue, "SEServerExtenderLog-${shortdate}.log" ) );
                            baseLogTarget.FileName = l.Render( new LogEventInfo { TimeStamp = DateTime.Now } );
                            ApplicationLog.BaseLog = BaseLog;
                        }
                        FileTarget chatLogTarget = LogManager.Configuration.FindTargetByName( "ChatLog" ) as FileTarget;
                        if ( chatLogTarget != null )
                        {
                            Layout l = new SimpleLayout( Path.Combine( argValue, "ChatLog-${shortdate}.log" ) );
                            chatLogTarget.FileName = l.Render( new LogEventInfo { TimeStamp = DateTime.Now } );
                            ApplicationLog.ChatLog = ChatLog;
                        }
                        FileTarget pluginLogTarget = LogManager.Configuration.FindTargetByName( "PluginLog" ) as FileTarget;
                        if ( pluginLogTarget != null )
                        {
                            Layout l = new SimpleLayout( Path.Combine( argValue, "PluginLog-${shortdate}.log" ) );
                            pluginLogTarget.FileName = l.Render( new LogEventInfo { TimeStamp = DateTime.Now } );
                            logPathSet = true;
                            ApplicationLog.PluginLog = PluginLog;
                        }

                    }
                }
                else
                {
                    string lowerCaseArgument = arg.ToLower( );
                    if ( lowerCaseArgument.Equals( "autostart" ) )
                    {
                        extenderArgs.AutoStart = true;
                    }
                    else if ( lowerCaseArgument.Equals( "nogui" ) )
                    {
                        extenderArgs.NoGui = true;

                        //Implies autostart
                        //extenderArgs.AutoStart = true;
                    }
                    else if ( lowerCaseArgument.Equals( "noconsole" ) )
                    {
                        extenderArgs.NoConsole = true;

                        //Implies nogui and autostart
                        extenderArgs.NoGui = true;
                        extenderArgs.AutoStart = true;
                    }
                    else if ( lowerCaseArgument.Equals( "debug" ) )
                    {
                        extenderArgs.Debug = true;
                    }
                    else if ( lowerCaseArgument.Equals( "nowcf" ) )
                    {
                        extenderArgs.NoWcf = true;
                    }
                    else if ( lowerCaseArgument.Equals( "wcfon" ) )
                    {
                        extenderArgs.NoWcf = false;
                    }
                    else if ( lowerCaseArgument.Equals( "closeoncrash" ) )
                    {
                        extenderArgs.CloseOnCrash = true;
                    }
                    else if ( lowerCaseArgument.Equals( "autosaveasync" ) )
                    {
                        extenderArgs.AutoSaveSync = false;
                    }
                    else if ( lowerCaseArgument.Equals( "autosavesync" ) )
                    {
                        extenderArgs.AutoSaveSync = true;
                    }
                    else if ( lowerCaseArgument.Equals( "restartoncrash" ) )
                    {
                        extenderArgs.RestartOnCrash = true;
                    }
                    else if (lowerCaseArgument.Equals("noprofiler") && !IsStable)
                    {
                        extenderArgs.NoProfiler = true;
                        Server.DisableProfiler = true;
                    }
                    //these things are legacy and don't work anyway
                    /*
                    else if ( lowerCaseArgument.Equals( "wrr" ) )
                    {
                        extenderArgs.WorldRequestReplace = true;
                    }
                    else if ( lowerCaseArgument.Equals( "wrm" ) )
                    {
                        extenderArgs.WorldDataModify = true;
                    }
                    else if (lowerCaseArgument.Equals("wvm"))
                    {
                        extenderArgs.WorldVoxelModify = true;
                    }
                    */
                }
            }

            if ( !Environment.UserInteractive )
            {
                extenderArgs.NoConsole = true;
                extenderArgs.NoGui = true;
                extenderArgs.AutoStart = true;
            }

            if ( extenderArgs.Debug )
                ExtenderOptions.IsDebugging = true;

            try
            {
                bool unitTestResult = BasicUnitTestManager.Instance.Run( );
                if ( !unitTestResult )
                    ExtenderOptions.IsInSafeMode = true;

                Server = Server.Instance;
                Server.CommandLineArgs = extenderArgs;
                Server.IsWCFEnabled = !extenderArgs.NoWcf;
                Server.Init( );

                //if(!DedicatedServerAssemblyWrapper.IsStable)
                //    InitSandbox(Path.Combine( GameInstallationInfo.GamePath, @"..\Content"), Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SpaceEngineers"));

                ChatManager.ChatCommand guiCommand = new ChatManager.ChatCommand( "gui", ChatCommand_GUI, false );
                ChatManager.Instance.RegisterChatCommand( guiCommand );

                if (!CommandLineArgs.NoConsole)
                {
                    if (string.IsNullOrEmpty(extenderArgs.ConsoleTitle) || string.IsNullOrWhiteSpace(extenderArgs.ConsoleTitle))
                    {
                        Console.Title = "SESE";
                    }
                    else
                    {
                        Console.Title = extenderArgs.ConsoleTitle;
                    }
                }

                if ( extenderArgs.AutoStart )
                {
                    Server.StartServer( );
                }

                if ( !extenderArgs.NoWcf )
                {
                    string uriString = string.Format( "{0}{1}", ConfigurationManager.AppSettings[ "WCFServerServiceBaseAddress" ], CommandLineArgs.InstanceName );
                    BaseLog.Info( "Opening up WCF service listener at {0}", uriString );
                    ServerServiceHost = new ServiceHost( typeof( ServerService.ServerService ), new Uri( uriString, UriKind.Absolute ) );
                    ServerServiceHost.Open( );
                    ChatManager.Instance.ChatMessage += ChatManager_ChatMessage;
                }

                if ( !extenderArgs.NoGui )
                {
                    Thread uiThread = new Thread( StartGui );
                    uiThread.SetApartmentState( ApartmentState.STA );
                    uiThread.Start( );
                }
                else if ( Environment.UserInteractive )
                    Console.ReadLine( );

            }
            catch ( AutoException eEx )
            {
                if ( !extenderArgs.NoConsole )
                    BaseLog.Info( "AutoException - {0}\n\r{1}", eEx.AdditionnalInfo, eEx.GetDebugString( ) );
                if ( !extenderArgs.NoGui )
                    MessageBox.Show( string.Format( "{0}\n\r{1}", eEx.AdditionnalInfo, eEx.GetDebugString( ) ), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error );

                if ( extenderArgs.NoConsole && extenderArgs.NoGui )
                    throw eEx.GetBaseException( );
            }
            catch ( TargetInvocationException ex )
            {
                if ( !extenderArgs.NoConsole )
                    BaseLog.Info( "TargetInvocationException - {0}\n\r{1}", ex, ex.InnerException );
                if ( !extenderArgs.NoGui )
                    MessageBox.Show( string.Format( "{0}\n\r{1}", ex, ex.InnerException ), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error );

                if ( extenderArgs.NoConsole && extenderArgs.NoGui )
                    throw;
            }
            catch ( Exception ex )
            {
                if ( !extenderArgs.NoConsole )
                    BaseLog.Info( ex, "Exception - {0}", ex );
                if ( !extenderArgs.NoGui )
                    MessageBox.Show( ex.ToString( ), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error );

                if ( extenderArgs.NoConsole && extenderArgs.NoGui )
                    throw;
            }
        }