Example #1
0
        public static void Init()
        {
            var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);

            var userFilePath = Path.Combine(localAppData, "LukasHaefliger");

            if (!Directory.Exists(userFilePath))
            {
                Directory.CreateDirectory(userFilePath);
            }
            var configFilePath = Path.Combine(userFilePath, "mysqlGenConfig.xml");
            var alreadyExists  = File.Exists(configFilePath);
            var config         = new Xmlconfig(configFilePath, true);

            Xmlconfig             = config;
            Settings              = config.Settings;
            config.CommitOnUnload = true;
            if (alreadyExists)
            {
                return;
            }
            #region initDefault
            Settings["server"]["MySQL"]["ServerIP"].Value = "";
            Settings["server"]["MySQL"]["User"].Value     = "";
            Settings["server"]["MySQL"]["Database"].Value = "";
            Settings["server"]["MySQL"]["Port"].Value     = "3306";
            Settings["server"]["MySQL"]["Password"].Value = "";
            Settings["server"]["MySQL"]["Prefix"].Value   = "";
            config.Commit();

            #endregion
        }
Example #2
0
        /// <summary>
        /// Performs loader-related initialization
        /// </summary>
        public virtual bool init()
        {
            Program.setD3Foreground();

            //Load Config
            _config = new Xmlconfig("config.xml", false).Settings;

            // Load scripts
            ///////////////////////////////////////////////
            Log.write("Loading scripts..");

            //Obtain the bot and operation types
            ConfigSetting         scriptConfig = new Xmlconfig("scripts.xml", false).Settings;
            IList <ConfigSetting> scripts      = scriptConfig["scripts"].GetNamedChildren("type");

            //Load the bot types
            List <Scripting.InvokerType> scriptingBotTypes = new List <Scripting.InvokerType>();

            foreach (ConfigSetting cs in scripts)
            {   //Convert the config entry to a bottype structure
                scriptingBotTypes.Add(
                    new Scripting.InvokerType(
                        cs.Value,
                        cs["inheritDefaultScripts"].boolValue,
                        cs["scriptDir"].Value)
                    );
            }

            //Load them into the scripting engine
            Scripting.Scripts.loadBotTypes(scriptingBotTypes);

            try
            {   //Loads!
                bool bSuccess = Scripting.Scripts.compileScripts();
                if (!bSuccess)
                {       //Failed. Exit
                    Log.write(TLog.Error, "Unable to load scripts.");
                    return(false);
                }
            }
            catch (Exception ex)
            {   //Error while compiling
                Log.write(TLog.Exception, "Exception while compiling scripts:\n" + ex.ToString());
                return(false);
            }

            string invokerType = _config["General/botType"].Value;

            //Instance our botType
            if (!Scripting.Scripts.invokerTypeExists(invokerType))
            {
                Log.write(TLog.Error, "Unable to find botType '{0}'", invokerType);
                return(false);
            }

            return(true);
        }
 private void btnSave_Click(object sender, EventArgs e)
 {
     Xmlconfig xcf = new Xmlconfig("Config.ini", true);
     xcf.Settings["EmployerInfo/AutoCheckUpdate"].boolValue = chxAutoCheckUpdate.Checked;
     frmMain.AutoCheckUpdate = chxAutoCheckUpdate.Checked;
     xcf.Settings["EmployerInfo/AskOpenFileWhenDone"].boolValue = chxAskOpenFileWhenDone.Checked;
     frmMain.AskOpenFileWhenDone = chxAskOpenFileWhenDone.Checked;
     xcf.Dispose();
     Close();
 }
Example #4
0
        /// <summary>
        /// Gets the property of the given key.
        /// </summary>
        /// <param name="name">Name of the property.</param>
        /// <param name="defaultValue">Value to use if it cannot be found.</param>
        /// <returns></returns>
        private static string Get(Xmlconfig config, string name, string defaultValue)
        {
            if (config.Settings.Contains(name))
            {
                return(config.Settings[name].Value);
            }

            config.Settings[name].Value = defaultValue;
            return(defaultValue);
        }
        private void frmSetting_Shown(object sender, EventArgs e)
        {
            Xmlconfig xcf = new Xmlconfig("Config.ini", true);
            Version = xcf.Settings["EmployerInfo/Version"].Value;
            if (Version == "") { txtVersion.Text = "Phần mềm chưa cập nhật lần nào!"; }
            else { txtVersion.Text = string.Format(txtVersion.Tag as string, Version); }

            chxAutoCheckUpdate.Checked = xcf.Settings["EmployerInfo/AutoCheckUpdate"].boolValue;
            chxAskOpenFileWhenDone.Checked = xcf.Settings["EmployerInfo/AskOpenFileWhenDone"].boolValue;

            xcf.Dispose();
        }
Example #6
0
        /// <summary>
        /// Loads additional assets specified by assets.xml
        /// </summary>
        public void loadAdditionalAssets()
        {       //Load up our assets config file
            ConfigSetting cfg = new Xmlconfig(@"../Global/assets.xml", false).Settings;

            foreach (ConfigSetting asset in cfg.GetNamedChildren("asset"))
            {   //Insert it into the asset list
                AssetFile assetf = AssetFileFactory.CreateFromGlobalFile <AssetFile>(asset.Value);

                if (assetf != null)
                {
                    addAssetData(assetf);
                }
            }
        }
