Example #1
0
        public override void FinishedLaunching(NSObject notification)
        {
            // Configure logger
            string path = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "log4net.config");

            XmlConfigurator.ConfigureAndWatch(new FileInfo(path));
            logger.Info("Ventriliquest 1.0 Starting up...");

            // Get list of available audio out devices
            xamspeech ham = new xamspeech();

            OutputDevices = ham.GetDevices();

            // Setup UI
            statusMenu = new NSMenu();
            statusItem = NSStatusBar.SystemStatusBar.CreateStatusItem(30);

            var outputItem = new NSMenuItem("Output Device",
                                            (a, b) => {
            });

            var deviceList = new NSMenu();

            outputItem.Submenu = deviceList;

            OutputDeviceUID = "Built-in Output";

            foreach (var entry in OutputDevices)
            {
                var test = new NSMenuItem(entry.Key.ToString(),
                                          (a, b) => {
                    foreach (NSMenuItem item in deviceList.ItemArray())
                    {
                        item.State = NSCellStateValue.Off;
                    }
                    NSMenuItem theItem  = (NSMenuItem)a;
                    theItem.State       = NSCellStateValue.On;
                    config.OutputDevice = theItem.Title;
                    foreach (var e in OutputDevices)
                    {
                        if (e.Key.ToString().Equals(theItem.Title))
                        {
                            OutputDeviceUID = e.Value.ToString();
                        }
                    }
                });
                if (entry.Key.ToString().Equals(config.OutputDevice))
                {
                    test.State      = NSCellStateValue.On;
                    OutputDeviceUID = entry.Value.ToString();
                }
                deviceList.AddItem(test);
            }

            var daItem = new NSMenuItem("Local Connections Only",
                                        (a, b) => {
                NSMenuItem theItem = (NSMenuItem)a;
                if (theItem.State == NSCellStateValue.On)
                {
                    config.LocalOnly = false;
                    theItem.State    = NSCellStateValue.Off;
                }
                else
                {
                    config.LocalOnly = true;
                    theItem.State    = NSCellStateValue.On;
                }
            });

            if (config.LocalOnly)
            {
                daItem.State = NSCellStateValue.On;
            }

            var quitItem = new NSMenuItem("Quit",
                                          (a, b) => Shutdown());

            var voiceconfigItem = new NSMenuItem("Voice Configuration",
                                                 (a, b) => Process.Start("http://127.0.0.1:7888/config"));

            statusMenu.AddItem(new NSMenuItem("Version: 1.1"));
            statusMenu.AddItem(outputItem);
            statusMenu.AddItem(daItem);
            statusMenu.AddItem(voiceconfigItem);
            statusMenu.AddItem(quitItem);
            statusItem.Menu           = statusMenu;
            statusItem.Image          = NSImage.ImageNamed("tts-1.png");
            statusItem.AlternateImage = NSImage.ImageNamed("tts-2.png");
            statusItem.HighlightMode  = true;

            speechdelegate.DidComplete += delegate {
                synthesis.Set();
            };
            sounddelegate.DidComplete += delegate {
                playback.Set();
                IsSounding = false;
                IsSpeaking = false;
                sound.Dispose();
            };

            speech.Delegate = speechdelegate;

            queuetimer          = new System.Timers.Timer(250);
            queuetimer.Elapsed += (object sender, ElapsedEventArgs e) => {
                TTSRequest r;
                if (Queue.TryDequeue(out r))
                {
                    if (r.Interrupt)
                    {
                        // stop current TTS
                        NSApplication.SharedApplication.InvokeOnMainThread(delegate {
                            if (IsSpeaking)
                            {
                                speech.StopSpeaking();
                            }
                            if (IsSounding)
                            {
                                sound.Stop();
                            }
                        });
                        // clear queue
                        SpeechQueue.Clear();
                    }
                    if (!r.Reset)
                    {
                        SpeechQueue.Enqueue(r);
                    }
                    RequestCount++;
                }
                var eventdata = new Hashtable();
                eventdata.Add("ProcessedRequests", RequestCount);
                eventdata.Add("QueuedRequests", SpeechQueue.Count);
                eventdata.Add("IsSpeaking", IsSpeaking);
                InstrumentationEvent ev = new InstrumentationEvent();
                ev.EventName = "status";
                ev.Data      = eventdata;
                NotifyGui(ev.EventMessage());
            };

            // when this timer fires, it will pull off of the speech queue and speak it
            // the 1000ms delay also adds a little pause between tts requests.
            speechtimer          = new System.Timers.Timer(250);
            speechtimer.Elapsed += (object sender, ElapsedEventArgs e) => {
                if (IsSpeaking.Equals(false))
                {
                    if (SpeechQueue.Count > 0)
                    {
                        TTSRequest r = SpeechQueue.Dequeue();
                        IsSpeaking          = true;
                        speechtimer.Enabled = false;
                        var oink = Path.Combine(audiopath, "temp.aiff");
                        NSApplication.SharedApplication.InvokeOnMainThread(delegate {
                            ConfigureSpeechEngine(r);
                            speech.StartSpeakingStringtoURL(r.Text, new NSUrl(oink, false));
                        });
                        synthesis.WaitOne();
                        NSApplication.SharedApplication.InvokeOnMainThread(delegate {
                            IsSounding     = true;
                            sound          = new NSSound(Path.Combine(audiopath, "temp.aiff"), false);
                            sound.Delegate = sounddelegate;
                            //if(OutputDeviceUID != "Default") {
                            sound.PlaybackDeviceID = OutputDeviceUID;
                            //}
                            sound.Play();
                        });
                        playback.WaitOne();
                        IsSounding          = false;
                        speechtimer.Enabled = true;
                    }
                }
            };

            queuetimer.Enabled = true;
            queuetimer.Start();
            speechtimer.Enabled = true;
            speechtimer.Start();

            InitHTTPServer();
        }
