Beispiel #1
0
        public SettingsLoader(string path = "settings.ini")
        {
            Tags = new List <TagSettings>();

            // Copying defaults to settings
            settings = new Dictionary <string, object>();
            foreach (var def in defaults)
            {
                settings.Add(def.Key, def.Value);
            }

            // Loading settings file
            if (!File.Exists(path))
            {
                File.WriteAllText(path, "");
            }
            var     fileParser = new FileIniDataParser();
            IniData data       = fileParser.ReadFile(path);

            // Initialize new ini with defaults
            if (!data.Sections.ContainsSection("settings"))
            {
                data.Sections.AddSection("settings");
            }

            // Synchronize options and defaults
            foreach (var setVal in defaults)
            {
                // Current default settings
                var sKey = setVal.Key.ToLower();
                var sVal = setVal.Value;

                // Current options. Can be null
                var opts = options[sKey];

                // Store value from defaults. (value in data is a key in opts)
                var defaultStoreValue = opts == null ? defaults[sKey].ToString() : opts.First(x => x.Value.Equals(sVal)).Key;

                // Option was not found in settings
                if (!data["settings"].ContainsKey(sKey))
                {
                    data["settings"].AddKey(sKey, defaultStoreValue);
                    continue;
                }

                // Current data value
                var dVal = opts == null ? data["settings"][sKey] : data["settings"][sKey].ToLower();
                dVal = dVal.Trim();

                // Option has invalid value
                if (opts != null && !opts.ContainsKey(dVal))
                {
                    data["settings"][sKey] = defaultStoreValue;
                    continue;
                }

                // Actual changing value from loaded data
                settings[sKey] = opts == null ? dVal : opts[dVal];
            }


            // Get tags from settings file
            foreach (var section in data.Sections)
            {
                var sname = section.SectionName.ToLower();

                // Filter all non-tag data
                if (!sname.StartsWith("tag:"))
                {
                    continue;
                }

                // Section name without leading 'tag:'
                string sectionName = sname.Substring("tag:".Length);

                // Check if keys are present
                if (!data[sname].ContainsKey("tag"))
                {
                    data[sname].AddKey("tag", sectionName);
                }
                if (!data[sname].ContainsKey("text"))
                {
                    data[sname].AddKey("text", data[sname]["tag"]);
                }
                if (!data[sname].ContainsKey("color"))
                {
                    data[sname].AddKey("tag", "#ffffff");
                }

                Tags.Add(new TagSettings(data[sname]["tag"],
                                         data[sname]["text"],
                                         data[sname]["color"]));
            }

            // Add default tag if necessary
            if (Tags.Count == 0)
            {
                Tags.Add(defaultTag);
                string sect = "tag:" + defaultTag.Tag;
                data.Sections.AddSection(sect);
                data[sect].AddKey("tag", defaultTag.Tag);
                data[sect].AddKey("text", defaultTag.Text);
                data[sect].AddKey("color", defaultTag.Color);
            }

            // Save generated data
            fileParser.WriteFile(path, data);
        }
Beispiel #2
0
        /// <summary>
        /// 读取流媒体配置文件中关键信息
        /// </summary>
        private static void getMediaServerConfig()
        {
            string iniPath = checkMediaServerConfig();

            processZLMediaKitConfigFile(iniPath); //处理FileIniDataParser碰到#开头的行,解析错误的问题
            var parser = new FileIniDataParser();

            IniData data    = parser.ReadFile(iniPath);
            var     _tmpStr = data["general"]["mediaServerId"];

            if (!string.IsNullOrEmpty(_tmpStr))
            {
                MediaServerId = _tmpStr.Trim();
            }
            else
            {
                //生成一个id
                data["general"]["mediaServerId"] = generalGuid();
                MediaServerId = data["general"]["mediaServerId"];
                parser.WriteFile(iniPath, data);
            }

            _tmpStr = data["http"]["port"];
            if (string.IsNullOrEmpty(_tmpStr))
            {
                data["http"]["port"] = "8818";
                MediaServerHttpPort  = 8818;
                parser.WriteFile(iniPath, data);
            }
            else
            {
                MediaServerHttpPort = ushort.Parse(_tmpStr);
            }

            _tmpStr = data["api"]["secret"];
            if (!string.IsNullOrEmpty(_tmpStr))
            {
                Secret = _tmpStr;
            }
            else
            {
                throw new DataException();
            }

            Uri streamNodeUri = new Uri(StreamNodeServerUrl);

            data["hook"]["enable"]         = "1";
            data["hook"]["on_flow_report"] =
                "http://" + streamNodeUri.Host + ":" + streamNodeUri.Port +
                "/WebHook/OnStop";                                                                           //流量统计,断开连接时超过flowThreshold值时会触发
            data["hook"]["on_http_access"] = "";                                                             //http事件,不作支持
            data["hook"]["on_play"]        =
                "http://" + streamNodeUri.Host + ":" + streamNodeUri.Port + "/WebHook/OnPlay";               //有流被客户端播放时
            data["hook"]["on_publish"] =
                "http://" + streamNodeUri.Host + ":" + streamNodeUri.Port + "/WebHook/OnPublish";            //有流发布时
            data["hook"]["on_record_mp4"] =
                "http://" + streamNodeUri.Host + ":" + streamNodeUri.Port + "/WebHook/OnRecordMp4Completed"; //当录制mp4完成时
            data["hook"]["on_record_ts"] =
                "http://" + streamNodeUri.Host + ":" + streamNodeUri.Port + "/WebHook/OnRecordTsCompleted";  //当录制ts完成时
            data["hook"]["on_rtsp_auth"]      = "";                                                          //rtsp鉴权,不作支持
            data["hook"]["on_rtsp_realm"]     = "";                                                          //rtsp专用鉴权,不作支持
            data["hook"]["on_shell_login"]    = "";                                                          //shell鉴权,不作支持
            data["hook"]["on_stream_changed"] =
                "http://" + streamNodeUri.Host + ":" + streamNodeUri.Port + "/WebHook/OnStreamChange";       //流注册或注销时
            data["hook"]["on_stream_none_reader"] =
                "http://" + streamNodeUri.Host + ":" + streamNodeUri.Port + "/WebHook/OnStreamNoneReader";   //流无人观看时
            data["hook"]["on_stream_not_found"] = "";                                                        //请求没有找到对应流的时候,不作支持
            data["hook"]["on_server_started"]   = "http://" + streamNodeUri.Host + ":" + streamNodeUri.Port +
                                                  "/WebHook/OnMediaServerStart";                             //当流媒体启动时
            data["hook"]["timeoutSec"]       = "5";                                                          //httpclient超时时间5秒
            data["general"]["flowThreshold"] = "1";                                                          //当用户超过1byte流量时,将触发on_flow_report的webhook(/WebHook/OnStop)

            parser.WriteFile(iniPath, data);
        }
        public static void Save(string path)
        {
            #region Base

            if (File.Exists(path))
            {
                if (!IsFileUsable(path))
                {
                    Extensions.Error("[Config][Save][Error] Config File is not usable", 0, false);
                    return;
                }
            }

            var configParser = new FileIniDataParser();
            var configData   = new IniData();

            configData["Radar"]["Enabled"] = Settings.Radar.Enabled.ToString();

            configData["Bunnyhop"]["Enabled"] = Settings.Bunnyhop.Enabled.ToString();
            configData["Bunnyhop"]["Key"]     = Settings.Bunnyhop.Key.ToString();

            configData["Trigger"]["Enabled"] = Settings.Trigger.Enabled.ToString();
            configData["Trigger"]["Key"]     = Settings.Trigger.Key.ToString();
            configData["Trigger"]["Delay"]   = Settings.Trigger.Delay.ToString();

            configData["Chams"]["Enabled"] = Settings.Chams.Enabled.ToString();

            configData["Chams"]["Allies"]         = Settings.Chams.Allies.ToString();
            configData["Chams"]["Allies_Color_R"] = Settings.Chams.Allies_Color_R.ToString();
            configData["Chams"]["Allies_Color_G"] = Settings.Chams.Allies_Color_G.ToString();
            configData["Chams"]["Allies_Color_B"] = Settings.Chams.Allies_Color_B.ToString();
            configData["Chams"]["Allies_Color_A"] = Settings.Chams.Allies_Color_A.ToString();

            configData["Chams"]["Enemies"]         = Settings.Chams.Enemies.ToString();
            configData["Chams"]["Enemies_Color_R"] = Settings.Chams.Enemies_Color_R.ToString();
            configData["Chams"]["Enemies_Color_G"] = Settings.Chams.Enemies_Color_G.ToString();
            configData["Chams"]["Enemies_Color_B"] = Settings.Chams.Enemies_Color_B.ToString();
            configData["Chams"]["Enemies_Color_A"] = Settings.Chams.Enemies_Color_A.ToString();

            configData["Glow"]["Enabled"]         = Settings.Glow.Enabled.ToString();
            configData["Glow"]["PlayerColorMode"] = Settings.Glow.PlayerColorMode.ToString();
            configData["Glow"]["FullBloom"]       = Settings.Glow.FullBloom.ToString();

            configData["Glow"]["Allies"]         = Settings.Glow.Allies.ToString();
            configData["Glow"]["Allies_Color_R"] = Settings.Glow.Allies_Color_R.ToString();
            configData["Glow"]["Allies_Color_G"] = Settings.Glow.Allies_Color_G.ToString();
            configData["Glow"]["Allies_Color_B"] = Settings.Glow.Allies_Color_B.ToString();
            configData["Glow"]["Allies_Color_A"] = Settings.Glow.Allies_Color_A.ToString();

            configData["Glow"]["Enemies"]         = Settings.Glow.Enemies.ToString();
            configData["Glow"]["Enemies_Color_R"] = Settings.Glow.Enemies_Color_R.ToString();
            configData["Glow"]["Enemies_Color_G"] = Settings.Glow.Enemies_Color_G.ToString();
            configData["Glow"]["Enemies_Color_B"] = Settings.Glow.Enemies_Color_B.ToString();
            configData["Glow"]["Enemies_Color_A"] = Settings.Glow.Enemies_Color_A.ToString();

            configData["Glow"]["Snipers"]         = Settings.Glow.Snipers.ToString();
            configData["Glow"]["Snipers_Color_R"] = Settings.Glow.Snipers_Color_R.ToString();
            configData["Glow"]["Snipers_Color_G"] = Settings.Glow.Snipers_Color_G.ToString();
            configData["Glow"]["Snipers_Color_B"] = Settings.Glow.Snipers_Color_B.ToString();
            configData["Glow"]["Snipers_Color_A"] = Settings.Glow.Snipers_Color_A.ToString();

            configData["Glow"]["Rifles"]         = Settings.Glow.Rifles.ToString();
            configData["Glow"]["Rifles_Color_R"] = Settings.Glow.Rifles_Color_R.ToString();
            configData["Glow"]["Rifles_Color_G"] = Settings.Glow.Rifles_Color_G.ToString();
            configData["Glow"]["Rifles_Color_B"] = Settings.Glow.Rifles_Color_B.ToString();
            configData["Glow"]["Rifles_Color_A"] = Settings.Glow.Rifles_Color_A.ToString();

            configData["Glow"]["MachineGuns"]         = Settings.Glow.MachineGuns.ToString();
            configData["Glow"]["MachineGuns_Color_R"] = Settings.Glow.MachineGuns_Color_R.ToString();
            configData["Glow"]["MachineGuns_Color_G"] = Settings.Glow.MachineGuns_Color_G.ToString();
            configData["Glow"]["MachineGuns_Color_B"] = Settings.Glow.MachineGuns_Color_B.ToString();
            configData["Glow"]["MachineGuns_Color_A"] = Settings.Glow.MachineGuns_Color_A.ToString();

            configData["Glow"]["MPs"]         = Settings.Glow.MPs.ToString();
            configData["Glow"]["MPs_Color_R"] = Settings.Glow.MPs_Color_R.ToString();
            configData["Glow"]["MPs_Color_G"] = Settings.Glow.MPs_Color_G.ToString();
            configData["Glow"]["MPs_Color_B"] = Settings.Glow.MPs_Color_B.ToString();
            configData["Glow"]["MPs_Color_A"] = Settings.Glow.MPs_Color_A.ToString();

            configData["Glow"]["Pistols"]         = Settings.Glow.Pistols.ToString();
            configData["Glow"]["Pistols_Color_R"] = Settings.Glow.Pistols_Color_R.ToString();
            configData["Glow"]["Pistols_Color_G"] = Settings.Glow.Pistols_Color_G.ToString();
            configData["Glow"]["Pistols_Color_B"] = Settings.Glow.Pistols_Color_B.ToString();
            configData["Glow"]["Pistols_Color_A"] = Settings.Glow.Pistols_Color_A.ToString();

            configData["Glow"]["Shotguns"]         = Settings.Glow.Shotguns.ToString();
            configData["Glow"]["Shotguns_Color_R"] = Settings.Glow.Shotguns_Color_R.ToString();
            configData["Glow"]["Shotguns_Color_G"] = Settings.Glow.Shotguns_Color_G.ToString();
            configData["Glow"]["Shotguns_Color_B"] = Settings.Glow.Shotguns_Color_B.ToString();
            configData["Glow"]["Shotguns_Color_A"] = Settings.Glow.Shotguns_Color_A.ToString();

            configData["Glow"]["C4"]         = Settings.Glow.C4.ToString();
            configData["Glow"]["C4_Color_R"] = Settings.Glow.C4_Color_R.ToString();
            configData["Glow"]["C4_Color_G"] = Settings.Glow.C4_Color_G.ToString();
            configData["Glow"]["C4_Color_B"] = Settings.Glow.C4_Color_B.ToString();
            configData["Glow"]["C4_Color_A"] = Settings.Glow.C4_Color_A.ToString();

            configData["Glow"]["Grenades"]         = Settings.Glow.Grenades.ToString();
            configData["Glow"]["Grenades_Color_R"] = Settings.Glow.Grenades_Color_R.ToString();
            configData["Glow"]["Grenades_Color_G"] = Settings.Glow.Grenades_Color_G.ToString();
            configData["Glow"]["Grenades_Color_B"] = Settings.Glow.Grenades_Color_B.ToString();
            configData["Glow"]["Grenades_Color_A"] = Settings.Glow.Grenades_Color_A.ToString();

            configData["Aimbot"]["Enabled"]                     = Settings.Aimbot.Enabled.ToString();
            configData["Aimbot"]["Fov"]                         = Settings.Aimbot.Fov.ToString();
            configData["Aimbot"]["Bone"]                        = Settings.Aimbot.Bone.ToString();
            configData["Aimbot"]["Smooth"]                      = Settings.Aimbot.Smooth.ToString();
            configData["Aimbot"]["RecoilControl"]               = Settings.Aimbot.RecoilControl.ToString();
            configData["Aimbot"]["YawRecoilReductionFactory"]   = Settings.Aimbot.YawRecoilReductionFactory.ToString();
            configData["Aimbot"]["PitchRecoilReductionFactory"] = Settings.Aimbot.PitchRecoilReductionFactory.ToString();
            configData["Aimbot"]["Curve"]                       = Settings.Aimbot.Curve.ToString();
            configData["Aimbot"]["CurveX"]                      = Settings.Aimbot.CurveX.ToString();
            configData["Aimbot"]["CurveY"]                      = Settings.Aimbot.CurveY.ToString();

            #endregion

            configData["FOVChanger"]["Enabled"]   = Settings.FOVChanger.Enabled.ToString();
            configData["FOVChanger"]["Fov"]       = Settings.FOVChanger.Fov.ToString();
            configData["ViewModelFov"]["Enabled"] = Settings.FOVChanger.ViewModelFov.Enabled.ToString();
            configData["ViewModelFov"]["Fov"]     = Settings.FOVChanger.ViewModelFov.Fov.ToString();

            configData["No_Flash"]["Enabled"]      = Settings.No_Flash.Enabled.ToString();
            configData["AutoPistol"]["Enabled"]    = Settings.AutoPistol.Enabled.ToString();
            configData["StandaloneRCS"]["Enabled"] = Settings.StandaloneRCS.Enabled.ToString();

            configParser.WriteFile(path, configData);

            Extensions.Information("[Config][Save] Saved", true);
        }
        private async void Connect()
        {
            try
            {
                ConnectCommand.Executable = false;

                if (string.IsNullOrWhiteSpace(ConsensusServerNetworkAddress))
                {
                    MessageBox.Show("Network address is required");
                    return;
                }
                if (string.IsNullOrWhiteSpace(ConsensusServerRpcUsername))
                {
                    MessageBox.Show("RPC username is required");
                    return;
                }
                if (ConsensusServerRpcPassword.Length == 0)
                {
                    MessageBox.Show("RPC password may not be empty");
                    return;
                }
                if (!File.Exists(ConsensusServerCertificateFile))
                {
                    MessageBox.Show("Certificate file not found");
                    return;
                }

                var rpcOptions = new ConsensusServerRpcOptions(ConsensusServerNetworkAddress,
                                                               ConsensusServerRpcUsername, ConsensusServerRpcPassword, ConsensusServerCertificateFile);
                try
                {
                    await App.Current.Synchronizer.WalletRpcClient.StartConsensusRpc(rpcOptions);
                }
                catch (Exception ex) when(ErrorHandling.IsTransient(ex) || ErrorHandling.IsClientError(ex))
                {
                    MessageBox.Show($"Unable to start {ConsensusServerRpcOptions.ApplicationName} RPC.\n\nCheck connection settings and try again.", "Error");
                    return;
                }

                await Task.Run(() =>
                {
                    // save defaults to a file so that the user doesn't have to type this information again
                    var ini = new IniData();
                    ini.Sections.AddSection("Application Options");
                    ini["Application Options"]["rpcuser"]   = ConsensusServerRpcUsername;
                    ini["Application Options"]["rpcpass"]   = ConsensusServerRpcPassword;
                    ini["Application Options"]["rpclisten"] = ConsensusServerNetworkAddress;
                    var appDataDir = Portability.LocalAppData(Environment.OSVersion.Platform,
                                                              AssemblyResources.Organization, AssemblyResources.ProductName);
                    var parser = new FileIniDataParser();
                    parser.WriteFile(Path.Combine(appDataDir, "defaults.ini"), ini);
                });

                var walletExists = await App.Current.Synchronizer.WalletRpcClient.WalletExistsAsync();

                if (!walletExists)
                {
                    _wizard.CurrentDialog = new CreateOrImportSeedDialog(Wizard);
                }
                else
                {
                    // TODO: Determine whether the public encryption is enabled and a prompt for the
                    // public passphrase prompt is needed before the wallet can be opened.  If it
                    // does not, then the wallet can be opened directly here instead of creating
                    // another dialog.
                    _wizard.CurrentDialog = new PromptPublicPassphraseDialog(Wizard);

                    //await _walletClient.OpenWallet("public");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
            finally
            {
                ConnectCommand.Executable = true;
            }
        }
Beispiel #5
0
        private void lookMapsFile(string path)
        {
            if (Path.GetExtension(path) == ".map" || Path.GetExtension(path) == ".bin" || Path.GetExtension(path) == ".html")
            {
                if (File.Exists(Path.GetDirectoryName(path) + Path.GetFileName(Path.GetDirectoryName(path)) + ".ini"))
                {
                    if (File.Exists(path.Replace(".ini", ".cmf")))
                    {
                        BitmapImage bmIcon  = new BitmapImage();
                        BitmapImage bmImage = new BitmapImage();
                        var         parser  = new FileIniDataParser();
                        IniData     data;
                        try
                        {
                            data = parser.ReadFile(Path.GetDirectoryName(path) + Path.GetFileName(Path.GetDirectoryName(path)) + ".ini", Encoding.Unicode);
                        }
                        catch
                        {
                            data = parser.ReadFile(Path.GetDirectoryName(path) + Path.GetFileName(Path.GetDirectoryName(path)) + ".ini");
                        }
                        Uri iconUri = null;
                        if ((data["FMMInfo"]["Icon"] != "" && Uri.TryCreate(data["FMMInfo"]["Icon"], UriKind.Absolute, out iconUri) && (data["FMMInfo"]["Icon"].EndsWith(".png") || data["FMMInfo"]["Icon"].EndsWith(".jpg") || data["FMMInfo"]["Icon"].EndsWith(".bmp"))))
                        {
                            try
                            {
                                var mS = GetStreamFromUrl(iconUri.OriginalString);
                                if (mS != null)
                                {
                                    using (WrappingStream wrapper = new WrappingStream(mS))
                                    {
                                        bmIcon.BeginInit();
                                        bmIcon.DecodePixelWidth = 200;
                                        bmIcon.CacheOption      = BitmapCacheOption.OnLoad;
                                        bmIcon.StreamSource     = wrapper;
                                        bmIcon.EndInit();
                                        bmIcon.Freeze();
                                    }
                                    mS.Dispose();
                                }
                                else
                                {
                                    bmIcon = null;
                                }
                            }
                            catch
                            {
                                // image probably corrupted or intercepted
                                bmIcon = null;
                            }
                        }
                        else
                        {
                            bmIcon = null;
                        }

                        Uri imageUri = null;

                        if ((data["FMMInfo"]["ImageFull"] != "" && Uri.TryCreate(data["FMMInfo"]["ImageFull"], UriKind.Absolute, out imageUri) && (data["FMMInfo"]["ImageFull"].EndsWith(".png") || data["FMMInfo"]["ImageFull"].EndsWith(".jpg") || data["FMMInfo"]["ImageFull"].EndsWith(".bmp"))) ||
                            (data["FMMInfo"]["ImageThumb"] != "" && Uri.TryCreate(data["FMMInfo"]["ImageThumb"], UriKind.Absolute, out imageUri) && (data["FMMInfo"]["ImageThumb"].EndsWith(".png") || data["FMMInfo"]["ImageThumb"].EndsWith(".jpg") || data["FMMInfo"]["ImageThumb"].EndsWith(".bmp"))))
                        {
                            try
                            {
                                var mS = GetStreamFromUrl(imageUri.OriginalString);
                                if (mS != null)
                                {
                                    using (WrappingStream wrapper = new WrappingStream(mS))
                                    {
                                        bmImage.BeginInit();
                                        bmImage.DecodePixelWidth = 200;
                                        bmImage.CacheOption      = BitmapCacheOption.OnLoad;
                                        bmImage.StreamSource     = wrapper;
                                        bmImage.EndInit();
                                        bmImage.Freeze();
                                    }
                                    mS.Dispose();
                                }
                                else
                                {
                                    bmImage = null;
                                }
                            }
                            catch
                            {
                                // image probably corrupted or intercepted
                                bmImage = null;
                            }
                        }
                        else
                        {
                            bmImage = null;
                        }

                        Dispatcher.Invoke(new Action(() => {
                            FMMFile newMap      = new FMMFile();
                            newMap.Name         = data["FMMInfo"]["Name"];
                            newMap.Author       = data["FMMInfo"]["Author"];
                            newMap.Version      = data["FMMInfo"]["Version"];
                            newMap.Desc         = data["FMMInfo"]["Desc"];
                            newMap.LongDesc     = data["FMMInfo"]["LongDesc"];
                            newMap.Url          = data["FMMInfo"]["Url"];
                            newMap.ImageFull    = data["FMMInfo"]["ImageFull"];
                            newMap.EDVersion    = data["FMMInfo"]["EDVersion"];
                            newMap.RevisionDate = data["FMMInfo"]["RevisionDate"];
                            newMap.Credits      = data["FMMInfo"]["Credits"];
                            newMap.Location     = path;

                            try
                            {
                                newMap.Icon = bmIcon;
                            }
                            catch
                            {
                                newMap.Icon = null;
                            }

                            try
                            {
                                newMap.Image = bmImage;
                            }
                            catch
                            {
                                newMap.Image = null;
                            }

                            mMaps.Add(newMap);
                        }));
                    }
                }
                else
                {
                    string mapName    = new string(ReadStringFromFile(path, 0x150, 0x20, Encoding.Unicode).Where(x => !Path.GetInvalidFileNameChars().Contains(x)).ToArray()).Trim();
                    string mapDesc    = new string(ReadStringFromFile(path, 0x170, 0x80, Encoding.ASCII).Where(c => !char.IsControl(c)).ToArray()).Trim();
                    string mapAuthor  = new string(ReadStringFromFile(path, 0x1f0, 0x17, Encoding.ASCII).Where(c => !char.IsControl(c)).ToArray()).Trim();
                    string mapBaseMap = "";
                    baseMaps.TryGetValue(LittleEndianByteArrayToInteger(ReadByteArrayFromFile(path, 0x120, 0x4), 0x0), out mapBaseMap);
                    Dispatcher.Invoke(new Action(() => {
                        mMaps.Add(new FMMFile {
                            Name = mapName, Desc = mapDesc, Author = mapAuthor, BaseMap = mapBaseMap, Icon = null, Location = path
                        });
                    }));
                }
            }
        }
Beispiel #6
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            if (!File.Exists("eula.txt"))
            {
                string eula = "" +
                              "1. 软件由 Holli_Freed 制作并开源与 GitHub 上\n" +
                              "\n" +
                              "GitHub:https://github.com/hacking001/v2tap\n" +
                              "\n" +
                              "最终解释权归 Holli_Freed 所有!" +
                              "";
                MessageBox.Show(eula, "免责声明", MessageBoxButtons.OK, MessageBoxIcon.Information);

                File.WriteAllText("eula.txt", "");
            }

            if (File.Exists("defaultConfig.ini"))
            {
                FileIniDataParser parser = new FileIniDataParser();
                IniData           data   = parser.ReadFile("defaultConfig.ini");
                v2rayServerAddressTextBox.Text   = data["v2ray"]["ServerAddress"];
                v2rayServerPortTextBox.Text      = data["v2ray"]["ServerPort"];
                v2rayUserIDTextBox.Text          = data["v2ray"]["UserID"];
                v2rayAlterIDTextBox.Text         = data["v2ray"]["AlterID"];
                v2rayTransferMethodComboBox.Text = data["v2ray"]["TransferMethod"];
                v2rayPathTextBox.Text            = data["v2ray"]["Path"];
                v2rayDefaultDNSTextBox.Text      = data["v2ray"]["DefaultDNS"];
                v2rayChinaDNSTextBox.Text        = data["v2ray"]["ChinaDNS"];
                v2rayTLSSecureCheckBox.Checked   = Boolean.Parse(data["v2ray"]["TLSSecure"]);
            }
            else
            {
                v2rayUserIDTextBox.Text = Guid.NewGuid().ToString();
                v2rayTransferMethodComboBox.SelectedIndex = 2;
            }

            using (UdpClient client = new UdpClient("114.114.114.114", 53))
            {
                IPAddress address = ((IPEndPoint)client.Client.LocalEndPoint).Address;

                int  addressCount = 0;
                int  gatewayCount = 0;
                bool addressGeted = false;

                NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
                foreach (NetworkInterface adapter in adapters)
                {
                    IPInterfaceProperties properties = adapter.GetIPProperties();

                    foreach (UnicastIPAddressInformation information in properties.UnicastAddresses)
                    {
                        if (information.Address.AddressFamily == AddressFamily.InterNetwork)
                        {
                            string IP = information.Address.ToString();

                            if (IP.StartsWith("10.") || IP.StartsWith("172.") || IP.StartsWith("192."))
                            {
                                if (Equals(information.Address, address))
                                {
                                    addressGeted = true;
                                }
                                else
                                {
                                    if (!addressGeted)
                                    {
                                        addressCount++;
                                    }
                                }

                                AdapterAddressComboBox.Items.Add(IP);
                            }
                        }
                    }

                    foreach (GatewayIPAddressInformation information in properties.GatewayAddresses)
                    {
                        if (information.Address.AddressFamily == AddressFamily.InterNetwork)
                        {
                            string IP = information.Address.ToString();

                            if (IP.StartsWith("10.") || IP.StartsWith("172.") || IP.StartsWith("192."))
                            {
                                if (!addressGeted)
                                {
                                    gatewayCount++;
                                }

                                AdapterGatewayComboBox.Items.Add(IP);
                            }
                        }
                    }
                }
                AdapterAddressComboBox.SelectedIndex = addressCount;
                AdapterGatewayComboBox.SelectedIndex = gatewayCount;
            }

            if (Process.GetProcessesByName("tun2socks").Length == 1 && Process.GetProcessesByName("wv2ray").Length == 1)
            {
                status = "检测到 tun2socks 和 v2ray 服务已启动!";

                ControlButton.Text = "关闭";
            }
            else
            {
                Utils.SharedUtils.ExecuteCommand("TASKKILL /F /T /IM tun2socks.exe");
                Utils.SharedUtils.ExecuteCommand("TASKKILL /F /T /IM wv2ray.exe");
            }

            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    try
                    {
                        Invoke((MethodInvoker) delegate
                        {
                            Text = "v2tap - " + DateTime.Now.ToString();
                        });

                        StatusLabel.Invoke((MethodInvoker) delegate
                        {
                            StatusLabel.Text = "当前状态:" + status;
                        });
                    }
                    catch (Exception)
                    {
                    }

                    Thread.Sleep(100);
                }
            });
        }