Example #7
0
        /// <summary>
        /// Initializes our asset loader
        /// </summary>
        public static bool Init()
        {
            DownloadLocation = System.Environment.CurrentDirectory;
            ConfigSetting _config = ConfigSetting.Blank;

            Log.Write("Loading server config...");
            if (!System.IO.File.Exists(DownloadLocation + "/server.xml"))
            {
                Log.Write("Cannot find our server.xml file.");
                return(false);
            }

            _config = new Xmlconfig("server.xml", false).Settings;

            CurrentUrl = _config["server/URL"].Value;
            backupUrl  = _config["server/URLBackup"].Value;
            if (string.IsNullOrWhiteSpace(CurrentUrl) && string.IsNullOrWhiteSpace(backupUrl))
            {
                Log.Write("Cannot load server.xml file.");
                return(false);
            }

            hashList = _config["assets/HashList"].Value;
            manifest = _config["assets/AssetList"].Value;

            //Lets try pinging the server to see if its even active
            Log.Write("Pinging server...");
            if (!PingServer(CurrentUrl))
            {
                CurrentUrl = backupUrl;

                //Failed, try backup
                if (!PingServer(CurrentUrl))
                {
                    Log.Write(string.Format("Cannot download file updates, server not responding at {0}.", CurrentUrl));
                    return(false);
                }
            }

            return(true);
        }
Example #8
0
        /// <summary>
        /// Opens the connection.
        /// </summary>
        /// <returns></returns>
        protected static IDbConnection openConnection()
        {
            string        root_path   = CustomRootPathProvider.rootPath();
            var           db_provider = Xmlconfig.get("provider", root_path);
            IDbConnection connection  = null;

            if (db_provider.Value == "sql_compact")
            {
                connection = new SqlCeConnection(
                    Xmlconfig.get(db_provider.Value, root_path).Value
                    );
            }
            else
            {
                connection = new SqlConnection(
                    Xmlconfig.get(db_provider.Value, root_path).Value
                    );
            }

            connection.Open();
            return(connection);
        }
Example #9
0
        /// <summary>
        /// Convert an old type of configuration file to a new one, porting the settings over.
        /// </summary>
        /// <param name="config"></param>
        /// <param name="filename"></param>
        private static void ConvertFromLegacyConfig(Xmlconfig config, string filename)
        {
            try
            {
                ExeConfigurationFileMap map = new ExeConfigurationFileMap();
                map.ExeConfigFilename = filename;

                Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(
                    map, ConfigurationUserLevel.None);
                ConfigurationManager.RefreshSection("appSettings");

                foreach (String key in ConfigurationManager.AppSettings.AllKeys)
                {
                    if (key.Contains("ClientSettings"))
                    {
                        continue;
                    }
                    string newKey = key.Replace('.', '/');
                    try
                    {
                        config.Settings[newKey].Value = configuration.AppSettings.Settings[key].Value;
                    }
                    catch (NullReferenceException)
                    {
                        // Occasionally some obsolete fields will be removed from a config file but leave behind
                        // traces. This watches for that case.
                    }
                }
            }
            catch (Exception ex)
            {
                string errorMessage = ex.Message;
                string stackTrace   = ex.StackTrace.ToString();
                Console.WriteLine("{0}/{1}", errorMessage, stackTrace);
                throw;
                // TODO: Should we do something here?
            }
        }
Example #10
0
        public static void WriteOptions(VTankOptions options)
        {
            KeysConverter kc       = new KeysConverter();
            string        filename = GetConfigFilePath();
            Xmlconfig     config   = new Xmlconfig();

            config.Settings["ServerAddress"].Value                        = options.ServerAddress;
            config.Settings["ServerPort"].Value                           = options.ServerPort;
            config.Settings["DefaultAccount"].Value                       = options.DefaultAccount;
            config.Settings["MapsFolder"].Value                           = options.MapsFolder;
            config.Settings["options/video/Resolution"].Value             = options.videoOptions.Resolution;
            config.Settings["options/video/Windowed"].Value               = options.videoOptions.Windowed;
            config.Settings["options/video/TextureQuality"].Value         = options.videoOptions.TextureQuality;
            config.Settings["options/video/AntiAliasing"].Value           = options.videoOptions.AntiAliasing;
            config.Settings["options/video/ShadingEnabled"].Value         = options.videoOptions.ShadingEnabled;
            config.Settings["options/audio/ambientSound/Volume"].Value    = options.audioOptions.ambientSound.Volume;
            config.Settings["options/audio/ambientSound/Muted"].Value     = options.audioOptions.ambientSound.Muted;
            config.Settings["options/audio/backgroundSound/Volume"].Value = options.audioOptions.backgroundSound.Volume;
            config.Settings["options/audio/backgroundSound/Muted"].Value  = options.audioOptions.backgroundSound.Muted;
            config.Settings["options/gameplay/ShowNames"].Value           = options.gamePlayOptions.ShowNames;
            config.Settings["options/gameplay/ProfanityFilter"].Value     = options.gamePlayOptions.ProfanityFilter;
            config.Settings["options/gameplay/InterfacePlugin"].Value     = options.gamePlayOptions.InterfacePlugin;
            config.Settings["options/keybindings/Forward"].Value          = kc.ConvertToString(options.keyBindings.Forward);
            config.Settings["options/keybindings/Backward"].Value         = kc.ConvertToString(options.keyBindings.Backward);
            config.Settings["options/keybindings/RotateLeft"].Value       = kc.ConvertToString(options.keyBindings.RotateLeft);
            config.Settings["options/keybindings/RotateRight"].Value      = kc.ConvertToString(options.keyBindings.RotateRight);
            //config.Settings["options/keybindings/FirePrimary"].Value = kc.ConvertToString(options.keyBindings.FirePrimary);
            //config.Settings["options/keybindings/FireSecondary"].Value = kc.ConvertToString(options.keyBindings.FireSecondary);
            config.Settings["options/keybindings/Menu"].Value    = kc.ConvertToString(options.keyBindings.Menu);
            config.Settings["options/keybindings/Minimap"].Value = kc.ConvertToString(options.keyBindings.Minimap);
            config.Settings["options/keybindings/Score"].Value   = kc.ConvertToString(options.keyBindings.Score);
            config.Settings["options/keybindings/Camera"].Value  = kc.ConvertToString(options.keyBindings.Camera);
            config.Settings["options/keybindings/Pointer"].Value = options.keyBindings.Pointer;

            /*if (!System.IO.File.Exists(filename))
             * {
             *  System.IO.FileStream stream = System.IO.File.Create(filename);
             *  stream.Close();
             * }
             *
             * ExeConfigurationFileMap map = new ExeConfigurationFileMap();
             * map.ExeConfigFilename = filename;
             *
             * Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(
             *  map, ConfigurationUserLevel.None);
             *
             * foreach (String key in ConfigurationManager.AppSettings.AllKeys)
             * {
             *  configuration.AppSettings.Settings[key].Value =
             *      ConfigurationManager.AppSettings[key];
             * }
             *
             * configuration.Save(ConfigurationSaveMode.Modified);
             *
             * ConfigurationManager.RefreshSection("appSettings");*/

            if (!config.Commit())
            {
                config.Save(filename);
            }
        }
