/// <summary>
        /// </summary>
        /// <returns>
        /// </returns>
        private static bool InitializeLogAndBug()
        {
            try
            {
                // Setup and enable NLog logging to file
                LogUtil.SetupConsoleLogging(LogLevel.Debug);
                LogUtil.SetupFileLogging("${basedir}/LoginEngineLog.txt", LogLevel.Trace);

                // NBug initialization
                SettingsOverride.LoadCustomSettings("NBug.LoginEngine.config");
                Settings.WriteLogToDisk = true;
                AppDomain.CurrentDomain.UnhandledException += Handler.UnhandledException;
                TaskScheduler.UnobservedTaskException      += Handler.UnobservedTaskException;
            }
            catch (Exception e)
            {
                Colouring.Push(ConsoleColor.Red);
                Console.WriteLine("Error occured while initalizing NLog/NBug");
                Console.WriteLine(e.Message);
                Colouring.Pop();
                return(false);
            }

            return(true);
        }
Exemple #2
0
        public void AppSettingsLoader_Load_UsesKeyOverride()
        {
            var mockSettingsLoader = new SettingLoaderMock();

            mockSettingsLoader.Settings.Add("IsFooBar", "Foobar");

            var settings = new SettingsOverride();

            Assert.IsTrue(AppSettingsLoader.Load(mockSettingsLoader, ref settings), "Load returned false");
            Assert.AreEqual("Foobar", settings.IsFoo, "String setting not set");
        }
        private void LoadSettingsOverrides()
        {
            Settings settings = Main.Settings;

            SettingsOverride modpackSettingsOverrides = new SettingsOverride(Main.Path, "modpack");

            modpackSettingsOverrides.LoadOverrides(settings);

            SettingsOverride userSettingsOverrides = new SettingsOverride(Main.Path, "user");

            userSettingsOverrides.LoadOverrides(settings);
        }
        private void SaveButton_Click(object sender, EventArgs e)
        {
            // Validate user provide settings
            if (string.IsNullOrEmpty(this.uiProviderComboBox.Text))
            {
                MessageBox.Show(
                    "The 'User Interface > UI Provider' selection should not be left blank. Please select a value for the provider or set the UI Mode to Auto.",
                    "User Interface Provider is Left Blank",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Warning);
                this.uiProviderComboBox.Focus();
                return;
            }

            Settings.EnableNetworkTrace = this.writeNetworkTraceToFileCheckBox.Checked;             // This should come before settings app config

            // Save application settings
            Settings.UIMode             = (UIMode)this.uiModeComboBox.SelectedItem;
            Settings.UIProvider         = (UIProvider)this.uiProviderComboBox.SelectedItem;
            Settings.MiniDumpType       = (MiniDumpType)this.miniDumpTypeComboBox.SelectedItem;
            Settings.SleepBeforeSend    = Convert.ToInt32(this.sleepBeforeSendNumericUpDown.Value);
            Settings.MaxQueuedReports   = Convert.ToInt32(this.maxQueuedReportsNumericUpDown.Value);
            Settings.StopReportingAfter = Convert.ToInt32(this.stopReportingAfterNumericUpDown.Value);
            Settings.WriteLogToDisk     = this.writeLogToDiskCheckBox.Checked;
            Settings.HandleProcessCorruptedStateExceptions = this.handleProcessCorruptedStateExceptionsCheckBox.Checked;
            Settings.ReleaseMode = this.releaseModeCheckBox.Checked;

            if ((UIMode)this.uiModeComboBox.SelectedItem == UIMode.None)
            {
                Settings.ExitApplicationImmediately = this.exitApplicationImmediatelyCheckBox.Checked;
            }

            Settings.StoragePath = this.storagePathComboBox.Text == "Custom" ? this.customStoragePathTextBox.Text : this.storagePathComboBox.Text;

            Settings.Destinations.Clear();

            // Save connection strings
            foreach (
                var connectionString in
                this.panelLoaders.Where(p => p.Controls.Count == 2)
                .Select(p => ((ISubmitPanel)p.Controls[0]).ConnectionString)
                .Where(s => !string.IsNullOrEmpty(s)))
            {
                Settings.AddDestinationFromConnectionString(connectionString);
            }

            this.settingsFile.Position = 0;
            SettingsOverride.SaveCustomSettings(this.settingsFile, this.encryptConnectionStringsCheckBox.Checked);
            this.status.Text = "Configuration file successfully saved. Please test your configuration.";
        }
