Пример #1
0
 /// <summary>
 ///     Force load data from ini file
 /// </summary>
 /// <param name="pathToIni">Path to ini file</param>
 public void ForceLoadData(string pathToIni)
 {
     if (data != null)
     {
         data = manager.forceLoadIniData(pathToIni);
     }
 }
Пример #2
0
        public static void CreateDefault()
        {
            //Create ini file
            FileIniDataParser parser = new FileIniDataParser();
            IniData data = new IniData();

            //Add global section
            data.Sections.AddSection("game");

            //Add global settings
            data["game"]["hidemode"] = "1";

            //Add collectors section
            data.Sections.AddSection("collectors");

            //Add collectors locations
            for (int i = 1; i <= 17; i++)
            {
                data["collectors"]["collector" + i] = "-1:-1";
            }

            //Add troops section
            data.Sections.AddSection("troops");

            //Add troops settings
            for (int i = 1; i <= 4; i++)
            {
                data["troops"]["barrack" + i] = "0";
            }

            //Add search section
            data.Sections.AddSection("search");

            //Add search settings
            data["search"]["gold"] = "50000";
            data["search"]["elixir"] = "50000";
            data["search"]["dark"] = "0";
            data["search"]["trophy"] = "0";
            data["search"]["bgold"] = "1";
            data["search"]["belixir"] = "1";
            data["search"]["bdark"] = "0";
            data["search"]["btrophy"] = "0";
            data["search"]["alert"] = "0";

            //Add attack section
            data.Sections.AddSection("attack");

            //Add attack settings
            data["attack"]["topleft"] = "True";
            data["attack"]["topright"] = "True";
            data["attack"]["bottomleft"] = "True";
            data["attack"]["bottomright"] = "True";
            data["attack"]["mode"] = "0";
            data["attack"]["maxtrophy"] = "1000";
            data["attack"]["bmaxtrophy"] = "False";
            data["attack"]["deploytime"] = "75";

            //Save the file
            parser.WriteFile(AppSettings.Cfg.FilePath, data);
        }
Пример #3
0
 public IniLoader(string iniFilePath)
 {
     if (iniFilePath != null && File.Exists(iniFilePath))
     {
         data = manager.getIniData(iniFilePath);
     }
 }
        /// <summary>
        ///     Writes the ini data to a stream.
        /// </summary>
        /// <param name="writer">A write stream where the ini data will be stored</param>
        /// <param name="iniData">An <see cref="IniData"/> instance.</param>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="writer"/> is <c>null</c>.
        /// </exception>
        public void WriteData(StreamWriter writer, IniData iniData)
        {
            if (writer == null)
                throw new ArgumentNullException("reader");

            writer.Write(iniData.ToString());
        }
