当前位置: 首页>>代码示例>>C#>>正文


C# Config.Load方法代码示例

本文整理汇总了C#中Config.Load方法的典型用法代码示例。如果您正苦于以下问题:C# Config.Load方法的具体用法?C# Config.Load怎么用?C# Config.Load使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Config的用法示例。


在下文中一共展示了Config.Load方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetConfig

        /// <summary>
        /// Loads an instance of Config from the Rules.config xml file
        /// </summary>
        /// <returns>The config.</returns>
        public static Config GetConfig()
        {
            if (null == config) {
                config = new Config ();
                config.Load ();
            }

            return config;
        }
开发者ID:Trollmor,项目名称:Telligent-Community-Samples,代码行数:13,代码来源:Core.cs

示例2: Initialize

        public virtual void Initialize()
        {
            MessageDispatcher.RegisterAssembly(Context.PluginAssembly);

            if (UseConfig)
            {
                Config = new Config(ConfigPath);
                Config.Load();
                Config.BindAssembly(Context.PluginAssembly);
            }
        }
开发者ID:Geraff,项目名称:BehaviorIsManaged,代码行数:11,代码来源:PluginBase.cs

示例3: Main

        static void Main(string[] args)
        {
            Config cfg = new Config("corr.cfg");
             cfg.Load();

             FilePath processor_path = cfg.Root["processor.path"].AsFilePath();
             FilePath output_path = cfg.Root["output.path"].AsFilePath();
             FilePath hdfs_path = cfg.Root["hdf.path"].AsFilePath();

             System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(hdfs_path.Path);
             System.IO.FileInfo[] aryFi = di.GetFiles("*.hdf5", System.IO.SearchOption.TopDirectoryOnly);

             Dictionary<string, string> info = new Dictionary<string,string>();

             ExternalApp app = new ExternalApp();
             app.Arguments = "--cfg task.cfg";
             app.CheckSuccessMethod = CheckSuccessMethod.DONOTCHECK;
             app.Executable = processor_path.Path + "MohidHDF5Processor.exe";
             app.UseShell = false;
             app.Verbose = false;
             app.Wait = true;
             app.WorkingDirectory = processor_path.Path;

             int count = 1;

             foreach (System.IO.FileInfo fi in aryFi)
             {
            Console.Write("{1}: Processing {0}...", fi.Name, count);

            info["<<input>>"] = fi.FullName;
            info["<<output>>"] = output_path.Path + fi.Name;

            TextFile.Replace(processor_path.Path + "task.template", processor_path.Path + "task.cfg", ref info);
            if (!app.Run())
            {
               Console.WriteLine("Failure when trying to correct file {0}", fi.Name);
               Console.WriteLine("[FAIL]");
            }
            else
               Console.WriteLine("[ OK ]");

            count++;
             }
        }
开发者ID:JauchOnGitHub,项目名称:csharptoolbox,代码行数:44,代码来源:Program.cs

示例4: CouponCodeGoCommand

        protected void CouponCodeGoCommand(object sender, CommandEventArgs e)
        {
            string couponCode = CouponCodeEdit.Text;
            using (Database db = new MySqlDatabase())
            {
                ClientInfo ci = db.GetClientInfo(Util.UserId);

                if (db.CheckActivationCode(couponCode))
                {
                    // Code is ok, raise the number of credits for this user
                    db.MarkActivationCode(couponCode, Util.UserId);

                    Config cfg = new Config();
                    cfg.Load(Server.MapPath("~/Config/trackprotect.config"));

                    long prodid = 0;
                    if (cfg["activationcode.productid"] != null)
                        prodid = Convert.ToInt64(cfg["activationcode.productid"]);
                    // Get the credits from the database
                    ProductInfo pi = db.GetProductById(prodid);

                    if (pi != null && pi.ProductId > 0)
                    {
                        // How many credits to issue
                        string transactionIdCoupon = string.Format("COUPON {0}", couponCode);
                        long orderId = db.CreateTransaction(Util.UserId, 0m, prodid, pi.Description);
                        db.UpdateTransaction(orderId.ToString(), "OK", "OK", "Payment Completed", "COUPON", couponCode, couponCode, transactionIdCoupon, "COUPON", 0m, pi, "EUR", Util.GetCountryIso2(ci.Country));
                        db.UpdateUserCredits(Util.UserId, prodid, pi.Credits);
                        db.AddCreditHistory(Util.UserId, prodid, pi.Credits, orderId);
                        Response.Redirect(string.Format("~/Member/CouponSuccess.aspx?cradd={0}", pi.Credits), false);
                    }
                }
                else
                {
                    Response.Redirect(string.Format("~/Member/CouponFailure.aspx?couponcode={0}", couponCode), false);
                }
            }
        }