Example #2
0
        static LogHelper()
        {
            var logCfg = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config");

            XmlConfigurator.ConfigureAndWatch(logCfg);
        }
Example #3
0
 private static void ConfigureLogging()
 {
     XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo($"{Application.dataPath}/Resources/log4netConfig.xml"));
 }
Example #4
0
        private static void InitLog4Net()
        {
            var logCfg = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config");

            XmlConfigurator.ConfigureAndWatch(logCfg);
        }
Example #5
0
        static void Main()
        {
            #region Logging
            var    versionInfo = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location);
            string logFolder   = string.Format(@"{0}\{1}\{2}\",
                                               Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
                                               versionInfo.CompanyName,
                                               versionInfo.ProductName);

            string LogFileName       = Application.ProductName + ".log";
            string LogConfigFileName = Application.ProductName + "-log.xml";

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

            if (!logFolder.EndsWith(Path.DirectorySeparatorChar.ToString()))
            {
                logFolder += Path.DirectorySeparatorChar;
            }

            if (!File.Exists(logFolder + LogConfigFileName))
            {
                XmlDocument logConfig = new XmlDocument();

                logConfig.InnerXml = LogFileDefinition(logFolder + "log" + Path.DirectorySeparatorChar,
                                                       LogFileName, "debug");
                logConfig.Save(logFolder + LogConfigFileName);
            } //if (!File.Exists(logFolder + Constants.LogConfigFileName))

            XmlConfigurator.ConfigureAndWatch(new FileInfo(logFolder + Path.DirectorySeparatorChar + LogConfigFileName));
            log.Debug("Logging configured");
            #endregion
            #region ConfigurationSources
            //Create Configuration Sources for app.config, and CommonAppDataPath and UserAppDataPath for the Solution
            IConfiguration conf = ConfigurationRepository.IConfiguration;
            conf.AddConfigurationSource(new IConfigurationSourceImpl(eConfigurationSource.AppConfig));
            conf.AddConfigurationSource(new IConfigurationSourceImpl(eConfigurationSource.UserAppData));
            #endregion

            #region Managed Extensible Framework
            ProgramFolder    = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar;
            DataSourceFolder = ProgramFolder + "data-sources" + Path.DirectorySeparatorChar;

            if (Directory.Exists(DataSourceFolder))
            {
                Catalog = new DirectoryCatalog(DataSourceFolder);
                var catalog = new AggregateCatalog(
                    new AssemblyCatalog(Assembly.GetExecutingAssembly()),
                    new DirectoryCatalog(ProgramFolder),
                    Catalog);

                Container = new CompositionContainer(catalog);
            }
            else
            {
                var catalog = new AggregateCatalog(
                    new AssemblyCatalog(Assembly.GetExecutingAssembly()),
                    new DirectoryCatalog(ProgramFolder));

                Container = new CompositionContainer(catalog);
            }
            #endregion

            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(MainForm.ThreadException);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(MainForm.UnhandledException);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //Bootstrap managed extensible framework
            MainForm mainForm = Container.GetExportedValue <MainForm>();
            Application.Run(mainForm);
        }
Example #6
0
 internal static void ConfigLogger()
 {
     XmlConfigurator.ConfigureAndWatch(new FileInfo(AppDomain.CurrentDomain.BaseDirectory + Log4NetConfigFileName));
     Logger.Log = LogManager.GetLogger("AppLogger");
 }
Example #7
0
 private static void LoadConfig()
 {
     //// TODO: Do exception handling for File access issues and supply sane defaults if it's unavailable.
     XmlConfigurator.ConfigureAndWatch(new FileInfo(LOG_CONFIG_FILE));
 }
Example #8
0
 private static void initialize()
 {
     XmlConfigurator.ConfigureAndWatch(new FileInfo(getConfigFilePath()));
 }