Пример #5
0
 public static string GetValue(IniData config, string section, string key)
 {
     if (config.Sections.ContainsSection(section) && config[section].ContainsKey(key)) {
         return config[section][key];
     }
     else return string.Empty;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="MonoDevelop.WakaTime.WakaTimeConfigFile"/> class.
 /// </summary>
 static WakaTimeConfigFile()
 {
     _configParser = new FileIniDataParser();
     _configFilepath = GetConfigFilePath();
     _configData = (File.Exists(_configFilepath))
         ? _configParser.ReadFile(_configFilepath, new UTF8Encoding(false))
         : new IniData();
     Read();
 }
Пример #7
0
        public Settings()
        {
            if (!File.Exists("Config.ini"))
            {
                CreateAndSaveSettings();
            }

            _data = Parser.ReadFile("Config.ini");
        }
Пример #8
0
        /// <summary>
        ///     Writes the ini data to a stream.
        /// </summary>
        /// <param name="writer">A write stream where the ini data will be stored</param>
        /// <param name="iniData">An <see cref="IniData"/> instance.</param>
        /// <param name="formatter">Formaterr instance that controls how the ini data is transformed to a string</param>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="writer"/> is <c>null</c>.
        /// </exception>
        public void WriteData(StreamWriter writer, IniData iniData, IIniDataFormatter formatter)
        {
            if (formatter == null)
                throw new ArgumentNullException("formatter");
            if (iniData == null)
                throw new ArgumentNullException("iniData");
            if (writer == null)
                throw new ArgumentNullException("writer");

            writer.Write(iniData.ToString(formatter));
        }
Пример #9
0
        public void correct_comment_assigment_to_keydata()
        {
            IniData inidata = new IniData();
            inidata.Sections.AddSection("TestSection");

            KeyData key = new KeyData("TestKey");
            key.Value = "TestValue";
            key.Comments.Add("This is a comment");
            inidata["TestSection"].SetKeyData(key);

            Assert.That(inidata["TestSection"].GetKeyData("TestKey").Comments[0], Is.EqualTo("This is a comment"));
        }
Пример #10
0
        private static IniData ModifyINIData(IniData modifiedParsedData)
        {
            modifiedParsedData["GeneralConfiguration"]["setMaxErrors"] = "10";
            modifiedParsedData.Sections.AddSection("newSection");
            modifiedParsedData.Sections.GetSectionData("newSection").Comments
                .Add("This is a new comment for the section");
            modifiedParsedData.Sections.GetSectionData("newSection").Keys.AddKey("myNewKey", "value");
            modifiedParsedData.Sections.GetSectionData("newSection").Keys.GetKeyData("myNewKey").Comments
            .Add("new key comment");

            return modifiedParsedData;
        }
Пример #11
0
        public void WritingTotring_Test()
        {
            StringIniParser parser = new StringIniParser();
            IniData data = new IniData();

            data.Sections.AddSection("newSection1");
            data.Sections["newSection1"].AddKey("newKey1", "newValue1");
            data.Sections["newSection1"].AddKey("newKey2", "newValue5");

            string result = parser.WriteString(data);

            Assert.That(result, Is.Not.Empty);
            Assert.That(result.Length, Is.Not.EqualTo(0));
        }
Пример #12
0
        /// <summary>
        ///     EN: Constructor of class to create instance and set path to save file
        /// </summary>
        /// <param name="filePath">Path to file</param>
        /// <example>Example: how to create instance</example>
        /// <code>IniWriter("folder/filename.ini")</code>
        public IniWriter(string filePath)
        {
            if (filePath != null)
            {
                path = filePath;

                if (data == null)
                {
                    data = new IniData();
                }

                parser = new FileIniDataParser();
            }
        }
Пример #13
0
        private IniFile()
        {
            Data = new IniData();

            // If ini file is not present, then just exit.
            if (!System.IO.File.Exists(IniFile.IniFileName))
            {
                return;
            }

            // Else parse the data.
            var iniParser = new FileIniDataParser();
            Data = iniParser.ReadFile(IniFileName);
        }
        public Settings()
        {
            var settingsFile = Path.Combine(BasePath, "config.ini");
            if (!File.Exists(settingsFile))
            {
                Logger.Log(String.Format("Settings file {0} does not exist. Creating default file.", settingsFile), Logger.LogType.Warn, typeof(Settings));
                using (File.Create(settingsFile)) { }
            }
            Logger.Log(String.Format("Loading settings from {0}", settingsFile), typeof(Settings));

            _parser = new FileIniDataParser();
            _ini = _parser.ReadFile(settingsFile);
            LoadSettings();
        }
        public void AddUnresolvedDependencies(AssemblyReference parentAssembly)
        {
            var parser = new FileIniDataParser();
            var versionsFileData = new IniData();

            if (!Directory.Exists(@"cache\unresolved"))
                Directory.CreateDirectory(@"cache\unresolved");

            var file = @"cache\unresolved\" + parentAssembly.Item2 + _sectionSeparator + parentAssembly.Item1 + ".ini";
            if (File.Exists(file))
                return;

            parser.WriteFile(file, versionsFileData);
        }
        public void Save(SemanticVersion version, string name, DllReference parentAssembly)
        {
            var parser = new FileIniDataParser();
            var versionsFileData = new IniData();

            versionsFileData.Sections.AddSection("Dependency");
            versionsFileData.Sections["Dependency"].AddKey("version", version.ToString());
            versionsFileData.Sections["Dependency"].AddKey("name", name);
            
            if(!Directory.Exists("cache"))
                Directory.CreateDirectory("cache");

            parser.WriteFile(@"cache\" + parentAssembly.Id.Item1 + _sectionSeparator + parentAssembly.Id.Item2 + _sectionSeparator + name + ".ini", versionsFileData);
        }
Пример #17
0
		public string WriteString(IniData iniData) {
			using (MemoryStream ms = new MemoryStream()) {
				using (StreamWriter sw = new StreamWriter(ms)) {
					WriteData(sw, iniData);
					sw.Flush();

					string result = System.Text.Encoding.UTF8.GetString(ms.ToArray());

					ms.Close();
					sw.Close();

					return result;
				}
			}
		}
 public void Load(string path, bool clean) {
   SARAH.GetInstance().Log("ConfigManager", "Loading: " + path);
   var parser = new FileIniDataParser();
   var conf   = parser.ReadFile(path);
   //SARAH.GetInstance().Log("ConfigManager", conf.ToString());
   if (clean) {
     foreach (var section in conf.Sections) {
       section.LeadingComments.Clear();
       section.TrailingComments.Clear();
       foreach (var keydata in section.Keys) {
         keydata.Comments.Clear();
       }
     }
   }
   if (Config == null) { Config = conf;  } else { Config.Merge(conf); }
 }
Пример #19
0
        public IniFile(string fileName)
        {
            if (File.Exists(fileName)) {
                IniFileName = fileName;
            } else {
                var builtinSettingsFolder = SettingsForm.ProgramRootFolder + SettingsForm.BUILTIN_SETTINGS_SUBPATH;
                File.Copy(builtinSettingsFolder + "\\" + IniFileName,
                    Settings.Default.SettingsFolderPath + "\\" + IniFileName);
                return;
            }

            try {
                Data = Parser.ReadFile(IniFileName);
            } catch (Exception ex) {
                MessageBox.Show("Error reading ini file: '" + IniFileName + "' -- Error information: " + ex.ToString());
                return;
            }
        }
Пример #20
0
        public void write_key_and_value_without_blanks()
        {
            var data = new IniData();
            data.Sections.AddSection("section1");
            data["section1"].AddKey("key1", "value1");
            data.Configuration.AssigmentSpacer = "";

            var parser = new StreamIniDataParser();
            string tempPath = System.IO.Path.GetTempFileName();
            using (var sw = new System.IO.StreamWriter(tempPath))
            {
                parser.WriteData(sw, data);
            }

            Assert.AreEqual(@"[section1]
key1=value1
", System.IO.File.ReadAllText(tempPath));
        }
Пример #21
0
		public void SaveFile(string fileName, IniData parsedData) {
			if (string.IsNullOrEmpty(fileName))
				throw new ArgumentException("Bad filename");

			if (parsedData == null)
				throw new ArgumentNullException("parsedData");

			try {
				using (FileStream fs = File.Open(fileName, FileMode.Create, FileAccess.Write)) {
					using (StreamWriter sr = new StreamWriter(fs)) {
						WriteData(sr, parsedData);
					}
				}

			} catch (IOException ex) {
				throw new ParsingException(String.Format("Could not save data to file {0}", fileName), ex);
			}

		}
        public virtual string IniDataToString(IniData iniData)
        {
            var sb = new StringBuilder();

            if (Configuration.AllowKeysWithoutSection)
            {
                // Write global key/value data
                WriteKeyValueData(iniData.Global, sb);
            }

            //Write sections
            foreach (SectionData section in iniData.Sections)
            {
                //Write current section
                WriteSection(section, sb);
            }

            return sb.ToString();
        }
Пример #23
0
        public IActionResult GetLanguageAsJSON(string languageCode)
        {
            FileIniDataParser parser = new FileIniDataParser();
            Dictionary <string, Dictionary <string, string> > outerDict = new Dictionary <string, Dictionary <string, string> >();
            Dictionary <string, string> objDict = new Dictionary <string, string>();
            string currentDirectory             = Directory.GetCurrentDirectory();
            string filePath = string.Empty;

            if (Environment.GetEnvironmentVariable("GeneralSettings__LanguageFilesLocation") != null)
            {
                filePath = Path.Combine(currentDirectory, $"{Environment.GetEnvironmentVariable("GeneralSettings__LanguageFilesLocation")}{languageCode}.ini");
            }
            else
            {
                filePath = Path.Combine(currentDirectory, $"{_generalSettings.LanguageFilesLocation}{languageCode}.ini");
            }

            IniData parsedData = parser.ReadFile(filePath, Encoding.UTF8);

            // Iterate through all the sections
            foreach (SectionData section in parsedData.Sections)
            {
                // Iterate through all the keys in the current section
                // printing the values
                foreach (KeyData key in section.Keys)
                {
                    objDict.Add(key.KeyName, key.Value);
                }

                outerDict.Add(section.SectionName, objDict);
            }

            string json = Newtonsoft.Json.JsonConvert.SerializeObject(outerDict);

            return(Content(json, "application/json", Encoding.UTF8));
        }
Пример #24
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            IniData iniData;

            if (File.Exists(App._iniPath))
            {
                iniData = App._iniParser.ReadFile(App._iniPath, Encoding.UTF8);
            }
            else
            {
                // Copy the INI configuration from our parser
                iniData = new IniData {
                    Configuration = App._iniParser.Parser.Configuration
                };
            }

            var iniDir = Path.GetDirectoryName(App._iniPath);

            if (iniDir != null)
            {
                Directory.CreateDirectory(iniDir);
            }

            App._iniViewModel.SaveToIni(iniData);

            App._iniParser.WriteFile(App._iniPath, iniData, App.IniEncoding);

            Close();

            if (App.LaunchAfterSave)
            {
                var path  = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                var tpExe = Path.Combine(path, "TemplePlus.exe");
                Process.Start(tpExe);
            }
        }
Пример #25
0
        /// <summary>
        /// Sets the system target.
        /// </summary>
        /// <param name="SystemTarget">System target.</param>
        public void SetSystemTarget(ESystemTarget SystemTarget)
        {
            //possible values are:
            //Win64
            //Win32
            //Linux
            //Mac
            lock (ReadLock)
            {
                try
                {
                    FileIniDataParser Parser = new FileIniDataParser();
                    IniData           data   = Parser.ReadFile(GetConfigPath());

                    data["Local"]["SystemTarget"] = SystemTarget.ToString();

                    WriteConfig(Parser, data);
                }
                catch (IOException ioex)
                {
                    Console.WriteLine("IOException in SetSystemTarget(): " + ioex.Message);
                }
            }
        }
Пример #26
0
        public static bool Boot()
        {
            try
            {
                var     parser = new FileIniDataParser();
                IniData data   = parser.ReadFile("settings.ini");
                Conf.ServerIP   = data["Server"]["AgentServerIP"];
                Conf.AgentPort  = Convert.ToInt16(data["Server"]["AgentServerTCPPort"]);
                Conf.AgentPort2 = Convert.ToInt16(data["Server"]["AgentServerTCPPort2"]);
                Conf.RelayPort  = Convert.ToInt16(data["Server"]["RelayServerPort"]);
                Conf.CommunityAgentServerPort = Convert.ToInt16(data["Server"]["CommunityServerPort"]);
                Conf.LoadBalanceServerPort    = Convert.ToInt16(data["Server"]["LoadBalanceServerPort"]);
                Conf.Connstr   = data["Server"]["MySQLConnection"];
                Conf.HashCheck = Convert.ToBoolean(data["Server"]["HashCheck"]);
                Log.Info("Loading Settings.ini........Done");

                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return(false);
        }
Пример #27
0
        private void loadFromFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                var     parser = new FileIniDataParser();
                IniData data   = parser.ReadFile(openFileDialog.FileName);

                acOdTextBox.Text                        = data["Games"]["Odyssey"];
                acOrTextBox.Text                        = data["Games"]["Origins"];
                steepTextBox.Text                       = data["Games"]["Steep"];
                tempTextBox.Text                        = data["Temp"]["Path"];
                deleteTempCheckbox.Checked              = bool.Parse(data["Temp"]["DeleteOnExit"]);
                renderModeComboBox.SelectedIndex        = int.Parse(data["3D"]["RenderMode"]);
                pointSizeBar.Value                      = int.Parse(data["3D"]["PointSize"]);
                filelistSeparatorComboBox.SelectedIndex = int.Parse(data["Misc"]["FilelistSeparator"]);
                popupComboBox.SelectedIndex             = int.Parse(data["Misc"]["Popups"]);
                fixNormalsCheckBox.Checked              = bool.Parse(data["Misc"]["FixNormals"]);

                int[] values = data["3D"]["Background"].Split(',').ToList().Select(x => int.Parse(x)).ToArray();
                colorDialog.Color = Color.FromArgb(values[3], values[0], values[1], values[2]);

                Message.Success("Loaded settings from file.");
            }
        }
Пример #28
0
 public static void GetIniParam()
 {
     if (File.Exists("Configuration.ini"))
     {
         //Récupération des données depuis ini parser
         var     parser = new FileIniDataParser();
         IniData data   = parser.ReadFile("Configuration.ini");
         Serveursmtp        = data["Param Mail"]["serveursmtp"];
         Utilisateur        = data["Param Mail"]["utilisateur"];
         Motdepasse         = data["Param Mail"]["motdepasse"];
         Port               = data["Param Mail"]["port"];
         Protocol           = data["Param Mail"]["protocol"];
         Expediteur         = data["Param Mail"]["expediteur"];
         Destinataireprefac = data["Param Mail"]["destinataireprefac"];
         if (data["Param Mail"]["envoiemailprefac"] != null)
         {
             Envoiemailprefac = bool.Parse(data["Param Mail"]["envoiemailprefac"]);
         }
         else
         {
             Envoiemailprefac = true;
         }
     }
 }
        public virtual string IniDataToString(IniData iniData)
        {
            var sb = new StringBuilder();

            if (Configuration.AllowKeysWithoutSection)
            {
                // Write global key/value data
				if (iniData.Global.Any()) {
					var maxChars = iniData.Global.Max( key => key.KeyName.Length );
					var frmtPrfx = "{0,-" + maxChars.ToString() + "}";
	
					WriteKeyValueData(iniData.Global, sb, frmtPrfx);
				}
            }

            //Write sections
            foreach (SectionData section in iniData.Sections)
            {
                //Write current section
                WriteSection(section, sb);
            }

            return sb.ToString();
        }
Пример #30
0
        /// <summary>
        /// Get user settings and default settings for mod.
        /// </summary>
        public static void GetSettings(Mod mod, out IniData settings, out IniData defaultSettings)
        {
            // Load default settings
            defaultSettings = GetDefaultSettings(mod);

            // Load serialized settings or recreate them
            string path = SettingsPath(mod);

            if (File.Exists(path))
            {
                settings = parser.ReadFile(path);

                try
                {
                    if (settings[internalSection][settingsVersionKey] != defaultSettings[internalSection][settingsVersionKey])
                    {
                        ResetSettings(mod, ref settings, defaultSettings);
                        Debug.LogFormat("Settings for {0} are incompatible with current version. " +
                                        "New settings have been recreated with default values", mod.Title);
                    }
                }
                catch
                {
                    ResetSettings(mod, ref settings, defaultSettings);
                    Debug.LogErrorFormat("Failed to read settings for {0}. " +
                                         "New settings have been recreated with default values", mod.Title);
                }
            }
            else
            {
                settings = null;
                ResetSettings(mod, ref settings, defaultSettings);
                Debug.LogFormat("Missing settings for {0}. " +
                                "New settings have been recreated with default values.", mod.Title);
            }
        }
Пример #31
0
 public PinUpConfig(IniData data, Configuration parent) : base(data, parent)
 {
 }
Пример #32
0
 protected AbstractConfiguration(IniData data, Configuration parent)
 {
     _parent = parent;
     _data   = data;
 }
Пример #33
0
        /// <summary>
        ///     Parses a string containing valid ini data
        /// </summary>
        /// <param name="iniDataString">
        ///     String with data
        /// </param>
        /// <returns>
        ///     An <see cref="IniData"/> instance with the data contained in
        ///     the <paramref name="iniDataString"/> correctly parsed an structured.
        /// </returns>
        /// <exception cref="ParsingException">
        ///     Thrown if the data could not be parsed
        /// </exception>
        public IniData Parse(string iniDataString)
        {
            IniData iniData = Configuration.CaseInsensitive ? new IniDataCaseInsensitive() : new IniData();

            iniData.Configuration = this.Configuration.Clone();

            if (string.IsNullOrEmpty(iniDataString))
            {
                return(iniData);
            }

            _errorExceptions.Clear();
            _currentCommentListTemp.Clear();
            _currentSectionNameTemp = null;

            try
            {
                var lines = iniDataString.Split(new [] { "\n", "\r\n" }, StringSplitOptions.None);
                for (int lineNumber = 0; lineNumber < lines.Length; lineNumber++)
                {
                    var line = lines[lineNumber];

                    if (line.Trim() == String.Empty)
                    {
                        continue;
                    }

                    try
                    {
                        ProcessLine(line, iniData);
                    }
                    catch (Exception ex)
                    {
                        var errorEx = new ParsingException(ex.Message, lineNumber + 1, line, ex);
                        if (Configuration.ThrowExceptionsOnError)
                        {
                            throw errorEx;
                        }
                        else
                        {
                            _errorExceptions.Add(errorEx);
                        }
                    }
                }

                // Orphan comments, assing to last section/key value
                if (_currentCommentListTemp.Count > 0)
                {
                    // Check if there are actually sections in the file
                    if (iniData.Sections.Count > 0)
                    {
                        iniData.Sections.GetSectionData(_currentSectionNameTemp).TrailingComments
                        .AddRange(_currentCommentListTemp);
                    }
                    // No sections, put the comment in the last key value pair
                    // but only if the ini file contains at least one key-value pair
                    else if (iniData.Global.Count > 0)
                    {
                        iniData.Global.GetLast().Comments
                        .AddRange(_currentCommentListTemp);
                    }


                    _currentCommentListTemp.Clear();
                }
            }
            catch (Exception ex)
            {
                _errorExceptions.Add(ex);
                if (Configuration.ThrowExceptionsOnError)
                {
                    throw;
                }
            }


            if (HasError)
            {
                return(null);
            }
            return((IniData)iniData.Clone());
        }
Пример #34
0
        protected override void BeginProcessing()
        {
            base.BeginProcessing();

            var dotHg = SessionState.Path.CurrentFileSystemLocation.ToString()
                        + @"\.hg";

            if (!Directory.Exists(dotHg))
            {
                Console.WriteLine("Please init an hg repository.");
                ThrowTerminatingError(new ErrorRecord(new DirectoryNotFoundException("Please init an hg repository"),
                                                      @"0", ErrorCategory.ObjectNotFound, dotHg));
            }

            var psHomeDrive = SessionState.PSVariable.GetValue("HOMEDRIVE");
            var psHomePath  = SessionState.PSVariable.GetValue("HOMEPATH");
            var hgIniPath   = (string)psHomeDrive + (string)psHomePath + @"\mercurial.ini";

            HgrcData           = new IniData();
            AuthSectionData    = new SectionData("auth");
            PathsSectionData   = new SectionData("paths");
            UiSectionData      = new SectionData("ui");
            HgIniUiSectionData = new SectionData("ui");

            _parser.Parser.Configuration.CommentString = "#";

            try
            {
                HgIniData = _parser.ReadFile(hgIniPath);
            }
            catch (ParsingException e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("There was a problem reading your mercurial.ini file.");
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine(
                    "\nThe default location is {0}{1}.\nDue to TortoiseHg formatting, New-Hgrc uses #-style comments.",
                    psHomeDrive, psHomePath);
                Console.ResetColor();
                return;
            }

            HgIniTortoiseHgSectionData = HgIniData.Sections.GetSectionData("tortoisehg");

            if (HgIniData.Sections.ContainsSection("ui"))
            {
                HgIniUiSectionData = HgIniData.Sections.GetSectionData("ui");
            }

            if (HgIniUiSectionData.Keys.ContainsKey("username"))
            {
                if (!HgIniUiSectionData.Keys.GetKeyData("username").Value.Equals(String.Empty) &&
                    !HgIniUiSectionData.Keys.GetKeyData("username").Value.Equals(null))
                {
                    Console.WriteLine(
                        "Your global UI username is currently {0}.\nUse for this repository?",
                        HgIniUiSectionData.Keys.GetKeyData("username").Value);
                    var cki = PromptYn();
                    Console.WriteLine();
                    if (cki.Key == ConsoleKey.Y || cki.Key == ConsoleKey.Enter)
                    {
                        AuthSectionData.Keys.AddKey("default.username", HgIniUiSectionData.Keys.GetKeyData("username").Value);
                        UiSectionData.Keys.AddKey("username", HgIniUiSectionData.Keys.GetKeyData("username").Value);
                    }
                    if (cki.Key == ConsoleKey.N)
                    {
                        PromptUsername();
                    }
                }
            }
            else
            {
                Console.WriteLine("New-Hgrc was unable to find a [ui].username value in your mercurial.ini.");
                PromptUsername();
            }

            PromptRemotePath();
        }
Пример #35
0
    // Constructor takes a path in which to look for content
    public ContentData(string path)
    {
        // This is all of the available sides of tiles (not currently tracking physical tiles)
        tileSides = new Dictionary <string, TileSideData>();

        // Available heros
        heros = new Dictionary <string, HeroData>();

        // Available monsters
        monsters = new Dictionary <string, MonsterData>();

        //This has the game game and all expansions, general info
        allPacks = new List <ContentPack>();

        // This has all monster activations
        activations = new Dictionary <string, ActivationData>();

        // This has all available tokens
        tokens = new Dictionary <string, TokenData>();

        // This has all avilable perils
        perils = new Dictionary <string, PerilData>();

        // Search each directory in the path (one should be base game, others expansion.  Names don't matter
        string[] contentDirectories = Directory.GetDirectories(path);
        foreach (string p in contentDirectories)
        {
            // All packs must have a content_pack.ini, otherwise ignore
            if (File.Exists(p + "/content_pack.ini"))
            {
                ContentPack pack = new ContentPack();

                // Get all data from the file
                IniData d = IniRead.ReadFromIni(p + "/content_pack.ini");
                // Todo: better error handling
                if (d == null)
                {
                    Debug.Log("Failed to get any data out of " + p + "/content_pack.ini!");
                    Application.Quit();
                }

                pack.name = d.Get("ContentPack", "name");
                if (pack.name.Equals(""))
                {
                    Debug.Log("Failed to get name data out of " + p + "/content_pack.ini!");
                    Application.Quit();
                }

                // id can be empty/missing
                pack.id = d.Get("ContentPack", "id");

                // If this is invalid we will just handle it later, not fatal
                pack.image = p + "/" + d.Get("ContentPack", "image");

                // Black description isn't fatal
                pack.description = d.Get("ContentPack", "description");

                // Get all the other ini files in the pack
                List <string> files = new List <string>();
                // content_pack file is included
                files.Add(p + "/content_pack.ini");

                // No extra files is valid
                if (d.Get("ContentPackData") != null)
                {
                    foreach (string file in d.Get("ContentPackData").Keys)
                    {
                        files.Add(p + "/" + file);
                    }
                }
                // Save list of files
                pack.iniFiles = files;

                // Add content pack
                allPacks.Add(pack);

                // We finish without actually loading the content, this is done later (content optional)
            }
        }
    }
Пример #36
0
        /// <summary>
        ///     EN: Set data and set data to cache
        /// </summary>
        /// <returns>Data from ini file</returns>
        private void setDataSetCache(string pathToIni)
        {
            if (pathToIni != null && File.Exists(pathToIni))
            {
                lock (syncValue)
                {
                    nameCache = pathToIni;
                    cache = parser.ReadFile(pathToIni);
                }

                lock (syncContainer)
                {
                    container.Add(nameCache, cache);
                }
            }
        }
Пример #37
0
 public void SetKeyFieldValue(string section_nm, string strKey_nm, string strKeyValue)
 {
     parsedData = parser.LoadFile(this.path);
     parsedData[section_nm][strKey_nm] = strKeyValue;
     parser.SaveFile(path, parsedData);
 }
Пример #38
0
        public MainWindow()
        {
            InitializeComponent();

            mUpdateRecentTransactionTimer           = new System.Timers.Timer(2500);
            mUpdateRecentTransactionTimer.Elapsed  += _UpdateRecentTransaction;
            mUpdateRecentTransactionTimer.AutoReset = true;
            mUpdateRecentTransactionTimer.Enabled   = true;

            mUpdateOrderBookTimer           = new System.Timers.Timer(2500);
            mUpdateOrderBookTimer.Elapsed  += _UpdateOrderBook;
            mUpdateOrderBookTimer.AutoReset = true;
            mUpdateOrderBookTimer.Enabled   = true;

            if (File.Exists("config.ini"))
            {
                var     parser = new FileIniDataParser();
                IniData config = parser.ReadFile("config.ini");

                bool   needSave = false;
                string value    = "";

                value = config["option"]["coin"];
                if (value.Length == 0)
                {
                    config["option"]["coin"] = mCoin;
                    needSave = true;
                }
                else
                {
                    mCoin = value;
                }

                value = config["option"]["flashing"];
                if (value.Length == 0)
                {
                    config["option"]["flashing"] = mUseFlashing.ToString();
                    needSave = true;
                }
                else
                {
                    mUseFlashing = bool.Parse(value);
                }

                value = config["option"]["topmost"];
                if (value.Length == 0)
                {
                    config["option"]["topmost"] = mUseTopMost.ToString();
                    needSave = true;
                }
                else
                {
                    mUseTopMost = bool.Parse(value);
                }

                if (needSave)
                {
                    parser.WriteFile("config.ini", config);
                }
            }
            else
            {
                var     parser = new FileIniDataParser();
                IniData config = new IniData();
                config["option"]["coin"]     = mCoin;
                config["option"]["flashing"] = mUseFlashing.ToString();
                config["option"]["topmost"]  = mUseTopMost.ToString();
                parser.WriteFile("config.ini", config);
            }

            this.Title   = mCoin + " Monitor";
            this.Topmost = mUseTopMost;
        }
Пример #39
0
        /// <summary>
        ///     EN: Force loading data from specyfic file without read from cache, but set to temporary cache and add to cache
        ///     container
        /// </summary>
        /// <param name="pathToIni">Path to ini file</param>
        /// <returns>Data from ini file</returns>
        public IniData forceLoadIniData(string pathToIni)
        {
            if (pathToIni != null && File.Exists(pathToIni))
            {
                lock (syncValue)
                {
                    nameCache = pathToIni;
                    cache = parser.ReadFile(pathToIni);
                }

                lock (syncContainer)
                {
                    if (container.Count > 0 && container.ContainsKey(nameCache))
                    {
                        updateContainerValue(nameCache, cache);
                    }
                    else
                    {
                        container.Add(nameCache, cache);
                    }
                }


                return cache;
            }

            return null;
        }
Пример #40
0
        /// <summary>
        /// Loads and registers the <see cref="GadgetMod"/> represented by the given file. Will log a warning and return null if the given file is not a valid <see cref="GadgetMod"/>. Will also add the name to <see cref="ErroredMods"/> if the file was valid, but an error occured during the mod-loading process.
        /// </summary>
        public static GadgetMod LoadModFile(string modFile)
        {
            string  modName = null;
            ZipFile modZip  = null;

            try
            {
                modZip = new ZipFile(modFile);
                if (Path.GetExtension(modFile) == ".umfmod")
                {
                    GadgetCore.CoreLib.DecryptUMFModFile(modZip);
                }
                if (modZip.ContainsEntry("Manifest.ini"))
                {
                    if (modZip.ContainsEntry("Libs"))
                    {
                        foreach (ZipEntry lib in modZip.Entries.Where(x => !x.IsDirectory && x.FileName.StartsWith("Libs")))
                        {
                            string existingFilePath = Path.Combine(GadgetPaths.GadgetCorePath, lib.FileName);
                            if (!File.Exists(existingFilePath) || lib.ModifiedTime > new FileInfo(existingFilePath).LastWriteTime)
                            {
                                lib.Extract(GadgetPaths.GadgetCorePath, ExtractExistingFileAction.OverwriteSilently);
                            }
                        }
                    }
                    using (MemoryStream stream = new MemoryStream())
                    {
                        modZip["Manifest.ini"].Extract(stream);
                        stream.Position = 0;
                        IniData manifest = manifestIniParser.ReadData(new StreamReader(stream));
                        modName = manifest["Metadata"]["Name"];
                        stream.SetLength(0);
                        if (manifest["Metadata"]["Assembly"] != null && modZip.ContainsEntry(manifest["Metadata"]["Assembly"]))
                        {
                            modZip[manifest["Metadata"]["Assembly"]].Extract(stream);
                        }
                        else
                        {
                            Logger.LogWarning("Failed to load mod `" + modName + "` because " + (manifest["Metadata"]["Assembly"] != null ? "the assembly name in its manifest is not valid!" : "its manifest does not contain the name of its asembly!"));
                            return(null);
                        }
                        Assembly modAssembly = Assembly.Load(stream.ToArray());
                        GadgetCore.LoadedAssemblies[modAssembly.GetName().Name] = modAssembly;
                        GadgetMod mod = new GadgetMod(modFile, manifest, modAssembly, modZip);
                        GadgetMods.RegisterMod(mod);
                        if (!BatchLoading)
                        {
                            LoadGadgetMod(mod);
                        }
                        modZip = null;
                        return(mod);
                    }
                }
                else
                {
                    Logger.LogWarning("Invalid or non-mod file '" + Path.GetFileName(modFile) + "' in Mods directory!");
                }
            }
            catch (Exception e)
            {
                Logger.LogError("Exception loading mod file '" + Path.GetFileName(modFile) + "':");
                Logger.LogError(e.ToString());
                if (modName != null)
                {
                    Tuple <string, string> erroredMod = Tuple.Create(modName, modFile);
                    if (!m_ErroredMods.Contains(erroredMod))
                    {
                        m_ErroredMods.Add(erroredMod);
                    }
                }
            }
            finally
            {
                modZip?.Dispose();
            }
            return(null);
        }
Пример #41
0
        public ProgramSettings(string iniFileName)
        {
            // is exists INI-file?
            Program.log.Debug(String.Format("Read INI File \"{0}\"", iniFileName));
            if (!File.Exists(iniFileName))
            {
                Program.log.Fatal("WinLogCheck stop: Cannot find INI File");
                Environment.Exit(2);
            }
            // read INI-file
            IniParser.FileIniDataParser iniParser = new FileIniDataParser();
            iniParser.CommentDelimiter = '#';
            IniData iniData = null;

            try
            {
                iniData = iniParser.LoadFile(iniFileName);
            }
            catch (Exception ex)
            {
                Program.log.Fatal("WinLogCheck stop: Cannot read INI File. " + ex);
                Environment.Exit(2);
            }
            // check report path and create it if not exists
            ReportPath = "";
            try
            {
                ReportPath = iniData["General"]["ReportPath"];
                if (String.IsNullOrWhiteSpace(ReportPath))
                {
                    ReportPath = "reports";
                }
                Program.log.Info(String.Format("Use directory \"{0}\" for temporary report.", ReportPath));
            }
            catch
            {
                ReportPath = "reports";
                Program.log.Info(String.Format("Use default directory \"{0}\" for temporary report.", ReportPath));
            }
            if (!Directory.Exists(ReportPath))
            {
                Program.log.Info(String.Format("Not exist directory \"{0}\". Create it.", ReportPath));
                try
                {
                    Directory.CreateDirectory(ReportPath);
                }
                catch (Exception ex)
                {
                    Program.log.Fatal(String.Format("WinLogCheck stop: Cannot create directory {0}. Stack: {1}", ReportPath, ex));
                    Environment.Exit(2);
                }
            }
            // check mail settings
            SMTP_Server = "";
            Mail_From   = "";
            Mail_To     = "";
            try
            {
                SMTP_Server = iniData["Mail"]["SMTP_Server"];
                Mail_From   = iniData["Mail"]["Mail_From"];
                Mail_To     = iniData["Mail"]["Mail_To"];
                if (String.IsNullOrWhiteSpace(SMTP_Server) || String.IsNullOrWhiteSpace(Mail_From) || String.IsNullOrWhiteSpace(Mail_To))
                {
                    SendReport = false;
                    Program.log.Warn("Check mail settings. Send summary report DISABLED");
                }
                else
                {
                    SendReport = true;
                    Program.log.Info("Send summary report ENABLED");
                }
            }
            catch
            {
                SendReport = false;
                Program.log.Warn("Check mail settings. Send summary report DISABLED");
            }
            ReportCSS = "";
            try
            {
                ReportCSS = iniData["General"]["ReportCSS"];
            }
            catch {}
            string sTimePeriod = "";

            try
            {
                sTimePeriod = iniData["General"]["TimePeriod"];
            }
            catch { }
            if (String.IsNullOrWhiteSpace(sTimePeriod))
            {
                TimePeriod = 24;
            }
            else
            {
                try
                {
                    TimePeriod = Convert.ToInt32(sTimePeriod);
                }
                catch
                {
                    TimePeriod = 24;
                }
            }
            Program.log.Info(String.Format("Get report for last {0} hours", TimePeriod.ToString()));
            WhereTime = DateTime.UtcNow.AddHours(-TimePeriod).ToString("yyyyMMdd HH:mm:ss");
        }
Пример #42
0
 public AppConfiguration(IniData data)
 {
     this.data = data;
 }
Пример #43
0
        public Form1()
        {
            InitializeComponent();

            //Create an instance of a ini file parser
            parser = new FileIniDataParser();
            parser.Parser.Configuration.CommentString = "#";

            String configINI = Environment.CurrentDirectory + "\\config.ini";
            parsedData = parser.ReadFile(configINI);

            //This line gets the SectionData from the section "global"
            KeyDataCollection keyCol = parsedData["global"];

            numerJezdni = keyCol["numerJezdni"];
            kierunek = keyCol["kierunek"];
            pasRuchu = keyCol["pasRuchu"];
            kategoriaDrogi = keyCol["kategoriaDrogi"];
            picturesPath = keyCol["picturesPath"];
            makroPath = keyCol["makroPath"];
            powiat = keyCol["powiat"];
            gmina = keyCol["gmina"];

            if (Directory.Exists(Environment.CurrentDirectory + "\\Headers"))
            {
                String[] headerFiles = Directory.GetFiles(Environment.CurrentDirectory + "\\Headers", "*.xml");
                foreach(String headerPath in headerFiles){

                    if (headerPath.ToLower().Contains("tp1a"))
                    {
                        tp1aHeader = new XmlDocument();
                        tp1aHeader.Load(headerPath);
                    }
                    else if (headerPath.ToLower().Contains("tp1b"))
                    {
                        tp1bHeader = new XmlDocument();
                        tp1bHeader.Load(headerPath);
                    }
                    else if (headerPath.ToLower().Contains("tp3"))
                    {
                        tp3Header = new XmlDocument();
                        tp3Header.Load(headerPath);
                    }
                    else if(headerPath.ToLower().Contains("foto"))
                    {
                        fotoHeader = new XmlDocument();
                        fotoHeader.Load(headerPath);
                    }

                }
            }

            bool sqliteExist = checkSQLite();

            if (!sqliteExist)
            {
                createDatabaseSqlite();

                createTables(sqlCon);
            }
            else
            {
                if (sqlCon == null || sqlCon.State != ConnectionState.Open)
                {
                   sqlCon = SetConnection();
                }

                SQLiteCommand cmd = sqlCon.CreateCommand();
                cmd.CommandText = "SELECT count(*) FROM dane";
                int count = Convert.ToInt32(cmd.ExecuteScalar());

                if(count !=0){
                    richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, FontStyle.Bold);
                    richTextBox1.AppendText("SQLite database exist and contains data."+Environment.NewLine);
                }
                else
                {
                    richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, FontStyle.Bold);
                    richTextBox1.AppendText("SQLite database exist with no data." + Environment.NewLine);
                }

            }

            if (Directory.Exists(Environment.CurrentDirectory + "\\xsd"))
            {
                String[] filesXSD = Directory.GetFiles(Environment.CurrentDirectory + "\\xsd");

                if (filesXSD != null && filesXSD.Length != 0)
                {
                    schemaDSN = new XmlSchemaSet();
                    schemaDSN.Add("http://www.gddkia.gov.pl/dsn/1.0.0", Environment.CurrentDirectory + "\\xsd\\dane_elementarne.xsd");

                    schemaGML = new XmlSchemaSet();
                    schemaGML.Add("http://www.opengis.net/gml", Environment.CurrentDirectory + "\\xsd\\gml\\gmlProfileDSN.xsd");

                    richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, FontStyle.Bold);
                    richTextBox1.AppendText("XSD Schema loaded." + Environment.NewLine);
                }
                else
                {
                    richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, FontStyle.Bold);
                    richTextBox1.AppendText("XSD Schema is not present." + Environment.NewLine);
                }
            }
        }