开发者ID:nageshverma2003,项目名称:TrackProtectSource,代码行数:38,代码来源:CouponCode.aspx.cs

示例5: LoadConfig

        public bool LoadConfig(FileName config_file)
        {
            try
             {
            config_loaded = false;

            config = new Config(config_file.FullPath);
            config.Load();

            config_root = config.Root;

            //Save here the data that will be used across the class
            data.Pin = config_root["pin_code", ""].AsString();
            data.SMSCenter = config_root["sms_center"].AsString();
            data.TimeOut = config_root["timeout", 10].AsInt() * 1000;
            data.WaitTime = config_root["wait", 10].AsInt() * 1000;
            data.Tries = config_root["tentatives", 2].AsInt();

            data.Port = SMSEngine.GetNewPort();
            ConfigNode port = config_root.ChildNodes.Find(delegate(ConfigNode node) { return node.Name == "port"; });
            if (port == null)
               throw new Exception("Block \"port\" not found");

            data.Port.WriteTimeout = port["write_timeout", 10].AsInt() * 1000;
            data.Port.ReadTimeout = port["read_timeout", 10].AsInt() * 1000;
            data.Port.PortName = port["port_name"].AsString();
            data.Port.BaudRate = port["baudrate", 9600].AsInt();
            data.Port.DataBits = port["databits", 8].AsInt();
            data.Port.Parity = (Parity) Enum.Parse(typeof(Parity), port["parity", "None"].AsString(), true);
            data.Port.StopBits = (StopBits)Enum.Parse(typeof(StopBits), port["stopbits", "One"].AsString(), true);
            data.Port.Handshake = (Handshake)Enum.Parse(typeof(Handshake), port["handshake", "RequestToSend"].AsString(), true);
            data.Port.DtrEnable = port["dtr_enabled", true].AsBool();
            data.Port.RtsEnable = port["rts_enabled", true].AsBool();
            data.Port.NewLine = Environment.NewLine;

            ConfigNode db = config_root.ChildNodes.Find(delegate(ConfigNode node) { return node.Name == "database"; });
            if (db == null)
               throw new Exception("Block \"database\" not found");

            if (db.NodeData.ContainsKey("connection_string"))
            {
               data.DBName = "";
               data.DBPath = "";
               data.ConnectionString = db["connection_string"].AsString();
            }
            else
            {
               data.DBName = db["name"].AsString();
               data.DBPath = db["path"].AsFilePath().Path;
               data.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
                                       data.DBPath + data.DBName +
                                       ";Persist Security Info=False";
            }

            config_loaded = true;
            return true;
             }
             catch (Exception ex)
             {
            if (Debug)
               Console.WriteLine("Engine.LoadConfig Exception: {0}", ex.Message);

            if (config_root != null)
               config_root = null;

            return false;
             }
        }
开发者ID:JauchOnGitHub,项目名称:csharptoolbox,代码行数:68,代码来源:Engine.cs