Example #11
0
    public SlideModule(IRootPathProvider pathProvider)
    {
        User me = null; //add the user  as a property to the model :)


        Before += ctx =>
        {
            if (ctx.Request.Cookies.ContainsKey("flex"))
            {
                var myId    = ctx.Request.Cookies["flex"];
                var id_user = new EncryptHelper(AppConfig.Provider,
                                                Xmlconfig.get(
                                                    "cryptokey",
                                                    pathProvider.GetRootPath()).Value).decrypt(myId);

                if (!string.IsNullOrEmpty(id_user))
                {
                    me = UsersRepository.getById(Convert.ToInt32(id_user));
                    return(null); //it means you can carry on!!!!
                }
            }

            var res = new Response();
            res.StatusCode = HttpStatusCode.Forbidden;
            return(res);
        };

        Get["/Slides"] = _ =>
        {
            var model = new
            {
                title  = "Mobile Day 2014",
                Slides = SlidesRepository.Slides,
                me     = me
            };
            return(View["Slides", model]);
        };

        Get[@"/Slides/{order}"] = parameters =>
        {
            //*important
            byte    order = parameters.order; //I'm forcing the right conversion
            dynamic model = null;

            if (order == 0)
            {
                model = new
                {
                    title = "Mobile Day 2014",
                    Slide = new Slide()
                    {
                        Ordine = 0, Contenuto = "", Stato = true
                    },
                    me = me
                };
            }
            else
            {
                model = new
                {
                    title = "Mobile Day 2014",
                    Slide = SlidesRepository.getByOrder(order),
                    me    = me
                };
            }
            return(View["single_Slide", model]);
        };

        Post["/Slides/{order}"] = parameters =>
        {
            short order     = parameters.order;
            Slide new_slide = null;

            new_slide = new Slide
            {
                Ordine    = Request.Form["ordine"],
                Contenuto = Request.Form["contenuto"],
                Attributi = Request.Form["attributi"],
                Stato     = Request.Form["stato"]
            };

            var old_slide = SlidesRepository.getByOrder(order);

            dynamic model = null;
            Slide   slide = null;

            if (old_slide == null)
            {
                if (new_slide.Ordine != 0)
                {
                    slide = SlidesRepository.muovi(new_slide);
                }
                else
                {
                    slide = SlidesRepository.nuovo(new_slide);
                }
            }
            else
            {
                slide = SlidesRepository.update(order, new_slide);
            }


            if (slide != null)
            {
                model = new
                {
                    title    = "Mobile Day 2014",
                    Slide    = slide,
                    success  = true,
                    messages = new List <string> {
                        "The Slide has been successfull modified"
                    },
                    me = me
                };
                if (order == 0)
                {
                    return(Response.AsRedirect("/slides/" + slide.Ordine)); //redirects to items
                }
            }
            else
            {
                model = new
                {
                    title    = "Mobile Day 2014",
                    Slide    = new_slide, //I'm going to return back the one given
                    success  = false,
                    messages = new List <string> {
                        "The Slide could not be modified"
                    },
                    me = me
                };
            }
            return(View["single_Slide", model]);
        };
    }
    public UserModule(IRootPathProvider pathProvider)
    {
        User me = null; //add the user  as a property to the model :)

        Before += ctx =>
        {
            if (ctx.Request.Cookies.ContainsKey("flex"))
            {
                var myId = ctx.Request.Cookies["flex"];
                var id_u = new EncryptHelper(AppConfig.Provider,
                                             Xmlconfig.get(
                                                 "cryptokey",
                                                 pathProvider.GetRootPath()).Value).decrypt(myId);

                if (!string.IsNullOrEmpty(id_u))
                {
                    me = UsersRepository.getById(Convert.ToInt32(id_u));
                    if (me != null)
                    {
                        return(null); //it means you can carry on!!!!
                    }
                }
            }

            var res = new Response();
            res.StatusCode = HttpStatusCode.Forbidden;
            return(res);
        };

        Get["/users"] = _ =>
        {
            var model = new
            {
                title = "Mobile Day 2014",
                users = UsersRepository.getOrderedByName(),
                me    = me
            };

            if (!me.IsAdmin) //check if I am an admin
            {
                var res = new Response();
                res.StatusCode = HttpStatusCode.Forbidden;
                return(res);
            }
            else
            {
                return(View["users", model]);
            }
        };

        Get[@"/users/{id:int}"] = parameters =>
        {
            //*important
            int id    = parameters.id; //I'm forcing the right conversion
            var puser = UsersRepository.getById(id);

            if (puser == null) //the user does not exists
            {
                var res = new Response();
                res.StatusCode = HttpStatusCode.NotFound;
                return(res);
            }

            var model = new
            {
                title = "Mobile Day 2014",
                user  = puser,
                me    = me
            };

            if ((me.Id != id) && !me.IsAdmin) //check if I am not an admin and I'm changing someone's else profile
            {
                var res = new Response();
                res.StatusCode = HttpStatusCode.Forbidden;
                return(res);
            }

            return(View["single_user", model]);
        };

        Post["/users/{id:int}"] = parameters =>
        {
            //*important
            int id = parameters.id;

            dynamic model = null;
            //check first if I'm a simple editor, not an Admin and I want to change someone's else profile
            if ((me.Id != id) && !me.IsAdmin)
            {
                var res = new Response();
                res.StatusCode = HttpStatusCode.Forbidden;
                return(res);
            }

            var us = new User
            {
                Id          = id,
                UserName    = Request.Form.username,
                Password    = Request.Form.password,
                SimpleRoles = Request.Form.hr
            };

            if ((me.Id == id) && me.IsAdmin && !us.SimpleRoles.Contains("0"))
            {
                model = new
                {
                    title    = "Mobile Day 2014",
                    user     = us,
                    me       = me,
                    success  = false,
                    messages = new List <string> {
                        "You can't quit being an admin!"
                    }
                };
            }
            else
            {
                var rip_password = Request.Form.repeate_password;

                //first of all validate data
                if ((us.Password != rip_password) && (!string.IsNullOrEmpty(us.Password)))
                {
                    model = new
                    {
                        title    = "Mobile Day 2014",
                        user     = us,
                        me       = me,
                        success  = false,
                        messages = new List <string> {
                            "Please, the passwords must match"
                        }
                    };
                }
                else
                {
                    //first of all validate data
                    if (string.IsNullOrEmpty(us.UserName) || (string.IsNullOrEmpty(us.SimpleRoles) && me.IsAdmin))
                    {
                        model = new
                        {
                            title    = "Mobile Day 2014",
                            user     = us,
                            me       = me,
                            success  = false,
                            messages = new List <string> {
                                "Please, provide username and at least one role."
                            }
                        };
                    }
                    else
                    {
                        var isChangePassword = false;
                        //Am I trying to change the password?
                        if (!string.IsNullOrEmpty(us.Password))
                        {
                            us.Password = new EncryptHelper(AppConfig.Provider, Xmlconfig.get("cryptokey",
                                                                                              pathProvider.GetRootPath()).Value).encrypt(us.Password); //real_password

                            isChangePassword = true;
                        }

                        if (me.IsAdmin) //only an admin can change the roles
                        {
                            us = UsersRepository.insertIfAdmin(us, isChangePassword);
                        }
                        else
                        {
                            us = UsersRepository.insert(us, isChangePassword);
                        }

                        if (us != null)
                        {
                            model = new
                            {
                                title    = "Mobile Day 2014",
                                user     = us,
                                me       = me,
                                success  = true,
                                messages = new List <string> {
                                    "User modified succesfully"
                                }
                            };
                        }
                        else
                        {
                            model = new
                            {
                                title    = "Mobile Day 2014",
                                user     = us,
                                me       = me,
                                success  = false,
                                messages = new List <string> {
                                    "Sorry, we couldn't find the user specified!"
                                }
                            };
                        }
                    }
                }
            }

            return(View["single_user", model]);
        };
    }
