private static void CheckForUpdateCallback(IAsyncResult ar)
 {
     object[] asyncState = (object[]) ar.AsyncState;
     HttpWebRequest request = (HttpWebRequest) asyncState[0];
     SynchronizationContext context = (SynchronizationContext) asyncState[1];
     Ini ini = null;
     Exception exception = null;
     bool flag = false;
     try
     {
         HttpWebResponse response = (HttpWebResponse) request.EndGetResponse(ar);
         ini = new Ini();
         using (TextReader reader = new StreamReader(response.GetResponseStream()))
         {
             ini.Read(reader);
         }
         FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(Application.ExecutablePath);
         ini.Set("Version", "CurrentVersion", versionInfo.ProductVersion);
     }
     catch (WebException exception2)
     {
         exception = exception2;
         flag = true;
     }
     catch (Exception exception3)
     {
         exception = exception3;
     }
     context.Send(new SendOrPostCallback(CheckForUpdatesDialog.ShowCheckResult), new object[] { exception, flag, ini });
 }
示例#2
0
文件: DaMonitor.cs 项目: LongQin/DAMS
        public DaMonitor(String iniFileName)
        {
            ini = new Ini(AppDomain.CurrentDomain.BaseDirectory + iniFileName);
            isMnt = ini.ReadValue("DbServer", "isMnt");
            if (isMnt == "1")
            {
                //Unit code
                sOrgCode = ini.ReadValue("Server", "sOrg");

                //Turn on the monitoring function
                //sIP = ini.ReadValue("DbServer", "sIP");
                //sPort = ini.ReadValue("DbServer", "sPort");
                //sSID = ini.ReadValue("DbServer", "sSID");
                //sUID = ini.ReadValue("DbServer", "sUID");
                //sPWD = ini.ReadValue("DbServer", "sPWD");
                LogConfig.info("Administrator", "    Monitoring function is turned on, key is as :" + isMnt);
                //LogConfig.info("            IP :", sIP);
                //LogConfig.info("    Port is as :", sPort);
                //LogConfig.info("     UID is as :", sUID);
                //LogConfig.info("     PWD is as :", sPWD);

                dbm = new DbManager();

                //Create SystemInfo object
                sysInfo = new SystemInfo();
            }
            else
            {
                LogConfig.info("Administrator", "Monitoring function is turned off, key is as :" + isMnt);
            }
        }
    public void Run(string[] args)
    {
        Console.WriteLine("Core/Config/Ini test:");

        using (var ini = new Ini())
        {
            string file = "test_ini.ini";
            Console.WriteLine("Load config file: {0}", file);
            ini.LoadFromFile(file);

            var helloSection = ini["Hello"];
            Console.WriteLine("Hello section get: {0}", helloSection.sectionName);

            var unknownSection = ini.GetSection("sdfsafafas");
            Console.WriteLine("Get not exist section, return: {0}", unknownSection);

            Console.WriteLine("[Hello] Cfg1 = {0}", ini.GetValue<int>("Hello", "Cfg1"));
            Console.WriteLine("[Hello] Cfg2 = {0}", ini.GetValue<string>("Hello", "Cfg2"));
            Console.WriteLine("[Hello] Cfg3 = {0}", ini.GetValue<string>("Hello", "Cfg3"));
            Console.WriteLine("[Hello] Cfg4 = {0}", ini.GetValue<bool>("Hello", "Cfg4"));

            Console.WriteLine("[World] Cfg1 = {0}", ini.GetValue<int>("World", "Cfg1"));
            Console.WriteLine("[World] Cfg2 = {0}", ini.GetValue<string>("World", "Cfg2"));
            Console.WriteLine("[World] Cfg3 = {0}", ini.GetValue<string>("World", "Cfg3"));
            Console.WriteLine("[World] Cfg4 = {0}", ini.GetValue<bool>("World", "Cfg4"));
        }

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }
示例#4
0
        public SpaceRecycler(String iniFileName)
        {
            //读取Main.ini  
            Ini ini = new Ini(AppDomain.CurrentDomain.BaseDirectory + iniFileName);

            //系统重启时刻
            sRebootTime = ini.ReadValue("Timer", "sRebootTime");
            if ("" == sRebootTime || "24:00" == sRebootTime || "24:00:00" == sRebootTime)
            {
                sRebootTime = " 23:59:58";
            }
            else
            {
                sRebootTime = " " + sRebootTime;
            }

            //缓存目录
            sCacheDir = ini.ReadValue("Local", "sCacheDir");

            //声音警告
            iDriveQuota = ini.ReadValue("Local", "iDriveQuota");

            //文件缓存期限
            String sDays = ini.ReadValue("Local", "iDays");
            if ("" == sDays)
            {
                //If cache duration is not setted, using default as 7 days
                iDays = 7;
            }
            else
            {
                iDays = Convert.ToInt16(sDays);
            }
        }
 protected override ResourceSet InternalGetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents)
 {
     ResourceSet set = (ResourceSet) base.ResourceSets[culture];
     if (set == null)
     {
         if (this.FLngIni == null)
         {
             this.FLngIni = new Ini();
             using (TextReader reader = new StreamReader(this.FLngPath, Encoding.Default, true))
             {
                 this.FLngIni.Read(reader);
             }
         }
         string language = this.GetLanguage(culture);
         if (!((!string.IsNullOrEmpty(language) && (language != "ENG")) && this.FLngIni.ContainsSection(language)))
         {
             language = "ENG";
         }
         if (!this.FLngIni.ContainsSection(language) && tryParents)
         {
             CultureInfo parent = culture.Parent;
             if (parent != CultureInfo.InvariantCulture)
             {
                 return this.InternalGetResourceSet(parent, createIfNotExists, tryParents);
             }
         }
         set = new IniResourceSet(this.FLngIni, language);
         base.ResourceSets.Add(culture, set);
     }
     return set;
 }
 public IniFormStringLocalizer(Ini iniSource)
 {
     if (iniSource == null)
     {
         throw new ArgumentNullException();
     }
     this.FIniSource = iniSource;
 }
 public IniFormStringLocalizer(Ini iniSource, string iniPath)
 {
     if ((iniSource == null) && string.IsNullOrEmpty(iniPath))
     {
         throw new ArgumentException();
     }
     this.FIniSource = iniSource;
     this.FIniPath = iniPath;
 }
 public IniResourceReader(Ini iniSource, Type resourceSource)
 {
     if (resourceSource == null)
     {
         throw new ArgumentNullException("resourceType");
     }
     this.InitializeSource(iniSource);
     this.InitializeSection(resourceSource.FullName);
 }
		/// <summary>
		/// Read PAD settings from INI file.
		/// </summary>
		/// <param name="padSectionName">INI section.</param>
		/// <param name="s">Settings.</param>
		/// <param name="p">PAD Settings.</param>
		/// <remarks>use 'ref' to indicate that objects will be updated inside.</remarks>
		void ReadWritePadSettings(string padSectionName, ref Setting s, ref PadSetting p, bool write)
		{
			s = new Setting();
			p = new PadSetting();
			// Get PAD1 settings data as a reference.
			var items = SettingsMap.Where(x => x.MapTo == MapTo.Controller1).ToArray();
			var sProps = s.GetType().GetProperties();
			var pProps = p.GetType().GetProperties();
			var ini2 = new Ini(IniFileName);
			foreach (var item in items)
			{
				string key = item.IniPath.Split('\\')[1];
				// Try to find property inside Settings object.
				var sProp = sProps.FirstOrDefault(x => x.Name == item.PropertyName);
				if (sProp != null)
				{
					if (write)
					{
						var sv = (string)sProp.GetValue(s, null) ?? "";
						// Write value to INI file.
						ini2.SetValue(padSectionName, key, sv);
					}
					else
					{
						// Read value from INI file.
						var sv = ini2.GetValue(padSectionName, key) ?? "";
						sProp.SetValue(s, sv, null);
					}
					continue;
				}
				// Try to find property inside PAD Settings object.
				var pProp = pProps.FirstOrDefault(x => x.Name == item.PropertyName);
				if (pProp != null)
				{

					if (write)
					{
						var pv = (string)pProp.GetValue(p, null) ?? "";
						// Write value to INI file.
						ini2.SetValue(padSectionName, key, pv);
					}
					else
					{
						// Read value from INI file.
						var pv = ini2.GetValue(padSectionName, key) ?? "";
						sProp.SetValue(s, pv, null);
					}
					continue;
				}
				// Property was not found.
				var message = string.Format("ReadWritePadSettings: Property '{0}' was not found", item.PropertyName);
				// Inform developer with the message.
				MessageBoxForm.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
示例#10
0
        private void Start()
        {
            var location = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "maxstax.ini");
            if (!File.Exists(location))
                return;

            var settings = new Ini(location);
            if (!settings.ContainsSection("MaxStax"))
                return;
            settings.SetSection("MaxStax");
            if (!settings.ContainsKey("Size"))
                return;
            this._maxStack = settings.GetInteger("Size", 100);
        }
示例#11
0
 private static string GetConnectionStr()
 {
     if (_connectionString == "")
     {
         Ini ini = new Ini(AppDomain.CurrentDomain.BaseDirectory + "Main.ini");
         string dataBaseName = ini.ReadValue("DbServer", "sSID");
         string userId = ini.ReadValue("DbServer", "sUID");
         string password =  ini.ReadValue("DbServer", "sPWD");
         string dataSource = ini.ReadValue("DbServer", "sIP");
         _connectionString = "Database='" + dataBaseName + "';";
         _connectionString += "Data Source='" + dataSource + "';User Id='" + userId + "';";
         _connectionString += "Password='******';charset='utf8';pooling=true";
     }
     return _connectionString;
 }
示例#12
0
        private static void AutoUpdate()
        {
            Console.WriteLine("Checking Updates...");

            Plugin[] Plugins = (from x in Updater.TreeRepositorie() where Updater.IsInstalled(x) select x).ToArray();
            bool     Updated = true;

            foreach (Plugin Plugin in Plugins)
            {
                if (!Updater.IsUpdated(Plugin) && Ini.GetConfig("Plugin", "AutoUpdate", AppDomain.CurrentDomain.BaseDirectory + "Plugins/" + Plugin.File, false) != "false")
                {
                    if (Updated)
                    {
                        AllocConsole();
                        Updated = false;
                    }
                    Console.WriteLine("Updating {0}", Plugin.Name);
                    Updater.Install(Plugin);
                }
            }
        }
示例#13
0
 private void VirusTotalBtn_Click(object sender, EventArgs e)
 {
     if (!(sender is Label owner))
     {
         return;
     }
     owner.Enabled = false;
     try
     {
         foreach (var key in Ini.GetKeys("SHA256", HashInfo))
         {
             Process.Start(string.Format(CultureInfo.InvariantCulture, CorePaths.VirusTotalUrl, Ini.Read("SHA256", key, HashInfo)));
             Thread.Sleep(200);
         }
     }
     catch (Exception ex) when(ex.IsCaught())
     {
         Log.Write(ex);
     }
     owner.Enabled = true;
 }
示例#14
0
        public void Set_3(EngineState s)
        {
            string pPath = s.Project.MainScript.FullPath;

            Ini.DeleteKey(pPath, "Variables", "%Set_3%");

            string rawCode = "Set,%Set_3%,PEBakery,PERMANENT";

            EngineTests.Eval(s, rawCode, CodeType.Set, ErrorCheck.Success);

            string comp = "PEBakery";
            string dest = s.Variables.GetValue(VarsType.Global, "Set_3");

            Assert.IsTrue(dest.Equals(comp, StringComparison.Ordinal));

            string permanent = Ini.GetKey(pPath, "Variables", "%Set_3%");

            Assert.IsTrue(dest.Equals(comp, StringComparison.Ordinal));

            Ini.DeleteKey(pPath, "Variables", "%Set_3%");
        }
示例#15
0
        public static T Get <T>(string section, string key, T @default)
        {
            var converter = TypeDescriptor.GetConverter(typeof(T));
            var target    = default(Section);

            if ((target = new Ini(Dirs.ConfigFile)[section]) is null)
            {
                return(@default);
            }
            var value = default(PropertyValue);

            if ((value = target[key]) == default)
            {
                return(@default);
            }
            if (value.IsEmpty())
            {
                return(@default);
            }
            return((T)converter.ConvertFrom(value.ToString()));
        }
示例#16
0
        public bool ContainsInstanceSectionOld(Guid instanceGuid, string iniFileName, out string sectionName)
        {
            var ini2 = new Ini(iniFileName);

            for (int i = 1; i <= 4; i++)
            {
                var section = string.Format("PAD{0}", i);
                var v       = ini2.GetValue(section, "InstanceGUID");
                if (string.IsNullOrEmpty(v))
                {
                    continue;
                }
                if (v.ToLower() == instanceGuid.ToString("D").ToLower())
                {
                    sectionName = section;
                    return(true);
                }
            }
            sectionName = null;
            return(false);
        }
示例#17
0
        public static void Initialize()
        {
            Busy  = false;
            State = EAppState.Opening;

            Properties = new AppProperies();
            Properties.Load();

            string dbPath = Ini.GetString("Database", "FileName");

            if (Path.IsPathRooted(dbPath) == false)
            {
                dbPath = Path.GetFullPath(dbPath);
            }

            DB          = new AppDatabase();
            DB.Database = dbPath;
            DB.Open();

            //Recipes = new RecipeList();
        }
        public override DownLoadState DownloadImpl()
        {
            try
            {
                var cls = new WinPrice.WPLibClass();
                var Profile = cls.OpenProfile(EprikaFile);
                var Session = Profile.StartSession("Price");
                for (int i = 0; i < 5 * 60; i++)
                {
                    if (Session.WaitComplete(500))
                        break;
                }
                if (Profile.HasPrice())
                {
                    string exchfilename = System.IO.Path.Combine(this.EprikaFile, "exchange.ini");
                    var Ini = new Ini(exchfilename);
                    string filename = Ini.GetValue("FileName", "export").Replace("\"", "");
                    if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(filename)))
                    {
                        System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(filename));
                    }
                    Profile.ExportPrice(filename);
                }

                Marshal.FinalReleaseComObject(Session);
                Marshal.FinalReleaseComObject(Profile);
                Marshal.FinalReleaseComObject(cls);

                cls = null;
                Profile = null;
                Session = null;

                return new DownLoadState() { };
            }
            catch (Exception ex)
            {
                Log.Error(Name, ex);
                throw;
            }
        }