示例6: Main

        static void Main(string[] args)
        {
            CmdArgs cmdArgs = new CmdArgs(args);
             Dictionary<String, String> replace_list = new Dictionary<string, string>();
             DateTime end, actual_start, actual_end;

             if (!cmdArgs.HasParameter("cfg"))
             {
            Console.WriteLine("Configuration file was not provided. Use --cfg [file] to provide one.");
            Console.WriteLine("Operation Aborted.");
            return;
             }

             Config cfg = new Config(cmdArgs.Parameter("cfg"));
             if (!cfg.Load())
             {
            Console.WriteLine("Was not possible to load '" + cmdArgs.Parameter("cfg") + "'.");
            if (!string.IsNullOrWhiteSpace(cfg.ExceptionMessage))
            {
               Console.WriteLine("The message returned was:");
               Console.WriteLine(cfg.ExceptionMessage);
               Console.WriteLine("Operation Aborted.");
               return;
            }
             }

             ConfigNode root = cfg.Root;

             int id = root["start.id", 1].AsInt();
             string template = root["template", "FillMatrix.template"].AsString();
             string dateFormat = root["dateFormat.format", "yyyy-MM-dd HH:mm:ss"].AsString();
             actual_start = root["start"].AsDateTime(dateFormat);
             end = root["end"].AsDateTime(dateFormat);
             int interval;
             if (root.NodeData.ContainsKey("interval.days"))
             {
            interval = root["interval.days"].AsInt();
            actual_end = actual_start.AddDays(interval);
             }
             else
             {
            interval = 10;
            actual_end = end;
             }
             string interpolation = root["interpolation.method", "2"].AsString();

             replace_list.Add("<<start>>", actual_start.ToString("yyyy M d H m s"));
             replace_list.Add("<<end>>", actual_end.ToString("yyyy M d H m s"));
             replace_list.Add("<<id>>", id.ToString());
             replace_list.Add("<<interpolation>>", interpolation);

             ExternalApp fillmatrix = new ExternalApp();

             while (actual_end <= end)
             {

            TextFile.Replace(template, "FillMatrix.dat", ref replace_list);

            fillmatrix.CheckSuccessMethod = CheckSuccessMethod.DONOTCHECK;
            fillmatrix.Wait = true;
            fillmatrix.WorkingDirectory = @".\";
            fillmatrix.Executable = @".\fillmatrix.exe";

            try
            {
               fillmatrix.Run();
            }
            catch (Exception ex)
            {
               Console.WriteLine("Erro detectado. Mensagem de erro:");
               Console.WriteLine(ex.Message);
               Console.WriteLine("ID    : {0}", id.ToString());
               Console.WriteLine("Start : {0}", actual_start.ToString());
               Console.WriteLine("End   : {0}", actual_end.ToString());
               Console.WriteLine("");
            }

            id++;
            actual_start = actual_end;
            actual_end = actual_start.AddDays(14);

            if (actual_start < end && actual_end > end)
               actual_end = end;

            replace_list["<<start>>"] = actual_start.ToString("yyyy M d H m s");
            replace_list["<<end>>"] = actual_end.ToString("yyyy M d H m s");
            replace_list["<<id>>"] = id.ToString();
             }
        }
开发者ID:JauchOnGitHub,项目名称:csharptoolbox,代码行数:89,代码来源:InterpolateRain.cs

示例7: SendQuotation

        protected void SendQuotation(object sender, CommandEventArgs e)
        {
            long productId = 0;
            int credits = 0;
            if (QuotationAmount.Text.Length > 0)
            {
                int tmp = 0;
                if (int.TryParse(QuotationAmount.Text, out tmp))
                    credits = tmp;
            }

            if (Session["quotation.pid"] != null)
                productId = (long)Session["quotation.pid"];

            if (credits > 0)
            {
                // Send e-mail with quotation request
                Config cfg = new Config();
                cfg.Load(Server.MapPath("~/Config/trackprotect.config"));

                string emailTo = cfg["email.sales"];
                StringBuilder body = new StringBuilder();

                // Get user/client information
                using (Database db = new MySqlDatabase())
                {
                    long userId = Util.UserId;
                    UserInfo ui = db.GetUser(userId);
                    ClientInfo ci = db.GetClientInfo(userId);
                    body.Append("<html><head></head><body><p><div style=\"background-color:#E6E6E6;\"><table><tr><td>");
                    body.Append("<img src=\"" + ConfigurationManager.AppSettings["EmailHeaderLogo"] + "\" alt=\"logo\"/></td><td><span>");
                    body.Append("<a style=\"color:#E4510A; margin-left:450px;\" href=\"" + ConfigurationManager.AppSettings["EmailmailToLink"] + "\" >" + ConfigurationManager.AppSettings["EmailmailToLink"] + "</a>");
                    body.Append("<br><a style=\"color:#E4510A; margin-left:450px;\" href=\"" + ConfigurationManager.AppSettings["SiteNavigationLink"] + "\">" + ConfigurationManager.AppSettings["SiteNavigationLink"] + "</a>");
                    body.Append("</span></td></tr></table></div><br><br>");

                    body.Append(ci.GetFullName());
                    body.AppendFormat("heeft een offerte aangevraagd voor {0} credits.\r\n", QuotationAmount.Text);
                    body.AppendFormat("e-mail         : {0}\r\n", ui.Email);
                    body.AppendFormat("e-mail receipt : {0}\r\n", ci.EmailReceipt);
                    body.AppendFormat("user-id        : {0}\r\n", ui.UserId);
                    body.AppendFormat("client-id      : {0}\r\n", ci.ClientId);

                    body.Append("<br><br><img src=\"" + ConfigurationManager.AppSettings["EmailFooterLogo"] + "\" alt=\"logo\"/>");
                    body.Append("<a href=\"" + ConfigurationManager.AppSettings["EmailFBlink"] + "\"><img src=\"" + ConfigurationManager.AppSettings["EmailFBLogo"] + "\" alt=\"facebook\"></img></a>");
                    body.Append("<a href=\"" + ConfigurationManager.AppSettings["EmailTwitterLink"] + "\"><img src=\"" + ConfigurationManager.AppSettings["EmailTwitterLogo"] + "\" alt=\"twitter\"></img></a>");
                    body.Append("<a href=\"" + ConfigurationManager.AppSettings["EmailSoundCloudLink"] + "\"><img src=\"" + ConfigurationManager.AppSettings["EmailSoundCloudLogo"] + "\" alt=\"soundcloud\"></img></a>");
                    body.Append("<br><br>Trackprotect is “a RHOS Initiative” – Robin Hood of Sound – A Sound Revolution.<br>");

                    if (productId == 0)
                        productId = 4;

                    db.CreateQuotation(ui.UserId, credits, productId, string.Format("Quotation for {0} credits", QuotationAmount.Text));
                }

                Util.SendEmail(new string[] { emailTo }, "[email protected]", Resources.Resource.Quotation, body.ToString(), new string[] { }, 0);
                Response.Redirect("~/Member/QuotationSuccess.aspx", false);
            }
            else
            {
                ErrorMessage.Text = Resources.Resource.InvalidAmount;
            }
        }