Example #13
0
 public Config(string configFile, bool createIfNotExists)
 {
     config = new Xmlconfig(configFile, createIfNotExists);
 }
 /// <summary>
 /// Create a collection of Users
 /// </summary>
 public static void create()
 {
     Users = Xmlconfig.getUsers(CustomRootPathProvider.rootPath());
 }
Example #15
0
        public static void Init()
        {
            var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);

            var userFilePath = Path.Combine(localAppData, "LukasHaefliger");

            if (!Directory.Exists(userFilePath))
            {
                Directory.CreateDirectory(userFilePath);
            }
            var configFilePath = Path.Combine(userFilePath, "windowSelector.xml");

#if DEBUG
            configFilePath += "d";
#endif
            var alreadyExists = File.Exists(configFilePath);
            var config        = new Xmlconfig(configFilePath, true);
            Xmlconfig             = config;
            Settings              = config.Settings;
            config.CommitOnUnload = true;
            if (alreadyExists)
            {
                return;
            }
            #region initDefault

            Settings["Settings"]["Color"].intValue = Color.Blue.ToArgb();
            Settings["Positions"]["N1"].Value      = "[" +
                                                     "{\"X\":0.0,\"Y\":50.0,\"Width\":50.0,\"Height\":50.0}," +
                                                     "{\"X\":0.0,\"Y\":50.0,\"Width\":25.0,\"Height\":50.0}," +
                                                     "{\"X\":0.0,\"Y\":50.0,\"Width\":33.33,\"Height\":50.0}," +
                                                     "{\"X\":0.0,\"Y\":50.0,\"Width\":66.67,\"Height\":50.0}" +
                                                     "]";
            Settings["Positions"]["N2"].Value = "[" +
                                                "{\"X\":0.0,\"Y\":50.0,\"Width\":100.0,\"Height\":50.0}," +
                                                "{\"X\":25.0,\"Y\":50.0,\"Width\":25.0,\"Height\":50.0}," +
                                                "{\"X\":50.0,\"Y\":50.0,\"Width\":25.0,\"Height\":50.0}," +
                                                "{\"X\":33.33,\"Y\":50.0,\"Width\":33.33,\"Height\":50.0}" +
                                                "]";
            Settings["Positions"]["N3"].Value = "[" +
                                                "{\"X\":50.0,\"Y\":50.0,\"Width\":50.0,\"Height\":50.0}," +
                                                "{\"X\":75.0,\"Y\":50.0,\"Width\":25.0,\"Height\":50.0}," +
                                                "{\"X\":66.67,\"Y\":50.0,\"Width\":33.33,\"Height\":50.0}," +
                                                "{\"X\":33.33,\"Y\":50.0,\"Width\":66.67,\"Height\":50.0}" +
                                                "]";
            Settings["Positions"]["N4"].Value = "[" +
                                                "{\"X\":0.0,\"Y\":0.0,\"Width\":50.0,\"Height\":100.0}," +
                                                "{\"X\":0.0,\"Y\":0.0,\"Width\":33.33,\"Height\":100.0}," +
                                                "{\"X\":0.0,\"Y\":0.0,\"Width\":66.67,\"Height\":100.0}," +
                                                "{\"X\":0.0,\"Y\":0.0,\"Width\":25,\"Height\":100.0}" +
                                                "]";
            Settings["Positions"]["N5"].Value = "[" +
                                                "{\"X\":0.0,\"Y\":0.0,\"Width\":100.0,\"Height\":100.0}," +
                                                "{\"X\":33.33,\"Y\":0.0,\"Width\":33.33,\"Height\":100.0}," +
                                                "{\"X\":16.67,\"Y\":0.0,\"Width\":66.67,\"Height\":100.0}" +
                                                "]";
            Settings["Positions"]["N6"].Value = "[" +
                                                "{\"X\":50.0,\"Y\":0.0,\"Width\":50.0,\"Height\":100.0}," +
                                                "{\"X\":66.67,\"Y\":0.0,\"Width\":33.33,\"Height\":100.0}," +
                                                "{\"X\":33.33,\"Y\":0.0,\"Width\":66.67,\"Height\":100.0}," +
                                                "{\"X\":75,\"Y\":0.0,\"Width\":25,\"Height\":100.0}" +
                                                "]";
            Settings["Positions"]["N7"].Value = "[" +
                                                "{\"X\":0.0,\"Y\":0.0,\"Width\":50.0,\"Height\":50.0}," +
                                                "{\"X\":0.0,\"Y\":0.0,\"Width\":25.0,\"Height\":50.0}," +
                                                "{\"X\":0.0,\"Y\":0.0,\"Width\":33.33,\"Height\":50.0}," +
                                                "{\"X\":0.0,\"Y\":0.0,\"Width\":66.67,\"Height\":50.0}" +
                                                "]";
            Settings["Positions"]["N8"].Value = "[" +
                                                "{\"X\":0.0,\"Y\":0.0,\"Width\":100.0,\"Height\":50.0}," +
                                                "{\"X\":25.0,\"Y\":0.0,\"Width\":25.0,\"Height\":50.0}," +
                                                "{\"X\":50.0,\"Y\":0.0,\"Width\":25.0,\"Height\":50.0}," +
                                                "{\"X\":33.33,\"Y\":0.0,\"Width\":33.33,\"Height\":50.0}" +
                                                "]";
            Settings["Positions"]["N9"].Value = "[" +
                                                "{\"X\":50.0,\"Y\":0.0,\"Width\":50.0,\"Height\":50.0}," +
                                                "{\"X\":75.0,\"Y\":0.0,\"Width\":25.0,\"Height\":50.0}," +
                                                "{\"X\":66.67,\"Y\":0.0,\"Width\":33.33,\"Height\":50.0}," +
                                                "{\"X\":33.33,\"Y\":0.0,\"Width\":66.67,\"Height\":50.0}" +
                                                "]";
            config.Commit();

            #endregion
        }