Beispiel #7
0
        public static string applyFOV(string fovOption, Boolean readOnly)
        {
            string            txtRec = "0";
            IniData           config;
            FileIniDataParser parser;
            string            path;

            try
            {
                path = getCfgFile();
                File.SetAttributes(path, File.GetAttributes(path) & ~FileAttributes.ReadOnly);
                parser = new FileIniDataParser();
                config = parser.ReadFile(path);
            } catch (Exception e)
            {
                return("1");
            }

            if (string.IsNullOrEmpty(fovOption))
            {
                // Send for null or empty
                return("0");
            }
            else if (fovOption == "100")
            {
                txtRec = "1920 x 810";
                config["/Script/FortniteGame.FortGameUserSettings"]["FullscreenMode"]                       = "2";
                config["/Script/FortniteGame.FortGameUserSettings"]["bUseDynamicResolution"]                = "False";
                config["/Script/FortniteGame.FortGameUserSettings"]["ResolutionSizeX"]                      = "1920";
                config["/Script/FortniteGame.FortGameUserSettings"]["ResolutionSizeY"]                      = "810";
                config["/Script/FortniteGame.FortGameUserSettings"]["LastUserConfirmedResolutionSizeX"]     = "1920";
                config["/Script/FortniteGame.FortGameUserSettings"]["LastUserConfirmedResolutionSizeY"]     = "810";
                config["/Script/FortniteGame.FortGameUserSettings"]["LastConfirmedFullscreenMode"]          = "2";
                config["/Script/FortniteGame.FortGameUserSettings"]["PreferredFullscreenMode"]              = "2";
                config["/Script/FortniteGame.FortGameUserSettings"]["DesiredScreenWidth"]                   = "1920";
                config["/Script/FortniteGame.FortGameUserSettings"]["DesiredScreenHeight"]                  = "810";
                config["/Script/FortniteGame.FortGameUserSettings"]["LastUserConfirmedDesiredScreenWidth"]  = "1920";
                config["/Script/FortniteGame.FortGameUserSettings"]["LastUserConfirmedDesiredScreenHeight"] = "810";
            }
            else if (fovOption == "90")
            {
                txtRec = "1920 x 945";
                config["/Script/FortniteGame.FortGameUserSettings"]["FullscreenMode"]                       = "2";
                config["/Script/FortniteGame.FortGameUserSettings"]["bUseDynamicResolution"]                = "False";
                config["/Script/FortniteGame.FortGameUserSettings"]["ResolutionSizeX"]                      = "1920";
                config["/Script/FortniteGame.FortGameUserSettings"]["ResolutionSizeY"]                      = "945";
                config["/Script/FortniteGame.FortGameUserSettings"]["LastUserConfirmedResolutionSizeX"]     = "1920";
                config["/Script/FortniteGame.FortGameUserSettings"]["LastUserConfirmedResolutionSizeY"]     = "945";
                config["/Script/FortniteGame.FortGameUserSettings"]["LastConfirmedFullscreenMode"]          = "2";
                config["/Script/FortniteGame.FortGameUserSettings"]["PreferredFullscreenMode"]              = "2";
                config["/Script/FortniteGame.FortGameUserSettings"]["DesiredScreenWidth"]                   = "1920";
                config["/Script/FortniteGame.FortGameUserSettings"]["DesiredScreenHeight"]                  = "945";
                config["/Script/FortniteGame.FortGameUserSettings"]["LastUserConfirmedDesiredScreenWidth"]  = "1920";
                config["/Script/FortniteGame.FortGameUserSettings"]["LastUserConfirmedDesiredScreenHeight"] = "945";
            }

            else if (fovOption == "110")
            {
                txtRec = "1920 x 675";
                config["/Script/FortniteGame.FortGameUserSettings"]["FullscreenMode"]                       = "2";
                config["/Script/FortniteGame.FortGameUserSettings"]["bUseDynamicResolution"]                = "False";
                config["/Script/FortniteGame.FortGameUserSettings"]["ResolutionSizeX"]                      = "1920";
                config["/Script/FortniteGame.FortGameUserSettings"]["ResolutionSizeY"]                      = "675";
                config["/Script/FortniteGame.FortGameUserSettings"]["LastUserConfirmedResolutionSizeX"]     = "1920";
                config["/Script/FortniteGame.FortGameUserSettings"]["LastUserConfirmedResolutionSizeY"]     = "675";
                config["/Script/FortniteGame.FortGameUserSettings"]["LastConfirmedFullscreenMode"]          = "2";
                config["/Script/FortniteGame.FortGameUserSettings"]["PreferredFullscreenMode"]              = "2";
                config["/Script/FortniteGame.FortGameUserSettings"]["DesiredScreenWidth"]                   = "1920";
                config["/Script/FortniteGame.FortGameUserSettings"]["DesiredScreenHeight"]                  = "675";
                config["/Script/FortniteGame.FortGameUserSettings"]["LastUserConfirmedDesiredScreenWidth"]  = "1920";
                config["/Script/FortniteGame.FortGameUserSettings"]["LastUserConfirmedDesiredScreenHeight"] = "675";
            }

            else if (fovOption == "120")
            {
                txtRec = "1920 x 540";
                config["/Script/FortniteGame.FortGameUserSettings"]["FullscreenMode"]                       = "2";
                config["/Script/FortniteGame.FortGameUserSettings"]["bUseDynamicResolution"]                = "False";
                config["/Script/FortniteGame.FortGameUserSettings"]["ResolutionSizeX"]                      = "1920";
                config["/Script/FortniteGame.FortGameUserSettings"]["ResolutionSizeY"]                      = "540";
                config["/Script/FortniteGame.FortGameUserSettings"]["LastUserConfirmedResolutionSizeX"]     = "1920";
                config["/Script/FortniteGame.FortGameUserSettings"]["LastUserConfirmedResolutionSizeY"]     = "540";
                config["/Script/FortniteGame.FortGameUserSettings"]["LastConfirmedFullscreenMode"]          = "2";
                config["/Script/FortniteGame.FortGameUserSettings"]["PreferredFullscreenMode"]              = "2";
                config["/Script/FortniteGame.FortGameUserSettings"]["DesiredScreenWidth"]                   = "1920";
                config["/Script/FortniteGame.FortGameUserSettings"]["DesiredScreenHeight"]                  = "540";
                config["/Script/FortniteGame.FortGameUserSettings"]["LastUserConfirmedDesiredScreenWidth"]  = "1920";
                config["/Script/FortniteGame.FortGameUserSettings"]["LastUserConfirmedDesiredScreenHeight"] = "540";
            }


            //Overwrite it
            parser.WriteFile(path, config);


            if (readOnly)
            {
                File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.ReadOnly);
            }

            return(txtRec);
        }