Example #9
0
 protected override void OnStart()
 {
     XmlConfigurator.ConfigureAndWatch(new FileInfo(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "log4net.config"));
     Tool.AppLogInfo("启动主程序");
 }
Example #10
0
 /// <summary>
 /// 启动logger
 /// </summary>
 /// <param name="repository">repository名称</param>
 /// <param name="fileName">配置文件名称</param>
 public static void StartLogger(string repository, string fileName)
 {
     _loggerRepository = LogManager.CreateRepository(repository);
     XmlConfigurator.ConfigureAndWatch(_loggerRepository, new FileInfo(fileName));
 }
Example #11
0
 /// <summary>
 /// 启动logger
 /// </summary>
 public static void StartLogger()
 {
     _loggerRepository = LogManager.CreateRepository(nameof(MyLogManager));
     XmlConfigurator.ConfigureAndWatch(_loggerRepository, new FileInfo("log4net.config"));
 }
Example #12
0
 public Logging()
 {
     LogManager.GetRepository().LevelMap.Add(AuditoriaLevel);
     XmlConfigurator.ConfigureAndWatch(GetNameFileConfig());
 }
Example #13
0
        /// <summary>
        /// Load the config file. This method should be called before using LoggerManager.
        /// Only need to be call once.
        /// </summary>
        /// <param name="filePath">The path of the config file.</param>
        public static void Initialize(string filePath)
        {
            FileInfo fileInfo = new FileInfo(Environment.CurrentDirectory + filePath);

            XmlConfigurator.ConfigureAndWatch(Log4netLoggerManager.GetRepository(Assembly.GetExecutingAssembly()), fileInfo);
        }
        public Log4NetLoggerFactory(string configFile)
        {
            FileInfo file = new FileInfo(configFile);

            XmlConfigurator.ConfigureAndWatch(file);
        }