Example #16
0
 /// <summary>
 /// Gets the property of the given key.
 /// </summary>
 /// <param name="name">Name of the property.</param>
 /// <returns>The property at the key, or an empty string if it cannot be found.</returns>
 private static string Get(Xmlconfig config, string name)
 {
     return(Get(config, name, ""));
 }
 void Set_LastId(string id)
 {
     System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/EmployerInfo");
     if (!di.Exists) { di.Create(); }
     Xmlconfig xg = new Xmlconfig(di.FullName + "/AppConfig.xml", true);
     xg.Settings["LastId"].Value = id;
     xg.Save(di.FullName + "/AppConfig.xml");
 }
Example #18
0
        /// <summary>
        /// Performs loader-related initialization
        /// </summary>
        public virtual bool init()
        {
            Program.setD3Foreground();

            //Load Config
            _config = new Xmlconfig("config.xml", false).Settings;

            // Load scripts
            ///////////////////////////////////////////////
            Log.write("Loading scripts..");

            //Obtain the bot and operation types
            ConfigSetting scriptConfig = new Xmlconfig("scripts.xml", false).Settings;
            IList<ConfigSetting> scripts = scriptConfig["scripts"].GetNamedChildren("type");

            //Load the bot types
            List<Scripting.InvokerType> scriptingBotTypes = new List<Scripting.InvokerType>();

            foreach (ConfigSetting cs in scripts)
            {	//Convert the config entry to a bottype structure
                scriptingBotTypes.Add(
                    new Scripting.InvokerType(
                            cs.Value,
                            cs["inheritDefaultScripts"].boolValue,
                            cs["scriptDir"].Value)
                );
            }

            //Load them into the scripting engine
            Scripting.Scripts.loadBotTypes(scriptingBotTypes);

            try
            {	//Loads!
                bool bSuccess = Scripting.Scripts.compileScripts();
                if (!bSuccess)
                {	//Failed. Exit
                    Log.write(TLog.Error, "Unable to load scripts.");
                    return false;
                }
            }
            catch (Exception ex)
            {	//Error while compiling
                Log.write(TLog.Exception, "Exception while compiling scripts:\n" + ex.ToString());
                return false;
            }

            string invokerType = _config["General/botType"].Value;
            //Instance our botType
            if (!Scripting.Scripts.invokerTypeExists(invokerType))
            {
                Log.write(TLog.Error, "Unable to find botType '{0}'", invokerType);
                return false;
            }

            return true;
        }
        void Unpack()
        {
            _Status = "Đang giải nén dữ liệu...";
            Application.DoEvents();
            tmer.Stop();

            try
            {
                var options = new ReadOptions { StatusMessageWriter = System.Console.Out };
                using (ZipFile zip = ZipFile.Read(PathApp+FilePack, options))
                {
                    zip.ExtractAll(PathApp, ExtractExistingFileAction.OverwriteSilently);
                }

                // Xóa UpdatePack và cập nhật thông tin version
                if (File.Exists(PathApp + FilePack)) { File.Delete(PathApp + FilePack); }
                Xmlconfig xcf = new Xmlconfig("Config.ini", true);
                xcf.Settings["EmployerInfo/Version"].Value = _Version;
                xcf.Save("Config.ini");
                xcf.Dispose();

                RunSoft();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Quá trình cập nhật gặp lỗi!!!\n\n" + ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                Close();
            }
        }
    public LoginModule(IRootPathProvider pathProvider)
    {
        Before += ctx =>
        {
            if (ctx.Request.Cookies.ContainsKey("flex"))
            {
                var myId    = ctx.Request.Cookies["flex"];
                var id_user = new EncryptHelper(AppConfig.Provider,
                                                Xmlconfig.get(
                                                    "cryptokey",
                                                    pathProvider.GetRootPath()).Value).decrypt(myId);

                if (!string.IsNullOrEmpty(id_user))
                {
                    return(Response.AsRedirect("/slides")); //redirects to items
                }
            }

            return(null); //it means you can carry on!!!!
        };



        Get["/login"] = _ =>
        {
            var model = new
            {
                title = "Mobile Day 2014 - Reveal.js - The HTML Presentation Framework"
            };

            return(View["login", model]);
        };

        Post["/login"] = _ =>
        {
            dynamic model = null;

            var us = new User
            {
                UserName = Request.Form.username,
                Password = Request.Form.password,
            };

            //first of all validate data

            if (string.IsNullOrEmpty(us.UserName) || string.IsNullOrEmpty(us.Password))
            {
                model = new
                {
                    title    = "Mobile Day 2014 - Reveal.js - The HTML Presentation Framework",
                    user     = us,
                    success  = false,
                    messages = new List <string> {
                        "Please, provide username and password"
                    }
                };
            }
            else
            {
                us.Password = new EncryptHelper(AppConfig.Provider, Xmlconfig.get("cryptokey",
                                                                                  pathProvider.GetRootPath()).Value).encrypt(us.Password); //real_password

                var ut_res = UsersRepository.authenticate(us);

                if (ut_res != null)
                {
                    var myEncryptedId = new EncryptHelper(AppConfig.Provider, Xmlconfig.get("cryptokey",
                                                                                            pathProvider.GetRootPath()).Value).encrypt(ut_res.Id.ToString()); //encrypt 4 cookie

                    //create cookie, http only with encrypted id user and add it to the current response
                    var mc = new NancyCookie("flex", myEncryptedId, true);

                    var res = Response.AsRedirect("/slides");
                    res.WithCookie(mc);
                    return(res);
                }
                else
                {
                    model = new
                    {
                        title    = "Mobile Day 2014 - Reveal.js - The HTML Presentation Framework",
                        user     = us,
                        success  = false,
                        messages = new List <string> {
                            "Wrong username or password"
                        }
                    };
                }
            }

            return(View["login", model]);
        };
    }
