Here are the examples of the csharp api Newtonsoft.Json.Linq.JToken.ToObject() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
582 Examples
19
Source : MProfileInfoLoader.cs
with MIT License
from CmlLib
with MIT License
from CmlLib
public static MProfileInfo[] GetProfilesFromWeb()
{
JArray jarr;
using (WebClient wc = new WebClient())
{
var jobj = JObject.Parse(wc.DownloadString("https://launchermeta.mojang.com/mc/game/version_manifest.json"));
jarr = JArray.Parse(jobj["versions"].ToString());
}
var arr = new MProfileInfo[jarr.Count];
for (int i = 0; i < jarr.Count; i++)
{
var obj = jarr[i].ToObject<MProfileInfo>();
obj.IsWeb = true;
arr[i] = obj;
}
return arr;
}
19
Source : GraphQLIntegrationTests.cs
with Apache License 2.0
from commercetools
with Apache License 2.0
from commercetools
[Fact]
public async Task UpdateAnOrder()
{
//Arrange
var orderNumber = $"order-{TestingUtility.RandomInt()}";
var query = @"mutation ($orderId:String, $orderNumber:String){
updateOrder(
version: 1,
id:$orderId,
actions: [
{
changeOrderState:{
orderState: Confirmed
}
},
{
setOrderNumber:{
orderNumber: $orderNumber
}
}
]
) {
id,
orderNumber,
orderState,
version
}
}";
//act
await WithCartWithSingleLineItem(client, 2, DefaultCartDraft,
async cart =>
{
replacedert.Single(cart.LineItems);
//create order with null orderNumber
await WithUpdateableOrder(client,
draft => DefaultOrderFromCartDraftWithNumber(draft, cart, orderNumber: null),
async order =>
{
replacedert.NotNull(order);
replacedert.Null(order.OrderNumber);
var queryParameters = new GraphQLParameters(query, new Dictionary<string, object>
{
{"orderId", order.Id},
{"orderNumber", orderNumber}
});
var graphQlCommand = new GraphQLCommand<dynamic>(queryParameters);
var result = await client.ExecuteAsync(graphQlCommand);
var updatedOrderJObject = result.data.updateOrder as JObject;
replacedert.NotNull(updatedOrderJObject);
var updatedOrder = updatedOrderJObject.ToObject<Order>();
replacedert.Equal(order.Id, updatedOrder.Id);
replacedert.Equal(OrderState.Confirmed, updatedOrder.OrderState);
replacedert.Equal(orderNumber, updatedOrder.OrderNumber);
return updatedOrder;
});
});
}
19
Source : ConanProject.cs
with MIT License
from conan-io
with MIT License
from conan-io
public string getProfile(ConanConfiguration configuration, Core.IErrorListService errorListService)
{
if (!File.Exists(ConfigFile)) return null;
try
{
JObject jObject = JObject.Parse(File.ReadAllText(ConfigFile));
var configs = jObject["configurations"].ToObject<Dictionary<string, string>>();
configs.TryGetValue(configuration.VSName, out string conanProfile);
if (conanProfile == null)
{
errorListService.WriteWarning($"File for Conan configuration found at '{ConfigFile}'," +
$" but no profile declared for VS configuration '{configuration.VSName}'");
}
return conanProfile;
}
catch (Exception)
{
errorListService.WriteError($"Error parsing Conan configuration from file '{ConfigFile}'");
return null;
}
}
19
Source : SocketServer.cs
with GNU General Public License v3.0
from d8ahazard
with GNU General Public License v3.0
from d8ahazard
public async Task SystemData(string sd) {
var sdd = JObject.Parse(sd);
var sd2 = sdd.ToObject<SystemData>();
try {
await _cs.UpdateSystem(sd2).ConfigureAwait(false);
//await Clients.Others.SendAsync("olo", DataUtil.GetStoreSerialized());
} catch (Exception e) {
Log.Warning("Exception updating SD: " + e.Message + " at " + e.StackTrace);
}
}
19
Source : JsonLoader.cs
with GNU General Public License v3.0
from d8ahazard
with GNU General Public License v3.0
from d8ahazard
public List<T> LoadFiles<T>() {
var output = new List<T>();
var dirIndex = 0;
var fCount = 50;
foreach (var dir in _directories.Where(Directory.Exists)) {
foreach (var file in Directory.EnumerateFiles(dir)) {
if (file.Contains(".json")) {
try {
var data = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(file));
if (data != null) {
if (dirIndex != 0) {
var id = data.GetValue("Id");
var name = data.GetValue("Name");
if (id != null && name != null) {
if ((int)id == 0 && (string)name! != "Random") {
data["Id"] = fCount;
}
} else {
continue;
}
}
var obj = data.ToObject<T>();
if (obj != null) {
output.Add(obj);
}
}
} catch (Exception e) {
Log.Warning($"Parse exception for {file}: " + e.Message);
}
}
fCount++;
}
dirIndex++;
}
return output;
}
19
Source : JsonLoader.cs
with GNU General Public License v3.0
from d8ahazard
with GNU General Public License v3.0
from d8ahazard
public AudioScene Gereplacedem(dynamic id) {
var files = LoadFiles<JObject>();
foreach (var f in files) {
if (!f.TryGetValue("Id", out var check)) {
continue;
}
if (check == id) {
return f.ToObject<AudioScene>();
}
}
return GetDefault();
}
19
Source : ColorSerializer.cs
with GNU General Public License v2.0
from DarthAffe
with GNU General Public License v2.0
from DarthAffe
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jsonObject = JObject.Load(reader);
if (jsonObject.Property("A").Value.ToObject<double>() > 1.0) //DarthAffe 09.06.2019: Convert old Settings
return new Color(jsonObject.Property("A").Value.ToObject<byte>(),
jsonObject.Property("R").Value.ToObject<byte>(),
jsonObject.Property("G").Value.ToObject<byte>(),
jsonObject.Property("B").Value.ToObject<byte>());
else
return new Color(jsonObject.Property("A").Value.ToObject<double>(),
jsonObject.Property("R").Value.ToObject<double>(),
jsonObject.Property("G").Value.ToObject<double>(),
jsonObject.Property("B").Value.ToObject<double>());
}
19
Source : ColorSerializer.cs
with GNU General Public License v2.0
from DarthAffe
with GNU General Public License v2.0
from DarthAffe
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jsonObject = JObject.Load(reader);
return new Color(jsonObject.Property("A").Value.ToObject<byte>(),
jsonObject.Property("R").Value.ToObject<byte>(),
jsonObject.Property("G").Value.ToObject<byte>(),
jsonObject.Property("B").Value.ToObject<byte>());
}
19
Source : MessageDataConverter.cs
with MIT License
from dolkensp
with MIT License
from dolkensp
public override Object ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
{
var data = JToken.ReadFrom(reader);
if (data.IsValid(this._objectSchema))
{
return new MessageData[] { (MessageData)data.ToObject<MessageData>() };
}
if (data.IsValid(this._arraySchema))
{
return (MessageData[])data.ToObject<MessageData[]>();
}
return null;
}
19
Source : RoleCollectionConverter.cs
with MIT License
from dolkensp
with MIT License
from dolkensp
public override Object ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
{
var roles = JToken.ReadFrom(reader);
if (roles.IsValid(this._mapSchema1))
{
return (RoleCollection)roles.ToObject<Dictionary<UInt64, UInt64[]>>();
}
if (roles.IsValid(this._mapSchema2))
{
return (RoleCollection)roles.ToObject<Dictionary<UInt64, UInt64[]>>();
}
if (roles.IsValid(this._arraySchema))
{
return (RoleCollection)roles.ToObject<UInt64[]>();
}
return null;
}
19
Source : _SpectrumClient.cs
with MIT License
from dolkensp
with MIT License
from dolkensp
private async Task SpinWebSocket()
{
while (!this._cancellationOwner.IsCancellationRequested)
{
try
{
await this.CheckSocket();
if (this._socketClient.State == WebSocketState.Open)
{
var buffer = new Byte[1024];
var sb = new StringBuilder();
var result = await this._socketClient.ReceiveAsync(new ArraySegment<Byte>(buffer), this._cancellationOwner.Token);
switch (result.MessageType)
{
case WebSocketMessageType.Close:
// await this._socketClient.CloseAsync(WebSocketCloseStatus.NormalClosure, String.Empty, this._cancellationOwner.Token);
break;
case WebSocketMessageType.Text:
sb.Append(Encoding.UTF8.GetString(buffer, 0, result.Count));
while (!result.EndOfMessage)
{
result = await this._socketClient.ReceiveAsync(new ArraySegment<Byte>(buffer), this._cancellationOwner.Token);
sb.Append(Encoding.UTF8.GetString(buffer, 0, result.Count));
}
var str_buffer = sb.ToString();
var jToken = JToken.Parse(str_buffer);
if (jToken.HasValues && jToken["type"] != null)
{
var payloadType = EnumUtils.ToEnum<PayloadType>(jToken["type"].Value<String>(), PayloadType.Unknown);
switch (payloadType)
{
// {"type":"message_lobby.presence.join","lobby_id":23178,"member_id":2305,"member":{"nickname":"eXpG_Neutron","displayname":"eXpG_Neutron","avatar":"https:\/\/robertsspaceindustries.com\/media\/k7aiwf1sigzm5r\/heap_infobox\/EXpG_Neutron.jpg?v=1488177011","meta":{"signature":"","badges":[{"name":"Grand Admiral","icon":"https:\/\/robertsspaceindustries.com\/media\/lish0be1gvu8xr\/heap_note\/Grand-Admiral.png"},{"name":"Backer","icon":"https:\/\/robertsspaceindustries.com\/rsi\/static\/images\/profile\/icon-backer.png"},{"name":"Explorer-Germany","icon":"https:\/\/robertsspaceindustries.com\/media\/6cedovn1e0wejr\/heap_note\/EXPG-Thumbnail.png","url":"https:\/\/robertsspaceindustries.com\/orgs\/EXPG"}]},"roles":{"1":["4","6","11","12"],"1091":["7641","7643"],"9711":["67976","67977"]},"presence":{"status":"online","info":null,"since":1488293242}}}
case PayloadType.MessageLobby_Presence_Join:
{
var payload = jToken.ToObject<Lobby.Join.Payload>();
var lobby = this._communities.SelectMany(c => c.Lobbies).Where(l => l.Id == payload.LobbyId).FirstOrDefault();
await (this.OnMemberJoin?.Invoke(payload, lobby) ?? Task.CompletedTask);
break;
}
// {"type":"message_lobby.presence.leave","lobby_id":23178,"member_id":2305}
case PayloadType.MessageLobby_Presence_Leave:
{
var payload = jToken.ToObject<Lobby.Leave.Payload>();
var lobby = this._communities.SelectMany(c => c.Lobbies).Where(l => l.Id == payload.LobbyId).FirstOrDefault();
await (this.OnMemberLeave?.Invoke(payload, lobby) ?? Task.CompletedTask);
break;
}
// {"type":"member.presence.update","member_id":27,"presence":{"status":"away","info":null,"since":1488293110}}
case PayloadType.Member_Presence_Update:
{
var payload = jToken.ToObject<Lobby.Update.Payload>();
var lobby = this._communities.SelectMany(c => c.Lobbies).Where(l => l.Id == payload.LobbyId).FirstOrDefault();
await (this.OnMemberUpdate?.Invoke(payload, lobby) ?? Task.CompletedTask);
break;
}
case PayloadType.Message_New:
{
var payload = jToken.ToObject<Message.New.Payload>();
var lobby = payload.Message.Lobby ?? this._communities.SelectMany(c => c.Lobbies).Where(l => l.Id == payload.Message.LobbyId).FirstOrDefault();
await (this.OnMessageReceived?.Invoke(payload, lobby) ?? Task.CompletedTask);
break;
}
case PayloadType.Unknown:
{
// File.AppendAllText("payload.unknown.log", $"\r\n{str_buffer}");
// Console.WriteLine($"Unknown Payload: {payloadType}");
await (this.OnFrameReceived?.Invoke(str_buffer) ?? Task.CompletedTask);
break;
}
default:
await (this.OnFrameReceived?.Invoke(str_buffer) ?? Task.CompletedTask);
break;
}
}
else
{
await (this.OnFrameReceived?.Invoke(str_buffer) ?? Task.CompletedTask);
}
break;
case WebSocketMessageType.Binary:
throw new NotImplementedException();
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error: {ex.Message}");
await (this.OnError?.Invoke(ex) ?? Task.CompletedTask);
}
}
}
19
Source : CustomAction.cs
with GNU General Public License v3.0
from eapowertools-archive
with GNU General Public License v3.0
from eapowertools-archive
[CustomAction]
public static ActionResult CreateTasks(Session session)
{
string installDir = session.CustomActionData["InstallDir"];
if (!installDir.EndsWith("\\"))
{
installDir += "\\";
}
string externalTaskID = "";
// External Task
Tuple<HttpStatusCode, string> hasExternalTask = MakeQrsRequest("/externalprogramtask/count?filter=name eq 'TelemetryDashboard-1-Generate-Metadata'", HttpMethod.Get);
if (hasExternalTask.Item1 != HttpStatusCode.OK)
{
return ActionResult.Failure;
}
if (JObject.Parse(hasExternalTask.Item2)["value"].ToObject<int>() == 0)
{
installDir = installDir.Replace("\\", "\\\\");
string body = @"
{
'path': '..\\ServiceDispatcher\\Node\\node.exe',
'parameters': '""" + Path.Combine(installDir, JS_LIBRARY_FOLDER) + @"\\fetchMetadata.js""',
'name': 'TelemetryDashboard-1-Generate-Metadata',
'taskType': 1,
'enabled': true,
'taskSessionTimeout': 1440,
'maxRetries': 0,
'impactSecurityAccess': false,
'schemaPath': 'ExternalProgramTask'
}";
Tuple<HttpStatusCode, string> createExternalTask = MakeQrsRequest("/externalprogramtask", HttpMethod.Post, HTTPContentType.json, Encoding.UTF8.GetBytes(body));
if (createExternalTask.Item1 != HttpStatusCode.Created)
{
return ActionResult.Failure;
}
else
{
externalTaskID = JObject.Parse(createExternalTask.Item2)["id"].ToString();
}
}
else
{
Tuple<HttpStatusCode, string> getExternalTaskId = MakeQrsRequest("/externalprogramtask?filter=name eq 'TelemetryDashboard-1-Generate-Metadata'", HttpMethod.Get);
externalTaskID = JArray.Parse(getExternalTaskId.Item2)[0]["id"].ToString();
}
// Reload Task
Tuple<HttpStatusCode, string> reloadTasks = MakeQrsRequest("/reloadtask/full?filter=name eq 'TelemetryDashboard-2-Reload-Dashboard'", HttpMethod.Get);
if (reloadTasks.Item1 != HttpStatusCode.OK)
{
return ActionResult.Failure;
}
JArray listOfTasks = JArray.Parse(reloadTasks.Item2);
// Get AppID for Telemetry Dashboard App
Tuple<HttpStatusCode, string> getAppID = MakeQrsRequest("/app?filter=name eq 'Telemetry Dashboard'", HttpMethod.Get);
string appId = JArray.Parse(getAppID.Item2)[0]["id"].ToString();
if (listOfTasks.Count == 0)
{
string body = @"
{
'compositeEvents': [
{
'compositeRules': [
{
'externalProgramTask': {
'id': '" + externalTaskID + @"',
'name': 'TelemetryDashboard-1-Generate-Metadata'
},
'ruleState': 1
}
],
'enabled': true,
'eventType': 1,
'name': 'telemetry-metadata-trigger',
'privileges': [
'read',
'update',
'create',
'delete'
],
'timeConstraint': {
'days': 0,
'hours': 0,
'minutes': 360,
'seconds': 0
}
}
],
'schemaEvents': [],
'task': {
'app': {
'id': '" + appId + @"',
'name': 'Telemetry Dashboard'
},
'customProperties': [],
'enabled': true,
'isManuallyTriggered': false,
'maxRetries': 0,
'name': 'TelemetryDashboard-2-Reload-Dashboard',
'tags': [],
'taskSessionTimeout': 1440,
'taskType': 0
}
}";
Tuple<HttpStatusCode, string> importExtensionResponse = MakeQrsRequest("/reloadtask/create", HttpMethod.Post, HTTPContentType.json, Encoding.UTF8.GetBytes(body));
if (importExtensionResponse.Item1 != HttpStatusCode.Created)
{
return ActionResult.Failure;
}
}
else
{
listOfTasks[0]["app"] = JObject.Parse(@"{ 'id': '" + appId + "'}");
listOfTasks[0]["modifiedDate"] = DateTime.UtcNow.ToString("s") + "Z";
string reloadTaskID = listOfTasks[0]["id"].ToString();
Tuple<HttpStatusCode, string> updatedApp = MakeQrsRequest("/reloadtask/" + reloadTaskID, HttpMethod.Put, HTTPContentType.json, Encoding.UTF8.GetBytes(listOfTasks[0].ToString()));
if (updatedApp.Item1 != HttpStatusCode.OK)
{
return ActionResult.Failure;
}
}
return ActionResult.Success;
}
19
Source : InvoiceManager.cs
with Apache License 2.0
from EdwinVW
with Apache License 2.0
from EdwinVW
public async Task<bool> HandleMessageAsync(string messageType, string message)
{
try
{
JObject messageObject = MessageSerializer.Deserialize(message);
switch (messageType)
{
case "CustomerRegistered":
await HandleAsync(messageObject.ToObject<CustomerRegistered>());
break;
case "MaintenanceJobPlanned":
await HandleAsync(messageObject.ToObject<MaintenanceJobPlanned>());
break;
case "MaintenanceJobFinished":
await HandleAsync(messageObject.ToObject<MaintenanceJobFinished>());
break;
case "DayHasPreplaceded":
await HandleAsync(messageObject.ToObject<DayHasPreplaceded>());
break;
}
}
catch (Exception ex)
{
Log.Error(ex, $"Error while handling {messageType} event.");
}
return true;
}
19
Source : NotificationManager.cs
with Apache License 2.0
from EdwinVW
with Apache License 2.0
from EdwinVW
public async Task<bool> HandleMessageAsync(string messageType, string message)
{
try
{
JObject messageObject = MessageSerializer.Deserialize(message);
switch (messageType)
{
case "CustomerRegistered":
await HandleAsync(messageObject.ToObject<CustomerRegistered>());
break;
case "MaintenanceJobPlanned":
await HandleAsync(messageObject.ToObject<MaintenanceJobPlanned>());
break;
case "MaintenanceJobFinished":
await HandleAsync(messageObject.ToObject<MaintenanceJobFinished>());
break;
case "DayHasPreplaceded":
await HandleAsync(messageObject.ToObject<DayHasPreplaceded>());
break;
default:
break;
}
}
catch (Exception ex)
{
Log.Error(ex, $"Error while handling {messageType} event.");
}
return true;
}
19
Source : EventHandler.cs
with Apache License 2.0
from EdwinVW
with Apache License 2.0
from EdwinVW
public async Task<bool> HandleMessageAsync(string messageType, string message)
{
JObject messageObject = MessageSerializer.Deserialize(message);
try
{
switch (messageType)
{
case "CustomerRegistered":
await HandleAsync(messageObject.ToObject<CustomerRegistered>());
break;
case "VehicleRegistered":
await HandleAsync(messageObject.ToObject<VehicleRegistered>());
break;
case "MaintenanceJobPlanned":
await HandleAsync(messageObject.ToObject<MaintenanceJobPlanned>());
break;
case "MaintenanceJobFinished":
await HandleAsync(messageObject.ToObject<MaintenanceJobFinished>());
break;
}
}
catch(Exception ex)
{
string messageId = messageObject.Property("MessageId") != null ? messageObject.Property("MessageId").Value<string>() : "[unknown]";
Log.Error(ex, "Error while handling {MessageType} message with id {MessageId}.", messageType, messageId);
}
// always akcnowledge message - any errors need to be dealt with locally.
return true;
}
19
Source : Training.cs
with MIT License
from Emotiv
with MIT License
from Emotiv
private void GetDetectionOk(object sender, JObject rsp)
{
Console.WriteLine("GetDetectionInfoOK: " + rsp);
_availActions = rsp["actions"].ToObject<List<string>>();
// query profiles
_ctxClient.QueryProfile(_cortexToken);
}
19
Source : Program.cs
with MIT License
from Emotiv
with MIT License
from Emotiv
private static void SubscribedOK(object sender, Dictionary<string, JArray> e)
{
foreach (string key in e.Keys)
{
if (key == "eeg")
{
// print header
ArrayList header = e[key].ToObject<ArrayList>();
//add timeStamp to header
header.Insert(0, "Timestamp");
WriteDataToFile(header);
}
}
}
19
Source : Program.cs
with MIT License
from Emotiv
with MIT License
from Emotiv
private static void SubscribedOK(object sender, Dictionary<string, JArray> e)
{
foreach (string key in e.Keys)
{
if (key == "mot")
{
// print header
ArrayList header = e[key].ToObject<ArrayList>();
//add timeStamp to header
header.Insert(0, "Timestamp");
WriteDataToFile(header);
}
}
}
19
Source : Program.cs
with MIT License
from Emotiv
with MIT License
from Emotiv
private static void SubscribedOK(object sender, Dictionary<string, JArray> e)
{
foreach (string key in e.Keys)
{
if (key == "met")
{
// print header
ArrayList header = e[key].ToObject<ArrayList>();
//add timeStamp to header
header.Insert(0, "Timestamp");
WriteDataToFile(header);
}
}
}
19
Source : Program.cs
with MIT License
from Emotiv
with MIT License
from Emotiv
private static void SubscribedOK(object sender, Dictionary<string, JArray> e)
{
foreach (string key in e.Keys)
{
if (key == "pow")
{
// print header
ArrayList header = e[key].ToObject<ArrayList>();
//add timeStamp to header
header.Insert(0, "Timestamp");
WriteDataToFile(header);
}
}
}
19
Source : BiliUtils.cs
with GNU General Public License v3.0
from Executor-Cheng
with GNU General Public License v3.0
from Executor-Cheng
public static string GetUserNameByUserId(int userId)
{
IDictionary<string, string> headers = new Dictionary<string, string>
{
{ "Origin", "https://space.bilibili.com" },
{ "Referer", $"https://space.bilibili.com/{userId}/" },
{ "X-Requested-With", "XMLHttpRequest" }
};
string json = HttpHelper.HttpPost("https://space.bilibili.com/ajax/member/GetInfo", $"mid={userId}&csrf=", 10, headers: headers);
JObject j = JObject.Parse(json);
if (j["status"].ToObject<bool>())
{
return j["data"]["name"].ToString();
}
else
{
throw new NotImplementedException($"未知的服务器返回:{j.ToString(0)}");
}
}
19
Source : ExtendNeteaseModule.cs
with GNU General Public License v3.0
from Executor-Cheng
with GNU General Public License v3.0
from Executor-Cheng
protected override List<SongInfo> GetPlaylist(string keyword)
{
try
{
NeteaseMusic.SongInfo[] songs;
if (long.TryParse(keyword, out long id))
{
songs = MainConfig.Instance.LoginSession.LoginStatus ?
NeteaseMusicApi.GetPlayList(MainConfig.Instance.LoginSession, id) :
NeteaseMusicApi.GetPlayList(id);
}
else
{
string json = NeteaseMusicApi.Search(keyword, SearchType.SongList, 1);
JObject j = JObject.Parse(json);
if (j["code"].ToObject<int>() == 200)
{
id = j["result"]["playlists"].Select(p => p["id"].ToObject<long>()).FirstOrDefault();
if (id > 0)
{
songs = MainConfig.Instance.LoginSession.LoginStatus ?
NeteaseMusicApi.GetPlayList(MainConfig.Instance.LoginSession, id) :
NeteaseMusicApi.GetPlayList(id);
}
else
{
Log("在获取歌单时收到了未知的服务器返回喵:" + json);
return null;
}
}
else
{
Log("在获取歌单时收到了未知的服务器返回喵:" + json);
return null;
}
}
NeteaseMusic.SongInfo[] cantPlaySongs = songs.Where(p => !p.CanPlay).ToArray();
if (cantPlaySongs.Length > 0)
{
if (songs.Length == cantPlaySongs.Length)
{
Log("该歌单内所有的单曲,网易云都没有版权,所以歌单添加失败了喵");
return null;
}
Log($"以下列出的单曲,网易云暂时没有版权,所以它们被除外了喵~\n{string.Join("\n", cantPlaySongs.Select(p => $"{string.Join("; ", p.Artists.Select(q => q.Name))} - {p.Name}"))}");
}
return songs.Where(p => p.CanPlay).Select(p => new SongInfo(this, p.Id.ToString(), p.Name, p.Artists.Select(q => q.Name).ToArray(), null)).ToList();
}
catch (WebException e)
{
Log($"获取歌单失败了喵:{e.Message}\r\n这是由于网络原因导致获取失败, 如果多次出现, 请检查你的网络连接喵。");
}
catch (Exception e)
{
Log($"获取歌单失败了喵:{e.Message}");
}
return null;
}
19
Source : NeteaseMusicApi.cs
with GNU General Public License v3.0
from Executor-Cheng
with GNU General Public License v3.0
from Executor-Cheng
private static JObject _GetPlayerUrl(NeteaseSession session, Quality bitRate = Quality.SuperQuality, params long[] songIds)
{
IDictionary<string, object> data = new Dictionary<string, object>
{
["ids"] = songIds,
["br"] = (int)bitRate
};
CryptoHelper.Encrypted encrypted = CryptoHelper.WebApiEncrypt(data);
string json = session == null ? HttpHelper.HttpPost("https://music.163.com/weapi/song/enhance/player/url", encrypted.GetFormdata(), userAgent: DefaultUserAgent) :
session.Session.HttpPost("https://music.163.com/weapi/song/enhance/player/url", encrypted.GetFormdata(), userAgent: DefaultUserAgent);
JObject j = JObject.Parse(json);
if (j["code"].ToObject<int>() == 200)
{
return j;
}
else
{
NotImplementedException exception = new NotImplementedException($"未知的服务器返回");
exception.Data.Add("Response", j.ToString());
throw exception;
}
}
19
Source : NeteaseMusicApi.cs
with GNU General Public License v3.0
from Executor-Cheng
with GNU General Public License v3.0
from Executor-Cheng
public async Task LogOutAsync()
{
IDictionary<string, object> data = new Dictionary<string, object>
{
["csrf_token"] = GetCsrfToken(),
};
NeteaseMusicApi.CryptoHelper.Encrypted encrypted = NeteaseMusicApi.CryptoHelper.WebApiEncrypt(data);
try
{
string json = await Session.HttpPostAsync("https://music.163.com/weapi/logout", encrypted.GetFormdata(), userAgent: NeteaseMusicApi.DefaultUserAgent);
JObject j = JObject.Parse(json);
if (j["code"].ToObject<int>() != 0)
{
NotImplementedException exception = new NotImplementedException($"未知的服务器返回");
exception.Data.Add("Response", j.ToString());
throw exception;
}
}
finally
{
Session.Reset();
}
}
19
Source : NeteaseMusicApi.cs
with GNU General Public License v3.0
from Executor-Cheng
with GNU General Public License v3.0
from Executor-Cheng
public static SongInfo[] SearchSongs(NeteaseSession session, string keyWords, int pageSize = 30, int offset = 0)
{
string json = Search(keyWords, SearchType.Song, pageSize, offset);
JObject j = JObject.Parse(json);
if (j["code"].ToObject<int>() == 200)
{
SongInfo[] result = j["result"]["songs"].Select(p => new SongInfo(p)).ToArray();
IDictionary<long, bool> canPlayDic = CheckMusicStatus(session, result.Select(p => p.Id).ToArray());
foreach (SongInfo song in result)
{
if (canPlayDic.TryGetValue(song.Id, out bool canPlay))
{
song.CanPlay = canPlay;
}
}
return result;
}
else
{
NotImplementedException exception = new NotImplementedException($"未知的服务器返回");
exception.Data.Add("Response", j.ToString());
throw exception;
}
}
19
Source : NeteaseMusicApi.cs
with GNU General Public License v3.0
from Executor-Cheng
with GNU General Public License v3.0
from Executor-Cheng
public static LyricInfo GetLyric(long songId)
{
IDictionary<string, object> data = new Dictionary<string, object>
{
["csrf_token"] = "",
["id"] = songId.ToString(),
["lv"] = -1,
["tv"] = -1
};
CryptoHelper.Encrypted encrypted = CryptoHelper.WebApiEncrypt(data);
string json = HttpHelper.HttpPost("https://music.163.com/weapi/song/lyric", encrypted.GetFormdata(), userAgent: DefaultUserAgent);
JObject j = JObject.Parse(json);
if (j["code"].ToObject<int>() == 200)
{
string lyricText = j["lrc"]?["lyric"]?.ToString();
string translatedLyricText = j["tlyric"]?["lyric"]?.ToString();
LyricInfo lyric = null;
if (!string.IsNullOrEmpty(lyricText))
{
lyric = new LyricInfo(lyricText);
}
if (!string.IsNullOrEmpty(translatedLyricText))
{
lyric.AppendLrc(translatedLyricText);
}
return lyric;
}
else
{
NotImplementedException exception = new NotImplementedException($"未知的服务器返回");
exception.Data.Add("Response", j.ToString());
throw exception;
}
}
19
Source : NeteaseMusicApi.cs
with GNU General Public License v3.0
from Executor-Cheng
with GNU General Public License v3.0
from Executor-Cheng
public static SongInfo[] GetPlayList(NeteaseSession session, long id)
{
IDictionary<string, object> data = new Dictionary<string, object>()
{
["id"] = id,
["n"] = 100000,
["s"] = 8
};
CryptoHelper.Encrypted encrypted = CryptoHelper.WebApiEncrypt(data);
string json = session == null ? HttpHelper.HttpPost("https://music.163.com/weapi/v3/playlist/detail", encrypted.GetFormdata(), userAgent: DefaultUserAgent) :
session.Session.HttpPost("https://music.163.com/weapi/v3/playlist/detail", encrypted.GetFormdata(), userAgent: DefaultUserAgent);
JObject j = JObject.Parse(json);
int code = j["code"].ToObject<int>();
switch (code)
{
case 200:
{
SongInfo[] result = j["playlist"]["tracks"].Select(p => new SongInfo(p)).ToArray();
IDictionary<long, bool> canPlayDic = CheckMusicStatus(session, result.Select(p => p.Id).ToArray());
foreach (SongInfo song in result)
{
if (canPlayDic.TryGetValue(song.Id, out bool canPlay))
{
song.CanPlay = canPlay;
}
}
return result;
}
case 401:
{
throw new InvalidOperationException("给定的歌单为私有歌单,非歌单所有者无权访问");
}
case 404:
{
throw new ArgumentException("给定的歌单ID无效", nameof(id));
}
default:
{
NotImplementedException exception = new NotImplementedException($"未知的服务器返回");
exception.Data.Add("Response", j.ToString());
throw exception;
}
}
}
19
Source : NeteaseMusicApi.cs
with GNU General Public License v3.0
from Executor-Cheng
with GNU General Public License v3.0
from Executor-Cheng
public void LogOut()
{
IDictionary<string, object> data = new Dictionary<string, object>
{
["csrf_token"] = GetCsrfToken(),
};
NeteaseMusicApi.CryptoHelper.Encrypted encrypted = NeteaseMusicApi.CryptoHelper.WebApiEncrypt(data);
try
{
string json = Session.HttpPost("https://music.163.com/weapi/logout", encrypted.GetFormdata(), userAgent: NeteaseMusicApi.DefaultUserAgent);
JObject j = JObject.Parse(json);
if (j["code"].ToObject<int>() != 0)
{
NotImplementedException exception = new NotImplementedException($"未知的服务器返回");
exception.Data.Add("Response", j.ToString());
throw exception;
}
}
finally
{
Session.Reset();
}
}
19
Source : NeteaseMusicApi.cs
with GNU General Public License v3.0
from Executor-Cheng
with GNU General Public License v3.0
from Executor-Cheng
public void GetUserInfo()
{
JObject data = new JObject(new JProperty("csrf_token", GetCsrfToken()));
var encrypted = NeteaseMusicApi.CryptoHelper.WebApiEncrypt(data);
string json = Session.HttpPost($"https://music.163.com/weapi/v1/user/detail/{UserId}", encrypted.GetFormdata(), userAgent: NeteaseMusicApi.DefaultUserAgent);
JObject j = JObject.Parse(json);
if (j["code"].ToObject<int>() == 200)
{
UserName = j["profile"]["nickname"].ToString();
VipType = j["profile"]["vipType"].ToObject<int>();
}
else
{
throw new NotImplementedException($"未知的服务器返回:{j.ToString(0)}");
}
;
}
19
Source : NeteaseMusicApi.cs
with GNU General Public License v3.0
from Executor-Cheng
with GNU General Public License v3.0
from Executor-Cheng
private void HandleLoginResult(string json)
{
JObject j = JObject.Parse(json);
int code = j["code"].ToObject<int>();
try
{
switch (code)
{
case 200:
{
UserName = j["profile"]["nickname"].ToString();
UserId = j["profile"]["userId"].ToObject<long>();
VipType = j["profile"]["vipType"].ToObject<int>();
LoginStatus = true;
break;
}
case 501:
{
throw new ArgumentException("账号不存在");
}
case 502:
case 509:
{
LoginStatus = false;
throw new ArgumentException(j["msg"].ToString());
}
default:
{
LoginStatus = false;
NotImplementedException exception = new NotImplementedException($"未知的服务器返回");
exception.Data.Add("Response", j.ToString());
throw exception;
}
}
}
catch (NullReferenceException)
{
System.Windows.MessageBox.Show($"处理登录返回失败:{json}", "Debug - 本地网易云喵块", 0, System.Windows.MessageBoxImage.Error);
throw;
}
}
19
Source : ProxyClientTests.cs
with MIT License
from extremecodetv
with MIT License
from extremecodetv
private async Task<Dictionary<string, string>> GetJsonDictionaryValue(HttpResponseMessage response, string valueName)
{
JToken token;
var source = await response.Content.ReadreplacedtringAsync();
var obj = JObject.Parse(source);
var result = obj.TryGetValue(valueName, out token);
if (!result)
{
return null;
}
return token.ToObject<Dictionary<string, string>>();
}
19
Source : NMMod.cs
with MIT License
from FelisDiligens
with MIT License
from FelisDiligens
public void RequestInformation()
{
if (!NexusMods.User.IsLoggedIn)
{
MsgBox.ShowID("nexusModsNotLoggedIn", MessageBoxIcon.Information);
return;
}
// Make API request:
APIRequest request = new APIRequest("https://api.nexusmods.com/v1/games/fallout76/mods/" + this.ID + ".json");
request.Headers["apikey"] = NexusMods.User.APIKey;
request.Execute();
if (request.Success && request.StatusCode == HttpStatusCode.OK)
{
/*
* Get data:
*/
JObject json = request.GetJObject();
// Is the mod available?
if (json["available"].ToObject<bool>())
{
this.replacedle = json["name"].ToString();
this.Author = json["author"].ToString();
this.Uploader = json["uploaded_by"].ToString();
this.Summary = json["summary"].ToString();
this.EndorsementCount = json["endorsement_count"].ToObject<int>();
this.CreatedTimestamp = json["created_timestamp"].ToObject<long>();
this.UpdatedTimestamp = json["updated_timestamp"].ToObject<long>();
this.ContainsAdultContent = json["contains_adult_content"].ToObject<bool>();
this.ThumbnailURL = json["picture_url"].ToString();
this.LatestVersion = json["version"].ToString();
JObject endorsement = (JObject)json["endorsement"];
string endorseStatus = endorsement["endorse_status"].ToString();
switch (endorseStatus)
{
case "Endorsed":
this.Endorsement = EndorseStatus.Endorsed;
break;
case "Abstained":
this.Endorsement = EndorseStatus.Abstained;
break;
case "Undecided":
default:
this.Endorsement = EndorseStatus.Undecided;
break;
}
/*
* Download thumbnail:
*/
if (!Directory.Exists(NexusMods.ThumbnailsPath))
Directory.CreateDirectory(NexusMods.ThumbnailsPath);
// If user opted in:
if (IniFiles.Config.GetBool("NexusMods", "bDownloadThumbnailsOnUpdate", true))
{
try
{
// Example: "https://staticdelivery.nexusmods.com/mods/2590/images/84/84-1542823522-262308780.png"
// Download if non-existent:
ThumbnailFileName = $"thumb_{this.ID}.jpg"; // Path.GetExtension(Path.GetFileName(uri.LocalPath));
if (!File.Exists(ThumbnailFilePath))
{
var thumbRequest = WebRequest.Create(this.ThumbnailURL);
using (var thumbResponse = thumbRequest.GetResponse())
using (var stream = thumbResponse.GetResponseStream())
{
// Create a thumbnail (small *.jpg) from the downloaded image:
Image image = Image.FromStream(stream);
Utils.MakeThumbnail(image, ThumbnailFilePath, false, 400, 160, 90L);
}
}
}
catch (Exception ex)
{
// TODO: Handle: Thumbnail couldn't be downloaded.
Console.WriteLine($"Couldn't download thumbnail.\n{ex.GetType().Name}: {ex.Message}");
}
}
}
}
else
{
// TODO: Handle: Couldn't retrieve info.
Console.WriteLine($"Couldn't retrieve info.\n{request.Exception.GetType().Name}: {request.Exception.Message}\n{request.ResponseText}");
}
this.LastAccessTimestamp = Utils.GetUnixTimeStamp();
}
19
Source : GreeterService.cs
with MIT License
from foyzulkarim
with MIT License
from foyzulkarim
public override async Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
{
var user = context.GetHttpContext().User;
var userName = user.Idenreplacedy.Name;
var claimsIdenreplacedy = user.Idenreplacedies.First() as ClaimsIdenreplacedy;
var claim = claimsIdenreplacedy.Claims.First(x => x.Type == "jti");
var jti = claim.Value;
string msg = "";
var inValid = string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(jti) || string.IsNullOrWhiteSpace(request.Name);
if (inValid)
{
return new HelloReply
{
Message = "Unauthorized"
};
}
var redisValue = await redisService.Get(userName);
if (string.IsNullOrWhiteSpace(redisValue))
{
return new HelloReply
{
Message = "Unauthorized"
};
}
var dbValue = (dynamic)JsonConvert.DeserializeObject(redisValue);
var jtiArray = ((dbValue as dynamic).jtis as dynamic) as JArray;
var list = jtiArray.ToObject<List<string>>();
var validJti = list.Exists(x => x == jti);
if (!validJti)
{
return new HelloReply
{
Message = "Unauthorized"
};
}
var permissionViewModels = JsonConvert.DeserializeObject<List<dynamic>>(
((dbValue as dynamic).resources as JValue).ToString());
var permitted = permissionViewModels.Exists(x => x.Name == request.Name && Convert.ToBoolean(x.IsAllowed));
if (!permitted)
{
return new HelloReply
{
Message = "Forbid"
};
}
return new HelloReply
{
Message = string.Empty
};
}
19
Source : RedisService.cs
with MIT License
from foyzulkarim
with MIT License
from foyzulkarim
public async Task<bool> RemoveJti(string key, string jti)
{
var db = _redis.GetDatabase();
var redisValue = await db.StringGetAsync(key);
var dbValue = (dynamic) JsonConvert.DeserializeObject(redisValue.ToString());
var array = ((dbValue as dynamic).jtis as dynamic) as JArray;
var jtiList = array.ToObject<List<string>>();
jtiList.Remove(jti);
var value = new {jtis = jtiList, resources = ((dbValue as dynamic).resources as JValue).ToString()};
var stringSet = await db.StringSetAsync(key, JsonConvert.SerializeObject(value));
return stringSet;
}
19
Source : RedisService.cs
with MIT License
from foyzulkarim
with MIT License
from foyzulkarim
public async Task<bool> Set(string key, TimeSpan expiry, string tokenJti, List<dynamic> resources)
{
var db = _redis.GetDatabase();
var redisValue = await db.StringGetAsync(key);
IList<string> jtiList = new List<string>();
if (redisValue.IsNullOrEmpty)
{
var jti = tokenJti;
jtiList.Add(jti);
}
else
{
var dbValue = (dynamic) JsonConvert.DeserializeObject(redisValue.ToString());
var array = ((dbValue as dynamic).jtis as dynamic) as JArray;
array.Add(tokenJti);
jtiList = array.ToObject<List<string>>();
}
var value = new {jtis = jtiList, resources = resources};
var stringSet = await db.StringSetAsync(key, JsonConvert.SerializeObject(value), expiry);
return stringSet;
}
19
Source : DownloadClient.cs
with GNU General Public License v3.0
from fraxiinus
with GNU General Public License v3.0
from fraxiinus
public async Task<string[]> GetDataDragonVersionStringsAsync()
{
const string url = @"https://ddragon.leagueoflegends.com/api/versions.json";
HttpResponseMessage response;
using (var request = new HttpRequestMessage(HttpMethod.Get, url))
{
request.Headers.UserAgent.ParseAdd(_userAgent);
request.Headers.Accept.ParseAdd("text/json");
try
{
response = await _httpClient.SendAsync(request).ConfigureAwait(true);
}
catch (HttpRequestException ex)
{
_log.Error($"Unable to send HTTP request to {url}, Exception: {ex}");
throw;
}
}
if (response.IsSuccessStatusCode)
{
_log.Information($"Made successful HTTP request {url}");
var json = await response.Content.ReadreplacedtringAsync().ConfigureAwait(true);
return JArray.Parse(json).ToObject<string[]>();
}
else
{
throw new HttpRequestException($"HTTP request to Data Dragon failed on {(int)response.StatusCode}, {url}");
}
}
19
Source : RoflParser.cs
with MIT License
from fraxiinus
with MIT License
from fraxiinus
private static MatchMetadata ParseMetadata(byte[] bytedata)
{
var result = new MatchMetadata { };
var jsonstring = Encoding.UTF8.GetString(bytedata);
var jsonobject = JObject.Parse(jsonstring);
result.GameDuration = (ulong)jsonobject["gameLength"];
result.GameVersion = (string)jsonobject["gameVersion"];
result.LastGameChunkID = (uint)jsonobject["lastGameChunkId"];
result.LastKeyframeID = (uint)jsonobject["lastKeyFrameId"];
// Create new lists of player dictionaries for sorting
var blueTeam = new List<Dictionary<string, string>>();
var redTeam = new List<Dictionary<string, string>>();
// Sort blue and red teams
foreach (JObject player in JArray.Parse(((string)jsonobject["statsJson"]).Replace(@"\", "")))
{
if(player["TEAM"].ToString() == "100")
{
blueTeam.Add(player.ToObject<Dictionary<string, string>>());
}
else if (player["TEAM"].ToString() == "200")
{
redTeam.Add(player.ToObject<Dictionary<string, string>>());
}
}
result.BluePlayers = blueTeam.ToArray();
result.RedPlayers = redTeam.ToArray();
//result.Players = JArray.Parse(((string)jsonobject["statsJson"]).Replace(@"\", ""));
return result;
}
19
Source : LrfParser.cs
with MIT License
from fraxiinus
with MIT License
from fraxiinus
private static (MatchMetadata, JObject) ParseMetadata(byte[] bytedata)
{
var result = new MatchMetadata { };
var jsonstring = Encoding.UTF8.GetString(bytedata);
var jsonobject = JObject.Parse(jsonstring);
result.GameDuration = ((ulong)jsonobject["matchLength"] * 1000);
result.GameVersion = (string)jsonobject["clientVersion"];
result.LastGameChunkID = 0;
result.LastKeyframeID = 0;
// Create new lists of player dictionaries for sorting
var blueTeam = new List<Dictionary<string, string>>();
var redTeam = new List<Dictionary<string, string>>();
// Sort blue and red teams
foreach (JObject player in (JArray)jsonobject["players"])
{
if (player["team"].ToString() == "1")
{
var playerDict = player.ToObject<Dictionary<string, string>>();
playerDict = TranslatePlayerDictionary(playerDict, (string)jsonobject["map"]);
blueTeam.Add(playerDict);
}
else if (player["team"].ToString() == "2")
{
var playerDict = player.ToObject<Dictionary<string, string>>();
playerDict = TranslatePlayerDictionary(playerDict, (string)jsonobject["map"]);
redTeam.Add(playerDict);
}
}
result.BluePlayers = blueTeam.ToArray();
result.RedPlayers = redTeam.ToArray();
//result.Players = JArray.Parse(((string)jsonobject["statsJson"]).Replace(@"\", ""));
return (result, jsonobject);
}
19
Source : RequestManager.cs
with MIT License
from fraxiinus
with MIT License
from fraxiinus
private async Task<string[]> GetDataDragonVersionStringsAsync()
{
// TODO Maybe make this cache?
// So it saves the file somewhere,
// if the set method doesn't find any matches, make a new request
using (WebClient wc = new WebClient())
{
string result = await wc.DownloadStringTaskAsync(@"https://ddragon.leagueoflegends.com/api/versions.json");
return JArray.Parse(result).ToObject<string[]>();
}
}
19
Source : InventoryKeyDB.cs
with GNU General Public License v3.0
from FromDarkHell
with GNU General Public License v3.0
from FromDarkHell
public static bool LoadInventoryKeyDatabase(string JSONString) {
var lastDB = KeyDatabase;
try {
JObject db = JObject.FromObject(JsonConvert.DeserializeObject(JSONString));
KeyDictionary = db.ToObject<Dictionary<string, string>>();
KeyDatabase = db;
var invKeys = KeyDictionary.Values.Distinct();
ItemTypeToKey = new Dictionary<string, List<string>>() {
{ "Grenades", invKeys.Where(x => x.Contains("_GrenadeMod_")).ToList() },
{ "Shields", invKeys.Where(x => x.Contains("_Shield_")).ToList() },
{ "Clreplaced Mods", invKeys.Where(x => x.Contains("_ClreplacedMod_")).ToList() },
{ "Artifacts", invKeys.Where(x => x.Contains("_Artifact_")).ToList() },
{ "replacedault Rifles", invKeys.Where(x => x.Contains("_AR_")).ToList() },
{ "Pistols", invKeys.Where(x => x.Contains("_Pistol_") || x.Contains("_PS_")).ToList() },
{ "SMGs", invKeys.Where(x => x.Contains("_SM_") || x.Contains("_SMG")).ToList() },
{ "Heavy Weapons", invKeys.Where(x => x.Contains("_HW_")).ToList() },
{ "Shotguns", invKeys.Where(x => x.Contains("_SG_") || x.Contains("_Shotgun_")).ToList() },
{ "Sniper Rifles", invKeys.Where(x => x.Contains("_SR_")).ToList() },
{ "Eridian Fabricator", invKeys.Where(x => x.Contains("EridianFabricator")).ToList() },
{ "Customizations", invKeys.Where(x => x.Contains("Customization")).ToList() }
};
return true;
}
catch (Exception) {
KeyDatabase = lastDB;
}
return false;
}
19
Source : InventoryNameDatabase.cs
with GNU General Public License v3.0
from FromDarkHell
with GNU General Public License v3.0
from FromDarkHell
public static bool LoadInventoryNameDatabase(string JSONString) {
var lastDB = NameDatabase;
try {
JObject db = JObject.FromObject(JsonConvert.DeserializeObject(JSONString));
NameDictionary = db.ToObject<Dictionary<string, string>>();
NameDatabase = db;
return true;
}
catch (Exception) {
NameDatabase = lastDB;
}
return false;
}
19
Source : InventoryNameDatabase.cs
with GNU General Public License v3.0
from FromDarkHell
with GNU General Public License v3.0
from FromDarkHell
public static bool LoadInventoryPrefixDatabase(string JSONString) {
var lastDB = PrefixDatabase;
try {
JObject db = JObject.FromObject(JsonConvert.DeserializeObject(JSONString));
PrefixDictionary = db.ToObject<Dictionary<string, string>>();
PrefixDatabase = db;
return true;
}
catch (Exception) {
PrefixDatabase = lastDB;
}
return false;
}
19
Source : InventorySerialDatabase.cs
with GNU General Public License v3.0
from FromDarkHell
with GNU General Public License v3.0
from FromDarkHell
public static bool LoadInventoryDataDatabase(string JSONString) {
var originalDB = InventoryDataDatabase;
try {
InventoryDataDatabase = JObject.FromObject(JsonConvert.DeserializeObject(JSONString));
BalanceToData = InventoryDataDatabase.ToObject<Dictionary<string, string>>();
return true;
}
catch(Exception ex) {
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
InventoryDataDatabase = originalDB;
}
return false;
}
19
Source : InventorySerialDatabase.cs
with GNU General Public License v3.0
from FromDarkHell
with GNU General Public License v3.0
from FromDarkHell
public static bool LoadPartDatabase(string JSONString) {
var originalDB = ValidPartDatabase;
try {
ValidPartDatabase = JObject.FromObject(JsonConvert.DeserializeObject(JSONString));
PartDatabase = new Dictionary<string, Dictionary<string, List<string>>>();
foreach (JProperty token in ValidPartDatabase.Children<JProperty>()) {
string part = token.Name;
JObject value = token.Value as JObject;
var dependencies = (value["Dependencies"] as JArray).ToObject<List<string>>();
var excluders = (value["Excluders"] as JArray).ToObject<List<string>>();
PartDatabase.Add(part, new Dictionary<string, List<string>>() {
{ "Dependencies", dependencies },
{ "Excluders", excluders }
});
}
return true;
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
ValidPartDatabase = originalDB;
}
return false;
}
19
Source : InventorySerialDatabase.cs
with GNU General Public License v3.0
from FromDarkHell
with GNU General Public License v3.0
from FromDarkHell
public static bool LoadGenericsDatabase(string JSONString) {
var originalDB = ValidGenericDatabase;
try {
ValidGenericDatabase = JObject.FromObject(JsonConvert.DeserializeObject(JSONString));
GenericsDatabase = new Dictionary<string, List<string>>();
foreach (JProperty token in ValidGenericDatabase.Children<JProperty>()) {
string part = token.Name;
var value = (token.Value as JArray).ToObject<List<string>>();
GenericsDatabase.Add(part, value);
}
return true;
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
ValidGenericDatabase = originalDB;
}
return false;
}
19
Source : JsonPathTests.cs
with MIT License
from fuse-open
with MIT License
from fuse-open
[Test]
public void JsonAbsoluteDirectoryPath()
{
var path = DirectoryPath.GetTempPath();
var json = JToken.FromObject(path);
var path2 = json.ToObject<AbsoluteDirectoryPath>();
replacedert.AreEqual(path, path2);
}
19
Source : JsonPathTests.cs
with MIT License
from fuse-open
with MIT License
from fuse-open
[Test]
public void JsonAbsoluteFilePath()
{
var path = FilePath.CreateTempFile();
var json = JToken.FromObject(path);
var path2 = json.ToObject<AbsoluteFilePath>();
replacedert.AreEqual(path, path2);
}
19
Source : JsonPathTests.cs
with MIT License
from fuse-open
with MIT License
from fuse-open
[Test]
public void JsonRelativeDirectoryPath()
{
var path = RelativeDirectoryPath.Empty / ".." / "Programs" / "Fuse" / "Data";
var json = JToken.FromObject(path);
var path2 = json.ToObject<RelativeDirectoryPath>();
replacedert.AreEqual(path, path2);
}
19
Source : JsonPathTests.cs
with MIT License
from fuse-open
with MIT License
from fuse-open
[Test]
public void JsonRelativeFilePath()
{
var path = RelativeDirectoryPath.Empty / ".." / "Programs" / "Fuse" / new FileName("Data.dat");
var json = JToken.FromObject(path);
var path2 = json.ToObject<RelativeFilePath>();
replacedert.AreEqual(path, path2);
}
19
Source : DotNetBuild.cs
with MIT License
from fuse-open
with MIT License
from fuse-open
public static DotNetBuild Parse(JToken json)
{
return new DotNetBuild(
replacedembly: json["replacedembly"].ToObject<string>(),
entrypointClreplaced: json["EntrypointClreplaced"].ToObject<string>(),
generatedTypeNames: json["GeneratedTypeNames"].ToObject<Dictionary<JToken, JToken>>().ToDictionary(
kv => kv.Key.ToObject<string>(),
kv => kv.Value.ToObject<string>()));
}
See More Examples