Example #15
0
        public static void Main(string[] args)
        {
            var consoleTitle = $"ACEmulator - v{ServerBuildInfo.FullVersion}";

            Console.Title = consoleTitle;

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            AppDomain.CurrentDomain.ProcessExit        += new EventHandler(OnProcessExit);

            // Typically, you wouldn't force the current culture on an entire application unless you know sure your application is used in a specific region (which ACE is not)
            // We do this because almost all of the client/user input/output code does not take culture into account, and assumes en-US formatting.
            // Without this, many commands that require special characters like , and . will break
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            // Init our text encoding options. This will allow us to use more than standard ANSI text, which the client also supports.
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

            // Look for the log4net.config first in the current environment directory, then in the ExecutingAssembly location
            var exeLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var containerConfigDirectory = "/ace/Config";
            var log4netConfig            = Path.Combine(exeLocation, "log4net.config");
            var log4netConfigExample     = Path.Combine(exeLocation, "log4net.config.example");
            var log4netConfigContainer   = Path.Combine(containerConfigDirectory, "log4net.config");

            if (IsRunningInContainer && File.Exists(log4netConfigContainer))
            {
                File.Copy(log4netConfigContainer, log4netConfig, true);
            }

            var log4netFileInfo = new FileInfo("log4net.config");

            if (!log4netFileInfo.Exists)
            {
                log4netFileInfo = new FileInfo(log4netConfig);
            }

            if (!log4netFileInfo.Exists)
            {
                var exampleFile = new FileInfo(log4netConfigExample);
                if (!exampleFile.Exists)
                {
                    Console.WriteLine("log4net Configuration file is missing.  Please copy the file log4net.config.example to log4net.config and edit it to match your needs before running ACE.");
                    throw new Exception("missing log4net configuration file");
                }
                else
                {
                    if (!IsRunningInContainer)
                    {
                        Console.WriteLine("log4net Configuration file is missing,  cloning from example file.");
                        File.Copy(log4netConfigExample, log4netConfig);
                    }
                    else
                    {
                        if (!File.Exists(log4netConfigContainer))
                        {
                            Console.WriteLine("log4net Configuration file is missing, ACEmulator is running in a container,  cloning from docker file.");
                            var log4netConfigDocker = Path.Combine(exeLocation, "log4net.config.docker");
                            File.Copy(log4netConfigDocker, log4netConfig);
                            File.Copy(log4netConfigDocker, log4netConfigContainer);
                        }
                        else
                        {
                            File.Copy(log4netConfigContainer, log4netConfig);
                        }
                    }
                }
            }

            var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());

            XmlConfigurator.ConfigureAndWatch(logRepository, log4netFileInfo);

            if (Environment.ProcessorCount < 2)
            {
                log.Warn("Only one vCPU was detected. ACE may run with limited performance. You should increase your vCPU count for anything more than a single player server.");
            }

            // Do system specific initializations here
            try
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    // On many windows systems, the default resolution for Thread.Sleep is 15.6ms. This allows us to command a tighter resolution
                    MM_BeginPeriod(1);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.ToString());
            }

            log.Info("Starting ACEmulator...");

            if (IsRunningInContainer)
            {
                log.Info("ACEmulator is running in a container...");
            }

            var configFile            = Path.Combine(exeLocation, "Config.js");
            var configConfigContainer = Path.Combine(containerConfigDirectory, "Config.js");

            if (IsRunningInContainer && File.Exists(configConfigContainer))
            {
                File.Copy(configConfigContainer, configFile, true);
            }

            if (!File.Exists(configFile))
            {
                if (!IsRunningInContainer)
                {
                    DoOutOfBoxSetup(configFile);
                }
                else
                {
                    if (!File.Exists(configConfigContainer))
                    {
                        DoOutOfBoxSetup(configFile);
                        File.Copy(configFile, configConfigContainer);
                    }
                    else
                    {
                        File.Copy(configConfigContainer, configFile);
                    }
                }
            }

            log.Info("Initializing ConfigManager...");
            ConfigManager.Initialize();

            if (ConfigManager.Config.Server.WorldName != "ACEmulator")
            {
                consoleTitle  = $"{ConfigManager.Config.Server.WorldName} | {consoleTitle}";
                Console.Title = consoleTitle;
            }

            if (ConfigManager.Config.Offline.PurgeDeletedCharacters)
            {
                log.Info($"Purging deleted characters, and their possessions, older than {ConfigManager.Config.Offline.PurgeDeletedCharactersDays} days ({DateTime.Now.AddDays(-ConfigManager.Config.Offline.PurgeDeletedCharactersDays)})...");
                ShardDatabaseOfflineTools.PurgeCharactersInParallel(ConfigManager.Config.Offline.PurgeDeletedCharactersDays, out var charactersPurged, out var playerBiotasPurged, out var possessionsPurged);
                log.Info($"Purged {charactersPurged:N0} characters, {playerBiotasPurged:N0} player biotas and {possessionsPurged:N0} possessions.");
            }

            if (ConfigManager.Config.Offline.PurgeOrphanedBiotas)
            {
                log.Info($"Purging orphaned biotas...");
                ShardDatabaseOfflineTools.PurgeOrphanedBiotasInParallel(out var numberOfBiotasPurged);
                log.Info($"Purged {numberOfBiotasPurged:N0} biotas.");
            }

            if (ConfigManager.Config.Offline.PruneDeletedCharactersFromFriendLists)
            {
                log.Info($"Pruning invalid friends from all friend lists...");
                ShardDatabaseOfflineTools.PruneDeletedCharactersFromFriendLists(out var numberOfFriendsPruned);
                log.Info($"Pruned {numberOfFriendsPruned:N0} invalid friends found on friend lists.");
            }

            if (ConfigManager.Config.Offline.PruneDeletedObjectsFromShortcutBars)
            {
                log.Info($"Pruning invalid shortcuts from all shortcut bars...");
                ShardDatabaseOfflineTools.PruneDeletedObjectsFromShortcutBars(out var numberOfShortcutsPruned);
                log.Info($"Pruned {numberOfShortcutsPruned:N0} deleted objects found on shortcut bars.");
            }

            if (ConfigManager.Config.Offline.PruneDeletedCharactersFromSquelchLists)
            {
                log.Info($"Pruning invalid squelches from all squelch lists...");
                ShardDatabaseOfflineTools.PruneDeletedCharactersFromSquelchLists(out var numberOfSquelchesPruned);
                log.Info($"Pruned {numberOfSquelchesPruned:N0} invalid squelched characters found on squelch lists.");
            }

            if (ConfigManager.Config.Offline.AutoUpdateWorldDatabase)
            {
                CheckForWorldDatabaseUpdate();

                if (ConfigManager.Config.Offline.AutoApplyWorldCustomizations)
                {
                    AutoApplyWorldCustomizations();
                }
            }
            else
            {
                log.Info($"AutoUpdateWorldDatabase is disabled...");
            }

            if (ConfigManager.Config.Offline.AutoApplyDatabaseUpdates)
            {
                AutoApplyDatabaseUpdates();
            }
            else
            {
                log.Info($"AutoApplyDatabaseUpdates is disabled...");
            }

            // This should only be enabled manually. To enable it, simply uncomment this line
            //ACE.Database.OfflineTools.Shard.BiotaGuidConsolidator.ConsolidateBiotaGuids(0xC0000000, out int numberOfBiotasConsolidated, out int numberOfErrors);

            ShardDatabaseOfflineTools.CheckForBiotaPropertiesPaletteOrderColumnInShard();

            log.Info("Initializing ServerManager...");
            ServerManager.Initialize();

            log.Info("Initializing DatManager...");
            DatManager.Initialize(ConfigManager.Config.Server.DatFilesDirectory, true);

            log.Info("Initializing DatabaseManager...");
            DatabaseManager.Initialize();

            if (DatabaseManager.InitializationFailure)
            {
                log.Fatal("DatabaseManager initialization failed. ACEmulator will now abort startup.");
                ServerManager.StartupAbort();
                Environment.Exit(0);
            }

            log.Info("Starting DatabaseManager...");
            DatabaseManager.Start();

            log.Info("Starting PropertyManager...");
            PropertyManager.Initialize();

            log.Info("Initializing GuidManager...");
            GuidManager.Initialize();

            if (ConfigManager.Config.Server.ServerPerformanceMonitorAutoStart)
            {
                log.Info("Server Performance Monitor auto starting...");
                ServerPerformanceMonitor.Start();
            }

            if (ConfigManager.Config.Server.WorldDatabasePrecaching)
            {
                log.Info("Precaching Weenies...");
                DatabaseManager.World.CacheAllWeenies();
                log.Info("Precaching Cookbooks...");
                DatabaseManager.World.CacheAllCookbooks();
                log.Info("Precaching Events...");
                DatabaseManager.World.GetAllEvents();
                log.Info("Precaching House Portals...");
                DatabaseManager.World.CacheAllHousePortals();
                log.Info("Precaching Points Of Interest...");
                DatabaseManager.World.CacheAllPointsOfInterest();
                log.Info("Precaching Spells...");
                DatabaseManager.World.CacheAllSpells();
                log.Info("Precaching Treasures - Death...");
                DatabaseManager.World.CacheAllTreasuresDeath();
                log.Info("Precaching Treasures - Material Base...");
                DatabaseManager.World.CacheAllTreasureMaterialBase();
                log.Info("Precaching Treasures - Material Groups...");
                DatabaseManager.World.CacheAllTreasureMaterialGroups();
                log.Info("Precaching Treasures - Material Colors...");
                DatabaseManager.World.CacheAllTreasureMaterialColor();
                log.Info("Precaching Treasures - Wielded...");
                DatabaseManager.World.CacheAllTreasureWielded();
            }
            else
            {
                log.Info("Precaching World Database Disabled...");
            }

            log.Info("Initializing PlayerManager...");
            PlayerManager.Initialize();

            log.Info("Initializing HouseManager...");
            HouseManager.Initialize();

            log.Info("Initializing InboundMessageManager...");
            InboundMessageManager.Initialize();

            log.Info("Initializing SocketManager...");
            SocketManager.Initialize();

            log.Info("Initializing WorldManager...");
            WorldManager.Initialize();

            log.Info("Initializing EventManager...");
            EventManager.Initialize();

            // Free up memory before the server goes online. This can free up 6 GB+ on larger servers.
            log.Info("Forcing .net garbage collection...");
            for (int i = 0; i < 10; i++)
            {
                GC.Collect();
            }

            // This should be last
            log.Info("Initializing CommandManager...");
            CommandManager.Initialize();

            if (!PropertyManager.GetBool("world_closed", false).Item)
            {
                WorldManager.Open(null);
            }
        }