示例#19
0
        public static List <LogInfo> IniRead(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_IniRead));
            CodeInfo_IniRead info = cmd.Info as CodeInfo_IniRead;

            string fileName    = StringEscaper.Preprocess(s, info.FileName);
            string sectionName = StringEscaper.Preprocess(s, info.Section);
            string key         = StringEscaper.Preprocess(s, info.Key);

            if (sectionName.Equals(string.Empty, StringComparison.Ordinal))
            {
                throw new ExecuteException("Section name cannot be empty");
            }
            if (key.Equals(string.Empty, StringComparison.Ordinal))
            {
                throw new ExecuteException("Key name cannot be empty");
            }

            string value = Ini.GetKey(fileName, sectionName, key);

            if (value != null)
            {
                logs.Add(new LogInfo(LogState.Success, $"Key [{key}] and its value [{value}] read from [{fileName}]"));

                string         escapedValue = StringEscaper.Escape(value, false, true);
                List <LogInfo> varLogs      = Variables.SetVariable(s, info.DestVar, escapedValue, false, false, false);
                logs.AddRange(varLogs);
            }
            else
            {
                logs.Add(new LogInfo(LogState.Ignore, $"Key [{key}] does not exist in [{fileName}]"));

                List <LogInfo> varLogs = Variables.SetVariable(s, info.DestVar, string.Empty, false, false, false);
                logs.AddRange(varLogs);
            }

            return(logs);
        }
示例#20
0
        private async Task UpdateTeam(Match currentMatch = null)
        {
            if (currentMatch == null)
            {
                currentMatch = await GetCurrentMatch();
            }
            var matchWorlds = currentMatch.Worlds;

            var worldRepo = GW2.V2.Worlds.ForDefaultCulture();
            var worlds    = new World[] {
                await worldRepo.FindAsync(matchWorlds.Red),
                await worldRepo.FindAsync(matchWorlds.Green),
                await worldRepo.FindAsync(matchWorlds.Blue)
            };

            CurrentWorlds["Red"]   = worlds[0].AbbreviatedName;
            CurrentWorlds["Green"] = worlds[1].AbbreviatedName;
            CurrentWorlds["Blue"]  = worlds[2].AbbreviatedName;

            var index = Array.IndexOf(TeamList, OurTeam);

            OurWorld   = worlds[index].AbbreviatedName;
            LeftTeam   = TeamList[(index - 1 + TeamList.Length) % TeamList.Length];
            RightTeam  = TeamList[(index + 1) % TeamList.Length];
            LeftWorld  = worlds[(index - 1 + TeamList.Length) % TeamList.Length].AbbreviatedName;
            RightWorld = worlds[(index + 1) % TeamList.Length].AbbreviatedName;

            CurrentTeams[OurTeam]   = "Our";
            CurrentTeams[LeftTeam]  = "Left";
            CurrentTeams[RightTeam] = "Right";

            Ini.Write("OurWorld", OurWorld, "GW2");
            Ini.Write("LeftTeam", LeftTeam, "GW2");
            Ini.Write("RightTeam", RightTeam, "GW2");
            Ini.Write("LeftWorld", LeftWorld, "GW2");
            Ini.Write("RightWorld", RightWorld, "GW2");
            Ini.Write("RedWorld", CurrentWorlds["Red"], "GW2");
            Ini.Write("GreenWorld", CurrentWorlds["Green"], "GW2");
            Ini.Write("BlueWorld", CurrentWorlds["Blue"], "GW2");
        }
        private void PokedexOrderEditor_Load(object sender, EventArgs e)
        {
            try
            {
                Offset1 = int.Parse(Ini.GetString(Conversions.ToString(MMainFunctions.GetIniFileLocation()), MainObject.Header, "NationalDexTable", ""), System.Globalization.NumberStyles.HexNumber);
                Offset2 = int.Parse(Ini.GetString(Conversions.ToString(MMainFunctions.GetIniFileLocation()), MainObject.Header, "SecondDexTable", ""), System.Globalization.NumberStyles.HexNumber);


                if (MainObject.Header2 == "BPE")
                {
                    Offset3 = int.Parse(Ini.GetString(Conversions.ToString(MMainFunctions.GetIniFileLocation()), MainObject.Header, "HoenntoNationalDex", ""), System.Globalization.NumberStyles.HexNumber);
                }

                int LoopVar;
                ListBox1.Items.Clear();
                LoopVar = 0;
                while (LoopVar < Conversions.ToDouble(Ini.GetString(Conversions.ToString(MMainFunctions.GetIniFileLocation()), MainObject.Header, "NumberOfPokemon", "")) - 1d == true)
                {
                    LoopVar = LoopVar + 1;
                    ListBox1.Items.Add(GetNameFunctions.GetPokemonName(LoopVar));
                }

                if (MainObject.Header2 == "BPE")
                {
                    GroupBox4.Enabled = true;
                }
                else
                {
                    GroupBox4.Enabled = false;
                }

                ListBox1.SelectedIndex = 0;
                Cursor = Cursors.Arrow;
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                throw;
            }
        }