Пример #44
0
        public ProgramSettings(string iniFileName)
        {
            // is exists INI-file?
            Program.log.Debug(String.Format("Read INI File \"{0}\"", iniFileName));
            if (!File.Exists(iniFileName))
            {
                Program.log.Fatal("MSBPLaunch stop: Cannot find INI File");
                Environment.Exit(2);
            }
            // read INI-file
            IniParser.FileIniDataParser iniParser = new FileIniDataParser();
            IniData iniData = null;

            try
            {
                iniData = iniParser.LoadFile(iniFileName);
            }
            catch (Exception ex)
            {
                Program.log.Fatal("MSBPLaunch stop: Cannot read INI File. " + ex);
                Environment.Exit(2);
            }
            // check msbp.exe
            MsbpExe = "";
            try
            {
                MsbpExe = iniData["General"]["MsbpExe"];
                if (String.IsNullOrWhiteSpace(MsbpExe))
                {
                    Program.log.Fatal("MSBPLaunch stop: Not found path settings for msbp.exe");
                    Environment.Exit(2);
                }
            }
            catch
            {
                Program.log.Fatal("MSBPLaunch stop: Not found path settings for msbp.exe");
                Environment.Exit(2);
            }
            if (!File.Exists(MsbpExe))
            {
                Program.log.Fatal(String.Format("MSBPLaunch stop: Not found {0}", MsbpExe));
                Environment.Exit(2);
            }
            // check backup path and create it if not exists
            BackupPath = "";
            try
            {
                BackupPath = iniData["General"]["BackupPath"];
                if (String.IsNullOrWhiteSpace(BackupPath))
                {
                    Program.log.Fatal("MSBPLaunch stop: Not found path settings for backups");
                    Environment.Exit(2);
                }
            }
            catch
            {
                Program.log.Fatal("MSBPLaunch stop: Not found path settings for backups");
                Environment.Exit(2);
            }
            if (!Directory.Exists(BackupPath))
            {
                Program.log.Info(String.Format("Not exist directory \"{0}\". Create it.", BackupPath));
                try
                {
                    Directory.CreateDirectory(BackupPath);
                }
                catch (Exception ex)
                {
                    Program.log.Fatal(String.Format("MSBPLaunch stop: Cannot create directory {0}. Stack: {1}", BackupPath, ex));
                    Environment.Exit(2);
                }
            }
            // check mail settings
            SMTP_Server = "";
            Mail_From   = "";
            Mail_To     = "";
            try
            {
                SMTP_Server = iniData["Mail"]["SMTP_Server"];
                Mail_From   = iniData["Mail"]["Mail_From"];
                Mail_To     = iniData["Mail"]["Mail_To"];
                if (String.IsNullOrWhiteSpace(SMTP_Server) || String.IsNullOrWhiteSpace(Mail_From) || String.IsNullOrWhiteSpace(Mail_To))
                {
                    SendReport = false;
                    Program.log.Warn("Check mail settings. Send summary report DISABLED");
                }
                else
                {
                    SendReport = true;
                    Program.log.Info("Send summary report ENABLED");
                }
            }
            catch
            {
                SendReport = false;
                Program.log.Warn("Check mail settings. Send summary report DISABLED");
            }
            // set storage time
            StorageTime = new SortedList();
            try
            {
                StorageTime.Add("D", iniData["StorageTime"]["D"]);
                StorageTime.Add("W", iniData["StorageTime"]["W"]);
                StorageTime.Add("Q", iniData["StorageTime"]["Q"]);
            }
            catch
            {
                StorageTime.Add("D", 0);
                StorageTime.Add("W", 0);
                StorageTime.Add("Q", 0);
            }
            // get week of day a full backup
            string sWeeklyFullBackup = "";

            try
            {
                sWeeklyFullBackup = iniData["General"]["WeeklyFullBackup"];
            }
            catch {}
            if (String.IsNullOrWhiteSpace(sWeeklyFullBackup))
            {
                WeeklyFullBackup = 6;
            }
            else
            {
                try
                {
                    WeeklyFullBackup = Convert.ToInt32(sWeeklyFullBackup);
                }
                catch
                {
                    WeeklyFullBackup = 6;
                }
            }
            // get list a excluded databases
            ExcludeDB = "";
            try
            {
                string ExcludeTmp = iniData["General"]["ExcludeDB"];
                if (!String.IsNullOrWhiteSpace(ExcludeTmp))
                {
                    Array aExcuded = ExcludeTmp.Trim().Split(',');
                    int   i        = 0;
                    foreach (string s in aExcuded)
                    {
                        if (i > 0)
                        {
                            ExcludeDB = ExcludeDB + ",";
                        }
                        ExcludeDB = ExcludeDB + "'" + s.Trim() + "'";
                        i++;
                    }
                }
            }
            catch
            {
                ExcludeDB = "";
            }
            if (ExcludeDB.Length > 0)
            {
                Program.log.Info(String.Format("Excluded database: {0}", ExcludeDB));
            }
            else
            {
                Program.log.Info(String.Format("Excluded database: {0}", "NONE"));
            }
        }