Example #21
0
        /// <summary>
        /// Allows the server to preload all assets.
        /// </summary>
        public bool init()
        {               // Load configuration
            ///////////////////////////////////////////////
            //Load our server config
            _connections = new Dictionary <IPAddress, DateTime>();
            Log.write(TLog.Normal, "Loading Server Configuration");
            _config = new Xmlconfig("server.xml", false).Settings;

            string assetsPath = "assets\\";

            //Load our zone config
            Log.write(TLog.Normal, "Loading Zone Configuration");

            if (!System.IO.Directory.Exists(assetsPath))
            {
                Log.write(TLog.Error, "Unable to find assets directory '" + assetsPath + "'.");
                return(false);
            }

            string filePath = AssetFileFactory.findAssetFile(_config["server/zoneConfig"].Value, assetsPath);

            if (filePath == null)
            {
                Log.write(TLog.Error, "Unable to find config file '" + assetsPath + _config["server/zoneConfig"].Value + "'.");
                return(false);
            }

            _zoneConfig = CfgInfo.Load(filePath);

            //Load assets from zone config and populate AssMan
            try
            {
                _assets = new AssetManager();

                _assets.bUseBlobs = _config["server/loadBlobs"].boolValue;

                //Grab the latest global news if specified
                if (_config["server/updateGlobalNws"].Value.Length > 0)
                {
                    Log.write(TLog.Normal, String.Format("Grabbing latest global news from {0}...", _config["server/updateGlobalNws"].Value));
                    if (!_assets.grabGlobalNews(_config["server/updateGlobalNws"].Value, "..\\Global\\global.nws"))
                    {
                        try
                        {
                            string global;
                            if ((global = Assets.AssetFileFactory.findAssetFile("global.nws", _config["server/copyServerFrom"].Value)) != null)
                            {
                                System.IO.File.Copy(global, "..\\Global\\global.nws");
                            }
                        }
                        catch (System.UnauthorizedAccessException)
                        {
                        }
                    }
                }

                if (!_assets.load(_zoneConfig, _config["server/zoneConfig"].Value))
                {                       //We're unable to continue
                    Log.write(TLog.Error, "Files missing, unable to continue.");
                    return(false);
                }
            }
            catch (System.IO.FileNotFoundException ex)
            {                   //Report and abort
                Log.write(TLog.Error, "Unable to find file '{0}'", ex.FileName);
                return(false);
            }

            //Make sure our protocol helpers are aware
            Helpers._server = this;

            //Load protocol config settings
            base._bLogPackets = _config["server/logPackets"].boolValue;
            Client.udpMaxSize = _config["protocol/udpMaxSize"].intValue;
            Client.crcLength  = _config["protocol/crcLength"].intValue;
            if (Client.crcLength > 4)
            {
                Log.write(TLog.Error, "Invalid protocol/crcLength, must be less than 4.");
                return(false);
            }

            Client.connectionTimeout = _config["protocol/connectionTimeout"].intValue;
            Client.bLogUnknowns      = _config["protocol/logUnknownPackets"].boolValue;

            ClientConn <Database> .clientPingFreq = _config["protocol/clientPingFreq"].intValue;


            // Load scripts
            ///////////////////////////////////////////////
            Log.write("Loading scripts..");

            //Obtain the bot and operation types
            ConfigSetting         scriptConfig = new Xmlconfig("scripts.xml", false).Settings;
            IList <ConfigSetting> scripts      = scriptConfig["scripts"].GetNamedChildren("type");

            //Load the bot types
            List <Scripting.InvokerType> scriptingBotTypes = new List <Scripting.InvokerType>();

            foreach (ConfigSetting cs in scripts)
            {                   //Convert the config entry to a bottype structure
                scriptingBotTypes.Add(
                    new Scripting.InvokerType(
                        cs.Value,
                        cs["inheritDefaultScripts"].boolValue,
                        cs["scriptDir"].Value)
                    );
            }

            //Load them into the scripting engine
            Scripting.Scripts.loadBotTypes(scriptingBotTypes);

            try
            {                   //Loads!
                bool bSuccess = Scripting.Scripts.compileScripts();
                if (!bSuccess)
                {                       //Failed. Exit
                    Log.write(TLog.Error, "Unable to load scripts.");
                    return(false);
                }
            }
            catch (Exception ex)
            {                   //Error while compiling
                Log.write(TLog.Exception, "Exception while compiling scripts:\n" + ex.ToString());
                return(false);
            }

            if (_config["server/pathFindingEnabled"].boolValue)
            {
                Log.write("Initializing pathfinder..");
                _pathfinder = new Bots.Pathfinder(this);
                _pathfinder.beginThread();
            }
            else
            {
                Log.write("Pathfinder disabled, skipping..");
            }

            // Sets the zone settings
            //////////////////////////////////////////////
            _name         = _config["server/zoneName"].Value;
            _description  = _config["server/zoneDescription"].Value;
            _isAdvanced   = _config["server/zoneIsAdvanced"].boolValue;
            _bindIP       = _config["server/bindIP"].Value;
            _bindPort     = _config["server/bindPort"].intValue;
            _attemptDelay = _config["database/connectionDelay"].intValue;

            // Connect to the database
            ///////////////////////////////////////////////
            //Attempt to connect to our database

            //Are we connecting at all?
            if (_attemptDelay == 0)
            {
                //Skip the database!
                _bStandalone = true;
                Log.write(TLog.Warning, "Skipping database server connection, server is in stand-alone mode..");
            }
            else
            {
                _bStandalone = false;
                _dbLogger    = Log.createClient("Database");
                _db          = new Database(this, _config["database"], _dbLogger);
                _dbEP        = new IPEndPoint(IPAddress.Parse(_config["database/ip"].Value), _config["database/port"].intValue);

                _db.connect(_dbEP, true);
            }

            //Initialize other parts of the zoneserver class
            if (!initPlayers())
            {
                return(false);
            }
            if (!initArenas())
            {
                return(false);
            }

            // Create the ping/player count responder
            //////////////////////////////////////////////
            _pingResponder = new ClientPingResponder(_players);

            Log.write("Asset Checksum: " + _assets.checkSum());

            //Create a new player silenced list
            _playerSilenced = new Dictionary <string, Dictionary <int, DateTime> >();

            //Setup a new zoneserver recycling class
            _recycle        = new Dictionary <ZoneServer, DateTime>();
            _recycleAttempt = Environment.TickCount;

            //InitializeGameEventsDictionary();

            return(true);
        }