开发者ID:nageshverma2003,项目名称:TrackProtectSource,代码行数:62,代码来源:Quotation.aspx.cs

示例8: LoadConfig

 public bool LoadConfig()
 {
     cfg = new Config();
      cfg.ConfigFile.FullName = "test.cfg";
      return cfg.Load();
 }
开发者ID:JauchOnGitHub,项目名称:csharptoolbox,代码行数:6,代码来源:ScriptTest.cs

示例9: TestPotatoConfigWritten

        public void TestPotatoConfigWritten() {
            var instance = (PotatoController)new PotatoController() {
                Shared = {
                    Variables = new VariableController().Execute() as VariableController,
                    Security = new SecurityController().Execute() as SecurityController,
                    Events = new EventsController().Execute() as EventsController,
                    Languages = new LanguageController().Execute() as LanguageController
                }
            }.Execute();

            instance.Shared.Variables.Tunnel(CommandBuilder.VariablesSet(CommonVariableNames.PotatoConfigPassword, "PotatoConfigurationPassword").SetOrigin(CommandOrigin.Local));

            instance.Connections.Add(new ConnectionController() {
                ConnectionModel = new ConnectionModel() {
                    ProtocolType = new ProtocolType() {
                        Name = "Mock Protocol",
                        Provider = "Myrcon",
                        Type = "MockProtocol"
                    },
                    Hostname = "1.1.1.1",
                    Port = 27516,
                    Arguments = "",
                    Password = "password"
                }
            });

            instance.WriteConfig();

            var loadConfig = new Config();
            loadConfig.Load(ConfigFileInfo);
            
            var configCommand = loadConfig.RootOf<PotatoController>().Children<JObject>().Select(item => item.ToObject<IConfigCommand>(JsonSerialization.Minimal)).ToList().Last();

            configCommand.Decrypt("PotatoConfigurationPassword");

            Assert.AreEqual("PotatoAddConnection", configCommand.Command.Name);
            Assert.AreEqual("Myrcon", configCommand.Command.Parameters[0].First<String>());
            Assert.AreEqual("MockProtocol", configCommand.Command.Parameters[1].First<String>());
            Assert.AreEqual("1.1.1.1", configCommand.Command.Parameters[2].First<String>());
            Assert.AreEqual("27516", configCommand.Command.Parameters[3].First<String>());
            Assert.AreEqual("password", configCommand.Command.Parameters[4].First<String>());
            Assert.AreEqual("", configCommand.Command.Parameters[5].First<String>());

            instance.Dispose();
        }
开发者ID:EBassie,项目名称:Potato,代码行数:45,代码来源:TestPotato.cs