Пример #45
0
        public IniData Parse(string iniDataString)
        {
            IniData iniData = this.Configuration.CaseInsensitive ? new IniDataCaseInsensitive() : new IniData();

            iniData.Configuration = this.Configuration.Clone();
            bool    flag = string.IsNullOrEmpty(iniDataString);
            IniData result;

            if (flag)
            {
                result = iniData;
            }
            else
            {
                this._errorExceptions.Clear();
                this._currentCommentListTemp.Clear();
                this._currentSectionNameTemp = null;
                try
                {
                    string[] array = iniDataString.Split(new string[]
                    {
                        "\n",
                        "\r\n"
                    }, StringSplitOptions.None);
                    for (int i = 0; i < array.Length; i++)
                    {
                        string text  = array[i];
                        bool   flag2 = text.Trim() == string.Empty;
                        if (!flag2)
                        {
                            try
                            {
                                this.ProcessLine(text, iniData);
                            }
                            catch (Exception ex)
                            {
                                ParsingException ex2 = new ParsingException(ex.Message, i + 1, text, ex);
                                bool             throwExceptionsOnError = this.Configuration.ThrowExceptionsOnError;
                                if (throwExceptionsOnError)
                                {
                                    throw ex2;
                                }
                                this._errorExceptions.Add(ex2);
                            }
                        }
                    }
                    bool flag3 = this._currentCommentListTemp.Count > 0;
                    if (flag3)
                    {
                        bool flag4 = iniData.Sections.Count > 0;
                        if (!flag4)
                        {
                            bool flag5 = iniData.Global.Count > 0;
                            if (flag5)
                            {
                                iniData.Global.GetLast().Comments.AddRange(this._currentCommentListTemp);
                            }
                        }
                        this._currentCommentListTemp.Clear();
                    }
                }
                catch (Exception item)
                {
                    this._errorExceptions.Add(item);
                    bool throwExceptionsOnError2 = this.Configuration.ThrowExceptionsOnError;
                    if (throwExceptionsOnError2)
                    {
                        throw;
                    }
                }
                bool hasError = this.HasError;
                if (hasError)
                {
                    result = null;
                }
                else
                {
                    result = (IniData)iniData.Clone();
                }
            }
            return(result);
        }
