public async Task <IHttpActionResult> GetSpecificCalendarGridView([FromBody] int?dateShift)
        {
            if ((MyConfig == null) || !MyConfig.IsConfigured)
            {
                return(new StatusCodeResult(HttpStatusCode.NoContent, Request));
            }

            var targetStartDate = DateTime.Today;

            if (dateShift.HasValue)
            {
                var dateDiff = DateTime.Today - DateTime.Today.AddDays(dateShift.Value);

                if (Math.Abs(dateDiff.Days) <= MyConfig.CalendarGridConfig.MaxDaysShift)
                {
                    targetStartDate = DateTime.Today.AddDays(dateShift.Value);
                }
            }

            var sessionConfig = MyConfig.CalendarGridConfig;

            sessionConfig.StartDate = targetStartDate;
            MyConfig.ConfigureGrid(sessionConfig);

            await MyConfig.Populate();

            using (var sw = new StringWriter())
            {
                var writer = new HtmlTextWriter(sw);
                await MyConfig.CalendarGrid.Render(writer);

                return(await Task.FromResult(Ok(sw.GetStringBuilder().ToString())));
            }
        }
示例#2
0
    protected void ChangePass_Click(object sender, EventArgs e)
    {
        try
        {
            if (fPassWord.Value == "" || fPassWordNew.Value == "" || fPassWordNewConfirm.Value == "")
            {
                ShowErrorMes("Vui lòng nhập đầy đủ thông tin mật khẩu");
                return;
            }

            else if (MD5Encrypt.EncryptDataMD5(fPassWord.Value.Trim(), "CMSVTS") != MyConfig.GetValueByKey("PassWord"))
            {
                ShowErrorMes("Mật khẩu cũ không đúng! Bạn nhập lại ...");
                fPassWord.Focus();
                return;
            }
            else if (fPassWordNew.Value != fPassWordNewConfirm.Value)
            {
                ShowErrorMes("Nhập mật khẩu lại không chính xác");
                fPassWordNewConfirm.Focus();
                return;
            }
            DAWebUser daWebUser = new DAWebUser();
            string    PassEcryp = MD5Encrypt.EncryptDataMD5(fPassWordNew.Value.Trim(), "CMSVTS");
            daWebUser.USP_WebUser_ChangePass(this.KeyID, PassEcryp);
            ShowSuccessMes("Đỗi mật khẩu thành công");
        }
        catch (Exception ex)
        {
            ShowErrorMes("Lỗi hệ thống: " + ex.ToString());
        }
    }
示例#3
0
    static void Main(string[] args)
    {
        var data = new MyConfig[2];

        for (int i = 0; i < 2; i++)
        {
            data[i] = new MyConfig {
                Name = "Name" + i
            };
            data[i].Properties = new MyConfigAttribute[]
            {
                new MyConfigAttribute {
                    Name = "Property Name " + i, Value = "Property Value " + i
                },
                new MyConfigAttribute {
                    Name = "2nd Property Name " + i, Value = "2nd Property Value " + i
                },
            };
        }
        var serializer = new XmlSerializer(typeof(MyConfig[]));

        using (StreamWriter tw = File.CreateText(@"c:\temp\myconfig.xml"))
        {
            serializer.Serialize(tw, data);
        }
        using (StreamReader tw = File.OpenText(@"c:\temp\myconfig.xml"))
        {
            var readBack = serializer.Deserialize(tw);
        }
        Console.ReadLine();
    }
示例#4
0
 public ConfigWindow(Window window, MyConfig config)
 {
     Owner = window;
     this.config = config;
     InitializeComponent();
     talkKeyText.Text = config.TalkKey.ToString();
 }