示例10: Initialize

        public static void Initialize()
        {
            if (Initialized)
                return;

            UIManager.Instance.SetBusy(true);
            try
            {

                if (!Debugger.IsAttached) // the debugger handle the unhandled exceptions
                    AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;

                AppDomain.CurrentDomain.ProcessExit += OnProcessExit;


                UIManager.Instance.BusyMessage = "Load config ...";
                Config = new Config(ConfigPath);

                foreach (Assembly assembly in m_hierarchy)
                {
                    Config.BindAssembly(assembly);
                    Config.RegisterAttributes(assembly);
                }

                Config.Load();

                logger.Info("{0} loaded", Path.GetFileName(Config.FilePath));


                UIManager.Instance.BusyMessage = "Loading D2O files ...";
                ObjectDataManager.Instance.AddReaders(Path.Combine(GetDofusPath(), DofusDataPath));
                I18NDataManager.Instance.DefaultLanguage = Languages.English;

                I18NDataManager.Instance.AddReaders(Path.Combine(GetDofusPath(), DofusI18NPath));
                IconsManager.Instance.Initialize(Path.Combine(GetDofusPath(), DofusItemIconPath));


                UIManager.Instance.BusyMessage = "Starting redis server ...";
                logger.Info("Starting redis server ...");
                RedisServerHost.Instance.ExecutablePath = RedisServerExe;
                RedisServerHost.Instance.StartOrFindProcess();

                UIManager.Instance.BusyMessage = string.Format("Loading {0}...", MapsManager.MapsDataFile);
                logger.Info("Loading {0}...", MapsManager.MapsDataFile);
                ProgressionCounter progression = MapsManager.Instance.Initialize(Path.Combine(GetDofusPath(), DofusMapsD2P));
                if (progression != null)
                    ExecuteProgress(progression);

                UIManager.Instance.BusyMessage = "Loading maps positions ...";
                logger.Info("Loading maps positions ...");
                progression = MapsPositionManager.Instance.Initialize();
                if (progression != null)
                    ExecuteProgress(progression);

                UIManager.Instance.BusyMessage = "Loading submaps ...";
                logger.Info("Loading submaps ...");
                progression = SubMapsManager.Instance.Initialize();
                if (progression != null)
                    ExecuteProgress(progression);


                MITM = new MITM.MITM(new MITMConfiguration
                    {
                        FakeAuthHost = BotAuthHost,
                        FakeAuthPort = BotAuthPort,
                        FakeWorldHost = BotWorldHost,
                        FakeWorldPort = BotWorldPort,
                        RealAuthHost = RealAuthHost,
                        RealAuthPort = RealAuthPort
                    });

                MessageDispatcher.DefineHierarchy(m_hierarchy);

                foreach (Assembly assembly in m_hierarchy)
                {
                    MessageDispatcher.RegisterSharedAssembly(assembly);
                }

                UIManager.Instance.BusyMessage = "Loading plugins ...";
                PluginManager.Instance.LoadAllPlugins();

                DispatcherTask = new DispatcherTask(new MessageDispatcher(), MITM);
                DispatcherTask.Start(); // we have to start it now to dispatch the initialization msg

                BotManager.Instance.Initialize();

                var msg = new HostInitializationMessage();
                DispatcherTask.Dispatcher.Enqueue(msg, MITM);

                msg.Wait();

            }
            finally
            {
                UIManager.Instance.SetBusy(false);
            }

            Initialized = true;
        }
开发者ID:Guiedo,项目名称:BehaviorIsManaged,代码行数:99,代码来源:Host.cs

示例11: FrmDBExportConfig_Load

        private void FrmDBExportConfig_Load(object sender, EventArgs e)
        {
            // локализация модуля
            string errMsg;
            if (!Localization.UseRussian)
            {
                if (Localization.LoadDictionaries(appDirs.LangDir, "ModDBExport", out errMsg))
                    Translator.TranslateForm(this, "Scada.Server.Modules.DBExport.FrmDBExportConfig");
                else
                    ScadaUiUtils.ShowError(errMsg);
            }

            // настройка элементов управления
            lblInstruction.Top = treeView.Top;

            // загрузка конфигурации
            config = new Config(appDirs.ConfigDir);
            if (File.Exists(config.FileName) && !config.Load(out errMsg))
                ScadaUiUtils.ShowError(errMsg);

            // создание копии конфигурации
            configCopy = config.Clone();

            // отображение конфигурации
            ConfigToControls();

            // снятие признака изменения конфигурации
            Modified = false;
        }
开发者ID:LoganDing,项目名称:scada,代码行数:29,代码来源:FrmDBExportConfig.cs

