Here are the examples of the csharp api Newtonsoft.Json.JsonConvert.SerializeObject(object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1206 Examples
19
View Source File : MainWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : 00000vish
License : GNU General Public License v3.0
Project Creator : 00000vish
internal static void writeAccountData()
{
Account[] accArray = new Account[AccountController.userAccounts.Count];
for (int i = 0; i < AccountController.userAccounts.Count; i++)
{
UserAccount item = (UserAccount)AccountController.userAccounts[i];
accArray[i] = new Account { username = item.username, preplacedword = item.preplacedword , desktopAuth = item.desktopAuth };
}
string json = JsonConvert.SerializeObject(new jsonObject { count = accArray.Length, accounts = accArray });
System.IO.File.WriteAllText(SAVE_FILE_NAME, json);
}
19
View Source File : Settings.xaml.cs
License : GNU General Public License v3.0
Project Creator : 00000vish
License : GNU General Public License v3.0
Project Creator : 00000vish
public static void updateSettingFile()
{
string json = JsonConvert.SerializeObject(jsonSetting);
System.IO.File.WriteAllText(SETTING_FILE, json);
}
19
View Source File : TestBase.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public override string ToString() {
return Newtonsoft.Json.JsonConvert.SerializeObject(this);
}
19
View Source File : APIReturn.cs
License : Apache License 2.0
Project Creator : 2881099
License : Apache License 2.0
Project Creator : 2881099
private void Jsonp(ActionContext context) {
string __callback = context.HttpContext.Request.HasFormContentType ? context.HttpContext.Request.Form["__callback"].ToString() : null;
if (string.IsNullOrEmpty(__callback)) {
this.ContentType = "text/json;charset=utf-8;";
this.Content = JsonConvert.SerializeObject(this);
} else {
this.ContentType = "text/html;charset=utf-8";
this.Content = $"<script>top.{__callback}({GlobalExtensions.Json(null, this)});</script>";
}
}
19
View Source File : GlobalExtensions.cs
License : Apache License 2.0
Project Creator : 2881099
License : Apache License 2.0
Project Creator : 2881099
public static object Json(this Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper html, object obj) {
string str = JsonConvert.SerializeObject(obj);
if (!string.IsNullOrEmpty(str)) str = Regex.Replace(str, @"<(/?script[\s>])", "<\"+\"$1", RegexOptions.IgnoreCase);
if (html == null) return str;
return html.Raw(str);
}
19
View Source File : Program.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
19
View Source File : Utils.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static Task Jsonp(HttpContext context, object options) {
string __callback = context.Request.HasFormContentType ? context.Request.Form["__callback"].ToString() : null;
if (string.IsNullOrEmpty(__callback)) {
context.Response.ContentType = "text/json;charset=utf-8;";
return context.Response.WriteAsync(JsonConvert.SerializeObject(options));
} else {
context.Response.ContentType = "text/html;charset=utf-8";
return context.Response.WriteAsync($"<script>top.{__callback}({JsonConvert.SerializeObject(options)});</script>");
}
}
19
View Source File : TccMaster.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
TccMaster<TDBKey> Then(Type tccUnitType, object state)
{
if (tccUnitType == null) throw new ArgumentNullException(nameof(tccUnitType));
var unitTypeBase = typeof(TccUnit<>);
if (state == null && tccUnitType.BaseType.GetGenericTypeDefinition() == typeof(TccUnit<>)) unitTypeBase = unitTypeBase.MakeGenericType(tccUnitType.BaseType.GetGenericArguments()[0]);
else unitTypeBase = unitTypeBase.MakeGenericType(state.GetType());
if (unitTypeBase.IsreplacedignableFrom(tccUnitType) == false) throw new ArgumentException($"{tccUnitType.DisplayCsharp(false)} 必须继承 {unitTypeBase.DisplayCsharp(false)}");
var unitCtors = tccUnitType.GetConstructors();
if (unitCtors.Length != 1 && unitCtors[0].GetParameters().Length > 0) throw new ArgumentException($"{tccUnitType.FullName} 不能使用构造函数");
var unitTypeConved = Type.GetType(tccUnitType.replacedemblyQualifiedName);
if (unitTypeConved == null) throw new ArgumentException($"{tccUnitType.FullName} 无效");
var unit = unitTypeConved.CreateInstanceGetDefaultValue() as ITccUnit;
(unit as ITccUnitSetter)?.SetState(state);
_thenUnits.Add(unit);
_thenUnitInfos.Add(new TccUnitInfo
{
Description = unitTypeConved.GetDescription(),
Index = _thenUnitInfos.Count + 1,
Stage = TccUnitStage.Try,
State = state == null ? null : Newtonsoft.Json.JsonConvert.SerializeObject(state),
StateTypeName = state?.GetType().replacedemblyQualifiedName,
Tid = _tid,
TypeName = tccUnitType.replacedemblyQualifiedName,
});
return this;
}
19
View Source File : TaskBuild.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
[JSFunction]
public string GetDataBaseAll()
{
var data = Curd.DataBase.Select
.ToList(a => new Ztree
{
id = a.Id,
name = a.Name,
open = false
});
return JsonConvert.SerializeObject(new { code = 0, data });
}
19
View Source File : TaskBuild.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
[JSFunction]
public string GetDataBase(string id, string tableName, int level)
{
DataBaseConfig model = null;
try
{
var data = new object();
if (Guid.TryParse(id, out Guid gid) && gid != Guid.Empty)
{
model = Curd.DataBase.Select.WhereDynamic(gid).ToOne();
using (IFreeSql fsql = new FreeSql.FreeSqlBuilder().UseConnectionString(model.DataType,
model.ConnectionStrings).Build())
{
if (level == 0)
{
var res = fsql.DbFirst.GetDatabases();
if (!string.IsNullOrEmpty(model.DataBaseName))
{
res = res.Where(a => a.ToUpper() == model.DataBaseName.ToUpper()).ToList();
}
data = res.Select(a => new
{
id = gid,
name = a,
children = fsql.DbFirst.GetTablesByDatabase(a).Select(b => new
{
id = gid,
name = b.Name
}).ToList()
}).ToList();
}
else
{
var res = fsql.DbFirst.GetTablesByDatabase(tableName);
data = res.Select(a => new { name = a.Name }).ToList();
}
}
}
return JsonConvert.SerializeObject(new { code = 0, data });
}
catch (Exception e)
{
return JsonConvert.SerializeObject(new { code = 1, msg = e.Message + "<br/> 数据库连接串:" + model?.ConnectionStrings });
}
}
19
View Source File : SagaMaster.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
SagaMaster<TDBKey> Then(Type sagaUnitType, object state)
{
if (sagaUnitType == null) throw new ArgumentNullException(nameof(sagaUnitType));
var unitTypeBase = typeof(SagaUnit<>);
if (state == null && sagaUnitType.BaseType.GetGenericTypeDefinition() == typeof(SagaUnit<>)) unitTypeBase = unitTypeBase.MakeGenericType(sagaUnitType.BaseType.GetGenericArguments()[0]);
else unitTypeBase = unitTypeBase.MakeGenericType(state.GetType());
if (unitTypeBase.IsreplacedignableFrom(sagaUnitType) == false) throw new ArgumentException($"{sagaUnitType.DisplayCsharp(false)} 必须继承 {unitTypeBase.DisplayCsharp(false)}");
var unitCtors = sagaUnitType.GetConstructors();
if (unitCtors.Length != 1 && unitCtors[0].GetParameters().Length > 0) throw new ArgumentException($"{sagaUnitType.FullName} 不能使用构造函数");
var unitTypeConved = Type.GetType(sagaUnitType.replacedemblyQualifiedName);
if (unitTypeConved == null) throw new ArgumentException($"{sagaUnitType.FullName} 无效");
var unit = unitTypeConved.CreateInstanceGetDefaultValue() as ISagaUnit;
(unit as ISagaUnitSetter)?.SetState(state);
_thenUnits.Add(unit);
_thenUnitInfos.Add(new SagaUnitInfo
{
Description = unitTypeConved.GetDescription(),
Index = _thenUnitInfos.Count + 1,
Stage = SagaUnitStage.Commit,
State = state == null ? null : Newtonsoft.Json.JsonConvert.SerializeObject(state),
StateTypeName = state?.GetType().replacedemblyQualifiedName,
Tid = _tid,
TypeName = sagaUnitType.replacedemblyQualifiedName,
});
return this;
}
19
View Source File : RepositoryTests.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
[Fact]
public void UpdateAttach() {
var repos = g.sqlite.GetGuidRepository<AddUpdateInfo>();
var item = new AddUpdateInfo { Id = Guid.NewGuid() };
repos.Attach(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 : RepositoryTests.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
[Fact]
public void Update() {
g.sqlite.Insert(new AddUpdateInfo()).ExecuteAffrows();
var repos = g.sqlite.GetGuidRepository<AddUpdateInfo>();
var item = new AddUpdateInfo { Id = g.sqlite.Select<AddUpdateInfo>().First().Id };
item.replacedle = "xxx";
repos.Update(item);
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
}
19
View Source File : TaskBuild.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
[JSFunction]
public string saveTaskBuild(string res)
{
try
{
var model = JsonConvert.DeserializeObject<Models.TaskBuild>(res);
Curd.fsql.SetDbContextOptions(o => o.EnableAddOrUpdateNavigateList = false);
var enreplacedy = Curd.TaskBuild.Insert(model);
model.TaskBuildInfos.ToList().ForEach(a => a.TaskBuildId = enreplacedy.Id);
Curd.TaskBuildInfo.Insert(model.TaskBuildInfos);
var list = Curd.TaskBuild.Select.ToList();
Data.Clear();
Data.AddRange(list);
Data.SaveChanges();
return JsonConvert.SerializeObject(new { code = 0, msg = "构建任务成功" });
}
catch (Exception ex)
{
return JsonConvert.SerializeObject(new { code = 1, msg = ex.Message });
}
}
19
View Source File : ImClient.cs
License : MIT License
Project Creator : 2881099
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 : TaskBuild.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
[JSFunction]
public string GetTemplate()
{
var data = Curd.Templates.Select
.ToList(a => new { a.Id, a.replacedle });
return JsonConvert.SerializeObject(new { code = 0, data });
}
19
View Source File : JsonFile.cs
License : Apache License 2.0
Project Creator : 42skillz
License : Apache License 2.0
Project Creator : 42skillz
public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
TextWriter writer = null;
try
{
var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
writer = new StreamWriter(filePath, append);
writer.Write(contentsToWriteToFile);
}
finally
{
writer?.Close();
}
}
19
View Source File : GUISettings.cs
License : MIT License
Project Creator : a1xd
License : MIT License
Project Creator : a1xd
public void Save()
{
File.WriteAllText(Constants.GuiConfigFileName, JsonConvert.SerializeObject(this));
}
19
View Source File : Host.cs
License : MIT License
Project Creator : acandylevey
License : MIT License
Project Creator : acandylevey
public void Listen()
{
if (!IsRegistered())
throw new NotRegisteredWithBrowserException(Hostname);
JObject data;
while ((data = Read()) != null)
{
Log.LogMessage("Data Received:" + JsonConvert.SerializeObject(data));
if (SendConfirmationReceipt)
SendMessage(new ResponseConfirmation(data).GetJObject());
ProcessReceivedMessage(data);
}
}
19
View Source File : Host.cs
License : MIT License
Project Creator : acandylevey
License : MIT License
Project Creator : acandylevey
public void SendMessage(JObject data)
{
Log.LogMessage("Sending Message:" + JsonConvert.SerializeObject(data));
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data.ToString(Formatting.None));
Stream stdout = Console.OpenStandardOutput();
stdout.WriteByte((byte)((bytes.Length >> 0) & 0xFF));
stdout.WriteByte((byte)((bytes.Length >> 8) & 0xFF));
stdout.WriteByte((byte)((bytes.Length >> 16) & 0xFF));
stdout.WriteByte((byte)((bytes.Length >> 24) & 0xFF));
stdout.Write(bytes, 0, bytes.Length);
stdout.Flush();
}
19
View Source File : ResponseConfirmation.cs
License : MIT License
Project Creator : acandylevey
License : MIT License
Project Creator : acandylevey
public JObject GetJObject()
{
return JsonConvert.DeserializeObject<JObject>(JsonConvert.SerializeObject(this));
}
19
View Source File : ClientTableSchema.cs
License : MIT License
Project Creator : adamped
License : MIT License
Project Creator : adamped
public new ClientTableSchema Clone()
{
var serialized = JsonConvert.SerializeObject(this);
return JsonConvert.DeserializeObject<ClientTableSchema>(serialized);
}
19
View Source File : ServerApi.cs
License : MIT License
Project Creator : adamped
License : MIT License
Project Creator : adamped
public void Insert(TableSchema row)
{
// Just to make sure it has a value if the client doesn't preplaced one through
if (row.LastUpdated == DateTimeOffset.MinValue)
row.LastUpdated = DateTimeOffset.Now;
IList<ColumnChange> changes = new List<ColumnChange>();
changes.Add(new ColumnChange() { Column = nameof(row.Name) });
changes.Add(new ColumnChange() { Column = nameof(row.Description) });
row.RowChanges = JsonConvert.SerializeObject(changes);
_rows.Add(row.Clone());
}
19
View Source File : TableSchema.cs
License : MIT License
Project Creator : adamped
License : MIT License
Project Creator : adamped
public TableSchema Clone()
{
var serialized = JsonConvert.SerializeObject(this);
return JsonConvert.DeserializeObject<TableSchema>(serialized);
}
19
View Source File : Client.cs
License : MIT License
Project Creator : adamped
License : MIT License
Project Creator : adamped
public void DifferentialSync()
{
var changed = _rows.Where(x => x.LastUpdated >= _lastSync || (x.Deleted != null && x.Deleted >= _lastSync)).ToList();
var list = new List<string>();
foreach (var item in changed)
{
var original = JsonConvert.DeserializeObject<TableSchema>(item.Original);
// A better way to implement this is needed. It only detects the first column changed.
// This would need to group them all together and send them.
// But again, this is a sample, I can't do all the work for you :)
// At the moment this will only work with Name or Description
if (original.Name != item.Name)
list.Add(JsonConvert.SerializeObject(new { Id = item.Id, LastUpdated=item.LastUpdated, Name = item.Name }));
else if (original.Description != item.Description)
list.Add(JsonConvert.SerializeObject(new { Id = item.Id, LastUpdated = item.LastUpdated, Description = item.Description }));
item.Original = null; // Clear original as now sync'd
}
_server.DifferentialSync(list);
foreach (var row in _server.PullSync(_lastSync))
if (!_rows.Any(x => x.Id == row.Id)) // Does not exist, hence insert
InsertRow(new ClientTableSchema(row));
else if (row.Deleted.HasValue)
DeleteRow(row.Id);
else
UpdateRow(new ClientTableSchema(row));
_lastSync = DateTimeOffset.Now;
}
19
View Source File : HttpResponse.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public void SendJsonObject(object result, bool compress = true)
{
// json serialize
byte[] bsJson = Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(result));
if (compress)
{
Response.Headers[HttpResponseHeader.ContentEncoding] = "gzip";
bsJson = bfbd.Common.Compress.GZip(bsJson, true);
}
SetExpires(0);
Response.ContentType = "text/json";
Response.ContentEncoding = Encoding.UTF8;
SetDebugHeaders();
Response.OutputStream.Write(bsJson, 0, bsJson.Length);
Response.OutputStream.Flush();
Response.Close();
}
19
View Source File : ResponseExtension.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public static void SendException(this HttpListenerResponse resp, Exception ex, bool detail = false)
{
if (!detail)
{
while (ex.InnerException != null)
ex = ex.InnerException;
}
var obj = new { Exception = (detail ? ex.ToString() : ex.Message) };
byte[] bsJson = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(obj));
SetExpireTime(resp, 0);
WriteFileContent(resp, bsJson, "text/json", false);
}
19
View Source File : ResponseExtension.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public static void SendJsonObject(this HttpListenerResponse resp, object result, bool compress = true)
{
// json serialize
byte[] bsJson = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(result));
SetExpireTime(resp, 0);
WriteFileContent(resp, bsJson, "text/json", compress);
}
19
View Source File : addForm.cs
License : MIT License
Project Creator : ajohns6
License : MIT License
Project Creator : ajohns6
private void addButton_Click(object sender, EventArgs e)
{
PAK pak = new PAK();
pak.modName = this.nameText.Text;
pak.modCreator = this.creatorText.Text;
pak.modType = this.typeCombo.Text;
pak.modDesc = this.descText.Text;
pak.modFile = filename;
pak.modDir = filename.Substring(0, filename.Length - 4);
if (!Directory.Exists(Path.Combine(mainForm.pakDir, "~" + pak.modDir)))
{
Directory.CreateDirectory(Path.Combine(mainForm.pakDir, "~" + pak.modDir));
File.Copy(this.fileText.Text, Path.Combine(mainForm.pakDir, "~" + pak.modDir, pak.modFile));
}
else
{
MessageBox.Show("A directory already exists for this PAK filename.\n\nIf you still wish to add this PAK file, you must either rename this PAK file or delete the existing directory.",
"Directory Already Exists",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
string jsonString = File.ReadAllText(mainForm.localJSON);
var list = JsonConvert.DeserializeObject<List<PAK>>(jsonString);
list.Add(pak);
var convertedJSON = JsonConvert.SerializeObject(list);
File.WriteAllText(mainForm.localJSON, convertedJSON);
this.Close();
}
19
View Source File : mainForm.cs
License : MIT License
Project Creator : ajohns6
License : MIT License
Project Creator : ajohns6
private void removeButton_Click(object sender, EventArgs e)
{
StringCollection removals = new StringCollection();
foreach (DataGridViewRow row in localGrid.Rows)
{
if (Convert.ToBoolean(row.Cells[0].Value))
{
removals.Add(row.Cells[5].Value.ToString());
}
}
foreach (string pak in removals)
{
if (Directory.Exists(Path.Combine(pakDir, pak)))
{
DeleteDirectory(Path.Combine(pakDir, pak));
}
if (Directory.Exists(Path.Combine(pakDir, "~" + pak)))
{
DeleteDirectory(Path.Combine(pakDir, "~" + pak));
}
gridSelections.Remove(pak);
string jsonString = File.ReadAllText(mainForm.localJSON);
var list = JsonConvert.DeserializeObject<List<PAK>>(jsonString);
list.Remove(list.Single( s => s.modDir == pak));
var convertedJSON = JsonConvert.SerializeObject(list);
File.WriteAllText(mainForm.localJSON, convertedJSON);
}
saveSettings();
populateGrid(localJSON);
}
19
View Source File : ConfigLoader.cs
License : MIT License
Project Creator : alexis-
License : MIT License
Project Creator : alexis-
public static void SaveToFile<T>(T obj, string fileName)
{
using (Stream s = File.Open(GetRulesPath(fileName), FileMode.Create, FileAccess.Write))
using (StreamWriter sw = new StreamWriter(s))
{
string json = JsonConvert.SerializeObject(obj);
sw.Write(json);
}
}
19
View Source File : WsRequestBuilder.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public string GetPrivateRequest(string pKey, string sKey)
{
_signer = new Signer(sKey);
_auth = new Auth() { Key = pKey, Method = "api_key", Sign = _signer.SignWs(_wsReuest.Channel, _wsReuest.Event, _wsReuest.Time.ToString()) };
_wsReuest.Auth = _auth;
return JsonConvert.SerializeObject(_wsReuest);
}
19
View Source File : WsRequestBuilder.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public string GetPublicRequest()
{
return JsonConvert.SerializeObject(_wsReuest);
}
19
View Source File : HuobiFuturesServer.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public string ToJson()
{
return JsonConvert.SerializeObject(this);
}
19
View Source File : Map.cs
License : MIT License
Project Creator : AliFlux
License : MIT License
Project Creator : AliFlux
public void AddImage(string id, string base64)
{
var code = "addImage(" + JsonConvert.SerializeObject(id) + ", " + JsonConvert.SerializeObject(base64) + ");";
Execute(code);
}
19
View Source File : Core.cs
License : MIT License
Project Creator : AliFlux
License : MIT License
Project Creator : AliFlux
public static string GetFrameScript(string accessToken, object style)
{
var mainScript = getEmbeddedResource("web.frame.js");
var glScript = getEmbeddedResource("web.mapbox-gl.js");
var css = getEmbeddedResource("web.mapbox-gl.css");
var result = mainScript
.Replace("{{mapbox-gl.js}}", glScript)
.Replace("{{mapbox-gl.css}}", css)
.Replace("{{style}}", JsonConvert.SerializeObject(style))
.Replace("{{accessToken}}", JsonConvert.SerializeObject(accessToken));
return result;
}
19
View Source File : ExpressionBuilder.cs
License : MIT License
Project Creator : AliFlux
License : MIT License
Project Creator : AliFlux
static string serializeObject(object obj)
{
return JsonConvert.SerializeObject(obj);
}
19
View Source File : Renderer.cs
License : MIT License
Project Creator : AliFlux
License : MIT License
Project Creator : AliFlux
public async static Task<BitmapSource> RenderCached(string cachePath, Style style, ICanvas canvas, int x, int y, double zoom, double sizeX = 512, double sizeY = 512, double scale = 1, List<string> whiteListLayers = null)
{
string layerString = whiteListLayers == null ? "" : string.Join(",-", whiteListLayers.ToArray());
var bundle = new
{
style.Hash,
sizeX,
sizeY,
scale,
layerString,
};
lock (cacheLock)
{
if (!Directory.Exists(cachePath))
{
Directory.CreateDirectory(cachePath);
}
}
var json = Newtonsoft.Json.JsonConvert.SerializeObject(bundle);
var hash = Utils.Sha256(json).Substring(0, 12); // get 12 digits to avoid fs length issues
var fileName = x + "x" + y + "-" + zoom + "-" + hash + ".png";
var path = Path.Combine(cachePath, fileName);
lock (cacheLock)
{
if (File.Exists(path))
{
return loadBitmap(path);
}
}
var bitmap = await Render(style, canvas, x, y, zoom, sizeX, sizeY, scale, whiteListLayers);
// save to file in async fashion
var _t = Task.Run(() =>
{
if (bitmap != null)
{
try
{
lock (cacheLock)
{
if (File.Exists(path))
{
return;
}
using (var fileStream = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite))
{
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
encoder.Save(fileStream);
}
}
}
catch (Exception e)
{
return;
}
}
});
return bitmap;
}
19
View Source File : main.cs
License : GNU General Public License v3.0
Project Creator : ALIILAPRO
License : GNU General Public License v3.0
Project Creator : ALIILAPRO
private void mtd(object Proxiess)
{
bool start = this._start;
if (start)
{
try
{
string host = Proxiess.ToString().Split(new char[]
{
':'
})[0];
string value = Proxiess.ToString().Split(new char[]
{
':'
})[1];
WebProxy proxy = new WebProxy(host, Convert.ToInt32(value));
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.cloudflareclient.com/v0a745/reg");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Accept-Encoding", "gzip");
httpWebRequest.ContentType = "application/json; charset=UTF-8";
httpWebRequest.Host = "api.cloudflareclient.com";
httpWebRequest.KeepAlive = true;
httpWebRequest.UserAgent = "okhttp/3.12.1";
httpWebRequest.Proxy = proxy;
string install_id = this.GenerateUniqCode(22);
string key = this.GenerateUniqCode(43) + "=";
string tos = DateTime.UtcNow.ToString("yyyy-MM-ddTHH\\:mm\\:ss.fff") + "+07:00";
string fcm_token = install_id + ":APA91b" + this.GenerateUniqCode(134);
string referer = this.txtid.Text;
string type = "Android";
string locale = "en-GB";
var body = new
{
install_id = install_id,
key = key,
tos = tos,
fcm_token = fcm_token,
referrer = referer,
warp_enabled = false,
type = type,
locale = locale
};
string jsonBody = JsonConvert.SerializeObject(body);
using (StreamWriter sw = new StreamWriter(httpWebRequest.GetRequestStream()))
{
sw.Write(jsonBody);
}
HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader sw = new StreamReader(httpResponse.GetResponseStream()))
{
string result = sw.ReadToEnd();
}
httpResponse = null;
this._test++;
this._send++;
this.lblgood.Text = this._send.ToString();
this.lbltest.Text = this._test.ToString();
this.lblgb.Text = lblgood.Text + " GB Successfully added to your account.";
}
catch
{
this._test++;
this._error++;
this.lblbad.Text = this._error.ToString();
this.lbltest.Text = this._test.ToString();
}
}
}
19
View Source File : MainForm.cs
License : GNU General Public License v2.0
Project Creator : AmanoTooko
License : GNU General Public License v2.0
Project Creator : AmanoTooko
private void StartKeyPlayback(int interval)
{
kc.isPlayingFlag = false;
kc.isRunningFlag = false;
kc.pauseOffset = 0;
ParameterController.GetInstance().Pitch = 0;
if (midFileDiag.FileName==string.Empty)
{
Log.overlayLog($"错误:没有Midi文件");
MessageBox.Show(new Form() { TopMost = true }, "没有midi你演奏个锤锤?", "喵喵喵?", MessageBoxButtons.OK, MessageBoxIcon.Question);
return;
}
if (_runningTask==null||
_runningTask.ThreadState!= System.Threading.ThreadState.Running&&
_runningTask.ThreadState != System.Threading.ThreadState.Suspended)
{
_runningTask?.Abort();
this.kc.isPlayingFlag = true;
btnSyncReady.BackColor = Color.Aquamarine;
btnSyncReady.Text = "中断演奏";
var Interval = interval < 1000 ? 1000 : interval;
var sub = (long) (1000 - interval);
int bpm = 120;
//timer1.Start();
var sw = new Stopwatch();
sw.Start();
Log.overlayLog($"文件名:{Path.GetFileName(midFileDiag.FileName)}");
Log.overlayLog($"定时:{Interval}毫秒后演奏");
if (ParameterController.GetInstance().isEnsembleSync)
{
System.Threading.Timer timer1 = new System.Threading.Timer((TimerCallback)(x => this.kc.KeyboardPress(48)), new object(), Interval - 4000, 0);
System.Threading.Timer timer2 = new System.Threading.Timer((TimerCallback)(x => this.kc.KeyboardRelease(48)), new object(), Interval - 3950, 0);
Log.overlayLog($"定时:同步音按下");
}
if(netMidiFlag)
{
keyPlayLists = mtk.netmidi?.Tracks[trackComboBox.SelectedIndex].notes;
bpm = mtk.netmidi.BPM;
}
else
{
OpenFile(midFileDiag.FileName);
bpm = mtk.GetBpm();
mtk.GetTrackManagers();
keyPlayLists = mtk.ArrangeKeyPlaysNew((double)(bpm / nudBpm.Value));
}
lyricPoster.LrcStart(midFileDiag.FileName.Replace(".mid", ".mml").Replace(".mml", ".lrc"), interval);
File.WriteAllText($"1.txt", JsonConvert.SerializeObject(keyPlayLists));
if (interval<0)
{
var keyPlay=keyPlayLists.Where((x)=>x.TimeMs> sub);
keyPlayLists=new Queue<KeyPlayList>();
foreach (KeyPlayList kp in keyPlay)
{
kp.TimeMs -= sub;
keyPlayLists.Enqueue(kp);
}
}
sw.Stop();
_runningFlag = true;
cts = new CancellationTokenSource();
if (Settings.Default.isUsingreplacedysis||netMidiFlag==true)
_runningTask = createPerformanceTask(cts.Token, interval - (int)sw.ElapsedMilliseconds);//minus bug?
else
_runningTask = createPerformanceTaskOriginal(cts.Token, (double)(nudBpm.Value / bpm));
_runningTask.Priority = ThreadPriority.Highest;
}
}
19
View Source File : KeyBinding.cs
License : GNU General Public License v2.0
Project Creator : AmanoTooko
License : GNU General Public License v2.0
Project Creator : AmanoTooko
public static string SaveConfigToFile()
{
var json = JsonConvert.SerializeObject(_keymap);
Debug.WriteLine(json);
return json;
}
19
View Source File : KeyBinding.cs
License : GNU General Public License v2.0
Project Creator : AmanoTooko
License : GNU General Public License v2.0
Project Creator : AmanoTooko
public static void SaveConfig()
{
var keyArrayList = new ArrayList();
foreach (var key in _keymap) keyArrayList.Add(key.Value);
var ctrlKeyArrayList = new ArrayList();
foreach (var key in _ctrKeyMap) ctrlKeyArrayList.Add(key.Value);
if (Settings.Default.IsEightKeyLayout)
{
Settings.Default.KeyBinding13 = keyArrayList;
Settings.Default.CtrlKeyBinding = ctrlKeyArrayList;
}
else
{
Settings.Default.KeyBinding37 = keyArrayList;
}
Settings.Default.HotKeyBinding = JsonConvert.SerializeObject(hotkeyArrayList);
Settings.Default.Save();
}
19
View Source File : BingTranslator.cs
License : GNU General Public License v3.0
Project Creator : AndrasMumm
License : GNU General Public License v3.0
Project Creator : AndrasMumm
public string Translate(string original)
{
if (!IsUseable())
{
return null;
}
if (string.IsNullOrEmpty(original))
{
return "";
}
//Creating request json
object[] body = new object[] { new { Text = original } };
var requestBody = JsonConvert.SerializeObject(body);
using (var request = new HttpRequestMessage())
{
//Building actual request
// Set the method to Post.
request.Method = HttpMethod.Post;
// Construct the URI and add headers.
request.RequestUri = new Uri(endPoint + route);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", authKey);
request.Headers.Add("Ocp-Apim-Subscription-Region", "westeurope");
// Send the request and get response.
var responseTask = httpClient.SendAsync(request).ConfigureAwait(false);
HttpResponseMessage response = responseTask.GetAwaiter().GetResult();
// Read response as a string.
var resultTask = response.Content.ReadreplacedtringAsync();
var result =resultTask.GetAwaiter().GetResult();
// Deserialize the response using the clreplacedes created earlier.
TranslationResult[] deserializedOutput = JsonConvert.DeserializeObject<TranslationResult[]>(result);
// Iterate over the deserialized results.
foreach (TranslationResult o in deserializedOutput)
{
/*
// Print the detected input language and confidence score.
Console.WriteLine("Input: {0}\n Output: {1}", original, o.Translations[0].Text);
*/
// Iterate over the results and print each translation.
return o.Translations[0].Text;
}
}
Console.WriteLine("Request failed!");
Useable = false;
return null;
}
19
View Source File : ConvertFile.cs
License : MIT License
Project Creator : AndrewButenko
License : MIT License
Project Creator : AndrewButenko
protected override void ExecuteOperation(Enreplacedy file, EnreplacedyReference parentRecord, string currentFileName)
{
var resultingFileName = ResultingFileName.Get(Context.ExecutionContext);
if (string.IsNullOrEmpty(resultingFileName))
throw new InvalidPluginExecutionException("Resulting File Name Parameter is empty!");
var resultingFileNameParts = resultingFileName.Split('.');
var currentFileNameParts = currentFileName.Split('.');
var baseUrl = "https://api.cloudconvert.com/convert";
var request = WebRequest.Create(baseUrl);
request.Method = "POST";
request.ContentType = "application/json";
var convertFileRequest = new ConvertFileRequest()
{
ApiKey = Context.Settings.CloudConvertKey,
File = file.GetAttributeValue<string>("doreplacedentbody"),
OutputFormat = resultingFileNameParts[resultingFileNameParts.Length - 1],
InputMethod = "base64",
FileName = currentFileName,
InputFormat = currentFileNameParts[currentFileNameParts.Length - 1]
};
var requestBodyString = JsonConvert.SerializeObject(convertFileRequest);
var requestData = Encoding.Default.GetBytes(requestBodyString);
using (var stream = request.GetRequestStream())
{
stream.Write(requestData, 0, requestData.Length);
}
var inputStream = request.GetResponse().GetResponseStream();
var memoStream = new MemoryStream();
inputStream.CopyTo(memoStream);
inputStream.Close();
string newFileContent;
memoStream.Position = 0;
using (var msr = new StreamReader(memoStream, Encoding.Default))
{
newFileContent = msr.ReadToEnd();
}
memoStream.Close();
var attachment = new Enreplacedy("annotation")
{
["subject"] = file.GetAttributeValue<string>("subject"),
["filename"] = resultingFileName,
["doreplacedentbody"] = Convert.ToBase64String(Encoding.Default.GetBytes(newFileContent)),
["isdoreplacedent"] = true,
["objectid"] = parentRecord
};
var isReplaceOriginal = IsReplaceOriginalFile.Get(Context.ExecutionContext);
if (isReplaceOriginal)
{
attachment.Id = file.Id;
Context.UserService.Update(attachment);
}
else
{
Context.UserService.Create(attachment);
}
}
19
View Source File : RoomPreset.cs
License : MIT License
Project Creator : andruzzzhka
License : MIT License
Project Creator : andruzzzhka
public void SavePreset()
{
if (!string.IsNullOrEmpty(path))
{
File.WriteAllText(path, JsonConvert.SerializeObject(this));
}
}
19
View Source File : RoomPreset.cs
License : MIT License
Project Creator : andruzzzhka
License : MIT License
Project Creator : andruzzzhka
public void SavePreset(string newPath)
{
if (!string.IsNullOrEmpty(newPath))
{
File.WriteAllText(newPath, JsonConvert.SerializeObject(this));
path = newPath;
}
}
19
View Source File : WebSocketListener.cs
License : MIT License
Project Creator : andruzzzhka
License : MIT License
Project Creator : andruzzzhka
protected override void OnOpen()
{
base.OnOpen();
if (Settings.Instance.Server.EnableWebSocketRoomInfo)
{
try {
List<string> paths = WebSocketListener.Server.WebSocketServices.Paths.ToList();
paths.Remove("/");
if (Settings.Instance.Server.EnableWebSocketRCON)
{
paths.Remove("/" + Settings.Instance.Server.RCONPreplacedword);
}
List<WSRoomInfo> rooms = paths.Where(x => x.Contains("room")).Select(x => new WSRoomInfo(x)).ToList();
List<RCONChannelInfo> channels = paths.Where(x => x.Contains("channel")).Select(x => new RCONChannelInfo(x)).ToList();
ServerHubInfo info = new ServerHubInfo()
{
ServerHubName = Settings.Instance.Server.ServerHubName,
Version = replacedembly.GetEntryreplacedembly().GetName().Version.ToString(),
TotalClients = HubListener.hubClients.Count + RoomsController.GetRoomsList().Sum(x => x.roomClients.Count) + RadioController.radioChannels.Sum(x => x.radioClients.Count),
Rooms = rooms,
RadioChannels = channels
};
Send(JsonConvert.SerializeObject(info));
}catch(Exception e)
{
Logger.Instance.Warning("Unable to send ServerHub info to WebSocket client! Exception: " + e);
}
}
}
19
View Source File : WebSocketListener.cs
License : MIT License
Project Creator : andruzzzhka
License : MIT License
Project Creator : andruzzzhka
public static void BroadcastState()
{
if (Server != null && Settings.Instance.Server.EnableWebSocketRoomInfo)
{
try
{
List<string> paths = Server.WebSocketServices.Paths.ToList();
paths.Remove("/");
if (Settings.Instance.Server.EnableWebSocketRCON)
{
paths.Remove("/" + Settings.Instance.Server.RCONPreplacedword);
}
List<WSRoomInfo> rooms = paths.Where(x => x.Contains("room")).Select(x => new WSRoomInfo(x)).ToList();
List<RCONChannelInfo> channels = paths.Where(x => x.Contains("channel")).Select(x => new RCONChannelInfo(x)).ToList();
string data = JsonConvert.SerializeObject(new { rooms, channels });
Server.WebSocketServices["/"].Sessions.BroadcastAsync(data, null);
}catch(Exception e)
{
Misc.Logger.Instance.Error("WebSocket broadcast failed! Exception: "+e);
}
}
}
19
View Source File : PluginConfig.cs
License : MIT License
Project Creator : andruzzzhka
License : MIT License
Project Creator : andruzzzhka
public static void LoadConfig()
{
if (IPA.Loader.PluginManager.AllPlugins.Select(x => x.Metadata.Name) //BSIPA Plugins
.Concat(IPA.Loader.PluginManager.Plugins.Select(x => x.Name)) //Old IPA Plugins
.Any(x => x == "Song Browser" || x == "Song Browser Plugin"))
{
Plugin.log.Info("Song Browser installed, disabling Song List Tweaks");
disableSongListTweaks = true;
}
if (!Directory.Exists("UserData"))
{
Directory.CreateDirectory("UserData");
}
LoadIni();
if (File.Exists(oldFavSongsPath) && !File.Exists(favSongsPath))
{
File.Move(oldFavSongsPath, favSongsPath);
}
if (!File.Exists(favSongsPath))
{
File.Create(favSongsPath).Close();
}
favoriteSongs.AddRange(File.ReadAllLines(favSongsPath, Encoding.UTF8));
if (!File.Exists(votedSongsPath))
{
File.WriteAllText(votedSongsPath, JsonConvert.SerializeObject(votedSongs), Encoding.UTF8);
}
else
{
votedSongs = JsonConvert.DeserializeObject<Dictionary<string, SongVote>>(File.ReadAllText(votedSongsPath, Encoding.UTF8));
}
if (!File.Exists(reviewedSongsPath))
{
File.WriteAllText(reviewedSongsPath, JsonConvert.SerializeObject(reviewedSongs), Encoding.UTF8);
}
else
{
reviewedSongs = JsonConvert.DeserializeObject<Dictionary<string, SongReview>>(File.ReadAllText(reviewedSongsPath, Encoding.UTF8));
}
try
{
if (Registry.CurrentUser.OpenSubKey(@"Software").GetSubKeyNames().Contains("178eef3d-4cea-5a1b-bfd0-07a21d068990"))
{
beatDropPlaylistsLocation = (string)Registry.CurrentUser.OpenSubKey(@"Software\178eef3d-4cea-5a1b-bfd0-07a21d068990").GetValue("InstallLocation", "");
if (Directory.Exists(beatDropPlaylistsLocation))
{
beatDropInstalled = true;
}
else if (Directory.Exists("%LocalAppData%\\Programs\\BeatDrop\\playlists"))
{
beatDropInstalled = true;
beatDropPlaylistsLocation = "%LocalAppData%\\Programs\\BeatDrop\\playlists";
}
else
{
beatDropInstalled = false;
beatDropPlaylistsLocation = "";
}
}
}
catch (Exception e)
{
Plugin.log.Info($"Can't open registry key! Exception: {e}");
if (Directory.Exists("%LocalAppData%\\Programs\\BeatDrop\\playlists"))
{
beatDropInstalled = true;
beatDropPlaylistsLocation = "%LocalAppData%\\Programs\\BeatDrop\\playlists";
}
else
{
Plugin.log.Info("Unable to find BeatDrop installation folder!");
}
}
if (!Directory.Exists("Playlists"))
{
Directory.CreateDirectory("Playlists");
}
}
19
View Source File : CaptionReaderViewModel.cs
License : MIT License
Project Creator : anthonychu
License : MIT License
Project Creator : anthonychu
private static ByteArrayContent CreatePostContent(object item)
{
var json = JsonConvert.SerializeObject(item);
var buffer = Encoding.UTF8.GetBytes(json);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return byteContent;
}
See More Examples