示例#5
0
    override protected Boolean CheckInput()
    {
        if (fUserName.Value.Trim() == "")
        {
            ShowErrorMes("Bạn chưa nhập tài khoản!");
            fUserName.Focus();
            return(false);
        }
        if (fPassWord.Value.Trim() != "")
        {
            if (MD5Encrypt.EncryptDataMD5(fPassWord.Value.Trim(), "CMSVTS") != MyConfig.GetValueByKey("PassWord"))
            {
                ShowErrorMes("Mật khẩu cũ không đúng! Bạn nhập lại ...");
                fPassWord.Focus();
                return(false);
            }
        }

        if (fPassWordNew.Value.Trim() != "")
        {
            if (MD5Encrypt.EncryptDataMD5(fPassWord.Value.Trim(), "CMSVTS") != MyConfig.GetValueByKey("PassWord"))
            {
                ShowErrorMes("Mật khẩu cũ không đúng! Bạn nhập lại ...");
                fPassWord.Focus();
                return(false);
            }
        }

        return(true);
    }
示例#6
0
        void Init()
        {
            //文件路径
            this.conflang = MyConfig.GetLanguageFile(this.datapath);
            //游戏数据,MSE数据
            this.datacfg = new DataConfig(MyConfig.GetCardInfoFile(this.datapath));
            //初始化YGOUtil的数据
            YGOUtil.SetConfig(this.datacfg);

            //代码提示
            string funtxt     = MyPath.Combine(this.datapath, MyConfig.FILE_FUNCTION);
            string conlua     = MyPath.Combine(this.datapath, MyConfig.FILE_CONSTANT);
            string confstring = MyPath.Combine(this.datapath, MyConfig.FILE_STRINGS);

            this.codecfg = new CodeConfig();
            //添加函数
            this.codecfg.AddFunction(funtxt);
            //添加指示物
            this.codecfg.AddStrings(confstring);
            //添加常量
            this.codecfg.AddConstant(conlua);
            this.codecfg.SetNames(this.datacfg.dicSetnames);
            //生成菜单
            this.codecfg.InitAutoMenus();
            this.history = new History(this);
            //读取历史记录
            this.history.ReadHistory(MyPath.Combine(this.datapath, MyConfig.FILE_HISTORY));
            //加载多语言
            LanguageHelper.LoadFormLabels(this.conflang);
        }
示例#7
0
        public static void Main(string[] args)
        {
            GlobalCommon.Logger = new Log4Net();
            GlobalCommon.ExceptionProcessor = new WeixinExceptionProcessor();
            Console.OutputEncoding = Encoding.UTF8;

            //设定服务端参数
            //设定监听端口
            if (!String.IsNullOrEmpty(MyConfig.GetConfiguration("Server", "BindUrl")))
            {
                defaulturl = MyConfig.GetConfiguration("Server", "BindUrl");
            }
            else if (args != null)
            {
                if (args.Length > 0 && ComFunc.nvl(args[0]) != "")
                    defaulturl = args[0];
            }
            Console.WriteLine($"服务器启动绑定URL为{defaulturl},如果要调整,请在启动应用时,后面接端口参数,或者在appsettings.json中的Server下设定BindUrl参数(参数优先)");

            var host = new WebHostBuilder()
               .UseKestrel()
               .UseContentRoot(Directory.GetCurrentDirectory())
               .UseUrls(defaulturl)
               .UseIISIntegration()
               .UseStartup<Startup>()
               .UseApplicationInsights()
               .Build();

            host.Run();
        }
 public LoginController(ApplicationContext db, IHostingEnvironment env, IEmailService emailService, IOptions <MyConfig> settings)
 {
     _db           = db;
     _env          = env;
     _emailService = emailService;
     _config       = settings.Value;
 }
示例#9
0
        public static MyRenderDeviceSettings?Initialize()
        {
            MyRenderProxy.RequestVideoAdapters();
            MyConfig config = MySandboxGame.Config;

            RunningGraphicsRenderer = config.GraphicsRenderer;
            int?screenWidth  = config.ScreenWidth;
            int?screenHeight = config.ScreenHeight;
            int?nullable3    = new int?(config.VideoAdapter);

            if (((nullable3 == null) || (screenWidth == null)) || (screenHeight == null))
            {
                return(MyPerGameSettings.DefaultRenderDeviceSettings);
            }
            MyRenderDeviceSettings settings = new MyRenderDeviceSettings {
                AdapterOrdinal    = nullable3.Value,
                NewAdapterOrdinal = nullable3.Value,
                BackBufferHeight  = screenHeight.Value,
                BackBufferWidth   = screenWidth.Value,
                RefreshRate       = config.RefreshRate,
                VSync             = config.VerticalSync,
                WindowMode        = config.WindowMode
            };

            if (MyPerGameSettings.DefaultRenderDeviceSettings != null)
            {
                settings.UseStereoRendering = MyPerGameSettings.DefaultRenderDeviceSettings.Value.UseStereoRendering;
                settings.SettingsMandatory  = MyPerGameSettings.DefaultRenderDeviceSettings.Value.SettingsMandatory;
            }
            return(new MyRenderDeviceSettings?(settings));
        }