示例#22
0
        public static void ConfigOverwrite(Dictionary <string, Dictionary <string, string> > iniMap, string path)
        {
            if (iniMap?.Any() != true)
            {
                return;
            }
            var file = PathEx.Combine(path);

            try
            {
                var dir = Path.GetDirectoryName(file);
                if (string.IsNullOrEmpty(dir))
                {
                    throw new ArgumentNullException(dir);
                }
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                if (!File.Exists(file))
                {
                    File.Create(file).Close();
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                return;
            }
            foreach (var data in iniMap)
            {
                var section = data.Key;
                foreach (var pair in iniMap[section])
                {
                    var key   = pair.Key;
                    var value = pair.Value;
                    Ini.WriteDirect(section, key, value, path);
                }
            }
        }
示例#23
0
        public static List <LogInfo> IniAddSection(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_IniAddSection));
            CodeInfo_IniAddSection info = cmd.Info as CodeInfo_IniAddSection;

            string fileName    = StringEscaper.Preprocess(s, info.FileName);
            string sectionName = StringEscaper.Preprocess(s, info.Section); // WB082 : 여기 값은 변수 Expand 안한다.

            if (sectionName.Equals(string.Empty, StringComparison.Ordinal))
            {
                throw new InvalidCodeCommandException("Section name cannot be empty", cmd);
            }

            if (StringEscaper.PathSecurityCheck(fileName, out string errorMsg) == false)
            {
                logs.Add(new LogInfo(LogState.Error, errorMsg));
                return(logs);
            }

            string dirPath = Path.GetDirectoryName(fileName);

            if (Directory.Exists(dirPath) == false)
            {
                Directory.CreateDirectory(dirPath);
            }

            bool result = Ini.AddSection(fileName, sectionName);

            if (result)
            {
                logs.Add(new LogInfo(LogState.Success, $"Section [{sectionName}] added to [{fileName}]", cmd));
            }
            else
            {
                logs.Add(new LogInfo(LogState.Error, $"Could not add section [{sectionName}] to [{fileName}]", cmd));
            }
            return(logs);
        }
示例#24
0
        private void Load(string _sName, SerialPort _Port, string _sPath = "")
        {
            //Set Dir.
            string sExeFolder  = System.AppDomain.CurrentDomain.BaseDirectory;
            string sFileName   = "Util\\SerialPort";
            string sSerialPath = sExeFolder + sFileName + ".ini";
            string sTitle      = "";

            if (sName == "")
            {
                sTitle = "PortID_" + iPortId.ToString();
            }
            else
            {
                sTitle = _sName;
            }

            CIniFile Ini;

            if (_sPath == "")
            {
                Ini = new CIniFile(sSerialPath);
            }
            else
            {
                Ini = new CIniFile(_sPath);
            }

            int iPortNo = 0;

            Ini.Load(sTitle, "PortNo", ref iPortNo); if (iPortNo == 0)
            {
                iPortNo = 1;
            }

            //맨처음 파일 없을때 대비.
            Ini.Save(sTitle, "PortNo   ", iPortNo);

            _Port.PortName = "Com" + iPortNo.ToString();
        }