示例12: TestEnabledPluginSavedToConfig

        public void TestEnabledPluginSavedToConfig() {
            Guid connectionGuid = Guid.NewGuid();
            Guid onePluginGuid = Guid.NewGuid();
            Guid twoPluginGuid = Guid.NewGuid();

            ICorePluginController plugins = new CorePluginController() {
                Connection = new ConnectionController() {
                    ConnectionModel = new ConnectionModel() {
                        ConnectionGuid = connectionGuid
                    }
                },
                LoadedPlugins = new List<PluginModel>() {
                    new PluginModel() {
                        Name = "One",
                        IsEnabled = false,
                        PluginGuid = onePluginGuid
                    },
                    new PluginModel() {
                        Name = "Two",
                        IsEnabled = true,
                        PluginGuid = twoPluginGuid
                    }
                }
            };

            IConfig config = new Config().Create<CorePluginController>();

            plugins.WriteConfig(config);

            config.Save(this.ConfigFile);

            // Now load up the config and ensure it saved what we wanted it too.

            var loadConfig = new Config();
            loadConfig.Load(this.ConfigFile);

            var commands = loadConfig.RootOf<CorePluginController>().Children<JObject>().Select(item => item.ToObject<IConfigCommand>(JsonSerialization.Minimal)).ToList();

            Assert.AreEqual("PluginsEnable", commands[0].Command.Name);
            Assert.AreEqual(connectionGuid, commands[0].Command.Scope.ConnectionGuid);
            Assert.AreEqual(twoPluginGuid, commands[0].Command.Scope.PluginGuid);
        }
开发者ID:EBassie,项目名称:Potato,代码行数:42,代码来源:TestPluginConfig.cs

示例13: TestSecurityWriteConfig

        public void TestSecurityWriteConfig() {
            var security = new SecurityController();
            security.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.SecurityAddGroup,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    "GroupName"
                })
            });
            security.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.SecurityGroupSetPermission,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    "GroupName",
                    "CustomPermission",
                    22
                })
            });
            security.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.SecurityGroupSetPermission,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    "GroupName",
                    CommandType.VariablesSet,
                    77
                })
            });
            security.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.SecurityGroupSetPermission,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    "GroupName",
                    CommandType.VariablesSetA,
                    88
                })
            });
            security.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.SecurityGroupAddAccount,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    "GroupName",
                    "Phogue"
                })
            });
            security.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.SecurityAccountSetPassword,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    "Phogue",
                    "password"
                })
            });

            security.Tunnel(CommandBuilder.SecurityAccountAppendAccessToken("Phogue", Guid.Parse("f380eb1e-1438-48c0-8c3d-ad55f2d40538"), "Token Hash", DateTime.Parse("2024-04-14 20:51:00 PM")).SetOrigin(CommandOrigin.Local));

            security.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.SecurityAccountSetPreferredLanguageCode,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    "Phogue",
                    "de-DE"
                })
            });
            security.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.SecurityAccountAddPlayer,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    "Phogue",
                    CommonProtocolType.DiceBattlefield3,
                    "ABCDEF"
                })
            });

            // Save a config of the language controller
            var saveConfig = new Config();
            saveConfig.Create(typeof(SecurityController));
            security.WriteConfig(saveConfig);
            saveConfig.Save(ConfigFileInfo);

            // Load the config in a new config.
            var loadConfig = new Config();
            loadConfig.Load(ConfigFileInfo);

            var commands = loadConfig.RootOf<SecurityController>().Children<JObject>().Select(item => item.ToObject<IConfigCommand>(JsonSerialization.Minimal)).ToList();

            Assert.AreEqual("SecurityAddGroup", commands[0].Command.Name);
            Assert.AreEqual("Guest", commands[0].Command.Parameters[0].First<String>());

            Assert.AreEqual("SecurityAddGroup", commands[1].Command.Name);
            Assert.AreEqual("GroupName", commands[1].Command.Parameters[0].First<String>());

            Assert.AreEqual("SecurityGroupSetPermission", commands[2].Command.Name);
            Assert.AreEqual("GroupName", commands[2].Command.Parameters[0].First<String>());
            Assert.AreEqual(CommandType.VariablesSet.ToString(), commands[2].Command.Parameters[1].First<String>());
            Assert.AreEqual("77", commands[2].Command.Parameters[2].First<String>());

            Assert.AreEqual("SecurityGroupSetPermission", commands[3].Command.Name);
            Assert.AreEqual("GroupName", commands[3].Command.Parameters[0].First<String>());
            Assert.AreEqual(CommandType.VariablesSetA.ToString(), commands[3].Command.Parameters[1].First<String>());
            Assert.AreEqual("88", commands[3].Command.Parameters[2].First<String>());
//.........这里部分代码省略.........
开发者ID:EBassie,项目名称:Potato,代码行数:101,代码来源:TestSecurity.cs