Beispiel #8
0
        /// <summary>
        /// The entry point of the program, where the program control starts and ends.
        /// </summary>
        /// <param name="args">The command-line arguments.</param>
        public static void Main(string[] args)
        {
            //Read Initial Config of Client
            //Create an instance of a ini file parser
            FileIniDataParser fileIniData = new FileIniDataParser();
            //Parse the ini file
            IniData parsedData = fileIniData.ReadFile("HazelUDPTestClient.ini");

            ServerIP = parsedData["ServerConfig"]["ServerIP"];
            //https://www.cambiaresearch.com/articles/68/convert-string-to-int-in-csharp
            ServerPort = System.Convert.ToInt32(parsedData["ServerConfig"]["ServerPort"]);

            Console.WriteLine("ServerIP: " + parsedData["ServerConfig"]["ServerIP"]);
            Console.WriteLine("ServerPort: " + parsedData["ServerConfig"]["ServerPort"]);

            NetworkEndPoint endPoint = new NetworkEndPoint(ServerIP, ServerPort, IPMode.IPv4);

            connection = new UdpClientConnection(endPoint);

            connection.DataReceived += DataReceived;
            connection.Disconnected += ServerDisconnectHandler;

            try
            {
                Console.WriteLine("Connecting!");
                connection.Connect();

                //Send single login message
                {
                    //Login
                    //AvatarName = "Vytek75";
                    AvatarName = parsedData["User"]["UserLogin"];
                    //AvatarPassword = "******";
                    AvatarPassword = parsedData["User"]["UserPassword"];
                    SendMessageToServer((sbyte)CommandType.LOGIN);
                    Console.WriteLine("Send to: " + connection.EndPoint.ToString());
                }

                ConsoleKeyInfo cki;
                // Prevent example from ending if CTL+C is pressed.
                Console.TreatControlCAsInput = true;

                Console.WriteLine("Press any combination of CTL, ALT, and SHIFT, and a console key.");
                Console.WriteLine("Press the Escape (Esc) key to quit: \n");
                do
                {
                    cki = Console.ReadKey();
                    Console.Write(" --- You pressed ");
                    if ((cki.Modifiers & ConsoleModifiers.Alt) != 0)
                    {
                        Console.Write("ALT+");
                    }
                    if ((cki.Modifiers & ConsoleModifiers.Shift) != 0)
                    {
                        Console.Write("SHIFT+");
                    }
                    if ((cki.Modifiers & ConsoleModifiers.Control) != 0)
                    {
                        Console.Write("CTL+");
                    }
                    Console.WriteLine(cki.Key.ToString());
                    if (cki.Key.ToString().ToLower() == "r")
                    {
                        //https://gateway.ipfs.io/ipfs/QmerSDvd9PTgcbTAz68rL1ujeCZakhdLeAUpdcfdkyhqyx
                        RezObject("QmerSDvd9PTgcbTAz68rL1ujeCZakhdLeAUpdcfdkyhqyx", UID, true);
                    }
                    if (cki.Key.ToString().ToLower() == "u")
                    {
                        //https://gateway.ipfs.io/ipfs/QmerSDvd9PTgcbTAz68rL1ujeCZakhdLeAUpdcfdkyhqyx
                        DeRezObject("QmerSDvd9PTgcbTAz68rL1ujeCZakhdLeAUpdcfdkyhqyx", UID, true, (ushort)DictObjects.Count);
                    }
                } while (cki.Key != ConsoleKey.Escape);

                connection.Close();
                Environment.Exit(0);
            }
            catch (Hazel.HazelException ex)
            {
                Console.Error.WriteLine("Error: " + ex.Message + " from " + ex.Source);
                connection.Close();
                Environment.Exit(1);
            }
        }
Beispiel #9
0
        public static dynamic FromFile(string filename)
        {
            var fi = new FileIniDataParser();

            return(new DynamicIniData(fi.ReadFile(filename)));
        }
        /// <summary>
        /// Document this, here and in the actual code
        /// </summary>
        /// <param name="emulatorsFilename"></param>
        /// <returns></returns>
        internal static EmulatorConfiguration Parse(string emulatorsFilename, AppConfiguration appConfig)
        {
            // TODO: Should the defined variables be cleared between calls to parse?
            var     parser = new FileIniDataParser();
            IniData data   = parser.ReadFile(emulatorsFilename);
            EmulatorConfiguration config = new EmulatorConfiguration
            {
                emulators = new List <Emulator>()
            };

            foreach (KeyData key in data.Global)
            {
                config.keys[key.KeyName] = config.ExpandVariables(key.Value, config.keys);
            }

            foreach (SectionData section in data.Sections)
            {
                Emulator emu = new Emulator
                {
                    Category = section.SectionName
                };

                // config.keys has global keys, and we have a local set of keys that has global keys and keys defined in this section
                Dictionary <string, string> emuKeys = new Dictionary <string, string>(config.keys);
                foreach (KeyData key in section.Keys)
                {
                    // see the documentation for Validate for more info on these attributes and what they should be
                    switch (key.KeyName)
                    {
                    case "Category":       if (!string.IsNullOrWhiteSpace(key.Value))
                        {
                            emu.Category = config.ExpandVariables(key.Value, emuKeys);
                        }
                        break;

                    case "Platform":       emu.Executable = config.ExpandVariables(key.Value, emuKeys); break;

                    case "Executable":     emu.Executable = config.ExpandVariables(key.Value, emuKeys); break;

                    case "StartIn":        emu.StartIn = config.ExpandVariables(key.Value, emuKeys); break;

                    case "Parameters":     emu.Parameters = config.ExpandVariables(key.Value, emuKeys); break;

                    case "RomBasePath":    emu.RomBasePath = config.ExpandVariables(key.Value, emuKeys);    break;

                    case "TitlePattern":   emu.TitlePattern = config.ExpandVariables(key.Value, emuKeys); break;

                    case "RomRegex":       emu.RomRegex = config.ExpandVariables(key.Value, emuKeys);   break;

                    case "GridBasePath":   emu.GridBasePath = config.ExpandVariables(key.Value, emuKeys);  break;

                    case "GridRegex":      emu.GridRegex = config.ExpandVariables(key.Value, emuKeys); break;

                    case "IconBasePath":   emu.IconBasePath = config.ExpandVariables(key.Value, emuKeys); break;

                    case "IconRegex":      emu.IconRegex = config.ExpandVariables(key.Value, emuKeys); break;

                    case "BoxartBasePath": emu.BoxartBasePath = config.ExpandVariables(key.Value, emuKeys); break;

                    case "BoxartRegex":    emu.BoxartRegex = config.ExpandVariables(key.Value, emuKeys); break;

                    default:     // Default is to add new key/value pairs for use elsewhere
                        emuKeys[key.KeyName] = config.ExpandVariables(key.Value, emuKeys);
                        break;
                    }
                }

                emu.SetDefaults(appConfig);
                emu.ExpandVariables();
                config.emulators.Add(emu);
            }
            Validate(config);
            return(config);
        }
Beispiel #11
0
        private static void LoadGameFile()
        {
            try
            {
                var parser = new FileIniDataParser();
                var data   = parser.ReadFile(StorageBase.GameIniFilePath, Globals.LocalEncoding);

                //state
                var state = data["State"];
                MapBase.OpenMap(state["Map"]);
                NpcManager.Load(state["Npc"]);
                ObjManager.Load(state["Obj"]);
                BackgroundMusic.Play(state["Bgm"]);
                Globals.PlayerIndex = int.Parse(state["Chr"]);
                if (state.ContainsKey("ScriptShowMapPos"))
                {
                    Globals.ScriptShowMapPos = int.Parse(state["ScriptShowMapPos"]) > 0;
                }
                else
                {
                    Globals.ScriptShowMapPos = false;
                }

                //option
                var option = data["Option"];
                MapBase.MapTime = int.Parse(option["MapTime"]);
                WeatherManager.ShowSnow(int.Parse(option["SnowShow"]) != 0);
                if (!string.IsNullOrEmpty(option["RainFile"]))
                {
                    WeatherManager.BeginRain(option["RainFile"]);
                }
                if (string.IsNullOrEmpty(option["Water"]))
                {
                    Globals.IsWaterEffectEnabled = false;
                }
                else
                {
                    Globals.IsWaterEffectEnabled = int.Parse(option["Water"]) != 0;
                }
                if (string.IsNullOrEmpty(option["MpcStyle"]))
                {
                    MapBase.DrawColor = Color.White;
                }
                else
                {
                    MapBase.DrawColor = StorageBase.GetColorFromString(option["MpcStyle"]);
                }
                if (string.IsNullOrEmpty(option["AsfStyle"]))
                {
                    Sprite.DrawColor = Color.White;
                }
                else
                {
                    Sprite.DrawColor = StorageBase.GetColorFromString(option["AsfStyle"]);
                }
                if (string.IsNullOrEmpty(option["SaveDisabled"]))
                {
                    Globals.IsSaveDisabled = false;
                }
                else
                {
                    Globals.IsSaveDisabled = int.Parse(option["SaveDisabled"]) > 0;
                }
                if (string.IsNullOrEmpty(option["IsDropGoodWhenDefeatEnemyDisabled"]))
                {
                    Globals.IsDropGoodWhenDefeatEnemyDisabled = false;
                }
                else
                {
                    Globals.IsDropGoodWhenDefeatEnemyDisabled = int.Parse(option["IsDropGoodWhenDefeatEnemyDisabled"]) > 0;
                }
                //Timer
                var timer = data["Timer"];
                if (timer != null)
                {
                    var isOn = timer["IsOn"] != "0";
                    if (isOn)
                    {
                        ScriptExecuter.OpenTimeLimit(int.Parse(timer["TotalSecond"]));
                        var isHide = timer["IsTimerWindowShow"] != "1";
                        if (isHide)
                        {
                            ScriptExecuter.HideTimerWnd();
                        }
                        if (timer["IsScriptSet"] != "0")
                        {
                            ScriptExecuter.SetTimeScript(int.Parse(timer["TriggerTime"]),
                                                         timer["TimerScript"]);
                        }
                    }
                }

                //Variables
                ScriptExecuter.LoadVariables(data["Var"]);

                //ParallelScript
                ScriptManager.LoadParallelScript(data["ParallelScript"]);
            }
            catch (Exception exception)
            {
                Log.LogFileLoadError("Game.ini", StorageBase.GameIniFilePath, exception);
            }
        }
 //Constructor que define el fichero de configuración
 public ConfigurationHandler()
 {
     this.parser        = new FileIniDataParser();
     this.configFile    = "config.ini";
     this.configuration = parser.ReadFile(this.configFile);
 }
Beispiel #13
0
        private static void RegisterURLHandler_Linux()
        {
            var parser = new FileIniDataParser();

            // Yes, 'Assigment' is the spelling used by the library.
            parser.Parser.Configuration.AssigmentSpacer = "";
            IniData data;

            log.InfoFormat("Trying to register URL handler");

            if (!File.Exists(MimeAppsListPath))
            {
                log.InfoFormat("{0} does not exist, trying to create it", MimeAppsListPath);
                File.WriteAllLines(MimeAppsListPath, new string[] { "[Default Applications]" });
            }

            try
            {
                data = parser.ReadFile(MimeAppsListPath);
            }
            catch (DirectoryNotFoundException ex)
            {
                log.InfoFormat("Skipping URL handler: {0}", ex.Message);
                return;
            }
            catch (FileNotFoundException ex)
            {
                log.InfoFormat("Skipping URL handler: {0}", ex.Message);
                return;
            }
            catch (ParsingException ex)
            {
                log.InfoFormat("Skipping URL handler: {0}", ex.Message);
                return;
            }

            if (data["Added Associations"] == null)
            {
                data.Sections.AddSection("Added Associations");
            }
            data["Added Associations"].RemoveKey("x-scheme-handler/ckan");
            data["Added Associations"].AddKey("x-scheme-handler/ckan", HandlerFileName);

            parser.WriteFile(MimeAppsListPath, data);

            var handlerPath      = Path.Combine(ApplicationsPath, HandlerFileName);
            var handlerDirectory = Path.GetDirectoryName(handlerPath);

            if (handlerDirectory == null || !Directory.Exists(handlerDirectory))
            {
                log.ErrorFormat("Error: {0} doesn't exist", handlerDirectory);
                return;
            }

            if (File.Exists(handlerPath))
            {
                File.Delete(handlerPath);
            }

            File.WriteAllText(handlerPath, "");
            data = parser.ReadFile(handlerPath);
            data.Sections.AddSection("Desktop Entry");
            data["Desktop Entry"].AddKey("Version", "1.0");
            data["Desktop Entry"].AddKey("Type", "Application");
            data["Desktop Entry"].AddKey("Exec", "mono \"" + System.Reflection.Assembly.GetExecutingAssembly().Location + "\" gui %u");
            data["Desktop Entry"].AddKey("Icon", "ckan");
            data["Desktop Entry"].AddKey("StartupNotify", "true");
            data["Desktop Entry"].AddKey("Terminal", "false");
            data["Desktop Entry"].AddKey("Categories", "Utility");
            data["Desktop Entry"].AddKey("MimeType", "x-scheme-handler/ckan");
            data["Desktop Entry"].AddKey("Name", "CKAN Launcher");
            data["Desktop Entry"].AddKey("Comment", "Launch CKAN");

            parser.WriteFile(handlerPath, data);
            AutoUpdate.SetExecutable(handlerPath);
        }