Пример #46
0
        private void FirstRunInitialization()
        {
            // CharacterData.ini Initialization
            CreateBackup(characterDataIniFileName, characterDataIniPath);

            ConfigFile characterDataConfigFile = new ConfigFile(characterDataIniPath, true);
            IniData    characterData           = characterDataConfigFile.data;

            characterData.Sections.AddSection(RCharacterDataSection);

            foreach (KeyValuePair <string, string> entry in DefaultValues.CharacterDataSection)
            {
                characterData[RCharacterDataSection].AddKey(entry.Key, entry.Value);
            }

            characterDataConfigFile.Write(characterData);

            // DefaultGame.ini Initialization
            CreateBackup(defaultGameIniFileName, defaultGameIniPath);

            ConfigFile defaultGame     = new ConfigFile(defaultGameIniPath);
            IniData    defaultGameData = defaultGame.data;

            foreach (KeyValuePair <string, string> entry in DefaultValues.GameReplicationInfoSection)
            {
                defaultGameData[RGameReplicationInfoSection][entry.Key] = entry.Value;
            }

            defaultGameData.Sections.RemoveSection(RDisplayColorInfoSection);

            defaultGame.Write(defaultGameData);

            // SpitfireGame (decompress) Initialization
            FileInfo spitfireGameUPKFileInfo = new FileInfo(spitfireGameUPKPath);

            if (spitfireGameUPKFileInfo.Length == spitfireGameUPKOriginalFileSize)
            {
                CreateBackup(spitfireGameUPKFileName, spitfireGameUPKPath);

                if (!File.Exists(spitfireGameUPKDecompressPath))
                {
                    File.Copy(spitfireGameUPKPath, spitfireGameUPKDecompressPath);
                }

                // Decompress
                ProcessStartInfo psi = new ProcessStartInfo
                {
                    FileName         = Path.GetFileName(decompressorPath),
                    WorkingDirectory = Path.GetDirectoryName(decompressorPath),
                    Arguments        = "\"" + Path.GetFileName(spitfireGameUPKDecompressPath) + "\""
                };
                Process process = Process.Start(psi);
                process.WaitForExit();
                File.Delete(spitfireGameUPKPath);
                File.Move(spitfireGameUPKDecompressedPath, spitfireGameUPKPath); //TODO I think decompress.exe can get output folder as parameter
            }


            Settings.Instance["FirstRun"] = false;
            Settings.Save();
        }
Пример #47
0
		void LangCreate()
		{
			var parser = new FileIniDataParser();
			IniData data = new IniData();

			data.Sections.AddSection("info");
			data.Sections["info"].AddKey("Code", "en"); // file id
			data.Sections["info"].AddKey("Name", "English");
			data.Sections["info"].AddKey("Author", "Anime4000");
			data.Sections["info"].AddKey("Version", $"{Global.App.VersionRelease}");
			data.Sections["info"].AddKey("Contact", "https://github.com/Anime4000");
			data.Sections["info"].AddKey("Comment", "Please refer IETF Language Tag here: http://www.i18nguy.com/unicode/language-identifiers.html");

			data.Sections.AddSection(Name);
			Control ctrl = this;
			do
			{
				ctrl = GetNextControl(ctrl, true);

				if (ctrl != null)
					if (ctrl is Label ||
						ctrl is Button ||
						ctrl is TabPage ||
						ctrl is CheckBox ||
						ctrl is RadioButton ||
						ctrl is GroupBox)
						if (!string.IsNullOrEmpty(ctrl.Text))
							data.Sections[Name].AddKey(ctrl.Name, ctrl.Text.Replace("\n", "\\n").Replace("\r", ""));

			} while (ctrl != null);

			foreach (ToolStripItem item in cmsQueueMenu.Items)
				if (item is ToolStripMenuItem)
					data.Sections[Name].AddKey(item.Name, item.Text);

			foreach (ToolStripItem item in tsmiQueueAviSynth.DropDownItems)
				if (item is ToolStripMenuItem)
					data.Sections[Name].AddKey(item.Name, item.Text);

			foreach (ColumnHeader item in lstQueue.Columns)
				data.Sections[Name].AddKey($"{item.Tag}", item.Text);

			foreach (ColumnHeader item in lstSub.Columns)
				data.Sections[Name].AddKey($"{item.Tag}", item.Text);

			foreach (ColumnHeader item in lstAttach.Columns)
				data.Sections[Name].AddKey($"{item.Tag}", item.Text);

			data.Sections.AddSection(Name);
			data.Sections[Name].AddKey("BenchmarkDownload", Language.BenchmarkDownload);
			data.Sections[Name].AddKey("BenchmarkNoFile", Language.BenchmarkNoFile);
			data.Sections[Name].AddKey("NotSupported", Language.NotSupported);
			data.Sections[Name].AddKey("OneItem", Language.OneItem);
			data.Sections[Name].AddKey("OneVideo", Language.OneVideo);
			data.Sections[Name].AddKey("SaveNewProfilesInfo", Language.SaveNewProfilesInfo);
			data.Sections[Name].AddKey("SaveNewProfilesTitle", Language.SaveNewProfilesTitle);
			data.Sections[Name].AddKey("SelectAviSynth", Language.SelectAviSynth);
			data.Sections[Name].AddKey("SelectNotAviSynth", Language.SelectNotAviSynth);
			data.Sections[Name].AddKey("SelectOneVideoAttch", Language.SelectOneVideoAttch);
			data.Sections[Name].AddKey("SelectOneVideoPreview", Language.SelectOneVideoPreview);
			data.Sections[Name].AddKey("SelectOneVideoSubtitle", Language.SelectOneVideoSubtitle);
			data.Sections[Name].AddKey("VideoToAviSynth", Language.VideoToAviSynth.Replace("\n", "\\n"));
			data.Sections[Name].AddKey("QueueSave", Language.QueueSave);
			data.Sections[Name].AddKey("QueueSaveError", Language.QueueSaveError);
			data.Sections[Name].AddKey("QueueOpenChange", Language.QueueOpenChange);
			data.Sections[Name].AddKey("Quit", Language.Quit);

			data.Sections[Name].AddKey("TipUpdateTitle", Language.TipUpdateTitle);
			data.Sections[Name].AddKey("TipUpdateMessage", Language.TipUpdateMessage);

			for (int i = 0; i < cboPictureYadifMode.Items.Count; i++)
				data.Sections[Name].AddKey($"DeInterlaceMode{i}", (string)cboPictureYadifMode.Items[i]);

			for (int i = 0; i < cboPictureYadifField.Items.Count; i++)
				data.Sections[Name].AddKey($"DeInterlaceField{i}", (string)cboPictureYadifField.Items[i]);

			for (int i = 0; i < cboPictureYadifFlag.Items.Count; i++)
				data.Sections[Name].AddKey($"DeInterlaceFlag{i}", (string)cboPictureYadifFlag.Items[i]);

			data.Sections[Name].AddKey("Untitled", Language.Untitled);
			data.Sections[Name].AddKey("Untitled", Language.Donate);

			parser.WriteFile(Path.Combine(Global.Folder.Language, "en.ini"), data, Encoding.UTF8);		
		}
Пример #48
0
        internal static void Initialize()
        {
            if (Initialized)
            {
                return;
            }
            Initialized = true;
            try
            {
                CoreLogger = new GadgetLogger("GadgetCore", "Core");
                CoreLogger.Log("GadgetCore v" + GadgetCoreAPI.FULL_VERSION + " Initializing!");
                Debug.Log("GadgetCore v" + GadgetCoreAPI.FULL_VERSION);
            }
            catch (Exception e)
            {
                Debug.Log(e);
                GadgetCoreAPI.Quit();
                return;
            }
            try
            {
                if (File.Exists(Application.persistentDataPath + "/PlayerPrefs.txt") && VerifySaveFile())
                {
                    if (GadgetCoreConfig.MaxBackups > 0)
                    {
                        File.Copy(Application.persistentDataPath + "/PlayerPrefs.txt", Path.Combine(GadgetPaths.SaveBackupsPath, "Save Backup - " + DateTime.Now.ToString("yyyy-dd-M_HH-mm-ss") + ".txt"));
                        FileInfo[] backups = new DirectoryInfo(GadgetPaths.SaveBackupsPath).GetFiles().OrderByDescending(x => x.LastWriteTime.Year <= 1601 ? x.CreationTime : x.LastWriteTime).ToArray();
                        if (backups.Length > GadgetCoreConfig.MaxBackups)
                        {
                            for (int i = GadgetCoreConfig.MaxBackups; i < backups.Length; i++)
                            {
                                backups[i].Delete();
                            }
                        }
                    }
                }
                else
                {
                    GadgetCoreAPI.Quit();
                    return;
                }
                HarmonyInstance = new Harmony("GadgetCore.core");
                Type[] types;
                try
                {
                    types = Assembly.GetExecutingAssembly().GetTypes();
                }
                catch (ReflectionTypeLoadException e)
                {
                    types = e.Types.Where(t => t != null).ToArray();
                }
                types.Do(delegate(Type type)
                {
                    object[] attributes = type.GetCustomAttributes(true);
                    if (!attributes.Any(x => x.GetType() == typeof(HarmonyGadgetAttribute)))
                    {
                        HarmonyInstance.CreateClassProcessor(type).Patch();
                    }
                });
                new Thread(new ThreadStart(() => {
                    Thread.CurrentThread.Name         = "GadgetCore Unity Engine Log Cloner";
                    Thread.CurrentThread.Priority     = System.Threading.ThreadPriority.Lowest;
                    Thread.CurrentThread.IsBackground = true;
                    string logPath = Application.dataPath + "\\output_log.txt";
                    if (!File.Exists(logPath))
                    {
                        logPath = Application.persistentDataPath + "\\output_log.txt";
                    }
                    if (!File.Exists(logPath))
                    {
                        logPath = "~/Library/Logs/Unity/Player.log";
                    }
                    if (!File.Exists(logPath))
                    {
                        logPath = "~/.config/unity3d/DefaultCompany/Roguelands/Player.log";
                    }
                    if (!File.Exists(logPath))
                    {
                        CoreLogger.LogWarning("Unable to find Unity log file!");
                        return;
                    }
                    string targetPath = Path.Combine(GadgetPaths.LogsPath, "Unity Output.log");
                    DateTime t        = default;
                    while (!Quitting)
                    {
                        if (File.Exists(logPath) && File.GetLastWriteTime(logPath) > t)
                        {
                            File.Copy(logPath, targetPath, true);
                            t = DateTime.Now;
                        }
                        Thread.Sleep(100);
                    }
                })).Start();
                AppDomain.CurrentDomain.AssemblyResolve += (object sender, ResolveEventArgs args) =>
                {
                    string name = new AssemblyName(args.Name).Name;
                    if (LoadedAssemblies.ContainsKey(name))
                    {
                        return(LoadedAssemblies[name]);
                    }
                    foreach (string file in Directory.GetFiles(GadgetPaths.LibsPath))
                    {
                        if (AssemblyName.GetAssemblyName(file).Name == name)
                        {
                            Assembly assembly = Assembly.LoadFrom(file);
                            LoadedAssemblies[name] = assembly;
                            return(assembly);
                        }
                    }
                    return(null);
                };
                AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += (object sender, ResolveEventArgs args) =>
                {
                    string name = new AssemblyName(args.Name).Name;
                    if (LoadedAssemblies.ContainsKey("ReflectionOnly: " + name))
                    {
                        return(LoadedAssemblies["ReflectionOnly: " + name]);
                    }
                    foreach (string file in Directory.GetFiles(GadgetPaths.LibsPath))
                    {
                        if (AssemblyName.GetAssemblyName(file).Name == name)
                        {
                            Assembly assembly = Assembly.ReflectionOnlyLoadFrom(file);
                            LoadedAssemblies["ReflectionOnly: " + name] = assembly;
                            return(assembly);
                        }
                    }
                    return(null);
                };
                LoadMainMenu();
                try
                {
                    UMFAPI = new UMFAPI();
                    UMFAPI.GetModNames();
                    CoreLogger.Log("Enabling UMF API as UMF is installed.");
                }
                catch (Exception)
                {
                    UMFAPI = null;
                    CoreLogger.Log("Disabling UMF API as UMF is not installed.");
                }
                CoreLib = Activator.CreateInstance(Assembly.LoadFile(Path.Combine(Path.Combine(GadgetPaths.GadgetCorePath, "DependentLibs"), "GadgetCoreLib.dll")).GetTypes().First(x => typeof(IGadgetCoreLib).IsAssignableFrom(x))) as IGadgetCoreLib;
                CoreLib.ProvideLogger(CoreLogger);
                GadgetCoreConfig.Load();
                CoreLogger.Log("Finished loading config.");
                RegisterKeys();
                IniData coreManifest = new IniData();
                coreManifest["Metadata"]["Name"]     = "GadgetCore";
                coreManifest["Metadata"]["Assembly"] = Path.Combine(GadgetPaths.ManagedPath, "GadgetCore.dll");
                GadgetMod coreMod = new GadgetMod(GadgetPaths.GadgetCorePath, coreManifest, Assembly.GetExecutingAssembly());
                GadgetMods.RegisterMod(coreMod);
                VanillaRegistration();
                SceneManager.sceneLoaded += OnSceneLoaded;
                SceneInjector.InjectMainMenu();
                GadgetLoader.LoadAllMods();
                DontDestroyOnLoad(new GameObject("GadgetCore", typeof(GadgetCore)));
                CoreLogger.LogConsole("GadgetCore v" + GadgetCoreAPI.FULL_VERSION + " Initialized!");
#pragma warning disable CS0162 // Unreachable code detected
                if (GadgetCoreAPI.IS_BETA)
                {
                    CoreLogger.LogWarning("You are currently running a beta version of GadgetCore! Be prepared for bugs!");
                }
#pragma warning restore CS0162 // Unreachable code detected
            }
            catch (Exception e)
            {
                CoreLogger.LogError("There was a fatal error loading GadgetCore: " + e);
            }
        }