示例#10
0
        private void btSetName_Click(object sender, EventArgs e)
        {
            string strNewName = tbName.Text.Trim();

            if (strNewName.ToLower() != strName.ToLower() && !string.IsNullOrEmpty(strName))
            {
                DialogResult dialogResult =
                    MessageBox.Show("Updating name will reset all completed exercises. Continue?",
                                    "Update Name", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                if (dialogResult == DialogResult.No)
                {
                    return;
                }
            }

            // Save name and hash to configSetting
            MyConfig.SetSetting(MyConfig.Key_StudentName, strNewName);
            MyConfig.SetSetting(MyConfig.Key_StudentHash, MyConfig.GetHashFromName(strNewName.ToLower()));

            // Copy all exercises
            MyFileHelper.CopyExerciseFolders();
            MyFileHelper.GenerateEmptyFilesFromList();

            btSetName.Enabled = false;

            Application.Restart();
        }
示例#11
0
        private void BtImport_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();

            dialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            dialog.DefaultExt       = ".zip"; // Default file extension
            dialog.Filter           = "zip files (*.zip)|*.zip|All files (*.*)|*.*";
            dialog.FileName         = MyConfig.GetSetting(MyConfig.Key_StudentHash) + ".zip";

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string fileName = dialog.FileName;
                if (!File.Exists(fileName))
                {
                    MessageBox.Show(fileName, "File NOT Found");
                    return;
                }

                string userFolder = MyFileHelper.GetUserfolderPath();

                DialogResult dialogResult =
                    MessageBox.Show("This will overwrite existing exercise files. Continue?",
                                    "Import Profile", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                if (dialogResult == DialogResult.No)
                {
                    return;
                }

                ZipArchiveExtensions.ExtractZipFileToDirectory(fileName, userFolder, true);

                Application.Restart();
            }
        }
示例#12
0
    override protected Boolean SetServerControl()
    {
        try
        {
            this.Grid    = RadGrid1;
            this.messBox = message_box;

            this.BtCreate = btCreate;
            //this.BtClone = btClone;
            this.BtDelete = btDelete;

            RadGrid1.PageSize = Convert.ToInt32(MyConfig.GetValueByKey("PageSize"));

            int OrderDay;
            try
            {
                OrderDay = int.Parse(MyConfig.GetValueByKey("OrderDay").ToString());
            }
            catch
            {
                OrderDay = 30;
            }
            sFromDate.SelectedDate = DateTime.Now.AddDays(-OrderDay);
            sToDate.SelectedDate   = DateTime.Now;
        }
        catch
        {
            return(false);
        }

        return(true);
    }
        public void Save()
        {
            var sut = GetSUT();

            var target = new XmlConfigDescriptor
            {
                Uri = new Uri("C:/app.config"),
                RootElementPath = "Root",
            };
            target.DataStore = new ConfigXmlDataStore
            {
                Uri = target.Uri,
                FileSystem = FileSystem,
            };

            var expected = new MyConfig
            {
                AppName = "MyAppName",
                AppVersion = "1.0.0.0",
            };

            var canSave = sut.CanSave<MyConfig>(expected, target.DataStore);
            Assert.IsTrue(canSave);

            sut.Save<MyConfig>(expected, target.DataStore);
            

            // Assert
            var actual = new MyConfig();
            LoadFromFile(target, FileSystem, actual);

            Assert.IsNotNull(actual);
            Assert.AreEqual(expected.AppName, actual.AppName);
            Assert.AreEqual(expected.AppVersion, actual.AppVersion);
        }
 public static void Load()
 {
     MyConfig section = (MyConfig)ConfigurationManager.GetSection("myConfig");
     string path = section.Path;
     LoadValues(path);
     if (section.Watch)
         FileSystemWatcher(path);
 }