示例14: TestSecurityLoadConfig

        public void TestSecurityLoadConfig() {
            var saveSecurity = new SecurityController();
            saveSecurity.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.SecurityAddGroup,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    "GroupName"
                })
            });
            saveSecurity.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.SecurityGroupSetPermission,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    "GroupName",
                    "CustomPermission",
                    22
                })
            });
            saveSecurity.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.SecurityGroupSetPermission,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    "GroupName",
                    CommandType.VariablesSet,
                    77
                })
            });
            saveSecurity.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.SecurityGroupSetPermission,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    "GroupName",
                    CommandType.VariablesSetA,
                    88
                })
            });
            saveSecurity.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.SecurityGroupAddAccount,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    "GroupName",
                    "Phogue"
                })
            });
            saveSecurity.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.SecurityAccountSetPassword,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    "Phogue",
                    "password"
                })
            });

            saveSecurity.Tunnel(CommandBuilder.SecurityAccountAppendAccessToken("Phogue", Guid.Parse("f380eb1e-1438-48c0-8c3d-ad55f2d40538"), "Token Hash", DateTime.Parse("2024-04-14 20:51:00 PM")).SetOrigin(CommandOrigin.Local));

            saveSecurity.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.SecurityAccountSetPreferredLanguageCode,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    "Phogue",
                    "de-DE"
                })
            });
            saveSecurity.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.SecurityAccountAddPlayer,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    "Phogue",
                    CommonProtocolType.DiceBattlefield3,
                    "ABCDEF"
                })
            });

            // Save a config of the security controller
            var saveConfig = new Config();
            saveConfig.Create(typeof(SecurityController));
            saveSecurity.WriteConfig(saveConfig);
            saveConfig.Save(ConfigFileInfo);

            // Load the config in a new config.
            var loadSecurity = (SecurityController)new SecurityController().Execute();
            var loadConfig = new Config();
            loadConfig.Load(ConfigFileInfo);
            loadSecurity.Execute(loadConfig);

            var lastGroup = loadSecurity.Groups.LastOrDefault(group => @group.Name == "GroupName") ?? new GroupModel();

            Assert.AreEqual("Guest", loadSecurity.Groups.First().Name);
            Assert.AreEqual("GroupName", loadSecurity.Groups.Last().Name);
            Assert.AreEqual(22, lastGroup.Permissions.First(permission => permission.Name == "CustomPermission").Authority);
            Assert.AreEqual(77, lastGroup.Permissions.First(permission => permission.Name == CommandType.VariablesSet.ToString()).Authority);
            Assert.AreEqual(88, lastGroup.Permissions.First(permission => permission.Name == CommandType.VariablesSetA.ToString()).Authority);
            Assert.AreEqual("Phogue", loadSecurity.Groups.SelectMany(group => group.Accounts).First().Username);
            Assert.AreEqual(Guid.Parse("f380eb1e-1438-48c0-8c3d-ad55f2d40538"), loadSecurity.Groups.SelectMany(group => group.Accounts).First().AccessTokens.First().Value.Id);
            Assert.AreEqual("Token Hash", loadSecurity.Groups.SelectMany(group => group.Accounts).First().AccessTokens.First().Value.TokenHash);
            Assert.AreEqual(DateTime.Parse("2024-04-14 20:51:00 PM"), loadSecurity.Groups.SelectMany(group => group.Accounts).First().AccessTokens.First().Value.LastTouched);
            Assert.AreEqual("de-DE", loadSecurity.Groups.Last().Accounts.First().PreferredLanguageCode);
            Assert.AreEqual(CommonProtocolType.DiceBattlefield3, loadSecurity.Groups.SelectMany(group => group.Accounts).SelectMany(account => account.Players).First().ProtocolType);
            Assert.AreEqual("ABCDEF", loadSecurity.Groups.SelectMany(group => group.Accounts).SelectMany(account => account.Players).First().Uid);

//.........这里部分代码省略.........
开发者ID:EBassie,项目名称:Potato,代码行数:101,代码来源:TestSecurity.cs