Exemple #5
0
        public App()
        {
            // Check to see if test application is initialized by the configurator tool
            if (Environment.GetCommandLineArgs().Count() > 1)
            {
                var stream = new FileStream(Environment.GetCommandLineArgs()[1], FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                SettingsOverride.LoadCustomSettings(stream);
            }

            // For demonstrational purposes only, normally this should be left with it's default value as false!
            Settings.HandleProcessCorruptedStateExceptions = true;

            // Sample NBug configuration for WPF applications
            AppDomain.CurrentDomain.UnhandledException += Handler.UnhandledException;
            Current.DispatcherUnhandledException       += Handler.DispatcherUnhandledException;
            TaskScheduler.UnobservedTaskException      += Handler.UnobservedTaskException;
        }
        public static void Main()
        {
            // Check to see if test application is initialized by the configurator tool
            if (Environment.GetCommandLineArgs().Count() > 1)
            {
                var stream = new FileStream(Environment.GetCommandLineArgs()[1], FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                SettingsOverride.LoadCustomSettings(stream);
            }

            // For demonstrational purposes only, normally this should be left with it's default value as false!
            Settings.HandleProcessCorruptedStateExceptions = true;

            // Sample NBug configuration for WinForms applications
            AppDomain.CurrentDomain.UnhandledException += Handler.UnhandledException;
            Application.ThreadException           += Handler.ThreadException;
            TaskScheduler.UnobservedTaskException += Handler.UnobservedTaskException;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
Exemple #7
0
        public static void Main(string[] args)
        {
            // Check to see if test application is initialized by the configurator tool
            if (args.Length > 0)
            {
                var stream = new FileStream(args[0], FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                SettingsOverride.LoadCustomSettings(stream);
            }

            // Sample NBug configuration for console applications
            AppDomain.CurrentDomain.UnhandledException += Handler.UnhandledException;
            TaskScheduler.UnobservedTaskException      += Handler.UnobservedTaskException;

            Console.WriteLine("NBug now auto-handles: AppDomain.CurrentDomain.UnhandledException");
            Console.WriteLine("NBug now auto-handles: Threading.Tasks.TaskScheduler.UnobservedTaskException");
            Console.WriteLine(Environment.NewLine);
            Console.Write("Generate a System.Exception (y/n): ");

            if (Console.ReadKey().Key == ConsoleKey.Y)
            {
                throw new Exception("This is an exception thrown from NBug console sample application.");
            }
        }
Exemple #8
0
        /// <summary>
        /// </summary>
        /// <param name="args">
        /// </param>
        private static void Main(string[] args)
        {
            bool processedargs = false;

            LogUtil.SetupConsoleLogging(LogLevel.Debug);
            LogUtil.SetupFileLogging("${basedir}/ZoneEngineLog.txt", LogLevel.Trace);

            SettingsOverride.LoadCustomSettings("NBug.ZoneEngine.Config");
            Settings.WriteLogToDisk = true;
            AppDomain.CurrentDomain.UnhandledException += Handler.UnhandledException;
            TaskScheduler.UnobservedTaskException      += Handler.UnobservedTaskException;

            csc = new ScriptCompiler();

            // TODO: ADD More Handlers.
            Console.Title = "CellAO " + AssemblyInfoclass.Title + " Console. Version: " + AssemblyInfoclass.Description
                            + " " + AssemblyInfoclass.AssemblyVersion + " " + AssemblyInfoclass.Trademark;

            ConsoleText ct = new ConsoleText();

            ct.TextRead("main.txt");
            Console.Write("Loading ");
            Console.ForegroundColor = ConsoleColor.DarkGreen;
            Console.Write(AssemblyInfoclass.Title + " ");
            Console.ForegroundColor = ConsoleColor.White;
            Console.Write(AssemblyInfoclass.Description);
            Console.ResetColor();
            Console.WriteLine("...");

            zoneServer = Container.GetInstance <ZoneServer>();
            int Port = Convert.ToInt32(Config.Instance.CurrentConfig.ZonePort);

            try
            {
                if (Config.Instance.CurrentConfig.ListenIP == "0.0.0.0")
                {
                    zoneServer.TcpEndPoint = new IPEndPoint(IPAddress.Any, Port);
                }
                else
                {
                    zoneServer.TcpIP = IPAddress.Parse(Config.Instance.CurrentConfig.ListenIP);
                }
            }
            catch
            {
                ct.TextRead("ip_config_parse_error.txt");
                Console.ReadKey();
                return;
            }

            string consoleCommand;

            ct.TextRead("zone_consolecommands.txt");

            // removed CheckDBs here, added commands check and updatedb (updatedb will change to a versioning
            while (true)
            {
                if (!processedargs)
                {
                    if (args.Length == 1)
                    {
                        if (args[0].ToLower() == "/autostart")
                        {
                            ct.TextRead("autostart.txt");
                            csc.Compile(false);
                            StartTheServer();
                        }
                    }

                    processedargs = true;
                }

                Console.Write("\nServer Command >>");
                consoleCommand = Console.ReadLine();
                switch (consoleCommand.ToLower())
                {
                case "start":
                    if (zoneServer.Running)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Zone Server is already running");
                        Console.ResetColor();
                        break;
                    }

                    // TODO: Add Sql Check.
                    csc.Compile(false);
                    StartTheServer();
                    break;

                case "startm":     // Multiple dll compile
                    if (zoneServer.Running)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Zone Server is already running");
                        Console.ResetColor();
                        break;
                    }

                    // TODO: Add Sql Check.
                    csc.Compile(true);
                    StartTheServer();
                    break;

                case "stop":
                    if (!zoneServer.Running)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Zone Server is not running");
                        Console.ResetColor();
                        break;
                    }

                    zoneServer.Stop();
                    break;

                case "check":
                case "updatedb":
                    using (SqlWrapper sqltester = new SqlWrapper())
                    {
                        sqltester.CheckDBs();
                        Console.ResetColor();
                    }

                    break;

                case "exit":
                case "quit":
                    if (zoneServer.Running)
                    {
                        zoneServer.Stop();
                    }

                    Process.GetCurrentProcess().Kill();
                    break;

                case "ls":     // list all available scripts, dont remove it since it does what it should
                    Console.WriteLine("Available scripts");

                    /* Old Lua way
                     * string[] files = Directory.GetFiles("Scripts");*/
                    try
                    {
                        string[] files = Directory.GetFiles("Scripts", "*.cs", SearchOption.AllDirectories);
                        if (files.Length == 0)
                        {
                            Console.WriteLine("No scripts were found.");
                            break;
                        }

                        Console.ForegroundColor = ConsoleColor.Green;
                        foreach (string s in files)
                        {
                            Console.WriteLine(s);
                        }
                    }
                    catch (Exception)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Scripts folder not found.");
                    }

                    Console.ResetColor();
                    break;

                case "ping":

                    // ChatCom.Server.Ping();
                    Console.WriteLine("Ping is disabled till we can fix it");
                    break;

                case "running":
                    if (zoneServer.Running)
                    {
                        Console.WriteLine("Zone Server is Running");
                        break;
                    }

                    Console.WriteLine("Zone Server not Running");
                    break;

                case "online":
                    if (zoneServer.Running)
                    {
                        Console.ForegroundColor = ConsoleColor.White;
                        lock (zoneServer.Clients)
                        {
                            foreach (Client c in zoneServer.Clients)
                            {
                                Console.WriteLine("Character " + c.Character.Name + " online");
                            }
                        }

                        Console.ResetColor();
                    }

                    break;

                default:
                    ct.TextRead("zone_consolecmdsdefault.txt");
                    break;
                }
            }
        }
