Newtonsoft.Json.JsonConvert.SerializeObject(object, System.Type, Newtonsoft.Json.Formatting, Newtonsoft.Json.JsonSerializerSettings)

Here are the examples of the csharp api Newtonsoft.Json.JsonConvert.SerializeObject(object, System.Type, Newtonsoft.Json.Formatting, Newtonsoft.Json.JsonSerializerSettings) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

3330 Examples 7

19 View Source File : AppConfig.cs
License : Apache License 2.0
Project Creator : 214175590

public void SaveConfig(int type = 0)
        {
            if(type == 0 || type == 1){
                try
                {
                    string mconfig = JsonConvert.SerializeObject(MConfig, Formatting.Indented);
                    if (!string.IsNullOrWhiteSpace(mconfig))
                    {
                        YSTools.YSFile.writeFileByString(MainForm.CONF_DIR + MC_NAME, mconfig, false, CONFIG_KEY);
                    }
                }
                catch (Exception ex)
                {
                    logger.Error("保存Main配置文件异常:" + ex.Message);
                    logger.Error("--->" + MC_NAME);
                }
            }

            if (type == 0 || type == 2)
            {
                string sconfig = null, scname = null;
                int index = 0;
                List<string> newFiles = new List<string>();
                foreach (KeyValuePair<string, SessionConfig> item in SessionConfigDict)
                {
                    try
                    {
                        sconfig = JsonConvert.SerializeObject(item.Value, Formatting.Indented);
                        if (!string.IsNullOrWhiteSpace(sconfig))
                        {
                            scname = string.Format("session{0}.json", index);
                            YSTools.YSFile.writeFileByString(MainForm.SESSION_DIR + scname, sconfig, false, CONFIG_KEY);
                            newFiles.Add(scname);
                            index++;
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error("保存Session配置文件异常:" + ex.Message);
                        logger.Error("--->" + item.Key);
                    }
                }

                DirectoryInfo dirs = new DirectoryInfo(MainForm.SESSION_DIR);
                FileInfo[] files = dirs.GetFiles();
                foreach(FileInfo file in files){
                    if (!newFiles.Contains(file.Name))
                    {
                        file.Delete();
                    }
                }
            }
            
        }

19 View Source File : Startup.cs
License : Apache License 2.0
Project Creator : 2881099

public void Configure(IApplicationBuilder app)
        {
            app.UseDeveloperExceptionPage();

            app.UseRouting();
            app.UseEndpoints(config => config.MapControllers());
            app.UseDefaultFiles();
            app.UseStaticFiles();

            ImHelper.Initialization(new ImClientOptions
            {
                Redis = Redis,
                Servers = Configuration["imserver"].Split(';')
            });

            ImHelper.Instance.OnSend += (s, e) =>
                Console.WriteLine($"ImClient.SendMessage(server={e.Server},data={JsonConvert.SerializeObject(e.Message)})");
        }

19 View Source File : SetsTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
        public void SAdd()
        {
            cli.Del("TestSAdd1");
            replacedert.Equal(1, cli.SAdd("TestSAdd1", String));
            replacedert.Equal(String, cli.SPop("TestSAdd1"));
            replacedert.Equal(4, cli.SAdd("TestSAdd1", Null, Clreplaced, String, Bytes));
            cli.SPop("TestSAdd1");
            replacedert.Equal(3, cli.SCard("TestSAdd1"));

            cli.Del("TestSAdd2");
            replacedert.Equal(1, cli.SAdd("TestSAdd2", Clreplaced));
            replacedert.Equal(JsonConvert.SerializeObject(Clreplaced), JsonConvert.SerializeObject(cli.SPop<TestClreplaced>("TestSAdd2")));
            replacedert.Equal(1, cli.SAdd("TestSAdd2", Clreplaced));
            replacedert.Equal(JsonConvert.SerializeObject(Clreplaced), cli.SPop("TestSAdd2"));
        }

19 View Source File : StringsTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
        public void Get()
        {
            var key = "TestGet_null";
            cli.Set(key, Null);
            replacedert.Equal((cli.Get(key))?.ToString() ?? "", Null?.ToString() ?? "");

            key = "TestGet_string";
            cli.Set(key, String);
            replacedert.Equal(cli.Get(key), String);

            key = "TestGet_bytes";
            cli.Set(key, Bytes);
            replacedert.Equal(cli.Get<byte[]>(key), Bytes);

            key = "TestGet_clreplaced";
            cli.Set(key, Clreplaced);
            replacedert.Equal(JsonConvert.SerializeObject(cli.Get<TestClreplaced>(key)), JsonConvert.SerializeObject(Clreplaced));

            key = "TestGet_clreplacedArray";
            cli.Set(key, new[] { Clreplaced, Clreplaced });
            replacedert.Equal(2, cli.Get<TestClreplaced[]>(key)?.Length);
            replacedert.Equal(JsonConvert.SerializeObject(cli.Get<TestClreplaced[]>(key)?.First()), JsonConvert.SerializeObject(Clreplaced));
            replacedert.Equal(JsonConvert.SerializeObject(cli.Get<TestClreplaced[]>(key)?.Last()), JsonConvert.SerializeObject(Clreplaced));
        }

19 View Source File : StringsTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
        public void MGet()
        {
            cli.Set("TestMGet_null1", Null);
            cli.Set("TestMGet_string1", String);
            cli.Set("TestMGet_bytes1", Bytes);
            cli.Set("TestMGet_clreplaced1", Clreplaced);
            cli.Set("TestMGet_null2", Null);
            cli.Set("TestMGet_string2", String);
            cli.Set("TestMGet_bytes2", Bytes);
            cli.Set("TestMGet_clreplaced2", Clreplaced);
            cli.Set("TestMGet_null3", Null);
            cli.Set("TestMGet_string3", String);
            cli.Set("TestMGet_bytes3", Bytes);
            cli.Set("TestMGet_clreplaced3", Clreplaced);

            replacedert.Equal(4, cli.MGet("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1").Length);
            replacedert.Equal("", cli.MGet("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[0]);
            replacedert.Equal(String, cli.MGet("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[1]);
            replacedert.Equal(Encoding.UTF8.GetString(Bytes), cli.MGet("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[2]);
            replacedert.Equal(JsonConvert.SerializeObject(Clreplaced), cli.MGet("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[3]);

            replacedert.Equal(4, cli.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1").Length);
            replacedert.Equal(new byte[0], cli.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[0]);
            replacedert.Equal(Encoding.UTF8.GetBytes(String), cli.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[1]);
            replacedert.Equal(Bytes, cli.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[2]);
            replacedert.Equal(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(Clreplaced)), cli.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[3]);

            replacedert.Equal(3, cli.MGet<TestClreplaced>("TestMGet_clreplaced1", "TestMGet_clreplaced2", "TestMGet_clreplaced3").Length);
            replacedert.Equal(JsonConvert.SerializeObject(Clreplaced), JsonConvert.SerializeObject(cli.MGet<TestClreplaced>("TestMGet_clreplaced1", "TestMGet_clreplaced2", "TestMGet_clreplaced3")[0]));
            replacedert.Equal(JsonConvert.SerializeObject(Clreplaced), JsonConvert.SerializeObject(cli.MGet<TestClreplaced>("TestMGet_clreplaced1", "TestMGet_clreplaced2", "TestMGet_clreplaced3")[1]));
            replacedert.Equal(JsonConvert.SerializeObject(Clreplaced), JsonConvert.SerializeObject(cli.MGet<TestClreplaced>("TestMGet_clreplaced1", "TestMGet_clreplaced2", "TestMGet_clreplaced3")[2]));
        }

19 View Source File : StringsTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
        public void PSetNx()
        {
            cli.PSetEx("TestSetNx_null", 10000, Null);
            replacedert.Equal("", cli.Get("TestSetNx_null"));

            cli.PSetEx("TestSetNx_string", 10000, String);
            replacedert.Equal(String, cli.Get("TestSetNx_string"));

            cli.PSetEx("TestSetNx_bytes", 10000, Bytes);
            replacedert.Equal(Bytes, cli.Get<byte[]>("TestSetNx_bytes"));

            cli.PSetEx("TestSetNx_clreplaced", 10000, Clreplaced);
            replacedert.Equal(JsonConvert.SerializeObject(Clreplaced), JsonConvert.SerializeObject(cli.Get<TestClreplaced>("TestSetNx_clreplaced")));
        }

19 View Source File : RepositoryTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
		public void AddUpdate() {
			var repos = g.sqlite.GetGuidRepository<AddUpdateInfo>();

			var item = repos.Insert(new AddUpdateInfo());
			Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));

			item = repos.Insert(new AddUpdateInfo { Id = Guid.NewGuid() });
			Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));

			item.replacedle = "xxx";
			repos.Update(item);
			Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));

			Console.WriteLine(repos.UpdateDiy.Where(a => a.Id == item.Id).Set(a => a.Clicks + 1).ToSql());
			repos.UpdateDiy.Where(a => a.Id == item.Id).Set(a => a.Clicks + 1).ExecuteAffrows();

			item = repos.Find(item.Id);
			Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
		}

19 View Source File : Program.cs
License : MIT License
Project Creator : 2881099

static void Main(string[] args)
    {
        FreeSql.DynamicProxy.GetAvailableMeta(typeof(MyClreplaced)); //The first dynamic compilation was slow
        var dt = DateTime.Now;
        var pxy = new MyClreplaced { T2 = "123123" }.ToDynamicProxy();
        Console.WriteLine(pxy.Get("key"));
        Console.WriteLine(pxy.GetAsync().Result);
        pxy.Text = "testSetProp1";
        Console.WriteLine(pxy.Text);

        Console.WriteLine(DateTime.Now.Subtract(dt).TotalMilliseconds + " ms\r\n");

        dt = DateTime.Now;
        pxy = new MyClreplaced().ToDynamicProxy();
        Console.WriteLine(pxy.Get("key1"));
        Console.WriteLine(pxy.GetAsync().Result);
        pxy.Text = "testSetProp2";
        Console.WriteLine(pxy.Text);

        Console.WriteLine(DateTime.Now.Subtract(dt).TotalMilliseconds + " ms\r\n");

        var api = DynamicProxy.Resolve<IUserApi>();
        api.Add(new UserInfo { Id = "001", Remark = "add" });
        Console.WriteLine(JsonConvert.SerializeObject(api.Get<UserInfo>("001")));
    }

19 View Source File : Program.cs
License : MIT License
Project Creator : 2881099

public override Task Before(FreeSql.DynamicProxyBeforeArguments args)
    {
        Console.WriteLine($"{args.MemberInfo.Name} HttpPost {_url} Body {JsonConvert.SerializeObject(args.Parameters)}");
        return base.Before(args);
    }

19 View Source File : HashesTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
        public void HGetAll()
        {
            cli.Del("TestHGetAll");
            cli.HMSet("TestHGetAll", "string1", base.String, "bytes1", base.Bytes, "clreplaced1", base.Clreplaced, "clreplaced1array", new[] { base.Clreplaced, base.Clreplaced });
            replacedert.Equal(4, cli.HGetAll("TestHGetAll").Count);
            replacedert.Equal(base.String, cli.HGetAll("TestHGetAll")["string1"]);
            replacedert.Equal(Encoding.UTF8.GetString(base.Bytes), cli.HGetAll("TestHGetAll")["bytes1"]);
            replacedert.Equal(JsonConvert.SerializeObject(base.Clreplaced), cli.HGetAll("TestHGetAll")["clreplaced1"]);
        }

19 View Source File : HashesTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
        public void HMSet()
        {
            cli.Del("TestHMSet");
            cli.HMSet("TestHMSet", "string1", base.String, "bytes1", base.Bytes, "clreplaced1", base.Clreplaced, "clreplaced1array", new[] { base.Clreplaced, base.Clreplaced });
            replacedert.Equal(4, cli.HMGet("TestHMSet", "string1", "bytes1", "clreplaced1", "clreplaced1array").Length);
            replacedert.Contains(base.String, cli.HMGet("TestHMSet", "string1", "bytes1", "clreplaced1", "clreplaced1array"));
            replacedert.Contains(Encoding.UTF8.GetString(base.Bytes), cli.HMGet("TestHMSet", "string1", "bytes1", "clreplaced1", "clreplaced1array"));
            replacedert.Contains(JsonConvert.SerializeObject(base.Clreplaced), cli.HMGet("TestHMSet", "string1", "bytes1", "clreplaced1", "clreplaced1array"));
        }

19 View Source File : StringsTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
        public void MSet()
        {
            cli.Del("TestMSet_null1", "TestMSet_string1", "TestMSet_bytes1", "TestMSet_clreplaced1");
            cli.MSet(new Dictionary<string, object> { ["TestMSet_null1"] = Null, ["TestMSet_string1"] = String, ["TestMSet_bytes1"] = Bytes, ["TestMSet_clreplaced1"] = Clreplaced });
            replacedert.Equal("", cli.Get("TestMSet_null1"));
            replacedert.Equal(String, cli.Get("TestMSet_string1"));
            replacedert.Equal(Bytes, cli.Get<byte[]>("TestMSet_bytes1"));
            replacedert.Equal(JsonConvert.SerializeObject(Clreplaced), JsonConvert.SerializeObject(cli.Get<TestClreplaced>("TestMSet_clreplaced1")));

            cli.Del("TestMSet_null1", "TestMSet_string1", "TestMSet_bytes1", "TestMSet_clreplaced1");
            cli.MSet("TestMSet_null1", Null, "TestMSet_string1", String, "TestMSet_bytes1", Bytes, "TestMSet_clreplaced1", Clreplaced);
            replacedert.Equal("", cli.Get("TestMSet_null1"));
            replacedert.Equal(String, cli.Get("TestMSet_string1"));
            replacedert.Equal(Bytes, cli.Get<byte[]>("TestMSet_bytes1"));
            replacedert.Equal(JsonConvert.SerializeObject(Clreplaced), JsonConvert.SerializeObject(cli.Get<TestClreplaced>("TestMSet_clreplaced1")));
        }

19 View Source File : StringsTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
        public void MSetNx()
        {
            cli.Del("TestMSetNx_null", "TestMSetNx_string", "TestMSetNx_bytes", "TestMSetNx_clreplaced", "abctest",
                "TestMSetNx_null1", "TestMSetNx_string1", "TestMSetNx_bytes1", "TestMSetNx_clreplaced1");

            replacedert.True(cli.MSetNx(new Dictionary<string, object> { ["TestMSetNx_null"] = Null }));
            replacedert.False(cli.MSetNx(new Dictionary<string, object> { ["TestMSetNx_null"] = Null }));
            replacedert.Equal("", cli.Get("TestMSetNx_null"));

            replacedert.True(cli.MSetNx(new Dictionary<string, object> { ["TestMSetNx_string"] = String }));
            replacedert.False(cli.MSetNx(new Dictionary<string, object> { ["TestMSetNx_string"] = String }));
            replacedert.Equal(String, cli.Get("TestMSetNx_string"));

            replacedert.True(cli.MSetNx(new Dictionary<string, object> { ["TestMSetNx_bytes"] = Bytes }));
            replacedert.False(cli.MSetNx(new Dictionary<string, object> { ["TestMSetNx_bytes"] = Bytes }));
            replacedert.Equal(Bytes, cli.Get<byte[]>("TestMSetNx_bytes"));

            replacedert.True(cli.MSetNx(new Dictionary<string, object> { ["TestMSetNx_clreplaced"] = Clreplaced }));
            replacedert.False(cli.MSetNx(new Dictionary<string, object> { ["TestMSetNx_clreplaced"] = Clreplaced }));
            replacedert.Equal(JsonConvert.SerializeObject(Clreplaced), JsonConvert.SerializeObject(cli.Get<TestClreplaced>("TestMSetNx_clreplaced")));

            cli.Set("abctest", 1);
            replacedert.False(cli.MSetNx(new Dictionary<string, object> { ["abctest"] = 2, ["TestMSetNx_null1"] = Null, ["TestMSetNx_string1"] = String, ["TestMSetNx_bytes1"] = Bytes, ["TestMSetNx_clreplaced1"] = Clreplaced }));
            replacedert.True(cli.MSetNx(new Dictionary<string, object> { ["TestMSetNx_null1"] = Null, ["TestMSetNx_string1"] = String, ["TestMSetNx_bytes1"] = Bytes, ["TestMSetNx_clreplaced1"] = Clreplaced }));
            replacedert.Equal(1, cli.Get<int>("abctest"));
            replacedert.Equal("", cli.Get("TestMSetNx_null1"));
            replacedert.Equal(String, cli.Get("TestMSetNx_string1"));
            replacedert.Equal(Bytes, cli.Get<byte[]>("TestMSetNx_bytes1"));
            replacedert.Equal(JsonConvert.SerializeObject(Clreplaced), JsonConvert.SerializeObject(cli.Get<TestClreplaced>("TestMSetNx_clreplaced1")));

            cli.Del("TestMSetNx_null", "TestMSetNx_string", "TestMSetNx_bytes", "TestMSetNx_clreplaced");
            cli.MSetNx("TestMSetNx_null1", Null, "TestMSetNx_string1", String, "TestMSetNx_bytes1", Bytes, "TestMSetNx_clreplaced1", Clreplaced);
            replacedert.Equal("", cli.Get("TestMSetNx_null1"));
            replacedert.Equal(String, cli.Get("TestMSetNx_string1"));
            replacedert.Equal(Bytes, cli.Get<byte[]>("TestMSetNx_bytes1"));
            replacedert.Equal(JsonConvert.SerializeObject(Clreplaced), JsonConvert.SerializeObject(cli.Get<TestClreplaced>("TestMSetNx_clreplaced1")));
        }

19 View Source File : StringsTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
        public void Set()
        {
            cli.Del("TestSetNx_null", "TestSetNx_string", "TestSetNx_bytes", "TestSetNx_clreplaced");
            cli.Set("TestSet_null", Null);
            replacedert.Equal("", cli.Get("TestSet_null"));

            cli.Set("TestSet_string", String);
            replacedert.Equal(String, cli.Get("TestSet_string"));

            cli.Set("TestSet_bytes", Bytes);
            replacedert.Equal(Bytes, cli.Get<byte[]>("TestSet_bytes"));

            cli.Set("TestSet_clreplaced", Clreplaced);
            replacedert.Equal(JsonConvert.SerializeObject(Clreplaced), JsonConvert.SerializeObject(cli.Get<TestClreplaced>("TestSet_clreplaced")));

            cli.Del("TestSetNx_null", "TestSetNx_string", "TestSetNx_bytes", "TestSetNx_clreplaced");
            cli.Set("TestSet_null", Null, 10);
            replacedert.Equal("", cli.Get("TestSet_null"));

            cli.Set("TestSet_string", String, 10);
            replacedert.Equal(String, cli.Get("TestSet_string"));

            cli.Set("TestSet_bytes", Bytes, 10);
            replacedert.Equal(Bytes, cli.Get<byte[]>("TestSet_bytes"));

            cli.Set("TestSet_clreplaced", Clreplaced, 10);
            replacedert.Equal(JsonConvert.SerializeObject(Clreplaced), JsonConvert.SerializeObject(cli.Get<TestClreplaced>("TestSet_clreplaced")));

            cli.Del("TestSetNx_null", "TestSetNx_string", "TestSetNx_bytes", "TestSetNx_clreplaced");
            cli.Set("TestSet_null", Null, true);
            replacedert.Equal("", cli.Get("TestSet_null"));

            cli.Set("TestSet_string", String, true);
            replacedert.Equal(String, cli.Get("TestSet_string"));

            cli.Set("TestSet_bytes", Bytes, true);
            replacedert.Equal(Bytes, cli.Get<byte[]>("TestSet_bytes"));

            cli.Set("TestSet_clreplaced", Clreplaced, true);
            replacedert.Equal(JsonConvert.SerializeObject(Clreplaced), JsonConvert.SerializeObject(cli.Get<TestClreplaced>("TestSet_clreplaced")));
        }

19 View Source File : StringsTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
        public void SetNx()
        {
            cli.Del("TestSetNx_null", "TestSetNx_string", "TestSetNx_bytes", "TestSetNx_clreplaced");
            replacedert.True(cli.SetNx("TestSetNx_null", Null));
            replacedert.False(cli.SetNx("TestSetNx_null", Null));
            replacedert.Equal("", cli.Get("TestSetNx_null"));

            replacedert.True(cli.SetNx("TestSetNx_string", String));
            replacedert.False(cli.SetNx("TestSetNx_string", String));
            replacedert.Equal(String, cli.Get("TestSetNx_string"));

            replacedert.True(cli.SetNx("TestSetNx_bytes", Bytes));
            replacedert.False(cli.SetNx("TestSetNx_bytes", Bytes));
            replacedert.Equal(Bytes, cli.Get<byte[]>("TestSetNx_bytes"));

            replacedert.True(cli.SetNx("TestSetNx_clreplaced", Clreplaced));
            replacedert.False(cli.SetNx("TestSetNx_clreplaced", Clreplaced));
            replacedert.Equal(JsonConvert.SerializeObject(Clreplaced), JsonConvert.SerializeObject(cli.Get<TestClreplaced>("TestSetNx_clreplaced")));

            cli.Del("TestSetNx_null", "TestSetNx_string", "TestSetNx_bytes", "TestSetNx_clreplaced");
            replacedert.True(cli.SetNx("TestSetNx_null", Null, 10));
            replacedert.False(cli.SetNx("TestSetNx_null", Null, 10));
            replacedert.Equal("", cli.Get("TestSetNx_null"));

            replacedert.True(cli.SetNx("TestSetNx_string", String, 10));
            replacedert.False(cli.SetNx("TestSetNx_string", String, 10));
            replacedert.Equal(String, cli.Get("TestSetNx_string"));

            replacedert.True(cli.SetNx("TestSetNx_bytes", Bytes, 10));
            replacedert.False(cli.SetNx("TestSetNx_bytes", Bytes, 10));
            replacedert.Equal(Bytes, cli.Get<byte[]>("TestSetNx_bytes"));

            replacedert.True(cli.SetNx("TestSetNx_clreplaced", Clreplaced, 10));
            replacedert.False(cli.SetNx("TestSetNx_clreplaced", Clreplaced, 10));
            replacedert.Equal(JsonConvert.SerializeObject(Clreplaced), JsonConvert.SerializeObject(cli.Get<TestClreplaced>("TestSetNx_clreplaced")));
        }

19 View Source File : StringsTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
        public void SetXx()
        {
            cli.Del("TestSetXx_null");
            replacedert.False(cli.SetXx("TestSetXx_null", Null, 10));
            cli.Set("TestSetXx_null", 1, true);
            replacedert.True(cli.SetXx("TestSetXx_null", Null, 10));
            replacedert.Equal("", cli.Get("TestSetXx_null"));

            cli.Del("TestSetXx_string");
            replacedert.False(cli.SetXx("TestSetXx_string", String, 10));
            cli.Set("TestSetXx_string", 1, true);
            replacedert.True(cli.SetXx("TestSetXx_string", String, 10));
            replacedert.Equal(String, cli.Get("TestSetXx_string"));

            cli.Del("TestSetXx_bytes");
            replacedert.False(cli.SetXx("TestSetXx_bytes", Bytes, 10));
            cli.Set("TestSetXx_bytes", 1, true);
            replacedert.True(cli.SetXx("TestSetXx_bytes", Bytes, 10));
            replacedert.Equal(Bytes, cli.Get<byte[]>("TestSetXx_bytes"));

            cli.Del("TestSetXx_clreplaced");
            replacedert.False(cli.SetXx("TestSetXx_clreplaced", Clreplaced, 10));
            cli.Set("TestSetXx_clreplaced", 1, true);
            replacedert.True(cli.SetXx("TestSetXx_clreplaced", Clreplaced, 10));
            replacedert.Equal(JsonConvert.SerializeObject(Clreplaced), JsonConvert.SerializeObject(cli.Get<TestClreplaced>("TestSetXx_clreplaced")));

            cli.Del("TestSetXx_null");
            replacedert.False(cli.SetXx("TestSetXx_null", Null, true));
            cli.Set("TestSetXx_null", 1, true);
            replacedert.True(cli.SetXx("TestSetXx_null", Null, true));
            replacedert.Equal("", cli.Get("TestSetXx_null"));

            cli.Del("TestSetXx_string");
            replacedert.False(cli.SetXx("TestSetXx_string", String, true));
            cli.Set("TestSetXx_string", 1, true);
            replacedert.True(cli.SetXx("TestSetXx_string", String, true));
            replacedert.Equal(String, cli.Get("TestSetXx_string"));

            cli.Del("TestSetXx_bytes");
            replacedert.False(cli.SetXx("TestSetXx_bytes", Bytes, true));
            cli.Set("TestSetXx_bytes", 1, true);
            replacedert.True(cli.SetXx("TestSetXx_bytes", Bytes, true));
            replacedert.Equal(Bytes, cli.Get<byte[]>("TestSetXx_bytes"));

            cli.Del("TestSetXx_clreplaced");
            replacedert.False(cli.SetXx("TestSetXx_clreplaced", Clreplaced, true));
            cli.Set("TestSetXx_clreplaced", 1, true);
            replacedert.True(cli.SetXx("TestSetXx_clreplaced", Clreplaced, true));
            replacedert.Equal(JsonConvert.SerializeObject(Clreplaced), JsonConvert.SerializeObject(cli.Get<TestClreplaced>("TestSetXx_clreplaced")));
        }

19 View Source File : StringsTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
        public void SetEx()
        {
            cli.Del("TestSetEx_null", "TestSetEx_string", "TestSetEx_bytes", "TestSetEx_clreplaced");
            cli.SetEx("TestSetEx_null", 10, Null);
            replacedert.Equal("", cli.Get("TestSetEx_null"));

            cli.SetEx("TestSetEx_string", 10, String);
            replacedert.Equal(String, cli.Get("TestSetEx_string"));

            cli.SetEx("TestSetEx_bytes", 10, Bytes);
            replacedert.Equal(Bytes, cli.Get<byte[]>("TestSetEx_bytes"));

            cli.SetEx("TestSetEx_clreplaced", 10, Clreplaced);
            replacedert.Equal(JsonConvert.SerializeObject(Clreplaced), JsonConvert.SerializeObject(cli.Get<TestClreplaced>("TestSetEx_clreplaced")));
        }

19 View Source File : ImClient.cs
License : MIT License
Project Creator : 2881099

public string PrevConnectServer(Guid clientId, string clientMetaData)
    {
        var server = SelectServer(clientId);
        var token = $"{Guid.NewGuid()}{Guid.NewGuid()}{Guid.NewGuid()}{Guid.NewGuid()}".Replace("-", "");
        _redis.Set($"{_redisPrefix}Token{token}", JsonConvert.SerializeObject((clientId, clientMetaData)), 10);
        return $"ws://{server}{_pathMatch}?token={token}";
    }

19 View Source File : ImClient.cs
License : MIT License
Project Creator : 2881099

public void SendMessage(Guid senderClientId, IEnumerable<Guid> receiveClientId, object message, bool receipt = false)
    {
        receiveClientId = receiveClientId.Distinct().ToArray();
        Dictionary<string, ImSendEventArgs> redata = new Dictionary<string, ImSendEventArgs>();

        foreach (var uid in receiveClientId)
        {
            string server = SelectServer(uid);
            if (redata.ContainsKey(server) == false) redata.Add(server, new ImSendEventArgs(server, senderClientId, message, receipt));
            redata[server].ReceiveClientId.Add(uid);
        }
        var messageJson = JsonConvert.SerializeObject(message);
        foreach (var sendArgs in redata.Values)
        {
            OnSend?.Invoke(this, sendArgs);
            _redis.Publish($"{_redisPrefix}Server{sendArgs.Server}",
                JsonConvert.SerializeObject((senderClientId, sendArgs.ReceiveClientId, messageJson, sendArgs.Receipt)));
        }
    }

19 View Source File : Startup.cs
License : MIT License
Project Creator : 2881099

public void Configure(IApplicationBuilder app)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            Console.OutputEncoding = Encoding.GetEncoding("GB2312");
            Console.InputEncoding = Encoding.GetEncoding("GB2312");

            app.UseDeveloperExceptionPage();

            app.UseRouting();
            app.UseEndpoints(config => config.MapControllers());
            app.UseDefaultFiles();
            app.UseStaticFiles();

            ImHelper.Initialization(new ImClientOptions
            {
                Redis = new FreeRedis.RedisClient("127.0.0.1:6379,poolsize=10"),
                Servers = new[] { "127.0.0.1:6001" }
            });

            ImHelper.Instance.OnSend += (s, e) => 
                Console.WriteLine($"ImClient.SendMessage(server={e.Server},data={JsonConvert.SerializeObject(e.Message)})");

            ImHelper.EventBus(
                t =>
                {
                    Console.WriteLine(t.clientId + "上线了");
                    var onlineUids = ImHelper.GetClientListByOnline();
                    ImHelper.SendMessage(t.clientId, onlineUids, $"用户{t.clientId}上线了");
                }, 
                t => Console.WriteLine(t.clientId + "下线了"));
        }

19 View Source File : KissManga.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public override void _Create(string mangaUrl)
        {
            id = mangaUrl;
            string replacedle = KissMangaHelper.GetName(mangaUrl);
            string lang_code = "gb"; // Not that it matters for KissManga

            FileHelper.CreateFolder(FileHelper.APP_ROOT, KissMangaHelper.GetUrlName(mangaUrl));

            MangaInfo info = new MangaInfo()
            {
                Type = "manga",
                Source = "kissmanga",
                Id = KissMangaHelper.GetUrlName(mangaUrl),
                Name = replacedle,
                LangCode = lang_code,
                Group = "^any-group",
                UserName = replacedle,
                Chapter = "1",
                Page = "1",
                Latest = "1"
            };

            string output = JsonConvert.SerializeObject(info);
            File.WriteAllText(Path.Combine(mangaRoot.FullName, "manga.json"), output);

            _Load(false);
            GetSetPrunedChapters(true);
        }

19 View Source File : KissManga.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public override void Save(string chapter, string page)
        {
            this.currentchapter = chapter;
            this.currentpage = page;

            MangaInfo info = new MangaInfo()
            {
                Type = "manga",
                Source = "kissmanga",
                Id = mangaRoot.Name,
                Name = name,
                LangCode = userlang,
                Group = usergroup,
                UserName = userreplacedle,
                Chapter = chapter,
                Page = page,
                Latest = lastchapter
            };

            string output = JsonConvert.SerializeObject(info);
            File.WriteAllText(Path.Combine(mangaRoot.FullName, "manga.json"), output);
        }

19 View Source File : MangaDex.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public override void _Create(string mangaUrl)
        {
            id = mangaUrl;
            string jsonText = MangaDexHelper.GetMangaJSON(mangaUrl);

            JObject jobj = JObject.Parse(jsonText);
            string replacedle = (string)jobj["manga"]["replacedle"];

            string lang_code = "gb";

            FileHelper.CreateFolder(FileHelper.APP_ROOT, MangaDexHelper.GetMangaID(mangaUrl));

            MangaInfo info = new MangaInfo()
            {
                Type = "manga",
                Source = "mangadex",
                Id = MangaDexHelper.GetMangaID(mangaUrl),
                Name = replacedle,
                LangCode = lang_code,
                Group = "^any-group",
                UserName = replacedle,
                Chapter = "1",
                Page = "1",
                Latest = "1"
            };

            string output = JsonConvert.SerializeObject(info);
            File.WriteAllText(Path.Combine(mangaRoot.FullName, "manga.json"), output);            

            _Load(false);
            GetSetPrunedChapters(true);
        }

19 View Source File : MangaDex.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public override void Save(string chapter, string page)
        {
            this.currentchapter = chapter;
            this.currentpage = page;

            MangaInfo info = new MangaInfo()
            {
                Type = "manga",
                Source = "mangadex",
                Id = mangaRoot.Name,
                Name = name,
                LangCode = userlang,
                Group = usergroup,
                UserName = userreplacedle,
                Chapter = chapter,
                Page = page,
                Latest = lastchapter
            };

            string output = JsonConvert.SerializeObject(info);
            File.WriteAllText(Path.Combine(mangaRoot.FullName, "manga.json"), output);
        }

19 View Source File : Nhentai.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public override void _Create(string mangaUrl)
        {
            FileHelper.CreateFolder(FileHelper.APP_ROOT, "h" + id);

            MangaInfo info = new MangaInfo()
            {
                Type = "hentai",
                Source = "nhentai",
                Id = id,
                Name = name,
                UserName = userreplacedle,
                Chapter = "1",
                Page = "1"
            };

            string output = JsonConvert.SerializeObject(info);            
            File.WriteAllText(Path.Combine(hentaiRoot.FullName, "manga.json"), output);

            DirectoryInfo chapDir = FileHelper.CreateFolder(hentaiRoot, "1");
            chapters.Add(new Chapter(chapDir, id, "1", true));

            _Load();
        }

19 View Source File : Nhentai.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public override void Save(string chapter, string page)
        {
            this.currentchapter = chapter;
            this.currentpage = page;

            MangaInfo info = new MangaInfo()
            {
                Type = "hentai",
                Source = "nhentai",
                Id = hentaiRoot.Name,
                Name = name,
                UserName = userreplacedle,
                Chapter = chapter,
                Page = page
            };

            string output = JsonConvert.SerializeObject(info);
            File.WriteAllText(Path.Combine(hentaiRoot.FullName, "manga.json"), output);
        }

19 View Source File : BitfinexApi.cs
License : MIT License
Project Creator : aabiryukov

private string GetRestResponse(BitfinexPostBase obj)
		{
			HttpRequestMessage request;
			{
				var jsonObj = JsonConvert.SerializeObject(obj);
				var payload = Convert.ToBase64String(Encoding.UTF8.GetBytes(jsonObj));
				request = new HttpRequestMessage(HttpMethod.Post, obj.Request);
				request.Headers.Add(ApiBfxKey, ApiKey);
				request.Headers.Add(ApiBfxPayload, payload);
				request.Headers.Add(ApiBfxSig, GetHexHashSignature(payload));
			}

			var responseMessage = WebApi.Client.SendAsync(request).Result;
			var response = responseMessage.Content.ReadreplacedtringAsync().Result;

			CheckResultCode(responseMessage.StatusCode, response);

			return response;
		}

19 View Source File : BitfinexSocketApi.cs
License : MIT License
Project Creator : aabiryukov

public BitfinexApiResult<long> SubscribeToTrades(string symbol, Action<BitfinexTradeSimple[]> handler)
        {
            lock (subscriptionLock)
            {
                var registration = new BitfinexTradeEventRegistration()
                {
                    Id = registrationId,
                    ChannelName = "trades",
                    Handler = handler
                };
                AddEventRegistration(registration);

                socket.Send(JsonConvert.SerializeObject(new BitfinexTradeSubscribeRequest(symbol)));

                return WaitSubscription(registration);
            }
        }

19 View Source File : BitfinexSocketApi.cs
License : MIT License
Project Creator : aabiryukov

private void Authenticate()
        {
            var n = nonce;
            var authentication = new BitfinexAuthentication()
            {
                Event = "auth",
                ApiKey = ApiKey,
                Nonce = n,
                Payload = "AUTH" + n
            };
            authentication.Signature = GetHexHashSignature(authentication.Payload);

            socket.Send(JsonConvert.SerializeObject(authentication));
        }

19 View Source File : BitfinexSocketApi.cs
License : MIT License
Project Creator : aabiryukov

public BitfinexApiResult<long> SubscribeToTradingPairTicker(string symbol, Action<BitfinexSocketTradingPairTick> handler)
        {
            lock (subscriptionLock)
            {
                var registration = new BitfinexTradingPairTickerEventRegistration()
                {
                    Id = registrationId,
                    ChannelName = "ticker",
                    Handler = handler
                };
                AddEventRegistration(registration);
                
                socket.Send(JsonConvert.SerializeObject(new BitfinexTickerSubscribeRequest(symbol)));

                return WaitSubscription(registration);
            }
        }

19 View Source File : BitfinexSocketApi.cs
License : MIT License
Project Creator : aabiryukov

public BitfinexApiResult<long> SubscribeToFundingPairTicker(string symbol, Action<BitfinexSocketFundingPairTick> handler)
        {
            lock (subscriptionLock)
            {
                var registration = new BitfinexFundingPairTickerEventRegistration()
                {
                    Id = registrationId,
                    ChannelName = "ticker",
                    Handler = handler
                };
                AddEventRegistration(registration);
                
                socket.Send(JsonConvert.SerializeObject(new BitfinexTickerSubscribeRequest(symbol)));

                return WaitSubscription(registration);
            }
        }

19 View Source File : BitfinexSocketApi.cs
License : MIT License
Project Creator : aabiryukov

public BitfinexApiResult<long> SubscribeToOrderBooks(string symbol, Action<BitfinexSocketOrderBook[]> handler, Precision precision = Precision.P0, Frequency frequency = Frequency.F0, int length = 25)
        {
            lock (subscriptionLock)
            {
                var registration = new BitfinexOrderBooksEventRegistration()
                {
                    Id = registrationId,
                    ChannelName = "book",
                    Handler = handler
                };
                AddEventRegistration(registration);

                var msg = JsonConvert.SerializeObject(new BitfinexBookSubscribeRequest(symbol, precision.ToString(), frequency.ToString(), length));
                socket.Send(msg);

                return WaitSubscription(registration);
            }
        }

19 View Source File : Host.cs
License : MIT License
Project Creator : acandylevey

public void GenerateManifest(string description, string[] allowedOrigins, bool overwrite = false)
        {
            if (File.Exists(ManifestPath) && !overwrite)
            {
                Log.LogMessage("Manifest exists already");
            }
            else
            {
                Log.LogMessage("Generating Manifest");

                string manifest = JsonConvert.SerializeObject(new Manifest(Hostname, description, Utils.replacedemblyExecuteablePath(), allowedOrigins));
                File.WriteAllText(ManifestPath, manifest);

                Log.LogMessage("Manifest Generated");
            }
        }

19 View Source File : SpeechRecognitionService.cs
License : MIT License
Project Creator : ActiveNick

private ArraySegment<byte> CreateSpeechConfigMessagePayloadBuffer(string requestId)
        {
            dynamic SpeechConfigPayload = CreateSpeechConfigPayload();

            // Convert speech.config payload to JSON
            var SpeechConfigPayloadJson = JsonConvert.SerializeObject(SpeechConfigPayload, Formatting.None);

            // Create speech.config message from required headers and JSON payload
            StringBuilder speechMsgBuilder = new StringBuilder();
            speechMsgBuilder.Append("path:speech.config" + lineSeparator);
            speechMsgBuilder.Append("x-requestid:" + requestId + lineSeparator);
            speechMsgBuilder.Append($"x-timestamp:{DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffK")}" + lineSeparator);
            speechMsgBuilder.Append($"content-type:application/json; charset=utf-8" + lineSeparator);
            speechMsgBuilder.Append(lineSeparator);
            speechMsgBuilder.Append(SpeechConfigPayloadJson);
            var strh = speechMsgBuilder.ToString();

            var encoded = Encoding.UTF8.GetBytes(speechMsgBuilder.ToString());
            var buffer = new ArraySegment<byte>(encoded, 0, encoded.Length);
            return buffer;
        }

19 View Source File : Client.cs
License : MIT License
Project Creator : adamped

public void UpdateRow(ClientTableSchema row)
		{
			var dbRow = _rows.Single(x => x.Id == row.Id);

			if (string.IsNullOrEmpty(dbRow.Original))
				dbRow.Original = JsonConvert.SerializeObject(row);

			dbRow.Name = row.Name;
			dbRow.Description = row.Description;
			dbRow.LastUpdated = DateTimeOffset.Now;
		}

19 View Source File : Core.Object.cs
License : MIT License
Project Creator : adamtcroft

public static Dictionary<string, object> Get(WwiseValues.Get get, WwiseValues.GetTransform transform = null)
                {
                    if (packet.results != null)
                        packet.results.Clear();

                    GetWrapper wrapper = new GetWrapper();
                    wrapper.id = get.objectArray;
                    //wrapper.from = new Dictionary<string, object>();
                    //wrapper.from.Add("id", wrapper.id);

                    string json = JsonConvert.SerializeObject(wrapper, Formatting.Indented);
                    packet.keywordArguments.Add("from", json);

                    packet.procedure = "ak.wwise.core.object.get";
                    packet.options.@return = returnValues2017_1_0_6302;
                    results = connection.Execute(packet);
                    packet.Clear();
                    return (Dictionary<string, object>)results;
                }

19 View Source File : Serialization.Save.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat

public static void Append(GNFS gnfs, Relation roughRelation)
                    {
                        if (roughRelation != null && !roughRelation.IsSmooth && !roughRelation.IsPersisted)
                        {
                            string filename = Path.Combine(gnfs.SaveLocations.SaveDirectory, $"{nameof(RelationContainer.RoughRelations)}.json");
                            string json = JsonConvert.SerializeObject(roughRelation, Formatting.Indented);

                            if (FileExists(gnfs))
                            {
                                json += ",";
                            }

                            File.AppendAllText(filename, json);
                            roughRelation.IsPersisted = true;
                        }
                    }

19 View Source File : Serialization.Save.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat

public static void Object(object obj, string filename)
            {
                string saveJson = JsonConvert.SerializeObject(obj, Formatting.Indented);
                File.WriteAllText(filename, saveJson);
            }

19 View Source File : Serialization.Save.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat

public static void Append(GNFS gnfs, Relation relation)
                    {
                        if (relation != null && relation.IsSmooth && !relation.IsPersisted)
                        {
                            string filename = Path.Combine(gnfs.SaveLocations.SaveDirectory, $"{nameof(RelationContainer.SmoothRelations)}.json");
                            string json = JsonConvert.SerializeObject(relation, Formatting.Indented);

                            if (FileExists(gnfs))
                            {
                                json = json.Insert(0, ",");
                            }

                            File.AppendAllText(filename, json);

                            gnfs.CurrentRelationsProgress.SmoothRelationsCounter += 1;

                            relation.IsPersisted = true;
                        }
                    }

19 View Source File : Serialization.Save.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat

public static void AppendList(GNFS gnfs, List<Relation> roughRelations)
                    {
                        if (roughRelations != null && roughRelations.Any())
                        {
                            string filename = Path.Combine(gnfs.SaveLocations.SaveDirectory, $"{nameof(RelationContainer.RoughRelations)}.json");
                            string json = JsonConvert.SerializeObject(roughRelations, Formatting.Indented);
                            json = json.Replace("[", "").Replace("]", ",");
                            File.AppendAllText(filename, json);
                            roughRelations.ForEach(rel => rel.IsPersisted = true);
                        }
                    }

19 View Source File : SendEmailConverter.cs
License : MIT License
Project Creator : afaniuolo

public override string ConvertValue(string sourceValue)
		{
			// example of sourceValue
			// <host>example.host</host><from>[email protected]</from><isbodyhtml>true</isbodyhtml><to>[email protected]</to><cc>[email protected]</cc><bcc>[email protected]</bcc><localfrom>[email protected]</localfrom><subject>This is the subject of the email.</subject><mail><p>This is the body of the email.</p><p>[<label id="{CFA55E36-3018-41A4-9F4D-2EA1293D5902}">Single-Line Text</label>]</p></mail>
			var host = XmlHelper.GetXmlElementValue(sourceValue, "host", true);
			var from = XmlHelper.GetXmlElementValue(sourceValue, "from", true);
			var isbodyhtml = XmlHelper.GetXmlElementValue(sourceValue, "isbodyhtml", true);
			var to = XmlHelper.GetXmlElementValue(sourceValue, "to", true);
			var cc = XmlHelper.GetXmlElementValue(sourceValue, "cc", true);
			var bcc = XmlHelper.GetXmlElementValue(sourceValue, "bcc", true);
			var localfrom = XmlHelper.GetXmlElementValue(sourceValue, "localfrom", true);
			var subject = ConvertFieldTokens(XmlHelper.GetXmlElementValue(sourceValue, "subject", true));
			var mail = ConvertFieldTokens(XmlHelper.GetXmlElementValue(sourceValue, "mail", true));

			var fromValue = !string.IsNullOrEmpty(from) ? from : localfrom;

			return JsonConvert.SerializeObject(new
				SendEmailAction() {
				from = fromValue,
				to = to,
				cc = cc,
				bcc = bcc,
				subject = subject,
				body = mail
			});
		}

19 View Source File : MainWindow.cs
License : GNU General Public License v3.0
Project Creator : aglab2

private void SaveLayout(string name)
        {
            ld.Trim();

            var redOutline = ld.redOutline;
            var greenOutline = ld.greenOutline;
            var invertedStar = ld.invertedStar;
            ld.invertedStar = null;
            ld.greenOutline = null;
            ld.redOutline = null;
            var json = JsonConvert.SerializeObject(ld);
            ld.invertedStar = invertedStar;
            ld.greenOutline = greenOutline;
            ld.redOutline = redOutline;

            File.WriteAllText(name, json);
        }

19 View Source File : UserConfiguration.cs
License : MIT License
Project Creator : aivarasatk

public void SaveSettings<T>(T settings) where T: clreplaced
        {
            try
            {
                var res = JsonConvert.SerializeObject(settings, Formatting.Indented);

                var path = settings switch
                {
                    Search => _searchSettingsPath,
                    Window => _windowSettingsPath,
                    AutoComplete => _autoCompleteSettingsPath,
                    _ => throw new NotImplementedException("Settings type not found"),
                };

                File.WriteAllText(path, res);
            }

19 View Source File : ObjectStore.cs
License : MIT License
Project Creator : AkiniKites

public static void AddObject<T>(this Patch patch, T obj, string name)
        {
            var json = JsonConvert.SerializeObject(obj, JsonHelper.Converters);
            using var ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
            patch.AddFile(ms, $"{Prefix}{name}");
        }

19 View Source File : GameCache.cs
License : MIT License
Project Creator : AkiniKites

public void Save(T data)
        {
            var cache = new CacheData()
            {
                Path = IoC.Settings.GamePath,
                Version = IoC.CurrentVersion.ToString(),
                Data = data
            };
            var json = JsonConvert.SerializeObject(cache,
                Formatting.Indented, JsonHelper.Converters);

            CheckDirectory();

            var cacheLock = _cacheLocks.GetOrAdd(CachePath, x => new ReaderWriterLockSlim());
            using (cacheLock.UsingWriterLock())
                File.WriteAllText(CachePath, json);

            IoC.Notif.CacheUpdate?.Invoke();
        }

19 View Source File : SettingsManager.cs
License : MIT License
Project Creator : AkiniKites

private static void Save(UserSettings settings)
        {
            try
            {
                _lock.Wait();

                Paths.CheckDirectory(ApplicationSettingsPath);

                using var backup = new FileBackup(SettingsPath);

                var json = JsonConvert.SerializeObject(settings, Formatting.Indented);
                File.WriteAllText(SettingsPath, json);

                backup.Delete();
            }
            finally
            {
                _lock.Release();
            }
        }

19 View Source File : CharacterReferences.cs
License : MIT License
Project Creator : AkiniKites

public void SearchDir(string path)
        {
            var search = new ByteSearch(path, LoadResults()?.Select(x => x.File));
            
            var charGen = new CharacterGenerator();
            var models = charGen.GetCharacterModels(true);
            models.AddRange(charGen.GetCharacterModels(false));

            var modelPatterns = models.Select(x => (x, x.Id.ToBytes())).ToList();
            
            var processed = new BlockingCollection<ByteSearchResult<CharacterModel>>();
            TrackProgress(processed);

            search.Search(modelPatterns, result =>
            {
                foreach (var item in result.Results)
                    Console.WriteLine($"{item.Key} -> {result.File}");
                processed.Add(result);
            });

            processed.CompleteAdding();

            var results = LoadResults().Where(x => x.Found);
            var refs = new Dictionary<Model, HashSet<string>>();
            foreach (var result in results)
            {
                foreach (var entry in result.Results)
                {
                    if (!refs.TryGetValue(entry.Key, out var files))
                    {
                        files = new HashSet<string>();
                        refs.Add(entry.Key, files);
                    }

                    var fileName = result.File.Substring(path.Length + 1).Replace("\\", "/");
                    if (fileName.EndsWith(".core"))
                        fileName = fileName.Substring(0, fileName.Length - 5);

                    files.Add(fileName);
                }
            }

            var references = refs.Select(x => new CharacterReference()
            {
                Source = x.Key.Source,
                Name = x.Key.Name,
                Files = x.Value.ToArray()
            });
            var json = JsonConvert.SerializeObject(references, Formatting.Indented);
            File.WriteAllText(ReferencesFile, json);
        }

19 View Source File : CharacterReferences.cs
License : MIT License
Project Creator : AkiniKites

private void SaveResults(List<ByteSearchResult<CharacterModel>> results)
        {
            lock (_lock)
            {
                var json = JsonConvert.SerializeObject(results,
                Formatting.Indented, JsonHelper.Converters);
                using (var fb = new FileBackup(ResultsFile))
                {
                    File.WriteAllText(ResultsFile, json);
                    fb.Delete();
                }
            }
        }

19 View Source File : ActionMods.cs
License : MIT License
Project Creator : AlbertMN

public static Tuple<bool, string, bool> ExecuteModAction(string name, string parameter = "") {
            MainProgram.DoDebug("[MOD ACTION] Running mod action \"" + name + "\"");
            string actionErrMsg = "No error message set",
                modLocation = Path.Combine(MainProgram.actionModsPath, modActions[name]),
                infoJsonFile = Path.Combine(modLocation, "info.json");

            if (File.Exists(infoJsonFile)) {
                string modFileContent = ReadInfoFile(infoJsonFile);
                if (modFileContent != null) {
                    try {
                        dynamic jsonTest = JsonConvert.DeserializeObject<dynamic>(modFileContent);
                        if (jsonTest != null) {
                            if (ValidateInfoJson(jsonTest)) {
                                //JSON is valid - get script file
                                string scriptFile = jsonTest["options"]["file_name"], scriptFileLocation = Path.Combine(modLocation, scriptFile);
                                bool actionIsFatal = jsonTest["options"]["is_fatal"] ?? false,
                                    requiresParameter = jsonTest["options"]["requires_param"] ?? false,
                                    requiresSecondaryParameter = jsonTest["options"]["require_second_param"] ?? false;

                                if (requiresParameter ? !String.IsNullOrEmpty(parameter) : true) {
                                    Console.WriteLine("Requires parameter? " + requiresParameter);
                                    Console.WriteLine("Has parameter? " + !String.IsNullOrEmpty(parameter));

                                    string[] secondaryParameters = ActionChecker.GetSecondaryParam(parameter);
                                    if (requiresSecondaryParameter ? secondaryParameters.Length > 1 : true) { //Also returns the first parameter
                                        if (File.Exists(scriptFileLocation)) {
                                            string accArg = requiresParameter && requiresSecondaryParameter ? JsonConvert.SerializeObject(ActionChecker.GetSecondaryParam(parameter)) : (requiresParameter ? parameter : "");

                                            try {
                                                ProcessStartInfo p = new ProcessStartInfo {
                                                    UseShellExecute = false,
                                                    CreateNoWindow = true,
                                                    RedirectStandardOutput = true,
                                                    RedirectStandardError = true
                                                };

                                                string theExtension = Path.GetExtension(scriptFile);

                                                if (theExtension == ".ps1") {
                                                    //Is powershell - open it correctly
                                                    p.FileName = "powershell.exe";
                                                    p.Arguments = String.Format("-WindowStyle Hidden -file \"{0}\" \"{1}\"", scriptFileLocation, accArg);
                                                } else if (theExtension == ".py") {
                                                    //Python - open it correctly
                                                    string minPythonVersion = (jsonTest["options"]["min_python_version"] ?? ""),
                                                        maxPythonVersion = (jsonTest["options"]["max_python_version"] ?? ""),
                                                        pythonPath = GetPythonPath(minPythonVersion, maxPythonVersion);

                                                    if (pythonPath != "") {
                                                        p.FileName = GetPythonPath();
                                                        p.Arguments = String.Format("{0} \"{1}\"", scriptFileLocation, accArg);
                                                    } else {
                                                        //No python version (or one with the min-max requirements) not found.
                                                        string pythonErr;

                                                        if (minPythonVersion == "" && maxPythonVersion == "") {
                                                            //Python just not found
                                                            pythonErr = "We could not locate Python on your computer. Please either download Python or specify its path in the ACC settings if it's already installed.";
                                                        } else {
                                                            if (minPythonVersion != "" && maxPythonVersion != "") {
                                                                //Both min & max set
                                                                pythonErr = "We could not locate a version of Python between v" + minPythonVersion + " and v" + maxPythonVersion + ". Please either download a version of Python in between the specified versions, or specify its path in the ACC settings if it's already installed.";
                                                            } else {
                                                                if (minPythonVersion != "") {
                                                                    //Min only
                                                                    pythonErr = "We could not locate a version of Python greater than v" + minPythonVersion + ". Please either download Python (min version " + minPythonVersion + ") or specify its path in the ACC settings if it's already installed.";
                                                                } else {
                                                                    //Max only
                                                                    pythonErr = "We could not locate a version of Python lower than v" + maxPythonVersion + ". Please either download Python (max version " + maxPythonVersion + ") or specify its path in the ACC settings if it's already installed.";
                                                                }
                                                            }
                                                        }

                                                        return Tuple.Create(false, pythonErr, false);
                                                    }
                                                } else if (theExtension == ".bat" || theExtension == ".cmd" || theExtension == ".btm") {
                                                    //Is batch - open it correctly (https://en.wikipedia.org/wiki/Batch_file#Filename_extensions)
                                                    p.FileName = "cmd.exe";
                                                    p.Arguments = String.Format("/c {0} \"{1}\"", scriptFileLocation, accArg);
                                                } else {
                                                    //"Other" filetype. Simply open file.
                                                    p.FileName = scriptFileLocation;
                                                    p.Arguments = accArg;
                                                }

                                                Process theP = Process.Start(p);

                                                if (!theP.WaitForExit(5000)) {
                                                    MainProgram.DoDebug("Action mod timed out");
                                                    theP.Kill();
                                                }
                                                string output = theP.StandardOutput.ReadToEnd();

                                                using (StringReader reader = new StringReader(output)) {
                                                    string line;
                                                    while ((line = reader.ReadLine()) != null) {
                                                        if (line.Length >= 17) {
                                                            if (line.Substring(0, 12) == "[ACC RETURN]") {
                                                                //Return for ACC
                                                                string returnContent = line.Substring(13),
                                                                    comment = returnContent.Contains(',') ? returnContent.Split(',')[1] : "";
                                                                bool actionSuccess = returnContent.Substring(0, 4) == "true";

                                                                if (comment.Length > 0 && char.IsWhiteSpace(comment, 0)) {
                                                                    comment = comment.Substring(1);
                                                                }

                                                                if (actionSuccess) {
                                                                    //Action was successfull
                                                                    Console.WriteLine("Action successful!");
                                                                } else {
                                                                    //Action was not successfull
                                                                    Console.WriteLine("Action failed :(");
                                                                }

                                                                Console.WriteLine("Comment; " + comment);
                                                                return Tuple.Create(actionSuccess, (comment.Length > 0 ? comment : "Action mod returned no reason for failing"), actionIsFatal);
                                                            }
                                                        }
                                                    }
                                                }

                                                return Tuple.Create(false, "Action mod didn't return anything to ACC", false);
                                            } catch (Exception e) {
                                                //Process init failed - it shouldn't, but better safe than sorry
                                                actionErrMsg = "Process initiation failed";
                                                Console.WriteLine(e);
                                            }
                                        } else {
                                            //Script file doesn't exist
                                            actionErrMsg = "Action mod script doesn't exist";
                                        }
                                    } else {
                                        actionErrMsg = "Action \"" + name + "\" requires a secondary parameter to be set";
                                    }
                                } else {
                                    actionErrMsg = "Action \"" + name + "\" requires a parameter to be set";
                                }
                            } else {
                                //JSON is not valid; validateErrMsg
                                actionErrMsg = validateErrMsg;
                            }
                        } else {
                            //JSON is invalid or failed
                            actionErrMsg = "Action mod JSON is invalid";
                        }
                    } catch (Exception e) {
                        //Failed to parse
                        actionErrMsg = "Failed to parse action mod JSON";
                        Console.WriteLine(e.Message);
                    }
                } else {
                    //Couldn't read file
                    MainProgram.DoDebug("1");
                }
            } else {
                MainProgram.DoDebug("0; " + modLocation);
            }

            return Tuple.Create(false, actionErrMsg, false);
        }

19 View Source File : JSONSourceComponentModel.cs
License : GNU General Public License v2.0
Project Creator : albertogeniola

public string ToJsonConfig()
        {
            return JsonConvert.SerializeObject(this);
        }

See More Examples