Example #16
0
 public void InitializeLogger()
 {
     XmlConfigurator.ConfigureAndWatch();
 }
Example #17
0
 /// <summary>
 /// using special log4net configure file
 /// </summary>
 public static void Configure(string configFileName)
 {
     XmlConfigurator.ConfigureAndWatch(new FileInfo(configFileName));
 }
        static void Main(string[] args)
        {
            // if the app is already running, make the already running app window the foreground window and exit this instance
            bool singleInstanceOnly = false;

            bool.TryParse(ConfigurationManager.AppSettings["AllowSingleHulkamaniaInstanceOnly"], out singleInstanceOnly);

            if (singleInstanceOnly && IsAlreadyRunning())
            {
                System.Environment.Exit(0);
                return;
            }

            MainForm mainForm;

            try {
                // Set up logging
                XmlConfigurator.ConfigureAndWatch(new FileInfo(LOGGING_CONFIG_FILE));
                logger.Info("********** Starting Hulkamania **********");

                // parse command line
                mUseDummyMotionController = (Array.IndexOf(args, "UseDummyMotionControl") >= 0);
                logger.Info("Checking 'UseDummyMotionControl' command line argument: using " + (mUseDummyMotionController ? "Dummy" : "HULK") + " motion controller");

                // Disable screensaver
                SystemParametersInfo(SPI.SPI_SETSCREENSAVEACTIVE, 0, 0, SPIF.None);

                // Check if required data output folder exists
                DataLogger.CheckIfRequiredFoldersExist(true);

                // Start the thread that will control the Hulk
                MotionController.Instance.CheckModalErrors();
                controllerThread = new Thread(Hulk.ControlHulk)
                {
                    Priority = ThreadPriority.Highest
                };
                controllerThread.Start();

                // Set up handlers to deal with any exceptions not caught elsewhere in the application
                AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
                Application.ThreadException += OnUnhandledGuiException;

                // Find available tasks
                baseDirectory = Path.GetDirectoryName(Application.ExecutablePath);
                LoadAvailableTasks();

                // Start the network server
                startServer();
                statusTransmitter.initialize(serverHandler);

                // Start the main form, which will run until it is closed by the user
                Application.EnableVisualStyles();
                mainForm = MainForm.GetMainForm();

                Application.Run(mainForm);

                statusTransmitter.shutdown();
                stopServer();
            } catch (Exception e) {
                HandleUnhandledException(e);
            }

            try {
                // Turn the screensaver back on
                SystemParametersInfo(SPI.SPI_SETSCREENSAVEACTIVE, 1, 0, SPIF.None);

                // Close the main control loop thread.
                Hulk.KeepRunning = false;

                // Stop the network server
                stopServer();
            } catch (Exception e) {
                HandleUnhandledException(e);
            }

            logger.Info("********** Quitting Hulkamania **********");

            Application.Exit();
        }