Exemple #9
0
        private static void Main(string[] args)
        {
            #region Console Texts...
            Console.Title = "CellAO " + AssemblyInfoclass.Title + " Console. Version: " + AssemblyInfoclass.Description
                            + " " + AssemblyInfoclass.AssemblyVersion + " " + AssemblyInfoclass.Trademark;

            ConsoleText ct = new ConsoleText();
            ct.TextRead("main.txt");
            Console.WriteLine("Loading " + AssemblyInfoclass.Title + "...");

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("[OK]");
            Console.ResetColor();
            #endregion

            //Sying helped figure all this code out, about 5 yearts ago! :P
            bool processedargs = false;
            loginLoginServer           = new LoginServer();
            loginLoginServer.EnableTCP = true;
            loginLoginServer.EnableUDP = false;
            try
            {
                loginLoginServer.TcpIP = IPAddress.Parse(Config.Instance.CurrentConfig.ListenIP);
            }
            catch
            {
                ct.TextRead("ip_config_parse_error.txt");
                Console.ReadKey();
                return;
            }
            loginLoginServer.TcpPort = Convert.ToInt32(Config.Instance.CurrentConfig.LoginPort);

            #region NLog
            LoggingConfiguration config        = new LoggingConfiguration();
            ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget();
            consoleTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
            FileTarget fileTarget = new FileTarget();
            config.AddTarget("file", fileTarget);
            fileTarget.FileName = "${basedir}/LoginEngineLog.txt";
            fileTarget.Layout   = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
            LoggingRule rule1 = new LoggingRule("*", LogLevel.Trace, consoleTarget);
            config.LoggingRules.Add(rule1);
            LoggingRule rule2 = new LoggingRule("*", LogLevel.Trace, fileTarget);
            config.LoggingRules.Add(rule2);
            LogManager.Configuration = config;
            #endregion

            #region NBug
            SettingsOverride.LoadCustomSettings("NBug.LoginEngine.Config");
            NBug.Settings.WriteLogToDisk = true;
            AppDomain.CurrentDomain.UnhandledException += Handler.UnhandledException;
            TaskScheduler.UnobservedTaskException      += Handler.UnobservedTaskException;
            //TODO: ADD More Handlers.
            #endregion

            loginLoginServer.MaximumPendingConnections = 100;

            #region Console Commands
            //Andyzweb: Added checks for start and stop
            //also added a running command to return status of the server
            //and added Console.Write("\nServer Command >>"); to login server
            string consoleCommand;
            ct.TextRead("login_consolecommands.txt");
            while (true)
            {
                if (!processedargs)
                {
                    if (args.Length == 1)
                    {
                        if (args[0].ToLower() == "/autostart")
                        {
                            ct.TextRead("autostart.txt");
                            ThreadMgr.Start();
                            loginLoginServer.Start();
                        }
                    }
                    processedargs = true;
                }
                Console.Write("\nServer Command >>");

                consoleCommand = Console.ReadLine();
                string temp = "";
                while (temp != consoleCommand)
                {
                    temp           = consoleCommand;
                    consoleCommand = consoleCommand.Replace("  ", " ");
                }
                consoleCommand = consoleCommand.Trim();
                switch (consoleCommand.ToLower())
                {
                case "start":
                    if (loginLoginServer.Running)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        ct.TextRead("loginisrunning.txt");
                        Console.ResetColor();
                        break;
                    }
                    ThreadMgr.Start();
                    loginLoginServer.Start();
                    break;

                case "stop":
                    if (!loginLoginServer.Running)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        ct.TextRead("loginisnotrunning.txt");
                        Console.ResetColor();
                        break;
                    }
                    ThreadMgr.Stop();
                    loginLoginServer.Stop();
                    break;

                case "exit":
                    Process.GetCurrentProcess().Kill();
                    break;

                case "running":
                    if (loginLoginServer.Running)
                    {
                        //Console.WriteLine("Login Server is running");
                        ct.TextRead("loginisrunning.txt");
                        break;
                    }
                    //Console.WriteLine("Login Server not running");
                    ct.TextRead("loginisnotrunning.txt");
                    break;

                    #region Help Commands....
                case "help":
                    ct.TextRead("logincmdhelp.txt");
                    break;

                case "help start":
                    ct.TextRead("helpstart.txt");
                    break;

                case "help exit":
                    ct.TextRead("helpstop.txt");
                    break;

                case "help running":
                    ct.TextRead("loginhelpcmdrunning.txt");
                    break;

                case "help Adduser":
                    ct.TextRead("logincmdadduserhelp.txt");
                    break;

                case "help setpass":
                    ct.TextRead("logincmdhelpsetpass.txt");
                    break;
                    #endregion

                default:

                    #region Adduser
                    //This section handles the command for adding a user to the database
                    if (consoleCommand.ToLower().StartsWith("adduser"))
                    {
                        string[] parts = consoleCommand.Split(' ');
                        if (parts.Length < 9)
                        {
                            Console.WriteLine(
                                "Invalid command syntax.\nPlease use:\nAdduser <username> <password> <number of characters> <expansion> <gm level> <email> <FirstName> <LastName>");
                            break;
                        }
                        string username = parts[1];
                        string password = parts[2];
                        int    numChars = 0;
                        try
                        {
                            numChars = int.Parse(parts[3]);
                        }
                        catch
                        {
                            Console.WriteLine("Error: <number of characters> must be a number (duh!)");
                            break;
                        }
                        int expansions = 0;
                        try
                        {
                            expansions = int.Parse(parts[4]);
                        }
                        catch
                        {
                            Console.WriteLine("Error: <expansions> must be a number between 0 and 2047!");
                            break;
                        }
                        if (expansions < 0 || expansions > 2047)
                        {
                            Console.WriteLine("Error: <expansions> must be a number between 0 and 2047!");
                            break;
                        }

                        int gm = 0;
                        try
                        {
                            gm = int.Parse(parts[5]);
                        }
                        catch
                        {
                            Console.WriteLine("Error: <GM Level> must be number (duh!)");
                            break;
                        }

                        string email = parts[6];
                        if (email == null)
                        {
                            email = String.Empty;
                        }
                        if (!TestEmailRegex(email))
                        {
                            Console.WriteLine("Error: <Email> You must supply an email address for this account");
                            break;
                        }
                        string firstname = parts[7];
                        try
                        {
                            if (firstname == null)
                            {
                                throw new ArgumentNullException();
                            }
                        }
                        catch
                        {
                            Console.WriteLine("Error: <FirstName> You must supply a first name for this accout");
                            break;
                        }
                        string lastname = parts[8];
                        try
                        {
                            if (lastname == null)
                            {
                                throw new ArgumentNullException();
                            }
                        }
                        catch
                        {
                            Console.WriteLine("Error: <LastName> You must supply a last name for this account");
                            break;
                        }

                        const string FormatString =
                            "INSERT INTO `login` (`CreationDate`, `Flags`,`AccountFlags`,`Username`,`Password`,`Allowed_Characters`,`Expansions`, `GM`, `Email`, `FirstName`, `LastName`) VALUES "
                            + "(NOW(), '0', '0', '{0}', '{1}', {2}, {3}, {4}, '{5}', '{6}', '{7}');";

                        LoginEncryption le = new LoginEncryption();

                        string hashedPassword = le.GeneratePasswordHash(password);

                        string sql = String.Format(
                            FormatString,
                            username,
                            hashedPassword,
                            numChars,
                            expansions,
                            gm,
                            email,
                            firstname,
                            lastname);
                        SqlWrapper sqlWrapper = new SqlWrapper();
                        try
                        {
                            sqlWrapper.SqlInsert(sql);
                        }
                        catch (MySqlException ex)
                        {
                            switch (ex.Number)
                            {
                            case 1062:         //duplicate entry for key
                                Console.WriteLine("A user account with this username already exists.");
                                break;

                            default:
                                Console.WriteLine(
                                    "An error occured while trying to add a new user account:\n{0}", ex.Message);
                                break;
                            }
                            break;
                        }
                        Console.WriteLine("User added successfully.");
                        break;
                    }
                    #endregion

                    #region Hashpass
                    //This function just hashes the string you enter using the loginencryption method
                    if (consoleCommand.ToLower().StartsWith("hash"))
                    {
                        string Syntax =
                            "The Syntax for this command is \"hash <String to hash>\" alphanumeric no spaces";
                        string[] parts = consoleCommand.Split(' ');
                        if (parts.Length != 2)
                        {
                            Console.WriteLine(Syntax);
                            break;
                        }
                        string          pass   = parts[1];
                        LoginEncryption le     = new LoginEncryption();
                        string          hashed = le.GeneratePasswordHash(pass);
                        Console.WriteLine(hashed);
                        break;
                    }
                    #endregion

                    #region setpass
                    //sets the password for the given username
                    //Added by Andyzweb
                    //Still TODO add exception and error handling
                    if (consoleCommand.ToLower().StartsWith("setpass"))
                    {
                        string Syntax =
                            "The syntax for this command is \"setpass <account username> <newpass>\" where newpass is alpha numeric no spaces";
                        string[] parts = consoleCommand.Split(' ');
                        if (parts.Length != 3)
                        {
                            Console.WriteLine(Syntax);
                            break;
                        }
                        string          username = parts[1];
                        string          newpass  = parts[2];
                        LoginEncryption le       = new LoginEncryption();
                        string          hashed   = le.GeneratePasswordHash(newpass);
                        string          formatString;
                        formatString = "UPDATE `login` SET Password = '******' WHERE login.Username = '******'";

                        string sql = String.Format(formatString, hashed, username);

                        SqlWrapper updt = new SqlWrapper();
                        try
                        {
                            updt.SqlUpdate(sql);
                        }
                        //yeah this part here, some kind of exception handling for mysql errors
                        catch
                        {
                        }
                    }
                    #endregion

                    ct.TextRead("login_consolecmdsdefault.txt");
                    break;
                }
            }
            #endregion
        }