Пример #49
0
		private void btnProfileSave_Click(object sender, EventArgs e)
		{
			if (cboProfile.SelectedIndex == -1) // Error free
				return;

			var i = cboProfile.SelectedIndex;
			var p = Profile.List[i == 0 ? 0 : i - 1];

			string file;
			string platform;
			string name;
			string author;
			string web;

			if (i == 0)
			{
				file = Path.Combine(Global.Folder.Profile, $"{DateTime.Now:yyyyMMdd_HHmmss}.ifp");
				platform = "User";
				name = $"{DateTime.Now:yyyy-MM-dd_HH:mm:ss}";
				author = Environment.UserName;
				web = "";
			}
			else
			{
				file = p.File;
				platform = p.Info.Platform;
				name = p.Info.Name;
				author = p.Info.Author;
				web = p.Info.Web;
			}

			using (var form = new frmInputBox(Language.SaveNewProfilesTitle, Language.SaveNewProfilesInfo, name))
			{
				var result = form.ShowDialog();
				if (result == DialogResult.OK)
				{
					name = form.ReturnValue; // return
				}
				else
				{
					return;
				}
			}

			var parser = new FileIniDataParser();
			IniData data = new IniData();

			data.Sections.AddSection("info");
			data["info"].AddKey("format", rdoMKV.Checked ? "mkv" : "mp4");
			data["info"].AddKey("platform", platform);
			data["info"].AddKey("name", name);
			data["info"].AddKey("author", author);
			data["info"].AddKey("web", web);

			data.Sections.AddSection("picture");
			data["picture"].AddKey("resolution", cboPictureRes.Text);
			data["picture"].AddKey("framerate", cboPictureFps.Text);
			data["picture"].AddKey("bitdepth", cboPictureBit.Text);
			data["picture"].AddKey("chroma", cboPictureYuv.Text);

			data.Sections.AddSection("video");
			data["video"].AddKey("preset", cboVideoPreset.Text);
			data["video"].AddKey("tune", cboVideoTune.Text);
			data["video"].AddKey("type", cboVideoType.SelectedIndex.ToString());
			data["video"].AddKey("value", txtVideoValue.Text);
			data["video"].AddKey("cmd", txtVideoCmd.Text);

			data.Sections.AddSection("audio");
			data["audio"].AddKey("encoder", $"{cboAudioEncoder.SelectedValue}");
			data["audio"].AddKey("bitrate", cboAudioBit.Text);
			data["audio"].AddKey("frequency", cboAudioFreq.Text);
			data["audio"].AddKey("channel", cboAudioChannel.Text);
			data["audio"].AddKey("compile", chkAudioMerge.Checked ? "true" : "false");
			data["audio"].AddKey("cmd", txtAudioCmd.Text);

			parser.WriteFile(file, data, Encoding.UTF8);
			Profile.Load(); //reload list
			ProfileAdd();
		}
Пример #50
0
        public void CheckParseGoodFileSuccess()
        {
            IniData parsedData = iniParser.LoadFile(strGoodINIFilePath);

            Assert.That(parsedData, Is.Not.Null);
        }
Пример #51
0
        static void Main()
        {
            var     parser_clases = new FileIniDataParser();
            IniData clases        = parser_clases.ReadFile("clases.ini");

            var     parser_razas = new FileIniDataParser();
            IniData razas        = parser_razas.ReadFile("razas.ini");

            var     parser_armas = new FileIniDataParser();
            IniData armas        = parser_armas.ReadFile("armas.ini");

            var     parser_hechizos = new FileIniDataParser();
            IniData hechizos        = parser_hechizos.ReadFile("hechizos.ini");

            string[] clases_array = new string[int.Parse(clases["CLASES"]["CANTIDAD"])];

            List <String> lista_armas_dagas     = new List <String>();
            List <String> lista_daños_dagas_apu = new List <String>();

            List <String> lista_armas_1mano = new List <String>();
            List <String> lista_daños_1mano = new List <String>();

            List <String> lista_armas_2manos = new List <String>();
            List <String> lista_daños_2manos = new List <String>();

            List <String> lista_armas_proyectiles       = new List <String>();
            List <String> lista_daños_proyectiles_comun = new List <String>();

            List <String> lista_armas_wrestling = new List <String>();
            List <String> lista_daños_wrestling = new List <String>();

            List <String> lista_hechizos       = new List <String>();
            List <String> lista_daños_hechizos = new List <String>();

            List <String> lista_cps = new List <String>();

            bool correr = true;

            while (correr == true)
            {
                // Genera array de todas las clases.
                int i = 0;

                string valido = "no";
                while (valido == "no")
                {
                    try
                    {
                        clases_array[i] = clases["CLASES"][i.ToString()];
                        i += 1;
                    }

                    catch
                    {
                        valido = "si";
                    }
                }

                /////inputs de nivel y fuerza
                int nivel = 0;
                valido = "no";
                while (valido == "no")
                {
                    Console.WriteLine("En que nivel se encuentran los personajes?");
                    string nivel_input = Console.ReadLine();
                    try
                    {
                        nivel = int.Parse(nivel_input);
                        if (nivel > 0)
                        {
                            valido = "si";
                        }
                        else
                        {
                            Console.WriteLine("El nivel no puede ser negativo.");
                        }
                    }
                    catch
                    {
                        Console.WriteLine("Debes ingresar un nivel valido.");
                    }
                }

                valido = "no";
                int fuerza = 0;

                while (valido == "no")
                {
                    Console.WriteLine("Cual es la raza de los personajes?");
                    string raza = Console.ReadLine().ToUpper();
                    try
                    {
                        fuerza  = int.Parse(razas[raza]["FUE"]);
                        fuerza += 18;
                        valido  = "si";
                    }
                    catch
                    {
                        Console.WriteLine("Debes ingresar una raza valida.");
                    }
                }

                valido = "no";
                while (valido == "no")
                {
                    Console.WriteLine("Los perosnajes tienen la fuerza maxeada?");
                    string dopa = Console.ReadLine().ToLower();

                    if (dopa == "si")
                    {
                        fuerza *= 2;
                        if (fuerza > 40)
                        {
                            fuerza = 25;
                            valido = "si";
                        }
                        else
                        {
                            fuerza -= 15;
                            valido  = "si";
                        }
                    }
                    else if (dopa == "no")
                    {
                        fuerza -= 15;
                        valido  = "si";
                    }
                    else
                    {
                        Console.WriteLine("Debes ingresar si o no.");
                    }
                }

                //input de defensa

                int def_min = 0;
                int def_max = 0;

                valido = "no";
                while (valido == "no")
                {
                    Console.WriteLine("Tener en cuenta defensas?");
                    string tienen_def = Console.ReadLine().ToLower();
                    if (tienen_def == "si")
                    {
                        while (valido == "no")
                        {
                            Console.WriteLine("Cual es la defena minima?");
                            string d_min = Console.ReadLine();
                            Console.WriteLine("Cual es la defena maxima?");
                            string d_max = Console.ReadLine();
                            try
                            {
                                def_min = int.Parse(d_min);
                                if (def_min < 0)
                                {
                                    def_min = 0;
                                }
                                def_max = int.Parse(d_max);
                                if (def_max < 0)
                                {
                                    def_max = 0;
                                }
                                valido = "si";
                            }
                            catch
                            {
                                Console.WriteLine("Debes ingresar defensas validas.");
                            }
                        }
                    }
                    else if (tienen_def == "no")
                    {
                        valido = "si";
                    }
                    else
                    {
                        Console.WriteLine("Debes ingresar si o no.");
                    }
                }

                //funcion de calculo de daños fisicos
                string calculo_daños(int base_min, int base_max, int flecha_min, int flecha_max, int dmin_arma, int dmax_arma, int fuerza, int golpe_min, int golpe_max, double mod, bool apu, double mod_apu)
                {
                    int min_min = base_min + dmin_arma + flecha_min;
                    int min_max = base_max + dmax_arma + flecha_max;
                    int max_max = base_max + dmax_arma;

                    double dmin = 0;
                    double dmax = 0;

                    dmin = (min_min * 3.0 + max_max / 5.0 * fuerza + golpe_min) * mod;
                    dmax = (min_max * 3.0 + max_max / 5.0 * fuerza + golpe_max) * mod;

                    dmin -= def_max;
                    dmax -= def_min;

                    if (apu == true)
                    {
                        dmin *= mod_apu;
                        dmax *= mod_apu;
                    }

                    if (dmin < 0)
                    {
                        dmin = 0;
                    }

                    if (dmax < 0)
                    {
                        dmax = 0;
                    }

                    int dmin_int = Convert.ToInt32(dmin);
                    int dmax_int = Convert.ToInt32(dmax);

                    string daños = dmin_int.ToString() + "-" + dmax_int.ToString();

                    return(daños);
                }

                //Revisa el tipo del arma, agrega el nombre del arma a una lista segun el tipo, genra una lista de cps para el arma y revisa cada clase
                //si la clase esta en la lista de cps agrega entrada vacia a la lista de daños, si no esta en la lista de cps calcula el daño del arma con los mods de
                //la clase y agrega el daño a la lista de daños.

                bool loop = true;

                int    contador_armas = 1;
                string numero_arma    = "ARMA#" + contador_armas.ToString();

                bool loop_cps = true;

                int    contador_cps = 1;
                string numero_cp    = "CP" + contador_cps.ToString();

                void lista_daños(string tipo, List <String> lista_nombres, List <String> lista_daños, bool apuñala, string mod, int base_min, int base_max)
                {
                    while (loop == true)
                    {
                        if (armas[numero_arma]["TIPO"] == tipo)
                        {
                            lista_nombres.Add(armas[numero_arma]["NOMBRE"]);

                            while (loop_cps == true)
                            {
                                if (armas[numero_arma][numero_cp] != null)
                                {
                                    lista_cps.Add(armas[numero_arma][numero_cp]);
                                    numero_cp = "CP" + (contador_cps += 1).ToString();
                                }
                                else
                                {
                                    loop_cps = false;
                                }
                            }

                            foreach (string clase in clases_array)
                            {
                                int flecha_min = 0;
                                int flecha_max = 0;
                                if (tipo == "PROYECTILES")
                                {
                                    flecha_min = int.Parse(clases[clase]["MUNICIONMIN"]);
                                    flecha_max = int.Parse(clases[clase]["MUNICIONMAX"]);
                                }

                                if (lista_cps.Contains(clase))
                                {
                                    lista_daños.Add("");
                                }
                                else
                                {
                                    int golpe_min  = 0;
                                    int golpe_max  = 0;
                                    int golpe_base = int.Parse(clases[clase]["GOLPE"]);
                                    int golpe_35   = int.Parse(clases[clase]["GOLPE35"]);
                                    if (nivel <= 35)
                                    {
                                        golpe_min = golpe_base * nivel + 1;
                                        if (golpe_min > 99)
                                        {
                                            golpe_min = 99;
                                        }
                                        golpe_max = golpe_base * nivel + 2;
                                        if (golpe_max > 99)
                                        {
                                            golpe_max = 99;
                                        }
                                    }

                                    else if (nivel > 35)
                                    {
                                        if (golpe_base * 35 < 99)
                                        {
                                            golpe_min = golpe_base * nivel + 1;
                                            golpe_max = golpe_base * nivel + 2;
                                        }

                                        else
                                        {
                                            golpe_min = golpe_35 * (nivel - 35) + 99;
                                            golpe_max = golpe_35 * (nivel - 35) + 99;
                                        }
                                    }
                                    string daño = (calculo_daños(base_min, base_max, flecha_min, flecha_max, int.Parse(armas[numero_arma]["DMIN"]), int.Parse(armas[numero_arma]["DMAX"]),
                                                                 fuerza, golpe_min, golpe_max, double.Parse(clases[clase][mod]), apuñala, double.Parse(clases[clase]["MODAPU"])));
                                    lista_daños.Add(daño);
                                }
                            }

                            lista_cps.Clear();
                            contador_cps    = 1;
                            numero_cp       = "CP" + contador_cps.ToString();
                            contador_armas += 1;
                            numero_arma     = "ARMA#" + contador_armas.ToString();
                            loop_cps        = true;
                        }

                        else if (armas[numero_arma]["TIPO"] != null)
                        {
                            contador_armas += 1;
                            numero_arma     = "ARMA#" + contador_armas.ToString();
                        }

                        else
                        {
                            contador_armas = 1;
                            numero_arma    = "ARMA#" + contador_armas.ToString();
                            loop           = false;
                        }
                    }
                    loop = true;
                }

                lista_daños("DAGAS", lista_armas_dagas, lista_daños_dagas_apu, true, "CCADMG", 0, 0);
                lista_daños("1MANO", lista_armas_1mano, lista_daños_1mano, false, "CCADMG", 0, 0);
                lista_daños("2MANOS", lista_armas_2manos, lista_daños_2manos, false, "CCADMG", 0, 0);
                lista_daños("PROYECTILES", lista_armas_proyectiles, lista_daños_proyectiles_comun, false, "PRODMG", 0, 0);
                lista_daños("PROYECTILESNM", lista_armas_proyectiles, lista_daños_proyectiles_comun, false, "PRODMG", 0, 0);
                lista_daños("WRESTLING", lista_armas_wrestling, lista_daños_wrestling, false, "CSADMG", 4, 9);

                // Calcula el daño de los hechizos.

                int    index_hechizo  = 1;
                string numero_hechizo = "HECHIZO#" + index_hechizo.ToString();

                contador_cps = 1;
                numero_cp    = "CP" + contador_cps.ToString();

                while (hechizos[numero_hechizo]["NOMBRE"] != null)
                {
                    lista_hechizos.Add(hechizos[numero_hechizo]["NOMBRE"]);
                    loop_cps = true;
                    while (loop_cps == true)
                    {
                        if (hechizos[numero_hechizo][numero_cp] != null)
                        {
                            lista_cps.Add(hechizos[numero_hechizo][numero_cp]);
                            numero_cp = "CP" + (contador_cps += 1).ToString();
                        }
                        else
                        {
                            loop_cps = false;
                        }
                    }
                    foreach (string clase in clases_array)
                    {
                        if (lista_cps.Contains(clase))
                        {
                            lista_daños_hechizos.Add("");
                        }
                        else
                        {
                            double mod_magia             = 1 + int.Parse(clases[clase]["MODMAGIA"]) / 100.0;
                            int    min                   = int.Parse(hechizos[numero_hechizo]["DMIN"]);
                            int    max                   = int.Parse(hechizos[numero_hechizo]["DMAX"]);
                            double daño_hechizo_min      = (min + (min * 3.0 * nivel) / 100.0) * mod_magia;
                            double daño_hechizo_max      = (max + (max * 3.0 * nivel) / 100.0) * mod_magia;
                            string daños_hechizos_juntos = Convert.ToInt32(daño_hechizo_min).ToString() + "-" + Convert.ToInt32(daño_hechizo_max).ToString();
                            lista_daños_hechizos.Add(daños_hechizos_juntos);
                        }
                    }
                    numero_hechizo = "HECHIZO#" + (index_hechizo += 1).ToString();
                }

                // Crea una tabla en base a las distintas combinaciones de armas y/o hechizo, tipo de arma, daños, y clases.

                var doc = new Document(
                    );

                Grid tabla = new Grid
                {
                    Color    = Blue,
                    Columns  = { },
                    Children = { }
                };

                i = 0;
                while (i < clases_array.Length + 1)
                {
                    tabla.Columns.Add(GridLength.Auto);
                    i += 1;
                }

                void tablas(string tag, List <String> lista_armas, List <String> lista_daños)
                {
                    if (lista_armas.Count > 0)
                    {
                        i = 0;
                        int index = 0;

                        tabla.Children.Add(new Cell(tag)
                        {
                            Color = Yellow
                        });

                        foreach (string clase in clases_array)
                        {
                            tabla.Children.Add(new Cell(clase)
                            {
                                Color = Yellow
                            });
                        }

                        foreach (string arma in lista_armas)
                        {
                            tabla.Children.Add(new Cell(arma)
                            {
                                Color = Red
                            });
                            while (i < int.Parse(clases["CLASES"]["CANTIDAD"]))
                            {
                                tabla.Children.Add(new Cell(lista_daños[index])
                                {
                                    Color = Gray
                                });
                                i     += 1;
                                index += 1;
                            }
                            i = 0;
                        }
                    }
                }

                tablas("DAGAS", lista_armas_dagas, lista_daños_dagas_apu);
                tablas("1MANO", lista_armas_1mano, lista_daños_1mano);
                tablas("2MANOS", lista_armas_2manos, lista_daños_2manos);
                tablas("PROYECTILES", lista_armas_proyectiles, lista_daños_proyectiles_comun);
                tablas("SIN ARMAS", lista_armas_wrestling, lista_daños_wrestling);
                tablas("HECHIZOS", lista_hechizos, lista_daños_hechizos);

                doc.Children.Add(tabla);
                ConsoleRenderer.RenderDocument(doc);

                valido = "no";
                while (valido == "no")
                {
                    Console.WriteLine("Correr nuevamente?");
                    string correr_nuevamente = Console.ReadLine().ToLower();
                    if (correr_nuevamente == "si")
                    {
                        valido = "si";
                    }
                    else if (correr_nuevamente == "no")
                    {
                        correr = false;
                        valido = "si";
                    }
                    else
                    {
                        Console.WriteLine("Debes ingresar si o no.");
                    }
                }
            }
        }