Beispiel #14
0
 /// <summary>
 /// Initiates the Theme Colour Parser.
 /// </summary>
 public ThemePropertyParser()
 {
     _iniParser = new FileIniDataParser();
     _iniParser.Parser.Configuration.CommentString = "#";
 }
Beispiel #15
0
 public Config()
 {
     var     parser = new FileIniDataParser();
     IniData data   = parser.ReadFile(".mdNote.ini");
 }
Beispiel #16
0
        void readSettings(string path)
        {
            streamSettings        = new Hashtable();
            recordSettings        = new Hashtable();
            basicSettings         = new IniData();
            streamSettingsCurrent = new Hashtable();
            recordSettingsCurrent = new Hashtable();
            basicSettingsCurrent  = new IniData();

            try
            {
                StreamReader readerS       = new StreamReader(Path.Combine(path, "streamEncoder.json"));
                string       settingsJsonS = readerS.ReadToEnd();
                readerS.Close();
                streamSettings = JsonConvert.DeserializeObject <Hashtable>(settingsJsonS);

                if (File.Exists(Path.Combine(MainForm.selectedProfilePath, "streamEncoder.json")) && ckbCompare.Checked)
                {
                    StreamReader readerSC       = new StreamReader(Path.Combine(MainForm.selectedProfilePath, "streamEncoder.json"));
                    string       settingsJsonSC = readerSC.ReadToEnd();
                    readerSC.Close();
                    streamSettingsCurrent = JsonConvert.DeserializeObject <Hashtable>(settingsJsonS);
                }
            }
            catch (FileNotFoundException)
            {
                rbtnStreaming.Enabled = false;
            }

            try
            {
                StreamReader readerR       = new StreamReader(Path.Combine(path, "recordEncoder.json"));
                string       settingsJsonR = readerR.ReadToEnd();
                readerR.Close();
                recordSettings = JsonConvert.DeserializeObject <Hashtable>(settingsJsonR);

                if (File.Exists(Path.Combine(MainForm.selectedProfilePath, "recordEncoder.json")) && ckbCompare.Checked)
                {
                    StreamReader readerRC       = new StreamReader(Path.Combine(MainForm.selectedProfilePath, "recordEncoder.json"));
                    string       settingsJsonRC = readerRC.ReadToEnd();
                    readerRC.Close();
                    recordSettingsCurrent = JsonConvert.DeserializeObject <Hashtable>(settingsJsonR);
                }
            }
            catch (FileNotFoundException)
            {
                rbtnRecording.Enabled = false;
            }

            FileIniDataParser parser = new FileIniDataParser();

            basicSettings = parser.ReadFile(Path.Combine(path, "basic.ini"));

            if (ckbCompare.Checked)
            {
                FileIniDataParser parserC = new FileIniDataParser();
                basicSettingsCurrent = parserC.ReadFile(Path.Combine(MainForm.selectedProfilePath, "basic.ini"));
            }

            if (rbtnStreaming.Checked)
            {
                buildList(streamSettings, streamSettingsCurrent);
            }

            else if (rbtnRecording.Checked)
            {
                buildList(recordSettings, recordSettingsCurrent);
            }

            else if (rbtnBasic.Checked)
            {
                buildIniList(basicSettings, basicSettingsCurrent);
            }
        }
        public static MailClient InitializeMailClient(string _fileName)
        {
            if (File.Exists(_fileName))
            {
                string _mailServerName  = string.Empty;
                string _mailServerPort  = string.Empty;
                string _userName        = string.Empty;
                string _password        = string.Empty;
                string _fromMailAddress = string.Empty;
                bool   _useSSL          = false;

                var parser = new FileIniDataParser();

                IniData data = parser.ReadFile(_fileName, Encoding.UTF8);

                var _parameters = data["MailClient Parameters"];

                foreach (KeyData kd in _parameters)
                {
                    switch (kd.KeyName.Trim())
                    {
                    case "MailServerName":
                        _mailServerName = kd.Value.Trim();
                        break;

                    case "MailServerPort":
                        _mailServerPort = kd.Value.Trim();
                        break;

                    case "UserName":
                        _userName = kd.Value.Trim();
                        break;

                    case "Password":
                        _password = kd.Value.Trim();
                        break;

                    case "MailAddress":
                        _fromMailAddress = kd.Value.Trim();
                        break;

                    case "EnableSLL":
                        _useSSL = kd.Value.Trim() == "TRUE" ? true : false;
                        break;

                    default:
                        break;
                    }
                }
                if (_mailServerName != string.Empty & _mailServerPort != string.Empty & _userName != string.Empty & _password != string.Empty & _fromMailAddress != string.Empty)
                {
                    return(new MailClient(_mailServerName, _mailServerPort, _userName, _password, _fromMailAddress, _useSSL));
                }
                else
                {
                    Log.Instance.Trace("{0}", MethodBase.GetCurrentMethod().Name);
                    Log.Instance.Error("Eksik parametre hatası. MailClient config dosyasını kontrol ediniz.");
                    return(null);
                }
            }
            else
            {
                Log.Instance.Error("MailClient config dosyası okunamadı");
                return(null);
            }
        }