Exemple #10
0
        /// <summary>
        /// The main.
        /// </summary>
        /// <param name="args">
        /// Program arguments
        /// </param>
        private static void Main(string[] args)
        {
            Console.Title = "CellAO " + AssemblyInfoclass.Title + " Console. Version: " + AssemblyInfoclass.Description
                            + " " + AssemblyInfoclass.AssemblyVersion + " " + AssemblyInfoclass.Trademark;

            ConsoleText ct = new ConsoleText();

            ct.TextRead("main.txt");
            Console.WriteLine("Loading " + AssemblyInfoclass.Title + "...");

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Using ISComm v1.0");
            Console.WriteLine("[OK]");
            Console.ResetColor();

            bool       processedArgs = false;
            ChatServer chatServer    = new ChatServer();

            Console.WriteLine("[ISComm] Waiting for link...");

            #region NLog
            LoggingConfiguration config        = new LoggingConfiguration();
            ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget();
            consoleTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
            FileTarget fileTarget = new FileTarget();
            config.AddTarget("file", fileTarget);
            fileTarget.FileName = "${basedir}/ChatEngineLog.txt";
            fileTarget.Layout   = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
            LoggingRule rule1 = new LoggingRule("*", LogLevel.Trace, consoleTarget);
            config.LoggingRules.Add(rule1);
            LoggingRule rule2 = new LoggingRule("*", LogLevel.Trace, fileTarget);
            config.LoggingRules.Add(rule2);
            LogManager.Configuration = config;
            #endregion

            #region NBug

            SettingsOverride.LoadCustomSettings("NBug.ChatEngine.Config");
            Settings.WriteLogToDisk = true;
            AppDomain.CurrentDomain.UnhandledException += Handler.UnhandledException;
            TaskScheduler.UnobservedTaskException      += Handler.UnobservedTaskException;

            // TODO: ADD More Handlers.
            #endregion

            IPAddress localISComm;

            try
            {
                // Local ISComm IP valid?
                localISComm = IPAddress.Parse(Config.Instance.CurrentConfig.ISCommLocalIP);
            }
            catch
            {
                // Fallback to ZoneIP
                localISComm = IPAddress.Parse(Config.Instance.CurrentConfig.ZoneIP);
            }

            if (!ZoneCom.Link(localISComm.ToString(), Config.Instance.CurrentConfig.CommPort, chatServer))
            {
                Console.WriteLine("[ISComm] Unable to link to ZoneEngine. :(");
                return;
            }

            Console.WriteLine("[ISComm] Linked with ZoneEngine! :D");

            chatServer.EnableTCP = true;
            chatServer.EnableUDP = false;

            try
            {
                chatServer.TcpIP = IPAddress.Parse(Config.Instance.CurrentConfig.ListenIP);
            }
            catch
            {
                ct.TextRead("ip_config_parse_error.txt");
                Console.ReadKey();
                return;
            }

            try
            {
                chatServer.UdpIP = IPAddress.Parse(Config.Instance.CurrentConfig.ListenIP);
            }
            catch
            {
                ct.TextRead("ip_config_parse_error.txt");
                Console.ReadKey();
                return;
            }

            chatServer.TcpPort = Convert.ToInt32(Config.Instance.CurrentConfig.ChatPort);
            chatServer.MaximumPendingConnections = 100;

            AppDomain.CurrentDomain.UnhandledException += Handler.UnhandledException;
            TaskScheduler.UnobservedTaskException      += Handler.UnobservedTaskException;

            // TODO: ADD More Handlers.

            // Andyzweb: I added checks for if the server is running or not
            // also a command called running that returns the status of the server
            // and added the Console.Write("\nServer Command >>"); to chatserver
            string consoleCommand;
            ct.TextRead("chat_consolecommands.txt");
            while (true)
            {
                if (!processedArgs)
                {
                    if (args.Length == 1)
                    {
                        if (args[0].ToLower() == "/autostart")
                        {
                            ct.TextRead("autostart.txt");
                            ThreadMgr.Start();
                            chatServer.Start();
                        }
                    }

                    processedArgs = true;
                }

                Console.Write("\nServer Command >>");
                consoleCommand = Console.ReadLine();
                switch (consoleCommand.ToLower())
                {
                case "start":
                    if (chatServer.Running)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Chat Server is already running");
                        Console.ResetColor();
                        break;
                    }

                    ThreadMgr.Start();
                    chatServer.Start();
                    break;

                case "stop":
                    if (!chatServer.Running)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Chat Server is not running");
                        Console.ResetColor();
                        break;
                    }

                    ThreadMgr.Stop();
                    chatServer.Stop();
                    break;

                case "exit":
                    Process.GetCurrentProcess().Kill();
                    break;

                case "running":
                    if (chatServer.Running)
                    {
                        Console.WriteLine("Chat Server is Running");
                        break;
                    }

                    Console.WriteLine("Chat Server not Running");
                    break;

                default:
                    ct.TextRead("chat_consolecmdsdefault.txt");
                    break;
                }
            }
        }
        /// <summary>
        /// Loads the settings file or loads defaults is settings file is empty or invalid.
        /// </summary>
        /// <param name="createNew">Force creating of new file. Overrides existing file by default.</param>
        private void LoadSettingsFile(bool createNew)
        {
            this.settingsFile.Position = 0;
            SettingsOverride.LoadCustomSettings(this.settingsFile);
            this.InitializeControls();

            this.fileTextBox.Text = createNew == false ? this.openFileDialog.FileName : this.createFileDialog.FileName;

            // Read application settings
            this.uiProviderComboBox.SelectedItem                       = Settings.UIProvider;
            this.uiModeComboBox.SelectedItem                           = Settings.UIMode; // Should come after uiProviderComboBox = ...
            this.miniDumpTypeComboBox.SelectedItem                     = Settings.MiniDumpType;
            this.sleepBeforeSendNumericUpDown.Value                    = Settings.SleepBeforeSend;
            this.maxQueuedReportsNumericUpDown.Value                   = Settings.MaxQueuedReports;
            this.stopReportingAfterNumericUpDown.Value                 = Settings.StopReportingAfter;
            this.writeLogToDiskCheckBox.Checked                        = Settings.WriteLogToDisk;
            this.exitApplicationImmediatelyCheckBox.Checked            = Settings.ExitApplicationImmediately;
            this.handleProcessCorruptedStateExceptionsCheckBox.Checked = Settings.HandleProcessCorruptedStateExceptions;
            this.releaseModeCheckBox.Checked                           = Settings.ReleaseMode;

            if (Settings.StoragePath == StoragePath.Custom)
            {
                this.storagePathComboBox.SelectedItem = StoragePath.Custom;
                this.customStoragePathTextBox.Text    = Settings.StoragePath;
            }
            else
            {
                // Make sure that we're getting the enum value
                this.storagePathComboBox.SelectedItem = (StoragePath)Settings.StoragePath;
            }

            if (Settings.Cipher != null && Settings.Cipher.Length != 0)
            {
                this.encryptConnectionStringsCheckBox.Checked = true;
            }

            if (this.settingsFile.Name.EndsWith("app.config"))
            {
                this.writeNetworkTraceToFileCheckBox.Enabled = true;
                this.networkTraceWarningLabel.Enabled        = true;

                if (Settings.EnableNetworkTrace.HasValue)
                {
                    this.writeNetworkTraceToFileCheckBox.Checked = Settings.EnableNetworkTrace.Value;
                }
            }

            while (this.mainTabs.TabPages.Count > 2)
            {
                this.mainTabs.TabPages.RemoveAt(2);
            }

            this.panelLoaders.Clear();

            // Read connection strings
            foreach (var destination in Settings.Destinations)
            {
                var loader = new PanelLoader();
                loader.RemoveDestination += this.loader_RemoveDestination;
                loader.LoadPanel(destination.ConnectionString);
                this.panelLoaders.Add(loader);
                var tabPage = new TabPage(string.Format("Submit #{0}", this.panelLoaders.Count));
                tabPage.Controls.Add(loader);
                this.mainTabs.TabPages.Add(tabPage);
            }
        }
