public void TestJsonFx() { var reader = new JsonFx.Json.JsonReader(); string input = @"{ ""foo"": true, ""array"": [ 42, false, ""Hello!"", null ] }"; dynamic output = reader.Read(input); Console.WriteLine(output.array[0]); // 42 }
public void ReadSettings() { var filePath = new System.IO.FileInfo(Manager.ServerDirectory.FullName + "/HttpInfoServer.json"); if (!filePath.Exists) { Log.Info("No HttpInfoServer.json, using default settings"); return; } try { var txt = System.IO.File.ReadAllText(filePath.FullName); var reader = new JsonFx.Json.JsonReader(); var dictionary = (Dictionary <string, object>)reader.Read(txt); TryGetValue(dictionary, "Port", ref Port); TryGetValue(dictionary, "PortHttps", ref PortHttps); TryGetValue(dictionary, "HelpTextWebsite", ref HelpTextWebsite); TryGetValue(dictionary, "PublicMode", ref PublicMode); TryGetValue(dictionary, "PrivateModeIps", ref PrivateModeIps); TryGetValue(dictionary, "PrivateModeTokens", ref PrivateModeTokens); Log.Info("Loaded settings from HttpInfoServer.json"); } catch (Exception e) { Log.Error($"Couldn't read HttpInfoServer.json. Is your json malformed?\n{e}"); } Log.Info($"{PrivateModeIps.Length} PrivateModeIps; {PrivateModeTokens.Length} PrivateModeTokens;"); }
private static void DeleteTemplates(string apikey, DirectoryInfo backupDir, string templateName = null) { var reader = new JsonReader(); var httpHelper = new HttpHelper(); //make backups.. always var templates = ExportTemplatesToFolder(apikey, backupDir, templateName); if (templates.Any()) { foreach (var template in templates) { //check if we wanted to delete a single template if (!string.IsNullOrWhiteSpace(templateName) && !templateName.Equals(template.Key, StringComparison.OrdinalIgnoreCase)) { //this seems to be the only way to get single template by name (not slug!) continue; } dynamic t = reader.Read(template.Value); //delete, take slug and use as name string name = t.slug; var deleteTemplate = httpHelper.Post(Mandrillurl + "/templates/delete.json", new {key = apikey, name}).Result; Console.WriteLine(string.Format("Template delete result {0}: {1} - {2}", name, deleteTemplate.Code, deleteTemplate.StatusDescription)); } } }
public void JsonFx_POCO() { var jsr = new JsonFx.Json.JsonReader(); var jsw = new JsonFx.Json.JsonWriter(); var f = new Foo { Name = "peter", Age = 42, TooOld = false }; f.Bars = new List <Bar>(); f.Bars.Add(new Bar() { Str = "Isestr", Ort = "Hamburg" }); var json = jsw.Write(f); Console.WriteLine(json); dynamic df = jsr.Read(json); Assert.AreEqual("peter", df.Name); Assert.IsFalse(df.TooOld); Assert.AreEqual(1, df.Bars.Length); var foo = jsr.Read <Foo>(json); Console.WriteLine(foo.Name); }
public void ReadSettings() { var filePath = new System.IO.FileInfo(Manager.ServerDirectory.FullName + "/ServerListTools.json"); if (!filePath.Exists) { Log.Info("No ServerListTools.json, using default settings"); return; } try { var txt = System.IO.File.ReadAllText(filePath.FullName); var reader = new JsonFx.Json.JsonReader(); var dictionary = (Dictionary <string, object>)reader.Read(txt); TryGetValue(dictionary, "LogServersFrequency", ref LogServersFrequency); TryGetValue(dictionary, "HealthCheckFrequency", ref HealthCheckFrequency); TryGetValue(dictionary, "HealthCheckDelay", ref HealthCheckDelay); TryGetValue(dictionary, "HealthCheckTimeout", ref HealthCheckTimeout); Log.Info("Loaded settings from ServerListTools.json"); } catch (Exception e) { Log.Error($"Couldn't read ServerListTools.json. Is your json malformed?\n{e}"); } }
internal void RespondChat() { var writer = new JsonFx.Json.JsonWriter(); if (!IsPrivateMode || DistancePlayer == null) { Context.Response.StatusCode = 401; Context.Response.StatusDescription = "Unauthorized"; Response = writer.Write(new { ErrorCode = 401, }); return; } var reader = new JsonFx.Json.JsonReader(); var data = (Dictionary <string, object>)reader.Read(Body); string message = (string)data["Message"]; var chatColor = "[" + Distance::ColorEx.ColorToHexNGUI(Distance::ColorEx.PlayerRainbowColor(DistancePlayer.Index)) + "]"; Plugin.Server.SayChat(new DistanceChat(chatColor + DistancePlayer.Name + "[FFFFFF]: " + message + "[-]") { SenderGuid = DistancePlayer.UnityPlayerGuid, ChatType = DistanceChat.ChatTypeEnum.PlayerChatMessage, ChatDescription = "HttpServer:PlayerChat" }); Response = writer.Write(new { Success = true, }); }
public void JsonFx_Expando() { var jsr = new JsonFx.Json.JsonReader(); var jsw = new JsonFx.Json.JsonWriter(); dynamic cmd = new ExpandoObject(); cmd.cmd = "Anzeigen"; dynamic frage = new ExpandoObject(); frage.Text = "Welches Tier ist kein Säugetier?"; cmd.payload = frage; var antwortoptionen = new List<dynamic>(); dynamic antwortoption = new ExpandoObject(); antwortoption.Text = "Hund"; antwortoption.IstKorrekt = false; antwortoptionen.Add(antwortoption); antwortoption = new ExpandoObject(); antwortoption.Text = "Ameise"; antwortoption.IstKorrekt = true; antwortoptionen.Add(antwortoption); frage.Antwortoptionen = antwortoptionen; var json = jsw.Write(cmd); Console.WriteLine(json); dynamic dc = jsr.Read(json); Console.WriteLine(dc.cmd); Console.WriteLine(dc.payload.Text); foreach (dynamic ao in dc.payload.Antwortoptionen) Console.WriteLine(" {0}, {1}", ao.Text, ao.IstKorrekt); }
public void OnSignInSuccess(string json) { try { JsonFx.Json.JsonReaderSettings jsonSettings = new JsonFx.Json.JsonReaderSettings(); jsonSettings.TypeHintName = "__type"; JsonFx.Json.JsonReader jsonReader = new JsonFx.Json.JsonReader(json, jsonSettings); UserDataModel loginResponse = jsonReader.Deserialize <UserDataModel>(); ITTDataCache.Instance.UpdateSessionManager(loginResponse); ITTGoogleAnalytics.Instance.googleAnalytics.LogEvent(new EventHitBuilder() .SetEventCategory("Registration - Sign In Screen") .SetEventAction("Sign In Success - Sign In Screen") .SetEventLabel("User has successfully logged into their account.")); if (null != OnSignInSuccessHandler) { OnSignInSuccessHandler(); OnSignInSuccessHandler = null; } StartCoroutine(OnHide()); } catch (Exception ex) { Debug.LogError("OnSignInSuccess error. " + ex.Message); } }
public void ReadSettings() { var filePath = new System.IO.FileInfo(Manager.ServerDirectory.FullName + "/RealmsFilter.json"); if (!filePath.Exists) { Log.Info("No RealmsFilter.json, using default settings"); return; } try { var txt = System.IO.File.ReadAllText(filePath.FullName); var reader = new JsonFx.Json.JsonReader(); var dictionary = (Dictionary <string, object>)reader.Read(txt); string filterMode = null; TryGetValue(dictionary, "FilterMode", ref filterMode); Log.Debug($"filterMode: {filterMode}"); if (filterMode != null) { FilterMode = (FilterModeType)Enum.Parse(typeof(FilterModeType), filterMode); } Log.Info("Loaded settings from RealmsFilter.json"); } catch (Exception e) { Log.Error($"Couldn't read BasicAutoServer.json. Is your json malformed?\n{e}"); } }
internal void RespondLink() { var writer = new JsonFx.Json.JsonWriter(); if (!IsPrivateMode) { Context.Response.StatusCode = 401; Context.Response.StatusDescription = "Unauthorized"; Response = writer.Write(new { ErrorCode = 401, }); return; } var reader = new JsonFx.Json.JsonReader(); var data = (Dictionary <string, object>)reader.Read(Body); string guid = (string)data["Guid"]; Plugin.Links[SessionId] = guid; Response = writer.Write(new { Success = true, }); if (data.ContainsKey("SendIpWarning") && (bool)data["SendIpWarning"]) { var player = Plugin.Manager.Server.GetDistancePlayer(guid); if (player != null) { Plugin.Server.SayLocalChat(player.UnityPlayer, DistanceChat.Server("HttpServer:Link", "Your game session has been automatically linked with a web session. You can now vote and chat from the website.\nIf this wasn't you, type [00FFFF]/unlink[-]")); } } }
internal void RespondServerChat() { var writer = new JsonFx.Json.JsonWriter(); if (!IsPrivateMode) { Context.Response.StatusCode = 401; Context.Response.StatusDescription = "Unauthorized"; Response = writer.Write(new { ErrorCode = 401, }); return; } var reader = new JsonFx.Json.JsonReader(); var data = (Dictionary <string, object>)reader.Read(Body); string message = (string)data["Message"]; object sender = "server"; data.TryGetValue("Sender", out sender); Plugin.Server.SayChat(new DistanceChat(message) { SenderGuid = (string)sender, ChatType = DistanceChat.ChatTypeEnum.ServerCustom, ChatDescription = "HttpServer:ServerChat" }); Response = writer.Write(new { Success = true, }); }
private static List <T> DeserializeWithJsonFx <T>(List <string> jsonStrings) { var reader = new JsonFxReader(); var objects = jsonStrings.Select(reader.Read <T>).ToList(); return(objects); }
public static IEnumerator getUpdates(updateCallback callback) { // The async http request code here is a mess cobbled together from various posts // on the internet. Non-async requests would freeze up the client. var webRequest = (HttpWebRequest)WebRequest.Create(updateCheckURL); webRequest.UserAgent = "Corecii-Spectrum-ServerMod"; webRequest.Method = "GET"; webRequest.Accept = "application/vnd.github.v3+json"; // NOTE: THIS IS NOT SECURE. IT DOES NOT CHECK THE SSL CERTIFICATE // I was getting SSL errors making the web request. After looking it up, it appeared // that the cause was an old version of whatever provides the network stuff. I // would assume that can't be updated unless Distance is updated, but I don't know. // Anyways, this is not too bad just for one request. If it's MitM'd, the worst case // scenario is that the player checks github for an update and finds nothing new. // After making the request, the original certificate checker is put back in place. HttpWebResponse response = null; Action wrapperAction = () => { var previousCallback = ServicePointManager.ServerCertificateValidationCallback; ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); }; webRequest.BeginGetResponse(new AsyncCallback((iar) => { response = (HttpWebResponse)((HttpWebRequest)iar.AsyncState).EndGetResponse(iar); ServicePointManager.ServerCertificateValidationCallback = previousCallback; }), webRequest); }; IAsyncResult asyncResult = wrapperAction.BeginInvoke(new AsyncCallback((iar) => { var action = (Action)iar.AsyncState; action.EndInvoke(iar); }), wrapperAction); while (!asyncResult.IsCompleted || response == null) { yield return(null); } /// if (response.StatusCode != HttpStatusCode.OK) { Console.WriteLine("There was an error checking for a newer version of ServerMod"); yield break; } var stream = response.GetResponseStream(); var reader = new StreamReader(stream); var result = reader.ReadToEnd(); response.Close(); var jsonReader = new JsonFx.Json.JsonReader(); var releases = jsonReader.Read <List <Dictionary <string, object> > >(result); callback(releases); /// yield break; }
public void TestJsonFxVSLinq2Json() { var reader = new JsonFx.Json.JsonReader(); string input = @"{ 'CPU': 'Intel', 'Drives': [ 'DVD read/writer', '500 gigabyte hard drive' ] }"; dynamic output = reader.Read(input); Assert.AreEqual(output.CPU, "Intel"); Assert.AreEqual(output.Drives[0], "DVD read/writer"); }
public object Deserialize(byte[] messagePackageData, int offset, int count) { var stream = new MemoryStream(messagePackageData, offset, count); var reader = new JsonFx.Json.JsonReader(stream); var package = reader.Deserialize <MessagePackage>(); var message = JsonFx.Json.JsonReader.Deserialize(package.serialized, messageTypeTable[package.name]); return(message); }
public static string GetPublicIP() { dynamic oIP = null; using (System.Net.WebClient wc = new System.Net.WebClient()) { string strJsonIP = wc.DownloadString("http://jsonip.com/"); JsonFx.Json.JsonReader r = new JsonFx.Json.JsonReader(); oIP = r.Read(strJsonIP); } return oIP.ip; }
private static dynamic ParseConfigurationFromResources() { var jsonTests = Assembly.GetExecutingAssembly().GetManifestResourceStream("Stabilograph.Protocol.Tests.settings.conf"); var sReader = new StreamReader(jsonTests); var jReader = new JsonFx.Json.JsonReader(); dynamic parsed = jReader.Read(sReader.ReadToEnd()); dynamic scope = ConfigObject.FromExpando(parsed); return scope; }
/// <summary> /// Deserialize the specified message using either JSONFX or NEWTONSOFT.JSON. /// The functionality is based on the pre-compiler flag /// </summary> /// <param name="message">Message.</param> public static T Deserialize <T>(string message) { object retMessage; #if (USE_JSONFX) var reader = new JsonFx.Json.JsonReader(); retMessage = reader.Read <T>(message); #else retMessage = JsonConvert.DeserializeObject <T>(message); #endif return((T)retMessage); }
public static string GetPublicIP() { dynamic oIP = null; using (System.Net.WebClient wc = new System.Net.WebClient()) { string strJsonIP = wc.DownloadString("http://jsonip.com/"); JsonFx.Json.JsonReader r = new JsonFx.Json.JsonReader(); oIP = r.Read(strJsonIP); } return(oIP.ip); }
public void ReadSettings() { var filePath = new System.IO.FileInfo(Manager.ServerDirectory.FullName + "/VoteCommands.json"); if (!filePath.Exists) { Log.Info("No VoteCommands.json, using default settings"); return; } try { var txt = System.IO.File.ReadAllText(filePath.FullName); var reader = new JsonFx.Json.JsonReader(); var dictionary = (Dictionary <string, object>)reader.Read(txt); TryGetValue(dictionary, "SkipThreshold", ref SkipThreshold); TryGetValue(dictionary, "ExtendThreshold", ref ExtendThreshold); TryGetValue(dictionary, "ExtendTime", ref ExtendTime); TryGetValue(dictionary, "VoteNotSafetyTime", ref VoteNotSafetyTime); TryGetValue(dictionary, "BadVoterDetectionCutoff", ref BadVoterDetectionCutoff); TryGetValue(dictionary, "BadVoterPunishmentTime", ref BadVoterPunishmentTime); TryGetValue(dictionary, "SoftBlocklistThreshold", ref SoftBlocklistThreshold); TryGetValue(dictionary, "RecentMapsSoftBlocklistRoundCount", ref RecentMapsSoftBlocklistRoundCount); var listBase = new object[0]; TryGetValue(dictionary, "RequiredTags", ref listBase); foreach (object valBase in listBase) { RequiredTags.Add((string)valBase); } listBase = new object[0]; TryGetValue(dictionary, "SoftBlocklist", ref listBase); foreach (object valBase in listBase) { SoftBlocklistLevelIds.Add((string)valBase); } listBase = new object[0]; TryGetValue(dictionary, "HardBlocklist", ref listBase); foreach (object valBase in listBase) { HardBlocklistLevelIds.Add((string)valBase); } TryGetValue(dictionary, "SoftBlocklistDifficulties", ref listBase); foreach (object valBase in listBase) { SoftBlocklistDifficulties.Add((string)valBase); } Log.Info("Loaded settings from VoteCommands.json"); } catch (Exception e) { Log.Error($"Couldn't read VoteCommands.json. Is your json malformed?\n{e}"); } }
private static void LoadSettings() { lock (LockerObject) { using (var fileStream = System.IO.File.Open(_filePath, FileMode.OpenOrCreate, FileAccess.Read)) { using (TextReader tr = new StreamReader(fileStream)) { var jsonReader = new JsonFx.Json.JsonReader(); var deserialized = jsonReader.Read(tr, typeof(List <Setting>)); var settings = deserialized as List <Setting>; _settings = settings ?? new List <Setting>(); } } } }
public async Task RefreshAccessToken() { using (var wc = new WebClient()) { var c = new NameValueCollection(); c["refresh_token"] = settings.RefreshToken; c["client_id"] = settings.ClientID; c["client_secret"] = settings.ClientSecret; c["grant_type"] = "refresh_token"; byte[] result = await wc.UploadValuesTaskAsync("https://api.imgur.com/oauth2/token", "POST", c); var token = new JsonFx.Json.JsonReader(new DataReaderSettings(new DataContractResolverStrategy())) .Read<ImgurToken>(Encoding.ASCII.GetString(result)); SaveValues(token); } }
public async Task RefreshAccessToken() { using (var wc = new WebClient()) { var c = new NameValueCollection(); c["refresh_token"] = settings.RefreshToken; c["client_id"] = settings.ClientID; c["client_secret"] = settings.ClientSecret; c["grant_type"] = "refresh_token"; byte[] result = await wc.UploadValuesTaskAsync("https://api.imgur.com/oauth2/token", "POST", c); var token = new JsonFx.Json.JsonReader(new DataReaderSettings(new DataContractResolverStrategy())) .Read <ImgurToken>(Encoding.ASCII.GetString(result)); SaveValues(token); } }
public Settings(Type type, string postfix = "") { if (string.IsNullOrEmpty(postfix)) { FileName = $"{type.Assembly.GetName().Name}.json"; } else { FileName = $"{type.Assembly.GetName().Name}.{postfix}.json"; } if (File.Exists(FilePath)) { var saveLater = false; using (var sr = new StreamReader(FilePath)) { var json = sr.ReadToEnd(); var reader = new JsonFx.Json.JsonReader(); Section sec = null; try { sec = reader.Read <Section>(json); } catch { saveLater = true; } if (sec != null) { foreach (string k in sec.Keys) { Add(k, sec[k]); } } } if (saveLater) { Save(); } } }
public ActionResult AddFileGroup(int id) { var didacheDb = new DidacheDb(); // get data var reader = new JsonFx.Json.JsonReader(); dynamic json = reader.Read(HttpUtility.UrlDecode(Request.Form.ToString())); CourseFileGroup group = new CourseFileGroup(); group.CourseID = id; group.SortOrder = 9999; group.Name = json.name; didacheDb.CourseFileGroups.Add(group); didacheDb.SaveChanges(); return Json(new {groupid = group.GroupID, name=json.name, courseid= id}); }
private static void AddTemplateToAccount(string apikey, string templateContent) { var reader = new JsonReader(); dynamic template = reader.Read(templateContent); var httpHelper = new HttpHelper(); if (!string.IsNullOrWhiteSpace(apikey)) { //make sure to rewrite everything to the name string name = template.name; template.key = apikey; template.slug = name; var addResponse = httpHelper.Post(Mandrillurl + "/templates/add.json", template).Result; Console.WriteLine(string.Format("Template add result {0}: {1} - {2}", template.slug, addResponse.Code, addResponse.StatusDescription)); } }
public static dynamic GetCustomFilter() { var customFilter = GetQueryStringParam("customFilter"); if (customFilter != null) { //TO DO : temp fix customFilter = customFilter.Replace("$", "_"); JsonFx.Serialization.DataReaderSettings sgs = new JsonFx.Serialization.DataReaderSettings(); var jsonReader = new JsonFx.Json.JsonReader(sgs); return jsonReader.Read(customFilter); } else { return null; } }
public void JsonFx_POCO() { var jsr = new JsonFx.Json.JsonReader(); var jsw = new JsonFx.Json.JsonWriter(); var f = new Foo { Name = "peter", Age = 42, TooOld = false }; f.Bars = new List<Bar>(); f.Bars.Add(new Bar(){Str = "Isestr", Ort = "Hamburg"}); var json = jsw.Write(f); Console.WriteLine(json); dynamic df = jsr.Read(json); Assert.AreEqual("peter", df.Name); Assert.IsFalse(df.TooOld); Assert.AreEqual(1, df.Bars.Length); var foo = jsr.Read<Foo>(json); Console.WriteLine(foo.Name); }
/// <summary> /// Get the next message from the client and deal with it. /// </summary> /// <remarks>This is called once we know a message is available.</remarks> protected void HandleNextMessage() { String message; var reader = new JsonFx.Json.JsonReader(); try { message = ReadMessage(request); } catch (Exception ex) { if (ex is ObjectDisposedException || ex is OperationCanceledException) { throw; } Log($"Error decoding socket msg: {ex}"); return; } string key = ""; try { var input = reader.Read <Dictionary <string, object> >(message); //Log($"message: {input}"); //XXX what happens if message is empty or not a dict? key = input.Keys.First(); Log($"Calling message handlers: '{key}'"); CallMessageHandler(key, new ClientMessage(input[key])); } catch (ArgumentException ex) { SendErrorPacket(ex.Message, type: "ArgumentException"); return; } catch (Exception ex) { if (ex is ObjectDisposedException || ex is OperationCanceledException) { throw; } Log($"Error handling socket msg: {message}: {ex}"); } }
} // RenderEdit private GlossaryData[] fromJSON(string jsonString) { JsonFx.Json.JsonReader r = new JsonFx.Json.JsonReader(jsonString); object o = r.Deserialize(); if (o is Dictionary <string, object> ) { List <GlossaryData> ret = new List <GlossaryData>(); Dictionary <string, object> dict = (o as Dictionary <string, object>); foreach (string dictKey in dict.Keys) { if (dict[dictKey] is Dictionary <string, object> ) { Dictionary <string, object> dictObj = (dict[dictKey] as Dictionary <string, object>); GlossaryData newGData = new GlossaryData(); foreach (string objParam in dictObj.Keys) { if (string.Compare(objParam, "word", true) == 0) { newGData.word = dictObj[objParam].ToString(); } else if (string.Compare(objParam, "text", true) == 0) { newGData.description = dictObj[objParam].ToString(); } else if (string.Compare(objParam, "isAcronym", true) == 0) { newGData.isAcronym = Convert.ToBoolean(dictObj[objParam].ToString()); } } // foreach ret.Add(newGData); } } // foreach return(ret.ToArray()); } return(new GlossaryData[0]); }
public void JsonFx_Expando() { var jsr = new JsonFx.Json.JsonReader(); var jsw = new JsonFx.Json.JsonWriter(); dynamic cmd = new ExpandoObject(); cmd.cmd = "Anzeigen"; dynamic frage = new ExpandoObject(); frage.Text = "Welches Tier ist kein Säugetier?"; cmd.payload = frage; var antwortoptionen = new List <dynamic>(); dynamic antwortoption = new ExpandoObject(); antwortoption.Text = "Hund"; antwortoption.IstKorrekt = false; antwortoptionen.Add(antwortoption); antwortoption = new ExpandoObject(); antwortoption.Text = "Ameise"; antwortoption.IstKorrekt = true; antwortoptionen.Add(antwortoption); frage.Antwortoptionen = antwortoptionen; var json = jsw.Write(cmd); Console.WriteLine(json); dynamic dc = jsr.Read(json); Console.WriteLine(dc.cmd); Console.WriteLine(dc.payload.Text); foreach (dynamic ao in dc.payload.Antwortoptionen) { Console.WriteLine(" {0}, {1}", ao.Text, ao.IstKorrekt); } }
public void DeeplyNestedExpandoConvert () { // can't use GetUUT here since this will already involve conversion var name = "Types"; var jsonTests = Assembly.GetExecutingAssembly ().GetManifestResourceStream ("JsonConfig.Tests.JSON." + name + ".json"); var sReader = new StreamReader (jsonTests); var jReader = new JsonFx.Json.JsonReader (); dynamic parsed = jReader.Read (sReader.ReadToEnd ()); dynamic config = ConfigObject.FromExpando (parsed); Assert.AreEqual ("bar", config.Foo); Assert.AreEqual ("bar", ((ICollection<dynamic>) config.NestedArray).First ().Foo); Assert.AreEqual ("bar", config.DoubleNestedArray[0].One[0].Foo); Assert.IsInstanceOfType (typeof (ConfigObject[]), config.DoubleNestedArray[0].One); Assert.AreEqual ("bar", config.DoubleNestedArray[0].One[0].Foo); Assert.AreEqual (4, config.DoubleNestedArray[0].One.Length); Assert.AreEqual ("bar", config.DoubleNestedArray[1].Two[0].Foo); Assert.AreEqual ("bar", config.DoubleNestedArray[1].Two[3].Foo); Assert.AreEqual ("bar", config.DoubleNestedArray[1].Two[3].Foo); }
public void DeeplyNestedExpandoConvert() { // can't use GetUUT here since this will already involve conversion var name = "Types"; var jsonTests = Assembly.GetExecutingAssembly().GetManifestResourceStream("JsonConfig.Tests.JSON." + name + ".json"); var sReader = new StreamReader(jsonTests); var jReader = new JsonFx.Json.JsonReader(); dynamic parsed = jReader.Read(sReader.ReadToEnd()); dynamic config = ConfigObject.FromExpando(parsed); Assert.AreEqual("bar", config.Foo); Assert.AreEqual("bar", ((ICollection <dynamic>)config.NestedArray).First().Foo); Assert.AreEqual("bar", config.DoubleNestedArray[0].One[0].Foo); Assert.IsInstanceOfType(typeof(ConfigObject[]), config.DoubleNestedArray[0].One); Assert.AreEqual("bar", config.DoubleNestedArray[0].One[0].Foo); Assert.AreEqual(4, config.DoubleNestedArray[0].One.Length); Assert.AreEqual("bar", config.DoubleNestedArray[1].Two[0].Foo); Assert.AreEqual("bar", config.DoubleNestedArray[1].Two[3].Foo); Assert.AreEqual("bar", config.DoubleNestedArray[1].Two[3].Foo); }
public void ReadSettings() { var filePath = new System.IO.FileInfo(Manager.ServerDirectory.FullName + "/ChatFilter.json"); if (!filePath.Exists) { Log.Info("No ChatFilter.json, using default settings"); return; } try { var txt = System.IO.File.ReadAllText(filePath.FullName); var reader = new JsonFx.Json.JsonReader(); var dictionary = (Dictionary <string, object>)reader.Read(txt); var listBase = new object[0]; TryGetValue(dictionary, "FilteredWords", ref listBase); foreach (object valBase in listBase) { Log.Debug($"Reading FilteredWord {valBase}"); var val = (string)valBase; FilteredWords.Add(val); } var listBase2 = new System.Double[0]; TryGetValue(dictionary, "PunishLevels", ref listBase2); foreach (object valBase in listBase2) { Log.Debug($"Reading PunishLevel {valBase}"); var val = (double)valBase; PunishLevels.Add(val); } Log.Info("Loaded settings from ChatFilter.json"); } catch (Exception e) { Log.Error($"Couldn't read ChatFilter.json. Is your json malformed?\n{e}"); } }
public void ReadPersistentState() { var filePath = new System.IO.FileInfo(Manager.ServerDirectory.FullName + "/ChatFilterState.json"); if (!filePath.Exists) { Log.Info("No ChatFilterState.json, using default settings"); return; } try { var txt = System.IO.File.ReadAllText(filePath.FullName); var reader = new JsonFx.Json.JsonReader(); var dictionary = (Dictionary <string, object>)reader.Read(txt); var dictBase = new Dictionary <System.String, System.Object>(); Log.Debug($"TempMuted: {dictionary["TempMuted"].GetType()}; PlayerLevels: {dictionary["PlayerLevels"].GetType()}"); TryGetValue(dictionary, "TempMuted", ref dictBase); foreach (var pairBase in dictBase) { TempMuted[(string)pairBase.Key] = (double)pairBase.Value; } Log.Info($"Read {dictBase.Count} values from TempMuted"); var dictBase2 = new Dictionary <System.String, System.Object>(); TryGetValue(dictionary, "PlayerLevels", ref dictBase2); foreach (var pairBase in dictBase2) { PlayerLevels[(string)pairBase.Key] = (int)pairBase.Value; } Log.Info($"Read {dictBase2.Count} values from PlayerLevels"); Log.Info("Loaded settings from ChatFilterState.json"); } catch (Exception e) { Log.Error($"Couldn't read ChatFilterState.json. Is your json malformed?\n{e}"); } }
public static void BuildMenu(Assembly assem, Platform.ShellRightClickContextMenuClass menuClass, InfoStorageAttribute storage, List <string> list, MenuClick onClick) { try { // filter file extensions if required var filter = new List <string>(storage.FileExtensionFilter); var filesList = storage.ExpandFileNames ? BuildFileList(filter, list) : list; if (filesList.Count > 0) { string menuFormatJson = storage.MenuFormat; var jsonReader = new JsonFx.Json.JsonReader(); dynamic menuFormatObject = jsonReader.Read <dynamic>(menuFormatJson); dynamic menuFormatObjectChildren = menuFormatObject.children; AddChildren(assem, menuClass, storage, IntPtr.Zero, menuFormatObjectChildren, filesList, true, onClick); } } catch (Exception e) { MessageBox.Show(e.Message + "\r\n\r\n" + e.StackTrace, "Error whilst creating menu"); } }
public void OnSignInSuccess(string json) { try { JsonFx.Json.JsonReaderSettings jsonSettings = new JsonFx.Json.JsonReaderSettings(); jsonSettings.TypeHintName = "__type"; JsonFx.Json.JsonReader jsonReader = new JsonFx.Json.JsonReader(json, jsonSettings); UserDataModel loginResponse = jsonReader.Deserialize<UserDataModel>(); ITTDataCache.Instance.UpdateSessionManager(loginResponse); ITTGoogleAnalytics.Instance.googleAnalytics.LogEvent(new EventHitBuilder() .SetEventCategory("Registration - Sign In Screen") .SetEventAction("Sign In Success - Sign In Screen") .SetEventLabel("User has successfully logged into their account.")); if (null != OnSignInSuccessHandler) { OnSignInSuccessHandler(); OnSignInSuccessHandler = null; } StartCoroutine(OnHide()); } catch(Exception ex) { Debug.LogError("OnSignInSuccess error. " + ex.Message); } }
public static T DeserializeJsonFx <T>(string json) { var reader = new JsonFx.Json.JsonReader(JsonFxReaderSettings); return(reader.Read <T>(json)); }
public void ReadSettings() { var filePath = new System.IO.FileInfo(Manager.ServerDirectory.FullName + "/BasicAutoServer.json"); if (!filePath.Exists) { Log.Info("No BasicAutoServer.json, using default settings"); return; } try { var txt = System.IO.File.ReadAllText(filePath.FullName); var reader = new JsonFx.Json.JsonReader(); var dictionary = (Dictionary <string, object>)reader.Read(txt); TryGetValue(dictionary, "MasterServerGameModeOverride", ref MasterServerGameModeOverride); TryGetValue(dictionary, "ServerName", ref ServerName); TryGetValue(dictionary, "MaxPlayers", ref MaxPlayers); TryGetValue(dictionary, "Port", ref Port); TryGetValue(dictionary, "UseNat", ref UseNat); TryGetValue(dictionary, "PrivateServerPassword", ref PrivateServerPassword); TryGetValue(dictionary, "ReportToMasterServer", ref ReportToMasterServer); TryGetValue(dictionary, "ReportToMasterServerInitialDelay", ref ReportToMasterServerInitialDelay); TryGetValue(dictionary, "MasterServerReRegisterFrequency", ref MasterServerReRegisterFrequency); TryGetValue(dictionary, "ReportToMasterServerAsDedicatedServer", ref ReportToMasterServerAsDedicatedServer); TryGetValue(dictionary, "GameMode", ref GameMode); TryGetValue(dictionary, "LoadWorkshopLevels", ref LoadWorkshopLevels); TryGetValue(dictionary, "AdvanceWhenStartingPlayersFinish", ref AdvanceWhenStartingPlayersFinish); TryGetValue(dictionary, "AdvanceWhenAllPlayersFinish", ref AdvanceWhenAllPlayersFinish); TryGetValue(dictionary, "IdleTimeout", ref IdleTimeout); TryGetValue(dictionary, "WelcomeMessage", ref WelcomeMessage); TryGetValue(dictionary, "LevelTimeout", ref LevelTimeout); TryGetValue(dictionary, "ReverseTagLevelTimeout", ref ReverseTagLevelTimeout); TryGetValue(dictionary, "ReverseTagWinTime", ref ReverseTagWinTime); var tipsBase = new object[0]; TryGetValue(dictionary, "TipMessages", ref tipsBase); foreach (object tipBase in tipsBase) { TipMessages.Add((string)tipBase); } var levelsBase = new object[0]; TryGetValue(dictionary, "Levels", ref levelsBase); var index = 0; foreach (object levelBase in levelsBase) { var levelDict = (Dictionary <string, object>)levelBase; string name = null; string path = null; string workshop = null; string mode = null; TryGetValue(levelDict, "Name", ref name); TryGetValue(levelDict, "RelativeLevelPath", ref path); TryGetValue(levelDict, "WorkshopFileId", ref workshop); TryGetValue(levelDict, "GameMode", ref mode); if (name == null || path == null || workshop == null || mode == null) { Log.Debug($"Level {index} ({name}) failed because it was missing a property"); } else { PresetLevels.Add(new DistanceLevel() { Name = name, RelativeLevelPath = path, WorkshopFileId = workshop, GameMode = mode, }); } } if (levelsBase.Length > 0) { Playlist.Clear(); Playlist.AddRange(PresetLevels); } Log.Info("Loaded settings from BasicAutoServer.json"); } catch (Exception e) { Log.Error($"Couldn't read BasicAutoServer.json. Is your json malformed?\n{e}"); } }
System.Collections.IEnumerator UpdatePlaylist() { HashSet <string> foundLevels = new HashSet <string>(); List <DistanceSearchRetriever> levelRetrievers = new List <DistanceSearchRetriever>(); var filePath = new System.IO.FileInfo(Manager.ServerDirectory.FullName + "/BasicAutoServer.json"); if (filePath.Exists) { try { var txt = System.IO.File.ReadAllText(filePath.FullName); var reader = new JsonFx.Json.JsonReader(); var dictionary = (Dictionary <string, object>)reader.Read(txt); if (dictionary.ContainsKey("Workshop")) { Log.Info("Using workshop level info stored in BasicAutoServer.json"); var levelSettings = (object[])dictionary["Workshop"]; foreach (var settingsObject in levelSettings) { var settings = (Dictionary <string, object>)settingsObject; var search = (string)settings["Search"]; var sort = (WorkshopSearchParameters.SortType)Enum.Parse(typeof(WorkshopSearchParameters.SortType), (string)settings["Sort"]); var days = (int)settings["Days"]; var tagsBase = (object[])settings["Tags"]; var tagsList = new List <string>() { }; foreach (object tagBase in tagsBase) { tagsList.Add((string)tagBase); } var count = (int)settings["Count"]; var searchParams = WorkshopSearchParameters.GameFiles( searchText: search, appId: Workshop.DistanceAppId, sort: sort, days: days, requiredTags: tagsList.ToArray(), numPerPage: 30 ); var retriever = new DistanceSearchRetriever(new DistanceSearchParameters() { Search = searchParams, DistanceLevelFilter = (levels) => { levels.RemoveAll(level => { return(foundLevels.Contains(level.DistanceLevelResult.RelativeLevelPath)); }); foreach (var level in levels) { foundLevels.Add(level.DistanceLevelResult.RelativeLevelPath); } var res = FilterWorkshopLevels(levels); return(res); }, MaxSearch = count, GameMode = GameMode }, false); levelRetrievers.Add(retriever); } } } catch (Exception e) { Log.Error($"Error retrieving workshop level settings:\n{e}"); } } if (levelRetrievers == null || levelRetrievers.Count == 0) { Log.Error("No workshop levels defined. Using default: official levels"); Playlist = OfficialPlaylist; yield break; } var levelListIndex = 0; foreach (var retriever in levelRetrievers) { retriever.StartCoroutine(); yield return(retriever.TaskCoroutine); if (retriever.HasError) { Log.Error($"Error retrieving levels: {retriever.Error}"); } foreach (var levelInfo in retriever.Results) { levelInfo.DistanceLevelResult.AddExternalData(new ListIndexExternalData(levelListIndex)); } levelListIndex++; } Log.Info($"Level Retrievers: {levelRetrievers.Count}"); var levelResults = levelRetrievers.ConvertAll(retriever => retriever.Results.ConvertAll(result => result.DistanceLevelResult)); var results = Combine(levelResults.ToArray()); var listStr = $"Levels ({results.Count}):"; foreach (var level in results) { listStr += $"\n{level.GetExternalData<ListIndexExternalData>().listIndex} {level.Name}"; } Log.Info(listStr); if (results.Count == 0) { Log.Error("Workshop search returned nothing, using default: official levels"); Playlist = OfficialPlaylist; hasLoadedWorkshopLevels = false; yield break; } Playlist = results; currentLevelIndex = -1; if (!hasLoadedWorkshopLevels) { hasLoadedWorkshopLevels = true; Server.SayChat(DistanceChat.Server("BasicAutoServer:LoadedLevels", "Workshop playlist generated. Skipping to workshop playlist...")); FinishAllPlayersAndAdvanceLevel(); } }
public static T FromJson <T>(this string jsonObj) { var reader = new JsonFx.Json.JsonReader(); return(reader.Read <T>(jsonObj)); }
public static dynamic FromJson(this string jsonObj) { var reader = new JsonFx.Json.JsonReader(); return(reader.Read(jsonObj)); }
public static void BuildMenu( Assembly assem, Platform.ShellRightClickContextMenuClass menuClass, InfoStorageAttribute storage, List<string> list, MenuClick onClick ) { try { // filter file extensions if required var filter = new List<string>( storage.FileExtensionFilter ); var filesList = storage.ExpandFileNames ? BuildFileList( filter, list ) : list; if ( filesList.Count > 0 ) { string menuFormatJson = storage.MenuFormat; var jsonReader = new JsonFx.Json.JsonReader(); dynamic menuFormatObject = jsonReader.Read<dynamic>( menuFormatJson ); dynamic menuFormatObjectChildren = menuFormatObject.children; AddChildren( assem, menuClass, storage, IntPtr.Zero, menuFormatObjectChildren, filesList, true, onClick ); } } catch ( Exception e ) { MessageBox.Show( e.Message + "\r\n\r\n" + e.StackTrace, "Error whilst creating menu" ); } }
private static void LoadSettings() { lock (LockerObject) { using (var fileStream = System.IO.File.Open(_filePath, FileMode.OpenOrCreate, FileAccess.Read)) { using (TextReader tr = new StreamReader(fileStream)) { var jsonReader = new JsonFx.Json.JsonReader(); var deserialized = jsonReader.Read(tr, typeof(List<Setting>)); var settings = deserialized as List<Setting>; _settings = settings ?? new List<Setting>(); } } } }
private static IDictionary<string, string> GetTemplatesFromAccount(string apikey, string templateName = null, bool ignoreDates = false) { var templatesInAccount= new Dictionary<string,string>(); var reader = new JsonReader(); var httpHelper = new HttpHelper(); var templatesResponse = httpHelper.Post(Mandrillurl + "/templates/list.json", new { key = apikey }).Result; if (templatesResponse.Code == HttpStatusCode.OK) { // dynamic templates = reader.Read(templatesResponse.Body); foreach (var t in templates) { if (!string.IsNullOrWhiteSpace(templateName) && !templateName.Equals(t.name, StringComparison.OrdinalIgnoreCase)) { //this seems to be the only way to get single template by name (not slug!) continue; } Console.WriteLine("Found template: " + t.name + " - " + t.slug); //if templates are exported to source control and imported into other accounts //it is usefull to strip out dates; otherwise they will be seen as an update to the file //and you end it endless loops of updating accounts. if (ignoreDates) { if (HasProperty(t, "published_at")) t.published_at = "2015-01-01 10:10:10"; if (HasProperty(t, "created_at")) t.created_at = "2015-01-01 10:10:10"; if (HasProperty(t, "updated_at")) t.updated_at = "2015-01-01 10:10:10"; if (HasProperty(t, "draft_updated_at")) t.draft_updated_at = "2015-01-01 10:10:10"; } templatesInAccount.Add(t.name, ToJsonPrettyPrint(t)); } } return templatesInAccount; }
public ActionResult UpdateUnitSorting(int id) { var didacheDb = new DidacheDb(); string data = HttpUtility.UrlDecode(Request.Form.ToString()); //dynamic newValue = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Dynamic.>(data); var reader = new JsonFx.Json.JsonReader(); dynamic output = reader.Read(data); foreach (var unitInfo in output) { // get and update the unit Unit unit = didacheDb.Units.Find(unitInfo.unitid); unit.SortOrder = unitInfo.sortorder; foreach (var taskInfo in unitInfo.tasks) { // get and update the task Task task = didacheDb.Tasks.Find(taskInfo.taskid); task.SortOrder = taskInfo.sortorder; } } string errorMessage = ""; bool success = false; try { didacheDb.SaveChanges(); success = true; } catch { var entries = didacheDb.GetValidationErrors(); foreach (var entry in entries) { errorMessage += "[" + entry.Entry.Entity.ToString() + "]\n"; foreach (var error in entry.ValidationErrors) { errorMessage += error.PropertyName + " = " + error.ErrorMessage + "; "; } } } return Json(new { success = success, errorMessage = errorMessage}); }
public ActionResult UpdateUserGroupSorting(int id) { var didacheDb = new DidacheDb(); string data = HttpUtility.UrlDecode(Request.Form.ToString()); //dynamic newValue = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Dynamic.>(data); var reader = new JsonFx.Json.JsonReader(); dynamic output = reader.Read(data); // get groups List<CourseUserGroup> groups = db.CourseUserGroups.Where(cfg => cfg.CourseID == id).ToList(); List<int> groupIDs = groups.Select(cfg => cfg.GroupID).ToList(); // get files List<CourseUser> courseUsers = db.CourseUsers.Where(cu => groupIDs.Contains(cu.GroupID)).ToList(); foreach (var groupInfo in output) { CourseUserGroup userGroup = groups.SingleOrDefault(cug => cug.GroupID == groupInfo.groupid); foreach (var userInfo in groupInfo.users) { CourseUser courseUser = courseUsers.SingleOrDefault(cu => cu.UserID == userInfo.userid); // has the group changed? if (courseUser.GroupID != userGroup.GroupID) { // create a new one with the new group CourseUser newCourseFile = new CourseUser() { UserID = courseUser.UserID, GroupID = userGroup.GroupID, RoleID = (int)CourseUserRole.Student }; db.CourseUsers.Remove(courseUser); db.CourseUsers.Add(newCourseFile); } else { // do nothing since we don't care about the order } } } db.SaveChanges(); /* foreach (var groupInfo in output) { // get and update the group CourseFileGroup fileGroup = didacheDb.CourseFileGroups.Find(groupInfo.groupid); fileGroup.SortOrder = groupInfo.sortorder; //fileGroup.Name = groupInfo.name; // TEST 2: get all existing, update, remove missing // get exsiting files List<CourseFileAssociation> courseFiles = didacheDb.CourseFileAssociations.Where(cfa => cfa.GroupID == fileGroup.GroupID).ToList(); foreach (var fileInfo in groupInfo.files) { // find the file CourseFileAssociation cfa = courseFiles.Find(c => c.FileID == fileInfo.fileid); if (cfa != null) { // update cfa.SortOrder = fileInfo.sortorder; // add to change list //changedFiles.Add(cfa); courseFiles.Remove(cfa); } else { cfa = new CourseFileAssociation(); cfa.GroupID = fileGroup.GroupID; cfa.FileID = fileInfo.fileid; cfa.SortOrder = fileInfo.sortorder; didacheDb.CourseFileAssociations.Add(cfa); } } // remove all remaining files foreach (CourseFileAssociation notUpdated in courseFiles) { didacheDb.CourseFileAssociations.Remove(notUpdated); } } */ didacheDb.SaveChanges(); // need to deserialize this and update all the groups and files return Json(new { success = true }); }