public void SetContent(string jsonContent) { Type me = GetType(); JsonTextReader reader = new JsonTextReader(new System.IO.StringReader(jsonContent)); while (!reader.EOF) { object obj = reader.DeserializeNext(); JObject jobj = obj as JObject; JArray jlevel = obj as JArray; JArray jlevels = null; if (jobj != null) { if (!jobj.Contains("Fields")) { continue; } jlevel = (jobj["Fields"]) as JArray; if (jobj.Contains("Levels")) { jlevels = (jobj["Levels"]) as JArray; } } System.Globalization.CultureInfo Culture = GxContext.Current.localUtil.CultureInfo; SetContent(Culture, GetName(), me, this, jlevel, jlevels); break; } }
public void IListContains() { JProperty p = new JProperty("Test", 1); IList l = new JObject(p); Assert.IsTrue(l.Contains(p)); Assert.IsFalse(l.Contains(new JProperty("Test", 1))); }
public void GenericListJTokenContains() { JProperty p = new JProperty("Test", 1); IList <JToken> l = new JObject(p); Assert.IsTrue(l.Contains(p)); Assert.IsFalse(l.Contains(new JProperty("Test", 1))); }
private void listViewMain_SelectedIndexChanged(object sender, EventArgs e) { if (selectedListViewIndex >= 0 && selectedListViewIndex < listViewMain.Items.Count) { listViewMain.Items[selectedListViewIndex].BackColor = SystemColors.Window; listViewMain.Items[selectedListViewIndex].ForeColor = SystemColors.WindowText; } selectedListViewIndex = -1; listBoxVVClear(); ListView.SelectedListViewItemCollection files = listViewMain.SelectedItems; if (files.Count == 0) { return; } if (vvConfig != null && vvConfig.Contains("VVPath")) { string vvDir = $"{(string)vvConfig.GetValue("VVPath")}\\{treeViewMain.SelectedNode.FullPath}\\{files[0].Text}"; if (Directory.Exists(vvDir)) { foreach (string filename in Directory.GetFiles(vvDir)) { string baseFilename = filename.Substring(filename.LastIndexOf("\\") + 1); if (baseFilename.Length == 32 && !baseFilename.Contains("_")) { continue; } VVItem item = new VVItem(PathBase(filename)); listBoxVV.Items.Add(item); } } } }
private bool TryGetValue(string key, JObject obj, out string value) { value = null; if (obj.Contains(key)) { value = obj[key].ToString(); return(true); } return(false); }
public void IListRemove() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); // won't do anything l.Remove(p3); Assert.AreEqual(2, l.Count); l.Remove(p1); Assert.AreEqual(1, l.Count); Assert.IsFalse(l.Contains(p1)); Assert.IsTrue(l.Contains(p2)); l.Remove(p2); Assert.AreEqual(0, l.Count); Assert.IsFalse(l.Contains(p2)); Assert.AreEqual(null, p2.Parent); }
public static List <Geospatial> GetLocationGeography(String address) { String urlString = MAPS_URI + "geocode/json?address=" + GXUtil.UrlEncode(address) + "&sensor=false"; String ApiKey = ""; if (Config.GetValueOf("GoogleApiKey", out ApiKey)) { urlString += "&key=" + ApiKey; } String response = GXGeolocation.GetContentFromURL(urlString); List <Geospatial> result = new List <Geospatial>(); try { if (!string.IsNullOrEmpty(response)) { StringReader sr = new StringReader(response); JsonTextReader tr = new JsonTextReader(sr); JObject json = (JObject)(tr.DeserializeNext()); if (json.Contains("results")) { JArray results = (JArray)json["results"]; for (int i = 0; i < results.Length; i++) { JObject jo = (JObject)results[i]; if (jo.Contains("geometry")) { JObject geometry = (JObject)jo["geometry"]; if (geometry.Contains("location")) { JObject location = (JObject)geometry["location"]; if (location != null && (location.Contains("lat")) && (location.Contains("lng"))) { Geospatial point = new Geospatial(Convert.ToDecimal(location["lat"]), Convert.ToDecimal(location["lng"])); result.Add(point); } } } } } } } catch (JsonException ex) { GXLogging.Error(log, "getLocation error json:" + response, ex); } return(result); }
public static bool GetConfigValue(string key, JObject storeConfig, out string value) { value = string.Empty; if (storeConfig.Contains(key)) { value = (string)storeConfig[key]; } if (string.IsNullOrEmpty(value)) { GXLogging.Error(log, string.Format("{0} must be specified", key)); } return(!string.IsNullOrEmpty(value)); }
internal static RemoteNotification FromGxUserType(GxUserType sdt) { RemoteNotification notification = new RemoteNotification(); JObject jobj = sdt.GetJSONObject() as JObject; if (jobj != null) { object deviceTypeObj = jobj["DeviceType"]; if (deviceTypeObj is Int16) { notification.DeviceType = (short)deviceTypeObj; } else { notification.DeviceType = -1; } notification.DeviceToken = TryGetObjectPropertyValue(jobj, "DeviceToken"); notification.Message = TryGetObjectPropertyValue(jobj, "Message"); notification.Title = TryGetObjectPropertyValue(jobj, "Title"); notification.Icon = TryGetObjectPropertyValue(jobj, "Icon"); notification.Sound = TryGetObjectPropertyValue(jobj, "Sound"); notification.Badge = TryGetObjectPropertyValue(jobj, "Badge"); notification.Delivery.Priority = TryGetObjectPropertyValue(jobj["Delivery"] as JObject, "Priority", "normal"); notification.ExecutionTime = 0; notification.Parameters = new NotificationParameters(); JObject eventObj = jobj["Event"] as JObject; if (eventObj != null) { notification.Action = eventObj["Name"] as string; object executionTime = eventObj["Execution"]; if (executionTime is Int16) { notification.ExecutionTime = (short)executionTime; } if (eventObj.Contains("Parameters")) { JArray arr = eventObj["Parameters"] as JArray; for (int i = 0; i < arr.Length; i++) { notification.Parameters.Add(arr.GetObject(i)["Name"] as string, arr.GetObject(i)["Value"] as string); } } } } return(notification); }
public static List <string> GetAddress(String location) { String urlString = MAPS_URI + "geocode/json?latlng=" + GXUtil.UrlEncode(location) + "&sensor=false"; String ApiKey = ""; if (Config.GetValueOf("GoogleApiKey", out ApiKey)) { urlString += "&key=" + ApiKey; } String response = GXGeolocation.GetContentFromURL(urlString); List <string> result = new List <string>(); try { if (!string.IsNullOrEmpty(response)) { StringReader sr = new StringReader(response); JsonTextReader tr = new JsonTextReader(sr); JObject json = (JObject)(tr.DeserializeNext()); if (json.Contains("results")) { JArray results = (JArray)json["results"]; for (int i = 0; i < results.Length; i++) { JObject jo = (JObject)results[i]; if (jo.Contains("formatted_address")) { result.Add((string)jo["formatted_address"]); } } } } } catch (JsonException ex) { GXLogging.Error(log, "getAddress error json:" + response, ex); } return(result); }
private StorePurchase ParsePurchase(JObject purchase) { StorePurchase p; ProductType pType = ProductType.Product; if (purchase.Contains("web_order_line_item_id")) { pType = ProductType.Subscription; } p = new StorePurchase() { ProductIdentifier = GetValueDefault("product_id", purchase, string.Empty), PurchaseId = GetValueDefault("transaction_id", purchase, string.Empty), PurchaseDate = GetDateValueFromMS("purchase_date_ms", purchase), ProductType = (int)pType, PurchaseStatus = PurchaseStatus.Valid, Custom = new StorePurchaseCustom() { Quantity = Int32.Parse(GetValueDefault("quantity", purchase, string.Empty)), IsTrialPeriod = GetValueDefault("is_trial_period", purchase, "false") == "true" } }; if (pType == ProductType.Subscription) { p.Subscription = new StorePurchaseSubscription() { Expiration = GetDateValueFromMS("expires_date_ms", purchase), FirstPurchased = GetDateValueFromMS("original_purchase_date_ms", purchase) }; if (p.Subscription.Expiration < DateTime.Now) { p.PurchaseStatus = PurchaseStatus.Expired; } } return(p); }
public JObject ManageJournalDownload(JObject lasthistory, string storepath, string cmdrname, TimeSpan checktime, int daysinpast) { //System.Diagnostics.Debug.WriteLine("---------------------- Journal console check @ " + DateTime.UtcNow.ToStringZulu()); JObject newhistory = new JObject(); const string datekeyformat = "yyyy-MM-dd"; string todo = null; // Go back and check state of the last days search.. find one to process. update newhistory with lasthistory for (int day = -daysinpast; day <= 0; day++) { DateTime t = DateTime.UtcNow.AddDays(day).StartOfDay(); string tname = t.ToString(datekeyformat); JToken value = null; lasthistory?.TryGetValue(tname, out value); // value = null if not got if (value != null) { newhistory.Add(tname, value); // applicable, copy across } string state = value.I("S").Str("NotTried"); // state of play //System.Diagnostics.Debug.WriteLine(tname + " Journal check: " + value?.ToString()); if (todo == null) { // either nottried (no record) or in a Check state and not too soon if (state == "NotTried" || ((state.StartsWith("Check")) && DateTime.UtcNow - value["T"].DateTimeUTC() >= checktime)) { todo = tname; } } } if (todo != null) // found one to try { System.Diagnostics.Trace.WriteLine("Journal Check day " + todo + " @ " + DateTime.UtcNow.ToStringZulu()); string journaljson = null; #if CONSOLETESTHARNESS string subfile = @"c:\code\journal." + todo + ".log"; // for the test, we pick up this file for this day System.Net.HttpStatusCode status = System.Net.HttpStatusCode.NoContent; if (File.Exists(subfile)) { journaljson = File.ReadAllText(subfile); status = System.Net.HttpStatusCode.OK; } #else journaljson = Journal(todo, out System.Net.HttpStatusCode status); // real code polls CAPI #endif string dayzeroname = DateTime.UtcNow.StartOfDay().ToString(datekeyformat); // name of current day in this system if (status == System.Net.HttpStatusCode.NoContent) { // server says no content for the day. If its a previous day, its over. Else we are in check1 continuously because the game might start newhistory[todo] = new JObject() { ["S"] = todo == dayzeroname ? "Check1" : "NoContent", ["T"] = DateTime.UtcNow.ToStringZulu() }; } else if (journaljson != null) { //File.WriteAllText(@"c:\code\readjournal.log",journaljson); string filename = Path.Combine(storepath, (GameIsBeta ? "JournalBeta." : "Journal.") + cmdrname.SafeFileString() + "." + todo + ".log"); string prevcontent = null; if (File.Exists(filename)) // if file there, try and read the lines, and if so, store { prevcontent = BaseUtils.FileHelpers.TryReadAllTextFromFile(filename); } string samesecondsegment = null; string samesecondtimestamp = ""; string newoutput = ""; StringReader sr = new StringReader(journaljson); string curline; while ((curline = sr.ReadLine()) != null) { if (curline.HasChars()) { JObject ev = JObject.Parse(curline); // lets sanity check it.. if (ev != null && ev.Contains("event") && ev.Contains("timestamp")) // reject lines which are not valid json records { string evtype = ev["event"].Str(); if (evtype == "Commander") // we adjust commander/loadgame commander name to our commander name - so { // when we scan it it goes into the right history, irrespective of the naming of the commander // vs the game ev["Name"] = cmdrname; // adjust commander name, rewrite again curline = ev.ToString(" "); } else if (evtype == "LoadGame") { ev["Commander"] = cmdrname; // adjust commander name, rewrite again curline = ev.ToString(" "); } if (prevcontent == null) // no previous file, just add { newoutput += curline + Environment.NewLine; } else { // we accumulate all entries with the same second (they cannot be distinguished if events are identical, so can't use a hashset same line check) // so that we have a group with the same second, then we see if its in the previous content string ts = ev["timestamp"].Str(); if (samesecondtimestamp == ts) // if same timestamp as previous, accumulate { //System.Diagnostics.Debug.WriteLine(" {0} Same segment {1}", ts, curline.Left(80)); samesecondsegment += curline + Environment.NewLine; } else { if (samesecondsegment == null || prevcontent.Contains(samesecondsegment)) // duplicate segment, ignore { // System.Diagnostics.Debug.WriteLine(samesecondsegment != null ? ".. Duplicate data " + ts + " " + samesecondsegment.Left(80): ""); } else { System.Diagnostics.Debug.WriteLine(" " + ts + " New data"); System.Diagnostics.Debug.WriteLine(samesecondsegment.LineNumbering(1, "#")); newoutput += samesecondsegment; } samesecondsegment = curline + Environment.NewLine; // start a new timestamp samesecondtimestamp = ts; } } } } } if (samesecondsegment.HasChars() && (prevcontent == null || !prevcontent.Contains(samesecondsegment))) // clean up last segment { System.Diagnostics.Debug.WriteLine(" " + samesecondtimestamp + " New data"); System.Diagnostics.Debug.WriteLine(samesecondsegment.LineNumbering(1, "#")); newoutput += samesecondsegment; } string stateout = "Check1"; // default is to go to check 1 state if (newoutput.HasChars()) // we have new data, so we go into check1 and it will be downloaded again later { System.Diagnostics.Trace.WriteLine(string.Format("..{0} New content for {1}", todo, filename)); System.IO.File.WriteAllText(filename, (prevcontent ?? "") + newoutput); } else { System.Diagnostics.Trace.WriteLine(string.Format("..{0} No change for {1}", todo, filename)); string instate = lasthistory[todo].I("S").Str("NotTried"); if (instate == "Check1" && todo != dayzeroname) // 1->2 only if not day0 { stateout = "Check2"; } else if (instate == "Check2") // 2->Done { stateout = "Done"; // otherwise 1 } } newhistory[todo] = new JObject() { ["S"] = stateout, ["T"] = DateTime.UtcNow.ToStringZulu() }; // no new data, mark done. System.Diagnostics.Trace.WriteLine(".. to state " + newhistory[todo].ToString()); } else { System.Diagnostics.Trace.WriteLine(" No response to " + todo + " (" + status.ToString() + ") will try again"); } } //System.Diagnostics.Debug.WriteLine("--------------- finished " + newhistory.ToString()); return(newhistory); }
private static JObject FilterJournalEvent(JObject message, JObject allowedFields, string path = "") { JObject ret = new JObject(); foreach (var kvp in message) { string mpath = $"{path}.{kvp.Key}"; if (allowedFields.Contains(kvp.Key)) { JToken allowedField = allowedFields[kvp.Key]; if (kvp.Value.HasValue) { if (allowedField.BoolNull() == true) // if straight value and allowed) { ret[kvp.Key] = kvp.Value; } else { System.Diagnostics.Debug.WriteLine("Reject Field " + mpath); } } // if Jarray, allowed is Jarray, and one JOBJECT underneath else if (kvp.Value.IsArray && allowedField.IsArray && allowedField.Count == 1 && allowedField[0] is JObject) { JObject allowed = (JObject)allowedField[0]; JArray vals = new JArray(); foreach (JObject val in kvp.Value) // go thru array { vals.Add(FilterJournalEvent(val, allowed, $"{mpath}[]")); } ret[kvp.Key] = vals; } else if (kvp.Value.IsArray && allowedField.StrNull() == "[]") // if Jarray, and allowed fields is a special [] string marker { JArray vals = new JArray(); foreach (JToken val in kvp.Value) // just add all values { if (val.HasValue) { vals.Add(val); } else { Trace.WriteLine($"Array value {mpath}[] is not a value: {val?.ToString()}"); } } ret[kvp.Key] = vals; } else if (kvp.Value.IsObject && allowedField.IsObject) // if object, and allowed is object { JObject allowed = (JObject)allowedField; JObject val = (JObject)kvp.Value; ret[kvp.Key] = FilterJournalEvent(val, allowed, mpath); // recurse add } else { Trace.WriteLine($"Object value {mpath} is not of expected type: {kvp.Value?.ToString()}"); } } else { Trace.WriteLine($"Object value {mpath} not in allowed list: {kvp.Value?.ToString()}"); } } return(ret); }
public void IListRemove() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); // won't do anything l.Remove(p3); Assert.Equal(2, l.Count); l.Remove(p1); Assert.Equal(1, l.Count); Assert.False(l.Contains(p1)); Assert.True(l.Contains(p2)); l.Remove(p2); Assert.Equal(0, l.Count); Assert.False(l.Contains(p2)); Assert.Equal(null, p2.Parent); }
public void IListContains() { JProperty p = new JProperty("Test", 1); IList l = new JObject(p); Assert.True(l.Contains(p)); Assert.False(l.Contains(new JProperty("Test", 1))); }
public void GenericListJTokenContains() { JProperty p = new JProperty("Test", 1); IList<JToken> l = new JObject(p); Assert.True(l.Contains(p)); Assert.False(l.Contains(new JProperty("Test", 1))); }
public void GenericListJTokenRemove() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); // won't do anything Assert.IsFalse(l.Remove(p3)); Assert.AreEqual(2, l.Count); Assert.IsTrue(l.Remove(p1)); Assert.AreEqual(1, l.Count); Assert.IsFalse(l.Contains(p1)); Assert.IsTrue(l.Contains(p2)); Assert.IsTrue(l.Remove(p2)); Assert.AreEqual(0, l.Count); Assert.IsFalse(l.Contains(p2)); Assert.AreEqual(null, p2.Parent); }
private StorePurchase ValidatePurchase(string purchaseToken, PurchaseResult purchaseResult, PurchaseEnvironment env) { StorePurchase p = null; string responseString; string url = (env == PurchaseEnvironment.Production) ? APPLE_STORE_VALIDATION_URL_PROD : APPLE_STORE_VALIDATION_URL_SANDBOX; JObject inputObj = new JObject(); inputObj.Put("receipt-data", purchaseResult.TransactionData.Trim()); inputObj.Put("password", _iTunesStorePassword); string key = Util.GetHashString(inputObj.ToString()); if (!dataCache.TryGetValue(key, out responseString)) { HttpStatusCode code = DoPost(inputObj.ToString(), url, out responseString); switch (code) { case HttpStatusCode.OK: break; default: throw new StoreInvalidPurchaseException(""); } dataCache.TryAdd(key, responseString); } JObject jResponse = Util.FromJSonString(responseString); if (jResponse.Contains("status")) { int statusCode = (int)jResponse["status"]; switch (statusCode) { case 21000: throw new StoreResponsePurchaseException("The App Store could not read the JSON object you provided."); case 21002: throw new StoreResponsePurchaseException("The data in the receipt-data property was malformed or missing."); case 21003: throw new StoreResponsePurchaseException("The receipt could not be authenticated."); case 21004: throw new StoreResponsePurchaseException("The shared secret you provided does not match the shared secret on file for your account."); case 21005: throw new StoreResponsePurchaseException("The receipt server is not currently available."); case 21006: throw new StoreResponsePurchaseException("Could not handle 21006 status response"); case 21007: string value; dataCache.TryRemove(key, out value); throw new StoreResponseEnvironmentException("This receipt is from the test environment, but it was sent to the production environment for verification. Send it to the test environment instead."); case 21008: break; case 0: break; default: throw new StoreResponsePurchaseException($"Could not handle '{statusCode}' status response"); } bool found = false; if (jResponse.Contains("receipt")) { JObject receipt = (JObject)jResponse["receipt"]; if (receipt.Contains("in_app")) { JArray purchases = (JArray)receipt["in_app"]; foreach (JObject purchase in purchases) { if (purchase.Contains("transaction_id") && (string)purchase["transaction_id"] == purchaseToken) { found = true; p = ParsePurchase(purchase); String ATT_ORIG_TRN_ID = "original_transaction_id"; if (p.PurchaseStatus == PurchaseStatus.Expired && p.ProductType == (int)ProductType.Subscription && purchase.Contains(ATT_ORIG_TRN_ID) && jResponse.Contains("latest_receipt_info")) { String originalTransactionId = (string)purchase[ATT_ORIG_TRN_ID]; JArray latestInfo = (JArray)jResponse["latest_receipt_info"]; List <StorePurchase> list = new List <StorePurchase>(); foreach (JObject latestPurchase in latestInfo) { if (latestPurchase.Contains(ATT_ORIG_TRN_ID) && (string)latestPurchase[ATT_ORIG_TRN_ID] == originalTransactionId) { p = ParsePurchase(latestPurchase); list.Add(p); if (p.PurchaseStatus == PurchaseStatus.Valid) { break; } } } if (p.PurchaseStatus != PurchaseStatus.Valid && list.Count > 0) { list = list.OrderByDescending(sp => sp.Subscription.Expiration).ToList(); p = list.First(); } } else { break; } } } } } if (!found) { throw new StorePurchaseNotFoundException("Purchase Id not found inside Apple Receipt"); } } else { throw new StoreResponsePurchaseException("Aplle Store validation servers seems to be unavailable."); } if (p.ProductType == (int)ProductType.Subscription) { p.Custom.OriginalPurchase = purchaseResult; } return(p); }
public bool Contains(string key) { return(_config.Contains(key)); }