Exemple #12
0
        /// <summary>
        /// </summary>
        /// <param name="args">
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// </exception>
        private static void Main(string[] args)
        {
            LogUtil.SetupConsoleLogging(LogLevel.Debug);
            LogUtil.SetupFileLogging("${basedir}/LoginEngineLog.txt", LogLevel.Trace);



            SettingsOverride.LoadCustomSettings("NBug.LoginEngine.Config");
            Settings.WriteLogToDisk = true;
            AppDomain.CurrentDomain.UnhandledException += Handler.UnhandledException;
            TaskScheduler.UnobservedTaskException      += Handler.UnobservedTaskException;



            Console.Title = "CellAO " + AssemblyInfoclass.Title + " Console. Version: " + AssemblyInfoclass.Description
                            + " " + AssemblyInfoclass.AssemblyVersion + " " + AssemblyInfoclass.Trademark;

            var ct = new ConsoleText();

            ct.TextRead("main.txt");
            Console.Write("Loading ");
            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.Write(AssemblyInfoclass.Title + " ");
            Console.ForegroundColor = ConsoleColor.White;
            Console.Write(AssemblyInfoclass.Description);
            Console.ResetColor();
            Console.WriteLine("...");

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("[OK]");
            Console.ResetColor();

            // Sying helped figure all this code out, about 5 yearts ago! :P
            bool processedargs = false;

            loginServer = Container.GetInstance <LoginServer>();
            bool TCPEnable = true;
            bool UDPEnable = false;
            int  Port      = Convert.ToInt32(Config.Instance.CurrentConfig.LoginPort);

            try
            {
                if (Config.Instance.CurrentConfig.ListenIP == "0.0.0.0")
                {
                    loginServer.TcpEndPoint = new IPEndPoint(IPAddress.Any, Port);
                }
                else
                {
                    loginServer.TcpIP = IPAddress.Parse(Config.Instance.CurrentConfig.ListenIP);
                }
            }
            catch
            {
                ct.TextRead("ip_config_parse_error.txt");
                Console.ReadKey();
                return;
            }

            // TODO: ADD More Handlers.
            loginServer.MaximumPendingConnections = 100;

            #region Console Commands

            // Andyzweb: Added checks for start and stop
            // also added a running command to return status of the server
            // and added Console.Write("\nServer Command >>"); to login server
            string consoleCommand;
            ct.TextRead("login_consolecommands.txt");
            while (true)
            {
                if (!processedargs)
                {
                    if (args.Length == 1)
                    {
                        if (args[0].ToLower() == "/autostart")
                        {
                            ct.TextRead("autostart.txt");
                            loginServer.Start(TCPEnable, UDPEnable);
                        }
                    }

                    processedargs = true;
                }

                Console.Write("\nServer Command >>");

                consoleCommand = Console.ReadLine();
                string temp = string.Empty;
                while (temp != consoleCommand)
                {
                    temp           = consoleCommand;
                    consoleCommand = consoleCommand.Replace("  ", " ");
                }

                consoleCommand = consoleCommand.Trim();
                switch (consoleCommand.ToLower())
                {
                case "start":
                    if (loginServer.IsRunning)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        ct.TextRead("loginisrunning.txt");
                        Console.ResetColor();
                        break;
                    }

                    loginServer.Start(TCPEnable, UDPEnable);
                    break;

                case "stop":
                    if (!loginServer.IsRunning)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        ct.TextRead("loginisnotrunning.txt");
                        Console.ResetColor();
                        break;
                    }

                    loginServer.Stop();
                    break;

                case "exit":
                    Process.GetCurrentProcess().Kill();
                    break;

                case "running":
                    if (loginServer.IsRunning)
                    {
                        // Console.WriteLine("Login Server is running");
                        ct.TextRead("loginisrunning.txt");
                        break;
                    }

                    // Console.WriteLine("Login Server not running");
                    ct.TextRead("loginisnotrunning.txt");
                    break;

                    #region Help Commands....

                case "help":
                    ct.TextRead("logincmdhelp.txt");
                    break;

                case "help start":
                    ct.TextRead("helpstart.txt");
                    break;

                case "help exit":
                    ct.TextRead("helpstop.txt");
                    break;

                case "help running":
                    ct.TextRead("loginhelpcmdrunning.txt");
                    break;

                case "help Adduser":
                    ct.TextRead("logincmdadduserhelp.txt");
                    break;

                case "help setpass":
                    ct.TextRead("logincmdhelpsetpass.txt");
                    break;

                    #endregion

                default:

                    #region Adduser

                    // This section handles the command for adding a user to the database
                    if (consoleCommand.ToLower().StartsWith("adduser"))
                    {
                        string[] parts = consoleCommand.Split(' ');
                        if (parts.Length < 9)
                        {
                            Console.WriteLine(
                                "Invalid command syntax.\nPlease use:\nAdduser <username> <password> <number of characters> <expansion> <gm level> <email> <FirstName> <LastName>");
                            break;
                        }

                        string username = parts[1];
                        string password = parts[2];
                        int    numChars = 0;
                        try
                        {
                            numChars = int.Parse(parts[3]);
                        }
                        catch
                        {
                            Console.WriteLine("Error: <number of characters> must be a number (duh!)");
                            break;
                        }

                        int expansions = 0;
                        try
                        {
                            expansions = int.Parse(parts[4]);
                        }
                        catch
                        {
                            Console.WriteLine("Error: <expansions> must be a number between 0 and 2047!");
                            break;
                        }

                        if (expansions < 0 || expansions > 2047)
                        {
                            Console.WriteLine("Error: <expansions> must be a number between 0 and 2047!");
                            break;
                        }

                        int gm = 0;
                        try
                        {
                            gm = int.Parse(parts[5]);
                        }
                        catch
                        {
                            Console.WriteLine("Error: <GM Level> must be number (duh!)");
                            break;
                        }

                        string email = parts[6];
                        if (email == null)
                        {
                            email = string.Empty;
                        }

                        if (!TestEmailRegex(email))
                        {
                            Console.WriteLine("Error: <Email> You must supply an email address for this account");
                            break;
                        }

                        string firstname = parts[7];
                        try
                        {
                            if (firstname == null)
                            {
                                throw new ArgumentNullException();
                            }
                        }
                        catch
                        {
                            Console.WriteLine("Error: <FirstName> You must supply a first name for this accout");
                            break;
                        }

                        string lastname = parts[8];
                        try
                        {
                            if (lastname == null)
                            {
                                throw new ArgumentNullException();
                            }
                        }
                        catch
                        {
                            Console.WriteLine("Error: <LastName> You must supply a last name for this account");
                            break;
                        }

                        DBLoginData login = new DBLoginData
                        {
                            Username           = username,
                            AccountFlags       = 0,
                            Allowed_Characters = numChars,
                            CreationDate       = DateTime.Now,
                            Email      = email,
                            Expansions = expansions,
                            FirstName  = firstname,
                            LastName   = lastname,
                            GM         = gm,
                            Flags      = 0,
                            Password   = new LoginEncryption().GeneratePasswordHash(password)
                        };
                        try
                        {
                            LoginDataDao.WriteLoginData(login);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(
                                "An error occured while trying to add a new user account:\n{0}", ex.Message);
                            break;
                        }

                        Console.WriteLine("User added successfully.");
                        break;
                    }

                    #endregion

                    #region Hashpass

                    // This function just hashes the string you enter using the loginencryption method
                    if (consoleCommand.ToLower().StartsWith("hash"))
                    {
                        string Syntax =
                            "The Syntax for this command is \"hash <String to hash>\" alphanumeric no spaces";
                        string[] parts = consoleCommand.Split(' ');
                        if (parts.Length != 2)
                        {
                            Console.WriteLine(Syntax);
                            break;
                        }

                        string pass   = parts[1];
                        var    le     = new LoginEncryption();
                        string hashed = le.GeneratePasswordHash(pass);
                        Console.WriteLine(hashed);
                        break;
                    }

                    #endregion

                    #region setpass

                    // sets the password for the given username
                    // Added by Andyzweb
                    // Still TODO add exception and error handling
                    if (consoleCommand.ToLower().StartsWith("setpass"))
                    {
                        string Syntax =
                            "The syntax for this command is \"setpass <account username> <newpass>\" where newpass is alpha numeric no spaces";
                        string[] parts = consoleCommand.Split(' ');
                        if (parts.Length != 3)
                        {
                            Console.WriteLine(Syntax);
                            break;
                        }

                        string username = parts[1];
                        string newpass  = parts[2];
                        var    le       = new LoginEncryption();
                        string hashed   = le.GeneratePasswordHash(newpass);

                        try
                        {
                            LoginDataDao.WriteNewPassword(
                                new DBLoginData {
                                Username = username, Password = hashed
                            });
                        }
                        // yeah this part here, some kind of exception handling for mysql errors
                        catch (Exception ex)
                        {
                            Console.WriteLine("Could not set new Password\r\n" + ex.Message);
                            LogUtil.ErrorException(ex);
                        }
                    }

                    #endregion

                    ct.TextRead("login_consolecmdsdefault.txt");
                    break;
                }
            }

            #endregion
        }