Example #22
0
        void CheckUpdate()
        {
            if (!File.Exists(Application.StartupPath + "\\" + @"\Update.exe")) { return; }

            try
            {
                Xmlconfig xcf = new Xmlconfig("Config.ini", true);
                string _Version = xcf.Settings["EmployerInfo/Version"].Value;
                AutoCheckUpdate = xcf.Settings["EmployerInfo/AutoCheckUpdate"].boolValue;
                AskOpenFileWhenDone = xcf.Settings["EmployerInfo/AskOpenFileWhenDone"].boolValue;

                if (!AutoCheckUpdate) { return; }

                string Link = "https://github.com/uyphamvuong/Rena_EmployerInfo/blob/master/README.md";
                WebBrowser wbr = new WebBrowser();
                DllWbr.Redirect(wbr, Link);
                string s_ = wbr.DocumentText;
                s_ = s_.Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace("\"", "'").Replace("  ", " ").Replace("  ", " ").Replace("  ", " ");
                string VersionNew = FuncHelp.CutFromTo(s_, ":::Rena_EmployerInfo Version:::", "</P>");

                xcf.Dispose();

                if (_Version != VersionNew)
                {
                    if (MessageBox.Show("Đã có phiên bản " + VersionNew + ", bản có muốn cập nhật?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        Process.Start("Update.exe");
                        Close();
                    }
                }

            }
            catch
            {

            }
        }
        void GetInfoFromWeb()
        {
            string s_  = "";
            try
            {
                DllWbr.Redirect(wbr, Link);
                s_ = wbr.DocumentText;
                s_ = s_.Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace("\"", "'").Replace("  ", " ").Replace("  ", " ").Replace("  ", " ");
                string VersionNew = FuncHelp.CutFromTo(s_, ":::Rena_EmployerInfo Version:::", "</P>");
                _LinkDown = FuncHelp.CutFromTo(s_, ":::Rena_EmployerInfo LinkDown:::", "</P>");
                _LinkDown = FuncHelp.CutFromTo(_LinkDown, "href='", "'");

                Xmlconfig xcf = new Xmlconfig("Config.ini", true);
                _Version = xcf.Settings["EmployerInfo/Version"].Value;
                xcf.Dispose();

                if (_Version != VersionNew)
                {
                    //Update
                    _Version = VersionNew;
                    startDownload();
                    _Status = "Đang tải gói dữ liệu cập nhật...";
                    tmer.Start();
                }
                else
                {
                    RunSoft();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("Quá trình cập nhật gặp lỗi!!!\n\n" + ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                Close();
            }
        }
Example #24
0
        public static VTankOptions ReadOptions()
        {
            bool          doCommit = false;
            VTankOptions  options  = new VTankOptions();
            KeysConverter kc       = new KeysConverter();

            VideoOptions    defaultVideo = getDefaultVideoOptions();
            AudioOptions    defaultAudio = getDefaultAudioOptions();
            GamePlayOptions defaultGame  = getDefaultGamePlayOptions();
            KeyBindings     defaultKeys  = getDefaultKeyBindings();

            string filename = GetConfigFilePath();

            if (!File.Exists(filename))
            {
                doCommit = true;
            }
            Xmlconfig config = new Xmlconfig(filename, true);

            try
            {
                if (config.Settings.Name == "configuration")
                {
                    // Old configuration file. Port to new configuration type.
                    config.NewXml("xml");
                    doCommit = true;
                    ConvertFromLegacyConfig(config, filename);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Warning: Your old configuration settings have been lost due to an unforeseen error.",
                                "Old configuration settings lost!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            // Configure options.
            // Format: options.Key = Get(config, "Key", "DefaultValue");
            options.ServerAddress                       = Get(config, "ServerAddress", "glacier2a.cis.vtc.edu");
            options.ServerPort                          = Get(config, "ServerPort", "4063");
            options.DefaultAccount                      = Get(config, "DefaultAccount");
            options.MapsFolder                          = Get(config, "MapsFolder", "maps");
            options.videoOptions.Resolution             = Get(config, "options/video/Resolution", defaultVideo.Resolution);
            options.videoOptions.Windowed               = Get(config, "options/video/Windowed", defaultVideo.Windowed);
            options.videoOptions.TextureQuality         = Get(config, "options/video/TextureQuality", defaultVideo.TextureQuality);
            options.videoOptions.AntiAliasing           = Get(config, "options/video/AntiAliasing", defaultVideo.AntiAliasing);
            options.videoOptions.ShadingEnabled         = Get(config, "options/video/ShadingEnabled", defaultVideo.ShadingEnabled);
            options.audioOptions.ambientSound.Volume    = Get(config, "options/audio/ambientSound/Volume", defaultAudio.ambientSound.Volume);
            options.audioOptions.ambientSound.Muted     = Get(config, "options/audio/ambientSound/Muted", defaultAudio.ambientSound.Muted);
            options.audioOptions.backgroundSound.Volume = Get(config, "options/audio/backgroundSound/Volume", defaultAudio.backgroundSound.Volume);
            options.audioOptions.backgroundSound.Muted  = Get(config, "options/audio/backgroundSound/Muted", defaultAudio.backgroundSound.Muted);
            options.gamePlayOptions.ShowNames           = Get(config, "options/gameplay/ShowNames", defaultGame.ShowNames);
            options.gamePlayOptions.ProfanityFilter     = Get(config, "options/gameplay/ProfanityFilter", defaultGame.ProfanityFilter);
            options.gamePlayOptions.InterfacePlugin     = Get(config, "options/gameplay/InterfacePlugin", defaultGame.InterfacePlugin);
            options.keyBindings.Forward                 = (Keys)kc.ConvertFromString(Get(config, "options/keybindings/Forward", defaultKeys.Forward.ToString()));
            options.keyBindings.Backward                = (Keys)kc.ConvertFromString(Get(config, "options/keybindings/Backward", defaultKeys.Backward.ToString()));
            options.keyBindings.RotateLeft              = (Keys)kc.ConvertFromString(Get(config, "options/keybindings/RotateLeft", defaultKeys.RotateLeft.ToString()));
            options.keyBindings.RotateRight             = (Keys)kc.ConvertFromString(Get(config, "options/keybindings/RotateRight", defaultKeys.RotateRight.ToString()));
            //options.keyBindings.FirePrimary = (Keys)kc.ConvertFromString(Get(config, "options/keybindings/FirePrimary", ""));
            //options.keyBindings.FireSecondary = (Keys)kc.ConvertFromString(Get(config, "options/keybindings/FireSecondary", ""));
            options.keyBindings.Menu    = (Keys)kc.ConvertFromString(Get(config, "options/keybindings/Menu", defaultKeys.Menu.ToString()));
            options.keyBindings.Minimap = (Keys)kc.ConvertFromString(Get(config, "options/keybindings/Minimap", defaultKeys.Minimap.ToString()));
            options.keyBindings.Score   = (Keys)kc.ConvertFromString(Get(config, "options/keybindings/Score", defaultKeys.Score.ToString()));
            options.keyBindings.Camera  = (Keys)kc.ConvertFromString(Get(config, "options/keybindings/Camera", defaultKeys.Camera.ToString()));
            options.keyBindings.Pointer = Get(config, "options/keybindings/Pointer", defaultKeys.Pointer);

            if (doCommit)
            {
                WriteOptions(options);
            }

            return(options);
        }