示例15: LoadConfig

        /// <summary> Loads configuration settings from a file called botsettings.txt </summary>
        private void LoadConfig()
        {
            try {
                config = new Config( "botsettings.txt" );
                if( !config.Exists() ) {
                    using( StreamWriter sw = new StreamWriter( "botsettings.txt" ) ) {
                        sw.WriteLine("UseRemoteServer: false");
                        sw.WriteLine("RemotePort: ");
                        sw.WriteLine("RemotePassword: ");
                        sw.WriteLine("CommandsRequireOperator: true");
                        sw.WriteLine("ReconnectAfterKick: true");
                        sw.WriteLine("SaveMap: false");
                        sw.WriteLine("Operators:");
                        sw.WriteLine("#And now, a little explaination on what all these mean.");
                        sw.WriteLine("#UseRemoteServer - Allows remote clients to connect and perform actions on the bot / chat through it. By default, this is disabled." +
                                     "If you choose to use the remote function, you may need to forward the port and/or add an exception to your firewall.");
                        sw.WriteLine("#RemotePort - The port the server will listen on for remote clients. It is fine to leave this blank if UseRemoteServer is false.");
                        sw.WriteLine("#RemotePassword - The password to use for verifying remote clients. " +
                                     "If UseRemoteServer is true and this is blank, the password will be set to \"password\". ");
                        sw.WriteLine("#CommandsRequireOperators - This determines whether bot commands require the person who called them to be in the operators file." +
                                     "Usually you would want this to be true.");
                        sw.WriteLine("#ReconnectAfterKick - This determines if the bot will reconnect after being kicked. Note that if the bot receives a kick packet before" +
                                     "a ServerIdentification packet, it will abort, and assume it has been banned from connecting.");
                        sw.WriteLine("#SaveMap - This determines if the bot will save the map when the chunk packets are sent to it." +
                                     "If this is true, it will be saved as a fCraft compatible map. (Large maps of 512 x 512 x 512 " +
                                     "can use up to ~150 megabytes of RAM when saving, so be wary. After saving, memory usage should return to normal.");
                        sw.WriteLine( "#Operators: Comma separated list of operators, with no spaces. (e.g. test,test1,test2)" );
                        Events.RaiseConfigCreating( new ConfigCreatingEventArgs( config, sw ) );
                    }
                }

                config.Load();
                if( !config.TryParseValueOrDefault( "useremoteserver", false, out UseRemoteServer ) )
                    Log( LogType.Warning, "Couldn't load value for useremoteserver from config. Setting to default value of false" );
                if( UseRemoteServer ) {
                    int remotePort;
                    if( !config.TryParseValueOrDefault( "remoteport", 25561, out remotePort ) ) {
                        Log( LogType.Warning, "Couldn't load value for remoteport from config. Setting to default value of 25561" );
                    }
                    string remotePassword;
                    config.TryGetRawValue( "remotepassword", out remotePassword );
                    if( String.IsNullOrEmpty( remotePassword ) ) {
                        remotePassword = "password";
                        Log( LogType.Warning, "Couldn't load value for remotepassword from config. Setting to default value of \"password\"" );
                    }

                    server = new Server();
                    server.Start( this, remotePort, remotePassword );
                }

                if( !config.TryParseValueOrDefault( "commandsrequireoperator", true, out _requiresop ) )
                    Log( LogType.Warning, "Couldn't load value for commandsrequireoperator from config. Setting to default value of true" );
                if( !config.TryParseValueOrDefault( "reconnectafterkick", true, out _reconnectonkick ) )
                    Log( LogType.Warning, "Couldn't load value for reconnectafterkick from config. Setting to default value of true" );
                if( !config.TryParseValueOrDefault( "savemap", false, out _savemap ) )
                    Log( LogType.Warning, "Couldn't load value for savemap from config. Setting to default value of false" );
                string rawUsers; // Comma separated.
                config.TryGetRawValue( "operators", out rawUsers );
                if( String.IsNullOrEmpty( rawUsers ) ) {
                    Log( LogType.Warning, "Couldn't load value for operators from config. Setting to default value of empty." );
                } else {
                    string[] users = rawUsers.Split( ',' );
                    bool fixedNames = false;
                    for( int i = 0; i < users.Length; i++ ) {
                        if( users[i].IndexOf( ' ' ) != -1 ) {
                            fixedNames = true;
                            users[i] = users[i].Replace( " ", String.Empty );
                        }
                    }
                    if( fixedNames ) {
                        config.AddOrUpdateValue( "operators", String.Join( ",", users ) );
                        Log( LogType.BotActivity, "Fixed up spaces in the list of operators." );
                        config.Save();
                    }
                    Users.AddRange( users );
                }

                Events.RaiseConfigLoading( new ConfigLoadingEventArgs( config ) );
            } catch( Exception e ) {
                Log( LogType.Error, "Couldn't load config:", e.ToString() );
            }
        }
开发者ID:Grivaryg,项目名称:LibClassicBot,代码行数:83,代码来源:MainBot.cs


注:本文中的Config.Load方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。