Exemple #13
0
        private static void Main(string[] args)
        {
            bool processedargs = false;

            // Please dont kill the commented out lines below for the moment -NV
            //Misc.Playfields.Instance.playfields[0].districts.Add(new ZoneEngine.Misc.DistrictInfo());
            //Misc.Playfields.Instance.playfields[0].districts[0].districtName = "some district";
            //Misc.Playfields.Instance.playfields[0].districts.Add(new ZoneEngine.Misc.DistrictInfo());
            //Misc.Playfields.Instance.playfields[0].districts[1].districtName = "some other district";
            //Misc.DistrictInfo.DumpXML(@"C:\list.xml", Misc.Playfields.Instance.playfields[0]);

            #region Console Text...
            Console.Title = "CellAO " + AssemblyInfoclass.Title + " Console. Version: " + AssemblyInfoclass.Description
                            + " " + AssemblyInfoclass.AssemblyVersion + " " + AssemblyInfoclass.Trademark;

            ConsoleText ct = new ConsoleText();
            ct.TextRead("main.txt");
            Console.WriteLine("Loading " + AssemblyInfoclass.Title + "...");

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Using ISComm v1.0");
            Console.WriteLine("[OK]");
            Console.ResetColor();
            #endregion

            #region Delete old SqlError.log, so it doesnt get too big
            if (File.Exists("sqlerror.log"))
            {
                File.Delete("sqlerror.log");
            }
            #endregion

            #region ISComm Code Area...
            Console.WriteLine("[ISComm] Waiting for Link...");
            ChatCom.StartLink(Config.Instance.CurrentConfig.CommPort);
            //System.Console.WriteLine("[ISComm] Linked Successfully! :D");
            #endregion

            zoneServer = new Server {
                EnableTCP = true, EnableUDP = false
            };

            #region Script Loading Code Area..
            csc = new ScriptCompiler();
            #endregion

            try
            {
                zoneServer.TcpIP = IPAddress.Parse(Config.Instance.CurrentConfig.ListenIP);
            }
            catch
            {
                ct.TextRead("ip_config_parse_error.txt");
                Console.ReadKey();
                return;
            }
            try
            {
                zoneServer.UdpIP = IPAddress.Parse(Config.Instance.CurrentConfig.ListenIP);
            }
            catch
            {
                ct.TextRead("ip_config_parse_error.txt");
                Console.ReadKey();
                return;
            }

            zoneServer.TcpPort = Convert.ToInt32(Config.Instance.CurrentConfig.ZonePort);

            #region NLog
            LoggingConfiguration config        = new LoggingConfiguration();
            ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget();
            consoleTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
            FileTarget fileTarget = new FileTarget();
            config.AddTarget("file", fileTarget);
            fileTarget.FileName = "${basedir}/ZoneEngineLog.txt";
            fileTarget.Layout   = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
            LoggingRule rule1 = new LoggingRule("*", LogLevel.Trace, consoleTarget);
            config.LoggingRules.Add(rule1);
            LoggingRule rule2 = new LoggingRule("*", LogLevel.Trace, fileTarget);
            config.LoggingRules.Add(rule2);
            LogManager.Configuration = config;
            #endregion

            #region NBug
            SettingsOverride.LoadCustomSettings("NBug.ZoneEngine.Config");
            NBug.Settings.WriteLogToDisk = true;
            AppDomain.CurrentDomain.UnhandledException += Handler.UnhandledException;
            TaskScheduler.UnobservedTaskException      += Handler.UnobservedTaskException;
            //TODO: ADD More Handlers.
            #endregion

            FunctionC.ReadFunctions();
            Console.WriteLine("Registered " + FunctionC.NumberofRegisteredFunctions().ToString() + " Functions");

            #region Console Commands...
            string consoleCommand;
            ct.TextRead("zone_consolecommands.txt");
            // removed CheckDBs here, added commands check and updatedb (updatedb will change to a versioning

            while (true)
            {
                if (!processedargs)
                {
                    if (args.Length == 1)
                    {
                        if (args[0].ToLower() == "/autostart")
                        {
                            ct.TextRead("autostart.txt");
                            csc.Compile(false);
                            StartTheServer();
                        }
                    }
                    processedargs = true;
                }
                Console.Write("\nServer Command >>");
                consoleCommand = Console.ReadLine();
                switch (consoleCommand.ToLower())
                {
                case "start":
                    if (zoneServer.Running)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Zone Server is already running");
                        Console.ResetColor();
                        break;
                    }

                    //TODO: Add Sql Check.
                    csc.Compile(false);
                    StartTheServer();
                    break;

                case "startm":     // Multiple dll compile
                    if (zoneServer.Running)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Zone Server is already running");
                        Console.ResetColor();
                        break;
                    }

                    //TODO: Add Sql Check.
                    csc.Compile(true);
                    StartTheServer();
                    break;

                case "stop":
                    if (!zoneServer.Running)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Zone Server is not running");
                        Console.ResetColor();
                        break;
                    }
                    zoneServer.Stop();
                    ThreadMgr.Stop();
                    break;

                case "check":
                case "updatedb":
                    using (SqlWrapper sqltester = new SqlWrapper())
                    {
                        sqltester.CheckDBs();
                        Console.ResetColor();
                    }
                    break;

                case "exit":
                case "quit":
                    if (zoneServer.Running)
                    {
                        zoneServer.Stop();
                        ThreadMgr.Stop();
                    }
                    Process.GetCurrentProcess().Kill();
                    break;

                case "ls":     //list all available scripts, dont remove it since it does what it should
                    Console.WriteLine("Available scripts");

                    /* Old Lua way
                     * string[] files = Directory.GetFiles("Scripts");*/
                    string[] files = Directory.GetFiles("Scripts\\", "*.cs", SearchOption.AllDirectories);
                    if (files.Length == 0)
                    {
                        Console.WriteLine("No scripts were found.");
                        break;
                    }
                    Console.ForegroundColor = ConsoleColor.Green;
                    foreach (string s in files)
                    {
                        Console.WriteLine(s);

                        /* Old Lua way
                         * if (s.EndsWith(".lua"))
                         * {
                         *  Console.WriteLine(s.Split('\\')[1].Split('.')[0]);
                         * }*/
                    }
                    Console.ResetColor();
                    break;

                case "ping":
                    // ChatCom.Server.Ping();
                    Console.WriteLine("Ping is disabled till we can fix it");
                    break;

                case "running":
                    if (zoneServer.Running)
                    {
                        Console.WriteLine("Zone Server is Running");
                        break;
                    }
                    Console.WriteLine("Zone Server not Running");
                    break;

                case "online":
                    if (zoneServer.Running)
                    {
                        Console.ForegroundColor = ConsoleColor.White;
                        lock (zoneServer.Clients)
                        {
                            foreach (Client c in zoneServer.Clients)
                            {
                                Console.WriteLine("Character " + c.Character.Name + " online");
                            }
                        }
                        Console.ResetColor();
                    }
                    break;

                default:
                    ct.TextRead("zone_consolecmdsdefault.txt");
                    break;
                }
            }
        }
Exemple #14
0
        public void AppSettingsLoader_Load_UsesKeyOverride()
        {
            var mockSettingsLoader = new SettingLoaderMock();
            mockSettingsLoader.Settings.Add("IsFooBar", "Foobar");

            var settings = new SettingsOverride();

            Assert.IsTrue(AppSettingsLoader.Load(mockSettingsLoader, ref settings), "Load returned false");
            Assert.AreEqual("Foobar", settings.IsFoo, "String setting not set");
        }
Exemple #15
0
 internal void ReloadDefaults()
 {
     SettingsOverride.LoadCustomSettings(settings);
 }