Beispiel #18
0
            public static int Get()
            {
                int i = 0;

                Array.Clear(Data, 0, Data.Length);

                // Last Settings
                Data[i, 0]  = "null";
                Data[i, 1]  = "Last saved configuration";
                Data[i, 2]  = Environment.UserName;
                Data[i, 3]  = Globals.AppInfo.BuildVersion;
                Data[i, 4]  = "https://www.facebook.com/internetfriendlymediaencoder";
                Data[i, 5]  = Properties.Settings.Default.UseMkv ? "mkv" : "mp4";
                Data[i, 6]  = Properties.Settings.Default.VideoPreset;
                Data[i, 7]  = Properties.Settings.Default.VideoTune;
                Data[i, 8]  = Properties.Settings.Default.VideoPixFmt;
                Data[i, 9]  = String.Format("{0}", Properties.Settings.Default.VideoRateType);
                Data[i, 10] = String.Format("{0}", Properties.Settings.Default.VideoRateValue);
                Data[i, 11] = Properties.Settings.Default.VideoCmd;
                Data[i, 12] = Properties.Settings.Default.AudioFormat;
                Data[i, 13] = String.Format("{0}", Properties.Settings.Default.AudioBitRate);
                Data[i, 14] = Properties.Settings.Default.AudioFreq;
                Data[i, 15] = Properties.Settings.Default.AudioChan;
                Data[i, 16] = String.Format("{0}", Properties.Settings.Default.AudioMode);
                Data[i, 17] = Properties.Settings.Default.AudioCmd;
                i++;

                // Default
                Data[i, 0]  = "null";
                Data[i, 1]  = "Default";
                Data[i, 2]  = Environment.UserName;
                Data[i, 3]  = Globals.AppInfo.BuildVersion;
                Data[i, 4]  = "https://www.facebook.com/internetfriendlymediaencoder";
                Data[i, 5]  = "mp4";
                Data[i, 6]  = "medium";
                Data[i, 7]  = "off";
                Data[i, 8]  = "420";
                Data[i, 9]  = "0";
                Data[i, 10] = "28";
                Data[i, 11] = "--dither";
                Data[i, 12] = "Passthrough/Extract all audio (Mode configuration ignored)";
                Data[i, 13] = "128";
                Data[i, 14] = "Automatic";
                Data[i, 15] = "Automatic";
                Data[i, 16] = "0";
                Data[i, 17] = "";

                foreach (var item in Directory.GetFiles(Folder, "*.nemu"))
                {
                    var     parser = new FileIniDataParser();
                    IniData data   = parser.ReadFile(item);

                    if (!Properties.Settings.Default.UseMkv)
                    {
                        if (String.Equals(data["profile"]["format"], "mkv", StringComparison.CurrentCultureIgnoreCase))
                        {
                            continue;
                        }
                    }

                    Count = ++i;

                    Data[i, 0]  = item;
                    Data[i, 1]  = data["profile"]["name"];
                    Data[i, 2]  = data["profile"]["author"];
                    Data[i, 3]  = data["profile"]["version"];
                    Data[i, 4]  = data["profile"]["homepage"];
                    Data[i, 5]  = data["profile"]["format"];
                    Data[i, 6]  = data["video"]["preset"];
                    Data[i, 7]  = data["video"]["tuning"];
                    Data[i, 8]  = data["video"]["pixfmt"];
                    Data[i, 9]  = data["video"]["ratectrl"];
                    Data[i, 10] = data["video"]["ratefact"];
                    Data[i, 11] = data["video"]["command"];
                    Data[i, 12] = data["audio"]["encoder"];
                    Data[i, 13] = data["audio"]["bit"];
                    Data[i, 14] = data["audio"]["freq"];
                    Data[i, 15] = data["audio"]["channel"];
                    Data[i, 16] = data["audio"]["mode"];
                    Data[i, 17] = data["audio"]["command"];
                }

                return(i);
            }
        private void Migration_ContentRendered(object sender, EventArgs e)
        {
            NamedBackgroundWorker nbw = new NamedBackgroundWorker(@"ME3CMMMigration");

            nbw.DoWork += (a, b) =>
            {
                bool cleanup  = false;
                bool migrated = true;
                Log.Information(@">>>> ME3CMMMigration Thread");
                Log.Information(@"Validate ME3CMM folders and files");
                var exeDir = Utilities.GetMMExecutableDirectory();


                var modsDir = Path.Combine(exeDir, @"mods");
                var dataDir = Path.Combine(exeDir, @"data");
                try
                {
                    if (Directory.Exists(modsDir) && Directory.Exists(dataDir))
                    {
                        Log.Information(@"mods and data dir exist.");
                        // 1. MIGRATE MODS
                        Log.Information(@"Step 1: Migrate mods");
                        MigratingModsTask.SetInProgress();

                        var targetModLibrary = Utilities.GetModsDirectory();

                        targetModLibrary = Path.Combine(targetModLibrary, @"ME3");
                        if (!Directory.Exists(targetModLibrary))
                        {
                            Log.Information(@"Creating target mod library directory: " + targetModLibrary);
                            Directory.CreateDirectory(targetModLibrary);
                        }

                        var sameRoot = Path.GetPathRoot(targetModLibrary) == Path.GetPathRoot(modsDir);

                        var directoriesInModsDir = Directory.GetDirectories(modsDir);

                        var numToMigrate = directoriesInModsDir.Count(x => File.Exists(Path.Combine(x, @"moddesc.ini")));
                        var numMigrated  = 0;

                        foreach (var modDirToMove in directoriesInModsDir)
                        {
                            var moddesc = Path.Combine(modDirToMove, @"moddesc.ini");
                            if (File.Exists(moddesc))
                            {
                                numMigrated++;
                                MigratingModsTask.TaskText = M3L.GetString(M3L.string_interp_migratingModsXoFY, numMigrated, numToMigrate);
                                //Migrate this folder
                                var targetDir = Path.Combine(targetModLibrary, Path.GetFileName(modDirToMove));
                                Log.Information($@"Migrating mod into ME3 directory: {modDirToMove} -> {targetDir}");
                                if (!Directory.Exists(targetDir))
                                {
                                    if (sameRoot)
                                    {
                                        Directory.Move(modDirToMove, targetDir);
                                    }
                                    else
                                    {
                                        Log.Information(@" >> Copying existing mod directory");
                                        Directory.CreateDirectory(targetDir);
                                        CopyDir.CopyAll_ProgressBar(new DirectoryInfo(modDirToMove), new DirectoryInfo(targetDir));
                                        Log.Information(@" >> Deleting existing directory");
                                        Utilities.DeleteFilesAndFoldersRecursively(modDirToMove);
                                    }

                                    Log.Information($@"Migrated {modDirToMove}");
                                }
                                else
                                {
                                    Log.Warning(@"Target directory already exists! Not migrating this directory.");
                                }
                            }
                        }

                        MigratingModsTask.SetDone();
                        Log.Information(@"Step 1: Finished mod migration");

                        // 2. MIGRATE SETTINGS
                        MigratingSettings.SetInProgress();
                        Log.Information(@"Step 2: Begin settings migration");
                        var me3cmminif = Path.Combine(exeDir, @"me3cmm.ini");
                        if (File.Exists(me3cmminif))
                        {
                            Log.Information(@"Migrating me3cmm.ini settings");
                            IniData me3cmmini = new FileIniDataParser().ReadFile(me3cmminif);
                            var     updaterServiceUsername = me3cmmini[@"UpdaterService"][@"username"];
                            if (string.IsNullOrWhiteSpace(Settings.UpdaterServiceUsername) && !string.IsNullOrWhiteSpace(updaterServiceUsername))
                            {
                                Settings.UpdaterServiceUsername = updaterServiceUsername;
                                Log.Information(@"Migrated Updater Service Username: "******"UpdaterService"][@"manifestspath"];
                            if (string.IsNullOrWhiteSpace(Settings.UpdaterServiceManifestStoragePath) && !string.IsNullOrWhiteSpace(manifestsPath))
                            {
                                Settings.UpdaterServiceManifestStoragePath = manifestsPath;
                                Log.Information(@"Migrated Updater Service Manifests Path: " + manifestsPath);
                            }

                            var lzmaStoragePath = me3cmmini[@"UpdaterService"][@"lzmastoragepath"];
                            if (string.IsNullOrWhiteSpace(Settings.UpdaterServiceLZMAStoragePath) && !string.IsNullOrWhiteSpace(lzmaStoragePath))
                            {
                                Settings.UpdaterServiceLZMAStoragePath = lzmaStoragePath;
                                Log.Information(@"Migrated Updater Service LZMA Storage Path: " + lzmaStoragePath);
                            }

                            //Modmaker Auto Injections
                            var controllerModOption = me3cmmini[@"Settings"][@"controllermoduser"];
                            if (Settings.ModMakerControllerModOption == false && controllerModOption == "1")
                            {
                                Settings.ModMakerControllerModOption = true; //Set to true (default is false)
                                Log.Information(@"Migrated Auto install controller mixins for ModMaker (true)");
                            }

                            var keybindsInjectionOption = me3cmmini[@"Settings"][@"autoinjectkeybinds"];
                            if (Settings.ModMakerAutoInjectCustomKeybindsOption == false && keybindsInjectionOption == "1")
                            {
                                Settings.ModMakerAutoInjectCustomKeybindsOption = true; //Set to true (default is false)
                                Log.Information(@"Migrated Auto inject keybinds for ModMaker (true)");
                            }

                            Settings.Save();
                        }

                        //Migrate BIOGAME_DIRECTORIES
                        var biogameDirsF = Path.Combine(dataDir, @"BIOGAME_DIRECTORIES");
                        if (File.Exists(biogameDirsF))
                        {
                            var biodirs = File.ReadAllLines(biogameDirsF);
                            foreach (var line in biodirs)
                            {
                                var gamepath = Directory.GetParent(line).FullName;
                                Log.Information(@"Validating ME3CMM target: " + gamepath);
                                GameTarget t             = new GameTarget(Mod.MEGame.ME3, gamepath, false);
                                var        failureReason = t.ValidateTarget();
                                if (failureReason == null)
                                {
                                    Utilities.AddCachedTarget(t);
                                }
                                else
                                {
                                    Log.Error($@"Not migrating invalid target {gamepath}: {failureReason}");
                                }
                            }
                        }

                        //Migrate ALOT Installer, if found
                        var alotInstallerDir = Path.Combine(dataDir, @"ALOTInstaller");
                        if (Directory.Exists(alotInstallerDir))
                        {
                            Log.Information(@"Migrating ALOTInstaller tool");
                            var externalToolsALOTInstaller = Path.Combine(dataDir, @"ExternalTools", @"ALOTInstaller");
                            Directory.CreateDirectory(Path.Combine(dataDir, @"ExternalTools"));
                            Directory.Move(alotInstallerDir, externalToolsALOTInstaller);
                            Log.Information(@"Migrated ALOTInstaller to ExternalTools");
                        }

                        //Migrate ME3Explorer, if found
                        var me3explorerDir = Path.Combine(dataDir, @"ME3Explorer");
                        if (Directory.Exists(me3explorerDir))
                        {
                            Log.Information(@"Migrating ME3Explorer tool");
                            var externalToolsME3ExplorerDir = Path.Combine(dataDir, @"ExternalTools", @"ME3Explorer");
                            Directory.CreateDirectory(Path.Combine(dataDir, @"ExternalTools"));
                            Directory.Move(me3explorerDir, externalToolsME3ExplorerDir);
                            Log.Information(@"Migrated ME3Explorer to ExternalTools");
                        }

                        //Migrate cached modmaker mods
                        var modmakerCacheDir = Path.Combine(dataDir, @"modmaker", @"cache");
                        if (Directory.Exists(modmakerCacheDir))
                        {
                            var modmakerXmls = Directory.GetFiles(modmakerCacheDir, @"*.xml");
                            if (modmakerXmls.Any())
                            {
                                var mmNewCacheDir = Utilities.GetModmakerDefinitionsCache();
                                Log.Information(@"Migrating ME3Tweaks ModMaker cached files");
                                foreach (var f in modmakerXmls)
                                {
                                    var fname    = Path.GetFileName(f);
                                    var destName = Path.Combine(mmNewCacheDir, fname);
                                    if (!File.Exists(destName))
                                    {
                                        Log.Information(@"Migrating modmaker mod delta definition file " + fname);
                                        File.Move(f, destName);
                                    }
                                }

                                Log.Information(@"Migrated ModMaker cached files");
                            }
                        }


                        //MIGRATE 7z.dll - this will only perform an interim fix (maybe network failure?) as we use 19.0 and ME3MM used 18.05
                        var me3mm7z  = Path.Combine(dataDir, @"tools\ModManagerCommandLine\x64\7z.dll");
                        var target7z = Utilities.Get7zDllPath();
                        if (File.Exists(me3mm7z) && !File.Exists(target7z))
                        {
                            Log.Information($@"Copying ME3MM 7z.dll to ME3Tweaks Mod Manager dll location: {me3mm7z} -> {target7z}");
                            File.Copy(me3mm7z, target7z, true);
                            Log.Information(@"Copied ME3MM 7z dll");
                        }

                        // Migrate DLC_AUTH_FAIL
                        var me3mmAuthFail  = Path.Combine(dataDir, @"help\DLC_AUTH_FAIL.png");
                        var targetAuthFail = Path.Combine(Utilities.GetLocalHelpResourcesDirectory(), @"DLC_AUTH_FAIL.png");
                        if (File.Exists(me3mmAuthFail) && !File.Exists(targetAuthFail))
                        {
                            Log.Information($@"Copying DLC_AUTH_FAIL help resource to ME3Tweaks Mod Manager help resources location: {me3mmAuthFail} -> {targetAuthFail}");
                            File.Copy(me3mmAuthFail, targetAuthFail, true);
                            Log.Information(@"Copied DLC_AUTH_FAIL");
                        }

                        //MIGRATE MOD GROUPS (batch install queues)
                        var modGroupsDir = Path.Combine(dataDir, @"modgroups");
                        if (Directory.Exists(modGroupsDir))
                        {
                            Log.Information(@"Migrating batch mod groups");
                            var queues = Directory.EnumerateFiles(modGroupsDir, @"*.txt").ToList();
                            foreach (var queue in queues)
                            {
                                var biqDest = Path.Combine(Utilities.GetBatchInstallGroupsFolder(), Path.GetFileName(queue));
                                Log.Information($@"Migrating mod install group: {queue} -> {biqDest}");
                                File.Move(queue, biqDest, true);
                                Log.Information(@"Migrated " + Path.GetFileName(queue));
                            }
                        }


                        // MIGRATE override
                        var overrideDir = Path.Combine(dataDir, @"override");
                        if (Directory.Exists(overrideDir))
                        {
                            Log.Information(@"Migrating override");
                            var filesInKBDir = Directory.EnumerateFiles(overrideDir, @"*.xml").ToList();
                            foreach (var file in filesInKBDir)
                            {
                                var keybindDir = Path.Combine(Utilities.GetKeybindsOverrideFolder(), @"me3-" + Path.GetFileName(file));
                                Log.Information($@"Migrating keybinds override: {file} -> {keybindDir}");
                                File.Move(file, keybindDir, true);
                                Log.Information(@"Migrated " + Path.GetFileName(file));
                            }
                        }

                        MigratingSettings.SetDone();

                        Log.Information(@"Step 2: Finished settings migration");
                        // 3. CLEANUP
                        App.Current.Dispatcher.Invoke(delegate { cleanup = M3L.ShowDialog(null, M3L.GetString(M3L.string_dialog_performMe3cmmCleanup), M3L.GetString(M3L.string_performCleanupQuestion), MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes) == MessageBoxResult.Yes; });
                        if (cleanup)
                        {
                            Log.Information(@"Step 3: Cleaning up");
                            CleaningUpTask.SetInProgress();
                            var directoriesInDataDir = Directory.GetFileSystemEntries(dataDir);
                            foreach (var entry in directoriesInDataDir)
                            {
                                var name = Path.GetFileName(entry);
                                if (Directory.Exists(entry))
                                {
                                    switch (name.ToLower())
                                    {
                                    case @"deployed mods":
                                    case @"externaltools": // Created by M3 at this point
                                    case @"patch_001_extracted":
                                    case @"pccdumps":      //guess these might be useful
                                        continue;

                                    default:
                                        try
                                        {
                                            Log.Information(@"Deleting directory: " + entry);
                                            Utilities.DeleteFilesAndFoldersRecursively(entry, true);
                                        }
                                        catch (Exception e)
                                        {
                                            Log.Error($@"Unable to delete item in data directory: {entry}, reason: {e.Message}");
                                        }

                                        break;
                                    }
                                }
                                else if (File.Exists(entry))
                                {
                                    try
                                    {
                                        Log.Information(@"Cleanup: Deleting file " + entry);
                                        File.Delete(entry);
                                    }
                                    catch (Exception e)
                                    {
                                        Log.Error($@"Unable to delete {entry}: {e.Message}");
                                    }
                                }
                            }

                            // Install redirect to ensure user shortcuts continue to work
                            var me3cmmPath = Path.Combine(exeDir, @"ME3CMM.exe");
                            Log.Information(@"Writing redirector to " + me3cmmPath);
                            Utilities.ExtractInternalFile(@"MassEffectModManagerCore.updater.ME3CMM.exe", me3cmmPath, true);
                        }
                        else
                        {
                            Log.Information(@"Skipping step 3: cleanup due to user request.");
                        }

                        CleaningUpTask.SetDone();
                        Log.Information(@"Step 3: Cleaned up");
                        Thread.Sleep(3000);
                    }
                    else
                    {
                        migrated = false;
                        Log.Error(@"mods and/or data dir don't exist! We will not attempt migration.");
                    }
                }
                catch (Exception e)
                {
                    migrated = false;
                    Log.Error(@"Error in migration: " + e.Message);
                    Crashes.TrackError(e);
                }
                Analytics.TrackEvent(@"ME3CMM Migration", new Dictionary <string, string>()
                {
                    { @"Migrated", migrated.ToString() },
                    { @"Cleaned up", cleanup.ToString() },
                });
                Log.Information(@"<<<< Exiting ME3CMMMigration Thread");
            };
            nbw.RunWorkerCompleted += (a, b) =>
            {
                if (b.Error != null)
                {
                    Log.Error($@"Exception occurred in {nbw.Name} thread: {b.Error.Message}");
                }
                Log.Information(@"Migration has completed.");
                M3L.ShowDialog(null, M3L.GetString(M3L.string_dialog_me3cmmMigrationCompleted));
                Close();
            };
            nbw.RunWorkerAsync();
        }
        private void processDLModIni(string modini)
        {
            Uri moduri = new Uri(modini);

            using (var client = new System.Net.WebClient())
            {
                try
                {
                    client.DownloadFile(moduri, Path.Combine(Directory.GetCurrentDirectory(), "fmm", "temp", System.IO.Path.GetFileName(moduri.LocalPath)));
                }
                catch { }
            }
            if (File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "fmm", "temp", System.IO.Path.GetFileName(moduri.LocalPath))))
            {
                Mod     newMod = new Mod();
                var     parser = new FileIniDataParser();
                IniData data;
                try
                {
                    data = parser.ReadFile(Path.Combine(Directory.GetCurrentDirectory(), "fmm", "temp", System.IO.Path.GetFileName(moduri.LocalPath)), Encoding.Unicode);
                }
                catch
                {
                    data = parser.ReadFile(Path.Combine(Directory.GetCurrentDirectory(), "fmm", "temp", System.IO.Path.GetFileName(moduri.LocalPath)));
                }
                Uri         iconUri = null;
                BitmapImage iconBm  = new BitmapImage();

                if ((data["FMMInfo"]["Icon"] != "" && Uri.TryCreate(data["FMMInfo"]["Icon"], UriKind.Absolute, out iconUri) && (data["FMMInfo"]["Icon"].EndsWith(".png") || data["FMMInfo"]["Icon"].EndsWith(".jpg") || data["FMMInfo"]["Icon"].EndsWith(".bmp"))))
                {
                    try
                    {
                        var mS = GetStreamFromUrl(iconUri.OriginalString);
                        if (mS != null)
                        {
                            using (WrappingStream wrapper = new WrappingStream(mS))
                            {
                                iconBm.BeginInit();
                                iconBm.DecodePixelWidth = 200;
                                iconBm.CacheOption      = BitmapCacheOption.OnLoad;
                                iconBm.StreamSource     = wrapper;
                                iconBm.EndInit();
                                iconBm.Freeze();
                            }
                            mS.Dispose();
                        }
                        else
                        {
                            iconBm = null;
                        }
                    }
                    catch
                    {
                        // image probably corrupted or intercepted
                        iconBm = null;
                    }
                }
                else
                {
                    iconBm = null;
                }

                Uri         imageUri = null;
                BitmapImage imageBm  = new BitmapImage();
                if ((data["FMMInfo"]["ImageFull"] != "" && Uri.TryCreate(data["FMMInfo"]["ImageFull"], UriKind.Absolute, out imageUri) && (data["FMMInfo"]["ImageFull"].EndsWith(".png") || data["FMMInfo"]["ImageFull"].EndsWith(".jpg") || data["FMMInfo"]["ImageFull"].EndsWith(".bmp"))) ||
                    (data["FMMInfo"]["ImageThumb"] != "" && Uri.TryCreate(data["FMMInfo"]["ImageThumb"], UriKind.Absolute, out imageUri) && (data["FMMInfo"]["ImageThumb"].EndsWith(".png") || data["FMMInfo"]["ImageThumb"].EndsWith(".jpg") || data["FMMInfo"]["ImageThumb"].EndsWith(".bmp"))))
                {
                    try
                    {
                        var mS = GetStreamFromUrl(imageUri.OriginalString);
                        if (mS != null)
                        {
                            using (WrappingStream wrapper = new WrappingStream(mS))
                            {
                                imageBm.BeginInit();
                                imageBm.DecodePixelWidth = 200;
                                imageBm.CacheOption      = BitmapCacheOption.OnLoad;
                                imageBm.StreamSource     = wrapper;
                                imageBm.EndInit();
                                imageBm.Freeze();
                            }
                            mS.Dispose();
                        }
                        else
                        {
                            imageBm = null;
                        }
                    }
                    catch
                    {
                        // image probably corrupted or intercepted
                        imageBm = null;
                    }
                }
                else
                {
                    imageBm = null;
                }

                Dispatcher.Invoke(new Action(() =>
                {
                    newMod.Name         = data["FMMInfo"]["Name"];
                    newMod.Author       = data["FMMInfo"]["Author"];
                    newMod.Version      = data["FMMInfo"]["Version"];
                    newMod.Desc         = data["FMMInfo"]["Desc"];
                    newMod.LongDesc     = data["FMMInfo"]["LongDesc"];
                    newMod.Warnings     = data["FMMInfo"]["Warnings"];
                    newMod.LongWarnings = data["FMMInfo"]["LongWarnings"];
                    newMod.Url          = data["FMMInfo"]["Url"];
                    newMod.ImageFull    = data["FMMInfo"]["ImageFull"];
                    newMod.EDVersion    = data["FMMInfo"]["EDVersion"];
                    newMod.RevisionDate = data["FMMInfo"]["RevisionDate"];
                    newMod.Credits      = data["FMMInfo"]["Credits"];
                    newMod.Required     = data["FMMInfo"]["Required"];
                    newMod.Icon         = iconBm;
                    newMod.Image        = imageBm;
                    newMod.Location     = modini.Substring(modini.LastIndexOf("/master/")).Replace("/master/", "");
                    dMods.Add(newMod);
                }));
            }
        }