示例#15
0
 protected override bool CheckMyParametersAndConfig(ConsoleParameter p, ConsoleData d)
 {
     foreach (var s in MyConfig.GetConfigurationList("Mail"))
     {
         p[DomainKey.CONFIG, $"Mail_{s.Key}"] = s.Value;
     }
     return(true);
 }
示例#16
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            var config = new MyConfig();

            Configuration.Bind("MyConfig", config);
            services.AddSingleton(config);
        }
 public JWTHSAuthorizeMiddleware(RequestDelegate next,
                                 DBRouteValueDictionary routeDict,
                                 MyConfig myConfig)
 {
     this._next      = next;
     this.routeDict  = routeDict;
     jWTTokenOptions = myConfig.JWTTokenOptions;
 }
示例#18
0
        public override global::System.Data.DataSet Clone()
        {
            MyConfig cln = ((MyConfig)(base.Clone()));

            cln.InitVars();
            cln.SchemaSerializationMode = this.SchemaSerializationMode;
            return(cln);
        }
示例#19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews().AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());

            MyConfig config = Configuration.GetSection("Conifguration").Get <MyConfig>();

            services.AddSingleton <IService>(x => new DataService(config.Url));
        }
示例#20
0
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == CompileFileKeys)
            {
                btCompile.PerformClick();
                // Compile code

                return(true);
            }
            else if (keyData == RunFileKeys)
            {
                btRun.PerformClick();
                // Run code

                return(true);
            }
            else if (keyData == NewFileKeys)
            {
                // New file
                btNewFile.PerformClick();
                return(true);
            }
            else if (keyData == LoadFileKeys)
            {
                // New file
                btLoadFile.PerformClick();
                return(true);
            }
            else if (keyData == ExportFileKeys)
            {
                btExport.PerformClick();
                return(true);
            }
            else if (keyData == SaveFileKeys)
            {
                // New file
                btSave.PerformClick();
                return(true);
            }
            else if (keyData == PasteKeys)
            {
                // Allow lecturer to paste
                string name = MyConfig.GetSetting(MyConfig.Key_StudentName);
                string super_user_contains = MyConfig.GetSetting(MyConfig.Key_SuperUserContains);
                if (name.ToLower().Contains(super_user_contains))
                {
                    return(base.ProcessCmdKey(ref msg, keyData));
                }
                else
                {
                    return(true);
                }
            }
            else
            {
                return(base.ProcessCmdKey(ref msg, keyData));
            }
        }