Пример #52
0
        private static void Save(string fileName = null, bool isSaveParter = false)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                if (isSaveParter || string.IsNullOrEmpty(_fileName))
                {
                    //Can't save without file name.
                    return;
                }
                fileName = _fileName;
            }
            if (!isSaveParter)
            {
                _fileName = fileName;
            }
            var path = @"save\game\" + fileName;

            try
            {
                var count = 0;
                var data  = new IniData();
                data.Sections.AddSection("Head");
                if (!isSaveParter)
                {
                    data["Head"].AddKey("Map",
                                        MapBase.MapFileName);
                }

                var index = 0;
                foreach (var npc in _list)
                {
                    if ((isSaveParter && !npc.IsPartner) ||
                        (!isSaveParter && npc.IsPartner) ||
                        npc.SummonedByMagicSprite != null)
                    {
                        continue;
                    }
                    var sectionName = "NPC" + string.Format("{0:000}", index++);
                    data.Sections.AddSection(sectionName);
                    npc.Save(data[sectionName]);
                    count++;
                }
                foreach (var npc in _hideList)
                {
                    if ((isSaveParter && !npc.IsPartner) ||
                        (!isSaveParter && npc.IsPartner) ||
                        npc.SummonedByMagicSprite != null)
                    {
                        continue;
                    }
                    var sectionName = "NPC" + string.Format("{0:000}", index++);
                    data.Sections.AddSection(sectionName);
                    npc.Save(data[sectionName]);
                    count++;
                }
                data["Head"].AddKey("Count", count.ToString());
                File.WriteAllText(path, data.ToString(), Globals.LocalEncoding);
            }
            catch (Exception exception)
            {
                Log.LogFileSaveError("Npc", path, exception);
            }
        }
Пример #53
0
        //
        public static void PreProcessPendingObjects(KnowledgeBase KB, IOutputService output, List <KBObject> objs)
        {
            FileIniDataParser fileIniData = new FileIniDataParser();

            output.Clear();
            output.SelectOutput("KBDoctor");
            output.StartSection("KBDoctor", "Review_Objects", "Review Objects");


            InitializeIniFile(KB);

            IniData parsedData  = fileIniData.ReadFile(KB.UserDirectory + "\\KBDoctor.ini");
            string  SectionName = "ReviewObject";

            List <KBObject> atts = new List <KBObject>();

            foreach (KBObject obj in objs)
            {
                List <KBObject> objlist = new List <KBObject>();
                objlist.Add(obj);
                if (Utility.isRunable(obj) && !Utility.IsGeneratedByPattern(obj))
                {
                    //Check objects with parameteres without inout
                    if (parsedData[SectionName]["ParamINOUT"].ToLower() == "true")
                    {
                        Objects.ParmWOInOut(objlist, output);
                    }

                    //Clean variables not used
                    if (parsedData[SectionName]["CleanUnusedVariables"].ToLower() == "true")
                    {
                        CleanKB.CleanKBObjectVariables(obj, output);
                    }

                    //Check commit on exit
                    if (parsedData[SectionName]["CheckCommitOnExit"].ToLower() == "true")
                    {
                        Objects.CommitOnExit(objlist, output);
                    }

                    //Is in module
                    if (parsedData[SectionName]["CheckModule"].ToLower() == "true")
                    {
                        Objects.isInModule(objlist, output);
                    }

                    //With variables not based on attributes
                    if (parsedData[SectionName]["VariablesBasedAttOrDomain"].ToLower() == "true")
                    {
                        Objects.ObjectsWithVarNotBasedOnAtt(objlist, output);
                    }

                    //Code commented
                    if (parsedData[SectionName]["CodeCommented"].ToLower() == "true")
                    {
                        Objects.CodeCommented(objlist, output);
                    }

                    //Check complexity metrics
                    //maxNestLevel  6 - ComplexityLevel  30 - MaxCodeBlock  500 - parametersCount  6
                    int maxNestLevel = 7;
                    Int32.TryParse(parsedData[SectionName]["MaxNestLevel"], out maxNestLevel);

                    int complexityLevel = 30;
                    complexityLevel = Int32.Parse(parsedData[SectionName]["MaxComplexity"]);

                    int maxCodeBlock = 500;
                    maxCodeBlock = Int32.Parse(parsedData[SectionName]["MaxBlockSize"]);

                    int maxParametersCount = 6;
                    maxParametersCount = Int32.Parse(parsedData[SectionName]["MaxParameterCount"]);

                    Objects.CheckComplexityMetrics(objlist, output, maxNestLevel, complexityLevel, maxCodeBlock, maxParametersCount);



                    /*
                     * Tiene todas las referencias?
                     * Tiene calls que pueden ser UDP
                     * Mas de un parametro de salida
                     * Constantes en el código
                     * Nombre "poco claro" / Descripcion "poco clara"
                     * Si es modulo, revisar que no tenga objetos publicos no llamados
                     * Si es modulo, revisar que no tenga objetos privados llamados desde fuera
                     * Si es modulo, Valor de la propiedad ObjectVisibility <> Private
                     */
                }
                if (obj is Artech.Genexus.Common.Objects.Attribute && parsedData[SectionName]["AttributeBasedOnDomain"].ToLower() == "true")
                {
                    atts.Add(obj);
                    //Attribute Has Domain
                    Objects.AttributeHasDomain(objlist, output);
                }
                if (obj is SDT && parsedData[SectionName]["SDTBasedAttOrDomain"].ToLower() == "true")
                {
                    //SDTItems Has Domain
                    Objects.SDTBasedOnAttDomain(objlist, output);
                }
            }
            if (atts.Count > 0 && parsedData[SectionName]["AttributeWithoutTable"].ToLower() == "true")
            {
                // Attributes without table
                Objects.AttributeWithoutTable(atts, output);
            }

            output.EndSection("KBDoctor", "Review_Objects", true);
        }