示例#25
0
        private void LogIn_Load(object sender, EventArgs e)
        {
            // Settingini파일 Load
            if (Directory.Exists(@"D:BarCodeLabel_Config") == false) { Directory.CreateDirectory(@"D:BarCodeLabel_Config"); }
            if (File.Exists(@"D:BarCodeLabel_Config\Setting.ini") == false) { File.Create(@"D:BarCodeLabel_Config\Setting.ini"); }
            if (File.Exists(@"D:BarCodeLabel_Config\" + DateTime.Now.ToString("yyyyMMdd") + ".ini") == false) { File.Create(@"D:BarCodeLabel_Config\" + DateTime.Now.ToString("yyyyMMdd") + ".ini"); }

            SettingIni = new Ini(@"D:BarCodeLabel_Config\Setting.ini");
            HistoryIni = @"D:BarCodeLabel_Config\" + DateTime.Now.ToString("yyyyMMdd") + ".ini";

            txt_ID.Text = "";
            txt_PW.Text = "";

            CM_Main.UID = "";
            CM_Main.UPW = "";

            CM_Main.Read_INI();
            
            if(CM_Main.UID != "")
            {
                txt_ID.Text = CM_Main.UID;
                check_SaveID.Checked = true;
            }
            else
            {
                txt_ID.Text = "";
                check_SaveID.Checked = false;
            }
            if(CM_Main.UPW != "")
            {
                txt_PW.Text = CM_Main.UPW;
                check_SavePW.Checked = true;
            }
            else
            {
                txt_PW.Text = "";
                check_SavePW.Checked = false;
            }
        }
示例#26
0
        private void btnSubcfgSave_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();

            sfd.AddExtension       = true;
            sfd.AutoUpgradeEnabled = true;
            sfd.CheckPathExists    = true;
            sfd.DefaultExt         = ".ini";
            sfd.DereferenceLinks   = true;
            sfd.OverwritePrompt    = true;
            sfd.ValidateNames      = true;
            sfd.FileName           = path;

            if (sfd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }

            Ini ini = new Ini(sfd.FileName);

            KeyconfigExport(ini);
        }
示例#27
0
        private void AssociateBtn_Click(object sender, EventArgs e)
        {
            var owner = sender as Control;

            if (owner == null)
            {
                return;
            }
            var isNull = string.IsNullOrWhiteSpace(fileTypes.Text);

            if (!isNull)
            {
                if (fileTypes.Text.Contains(","))
                {
                    isNull = fileTypes.Text.Split(',').Where(s => !s.StartsWith(".")).ToArray().Length == 0;
                }
                else
                {
                    isNull = fileTypes.Text.StartsWith(".");
                }
            }
            if (isNull)
            {
                MessageBoxEx.Show(this, Lang.GetText($"{owner.Name}Msg"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var appName = Main.GetAppInfo(appsBox.SelectedItem.ToString()).ShortName;

            if (string.IsNullOrWhiteSpace(appName) || FileTypesConflict())
            {
                MessageBoxEx.Show(this, Lang.GetText(nameof(en_US.OperationCanceledMsg)), MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (!fileTypes.Text.EqualsEx(Ini.Read(appName, "FileTypes")))
            {
                SaveBtn_Click(saveBtn, EventArgs.Empty);
            }
            Main.AssociateFileTypesHandler(appName, this);
        }
示例#28
0
        public void SaveImmediately()
        {
            if (!_canSave)
            {
                _hasToSave = true;
                return;
            }

            try {
                SetToIni();
                IgnoreChangesForAWhile();
                Ini.Save(Filename);
            } catch (Exception e) {
                if (Path.GetFileName(Filename) != "assetto_corsa.ini")
                {
                    NonfatalError.Notify(ToolsStrings.AcSettings_CannotSave, ToolsStrings.AcSettings_CannotSave_Commentary, e);
                }
            } finally {
                IsSaving   = false;
                _hasToSave = false;
            }
        }
示例#29
0
        private const double DRC  = 0.8; // Dynamic Range Compression to 80%

        public ConvertWithMencoder(ConversionJobOptions conversionOptions, string tool, VideoInfo videoFile, JobStatus jobStatus, Log jobLog, Scanner commercialScan)
            : base(conversionOptions, tool, videoFile, jobStatus, jobLog, commercialScan)
        {
            //Check if MEncoder EDL Removal has been disabled at conversion time
            Ini ini = new Ini(GlobalDefs.ProfileFile);

            mEncoderEDLSkip = ini.ReadBoolean(conversionOptions.profile, "MEncoderEDLSkip", false);
            _jobLog.WriteEntry(this, "MEncoder skip EDL cuts (MEncoderEDLSkip) : " + mEncoderEDLSkip.ToString(), Log.LogEntryType.Debug);

            _extractCC = conversionOptions.extractCC;
            if (!String.IsNullOrEmpty(_extractCC)) // If Closed Caption extraction is enabled, we don't use cut EDL using Mencoder during encoding, Mencoder has a bug which causes it to cut out of sync with the EDL file which throws the CC out of sync, it will be cut separately
            {
                _jobLog.WriteEntry(this, Localise.GetPhrase("Closed Captions Enabled, skipping EDL cutting during encoding"), Log.LogEntryType.Information);
                mEncoderEDLSkip = true;
            }

            if ((_startTrim != 0) || (_endTrim != 0)) // If trimming is enabled skip cutting using EDL otherwise MEncoder messes it up
            {
                _jobLog.WriteEntry(this, Localise.GetPhrase("Trimming Enabled, skipping EDL cutting during encoding"), Log.LogEntryType.Information);
                mEncoderEDLSkip = true;
            }
        }
示例#30
0
        public void Typical()
        {
            var fileSystem = new MockFileSystem(new Dictionary <string, MockFileData>()
            {
                { Ini.GetTypicalPath(GameRelease.SkyrimSE).Path, new MockFileData(@"[Archive]
sResourceArchiveList=Skyrim - Misc.bsa, Skyrim - Shaders.bsa
sResourceArchiveList2=Skyrim - Voices_en0.bsa, Skyrim - Textures0.bsa") }
            });

            var get = new GetArchiveIniListings(
                fileSystem,
                new GameReleaseInjection(GameRelease.SkyrimSE));

            get.Get(Ini.GetTypicalPath(GameRelease.SkyrimSE))
            .Should().Equal(new FileName[]
            {
                "Skyrim - Misc.bsa",
                "Skyrim - Shaders.bsa",
                "Skyrim - Voices_en0.bsa",
                "Skyrim - Textures0.bsa",
            });
        }
        private void ListBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            string pagepointer;
            string pokemonpointer;

            string localReadHEX()
            {
                int argStart2 = int.Parse(Ini.GetString(Conversions.ToString(MMainFunctions.GetIniFileLocation()), MainObject.Header, "HabitatTable", ""), System.Globalization.NumberStyles.HexNumber) + ListBox1.SelectedIndex * 8; int argLength = 4; var ret = HexFunctions.ReadHex(ref MainObject.LoadedRom, ref argStart2, ref argLength); return(ret);
            }

            string localReverseHEX()
            {
                string argHEXData = "hs2f853a68fa4e437f85e1eeac891b4e61()"; var ret = HexFunctions.ReverseHex(ref argHEXData); return(ret);
            }

            pagepointer = Conversion.Hex(int.Parse(localReverseHEX(), System.Globalization.NumberStyles.HexNumber) - 0x8000000);
            string localReadHEX1()
            {
                int argStart2 = int.Parse(pagepointer, System.Globalization.NumberStyles.HexNumber) + ListBox2.SelectedIndex * 8; int argLength = 4; var ret = HexFunctions.ReadHex(ref MainObject.LoadedRom, ref argStart2, ref argLength); return(ret);
            }

            string localReverseHEX1()
            {
                string argHEXData = "hs973c9cb15ed243c8bc67e408979f365f()"; var ret = HexFunctions.ReverseHex(ref argHEXData); return(ret);
            }

            pokemonpointer = Conversion.Hex(int.Parse(localReverseHEX1(), System.Globalization.NumberStyles.HexNumber) - 0x8000000);
            string localReadHEX2()
            {
                int argStart2 = int.Parse(pokemonpointer, System.Globalization.NumberStyles.HexNumber) + ListBox3.SelectedIndex * 2; int argLength = 2; var ret = HexFunctions.ReadHex(ref MainObject.LoadedRom, ref argStart2, ref argLength); return(ret);
            }

            string localReverseHEX2()
            {
                string argHEXData = "hs689333cc3fb64fe8b6c4b213ad46319f()"; var ret = HexFunctions.ReverseHex(ref argHEXData); return(ret);
            }

            ComboBox1.SelectedIndex = int.Parse(localReverseHEX2(), System.Globalization.NumberStyles.HexNumber) - 1;
        }
示例#32
0
        private static bool GetSolution()
        {
            var solutionFileDialog = new OpenFileDialog
            {
                Title    = "Select Clarion Solution",
                FileName = string.Empty,
                Filter   = "Clarion Solution Files|*.sln"
            };
            var dr = solutionFileDialog.ShowDialog();

            if (dr == DialogResult.OK)
            {
                UserSettings.SolutionName = solutionFileDialog.FileName;

                var versionControlINI = Path.GetDirectoryName(solutionFileDialog.FileName) +
                                        "\\up_vcSettings.ini";
                var iniFile = new Ini(versionControlINI);
                UserSettings.FilesFolder = $"{Path.GetDirectoryName(versionControlINI)}\\{iniFile.GetValue("OutputFolder", "VC_InterFace").Remove(0, 2)}";
                return(true);
            }
            return(false);
        }
示例#33
0
        public static Bitmap GetCryImage(Cry cry)
        {
            Bitmap cryImage;

            if (Ini.GetString(MainObject.AppPath + "GBAPGESettings.ini", "Settings", "DisableCryImage", "0") == "1")
            {
                cryImage = new Bitmap(128, 128);
            }
            else
            {
                cryImage = new Bitmap(cry.Data.Length, 128);
                using (var g = Graphics.FromImage(cryImage))
                {
                    for (int i = 1, loopTo = cry.Data.Length - 1; i <= loopTo; i++)
                    {
                        g.DrawLine(Pens.Green, i - 1, 64 + cry.Data[i - 1], i, 64 + cry.Data[i]);
                    }
                }
            }

            return(cryImage);
        }
示例#34
0
        private void FinishedOnMenuItems_Click(object sender, EventArgs e)
        {
            var senderItem = (ToolStripMenuItem)sender;

            var fm = GetSelectedFM();

            fm.FinishedOn        = 0;
            fm.FinishedOnUnknown = false;

            if (senderItem == FinishedOnUnknownMenuItem)
            {
                fm.FinishedOnUnknown = senderItem.Checked;
            }
            else
            {
                uint at = 1;
                foreach (ToolStripMenuItem item in FinishedOnMenu !.Items)
                {
                    if (item == FinishedOnUnknownMenuItem)
                    {
                        continue;
                    }

                    if (item.Checked)
                    {
                        fm.FinishedOn |= at;
                    }
                    at <<= 1;
                }
                if (fm.FinishedOn > 0)
                {
                    FinishedOnUnknownMenuItem !.Checked = false;
                    fm.FinishedOnUnknown = false;
                }
            }

            Owner.RefreshSelectedFMRowOnly();
            Ini.WriteFullFMDataIni();
        }
示例#35
0
        /// <summary>
        /// Save pad settings.
        /// </summary>
        /// <param name="padIndex">Source PAD index.</param>
        /// <param name="file">Destination INI file name.</param>
        /// <param name="iniSection">Destination INI section to save.</param>
        public bool SavePadSettings(int padIndex, string file)
        {
            var ini   = new Ini(file);
            var saved = false;
            var pad   = string.Format("PAD{0}", padIndex + 1);

            foreach (string path in SettingsMap.Keys)
            {
                string section = path.Split('\\')[0];
                // If this is not PAD section then skip.
                if (section != pad)
                {
                    continue;
                }
                var r = SaveSetting(ini, path);
                if (r)
                {
                    saved = true;
                }
            }
            return(saved);
        }
示例#36
0
 private void StopTrace()
 {
     StartBtn.Text        = StrStart;
     TraceCb.Enabled      = true;
     TagTB.Enabled        = true;
     speedupBtn.Enabled   = false;
     speeddownBtn.Enabled = false;
     pauseBtn.Enabled     = false;
     isStop = false;
     if (null != ShowThread)
     {
         if (ShowThread.IsAlive)
         {
             ShowThread.Abort();
         }
         ShowThread = null;
     }
     Application.DoEvents();
     Thread.Sleep(10);
     ClearTagPen();
     Ini.Close(Ini.CardPath);
 }
示例#37
0
        public static void SaveAnimationSpriteToFreeSpace(int pokemonindex, byte[] sprite)
        {
            var    sOffset = int.Parse(Ini.GetString(Conversions.ToString(MMainFunctions.GetIniFileLocation()), MainObject.Header, "PokemonAnimations", ""), System.Globalization.NumberStyles.HexNumber) + pokemonindex * 8; // Pointer to Pokemon front sprites, + 8 = Bulbasaur.
            string imgString;

            byte[] imgBytes;
            string imgNewOffset;

            string LocalCompressLz77String()
            {
                var argsrcString = WichuRomFunctions.ConvertByteArrayToString(ref sprite);
                var ret          = WichuRomFunctions.CompressLz77String(ref argsrcString);

                return(ret);
            }

            var argstr = LocalCompressLz77String();

            imgBytes     = WichuRomFunctions.ConvertStringToByteArray(ref argstr);
            imgString    = ByteFunctions.ByteArrayToHexString(imgBytes);
            imgNewOffset = modSearchFreeSpace.SearchFreeSpaceFourAligned(MainObject.LoadedRom, 0xFF, (long)(Strings.Len(imgString) / 2d), Conversions.ToLong("&H" + Ini.GetString(Conversions.ToString(MMainFunctions.GetIniFileLocation()), MainObject.Header, "StartSearchingForSpaceOffset", "800000"))).ToString();


            var argStart = Conversions.ToInteger(imgNewOffset);

            HexFunctions.WriteHex(ref MainObject.LoadedRom, ref argStart, ref imgString);

            string LocalReverseHex()
            {
                var argHexData = Conversion.Hex(Conversions.ToDouble(imgNewOffset) + 134217728d);
                var ret        = HexFunctions.ReverseHex(ref argHexData);

                return(ret);
            }

            var argData = LocalReverseHex();

            HexFunctions.WriteHex(ref MainObject.LoadedRom, ref sOffset, ref argData);
        }
示例#38
0
        public static string ConvertIniStringToXmlString(string iniString)
        {
            var xmlDoc = new XmlDocument();
            var root   = xmlDoc.CreateElement("root");
            var ini    = Ini.FromString(iniString);

            foreach (var section in ini.Sections)
            {
                if (section.Comment != null)
                {
                    root.AppendChild(xmlDoc.CreateComment(section.Comment));
                }

                var node = xmlDoc.CreateElement(section.SectionStart.SectionName);
                foreach (var i in section.Elements)
                {
                    XmlNode ele = null;
                    if (i is IniBlankLine)
                    {
                    }
                    else if (i is IniCommentary)
                    {
                        ele = xmlDoc.CreateComment((i as IniCommentary).Comment);
                    }
                    else if (i is IniValue)
                    {
                        ele           = xmlDoc.CreateElement((i as IniValue).Key);
                        ele.InnerText = (i as IniValue).Value;
                    }
                    if (ele != null)
                    {
                        node.AppendChild(ele);
                    }
                }
                root.AppendChild(node);
            }
            return(root.InnerXml);
        }
示例#39
0
        /// <summary>
        /// Load the specified SIMO file (in plain format) into the dictionary.
        /// TODO: The function is really slow... A good optimization is needed!
        /// </summary>
        public void LoadFromTxt(String Path)
        {
            Clear();

            lock (Entries)
            {
                Ini Ini = new Ini(Path);
                using (StreamReader Stream = new StreamReader(Path, Encoding.GetEncoding("Windows-1252")))
                {
                    String Line = null;
                    while ((Line = Stream.ReadLine()) != null)
                    {
                        if (Line.StartsWith("["))
                        {
                            Int32 UniqId = Int32.Parse(Line.Substring("[ObjIDType".Length, Line.IndexOf("]") - "[ObjIDType".Length));
                            Int32 Amount = Ini.ReadInt32("ObjIDType" + UniqId, "PartAmount");

                            Int32  Length = sizeof(Entry) + Amount * sizeof(Part);
                            Entry *pEntry = (Entry *)Kernel.malloc(Length);

                            pEntry->UniqId = UniqId;
                            pEntry->Amount = Amount;

                            for (Int32 i = 0; i < Amount; i++)
                            {
                                ((Part *)pEntry->Parts)[i].PartID  = Ini.ReadInt32("ObjIDType" + UniqId, "Part" + i.ToString());
                                ((Part *)pEntry->Parts)[i].Texture = Ini.ReadInt32("ObjIDType" + UniqId, "Texture" + i.ToString());
                            }

                            if (!Entries.ContainsKey(pEntry->UniqId))
                            {
                                Entries.Add(pEntry->UniqId, (IntPtr)pEntry);
                            }
                        }
                    }
                }
            }
        }
示例#40
0
        public void Draw(MySpriteDrawFrame frame, Data dataChanged)
        {
            if (UseDataMinMax)
            {
                def.min = shipData[def.data].Min;
                def.max = shipData[def.data].Max;
                total   = def.max - def.min;
            }
            val = Ini.AdjustToUnit(def, shipData, total, UseDataMinMax);

            //Check for hide condition.
            if (Ini.MeetsConditions(def.conditions, val, def.condVals))
            {
                return;
            }

            if ((dataChanged & def.data) != 0)
            {
                spriteSize.X = (float)Math.Abs(MathHelper.Clamp(shipData[def.data].Value, def.min, def.max) / total * def.size.X);
                //_sprite.Position = sm.AdjustToAnchor(def.anchor, def.position, spriteSize);
                sprite.Position = sm.AdjustToRotation(sm.AdjustToAnchor(def.anchor, def.position, spriteSize), def.position, def.rotation);
                sprite.Size     = spriteSize;
                if (def.backgroundSet)
                {
                    frame.Add(background);
                }
                frame.Add(sprite);
            }
            else
            {
                sprite.Size = spriteSize;
                if (def.backgroundSet)
                {
                    frame.Add(background);
                }
                frame.Add(sprite);
            }
        }
示例#41
0
        public static List <LogInfo> IniDelete(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_IniDelete));
            CodeInfo_IniDelete info = cmd.Info as CodeInfo_IniDelete;

            string fileName    = StringEscaper.Preprocess(s, info.FileName);
            string sectionName = StringEscaper.Preprocess(s, info.Section); // WB082 : 여기 값은 변수 Expand 안한다.
            string key         = StringEscaper.Preprocess(s, info.Key);     // WB082 : 여기 값은 변수 Expand는 안 하나, Escaping은 한다.

            if (sectionName.Equals(string.Empty, StringComparison.Ordinal))
            {
                throw new InvalidCodeCommandException("Section name cannot be empty", cmd);
            }
            if (key.Equals(string.Empty, StringComparison.Ordinal))
            {
                throw new InvalidCodeCommandException("Key name cannot be empty", cmd);
            }

            if (StringEscaper.PathSecurityCheck(fileName, out string errorMsg) == false)
            {
                logs.Add(new LogInfo(LogState.Error, errorMsg));
                return(logs);
            }

            bool result = Ini.DeleteKey(fileName, sectionName, key);

            if (result)
            {
                logs.Add(new LogInfo(LogState.Success, $"Key [{key}] deleted from [{fileName}]", cmd));
            }
            else
            {
                logs.Add(new LogInfo(LogState.Ignore, $"Could not delete key [{key}] from [{fileName}]", cmd));
            }
            return(logs);
        }
示例#42
0
        private static void UpdateAppInfoData(string config, string[] blacklist = null, byte[] serverKey = null)
        {
            var sectionContainsFilter = new[]
            {
                AppSupplierHosts.PortableApps,
                $"By{nameof(AppSuppliers.PortableApps)}"
            };

            foreach (var section in Ini.GetSections(config, false))
            {
                if (blacklist?.ContainsEx(section) == true || section.ContainsEx(sectionContainsFilter))
                {
                    continue;
                }

                #region Name

                var name = Ini.Read(section, "Name", config);
                if (string.IsNullOrWhiteSpace(name))
                {
                    continue;
                }
                var filters = new[]
		/// <summary>
		/// Write value to INI file by control.
		/// </summary>
		bool WriteSettingsToIni(params SettingsMapItem[] items)
		{
			var saved = false;
			var ini = new Ini(IniFileName);
			foreach (var item in items)
			{
				if (item != null)
				{
					var section = item.IniSection;
					string key = item.IniKey;
					var iniValue = ini.GetValue(section, key);
					var newValue = GetSettingValue(item.Control);
					if (iniValue != newValue)
					{
						var result = ini.SetValue(section, key, newValue);
						if (result != 0) saved = true;
					}
				}
			}
			return saved;
		}
		/// <summary>
		/// Read settings from INI file into windows form controls.
		/// </summary>
		/// <param name="file">INI file containing settings.</param>
		/// <param name="iniSection">Read setings from specified section only. Null - read from all sections.</param>
		public void ReadSettings(string file)
		{
			var ini2 = new Ini(file);
			foreach (string path in SettingsMap.Keys)
			{
				string section = path.Split('\\')[0];
				// If this is PAD section.
				var padIndex = SettingName.GetPadIndex(path);
				if (padIndex > -1)
				{
					section = GetInstanceSection(padIndex);
					// If destination section is empty because controller is not connected then skip.
					if (string.IsNullOrEmpty(section)) continue;
				}
				Control control = SettingsMap[path];
				string key = path.Split('\\')[1];
				string v = ini2.GetValue(section, key);
				ReadSettingTo(control, key, v);
			}
			loadCount++;
			if (ConfigLoaded != null) ConfigLoaded(this, new SettingEventArgs(ini2.File.Name, loadCount));
			// Read XML too.
			SettingsFile.Current.Load();
		}
		///// <summary>
		///// Write game settings to INI file.
		///// </summary>
		///// <param name="game"></param>
		//public string GetIniContent(Game game)
		//{
		//	// Get game directory.
		//	var dir = new FileInfo(game.FullPath).Directory;
		//	// Get INI file.
		//	var iniFile = dir.GetFiles(IniFileName).FirstOrDefault();
		//	var ini = new Ini(iniFile.FullName);
		//	var optionKeys = new[] { SettingName.PAD1, SettingName.PAD2, SettingName.PAD3, SettingName.PAD4 };
		//	for (int i = 0; i < optionKeys.Length; i++)
		//	{
		//		var optionKey = optionKeys[i];
		//		var mapTo = (MapTo)(i + 1);
		//		// Write PADx.
		//		var mapItem = SettingsMap.FirstOrDefault(x => x.IniSection == OptionsSection && x.IniKey == optionKey);
		//		WriteSettingsToIni(mapItem);
		//		var settings = SettingManager.Settings.Items.Where(x => x.MapTo == (int)mapTo).ToArray();
		//		for (int s = 0; s < settings.Length; s++)
		//		{
		//			var setting = settings[i];
		//			var padSetting = SettingManager.GetPadSetting(setting.PadSettingChecksum);
		//			var padSectionName = string.Format("IG_{0:N}", setting.InstanceGuid);
		//			WritePadSettingsToIni(padSectionName, setting, padSetting);
		//		}
		//	}
		//	return null;
		//}


		/// <summary>
		/// Write game settings to INI file.
		/// </summary>
		/// <param name="game"></param>
		public string GetIniContent2(Game game)
		{
			// Get game directory.
			var dir = new FileInfo(game.FullPath).Directory;
			// Get INI file.
			var iniFile = dir.GetFiles(IniFileName).FirstOrDefault();
			var ini = new Ini(iniFile.FullName);
			var optionKeys = new[] { SettingName.PAD1, SettingName.PAD2, SettingName.PAD3, SettingName.PAD4 };
			for (int i = 0; i < optionKeys.Length; i++)
			{
				var optionKey = optionKeys[i];
				var mapTo = (MapTo)(i + 1);
				// Write PADx.
				var mapItem = SettingsMap.FirstOrDefault(x => x.IniSection == OptionsSection && x.IniKey == optionKey);
				WriteSettingsToIni(mapItem);
				var settings = SettingManager.Settings.Items.Where(x => x.MapTo == (int)mapTo).ToArray();
				for (int s = 0; s < settings.Length; s++)
				{
					var setting = settings[i];
					var padSetting = SettingManager.GetPadSetting(setting.PadSettingChecksum);
					var padSectionName = string.Format("IG_{0:N}", setting.InstanceGuid);
					WritePadSettingsToIni(padSectionName, setting, padSetting);
				}
			}
			return null;
		}
		/// <summary>
		/// Get PadSetting object from INI by device Instance GUID.
		/// </summary>
		/// <param name="instanceGuid">Instance GUID.</param>
		/// <returns>PadSettings object.</returns>
		public PadSetting GetPadSetting(string padSectionName)
		{
			var ini2 = new Ini(IniFileName);
			var ps = new PadSetting();
			ps.PadSettingChecksum = Guid.Empty;
			ps.AxisToDPadDeadZone = ini2.GetValue(padSectionName, SettingName.AxisToDPadDeadZone);
			ps.AxisToDPadEnabled = ini2.GetValue(padSectionName, SettingName.AxisToDPadEnabled);
			ps.AxisToDPadOffset = ini2.GetValue(padSectionName, SettingName.AxisToDPadOffset);
			ps.ButtonA = ini2.GetValue(padSectionName, SettingName.ButtonA);
			ps.ButtonB = ini2.GetValue(padSectionName, SettingName.ButtonB);
			ps.ButtonGuide = ini2.GetValue(padSectionName, SettingName.ButtonGuide);
			ps.ButtonBig = ini2.GetValue(padSectionName, SettingName.ButtonBig);
			ps.ButtonBack = ini2.GetValue(padSectionName, SettingName.ButtonBack);
			ps.ButtonStart = ini2.GetValue(padSectionName, SettingName.ButtonStart);
			ps.ButtonX = ini2.GetValue(padSectionName, SettingName.ButtonX);
			ps.ButtonY = ini2.GetValue(padSectionName, SettingName.ButtonY);
			ps.DPad = ini2.GetValue(padSectionName, SettingName.DPad);
			ps.DPadDown = ini2.GetValue(padSectionName, SettingName.DPadDown);
			ps.DPadLeft = ini2.GetValue(padSectionName, SettingName.DPadLeft);
			ps.DPadRight = ini2.GetValue(padSectionName, SettingName.DPadRight);
			ps.DPadUp = ini2.GetValue(padSectionName, SettingName.DPadUp);
			ps.ForceEnable = ini2.GetValue(padSectionName, SettingName.ForceEnable);
			ps.ForceOverall = ini2.GetValue(padSectionName, SettingName.ForceOverall);
			ps.ForceSwapMotor = ini2.GetValue(padSectionName, SettingName.ForceSwapMotor);
			ps.ForceType = ini2.GetValue(padSectionName, SettingName.ForceType);
			ps.GamePadType = ini2.GetValue(padSectionName, SettingName.DeviceSubType);
			ps.LeftMotorPeriod = ini2.GetValue(padSectionName, SettingName.LeftMotorPeriod);
            ps.LeftMotorStrength = ini2.GetValue(padSectionName, SettingName.LeftMotorStrength);
			ps.LeftShoulder = ini2.GetValue(padSectionName, SettingName.LeftShoulder);
			ps.LeftThumbAntiDeadZoneX = ini2.GetValue(padSectionName, SettingName.LeftThumbAntiDeadZoneX);
			ps.LeftThumbAntiDeadZoneY = ini2.GetValue(padSectionName, SettingName.LeftThumbAntiDeadZoneY);
			ps.LeftThumbLinearX = ini2.GetValue(padSectionName, SettingName.LeftThumbLinearX);
			ps.LeftThumbLinearY = ini2.GetValue(padSectionName, SettingName.LeftThumbLinearY);
			ps.LeftThumbAxisX = ini2.GetValue(padSectionName, SettingName.LeftThumbAxisX);
			ps.LeftThumbAxisY = ini2.GetValue(padSectionName, SettingName.LeftThumbAxisY);
			ps.LeftThumbButton = ini2.GetValue(padSectionName, SettingName.LeftThumbButton);
			ps.LeftThumbDeadZoneX = ini2.GetValue(padSectionName, SettingName.LeftThumbDeadZoneX);
			ps.LeftThumbDeadZoneY = ini2.GetValue(padSectionName, SettingName.LeftThumbDeadZoneY);
			ps.LeftThumbDown = ini2.GetValue(padSectionName, SettingName.LeftThumbDown);
			ps.LeftThumbLeft = ini2.GetValue(padSectionName, SettingName.LeftThumbLeft);
			ps.LeftThumbRight = ini2.GetValue(padSectionName, SettingName.LeftThumbRight);
			ps.LeftThumbUp = ini2.GetValue(padSectionName, SettingName.LeftThumbUp);
			ps.LeftTrigger = ini2.GetValue(padSectionName, SettingName.LeftTrigger);
			ps.LeftTriggerDeadZone = ini2.GetValue(padSectionName, SettingName.LeftTriggerDeadZone);
			ps.PassThrough = ini2.GetValue(padSectionName, SettingName.PassThrough);
			ps.RightMotorPeriod = ini2.GetValue(padSectionName, SettingName.RightMotorPeriod);
            ps.RightMotorStrength = ini2.GetValue(padSectionName, SettingName.RightMotorStrength);
            ps.RightShoulder = ini2.GetValue(padSectionName, SettingName.RightShoulder);
			ps.RightThumbAntiDeadZoneX = ini2.GetValue(padSectionName, SettingName.RightThumbAntiDeadZoneX);
			ps.RightThumbAntiDeadZoneY = ini2.GetValue(padSectionName, SettingName.RightThumbAntiDeadZoneY);
			ps.RightThumbAxisX = ini2.GetValue(padSectionName, SettingName.RightThumbAxisX);
			ps.RightThumbAxisY = ini2.GetValue(padSectionName, SettingName.RightThumbAxisY);
			ps.RightThumbButton = ini2.GetValue(padSectionName, SettingName.RightThumbButton);
			ps.RightThumbDeadZoneX = ini2.GetValue(padSectionName, SettingName.RightThumbDeadZoneX);
			ps.RightThumbDeadZoneY = ini2.GetValue(padSectionName, SettingName.RightThumbDeadZoneY);
			ps.RightThumbLinearX = ini2.GetValue(padSectionName, SettingName.RightThumbLinearX);
			ps.RightThumbLinearY = ini2.GetValue(padSectionName, SettingName.RightThumbLinearY);
			ps.RightThumbDown = ini2.GetValue(padSectionName, SettingName.RightThumbDown);
			ps.RightThumbLeft = ini2.GetValue(padSectionName, SettingName.RightThumbLeft);
			ps.RightThumbRight = ini2.GetValue(padSectionName, SettingName.RightThumbRight);
			ps.RightThumbUp = ini2.GetValue(padSectionName, SettingName.RightThumbUp);
			ps.RightTrigger = ini2.GetValue(padSectionName, SettingName.RightTrigger);
			ps.RightTriggerDeadZone = ini2.GetValue(padSectionName, SettingName.RightTriggerDeadZone);
			return ps;
		}
示例#47
0
 /// <summary>
 /// Get array[4] of direct input devices.
 /// </summary>
 DeviceInstance[] GetDevices()
 {
     var devices = Manager.GetDevices(DeviceClass.GameControl, DeviceEnumerationFlags.AllDevices).ToArray();
     var orderedDevices = new DeviceInstance[4];
     // Assign devices to their positions.
     for (int d = 0; d < devices.Length; d++)
     {
         var ig = devices[d].InstanceGuid;
         var section = SettingManager.Current.GetInstanceSection(ig);
         var ini2 = new Ini(SettingManager.IniFileName);
         string v = ini2.GetValue(section, SettingName.MapToPad);
         int mapToPad = 0;
         if (int.TryParse(v, out mapToPad) && mapToPad > 0 && mapToPad <= 4)
         {
             // If position is not occupied then...
             if (orderedDevices[mapToPad - 1] == null)
             {
                 orderedDevices[mapToPad - 1] = devices[d];
             }
         }
     }
     // Get list of unassigned devices.
     var unassignedDevices = devices.Except(orderedDevices).ToArray();
     for (int i = 0; i < unassignedDevices.Length; i++)
     {
         // Assign to first empty slot.
         for (int d = 0; d < orderedDevices.Length; d++)
         {
             // If position is not occupied then...
             if (orderedDevices[d] == null)
             {
                 orderedDevices[d] = unassignedDevices[i];
                 break;
             }
         }
     }
     return orderedDevices;
 }
		/// <summary>
		/// Read PAD settings from INI file to form.
		/// </summary>
		/// <param name="file">INI file name.</param>
		/// <param name="iniSection">Source INI pad section.</param>
		/// <param name="padIndex">Destination pad index.</param>
		public void ReadPadSettings(string file, string iniSection, int padIndex)
		{
			var ini2 = new Ini(file);
			var pad = string.Format("PAD{0}", padIndex + 1);
			foreach (string path in SettingsMap.Keys)
			{
				string section = path.Split('\\')[0];
				if (section != pad) continue;
				string key = path.Split('\\')[1];
				Control control = SettingsMap[path];
				string dstPath = string.Format("{0}\\{1}", pad, key);
				control = SettingsMap[dstPath];
				string v = ini2.GetValue(iniSection, key);
				ReadSettingTo(control, key, v);
			}
			loadCount++;
			if (ConfigLoaded != null) ConfigLoaded(this, new SettingEventArgs(ini2.File.Name, loadCount));
		}
		public void SetPadSetting(string padSectionName, DeviceInstance di)
		{
			var ini2 = new Ini(IniFileName);
			//ps.PadSettingChecksum = Guid.Empty;
			ini2.SetValue(padSectionName, SettingName.ProductName, di.ProductName);
			ini2.SetValue(padSectionName, SettingName.ProductGuid, di.ProductGuid.ToString());
			ini2.SetValue(padSectionName, SettingName.InstanceGuid, di.InstanceGuid.ToString());
		}
		public bool ContainsInstanceSectionOld(Guid instanceGuid, string iniFileName, out string sectionName)
		{
			var ini2 = new Ini(iniFileName);
			for (int i = 1; i <= 4; i++)
			{
				var section = string.Format("PAD{0}", i);
				var v = ini2.GetValue(section, "InstanceGUID");
				if (string.IsNullOrEmpty(v)) continue;
				if (v.ToLower() == instanceGuid.ToString("D").ToLower())
				{
					sectionName = section;
					return true;
				}
			}
			sectionName = null;
			return false;
		}
		/// <summary>
		/// Check settings.
		/// </summary>
		/// <returns>True if settings changed.</returns>
		public bool CheckSettings(List<DeviceInstance> diInstances, List<DeviceInstance> diInstancesOld)
		{
			var updated = false;
			var ini2 = new Ini(IniFileName);
			var oldCount = diInstancesOld.Count;
			for (int i = 0; i < 4; i++)
			{
				var pad = string.Format("PAD{0}", i + 1);
				var section = "";
				// If direct Input instance is connected.
				if (i < diInstances.Count)
				{
					var ig = diInstances[i].InstanceGuid;
					section = GetInstanceSection(ig);
					// If INI file contain settings for this device then...
					string sectionName = null;
					if (ContainsInstanceSection(ig, IniFileName, out sectionName))
					{
						var samePosition = i < oldCount && diInstancesOld[i].InstanceGuid.Equals(diInstances[i].InstanceGuid);
						// Load settings.
						if (!samePosition)
						{
							MainForm.Current.SuspendEvents();
							ReadPadSettings(IniFileName, section, i);
							MainForm.Current.ResumeEvents();
						}
					}
					else
					{
						MainForm.Current.MainTabControl.SelectedIndex = i;
						MainForm.Current.SuspendEvents();
						ClearPadSettings(i);
						MainForm.Current.ResumeEvents();
						var f = new NewDeviceForm();
						f.LoadData(diInstances[i], i);
						f.StartPosition = FormStartPosition.CenterParent;
						var result = f.ShowDialog(MainForm.Current);
						f.Dispose();
						updated = (result == DialogResult.OK);
					}
				}
				else
				{
					MainForm.Current.SuspendEvents();
					ClearPadSettings(i);
					MainForm.Current.ResumeEvents();
				}
				// Update Mappings.
				ini2.SetValue(SettingName.Mappings, pad, section);
			}
			return updated;
		}
		/// <summary>
		/// Save setting from windows form control to current INI file.
		/// </summary>
		/// <param name="path">path of parameter (related to actual control)</param>
		/// <param name="dstIniSection">if not null then section will be different inside INI file than specified in path</param>
		public bool SaveSetting(Ini ini, string path)
		{
			var control = SettingsMap[path];
			string key = path.Split('\\')[1];
			string v = string.Empty;
            if (key == SettingName.HookMode || key.EndsWith(SettingName.DeviceSubType) || key.EndsWith(SettingName.ForceType))
			{
				var v1 = ((ComboBox)control).SelectedItem;
				if (v1 == null) { v = "0"; }
				else if (v1 is KeyValuePair) { v = ((KeyValuePair)v1).Value; }
				else { v = System.Convert.ToInt32(v1).ToString(); }
			}
			// If di menu strip attached.
			else if (control is ComboBox)
			{
                var cbx = (ComboBox)control;
                if (control.ContextMenuStrip == null)
                {
                    v = control.Text;
                }
                else
                {
                    v = new SettingsConverter(control.Text, key).ToIniSetting();
                    // make sure that disabled button value is "0".
                    if (SettingName.IsButton(key) && string.IsNullOrEmpty(v)) v = "0";
                }
			}
			else if (control is TextBox)
			{
				// if setting is readonly.
				if (key == SettingName.InstanceGuid || key == SettingName.ProductGuid)
				{
					v = string.IsNullOrEmpty(control.Text) ? Guid.Empty.ToString("D") : control.Text;
				}
				else v = control.Text;
			}
			else if (control is ListBox)
			{
				var lbx = (ListBox)control;
				v = string.Join(",", lbx.Items.Cast<string>().ToArray());
			}
			else if (control is NumericUpDown)
			{
				NumericUpDown nud = (NumericUpDown)control;
				v = nud.Value.ToString();
			}
			else if (control is TrackBar)
			{
				TrackBar tc = (TrackBar)control;
				// convert 100%  to 256
				if (key == SettingName.AxisToDPadDeadZone || key == SettingName.AxisToDPadOffset || key == SettingName.LeftTriggerDeadZone || key == SettingName.RightTriggerDeadZone)
				{
					v = System.Convert.ToInt32((float)tc.Value / 100F * 256F).ToString();
				}
				// convert 100%  to 500
				else if (key == SettingName.LeftMotorPeriod || key == SettingName.RightMotorPeriod)
				{
					v = System.Convert.ToInt32((float)tc.Value / 100F * 500F).ToString();
				}
				// Convert 100% to 32767
				else if (key == SettingName.LeftThumbDeadZoneX || key == SettingName.LeftThumbDeadZoneY || key == SettingName.RightThumbDeadZoneX || key == SettingName.RightThumbDeadZoneY)
				{
					v = System.Convert.ToInt32((float)tc.Value / 100F * ((float)Int16.MaxValue)).ToString();
				}
				else v = tc.Value.ToString();
			}
			else if (control is CheckBox)
			{
				CheckBox tc = (CheckBox)control;
				v = tc.Checked ? "1" : "0";
			}
			if (SettingName.IsThumbAxis(key))
			{
				v = v.Replace(SettingName.SType.Axis, "");
			}
			if (SettingName.IsDPad(key)) v = v.Replace(SettingName.SType.DPad, "");
			if (v == "v1") v = "UP";
			if (v == "v2") v = "RIGHT";
			if (v == "v3") v = "DOWN";
			if (v == "v4") v = "LEFT";
			if (v == "")
			{
				if (key == SettingName.DPadUp) v = "UP";
				if (key == SettingName.DPadDown) v = "DOWN";
				if (key == SettingName.DPadLeft) v = "LEFT";
				if (key == SettingName.DPadRight) v = "RIGHT";
			}
			// add comment.
			//var l = SettingName.MaxNameLength - key.Length + 24;
			//v = string.Format("{0, -" + l + "} # {1} Default: '{2}'.", v, SettingName.GetDescription(key), SettingName.GetDefaultValue(key));
			var section = path.Split('\\')[0];
			var padIndex = SettingName.GetPadIndex(path);
			// If this is PAD section then
			if (padIndex > -1)
			{
				section = GetInstanceSection(padIndex);
				// If destination section is empty because controller is not connected then skip.
				if (string.IsNullOrEmpty(section)) return false;
			}
			var oldValue = ini.GetValue(section, key);
			var saved = false;
			if (oldValue != v)
			{
				ini.SetValue(section, key, v);
				saveCount++;
				saved = true;
				if (ConfigSaved != null) ConfigSaved(this, new SettingEventArgs(IniFileName, saveCount));
			}
			// Flush XML too.
			SettingsFile.Current.Save();
			return saved;
		}
		public bool ContainsInstanceSection(Guid instanceGuid, string iniFileName, out string sectionName)
		{
			var ini2 = new Ini(iniFileName);
			var section = GetInstanceSection(instanceGuid);
			var contains = !string.IsNullOrEmpty(ini2.GetValue(section, "InstanceGUID"));
			sectionName = contains ? section : null;
			return contains;
		}
示例#54
0
        public void createCalendar(Ini.IniFile ini, List<Classroom> classrooms, PAZController controller)
        {
            _controller = controller;
            DateTime startDate = DateTime.Parse(ini["DATES"]["startdate"]);
            DateTime stopDate = DateTime.Parse(ini["DATES"]["enddate"]);
            Brush headerColor = Brushes.LightGray;
            int interval = 1;
            int rows = 0;

            //Firste column color rec
            Rectangle recC = new Rectangle();
            recC.Fill = headerColor;
            Grid.SetColumn(recC, 0);
            Grid.SetRow(recC, 0);
            Children.Add(recC);

            //Defining rowdef & row height
            RowDefinition row = new RowDefinition();
            GridLength height = new GridLength(140);

            for (DateTime dateTime = startDate; dateTime <= stopDate; dateTime += TimeSpan.FromDays(interval))
            {
                if (dateTime.DayOfWeek != DayOfWeek.Sunday && dateTime.DayOfWeek != DayOfWeek.Saturday)
                {
                    //Adding color
                    Rectangle rec = new Rectangle();
                    rec.Fill = headerColor;
                    Grid.SetColumn(rec, 0);
                    Grid.SetRow(rec, rows);
                    Grid.SetColumnSpan(rec, classrooms.Count + 1);
                    Children.Add(rec);
                    //Add labels
                    for (int c = 0; c < classrooms.Count + 1; c++)
                    {
                        if (ColumnDefinitions.Count != classrooms.Count + 1)
                        {
                            //making columns
                            ColumnDefinition column = new ColumnDefinition();
                            GridLength width;
                            if (c == 0)
                                width = new GridLength(75);
                            else
                                width = new GridLength(120);
                            column.Width = width;
                            ColumnDefinitions.Add(column);
                        }
                        //making labels
                        Label header = new Label();
                        if (c == 0)
                            header.Content = dateTime.ToString("dddd",
                      new CultureInfo("nl-NL")) + "\n" + dateTime.ToShortDateString();
                        else
                            header.Content = classrooms[c - 1].Room_number;
                        header.VerticalContentAlignment = System.Windows.VerticalAlignment.Center;
                        header.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center;
                        Grid.SetColumn(header, c);
                        Grid.SetRow(header, rows);
                        Children.Add(header);
                    }

                    List<Timeslot> timeslots = controller.Timeslots;

                    //Making rows
                    for (int block = 0; block < timeslots.Count ; ++block)
                    {
                        row = new RowDefinition();
                        //blok 0 = row for headers(classrooms,date)
                        if (block == 0)
                            row.Height = new GridLength(60);
                        else
                            row.Height = height;
                        RowDefinitions.Add(row);
                        rows++;

                        Label blk = new Label();
                        blk.Content = timeslots[block].Time;
                        blk.VerticalContentAlignment = System.Windows.VerticalAlignment.Center;
                        blk.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center;
                        Grid.SetColumn(blk, 0);
                        Grid.SetRow(blk, rows);
                        Children.Add(blk);
                    }

                    //Maken dateGrids
                    Grid dateGrid = new Grid();
                    for (int i = 0; i < ColumnDefinitions.Count - 1; i++)
                    {
                        ColumnDefinition column = new ColumnDefinition();
                        GridLength width = new GridLength(120);
                        column.Width = width;
                        dateGrid.ColumnDefinitions.Add(column);
                    }
                    for (int i = 0; i < 4; i++)
                    {
                        row = new RowDefinition();
                        row.Height = height;
                        dateGrid.RowDefinitions.Add(row);
                    }

                    for (int j = 0; j < 4; j++)
                    {
                        for (int i = 0; i < dateGrid.ColumnDefinitions.Count; i++)
                        {
                            CustomLabel emptySession = new CustomLabel();
                            Grid.SetColumn(emptySession, i);
                            Grid.SetRow(emptySession, j);
                            emptySession.AllowDrop = true;
                            emptySession.Drop += new DragEventHandler(Session_Drop);
                            dateGrid.Children.Add(emptySession);
                        }
                    }
                    Grid.SetColumn(dateGrid, 1);
                    Grid.SetColumnSpan(dateGrid, dateGrid.ColumnDefinitions.Count);
                    Grid.SetRow(dateGrid, rows - 3);
                    Grid.SetRowSpan(dateGrid, dateGrid.RowDefinitions.Count);
                    dateGrid.ShowGridLines = true;
                    dateGrids.Add(dateTime.ToShortDateString(), dateGrid);
                    Children.Add(dateGrid);

                    //row block 4
                    row = new RowDefinition();
                    row.Height = height;
                    RowDefinitions.Add(row);
                    rows++;
                }
            }
            //set first column color over all rows
            Grid.SetRowSpan(recC, rows);
        }
		/// <summary>
		/// Save control value to INI file.
		/// </summary>
		public bool SaveSetting(Control control)
		{
			var ini = new Ini(IniFileName);
			var saved = false;
			foreach (string path in SettingsMap.Keys)
			{
				if (SettingsMap[path] == control)
				{
					var r = SaveSetting(ini, path);
					if (r) saved = r;
					break;
				}
			}
			return saved;
		}
		/// <summary>
		/// Save all setting values to INI file.
		/// </summary>
		/// <returns></returns>
		public bool SaveSettings()
		{
			var ini = new Ini(IniFileName);
			var saved = false;
			foreach (string path in SettingsMap.Keys)
			{
				var r = SaveSetting(ini, path);
				if (r) saved = true;
			}
			return saved;
		}
示例#57
0
文件: MainForm.cs 项目: robbex/x360ce
 /// <summary>
 /// Get array[4] of direct input devices.
 /// </summary>
 DeviceInstance[] GetDevices()
 {
     var devices = Manager.GetDevices(DeviceClass.GameControl, DeviceEnumerationFlags.AllDevices).ToList();
     if (SettingManager.Current.ExcludeSuplementals)
     {
         // Supplemental devices are specialized device with functionality unsuitable for the main control of an application,
         // such as pedals used with a wheel.The following subtypes are defined.
         var supplementals = devices.Where(x => x.Type == SharpDX.DirectInput.DeviceType.Supplemental).ToArray();
         foreach (var supplemental in supplementals)
         {
             devices.Remove(supplemental);
         }
     }
     // Move gaming wheels to the top index position by default.
     // Games like GTA need wheel to be first device to work properly.
     var wheels = devices.Where(x => x.Type == SharpDX.DirectInput.DeviceType.Driving || x.Subtype == (int)DeviceSubType.Wheel).ToArray();
     foreach (var wheel in wheels)
     {
         devices.Remove(wheel);
         devices.Insert(0, wheel);
     }
     var orderedDevices = new DeviceInstance[4];
     // Assign devices to their positions.
     for (int d = 0; d < devices.Count; d++)
     {
         var ig = devices[d].InstanceGuid;
         var section = SettingManager.Current.GetInstanceSection(ig);
         var ini2 = new Ini(SettingManager.IniFileName);
         string v = ini2.GetValue(section, SettingName.MapToPad);
         int mapToPad = 0;
         if (int.TryParse(v, out mapToPad) && mapToPad > 0 && mapToPad <= 4)
         {
             // If position is not occupied then...
             if (orderedDevices[mapToPad - 1] == null)
             {
                 orderedDevices[mapToPad - 1] = devices[d];
             }
         }
     }
     // Get list of unassigned devices.
     var unassignedDevices = devices.Except(orderedDevices).ToArray();
     for (int i = 0; i < unassignedDevices.Length; i++)
     {
         // Assign to first empty slot.
         for (int d = 0; d < orderedDevices.Length; d++)
         {
             // If position is not occupied then...
             if (orderedDevices[d] == null)
             {
                 orderedDevices[d] = unassignedDevices[i];
                 break;
             }
         }
     }
     return orderedDevices;
 }
		/// <summary>
		/// Read INI file by game.
		/// </summary>
		/// <param name="game"></param>
		public SearchResult ReadIniFile(Game game)
		{
			var result = new SearchResult();
			var settings = new List<Setting>();
			var padSettings = new List<PadSetting>();
			// Get game directory.
			var dir = new FileInfo(game.FullPath).Directory;
			// Get INI file.
			var iniFile = dir.GetFiles(IniFileName).FirstOrDefault();
			if (iniFile != null)
			{
				var ini = new Ini(iniFile.FullName);
				var optionKeys = new[]
				{
					SettingName.PAD1,
					SettingName.PAD2,
					SettingName.PAD3,
					SettingName.PAD4,
				};
				for (int i = 0; i < optionKeys.Length; i++)
				{
					var optionKey = optionKeys[i];
					var mapTo = (MapTo)(i + 1);
					var value = ini.GetValue(OptionsSection, optionKey);
					var padSectionNames = value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
					foreach (var padSectionName in padSectionNames)
					{
						Setting setting;
						PadSetting padSetting;
						ReadPadSettingsFromIni(padSectionName, out setting, out padSetting);
						setting.MapTo = (int)mapTo;
						// If settings was not added already then...
						if (!settings.Any(x => x.InstanceGuid.Equals(setting.InstanceGuid)))
						{
							settings.Add(setting);
							// If PAD setting was not added already then...
							if (padSettings.Any(x => x.PadSettingChecksum.Equals(x.PadSettingChecksum)))
							{
								padSettings.Add(padSetting);
							}
						}
					}
				}
			}
			return result;
		}
		/// <summary>
		/// Save pad settings.
		/// </summary>
		/// <param name="padIndex">Source PAD index.</param>
		/// <param name="file">Destination INI file name.</param>
		/// <param name="iniSection">Destination INI section to save.</param>
		public bool SavePadSettings(int padIndex, string file)
		{
			var ini = new Ini(file);
			var saved = false;
			var pad = string.Format("PAD{0}", padIndex + 1);
			foreach (string path in SettingsMap.Keys)
			{
				string section = path.Split('\\')[0];
				// If this is not PAD section then skip.
				if (section != pad) continue;
				var r = SaveSetting(ini, path);
				if (r) saved = true;
			}
			return saved;
		}
		/// <summary>
		/// Set INI settings from PadSetting object by device Instance GUID.
		/// </summary>
		/// <param name="instanceGuid">Instance GUID.</param>
		/// <returns>PadSettings object.</returns>
		public void SetPadSetting(string padSectionName, PadSetting ps)
		{
			var ini2 = new Ini(IniFileName);
			//ps.PadSettingChecksum = Guid.Empty;
			ini2.SetValue(padSectionName, SettingName.AxisToDPadDeadZone, ps.AxisToDPadDeadZone);
			ini2.SetValue(padSectionName, SettingName.AxisToDPadEnabled, ps.AxisToDPadEnabled);
			ini2.SetValue(padSectionName, SettingName.AxisToDPadOffset, ps.AxisToDPadOffset);
			ini2.SetValue(padSectionName, SettingName.ButtonA, ps.ButtonA);
			ini2.SetValue(padSectionName, SettingName.ButtonB, ps.ButtonB);
			ini2.SetValue(padSectionName, SettingName.ButtonGuide, ps.ButtonBig);
			ini2.SetValue(padSectionName, SettingName.ButtonBack, ps.ButtonBack);
			ini2.SetValue(padSectionName, SettingName.ButtonStart, ps.ButtonStart);
			ini2.SetValue(padSectionName, SettingName.ButtonX, ps.ButtonX);
			ini2.SetValue(padSectionName, SettingName.ButtonY, ps.ButtonY);
			ini2.SetValue(padSectionName, SettingName.DPad, ps.DPad);
			ini2.SetValue(padSectionName, SettingName.DPadDown, ps.DPadDown);
			ini2.SetValue(padSectionName, SettingName.DPadLeft, ps.DPadLeft);
			ini2.SetValue(padSectionName, SettingName.DPadRight, ps.DPadRight);
			ini2.SetValue(padSectionName, SettingName.DPadUp, ps.DPadUp);
			ini2.SetValue(padSectionName, SettingName.ForceEnable, ps.ForceEnable);
			ini2.SetValue(padSectionName, SettingName.ForceOverall, ps.ForceOverall);
			ini2.SetValue(padSectionName, SettingName.ForceSwapMotor, ps.ForceSwapMotor);
			ini2.SetValue(padSectionName, SettingName.ForceType, ps.ForceType);
			ini2.SetValue(padSectionName, SettingName.DeviceSubType, ps.GamePadType);
			ini2.SetValue(padSectionName, SettingName.LeftMotorPeriod, ps.LeftMotorPeriod);
            ini2.SetValue(padSectionName, SettingName.LeftMotorStrength, ps.LeftMotorStrength);
            ini2.SetValue(padSectionName, SettingName.LeftShoulder, ps.LeftShoulder);
			ini2.SetValue(padSectionName, SettingName.LeftThumbAntiDeadZoneX, ps.LeftThumbAntiDeadZoneX);
			ini2.SetValue(padSectionName, SettingName.LeftThumbAntiDeadZoneY, ps.LeftThumbAntiDeadZoneY);
			ini2.SetValue(padSectionName, SettingName.LeftThumbLinearX, ps.LeftThumbLinearX);
			ini2.SetValue(padSectionName, SettingName.LeftThumbLinearY, ps.LeftThumbLinearY);
			ini2.SetValue(padSectionName, SettingName.LeftThumbAxisX, ps.LeftThumbAxisX);
			ini2.SetValue(padSectionName, SettingName.LeftThumbAxisY, ps.LeftThumbAxisY);
			ini2.SetValue(padSectionName, SettingName.LeftThumbButton, ps.LeftThumbButton);
			ini2.SetValue(padSectionName, SettingName.LeftThumbDeadZoneX, ps.LeftThumbDeadZoneX);
			ini2.SetValue(padSectionName, SettingName.LeftThumbDeadZoneY, ps.LeftThumbDeadZoneY);
			ini2.SetValue(padSectionName, SettingName.LeftThumbDown, ps.LeftThumbDown);
			ini2.SetValue(padSectionName, SettingName.LeftThumbLeft, ps.LeftThumbLeft);
			ini2.SetValue(padSectionName, SettingName.LeftThumbRight, ps.LeftThumbRight);
			ini2.SetValue(padSectionName, SettingName.LeftThumbUp, ps.LeftThumbUp);
			ini2.SetValue(padSectionName, SettingName.LeftTrigger, ps.LeftTrigger);
			ini2.SetValue(padSectionName, SettingName.LeftTriggerDeadZone, ps.LeftTriggerDeadZone);
			ini2.SetValue(padSectionName, SettingName.PassThrough, ps.PassThrough);
			ini2.SetValue(padSectionName, SettingName.RightMotorPeriod, ps.RightMotorPeriod);
            ini2.SetValue(padSectionName, SettingName.RightMotorStrength, ps.RightMotorStrength);
            ini2.SetValue(padSectionName, SettingName.RightShoulder, ps.RightShoulder);
			ini2.SetValue(padSectionName, SettingName.RightThumbAntiDeadZoneX, ps.RightThumbAntiDeadZoneX);
			ini2.SetValue(padSectionName, SettingName.RightThumbAntiDeadZoneY, ps.RightThumbAntiDeadZoneY);
			ini2.SetValue(padSectionName, SettingName.RightThumbLinearX, ps.RightThumbLinearX);
			ini2.SetValue(padSectionName, SettingName.RightThumbLinearY, ps.RightThumbLinearY);
			ini2.SetValue(padSectionName, SettingName.RightThumbAxisX, ps.RightThumbAxisX);
			ini2.SetValue(padSectionName, SettingName.RightThumbAxisY, ps.RightThumbAxisY);
			ini2.SetValue(padSectionName, SettingName.RightThumbButton, ps.RightThumbButton);
			ini2.SetValue(padSectionName, SettingName.RightThumbDeadZoneX, ps.RightThumbDeadZoneX);
			ini2.SetValue(padSectionName, SettingName.RightThumbDeadZoneY, ps.RightThumbDeadZoneY);
			ini2.SetValue(padSectionName, SettingName.RightThumbDown, ps.RightThumbDown);
			ini2.SetValue(padSectionName, SettingName.RightThumbLeft, ps.RightThumbLeft);
			ini2.SetValue(padSectionName, SettingName.RightThumbRight, ps.RightThumbRight);
			ini2.SetValue(padSectionName, SettingName.RightThumbUp, ps.RightThumbUp);
			ini2.SetValue(padSectionName, SettingName.RightTrigger, ps.RightTrigger);
			ini2.SetValue(padSectionName, SettingName.RightTriggerDeadZone, ps.RightTriggerDeadZone);
		}