示例#21
0
        //备份到2号服务器
        private void vf_Ftp2(object a)
        {
            Tools.WriteLog("Log", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "进入FTP2");
            //检查是否有未上传的文件
            while (!ib_Ftp2Upload)
            {
                bool OK = false;
                //List<string> list = INIFile.ReadKeyValues("IfFtpUpLoad");
                List <string> list       = SysVisitor.Current.ReadKeyValues("IfFtpUpLoad");
                List <string> ls_Ftplist = ListToUploadList(list, "Ftp2");//获取待上传文件列表
                if (ls_Ftplist.Count > 0)
                {
                    OK = true;
                }             //有文件未上传

                //获取FTP2相关参数
                string IP       = SysVisitor.Current.of_GetMySysSet("FTP2", "IP");
                string UserID   = SysVisitor.Current.of_GetMySysSet("FTP2", "UserID");
                string Password = SysVisitor.Current.of_GetMySysSet("FTP2", "Password");
                string Path     = SysVisitor.Current.of_GetMySysSet("FTP2", "Path");
                string Port     = SysVisitor.Current.of_GetMySysSet("FTP2", "Port");
                FtpWeb Ftp      = new FtpWeb(IP, Path, UserID, Password);
                if (!Ftp.Connect())//FTP 不可用
                {
                    ib_Ftp2Upload = true;
                    Tools.WriteLog("error", "FTP2服务器不可用");
                    break;
                }
                if (OK)
                {
                    if (!Ftp.DirectoryExist(DateTime.Now.ToString("yyyy-MM-dd")))
                    {
                        Ftp.MakeDir(DateTime.Now.ToString("yyyy-MM-dd"));
                    }
                    Path = Path + @"\" + DateTime.Now.ToString("yyyy-MM-dd");
                    //FTP2文件上传
                    FtpWeb ftp   = new FtpWeb(IP, Path, UserID, Password);
                    int    value = 0;//计算上传成功总数
                    for (int i = 0; i < ls_Ftplist.Count; i++)
                    {
                        int j = ftp.Upload(ls_Ftplist[i].ToString());
                        if (j == 1)//上传成功
                        {
                            value++;
                        }
                        string str = SysVisitor.Current.of_GetMySysSet("IfFtpUpLoad", ls_Ftplist[i].ToString());
                        str = str.Substring(str.Length - 3, 1);
                        SysVisitor.Current.of_SetMySysSet("IfFtpUpLoad", ls_Ftplist[i].ToString(), str + ",0");//更新节点

                        string ls_sql = "delete from mysysset where itemtype='IfFtpUpLoad' and itemvalue='0,0'";
                        MyConfig.ExecuteNonQuery(ls_sql);
                    }
                    Tools.WriteLog("Ftp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "FTP2已成功上传 " + value + " 个文件,剩余待上传个数:" + (ls_Ftplist.Count - value));
                }
                Thread.Sleep(60 * 1000);//等待60秒
            }
            return;
        }  //Getreport
示例#22
0
 public CorrectiveController(IWorkContext workContext,
                             ICorrectiveTaskService correctiveTaskService,
                             IAccountService accountService,
                             MyConfig myConfig) : base(workContext)
 {
     this._correctiveTaskService = correctiveTaskService;
     this._accountService        = accountService;
     this._myConfig = myConfig;
 }
示例#23
0
        public override void LoadContent()
        {
            base.LoadContent();

            m_backgroundColor = Vector4.Zero;

            MyConfig.NeedShowHelpScreen = false;
            MyConfig.Save();
        }
示例#24
0
 public PreviewController(IFileResultService fileResultService,
                          MyConfig myConfig,
                          IPreviewTokenService previewTokenService,
                          IWorkContext workContext)
 {
     this._fileResultService   = fileResultService;
     this._myConfig            = myConfig;
     this._previewTokenService = previewTokenService;
 }
示例#25
0
        public MyConfigController(IHostEnvironment hostingEnvironment,
                                  MyConfig myConfig, ILogger <MyConfigController> logger)
        {
            string path = hostingEnvironment.ContentRootPath + "\\MyConfig";

            jsonFileHelper = new JsonFileHelper(path);
            this.myConfig  = myConfig;
            this.logger    = logger;
        }
示例#26
0
        public string of_GetMySysSet(string as_type, string as_item)
        {
            MyConfig.DbName = "config.db";
            string ls_value = "";
            string ls_sql   = "select itemvalue from mysysset where itemtype='" + as_type + "' and itemname='" + as_item + "'";

            ls_value = MyConfig.ExecuteScalar(ls_sql);
            return(ls_value);
        }
示例#27
0
 public void Start()
 {
     m_config = GameObject.Find("GameConfig").GetComponent <MyConfig>();
     if (m_config.SearchWeapon(this.name, ref m_weapon) == false)
     {
         Debug.Log("wrong load weapon " + this.name);
     }
     Yval = transform.localPosition.y;
 }
示例#28
0
        //打开脚本
        public bool OpenScript(bool openinthis)
        {
            if (!dataform.CheckOpen())
            {
                return(false);
            }
            Card c = dataform.GetCard();

            if (c.id <= 0 || c.IsType(CardType.TYPE_NORMAL) && !c.IsType(CardType.TYPE_PENDULUM))//卡片密码不能小于等于0, 非灵摆的通常怪兽无需脚本
            {
                return(false);
            }
            long id = c.id;

            if (c.alias != 0)
            {
                long dif = c.id - c.alias;
                if (dif > -10 && dif < 10)
                {
                    id = c.alias;
                }
            }
            string lua = dataform.GetPath().GetScript(id);

            if (!File.Exists(lua))
            {
                MyPath.CreateDirByFile(lua);
                if (MyMsg.Question(LMSG.IfCreateScript))//是否创建脚本
                {
                    using (FileStream fs = new FileStream(lua,
                                                          FileMode.OpenOrCreate, FileAccess.Write))
                    {
                        StreamWriter sw = new StreamWriter(fs, new UTF8Encoding(false));
                        sw.WriteLine("--" + c.name);
                        sw.WriteLine("function c" + id.ToString() + ".initial_effect(c)");
                        sw.WriteLine("\t");
                        sw.WriteLine("end");
                        sw.Close();
                        fs.Close();
                    }
                }
            }
            if (File.Exists(lua)) //如果存在,则打开文件
            {
                if (openinthis)   //是否用本程序打开
                {
                    MyConfig.OpenFileInThis(lua);
                }
                else
                {
                    System.Diagnostics.Process.Start(lua);
                }
                return(true);
            }
            return(false);
        }
示例#29
0
 public StepController(IInterfaceDAL interfaceDAL,
                       IFlowStepDAL flowStepDAL,
                       MyConfig myConfig,
                       IConfiguration configuration)
 {
     this.interfaceDAL  = interfaceDAL;
     this.flowStepDAL   = flowStepDAL;
     this.myConfig      = myConfig;
     this.configuration = configuration;
 }
示例#30
0
        /// <summary>
        /// Initialize components and plugins in the nop environment.
        /// </summary>
        /// <param name="config">Config</param>
        public void Initialize(MyConfig config)
        {
            //register dependencies
            RegisterDependencies(config);

            if (!config.IgnoreStartupTasks)
            {
                RunStartupTasks();
            }
        }
示例#31
0
        private static void _doABVerificationTestSim(MyConfig simConfig, IBinInfo binInfo)
        {
            try {
                Console.Out.WriteLine("Verify functional behavior...");

                // *** GOOD SIGN *** //
                var sim = new Simulator(simConfig);

                sim.Config.BreakPoints.Add(binInfo.Symbols["serial_putc"].Address, eng => {
                    Console.Out.Write((char)eng.RegRead(Arm.UC_ARM_REG_R0));
                });

                var simResult = sim.RunSimulation();

                if (simResult != Result.Completed)
                {
                    Console.Out.WriteLine("Incorrect behavior (" + simResult + ") with signed payload!");
                    Environment.Exit(-1);
                }

                // *** Incorrect SIGN *** //
                simConfig.UseAltData = true;

                ((OtpPeripheral)simConfig.AddressSpace[0x12000000]).PersistentChanges = false;

                sim = new Simulator(simConfig);

                sim.Config.BreakPoints.Add(binInfo.Symbols["serial_putc"].Address, eng => {
                    Console.Out.Write((char)eng.RegRead(Arm.UC_ARM_REG_R0));
                });

                simResult = sim.RunSimulation();

                if (simResult != Result.Failed && simResult != Result.Timeout)
                {
                    Console.Out.WriteLine($"Incorrect behavior ({simResult.ToString()}) with incorrectly signed payload!");
                    Environment.Exit(-1);
                }

                Console.Out.WriteLine("Verification finished. Bootloader is verified to work as intended.");
                Environment.Exit(0);
            }
            catch (SimulationException ex) {
                Console.Out.WriteLine(ex.Message);
                Console.Out.WriteLine();

                if (ex is PlatformEngineException exception)
                {
                    exception.Engine.DumpState(Console.Out, binInfo);
                }

                Environment.Exit(-1);
            }
        }
示例#32
0
        public void SaveJson(MyConfig config)
        {
            string json = JsonConvert.SerializeObject(
                config,
                new JsonSerializerSettings
            {
                DateTimeZoneHandling = DateTimeZoneHandling.Local
            });

            File.WriteAllText(@"./config.json", json);
        }
示例#33
0
        static void Main(string[] args)
        {
            //string testFile = Path.Combine(Path.GetTempPath(), "OOPConfig.txt");

            var r = new Random();

            var randomString = new StringBuilder();
            for (int i = 0; i < 128; i++)
            {
                randomString.Append((char)(r.Next(95) + 32));
            }

            var config1 = new MyConfig();
            config1.SomeBool = true;
            config1.SomeString = "  Hello; wörld!\r\n🐧\r\nLorem ipsum!  =\x00=  ";
            config1.SomeString2 = randomString.ToString();
            config1.SomeInt = r.Next(-9999, 9999);
            config1.SomeDouble = r.NextDouble();
            config1.SomeObject = new MySerObject { Message = "Hello, world!" };
            config1.SomeDateTime = new DateTime(1976, 7, 4, r.Next(24), r.Next(60), r.Next(60));
            config1.SomeDTOffset = DateTimeOffset.Now;
            config1.SomeTimeSpan = new TimeSpan(r.Next(4), r.Next(60), r.Next(60));
            config1.SomeEnum = (MyEnum)r.Next(4);
            config1.SomeFlags = MyFlagsEnum.Alpha | MyFlagsEnum.Gamma;

            config1.Save();

            var config2 = Configuration.Load<MyConfig>();
            Debug.Assert(config2.SomeBool == config1.SomeBool);
            Debug.Assert(config2.SomeString == config1.SomeString);
            Debug.Assert(config2.SomeString2 == config1.SomeString2);
            Debug.Assert(config2.SomeInt == config1.SomeInt);
            Debug.Assert(config2.SomeDouble == config1.SomeDouble);
            Debug.Assert(config2.SomeObject.Message == config1.SomeObject.Message);
            Debug.Assert(config2.SomeDateTime == config1.SomeDateTime);
            Debug.Assert(config2.SomeDTOffset == config1.SomeDTOffset);
            Debug.Assert(config2.SomeTimeSpan == config1.SomeTimeSpan);
            Debug.Assert(config2.SomeEnum == config1.SomeEnum);
            Debug.Assert(config2.SomeFlags == config1.SomeFlags);
        }
        public void Load()
        {
            var sut = GetSUT();

            var source = new XmlConfigDescriptor
            {
                Uri = new Uri("C:/app.config"),
                RootElementPath = "Root",
            };
            var expected = new MyConfig
            {
                AppName = "MyAppName",
                AppVersion = "1.0.0.0",
            };
            SaveToFile(source, FileSystem, expected);

            var canLoad = sut.CanLoad<MyConfig>(source);
            Assert.IsTrue(canLoad);

            var actual = sut.Load<MyConfig>(source);
            Assert.IsNotNull(actual);
            Assert.AreEqual(expected.AppName, actual.AppName);
            Assert.AreEqual(expected.AppVersion, actual.AppVersion);
        }
 public void Initialize()
 {
     _config = new MyConfig();
 }
        public void LoadEditAndSave()
        {
            var sut = GetSUT();

            // Arrange
            var source = new XmlConfigDescriptor
            {
                Uri = new Uri("C:/app.config"),
                RootElementPath = "Root",
            };
            source.DataStore = new ConfigXmlDataStore
            {
                Uri = source.Uri,
                FileSystem = FileSystem,
            };

            var original = new MyConfig
            {
                AppName = "MyAppName",
                AppVersion = "1.0.0.0",
            };
            SaveToFile(source, FileSystem, original);

            // Act
            var canLoad = sut.CanLoad<MyConfig>(source);
            Assert.IsTrue(canLoad);

            var edited = sut.Load<MyConfig>(source);

            // Assert
            Assert.IsNotNull(edited);
            Assert.AreEqual(original.AppName, edited.AppName);
            Assert.AreEqual(original.AppVersion, edited.AppVersion);


            // Arrange
            edited.AppVersion = "2.0.0.0";
            
            // Act
            var canSave = sut.CanSave<MyConfig>(edited, source.DataStore);
            Assert.IsTrue(canSave);

            sut.Save<MyConfig>(edited, source.DataStore);


            // Assert
            var actual = new MyConfig();
            LoadFromFile(source, FileSystem, actual);

            Assert.IsNotNull(actual);
            Assert.AreEqual(edited.AppName, actual.AppName);
            Assert.AreEqual(edited.AppVersion, actual.AppVersion);
        }
示例#37
0
 public HomeController(MyConfig config)
 {
     _config = config;
 }
 public DictionaryBasedConfig_Test()
 {
     _config = new MyConfig();
 }