Пример #54
0
        public static ProgramMapping BuildFromFile(string filename)
        {
            var     parser = new FileIniDataParser();
            IniData data   = parser.ReadFile(filename);

            string name = data["ID"]["name"];
            string program_regex_str = data["PROGRAM"]["regex"];

            Dictionary <Types.ButtonFlags, Action> mappings = new Dictionary <Types.ButtonFlags, Action>();
            KeyDataCollection mapping_section = data["MAPPINGS"];
            KeyDataCollection labels_section  = data["LABELS"];

            if (mapping_section.ContainsKey("START"))
            {
                mappings.Add(Types.ButtonFlags.START, new Action(readMapping(mapping_section, "START"), labels_section["START"]));
            }
            if (mapping_section.ContainsKey("BACK"))
            {
                mappings.Add(Types.ButtonFlags.BACK, new Action(mapping_section["BACK"], labels_section["BACK"]));
            }
            if (mapping_section.ContainsKey("A"))
            {
                mappings.Add(Types.ButtonFlags.A, new Action(mapping_section["A"], labels_section["A"]));
            }
            if (mapping_section.ContainsKey("B"))
            {
                mappings.Add(Types.ButtonFlags.B, new Action(mapping_section["B"], labels_section["B"]));
            }
            if (mapping_section.ContainsKey("X"))
            {
                mappings.Add(Types.ButtonFlags.X, new Action(readMapping(mapping_section, "X"), labels_section["X"]));
            }
            if (mapping_section.ContainsKey("Y"))
            {
                mappings.Add(Types.ButtonFlags.Y, new Action(mapping_section["Y"], labels_section["Y"]));
            }
            if (mapping_section.ContainsKey("LEFT_SHOULDER"))
            {
                mappings.Add(Types.ButtonFlags.LEFT_SHOULDER, new Action(mapping_section["LEFT_SHOULDER"], labels_section["LEFT_SHOULDER"]));
            }
            if (mapping_section.ContainsKey("RIGHT_SHOULDER"))
            {
                mappings.Add(Types.ButtonFlags.RIGHT_SHOULDER, new Action(mapping_section["RIGHT_SHOULDER"], labels_section["RIGHT_SHOULDER"]));
            }
            if (mapping_section.ContainsKey("DPAD_DOWN"))
            {
                mappings.Add(Types.ButtonFlags.DPAD_DOWN, new Action(mapping_section["DPAD_DOWN"], labels_section["DPAD_DOWN"]));
            }
            if (mapping_section.ContainsKey("DPAD_LEFT"))
            {
                mappings.Add(Types.ButtonFlags.DPAD_LEFT, new Action(mapping_section["DPAD_LEFT"], labels_section["DPAD_LEFT"]));
            }
            if (mapping_section.ContainsKey("DPAD_UP"))
            {
                mappings.Add(Types.ButtonFlags.DPAD_UP, new Action(mapping_section["DPAD_UP"], labels_section["DPAD_UP"]));
            }
            if (mapping_section.ContainsKey("DPAD_RIGHT"))
            {
                mappings.Add(Types.ButtonFlags.DPAD_RIGHT, new Action(mapping_section["DPAD_RIGHT"], labels_section["DPAD_RIGHT"]));
            }

            return(ProgramMapping.Build(name, program_regex_str, mappings));
        }
Пример #55
0
 /// <summary>
 ///     EN: Update cache value in container on specific index
 /// </summary>
 /// <param name="pathToIni">Path to ini file</param>
 /// <param name="data">Data from ini file</param>
 private void updateContainerValue(string pathToIni, IniData data)
 {
     if (pathToIni != null && data != null)
     {
         container[pathToIni] = data;
     }
 }
Пример #56
0
        public void LoadFromIni(IniData iniData)
        {
            var tpData = iniData["TemplePlus"];

            InstallationPath = tpData["toeeDir"];

            DisableAutomaticUpdates = tpData["autoUpdate"] != "true";

            if (tpData["hpOnLevelup"] != null)
            {
                switch (tpData["hpOnLevelup"].ToLowerInvariant())
                {
                case "max":
                    HpOnLevelUp = HpOnLevelUpType.Max;
                    break;

                case "average":
                    HpOnLevelUp = HpOnLevelUpType.Average;
                    break;

                default:
                    HpOnLevelUp = HpOnLevelUpType.Normal;
                    break;
                }
            }
            MaxHpForNpcHitdice = tpData["maxHpForNpcHitdice"] == "true";
            if (tpData["fogOfWar"] != null)
            {
                switch (tpData["fogOfWar"].ToLowerInvariant())
                {
                case "always":
                    FogOfWar = FogOfWarType.Always;
                    break;

                case "normal":
                    FogOfWar = FogOfWarType.Normal;
                    break;

                case "unfogged":
                    FogOfWar = FogOfWarType.Unfogged;
                    break;

                default:
                    FogOfWar = FogOfWarType.Normal;
                    break;
                }
            }

            int points;

            if (int.TryParse(tpData["pointBuyPoints"], out points))
            {
                PointBuyPoints = points;
            }

            int renderWidth, renderHeight;

            if (int.TryParse(tpData["renderWidth"], out renderWidth) &&
                int.TryParse(tpData["renderHeight"], out renderHeight))
            {
                RenderWidth  = renderWidth;
                RenderHeight = renderHeight;
            }

            SoftShadows        = tpData["softShadows"] == "true";
            AntiAliasing       = tpData["antialiasing"] == "true";
            WindowedMode       = tpData["windowed"] == "true";
            WindowedLockCursor = tpData["windowedLockCursor"] == "true";
            DungeonMaster      = tpData["dungeonMaster"] == "true";

            int maxLevel;

            if (int.TryParse(tpData["maxLevel"], out maxLevel))
            {
                MaxLevel = maxLevel;
            }

            bool allowXpOverflow;

            if (bool.TryParse(tpData["allowXpOverflow"], out allowXpOverflow))
            {
                AllowXpOverflow = allowXpOverflow;
            }

            bool slowerLevelling;

            if (bool.TryParse(tpData["slowerLevelling"], out slowerLevelling))
            {
                SlowerLevelling = slowerLevelling;
            }

            bool tolerantTownsfolk;

            if (bool.TryParse(tpData["tolerantNpcs"], out tolerantTownsfolk))
            {
                TolerantTownsfolk = tolerantTownsfolk;
            }

            bool showExactHPforNPCs, showNpcStats;

            if (bool.TryParse(tpData["showExactHPforNPCs"], out showExactHPforNPCs) &&
                bool.TryParse(tpData["showNpcStats"], out showNpcStats))
            {
                TransparentNpcStats = showNpcStats && showExactHPforNPCs;
            }

            bool fastSneaking;

            if (bool.TryParse(tpData["fastSneakAnim"], out fastSneaking))
            {
                FastSneaking = fastSneaking;
            }
            bool disableDoorRelocking;

            if (bool.TryParse(tpData["disableDoorRelocking"], out disableDoorRelocking))
            {
                DisableDoorRelocking = disableDoorRelocking;
            }
            bool alertAiThroughDoors;

            if (bool.TryParse(tpData["alertAiThroughDoors"], out alertAiThroughDoors))
            {
                AlertAiThroughDoors = alertAiThroughDoors;
            }



            bool newClasses;

            if (bool.TryParse(tpData["newClasses"], out newClasses))
            {
                NewClasses = newClasses;
            }

            bool nonCore;

            if (bool.TryParse(tpData["nonCoreMaterials"], out nonCore))
            {
                NonCore = nonCore;
            }


            // Lax Rules
            bool laxRules;

            if (bool.TryParse(tpData["laxRules"], out laxRules))
            {
                LaxRules = laxRules;
            }
            bool disableAlignmentRestrictions;

            if (bool.TryParse(tpData["disableAlignmentRestrictions"], out disableAlignmentRestrictions))
            {
                DisableAlignmentRestrictions = disableAlignmentRestrictions;
            }
            bool disableCraftingSpellReqs;

            if (bool.TryParse(tpData["disableCraftingSpellReqs"], out disableCraftingSpellReqs))
            {
                DisableCraftingSpellReqs = disableCraftingSpellReqs;
            }
            bool disableMulticlassXpPenalty;

            if (bool.TryParse(tpData["disableMulticlassXpPenalty"], out disableMulticlassXpPenalty))
            {
                DisableMulticlassXpPenalty = disableMulticlassXpPenalty;
            }
            bool showTargetingCirclesInFogOfWar;

            if (bool.TryParse(tpData["showTargetingCirclesInFogOfWar"], out showTargetingCirclesInFogOfWar))
            {
                ShowTargetingCirclesInFogOfWar = showTargetingCirclesInFogOfWar;
            }
        }
Пример #57
0
 public string GetKeyFieldValue(string section_nm, string strKey_nm)
 {
     parsedData = parser.LoadFile(this.path);
     return(parsedData[section_nm][strKey_nm]);
 }
Пример #58
0
        public void SaveToIni(IniData iniData)
        {
            var tpData = iniData["TemplePlus"];

            if (tpData == null)
            {
                iniData.Sections.Add(new SectionData("TemplePlus"));
                tpData = iniData["TemplePlus"];
            }

            tpData["toeeDir"]    = InstallationPath;
            tpData["autoUpdate"] = DisableAutomaticUpdates ? "false" : "true";
            switch (HpOnLevelUp)
            {
            case HpOnLevelUpType.Max:
                tpData["hpOnLevelup"] = "max";
                break;

            case HpOnLevelUpType.Average:
                tpData["hpOnLevelup"] = "average";
                break;

            default:
                tpData["hpOnLevelup"] = "normal";
                break;
            }
            tpData["maxHpForNpcHitdice"] = MaxHpForNpcHitdice ? "true" : "false";
            switch (FogOfWar)
            {
            case FogOfWarType.Unfogged:
                tpData["fogOfWar"] = "unfogged";
                break;

            case FogOfWarType.Always:
                tpData["fogOfWar"] = "always";
                break;

            default:
                tpData["fogOfWar"] = "normal";
                break;
            }
            tpData["laxRules"] = LaxRules ? "true" : "false";

            tpData["disableAlignmentRestrictions"]   = DisableAlignmentRestrictions ? "true" : "false";
            tpData["disableCraftingSpellReqs"]       = DisableCraftingSpellReqs ? "true" : "false";
            tpData["disableMulticlassXpPenalty"]     = DisableMulticlassXpPenalty ? "true" : "false";
            tpData["showTargetingCirclesInFogOfWar"] = ShowTargetingCirclesInFogOfWar ? "true" : "false";


            tpData["pointBuyPoints"]       = PointBuyPoints.ToString();
            tpData["renderWidth"]          = RenderWidth.ToString();
            tpData["renderHeight"]         = RenderHeight.ToString();
            tpData["windowed"]             = WindowedMode ? "true" : "false";
            tpData["windowWidth"]          = RenderWidth.ToString();
            tpData["windowHeight"]         = RenderHeight.ToString();
            tpData["antialiasing"]         = AntiAliasing? "true" : "false";
            tpData["softShadows"]          = SoftShadows ? "true" : "false";
            tpData["windowedLockCursor"]   = WindowedLockCursor ? "true" : "false";
            tpData["dungeonMaster"]        = DungeonMaster ? "true" : "false";
            tpData["maxLevel"]             = MaxLevel.ToString();
            tpData["allowXpOverflow"]      = AllowXpOverflow ? "true" : "false";
            tpData["slowerLevelling"]      = SlowerLevelling ? "true" : "false";
            tpData["newClasses"]           = NewClasses? "true" : "false";
            tpData["nonCoreMaterials"]     = NonCore ? "true" : "false";
            tpData["tolerantNpcs"]         = TolerantTownsfolk? "true" : "false";
            tpData["showExactHPforNPCs"]   = TransparentNpcStats? "true" : "false";
            tpData["showNpcStats"]         = TransparentNpcStats ? "true" : "false";
            tpData["fastSneakAnim"]        = FastSneaking ? "true" : "false";
            tpData["disableDoorRelocking"] = DisableDoorRelocking? "true" : "false";
            tpData["alertAiThroughDoors"]  = AlertAiThroughDoors ? "true" : "false";
        }
Пример #59
0
 public VpdbConfig(IniData data, Configuration parent) : base(data, parent)
 {
 }
Пример #60
-1
		/// <summary>
		/// Writes the config data to disk. This method is thread-blocking, and all write operations 
		/// are synchronized via lock(WriteLock).
		/// </summary>
		/// <param name="Parser">The parser dealing with the current data.</param>
		/// <param name="Data">The data which should be written to file.</param>
		private void WriteConfig(FileIniDataParser Parser, IniData Data)
		{
			lock (WriteLock)
			{
				Parser.WriteFile (GetConfigPath (), Data);
			}
		}