Example #19
0
        private static void Main(string[] args)
        {
            Console.Title = "Fabiano Swagger of Doom - World Server";
            try
            {
                XmlConfigurator.ConfigureAndWatch(new FileInfo("log4net_wServer.config"));

                Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
                Thread.CurrentThread.Name           = "Entry";

                Settings = new SimpleSettings("wServer");
                new Database(
                    Settings.GetValue <string>("db_host", "127.0.0.1"),
                    Settings.GetValue <string>("db_database", "rotmgprod"),
                    Settings.GetValue <string>("db_user", "root"),
                    Settings.GetValue <string>("db_auth", ""));

                manager = new RealmManager(
                    Settings.GetValue <int>("maxClients", "100"),
                    Settings.GetValue <int>("tps", "20"));

                ServerDomain     = Settings.GetValue("serverDomain", "127.0.0.1");
                WhiteList        = Settings.GetValue <bool>("whiteList", "false");
                Verify           = Settings.GetValue <bool>("verifyEmail", "false");
                TestingMerchants = Settings.GetValue <bool>("testingMerchants", "false");
                MaxAllowedCredit = Settings.GetValue <int>("maxAllowedCredits", "200000");
                MaxAllowedFame   = Settings.GetValue <int>("maxAllowedFame", "750000");
                WhiteListTurnOff = Settings.GetValue <DateTime>("whitelistTurnOff");

                manager.Initialize();
                manager.Run();

                Server       server = new Server(manager);
                PolicyServer policy = new PolicyServer();

                Console.CancelKeyPress += (sender, e) => e.Cancel = true;

                policy.Start();
                server.Start();
                if (Settings.GetValue <bool>("broadcastNews", "false") && File.Exists("news.txt"))
                {
                    new Thread(AutoBroadcaster).Start();
                }
                logger.Info("Server initialized.");

                uint key = 0;
                while ((key = (uint)Console.ReadKey(true).Key) != (uint)ConsoleKey.Escape)
                {
                    if (key == (2 | 80))
                    {
                        Settings.Reload();
                    }
                }

                logger.Info("Terminating...");
                server.Stop();
                policy.Stop();
                manager.Stop();
                logger.Info("Server terminated.");
            }
            catch (Exception e)
            {
                logger.Fatal(e);

                foreach (var c in manager.Clients)
                {
                    c.Value.Disconnect();
                }
                Console.ReadLine();
            }
        }