Beispiel #21
0
        public static CookieCollection GetCookieCollection(string url)
        {
            CookieCollection ret = new CookieCollection();
            Uri location         = new Uri(url);

            if (Settings.Default.CookieSource == "Internet Explorer")
            {
                BinaryReader br        = new BinaryReader(File.Open(Environment.GetFolderPath(Environment.SpecialFolder.Cookies) + "/Low/index.dat", FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
                byte[]       indexfile = br.ReadBytes((int)br.BaseStream.Length);
                br.Close();
                int    loc        = 0;
                int    locfile    = 0;
                int    endlocfile = 0;
                byte[] domainfind = Encoding.Default.GetBytes(location.Host.Replace("www.", ""));
                loc = indexfile.indexOf(domainfind);
                byte[] bfile;
                if (loc != -1)
                {
                    locfile    = Array.IndexOf(indexfile, (byte)0xDE, loc);
                    endlocfile = Array.IndexOf(indexfile, (byte)0x2E, locfile);
                    bfile      = indexfile.sub(locfile + 1, endlocfile);
                    CookieStruct[] cs = ReadCookie(Environment.GetFolderPath(Environment.SpecialFolder.Cookies) + "/Low/" + Encoding.Default.GetString(bfile) + ".txt");
                    foreach (CookieStruct c in cs)
                    {
                        Cookie nc = new Cookie(c.VarName.Trim(), c.VarValue.Trim());
                        nc.Expires = c.ExpirationDate;
                        nc.Domain  = c.Domain;
                        ret.Add(nc);
                    }
                }
            }
            else if (Settings.Default.CookieSource == "Chrome")
            {
                string chromepath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Google\Chrome\User Data\Default";
                //string cookie = chromepath + @"\Cookies";
                if (!File.Exists(chromepath + @"\Cookies"))
                {
                    throw new Exception("Could not find Chrome cookie file!");
                }
                if (File.Exists(chromepath + @"\Cookies.dndm"))
                {
                    File.Delete(chromepath + @"\Cookies.dndm");
                }

                // We have to copy the cookies SQLite file because Chrome locks it
                File.Copy(chromepath + @"\Cookies", chromepath + @"\Cookies.dndm", true);

                SQLiteDatabase db = new SQLiteDatabase(chromepath + @"\Cookies.dndm");

                DataTable cookietable = db.GetDataTable(String.Format("SELECT * FROM cookies where host_key = \"{0}\" or host_key = \"{1}\" or host_key = \"{2}\" or host_key = \"{3}\"", location.Host, location.Host, location.Host.Replace("www.", ""), "." + location.Host));
                if (cookietable.Rows.Count > 0)
                {
                    foreach (DataRow dr in cookietable.Rows)
                    {
                        Cookie nc = new Cookie(dr["name"].ToString().Trim(), dr["value"].ToString().Trim());
                        nc.Expires = DateTimeExtension.FromUnixTime((Double.Parse(dr["expires_utc"].ToString()) / 1000000) - 11644473600);
                        nc.Domain  = dr["host_key"].ToString();
                        ret.Add(nc);
                    }
                }

                File.Delete(chromepath + @"\Cookies.dndm");
            }
            else if (Settings.Default.CookieSource == "Firefox")
            {
                //Get default folder
                string firefoxpath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\..\Roaming\Mozilla\Firefox";
                firefoxpath = Path.GetFullPath(firefoxpath);
                string            profilesini   = firefoxpath + @"\profiles.ini";
                FileIniDataParser iniparser     = new FileIniDataParser();
                IniData           inifile       = iniparser.ReadFile(profilesini);
                string            profilefolder = inifile["Profile0"]["Path"];
                string            userfolder    = firefoxpath + @"\" + profilefolder;

                string ffbookmarks = userfolder + @"\cookies.sqlite";
                string tmpffbook   = userfolder + @"\cookies.dndm";
                File.Copy(ffbookmarks, tmpffbook, true);

                SQLiteDatabase db          = new SQLiteDatabase(Path.GetFullPath(tmpffbook));
                DataTable      cookietable = db.GetDataTable(String.Format("SELECT * FROM moz_cookies where host = \"{0}\" or host = \"{1}\" or host = \"{2}\" or host = \"{3}\"", location.Host, location.Host, location.Host.Replace("www.", ""), "." + location.Host));
                if (cookietable.Rows.Count > 0)
                {
                    foreach (DataRow dr in cookietable.Rows)
                    {
                        Cookie nc = new Cookie(dr["name"].ToString(), dr["value"].ToString());
                        nc.Expires = DateTimeExtension.FromUnixTime(Double.Parse(dr["expiry"].ToString()));
                        nc.Domain  = dr["host"].ToString();
                        ret.Add(nc);
                    }
                }
                File.Delete(tmpffbook);
            }

            // Old way of finding cookies - no longer works due to IE randomization of cookie file names

            /*FileInfo[] fis = SearchCookies(Domain);
             * foreach (FileInfo fi in fis)
             * {
             *  CookieStruct[] cs = ReadCookie(fi.FullName);
             *  foreach(CookieStruct c in cs)
             *      if (baseUrl.EndsWith(c.Domain) && c.ExpirationDate > DateTime.Now)
             *      {
             *          Cookie nc = new Cookie(c.VarName, c.VarValue);
             *          nc.Expires = c.ExpirationDate;
             *          nc.Domain = c.Domain;
             *          ret.Add(nc);
             *      }
             * }*/


            return(ret);
        }
Beispiel #22
0
 public ModuleLoader()
 {
     this.parser = new FileIniDataParser();
     this.parser.Parser.Configuration.SkipInvalidLines = true;
 }
Beispiel #23
0
        public MainForm()
        {
            if (LoginForm.test)
            {
                InitializeComponent();

                // Парсим конфиг
                var     parser    = new FileIniDataParser();
                IniData banksData = new IniData();
                try
                {
                    banksData = parser.ReadFile("config.ini");
                }
                catch
                {
                    errorAndExit("Возникла ошибка отсутствия файла конфигурации", "Отсутствует файл конфигурации");
                }

                // Проверка запущена ли программа с админскими правами
                try
                {
                    string currentPath   = Path.GetDirectoryName(Application.ExecutablePath);
                    string pathVariables = Environment.GetEnvironmentVariable("PATH");
                    if (!pathVariables.Contains(currentPath))
                    {
                        Environment.SetEnvironmentVariable("PATH", pathVariables + @";" + currentPath, EnvironmentVariableTarget.Machine);
                    }
                }
                catch
                {
                    errorAndExit("Программа запущена без прав администратор", "Программа запущена без прав администратор");
                }

                if (banksData.Sections.Count > 1 && banksData["Options"]["interface"] != null &&
                    banksData["Options"]["mask"] != null && banksData["Options"]["gateway"] != null && banksData["Options"]["usbip_server_ip"] != null &&
                    banksData["Options"]["usbip_server_ip"] != null && banksData["Options"]["ping_resource"] != null)
                {
                    networkInterface = banksData["Options"]["interface"];
                    mask             = banksData["Options"]["mask"];
                    gateway          = banksData["Options"]["gateway"];
                    dns             = banksData["Options"]["dns"];
                    usbipServerIP   = banksData["Options"]["usbip_server_ip"];
                    usbipServerPort = banksData["Options"]["usbip_server_port"];
                    pingResource    = banksData["Options"]["ping_resource"];

                    // Заполнение формы
                    foreach (SectionData bank in banksData.Sections.Skip(1))
                    {
                        // Формирование кнопки
                        Button buttonBank = new Button
                        {
                            Left  = left,
                            Top   = top,
                            Width = 250,
                            Text  = bank.Keys["name"]
                        };
                        banks.Add(buttonBank);

                        // Параметры тултипа для кнопки
                        string toolTipCaption = "ID: " + bank.Keys["id"] +
                                                "\nIP: " + bank.Keys["ip"] +
                                                "\nID ключа: " + bank.Keys["usb_key_id"];

                        if (bank.Keys["usb_key2_id"] != null)
                        {
                            toolTipCaption += "\nID второго ключа: " + bank.Keys["usb_key2_id"];
                        }

                        if (bank.Keys["phone"] != null)
                        {
                            toolTipCaption += "\nНомер сим-карты: " + bank.Keys["phone"];
                        }

                        ToolTip info = new ToolTip();
                        info.InitialDelay = 1000;
                        info.AutoPopDelay = 60000;
                        info.SetToolTip(buttonBank, toolTipCaption);

                        // Статус кнопки
                        PictureBox statusBank = new PictureBox();
                        PictureBox statusKeys = new PictureBox();
                        PictureBox statusInet = new PictureBox();

                        statusBank.Image = Properties.Resources.led_grey;
                        statusKeys.Image = Properties.Resources.led_grey;
                        statusInet.Image = Properties.Resources.led_grey;

                        statusBank.SizeMode = PictureBoxSizeMode.StretchImage;
                        statusBank.Size     = new Size(20, 20);
                        statusKeys.SizeMode = PictureBoxSizeMode.StretchImage;
                        statusKeys.Size     = new Size(20, 20);
                        statusInet.SizeMode = PictureBoxSizeMode.StretchImage;
                        statusInet.Size     = new Size(20, 20);

                        listStatusBank.Add(statusBank);
                        listStatusKeys.Add(statusKeys);
                        listStatusInet.Add(statusInet);

                        statusBank.Location = new Point(buttonBank.Location.X + buttonBank.Width + 34, buttonBank.Location.Y + 2);
                        statusKeys.Location = new Point(statusBank.Location.X + statusBank.Width + 31, statusBank.Location.Y);
                        statusInet.Location = new Point(statusKeys.Location.X + statusKeys.Width + 27, statusKeys.Location.Y);

                        // Обработка нажатия кнопки
                        buttonBank.Click += (sender, args) =>
                        {
                            if (bank.Keys["id"] != null && bank.Keys["ip"] != null && bank.Keys["usb_key_id"] != null)
                            {
                                logToFile("Выбран банк: " + bank.Keys["name"] + ", ID: " + bank.Keys["id"]);

                                // Очищение формы и выбор текущего банка
                                listStatusBank[currentBank].Image = Properties.Resources.led_grey;
                                listStatusKeys[currentBank].Image = Properties.Resources.led_grey;
                                listStatusInet[currentBank].Image = Properties.Resources.led_grey;
                                currentBank = Int32.Parse(bank.Keys["id"]) - 1;

                                // Зажигаем кнопку, что банк активировался
                                listStatusBank[currentBank].Image = Properties.Resources.led_green;

                                string keys = bank.Keys["usb_key_id"];
                                if (bank.Keys["usb_key2_id"] != null)
                                {
                                    keys += ", " + bank.Keys["usb_key2_id"];
                                }

                                this.Enabled = false;

                                loadingForm.labelText = "Применение параметров сетевого адаптера";

                                Thread ThreadLoadingDialog = new Thread(LoadingThreadDialog);
                                ThreadLoadingDialog.Start();

                                dismountKeys();

                                // Запускаем поток настройки сетевого интерфейса
                                Thread ThreadNetwork = new Thread(() =>
                                {
                                    Network network = new Network(networkInterface, mask, gateway, dns, pingResource, bank);
                                });
                                ThreadNetwork.Start();

                                // Запускаем поток подключения ключей
                                Thread threadUsbIPClient = new Thread(() =>
                                {
                                    loadingForm.labelText = "Инициализация ключей на стороне сервера";

                                    if (usbipClientThread(keys))
                                    {
                                        Thread ThreadSelectBank = new Thread(() =>
                                        {
                                            SelectBank selectBank = new SelectBank(usbipServerIP, pingResource, statusBank, statusKeys, statusInet, bank);
                                        });
                                        ThreadNetwork.Join();
                                        ThreadSelectBank.Start();
                                        ThreadSelectBank.Join();
                                    }
                                    else
                                    {
                                        statusKeys.Image = Properties.Resources.led_red;
                                        MainForm.logToFile("Сервер вернул ошибку");
                                        MessageBox.Show("Ошибка на стороне сервера", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                });
                                threadUsbIPClient.Start();
                                threadUsbIPClient.Join();
                                ThreadLoadingDialog.Abort();
                                this.Enabled = true;
                            }
                            else
                            {
                                logToFile("Вызвана ошибка конфигурации банка");
                                MessageBox.Show("Ошибка конфигурации банка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        };

                        if (counterRow)
                        {
                            Label labelBank = new Label
                            {
                                Text     = "Банк",
                                Left     = left,
                                Top      = 34,
                                AutoSize = true
                            };

                            Label labelOnOff = new Label
                            {
                                Text     = "Вкл/Выкл",
                                Left     = left + 265,
                                Top      = 34,
                                AutoSize = true
                            };

                            Label labelKeys = new Label
                            {
                                Text     = "Ключи",
                                Left     = left + 325,
                                Top      = 34,
                                AutoSize = true
                            };

                            Label labelInternet = new Label
                            {
                                Text     = "Интернет",
                                Left     = left + 365,
                                Top      = 34,
                                AutoSize = true
                            };

                            this.Controls.Add(labelBank);
                            this.Controls.Add(labelOnOff);
                            this.Controls.Add(labelKeys);
                            this.Controls.Add(labelInternet);
                            counterRow = false;
                        }

                        if (!LoginForm.hr)
                        {
                            addButton();

                            newLine();
                        }
                        else if (LoginForm.hr && bank.Keys["hr"] == "1")
                        {
                            addButton();

                            newLine();
                        }

                        // Функция переноса кнопок на новую строку и формирование по 20 столбцов, но не более 2 столбоцов по 20 кнопок
                        void newLine()
                        {
                            top += buttonBank.Height + 2;

                            if (banks.Count % 20 == 0)
                            {
                                this.Size  = new Size(950, 600);
                                left      += 450;
                                top        = 50;
                                counterRow = true;
                            }
                        }

                        // Функция добовления кнопок на форму
                        void addButton()
                        {
                            this.Controls.Add(buttonBank);
                            this.Controls.Add(statusBank);
                            this.Controls.Add(statusKeys);
                            this.Controls.Add(statusInet);
                        }
                    }
                }
                else if (banksData.Sections.Count > 41)
                {
                    errorAndExit("Слишком много банков добавленно", "Превышен лимит банков. Обратитесь за новой лицензией :)");
                }
                else
                {
                    errorAndExit("Вызвана ошибка содержимого файла конфигурации", "Ошибка конфигурации приложения");
                }
            }
            else
            {
                Environment.Exit(1);
            }
        }
        public static void Apply()
        {
            if (File.Exists(ConfigurationExtra.ConfigIniPath))
            {
                FileIniDataParser parser     = new FileIniDataParser();
                IniData           configdata = parser.ReadFile(ConfigurationExtra.ConfigIniPath);
                foreach (KeyValuePair <string, List <GameObject> > settingSection in settingFamillySettings)
                {
                    foreach (GameObject settingEntry in settingSection.Value)
                    {
                        PropertyInfo propSection       = Configuration.Current.GetType().GetProperty(settingSection.Key);
                        var          settingFamilyProp = propSection.GetValue(Configuration.Current, null);
                        Type         propType          = settingFamilyProp.GetType();
                        if (settingEntry.name.Contains("Toggle_Enable"))
                        {
                            Toggle    enableSectionTog = settingEntry.GetComponentInChildren <Toggle>();
                            FieldInfo prop             = propType.GetField("IsEnabled");
                            prop.SetValue(settingFamilyProp, enableSectionTog.isOn);
                            configdata[settingSection.Key]["enabled"] = enableSectionTog.isOn.ToString();
                        }
                        else
                        {
                            InputField inputEntry       = settingEntry.GetComponentInChildren <InputField>();
                            Toggle     enableSectionTog = settingEntry.GetComponentInChildren <Toggle>();
                            Dropdown   inputDropdown    = settingEntry.GetComponentInChildren <Dropdown>();
                            if (inputEntry != null)
                            {
                                string newVal = inputEntry.text;
                                if (newVal == "")
                                {
                                    continue;
                                }
                                else
                                {
                                    PropertyInfo prop = propType.GetProperty(settingEntry.name.Replace("(Clone)", ""));
                                    if (prop.PropertyType == typeof(float))
                                    {
                                        prop.SetValue(settingFamilyProp, float.Parse(newVal), null);
                                        configdata[settingSection.Key][settingEntry.name.Replace("(Clone)", "")] = newVal;
                                        continue;
                                    }

                                    if (prop.PropertyType == typeof(int))
                                    {
                                        prop.SetValue(settingFamilyProp, int.Parse(newVal), null);
                                        configdata[settingSection.Key][settingEntry.name.Replace("(Clone)", "")] = newVal;
                                        continue;
                                    }

                                    if (prop.PropertyType == typeof(bool))
                                    {
                                        prop.SetValue(settingFamilyProp, bool.Parse(newVal), null);
                                        configdata[settingSection.Key][settingEntry.name.Replace("(Clone)", "")] = newVal;
                                        continue;
                                    }

                                    if (prop.PropertyType == typeof(KeyCode) && !RPC.VPlusConfigSync.isConnecting)
                                    {
                                        prop.SetValue(settingFamilyProp, Enum.Parse(typeof(KeyCode), newVal), null);
                                        configdata[settingSection.Key][settingEntry.name.Replace("(Clone)", "")] = newVal;
                                        continue;
                                    }
                                    settingFamillySettings[settingSection.Key][settingFamillySettings[settingSection.Key].IndexOf(settingEntry)] =
                                        CreateTextSettingEntry(settingEntry.name.Replace("(Clone)", ""),
                                                               newVal, settingEntry.transform.parent,
                                                               string.Join("\n", configdata[settingSection.Key].GetKeyData(settingEntry.name.Replace("(Clone)", "")).Comments));
                                }
                            }
                            else if (inputDropdown != null)
                            {
                                PropertyInfo prop   = propType.GetProperty(settingEntry.name.Replace("(Clone)", ""));
                                string       newVal = keycodeNames[inputDropdown.value];
                                if (newVal == ((KeyCode)prop.GetValue(settingFamilyProp, null)).ToString())
                                {
                                    continue;
                                }
                                if (prop.PropertyType == typeof(KeyCode) && !RPC.VPlusConfigSync.isConnecting)
                                {
                                    prop.SetValue(settingFamilyProp, Enum.Parse(typeof(KeyCode), newVal), null);
                                    configdata[settingSection.Key][settingEntry.name.Replace("(Clone)", "")] = newVal;
                                    continue;
                                }
                            }
                            else
                            {
                                PropertyInfo prop = propType.GetProperty(settingEntry.name.Replace("(Clone)", ""));
                                prop.SetValue(settingFamilyProp, enableSectionTog.isOn, null);
                                configdata[settingSection.Key][settingEntry.name.Replace("(Clone)", "")] = enableSectionTog.isOn.ToString();
                            }
                        }
                    }
                }
                parser.WriteFile(ConfigurationExtra.ConfigIniPath, configdata);
                ValheimPlusPlugin.harmony.UnpatchSelf();
                ValheimPlusPlugin.harmony.PatchAll();
            }
        }
Beispiel #25
0
        private static IMessageBase CheckMember(string id, MiraiHttpSession Session)
        {
            Logger.Instance.AddLog(LogType.Debug, "判断的部落ID为" + id);
            ICocCorePlayers players = BaseData.Instance.container.Resolve <ICocCorePlayers>();
            Player          player  = players.GetPlayer(id);

            if (player != null && string.IsNullOrEmpty(player.Reason))
            {
                StringBuilder sb = new StringBuilder();
                bool          troopFull = true, spellFull = true, heroFull = true;
                int           heroLvNeed = 0;
                var           troopsLV   = BaseData.GetTownhallTroopsLV(player.TownHallLevel);
                sb.AppendLine("大本营等级:" + player.TownHallLevel + ",名字:" + player.Name);
                sb.AppendLine("兵力:");
                foreach (var troop in player.Troops)
                {
                    if (troop.Village != "home")
                    {
                        continue;
                    }
                    if (!troopsLV.Keys.Contains(troop.Name.Replace(" ", "_")))
                    {
                        for (int x = 1; x < BaseData.Instance.THLevels.Length; x++)
                        {
                            BaseData.Instance.thConfig[x.ToString() + "本"].AddKey(troop.Name.Replace(" ", "_"), troop.MaxLevel.ToString());
                        }
                        BaseData.Instance.config["兵种翻译"].AddKey(troop.Name.Replace(" ", "_"), troop.Name);
                        FileIniDataParser parser = new FileIniDataParser();
                        parser.WriteFile("Townhall.ini", BaseData.Instance.thConfig);
                        parser.WriteFile("config.ini", BaseData.Instance.config);
                        sb.AppendLine("* " + troop.Name + " 还缺" + (troop.MaxLevel - troop.Level) + "级 (Townhall.ini设置丢失,自动生成)");
                    }
                    else
                    {
                        if (troopsLV[troop.Name.Replace(" ", "_")] == 99)
                        {
                            BaseData.Instance.thConfig[player.TownHallLevel.ToString() + "本"][troop.Name.Replace(" ", "_")] = troop.MaxLevel.ToString();
                            FileIniDataParser parser = new FileIniDataParser();
                            parser.WriteFile("Townhall.ini", BaseData.Instance.thConfig);
                        }
                        if (troopsLV[troop.Name.Replace(" ", "_")] > troop.Level)
                        {
                            troopFull = false;
                            try
                            {
                                sb.AppendLine("* " + BaseData.Instance.config["兵种翻译"][troop.Name.Replace(" ", "_")] + " 还缺" + (troopsLV[troop.Name.Replace(" ", "_")] - troop.Level) + "级");
                            }
                            catch
                            {
                                sb.AppendLine("* " + troop.Name + " 还缺" + (troopsLV[troop.Name.Replace(" ", "_")] - troop.Level) + "级");
                            }
                        }
                    }
                }
                if (troopFull)
                {
                    sb.AppendLine("已满级");
                }
                sb.AppendLine("==================================");
                sb.AppendLine("药水:");
                foreach (var spell in player.Spells)
                {
                    if (!troopsLV.Keys.Contains(spell.Name.Replace(" ", "_")))
                    {
                        for (int x = 1; x < BaseData.Instance.THLevels.Length; x++)
                        {
                            BaseData.Instance.thConfig[x.ToString() + "本"].AddKey(spell.Name.Replace(" ", "_"), spell.MaxLevel.ToString());
                        }
                        BaseData.Instance.config["兵种翻译"].AddKey(spell.Name.Replace(" ", "_"), spell.Name);
                        FileIniDataParser parser = new FileIniDataParser();
                        parser.WriteFile("Townhall.ini", BaseData.Instance.thConfig);
                        parser.WriteFile("config.ini", BaseData.Instance.config);
                        sb.AppendLine("* " + spell.Name + " 还缺" + (spell.MaxLevel - spell.Level) + "级 (Townhall.ini设置丢失,自动生成)");
                    }
                    else
                    {
                        if (troopsLV[spell.Name.Replace(" ", "_")] == 99)
                        {
                            BaseData.Instance.thConfig[player.TownHallLevel + "本"][spell.Name.Replace(" ", "_")] = spell.MaxLevel.ToString();
                            FileIniDataParser parser = new FileIniDataParser();
                            parser.WriteFile("Townhall.ini", BaseData.Instance.thConfig);
                        }
                        if (troopsLV[spell.Name.Replace(" ", "_")] > spell.Level)
                        {
                            spellFull = false;
                            try
                            {
                                sb.AppendLine("* " + BaseData.Instance.config["兵种翻译"][spell.Name.Replace(" ", "_")] + " 还缺" + (troopsLV[spell.Name.Replace(" ", "_")] - spell.Level) + "级");
                            }
                            catch
                            {
                                sb.AppendLine("* " + spell.Name + " 还缺" + (troopsLV[spell.Name.Replace(" ", "_")] - spell.Level) + "级");
                            }
                        }
                    }
                }
                if (spellFull)
                {
                    sb.AppendLine("已满级");
                }
                if (player.Heroes.Count > 0)
                {
                    sb.AppendLine("==================================");
                    sb.AppendLine("英雄:");
                    foreach (var hero in player.Heroes)
                    {
                        if (hero.Village != "home")
                        {
                            continue;
                        }
                        if (!troopsLV.Keys.Contains(hero.Name.Replace(" ", "_")))
                        {
                            for (int x = 1; x < BaseData.Instance.THLevels.Length; x++)
                            {
                                BaseData.Instance.thConfig[x.ToString() + "本"].AddKey(hero.Name.Replace(" ", "_"), hero.MaxLevel.ToString());
                            }
                            BaseData.Instance.config["兵种翻译"].AddKey(hero.Name.Replace(" ", "_"), hero.Name);
                            FileIniDataParser parser = new FileIniDataParser();
                            parser.WriteFile("Townhall.ini", BaseData.Instance.thConfig);
                            parser.WriteFile("config.ini", BaseData.Instance.config);
                            sb.AppendLine("* " + hero.Name + " 还缺" + (hero.MaxLevel - hero.Level) + "级 (Townhall.ini设置丢失,自动生成)");
                        }
                        else
                        {
                            if (troopsLV[hero.Name.Replace(" ", "_")] == 99)
                            {
                                BaseData.Instance.thConfig[player.TownHallLevel + "本"][hero.Name.Replace(" ", "_")] = hero.MaxLevel.ToString();
                                FileIniDataParser parser = new FileIniDataParser();
                                parser.WriteFile("Townhall.ini", BaseData.Instance.thConfig);
                            }
                            if (troopsLV[hero.Name.Replace(" ", "_")] > hero.Level)
                            {
                                heroLvNeed += (troopsLV[hero.Name.Replace(" ", "_")] - hero.Level);
                                heroFull    = false;
                                try
                                {
                                    sb.AppendLine("* " + BaseData.Instance.config["兵种翻译"][hero.Name.Replace(" ", "_")] + " 还缺" + (troopsLV[hero.Name.Replace(" ", "_")] - hero.Level) + "级");
                                }
                                catch
                                {
                                    sb.AppendLine("* " + hero.Name + " 还缺" + (troopsLV[hero.Name.Replace(" ", "_")] - hero.Level) + "级");
                                }
                            }
                        }
                    }
                    if (heroFull)
                    {
                        sb.AppendLine("已满级");
                    }
                }
                if (sb.ToString().Split('\n').Length > 13 || heroLvNeed >= 10)
                {
                    sb.AppendLine("==================================");
                    sb.AppendLine("注意:严禁升本!否则将会被机票!");
                }
                if (!Directory.Exists("Buffer"))
                {
                    Directory.CreateDirectory("Buffer");
                }
                return(BaseData.TextToImg(sb.ToString(), Session));
            }
            else
            {
                if (player == null)
                {
                    return(new PlainMessage("未知的部落冲突ID,无法搜索该玩家资料!"));
                }
                else
                {
                    return(new PlainMessage("出现错误,请稍后再试!错误详情:" + player.Reason));
                }
            }
        }
        public static void Show()
        {
            norseFont = Resources.FindObjectsOfTypeAll <Font>().FirstOrDefault(fnt => fnt.name == "Norse");
            settingFamillySettings = new Dictionary <string, List <GameObject> >();
            if (modSettingsPanelCloner == null)
            {
                Load();
            }
            if (modSettingsPanel == null)
            {
                modSettingsPanel = GameObject.Instantiate(modSettingsPanelCloner);
                modSettingsPanel.transform.SetParent(FejdStartup.instance.m_mainMenu.transform, false);
                modSettingsPanel.transform.localPosition = Vector3.zero;
                applyButton = GameObjectAssistant.GetChildComponentByName <Button>("Apply", modSettingsPanel);
                dropper     = modSettingsPanel.GetComponentInChildren <Dropdown>();
                okButton    = GameObjectAssistant.GetChildComponentByName <Button>("OK", modSettingsPanel);
                applyButton.onClick.AddListener(delegate {
                    int dropdownval = dropper.value;
                    dropper.value   = 0;
                    Apply();
                    Show();
                    dropper.value = dropdownval;
                });
                okButton.onClick.AddListener(delegate {
                    Apply();
                    modSettingsPanel.SetActive(false);
                    SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
                });
                applyButton.gameObject.SetActive(false);
            }
            settingsContentPanel = GameObjectAssistant.GetChildComponentByName <Transform>("SettingsContent", modSettingsPanel).gameObject;
            settingsContentPanel.transform.parent.parent.gameObject.GetComponentInChildren <Scrollbar>().direction = Scrollbar.Direction.BottomToTop;
            dropper.options.Clear();
            FileIniDataParser parser     = new FileIniDataParser();
            IniData           configdata = parser.ReadFile(ConfigurationExtra.ConfigIniPath);

            foreach (var prop in typeof(Configuration).GetProperties())
            {
                string keyName = prop.Name;
                if (keyName == "Current" || keyName == "Settings" || keyName == "Time" || keyName == "Deconstruct")
                {
                    continue;
                }
                else
                {
                    settingFamillySettings.Add(keyName, new List <GameObject>());
                    var        settingFamillyProp = Configuration.Current.GetType().GetProperty(prop.Name).GetValue(Configuration.Current, null);
                    GameObject enableToggleThis   = CreateEnableToggle(keyName,
                                                                       settingFamillyProp.GetType().GetField("IsEnabled").GetValue(settingFamillyProp).ToString(),
                                                                       settingsContentPanel.transform,
                                                                       string.Join("\n", configdata[keyName].GetKeyData("enabled").Comments));
                    settingFamillySettings[keyName].Add(enableToggleThis);
                    var praeteriCommentarium = "";
                    foreach (var setting in prop.PropertyType.GetProperties())
                    {
                        if (setting.Name == "NeedsServerSync")
                        {
                            continue;
                        }
                        var keyDatumCommentate = configdata[keyName].GetKeyData(setting.Name);
                        var commentarium       = "";
                        if (keyDatumCommentate != null)
                        {
                            commentarium         = string.Join("\n", keyDatumCommentate.Comments);
                            praeteriCommentarium = commentarium;
                        }
                        else
                        {
                            commentarium = praeteriCommentarium;
                        }
                        if (settingFamillyProp.GetType().GetProperty(setting.Name).PropertyType == typeof(bool))
                        {
                            settingFamillySettings[keyName].Add(CreateBoolSettingEntry(setting.Name,
                                                                                       settingFamillyProp.GetType().GetProperty(setting.Name).GetValue(settingFamillyProp, null).ToString(),
                                                                                       settingsContentPanel.transform, commentarium));
                        }
                        else if (settingFamillyProp.GetType().GetProperty(setting.Name).PropertyType == typeof(KeyCode))
                        {
                            settingFamillySettings[keyName].Add(CreateKeyCodeSettingEntry(setting.Name,
                                                                                          settingFamillyProp.GetType().GetProperty(setting.Name).GetValue(settingFamillyProp, null).ToString(),
                                                                                          settingsContentPanel.transform, commentarium));
                        }
                        else
                        {
                            settingFamillySettings[keyName].Add(CreateTextSettingEntry(setting.Name,
                                                                                       settingFamillyProp.GetType().GetProperty(setting.Name).GetValue(settingFamillyProp, null).ToString(),
                                                                                       settingsContentPanel.transform, commentarium));
                        }
                    }
                    dropper.options.Add(new Dropdown.OptionData(keyName));
                }
            }
            availableSettings = dropper.options.Select(option => option.text).ToList();
            dropper.onValueChanged.AddListener(delegate {
                foreach (Transform ting in settingsContentPanel.transform)
                {
                    ting.gameObject.SetActive(false);
                }
                foreach (GameObject newTing in settingFamillySettings[availableSettings[dropper.value]])
                {
                    newTing.SetActive(true);
                }
            });
            dropper.value = availableSettings.IndexOf("ValheimPlus");
            modSettingsPanel.SetActive(true);
        }
Beispiel #27
0
        public static void Load(string path)
        {
            if (!IsFileUsable(path))
            {
                Extensions.Error("[Config][Load][Error] Config File is not usable", 0, false);
                return;
            }

            var configParser = new FileIniDataParser();
            var configData   = configParser.ReadFile(path);

            try
            {
                Settings.Radar.Enabled = bool.Parse(configData["Radar"]["Enabled"]);

                Settings.Bunnyhop.Enabled = bool.Parse(configData["Bunnyhop"]["Enabled"]);
                Settings.Bunnyhop.Key     = int.Parse(configData["Bunnyhop"]["Key"]);

                Settings.Trigger.Enabled = bool.Parse(configData["Trigger"]["Enabled"]);
                Settings.Trigger.Key     = int.Parse(configData["Trigger"]["Key"]);
                Settings.Trigger.Delay   = int.Parse(configData["Trigger"]["Delay"]);

                Settings.Chams.Enabled = bool.Parse(configData["Chams"]["Enabled"]);

                Settings.Chams.Allies         = bool.Parse(configData["Glow"]["Allies"]);
                Settings.Chams.Allies_Color_R = float.Parse(configData["Chams"]["Allies_Color_R"]);
                Settings.Chams.Allies_Color_G = float.Parse(configData["Chams"]["Allies_Color_G"]);
                Settings.Chams.Allies_Color_B = float.Parse(configData["Chams"]["Allies_Color_B"]);
                Settings.Chams.Allies_Color_A = float.Parse(configData["Chams"]["Allies_Color_A"]);

                Settings.Chams.Enemies         = bool.Parse(configData["Glow"]["Enemies"]);
                Settings.Chams.Enemies_Color_R = float.Parse(configData["Chams"]["Enemies_Color_R"]);
                Settings.Chams.Enemies_Color_G = float.Parse(configData["Chams"]["Enemies_Color_G"]);
                Settings.Chams.Enemies_Color_B = float.Parse(configData["Chams"]["Enemies_Color_B"]);
                Settings.Chams.Enemies_Color_A = float.Parse(configData["Chams"]["Enemies_Color_A"]);

                Settings.Glow.Enabled         = bool.Parse(configData["Glow"]["Enabled"]);
                Settings.Glow.PlayerColorMode = int.Parse(configData["Glow"]["PlayerColorMode"]);
                Settings.Glow.FullBloom       = bool.Parse(configData["Glow"]["FullBloom"]);

                Settings.Glow.Allies         = bool.Parse(configData["Glow"]["Allies"]);
                Settings.Glow.Allies_Color_R = float.Parse(configData["Glow"]["Allies_Color_R"]);
                Settings.Glow.Allies_Color_G = float.Parse(configData["Glow"]["Allies_Color_G"]);
                Settings.Glow.Allies_Color_B = float.Parse(configData["Glow"]["Allies_Color_B"]);
                Settings.Glow.Allies_Color_A = float.Parse(configData["Glow"]["Allies_Color_A"]);

                Settings.Glow.Enemies         = bool.Parse(configData["Glow"]["Enemies"]);
                Settings.Glow.Enemies_Color_R = float.Parse(configData["Glow"]["Enemies_Color_R"]);
                Settings.Glow.Enemies_Color_G = float.Parse(configData["Glow"]["Enemies_Color_G"]);
                Settings.Glow.Enemies_Color_B = float.Parse(configData["Glow"]["Enemies_Color_B"]);
                Settings.Glow.Enemies_Color_A = float.Parse(configData["Glow"]["Enemies_Color_A"]);

                Settings.Glow.Snipers         = bool.Parse(configData["Glow"]["Snipers"]);
                Settings.Glow.Snipers_Color_R = float.Parse(configData["Glow"]["Snipers_Color_R"]);
                Settings.Glow.Snipers_Color_G = float.Parse(configData["Glow"]["Snipers_Color_G"]);
                Settings.Glow.Snipers_Color_B = float.Parse(configData["Glow"]["Snipers_Color_B"]);
                Settings.Glow.Snipers_Color_A = float.Parse(configData["Glow"]["Snipers_Color_A"]);

                Settings.Glow.Rifles         = bool.Parse(configData["Glow"]["Rifles"]);
                Settings.Glow.Rifles_Color_R = float.Parse(configData["Glow"]["Rifles_Color_R"]);
                Settings.Glow.Rifles_Color_G = float.Parse(configData["Glow"]["Rifles_Color_G"]);
                Settings.Glow.Rifles_Color_B = float.Parse(configData["Glow"]["Rifles_Color_B"]);
                Settings.Glow.Rifles_Color_A = float.Parse(configData["Glow"]["Rifles_Color_A"]);

                Settings.Glow.MachineGuns         = bool.Parse(configData["Glow"]["MachineGuns"]);
                Settings.Glow.MachineGuns_Color_R = float.Parse(configData["Glow"]["MachineGuns_Color_R"]);
                Settings.Glow.MachineGuns_Color_G = float.Parse(configData["Glow"]["MachineGuns_Color_G"]);
                Settings.Glow.MachineGuns_Color_B = float.Parse(configData["Glow"]["MachineGuns_Color_B"]);
                Settings.Glow.MachineGuns_Color_A = float.Parse(configData["Glow"]["MachineGuns_Color_A"]);

                Settings.Glow.MPs         = bool.Parse(configData["Glow"]["MPs"]);
                Settings.Glow.MPs_Color_R = float.Parse(configData["Glow"]["MPs_Color_R"]);
                Settings.Glow.MPs_Color_G = float.Parse(configData["Glow"]["MPs_Color_G"]);
                Settings.Glow.MPs_Color_B = float.Parse(configData["Glow"]["MPs_Color_B"]);
                Settings.Glow.MPs_Color_A = float.Parse(configData["Glow"]["MPs_Color_A"]);

                Settings.Glow.Pistols         = bool.Parse(configData["Glow"]["Pistols"]);
                Settings.Glow.Pistols_Color_R = float.Parse(configData["Glow"]["Pistols_Color_R"]);
                Settings.Glow.Pistols_Color_G = float.Parse(configData["Glow"]["Pistols_Color_G"]);
                Settings.Glow.Pistols_Color_B = float.Parse(configData["Glow"]["Pistols_Color_B"]);
                Settings.Glow.Pistols_Color_A = float.Parse(configData["Glow"]["Pistols_Color_A"]);

                Settings.Glow.Shotguns         = bool.Parse(configData["Glow"]["Shotguns"]);
                Settings.Glow.Shotguns_Color_R = float.Parse(configData["Glow"]["Shotguns_Color_R"]);
                Settings.Glow.Shotguns_Color_G = float.Parse(configData["Glow"]["Shotguns_Color_G"]);
                Settings.Glow.Shotguns_Color_B = float.Parse(configData["Glow"]["Shotguns_Color_B"]);
                Settings.Glow.Shotguns_Color_A = float.Parse(configData["Glow"]["Shotguns_Color_A"]);

                Settings.Glow.C4         = bool.Parse(configData["Glow"]["C4"]);
                Settings.Glow.C4_Color_R = float.Parse(configData["Glow"]["C4_Color_R"]);
                Settings.Glow.C4_Color_G = float.Parse(configData["Glow"]["C4_Color_G"]);
                Settings.Glow.C4_Color_B = float.Parse(configData["Glow"]["C4_Color_B"]);
                Settings.Glow.C4_Color_A = float.Parse(configData["Glow"]["C4_Color_A"]);

                Settings.Glow.Grenades         = bool.Parse(configData["Glow"]["Grenades"]);
                Settings.Glow.Grenades_Color_R = float.Parse(configData["Glow"]["Grenades_Color_R"]);
                Settings.Glow.Grenades_Color_G = float.Parse(configData["Glow"]["Grenades_Color_G"]);
                Settings.Glow.Grenades_Color_B = float.Parse(configData["Glow"]["Grenades_Color_B"]);
                Settings.Glow.Grenades_Color_A = float.Parse(configData["Glow"]["Grenades_Color_A"]);

                Settings.Aimbot.Enabled                     = bool.Parse(configData["Aimbot"]["Enabled"]);
                Settings.Aimbot.Fov                         = float.Parse(configData["Aimbot"]["Fov"]);
                Settings.Aimbot.Bone                        = int.Parse(configData["Aimbot"]["Bone"]);
                Settings.Aimbot.Smooth                      = float.Parse(configData["Aimbot"]["Smooth"]);
                Settings.Aimbot.RecoilControl               = bool.Parse(configData["Aimbot"]["RecoilControl"]);
                Settings.Aimbot.YawRecoilReductionFactory   = float.Parse(configData["Aimbot"]["YawRecoilReductionFactory"]);
                Settings.Aimbot.PitchRecoilReductionFactory = float.Parse(configData["Aimbot"]["PitchRecoilReductionFactory"]);
                Settings.Aimbot.Curve                       = bool.Parse(configData["Aimbot"]["Curve"]);
                Settings.Aimbot.CurveX                      = float.Parse(configData["Aimbot"]["CurveX"]);
                Settings.Aimbot.CurveY                      = float.Parse(configData["Aimbot"]["CurveY"]);

                Settings.FOVChanger.Enabled = bool.Parse(configData["FOVChanger"]["Enabled"]);
                Settings.FOVChanger.Fov     = int.Parse(configData["FOVChanger"]["Fov"]);

                Settings.FOVChanger.ViewModelFov.Enabled = bool.Parse(configData["ViewModelFov"]["Enabled"]);
                Settings.FOVChanger.ViewModelFov.Fov     = float.Parse(configData["ViewModelFov"]["Fov"]);

                Settings.FOVChanger.ViewModelFov.Enabled =
                    Settings.StandaloneRCS.Enabled       = bool.Parse(configData["StandaloneRCS"]["Enabled"]);
                Settings.AutoPistol.Enabled = bool.Parse(configData["AutoPistol"]["Enabled"]);
                Settings.No_Flash.Enabled   = bool.Parse(configData["No_Flash"]["Enabled"]);
            }
            catch
            {
                Extensions.Error("[Config][Error] Could not load Config, try to delete your old one", 0, false);
            }

            Extensions.Information("[Config][Load] Loaded", true);
        }
Beispiel #28
0
        static int Main(string[] args)
        {
            var parser = new FileIniDataParser();

            IniData data;

            var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            try
            {
                data = parser.ReadFile(Path.Combine(path, "zvt.ini"));

                portName = data["settings"]["port"];

                stopbits = data["settings"]["stopbits"];

                verbose = bool.Parse(data["settings"]["verbose"]);

                timeout = int.Parse(data["settings"]["timeout"]) * 1000;

                logs = data["settings"]["logs"];
            }
            catch
            {
                Console.WriteLine("ERROR: Unable to parse configuration file 'zvt.ini'");

                return(-1);
            }

            int exitCode = 2;

            var command = args.Length == 0 ? null : args[0].ToLower();

            if (command != "-pay" && command != "-endofday")
            {
                Console.WriteLine("Usage: zvt.exe -pay amount");
                Console.WriteLine("Usage: zvt.exe -endofday");

                return(1);
            }

            SerialPort s = null;

            try
            {
                StopBits sb;

                switch (stopbits.Trim())
                {
                case "0": sb = StopBits.None; break;

                case "1": sb = StopBits.One; break;

                case "1.5": sb = StopBits.OnePointFive; break;

                case "2": sb = StopBits.Two; break;

                default: throw new ArgumentOutOfRangeException("stopbits");
                }

                s = new SerialPort(portName, 9600, Parity.None, 8, sb)
                {
                    ReceivedBytesThreshold = 1,
                    ReadTimeout            = timeout
                };

                s.Open();

                int reg      = SendRawData(s, new byte[] { 0x06, 0x00, 0x00 });
                var reg_recv = RecvRawData(s);

                /*var r = RecvRawData(s);
                 * SendRawData(s, new byte[] { 0x80, 0x00, 0x00 });*/

                /*var x = SendRawData(s, new byte[] { 0x06, 0xE0, 0x02, 0xF0, 0x00 });
                 * var y = RecvRawData(s);*/

                /*var x = SendRawData(s, new byte[] { 0x06, 0xB0, 0x00 });
                 * var y = RecvRawData(s);*/

                switch (command)
                {
                case "-pay":
                {
                    Registration(s);

                    var paymentAmount = decimal.Parse(args[1], System.Globalization.CultureInfo.InvariantCulture);

                    var cashbackAmount = 0.0m;

                    if (args.Length > 2)
                    {
                        var secondCommand = args[2].ToLower();

                        if (secondCommand == "-cashback")
                        {
                            cashbackAmount = decimal.Parse(args[3], System.Globalization.CultureInfo.InvariantCulture);
                        }
                    }

                    if (Pay(s, paymentAmount, cashbackAmount) == true)
                    {
                        exitCode = 0;
                    }
                    break;
                }

                case "-endofday":
                    Registration(s);

                    if (EndOfDay(s) == true)
                    {
                        exitCode = 0;
                    }

                    //LogOff(s);
                    break;
                }
            }
            catch (Exception e)
            {
                Debug(e.Message + "\r\n" + e.StackTrace);

                Console.WriteLine("" + e.Message);
            }
            finally
            {
                if (s != null)
                {
                    s.Close();
                }
            }

            Console.WriteLine("Exit code = " + exitCode);

            Debug("Exit code = " + exitCode);

            File.WriteAllText(Path.Combine(path, "result.txt"), exitCode.ToString());

            return(exitCode);
        }
Beispiel #29
0
        /// <summary>
        /// Initializes the config by checking for bad values or files.
        /// Run once when the launcher starts, then avoid unless absolutely neccesary.
        /// </summary>
        public void Initialize()
        {
            //Since Initialize will write to the config, we'll create the parser here and load the file later
            FileIniDataParser Parser = new FileIniDataParser();

            string configDir  = GetConfigDir();
            string configPath = GetConfigPath();

            //Major release 0.1.0, linux support
            Version defaultLauncherVersion = new Version("0.1.0");

            //Check for pre-unix config. If it exists, fix the values and copy it.
            UpdateOldConfig();

            //Check for old cookie file. If it exists, rename it.
            ReplaceOldUpdateCookie();

            //should be safe to lock the config now for initializing it
            lock (ReadLock)
            {
                if (!Directory.Exists(configDir))
                {
                    Directory.CreateDirectory(configDir);
                }
                if (!File.Exists(configPath))
                {
                    //here we create a new empty file
                    FileStream configStream = File.Create(configPath);
                    configStream.Close();

                    //read the file as an INI file
                    try
                    {
                        IniData data = Parser.ReadFile(GetConfigPath());

                        //generate a new GUID for this install instance of the launcher
                        string GeneratedGUID = Guid.NewGuid().ToString();

                        data.Sections.AddSection("Local");
                        data.Sections.AddSection("Remote");
                        data.Sections.AddSection("Launchpad");

                        data["Local"].AddKey("LauncherVersion", defaultLauncherVersion.ToString());
                        data["Local"].AddKey("GameName", "LaunchpadExample");

                        //set the default system target to what the launcher is running on. Developers will need
                        //to alter this in the config, based on where they're deploying to.
                        data["Local"].AddKey("SystemTarget", GetCurrentPlatform().ToString());
                        data["Local"].AddKey("GUID", GeneratedGUID);

                        data["Remote"].AddKey("FTPUsername", "anonymous");
                        data["Remote"].AddKey("FTPPassword", "anonymous");
                        data["Remote"].AddKey("FTPUrl", "ftp://directorate.asuscomm.com");

                        data["Launchpad"].AddKey("bOfficialUpdates", "true");

                        WriteConfig(Parser, data);
                    }
                    catch (IOException ioex)
                    {
                        Console.WriteLine("IOException in ConfigHandler.Initialize(): " + ioex.Message);
                    }
                }
                else
                {
                    IniData data = Parser.ReadFile(GetConfigPath());

                    data["Local"]["LauncherVersion"] = defaultLauncherVersion.ToString();
                    if (!data ["Local"].ContainsKey("GUID"))
                    {
                        string GeneratedGUID = Guid.NewGuid().ToString();
                        data ["Local"].AddKey("GUID", GeneratedGUID);
                    }

                    WriteConfig(Parser, data);
                }
            }
        }
Beispiel #30
0
        public static void SaveConfig()
        {
            var path = Path.Combine(Directory.GetCurrentDirectory(), "Settings.ini");

            if (!File.Exists(path))
            {
                using (var sw = File.AppendText(path))
                {
                    {
                        sw.WriteLine("");
                    }
                }
            }

            var parser = new FileIniDataParser();
            var data   = parser.ReadFile("Settings.ini");

            //Keep ^^

            data["GLOW TEAM"]["Enabled"] = Settings.Glow.GlowTeam.ToString();
            data["GLOW TEAM"]["Chams"]   = Settings.Glow.ChamsTeam.ToString();
            data["GLOW TEAM"]["Red"]     = Settings.Glow.TeamRed.ToString();
            data["GLOW TEAM"]["Green"]   = Settings.Glow.TeamGreen.ToString();
            data["GLOW TEAM"]["Blue"]    = Settings.Glow.TeamBlue.ToString();

            data["GLOW ENEMY"]["Enabled"] = Settings.Glow.GlowEnemy.ToString();
            data["GLOW ENEMY"]["Chams"]   = Settings.Glow.ChamsEnemy.ToString();
            data["GLOW ENEMY"]["Red"]     = Settings.Glow.EnemyRed.ToString();
            data["GLOW ENEMY"]["Green"]   = Settings.Glow.EnemyGreen.ToString();
            data["GLOW ENEMY"]["Blue"]    = Settings.Glow.EnemyBlue.ToString();

            data["FOV"]["Enabled"] = Settings.Fovchanger.Enabled.ToString();
            data["FOV"]["Fov"]     = Settings.Fovchanger.Fov.ToString();

            data["BUNNY"]["Enabled"] = Settings.Bhop.Enabled.ToString();

            data["NO FLASH"]["Enabled"]      = Settings.Noflash.Enabled.ToString();
            data["NO FLASH"]["Flash Amount"] = Settings.Noflash.Flash.ToString();

            data["NOHANDS"]["Enabled"] = Settings.Noflash.Enabled.ToString();

            data["HITSOUND"]["Enabled"] = Settings.Hitsound.Enabled.ToString();
            data["HITSOUND"]["Mode"]    = Settings.Hitsound.Mode.ToString();

            data["TRIGGER"]["Enabled"] = Settings.Trigger.Enabled.ToString();

            data["OVERLAY"]["Enabled"]   = Settings.Overlay.Enabled.ToString();
            data["OVERLAY"]["Crosshair"] = Settings.Overlay.Crosshair.ToString();

            data["SKINCHANGER"]["Enabled"]       = Settings.Skinchanger.Enabled.ToString();
            data["SKINCHANGER"]["DEAGLESkin"]    = Settings.Skinchanger.WEAPON_DEAGLE.ToString();
            data["SKINCHANGER"]["ELITESkin"]     = Settings.Skinchanger.WEAPON_ELITE.ToString();
            data["SKINCHANGER"]["FIVESEVENSkin"] = Settings.Skinchanger.WEAPON_FIVESEVEN.ToString();
            data["SKINCHANGER"]["GLOCKSkin"]     = Settings.Skinchanger.WEAPON_GLOCK.ToString();
            data["SKINCHANGER"]["AK47Skin"]      = Settings.Skinchanger.WEAPON_AK47.ToString();
            data["SKINCHANGER"]["AUGSkin"]       = Settings.Skinchanger.WEAPON_AUG.ToString();
            data["SKINCHANGER"]["AWPSkin"]       = Settings.Skinchanger.WEAPON_AWP.ToString();
            data["SKINCHANGER"]["FAMASSkin"]     = Settings.Skinchanger.WEAPON_FAMAS.ToString();
            data["SKINCHANGER"]["G3SG1Skin"]     = Settings.Skinchanger.WEAPON_G3SG1.ToString();
            data["SKINCHANGER"]["GALILSkin"]     = Settings.Skinchanger.WEAPON_GALILAR.ToString();
            data["SKINCHANGER"]["M249Skin"]      = Settings.Skinchanger.WEAPON_M249.ToString();
            data["SKINCHANGER"]["M4A1Skin"]      = Settings.Skinchanger.WEAPON_M4A1.ToString();
            data["SKINCHANGER"]["MAC10Skin"]     = Settings.Skinchanger.WEAPON_MAC10.ToString();

            //Get value ^^

            parser.WriteFile("Settings.ini", data);
            //Save config ^^
        }