Example #20
0
 public SystemLoggerProviderLog4Net(ISettings settings)
     : base(settings)
 {
     XmlConfigurator.ConfigureAndWatch(new FileInfo(settings.LoggingPath));
 }
 public void LoadLoggingSettings()
 {
     XmlConfigurator.ConfigureAndWatch(
         new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4net.config")));
 }
Example #22
0
 protected virtual void InitLogging()
 {
     LogManager.SetLoggerFactory(Log4NetLoggerFactory.Instance);
     GlobalContext.Properties["LogFileName"] = "SS" + ApplicationName;
     XmlConfigurator.ConfigureAndWatch(new FileInfo(Path.Combine(BinaryPath, "log4net.config")));
 }
Example #23
0
 public void XmlConfiguratorConfigureAndWatch(string configFile)
 {
     XmlConfigurator.ConfigureAndWatch(new FileInfo(configFile));
 }
Example #24
0
 static LogHelper()
 {
     XmlConfigurator.ConfigureAndWatch(new FileInfo("log4net.config"));
 }
Example #25
0
        public Log4NetLoggerFactory(string configFileName)
        {
            var file = GetConfigFile(configFileName);

            XmlConfigurator.ConfigureAndWatch(file);
        }
Example #26
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        /// <param name="args">
        /// The args.
        /// </param>
        private static void Main(params string[] args)
        {
            LogManager.SetLoggerFactory(ExitGames.Logging.Log4Net.Log4NetLoggerFactory.Instance);
            Console.WriteLine(AppDomain.CurrentDomain.BaseDirectory);

            // Set logfile name and application name variables
            FileInfo configFileInfo;

            try
            {
                // IOException if another process already writes to the file
                if (File.Exists(@"log\" + firstGameName + ".log"))
                {
                    File.Delete(@"log\" + firstGameName + ".log");
                }

                GlobalContext.Properties["LogName"] = firstGameName + ".log";

                configFileInfo = new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4net.config"));
            }
            catch (IOException)
            {
                GlobalContext.Properties["LogName"] = baseGameName + ".log";

                // just write to console for now
                configFileInfo = new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4netConsole.config"));
            }

            XmlConfigurator.ConfigureAndWatch(configFileInfo);

            AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;

            WindowsCounters.Initialize();

            int index = 0;

            if (args.Length > index)
            {
                Settings.TestCase = args[index];
            }

            index++;
            if (args.Length > index)
            {
                Settings.NumGames = byte.Parse(args[index]);
            }

            index++;
            if (args.Length > index)
            {
                Settings.NumClientsPerGame = byte.Parse(args[index]);
            }

            index++;
            if (args.Length > index)
            {
                Settings.ServerAddress = args[index];
            }

            index++;
            if (args.Length > index)
            {
                Settings.FlushInterval = int.Parse(args[index]);
            }

            index++;
            if (args.Length > index)
            {
                Settings.SendReliableData = bool.Parse(args[index]);
            }

            index++;
            if (args.Length > index)
            {
                Settings.ReliableDataSendInterval = int.Parse(args[index]);
            }

            index++;
            if (args.Length > index)
            {
                Settings.SendUnreliableData = bool.Parse(args[index]);
            }

            index++;
            if (args.Length > index)
            {
                Settings.UnreliableDataSendInterval = int.Parse(args[index]);
            }

            Console.WriteLine("Test case: " + Settings.TestCase);
            Console.WriteLine("Settings: {0} games per process, {1} players per game, game server at {2}",
                              Settings.NumGames,
                              Settings.NumClientsPerGame,
                              Settings.ServerAddress);

            if (Settings.SendReliableData)
            {
                Console.WriteLine("Sending reliable operation every {0} ms", Settings.ReliableDataSendInterval);
            }

            if (Settings.SendUnreliableData)
            {
                Console.WriteLine("Sending unreliable operation every {0} ms", Settings.UnreliableDataSendInterval);
            }

            Console.WriteLine();

            stopped = false;
            fiber.Start();
            counterLoggingFiber.Start();

            counterLoggingFiber.ScheduleOnInterval(PrintCounter, Settings.LogCounterInterval, Settings.LogCounterInterval);

            try
            {
                log.InfoFormat("Starting {0} games with {1} players", Settings.NumGames, Settings.NumClientsPerGame);
                for (int g = 0; g < Settings.NumGames; g++)
                {
                    fiber.Enqueue(StartGame);
                }

                ////log.InfoFormat("{0} clients running", clients.Count);
                Console.WriteLine("[{0}] Press Return to End", Process.GetCurrentProcess().Id);
                Console.ReadLine();

                ////log.InfoFormat("Stopping {0} clients", clients.Count);
                StopGames();
                fiber.Stop();

                // wait for stop to complete
                resetEvent.WaitOne();
            }
            catch (Exception e)
            {
                log.Error(e);
            }
            finally
            {
                log.InfoFormat("[{0}] Stopped", Process.GetCurrentProcess().Id);
            }
        }
 private static void SetUpLog4Net()
 {
     XmlConfigurator.ConfigureAndWatch(new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"));
     LogManager.Use <Log4NetFactory>();
 }
Example #28
0
        /// <summary>
        /// Configures the repository using information from the assembly.
        /// </summary>
        /// <param name="assembly">The assembly containing <see cref="log4net.Config.ConfiguratorAttribute"/>
        /// attributes which define the configuration for the repository.</param>
        /// <param name="repository">The repository to configure.</param>
        /// <exception cref="ArgumentNullException">
        ///     <para><paramref name="assembly" /> is <see langword="null" />.</para>
        ///     <para>-or-</para>
        ///     <para><paramref name="repository" /> is <see langword="null" />.</para>
        /// </exception>
        private void ConfigureRepository(Assembly assembly, ILoggerRepository repository)
        {
            if (assembly == null)
            {
                throw new ArgumentNullException("assembly");
            }

            if (repository == null)
            {
                throw new ArgumentNullException("repository");
            }

            // Look for the Configurator attributes (e.g. XmlConfiguratorAttribute) on the assembly
#if NETSTANDARD1_3
            object[] configAttributes = assembly.GetCustomAttributes(typeof(log4net.Config.ConfiguratorAttribute)).ToArray();
#else
            object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.ConfiguratorAttribute), false);
#endif
            if (configAttributes != null && configAttributes.Length > 0)
            {
                // Sort the ConfiguratorAttributes in priority order
                Array.Sort(configAttributes);

                // Delegate to the attribute the job of configuring the repository
                foreach (log4net.Config.ConfiguratorAttribute configAttr in configAttributes)
                {
                    if (configAttr != null)
                    {
                        try
                        {
                            configAttr.Configure(assembly, repository);
                        }
                        catch (Exception ex)
                        {
                            LogLog.Error(declaringType, "Exception calling [" + configAttr.GetType().FullName + "] .Configure method.", ex);
                        }
                    }
                }
            }

            if (repository.Name == DefaultRepositoryName)
            {
                // Try to configure the default repository using an AppSettings specified config file
                // Do this even if the repository has been configured (or claims to be), this allows overriding
                // of the default config files etc, if that is required.
                string repositoryConfigFile = SystemInfo.GetAppSetting("log4net.Config");
                if (repositoryConfigFile != null && repositoryConfigFile.Length > 0)
                {
                    string applicationBaseDirectory = null;
                    try
                    {
                        applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory;
                    }
                    catch (Exception ex)
                    {
                        LogLog.Warn(declaringType, "Exception getting ApplicationBaseDirectory. appSettings log4net.Config path [" + repositoryConfigFile + "] will be treated as an absolute URI", ex);
                    }

                    string repositoryConfigFilePath = repositoryConfigFile;
                    if (applicationBaseDirectory != null)
                    {
                        repositoryConfigFilePath = Path.Combine(applicationBaseDirectory, repositoryConfigFile);
                    }

                    // Determine whether to watch the file or not based on an app setting value:
                    bool watchRepositoryConfigFile = false;
#if NET_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0 || NETSTANDARD1_3
                    bool.TryParse(SystemInfo.GetAppSetting("log4net.Config.Watch"), out watchRepositoryConfigFile);
#else
                    {
                        string watch = SystemInfo.GetAppSetting("log4net.Config.Watch");
                        if (watch != null && watch.Length > 0)
                        {
                            try
                            {
                                watchRepositoryConfigFile = Boolean.Parse(watch);
                            }
                            catch (FormatException)
                            {
                                // simply not a Boolean
                            }
                        }
                    }
#endif

                    if (watchRepositoryConfigFile)
                    {
                        // As we are going to watch the config file it is required to resolve it as a
                        // physical file system path pass that in a FileInfo object to the Configurator
                        FileInfo repositoryConfigFileInfo = null;
                        try
                        {
                            repositoryConfigFileInfo = new FileInfo(repositoryConfigFilePath);
                        }
                        catch (Exception ex)
                        {
                            LogLog.Error(declaringType, "DefaultRepositorySelector: Exception while parsing log4net.Config file physical path [" + repositoryConfigFilePath + "]", ex);
                        }

                        try
                        {
                            LogLog.Debug(declaringType, "Loading and watching configuration for default repository from AppSettings specified Config path [" + repositoryConfigFilePath + "]");

                            XmlConfigurator.ConfigureAndWatch(repository, repositoryConfigFileInfo);
                        }
                        catch (Exception ex)
                        {
                            LogLog.Error(declaringType, "DefaultRepositorySelector: Exception calling XmlConfigurator.ConfigureAndWatch method with ConfigFilePath [" + repositoryConfigFilePath + "]", ex);
                        }
                    }
                    else
                    {
                        // As we are not going to watch the config file it is easiest to just resolve it as a
                        // URI and pass that to the Configurator
                        Uri repositoryConfigUri = null;
                        try
                        {
                            repositoryConfigUri = new Uri(repositoryConfigFilePath);
                        }
                        catch (Exception ex)
                        {
                            LogLog.Error(declaringType, "Exception while parsing log4net.Config file path [" + repositoryConfigFile + "]", ex);
                        }

                        if (repositoryConfigUri != null)
                        {
                            LogLog.Debug(declaringType, "Loading configuration for default repository from AppSettings specified Config URI [" + repositoryConfigUri.ToString() + "]");

                            try
                            {
                                // TODO: Support other types of configurator
                                XmlConfigurator.Configure(repository, repositoryConfigUri);
                            }
                            catch (Exception ex)
                            {
                                LogLog.Error(declaringType, "Exception calling XmlConfigurator.Configure method with ConfigUri [" + repositoryConfigUri + "]", ex);
                            }
                        }
                    }
                }
            }
        }
 public void ConfigureAndWatchAppConfig()
 {
     XmlConfigurator.ConfigureAndWatch(new FileInfo(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile));
 }
Example #30
0
        public CommHelper()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + @"/Config/log4net.config";

            XmlConfigurator.ConfigureAndWatch(new FileInfo(path));
        }