public override void Serialize(System.IO.BinaryWriter aWriter) { var tmp = new JSONData(""); tmp.AsInt = AsInt; if (tmp.m_Data == this.m_Data) { aWriter.Write((byte)JSONBinaryTag.IntValue); aWriter.Write(AsInt); return; } tmp.AsFloat = AsFloat; if (tmp.m_Data == this.m_Data) { aWriter.Write((byte)JSONBinaryTag.FloatValue); aWriter.Write(AsFloat); return; } tmp.AsDouble = AsDouble; if (tmp.m_Data == this.m_Data) { aWriter.Write((byte)JSONBinaryTag.DoubleValue); aWriter.Write(AsDouble); return; } tmp.AsBool = AsBool; if (tmp.m_Data == this.m_Data) { aWriter.Write((byte)JSONBinaryTag.BoolValue); aWriter.Write(AsBool); return; } aWriter.Write((byte)JSONBinaryTag.Value); aWriter.Write(m_Data); }
public JsonResult OnGetAjaxEmailListAsync() { UpdateEmails(); List <JSONData> myData = new List <JSONData>(); if (MailToMe.Count() > 0) { DateTime Last = MailToMe.ElementAt(0).TimeSent.Date; JSONData first = new JSONData(); first.Date = Last.Date.ToShortDateString(); foreach (Email A in MailToMe) { if (A.TimeSent.Date == Last) { first.myEmails.Add(A); AddUserToJSONList(first, A); } else { myData.Add(first); String NEXTTOP = first.TopID + first.TopID; String NEXTBOT = first.BottomID + first.BottomID; first = new JSONData(); first.TopID = NEXTTOP; first.BottomID = NEXTBOT; Last = A.TimeSent.Date; first.Date = Last.Date.ToShortDateString(); first.myEmails.Add(A); AddUserToJSONList(first, A); } } myData.Add(first); //Adds the last JSONData object we were dealing with; } return(new JsonResult(myData)); }
/// <summary> /// Ecris dans un seul fichier JSON grace a l'objet JSONData /// Tout les autres objets y sont aussi ecris /// </summary> /// <param name="dataJSON"></param> public void WriteInJSONFile(JSONData dataJSON) { //permet davoir le string de lancien JSON file if (File.Exists(fullPath)) { using (StreamReader sr = new StreamReader(fileName)) { infoJSON = sr.ReadToEnd(); } } //true permet de ne pas overwrite le fichier using (StreamWriter sw = new StreamWriter(fullPath)) { if (infoJSON == "") { sw.Write("[\n" + dataJSON.AllInfo + "\n]"); } else { infoJSON = infoJSON.Remove(infoJSON.Length - 1); sw.Write(infoJSON + "\n" + dataJSON.AllInfo + "\n]"); } } }
static void Main(string[] args) { // Create variables to read data into Int32 ID_result; DateTime LoggedTime_result; string JSONData; string JSONData2; Int32 Device_ID; // Try to access the Microsoft SQL database try { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); builder.DataSource = "DATASOURCE_NAME.database.windows.net"; builder.UserID = "DB_USERNAME"; builder.Password = "******"; builder.InitialCatalog = "DB_NAME"; using (SqlConnection connection = new SqlConnection(builder.ConnectionString)) { Console.WriteLine("\nQuery data example:"); Console.WriteLine("=========================================\n"); connection.Open(); StringBuilder sb = new StringBuilder(); sb.Append("SELECT [Id], [LoggedTime], [Data], [LoggingDeviceId] "); // To select all entries sb.Append("FROM [dbo].[LoggedData];"); String sql = sb.ToString(); using (SqlCommand command = new SqlCommand(sql, connection)) { using (SqlDataReader reader = command.ExecuteReader()) { JSONData2 = ""; while (reader.Read()) { ID_result = reader.GetInt32(0); LoggedTime_result = reader.GetDateTime(1); JSONData = reader.GetString(2); Device_ID = reader.GetInt32(3); // Remove "{"records":[" and "]}" JSONData2 = JSONData2 + JSONData.Replace(@"{""records"":[", "").Replace(@"]}", "");//.Replace(@"},", "},\n"); // // TODO: IDENTIFY RECORDS ALREADY READ IN (BY ID???), INCLUDE LOGGER ID AND OTHER INFO IN OUTPUT... // ACCOMPLISH THIS BY LOOPING A QUERY??? THIS ISN'T NECESSARY IF YOU HAVE ONLY ONE C5 CELLULAR LOGGER. // => while ID id the same, write to a filename with the logger ID appended, then switch to new file when that changes // => Another feature could be to delete entries from the database once they've been written to the CSV file // // } // Properly paste JSON entries together, such that each line has the timestamp, name, and value, // and is seperated by a comma and newline character JSONData2 = JSONData2.Replace(@"},", "},\n").Replace(@"}{", "},\n{").Replace(@"},{", "},\n{"); System.IO.File.WriteAllText(@"C:\Users\dmero\Desktop\WriteText.txt", JSONData2); Console.WriteLine("Process Complete: Press any key to exit."); Console.ReadKey(); } } } } catch (SqlException e) { Console.WriteLine(e.ToString()); } }
/// <summary> /// Use a JSON Object to build the corresponding string /// </summary> /// <param name="data">JSON object to convert</param> /// <param name="colorcode">Allow parent color code to affect child elements (set to "" for function init)</param> /// <returns>returns the Minecraft-formatted string</returns> private static string JSONData2String(JSONData data, string colorcode) { string extra_result = ""; switch (data.Type) { case JSONData.DataType.Object: if (data.Properties.ContainsKey("color")) { colorcode = color2tag(JSONData2String(data.Properties["color"], "")); } if (data.Properties.ContainsKey("extra")) { JSONData[] extras = data.Properties["extra"].DataArray.ToArray(); foreach (JSONData item in extras) extra_result = extra_result + JSONData2String(item, colorcode) + "§r"; } if (data.Properties.ContainsKey("text")) { return colorcode + JSONData2String(data.Properties["text"], colorcode) + extra_result; } else if (data.Properties.ContainsKey("translate")) { List<string> using_data = new List<string>(); if (data.Properties.ContainsKey("using") && !data.Properties.ContainsKey("with")) data.Properties["with"] = data.Properties["using"]; if (data.Properties.ContainsKey("with")) { JSONData[] array = data.Properties["with"].DataArray.ToArray(); for (int i = 0; i < array.Length; i++) { using_data.Add(JSONData2String(array[i], colorcode)); } } return colorcode + TranslateString(JSONData2String(data.Properties["translate"], ""), using_data) + extra_result; } else return extra_result; case JSONData.DataType.Array: string result = ""; foreach (JSONData item in data.DataArray) { result += JSONData2String(item, colorcode); } return result; case JSONData.DataType.String: return colorcode + data.StringValue; } return ""; }
/// <summary> /// Used for storing your own player-related data on the device. /// JSONData supports all primitive data types. /// </summary> public static void SetPlayerData(string id, JSONData data) { //pass result to node instance.gameData[playerKey][id] = data; Save(id); }
/// <summary> /// Parse a JSON string to build a JSON object /// </summary> /// <param name="toparse">String to parse</param> /// <param name="cursorpos">Cursor start (set to 0 for function init)</param> /// <returns></returns> private static JSONData String2Data(string toparse, ref int cursorpos) { try { JSONData data; switch (toparse[cursorpos]) { //Object case '{': data = new JSONData(JSONData.DataType.Object); cursorpos++; while (toparse[cursorpos] != '}') { if (toparse[cursorpos] == '"') { JSONData propertyname = String2Data(toparse, ref cursorpos); if (toparse[cursorpos] == ':') { cursorpos++; } else { /* parse error ? */ } JSONData propertyData = String2Data(toparse, ref cursorpos); data.Properties[propertyname.StringValue] = propertyData; } else cursorpos++; } cursorpos++; break; //Array case '[': data = new JSONData(JSONData.DataType.Array); cursorpos++; while (toparse[cursorpos] != ']') { if (toparse[cursorpos] == ',') { cursorpos++; } JSONData arrayItem = String2Data(toparse, ref cursorpos); data.DataArray.Add(arrayItem); } cursorpos++; break; //String case '"': data = new JSONData(JSONData.DataType.String); cursorpos++; while (toparse[cursorpos] != '"') { if (toparse[cursorpos] == '\\') { try //Unicode character \u0123 { if (toparse[cursorpos + 1] == 'u' && isHex(toparse[cursorpos + 2]) && isHex(toparse[cursorpos + 3]) && isHex(toparse[cursorpos + 4]) && isHex(toparse[cursorpos + 5])) { //"abc\u0123abc" => "0123" => 0123 => Unicode char n°0123 => Add char to string data.StringValue += char.ConvertFromUtf32(int.Parse(toparse.Substring(cursorpos + 2, 4), System.Globalization.NumberStyles.HexNumber)); cursorpos += 6; continue; } else cursorpos++; //Normal character escapement \" } catch (IndexOutOfRangeException) { cursorpos++; } // \u01<end of string> catch (ArgumentOutOfRangeException) { cursorpos++; } // Unicode index 0123 was invalid } data.StringValue += toparse[cursorpos]; cursorpos++; } cursorpos++; break; //Boolean : true case 't': data = new JSONData(JSONData.DataType.String); cursorpos++; if (toparse[cursorpos] == 'r') { cursorpos++; } if (toparse[cursorpos] == 'u') { cursorpos++; } if (toparse[cursorpos] == 'e') { cursorpos++; data.StringValue = "true"; } break; //Boolean : false case 'f': data = new JSONData(JSONData.DataType.String); cursorpos++; if (toparse[cursorpos] == 'a') { cursorpos++; } if (toparse[cursorpos] == 'l') { cursorpos++; } if (toparse[cursorpos] == 's') { cursorpos++; } if (toparse[cursorpos] == 'e') { cursorpos++; data.StringValue = "false"; } break; //Unknown data default: cursorpos++; return String2Data(toparse, ref cursorpos); } return data; } catch (IndexOutOfRangeException) { return new JSONData(JSONData.DataType.String); } }
public void POST(JSONData content) { // mBatchedContent.Add(mBatchedContent.Count.ToString(), content); - disabled while this crash callstack investigated. https://ptowndev.slack.com/files/rajantande/F0C7CBYA3/screen_shot_2015-10-09_at_16.20.55.png }
public static string ToJSON(List <IAPGroup> IAPs, bool playfabVersion = false) { JSONNode data = new JSONClass(); data["CatalogVersion"] = new JSONData(1); JSONArray itemArray = new JSONArray(); for (int i = 0; i < IAPs.Count; i++) { for (int j = 0; j < IAPs[i].items.Count; j++) { IAPObject obj = IAPs[i].items[j]; JSONNode node = new JSONClass(); node["CatalogVersion"] = new JSONData(1); node["ItemId"] = new JSONData(obj.id); node["DisplayName"] = new JSONData(obj.title); node["Description"] = new JSONData(obj.description); switch (obj.type) { case ProductType.Consumable: node["Consumable"]["UsagePeriod"] = new JSONData(5); if (obj.editorType != IAPType.Currency) { node["IsStackable"] = new JSONData(true); } break; #if UNITY_PURCHASING case ProductType.Subscription: node["IsStackable"] = new JSONData(true); break; #endif } switch (obj.editorType) { case IAPType.Default: case IAPType.Currency: string allowedChars = "01234567890.,"; string realPrice = new string(obj.realPrice.Where(c => allowedChars.Contains(c)).ToArray()); double price = 0; if (!string.IsNullOrEmpty(realPrice)) { double.TryParse(realPrice, out price); price *= 100; } node["VirtualCurrencyPrices"]["RM"] = new JSONData(price); if (obj.editorType == IAPType.Currency) { for (int k = 0; k < obj.virtualPrice.Count; k++) { node["Bundle"]["BundledVirtualCurrencies"][obj.virtualPrice[k].name.Substring(0, 2).ToUpper()] = new JSONData(obj.virtualPrice[k].amount); } } break; case IAPType.Virtual: bool isFree = true; for (int k = 0; k < obj.virtualPrice.Count; k++) { node["VirtualCurrencyPrices"][obj.virtualPrice[k].name.Substring(0, 2).ToUpper()] = new JSONData(obj.virtualPrice[k].amount); if (obj.virtualPrice[k].amount > 0) { isFree = false; } } if (playfabVersion && isFree) { continue; } break; } node["SIS"]["Group"]["Name"] = new JSONData(IAPs[i].name); node["SIS"]["Group"]["Id"] = new JSONData(IAPs[i].id); node["SIS"]["Fetch"] = new JSONData(obj.fetch); node["SIS"]["Price"] = new JSONData(obj.realPrice); node["SIS"]["Type"] = new JSONData((int)obj.type); if (obj.icon) { node["SIS"]["Icon"] = new JSONData(AssetDatabase.GetAssetPath(obj.icon)); } if (!string.IsNullOrEmpty(obj.req.entry)) { node["SIS"]["Requirement"]["Id"] = new JSONData(obj.req.entry); node["SIS"]["Requirement"]["Value"] = new JSONData(obj.req.target); node["SIS"]["Requirement"]["Text"] = new JSONData(obj.req.labelText); } if (!string.IsNullOrEmpty(obj.req.nextId)) { node["SIS"]["Requirement"]["Next"] = new JSONData(obj.req.nextId); } for (int k = 0; k < obj.storeIDs.Count; k++) { string platformId = obj.storeIDs[k].id; if (playfabVersion) { JSONNode platformNode = JSON.Parse(node.ToString()); platformNode["ItemId"] = new JSONData(platformId); if (itemArray.Childs.Count(x => x["ItemId"].Value == platformId) == 0) { itemArray[itemArray.Count] = platformNode; } continue; } int platform = (int)((IAPPlatform)System.Enum.Parse(typeof(IAPPlatform), obj.storeIDs[k].store)); node["SIS"]["PlatformId"][platform.ToString()] = new JSONData(platformId); } itemArray[itemArray.Count] = node; } } data["Catalog"] = itemArray; return(data.ToString()); }
private void AddData(string key, JSONData val) { response["data"][key] = val; }
//Converts json data into TelemetryData objects, sorts by severity and name, and updates notification array void UpdateNotificationsArray(JSONData jsonData) { //Numerical data NumericalData Heart_bpm = new NumericalData("Heart rate", jsonData.heart_bpm, "bpm", 0, 300); NumericalData P_suit = new NumericalData("Suit pressure", jsonData.p_suit, "psia", 2, 4); NumericalData P_sub = new NumericalData("External pressure", jsonData.p_sub, "psia", 2, 4); NumericalData T_sub = new NumericalData("External temperature", jsonData.t_sub, "F", -150, 250); NumericalData V_fan = new NumericalData("Fan speed", jsonData.v_fan, "RPM", 10000, 40000); NumericalData P_o2 = new NumericalData("O2 pressure", jsonData.p_o2, "psia", 750, 950); NumericalData Rate_o2 = new NumericalData("O2 flow rate", jsonData.rate_o2, "psi/min", 0.5, 1); NumericalData Cap_battery = new NumericalData("Battery capacity", jsonData.cap_battery, "amp-hr", 0, 30); NumericalData P_h2o_g = new NumericalData("H2O gas pressure", jsonData.p_h2o_g, "psia", 14, 16); NumericalData P_h2o_l = new NumericalData("H2O liquid pressure", jsonData.p_h2o_l, "psia", 14, 16); NumericalData P_sop = new NumericalData("SOP pressure", jsonData.p_sop, "psia", 750, 950); NumericalData Rate_sop = new NumericalData("SOP flow rate", jsonData.rate_sop, "psia/min", 0.5, 1); //Switch data SwitchData Sop_on = new SwitchData("SOP active", jsonData.sop_on, false); SwitchData Sspe = new SwitchData("Pressure emergency", jsonData.sspe, true); SwitchData Fan_error = new SwitchData("Fan error", jsonData.fan_error, true); SwitchData Vent_error = new SwitchData("Vent error", jsonData.vent_error, true); SwitchData Vehicle_power = new SwitchData("Receiving power", jsonData.vehicle_power, false); SwitchData H2o_off = new SwitchData("H2O offline", jsonData.h2o_off, true); SwitchData O2_off = new SwitchData("O2 offline", jsonData.o2_off, true); //Timer data TimerData T_battery = new TimerData("Battery life", jsonData.t_battery, "01:00:00", "00:30:00"); TimerData T_oxygen = new TimerData("Oxygen remaining", jsonData.t_oxygen, "01:00:00", "00:30:00"); TimerData T_water = new TimerData("Water remaining", jsonData.t_water, "01:00:00", "00:30:00"); //These next two lists are already in alphabetical order to save us a sort //*****BE VERY CAREFUL WHEN EDITING THESE NEXT TWO LISTS***** //*****There are constants at the top of the script which depend on the objects' positions***** numericalTextList[0] = Cap_battery; numericalTextList[1] = P_sub; numericalTextList[2] = T_sub; numericalTextList[3] = V_fan; numericalTextList[4] = P_h2o_g; numericalTextList[5] = P_h2o_l; numericalTextList[6] = Heart_bpm; numericalTextList[7] = Rate_o2; numericalTextList[8] = P_o2; numericalTextList[9] = Rate_sop; numericalTextList[10] = P_sop; numericalTextList[11] = P_suit; switchTextList[0] = Fan_error; switchTextList[1] = H2o_off; switchTextList[2] = O2_off; switchTextList[3] = Sspe; switchTextList[4] = Vehicle_power; switchTextList[5] = Sop_on; switchTextList[6] = Vent_error; timerTextList[0] = T_battery; timerTextList[1] = T_oxygen; timerTextList[2] = T_water; //We'll need to sort this list //Feel free to edit this list notificationsList[0] = P_sub; notificationsList[1] = T_sub; notificationsList[2] = V_fan; notificationsList[3] = P_o2; notificationsList[4] = Rate_o2; notificationsList[5] = Cap_battery; notificationsList[6] = P_h2o_g; notificationsList[7] = P_h2o_l; notificationsList[8] = P_sop; notificationsList[9] = Rate_sop; notificationsList[10] = Sop_on; notificationsList[11] = Sspe; notificationsList[12] = Fan_error; notificationsList[13] = Vent_error; notificationsList[14] = Vehicle_power; notificationsList[15] = H2o_off; notificationsList[16] = O2_off; notificationsList[17] = P_suit; notificationsList[18] = Heart_bpm; notificationsList[19] = T_battery; notificationsList[20] = T_oxygen; notificationsList[21] = T_water; //Sort by severity and then alphabetically notificationsList.Sort((x, y) => { int retval = x.severity.CompareTo(y.severity); if (retval == 0) { retval = x.name.CompareTo(y.name); } return(retval); }); }
//Repeatedly read telemetry data from server using an HTTP GET request and update notification data IEnumerator GetTelemetryData() { while (true) { string numericalStr = "blank:blank", switchStr = "blank:blank", jsonStr = "blank:blank"; //Get numerical data using (UnityWebRequest www1 = UnityWebRequest.Get(numericalDataURL)) { yield return(www1.Send()); if (www1.isError) { numericalServerConnErr = true; Debug.Log(www1.error); } else { numericalServerConnErr = false; numericalStr = www1.downloadHandler.text; numericalStr = numericalStr.Trim(); } } //Get switch data using (UnityWebRequest www2 = UnityWebRequest.Get(switchDataURL)) { yield return(www2.Send()); if (www2.isError) { switchServerConnErr = true; Debug.Log(www2.error); } else { switchServerConnErr = false; switchStr = www2.downloadHandler.text; switchStr = switchStr.Trim(); } } //Parse and update notifications if valid connections to servers exist //Note that BOTH connections must be working for any updates to occur //TODO: if one server goes down, figure out how to only update notifications from the other server if (!switchServerConnErr && !numericalServerConnErr) { jsonStr = numericalStr.Substring(1, numericalStr.Length - 3) + "," + switchStr.Substring(2, switchStr.Length - 3); JSONData jsonData = JSONData.CreateFromJSON(jsonStr); UpdateNotificationsArray(jsonData); } //Clear notifications foreach (Transform child in notificationsPanel.transform) { Destroy(child.gameObject); } //Clear right panel text foreach (Transform child in textPanel.transform) { Destroy(child.gameObject); } //Create new notifications //Special notifications for server communication failure appear first (if any) SwitchData switchConnNotification, numConnNotification; int index = 0; if (switchServerConnErr) { switchConnNotification = new SwitchData("Switch server connection", "false", false); CreateTelemetryNotification(switchConnNotification, index); ++index; } if (numericalServerConnErr) { numConnNotification = new SwitchData("Telemetry server connection", "false", false); CreateTelemetryNotification(numConnNotification, index); ++index; } for (; index < MAX_NOTIFICATIONS; ++index) { if (notificationsList[index] == null) { break; //hit end of list early } if (notificationsList[index].severity == Severity.NOMINAL) { break; //only show errors and warnings } CreateTelemetryNotification(notificationsList[index], index); } //Update notification icon Severity notifySeverity = notificationsList[0].severity; //there should always be something in index 0, even if server is down if (switchServerConnErr || numericalServerConnErr) { notifySeverity = Severity.CRITICAL; } String notifyIconPath = String.Format("Icons/notify-{0}", notifySeverity.ToString()); Sprite notifyIcon = Resources.Load <Sprite>(notifyIconPath); notifyImage.GetComponent <Image>().sprite = notifyIcon; //Update notification count int numNotifications = (NUM_NUMERICAL + NUM_SWITCH + NUM_TIMER) - notificationsList.FindAll(x => x.severity == Severity.NOMINAL).Count; if (numNotifications == 0) { notificationCountText.SetActive(false); } else { notificationCountText.SetActive(true); notificationCountText.GetComponentInChildren <Text>().text = "" + numNotifications; } /* * if (notifySeverity == Severity.CRITICAL) * { * notifyImage.GetComponent<AudioSource>().Play(); * } * else * { * notifyImage.GetComponent<AudioSource>().Stop(); * } */ //Create telemetry text for right panel CreateTelemetryTextHeaders(); for (int j = 0; j < numericalTextList.Count; ++j) { CreateTelemetryText(numericalTextList[j], j, TelemetryType.NUMERICAL); } for (int k = 0; k < switchTextList.Count; ++k) { CreateTelemetryText(switchTextList[k], k, TelemetryType.SWITCH); } for (int m = 0; m < timerTextList.Count; ++m) { CreateTelemetryText(timerTextList[m], m, TelemetryType.TIMER); } //Get pressure, oxygen, temperature, and battery data NumericalData suit_pressure = numericalTextList[SUIT_PRESSURE_INDEX]; NumericalData oxygen_pressure = numericalTextList[OXYGEN_INDEX]; NumericalData temperature = numericalTextList[TEMPERATURE_INDEX]; TimerData battery = timerTextList[BATTERY_INDEX]; //Update the pressure, oxygen, temperature, and battery icons and text if (suit_pressure != null) { String pressureIconPath = String.Format("Icons/suit-{0}", suit_pressure.severity.ToString()); Sprite pressureIcon = Resources.Load <Sprite>(pressureIconPath); pressureImage.sprite = pressureIcon; pressureText.GetComponentInChildren <Text>().text = suit_pressure.value + " " + suit_pressure.units; } if (oxygen_pressure != null) { String oxygenIconPath = String.Format("Icons/oxygen-{0}", oxygen_pressure.severity.ToString()); Sprite oxygenIcon = Resources.Load <Sprite>(oxygenIconPath); oxygenImage.sprite = oxygenIcon; oxygenText.GetComponentInChildren <Text>().text = oxygen_pressure.value + " " + oxygen_pressure.units; } if (temperature != null) { String temperatureIconPath = String.Format("Icons/temperature-{0}", temperature.severity.ToString()); Sprite temperatureIcon = Resources.Load <Sprite>(temperatureIconPath); temperatureImage.sprite = temperatureIcon; temperatureText.GetComponentInChildren <Text>().text = temperature.value + " " + temperature.units; } if (battery != null) { String batteryIconPath = String.Format("Icons/battery-{0}", battery.severity.ToString()); Sprite batteryIcon = Resources.Load <Sprite>(batteryIconPath); batteryImage.sprite = batteryIcon; } //Update pressure and oxygen arrows if they have values //If null, the arrows won't change their rotation if (suit_pressure != null) { double pressureAngle = ValueToDegrees(suit_pressure); pressureArrow.GetComponent <RectTransform>().rotation = Quaternion.Euler(0, 0, (float)pressureAngle); } if (oxygen_pressure != null) { double oxygenAngle = ValueToDegrees(oxygen_pressure); oxygenArrow.GetComponent <RectTransform>().rotation = Quaternion.Euler(0, 0, (float)oxygenAngle); } //Wait before pulling data again yield return(new WaitForSecondsRealtime((float)REFRESH_RATE)); } }
public JSONDataParser(JSONData jsonData) { _jsonData = jsonData; }
private void RequestConnection() { try { //make handshake with TCP_client, and the port is set to be 4444 var client = new TcpClient(CommandSet.IP, CommandSet.DISCOVERY_PORT); var stream = new NetworkStream(client.Client); //initialize reader and writer var streamWriter = new StreamWriter(stream); var streamReader = new StreamReader(stream); //when the drone receive the message bellow, it will return the confirmation var handshake = new JSONClass(); handshake["controller_type"] = "computer"; handshake["controller_name"] = "oyo"; handshake["d2c_port"] = new JSONData(43210); // "43210" handshake["arstream2_client_stream_port"] = new JSONData(55004); handshake["arstream2_client_control_port"] = new JSONData(55005); streamWriter.WriteLine(handshake.ToString()); streamWriter.Flush(); var message = streamReader.ReadLine(); if (message == null) { throw new Exception(message); } //initialize this.GenerateAllStates(); this.GenerateAllSettings(); //enable video streaming //this.EnableVideoStream(); if (this._d2c.Connect() == false) { return; } this.Connected = true; this._commandThread = new Thread(this.commandThreadRoutine); this._commandThread.Start(); this._streamingThread = new Thread(this.streamingThreadRoutine); this._streamingThread.Start(); if (this.OnConnected != null) { this.OnConnected.Invoke(this); } } catch (Exception e) { if (this.OnError != null) { this.OnError.Invoke(this, e.Message); } } }
public override string ToString(string aPrefix) { var tmp = new JSONData(""); tmp.AsInt = AsInt; if (tmp.m_Data == this.m_Data) { return string.Format("{0}", Escape(m_Data)); } tmp.AsBool = AsBool; if (tmp.m_Data == this.m_Data) { return string.Format("{0}", Escape(m_Data)); } return string.Format("\"{0}\"", Escape(m_Data)); }
/// <summary> /// Set decks to choose from json data. /// </summary> public DecksPageVM() { Decks = JSONData.GetSavedDecks(); }
public void LoadJSON(JSONData data) { slider.value = data.sliderValue; }
public MainWindow() { InitializeComponent(); jsonData = new JSONData(); DataContext = jsonData; }
public async Task <IActionResult> Creation(CorporationDtoCreation corporationDto) { JSONData jsondata = new JSONData(); if (!ModelState.IsValid) { //ModelState.AddModelError(string.Empty, "自定义描述错误"); //ModelState.Remove("AreaID"); //ViewBag.ModelState = ModelState; //ViewData["ModelState"] = ModelState; //var values = ModelState.Values.Where(s => s.Errors.Any()); ViewBag.AreaIDs = string.Join(",", corporationDto.AreaID); Dictionary <string, string> ModelErrors = new Dictionary <string, string>(); var keys = ModelState.Keys.Where(k => ModelState[k].Errors.Count > 0); foreach (var key in keys) { var ErrorMessages = ""; if (key == "AreaID") { ErrorMessages = "请正确选择区划地址!"; } else { foreach (var error in ModelState[key].Errors) { ErrorMessages += ' ' + error.ErrorMessage; } } ModelErrors.Add(key, ErrorMessages); } jsondata.Code = EnumCollection.ResponseStatusCode.MODELSTATE; jsondata.Data = new { ModelErrors, AreaIDs = string.Join(",", corporationDto.AreaID) }; jsondata.Message = "数据校验非法,请核实!"; return(Json(jsondata)); } var firstArerID = corporationDto.AreaID.FirstOrDefault(); if (Constant.SpecialAdministrativeRegionAreaID.Contains(firstArerID)) { if (corporationDto.AreaID.Count < 2) { jsondata.Code = EnumCollection.ResponseStatusCode.ARGUMENTSLOSE; jsondata.Message = "请选择完整的区划地址"; return(Json(jsondata)); } } if (corporationDto.AreaID.Count < 4) { jsondata.Code = EnumCollection.ResponseStatusCode.ARGUMENTSLOSE; jsondata.Message = "请选择完整的区划地址"; return(Json(jsondata)); } Corporation corporation = AutoMapper.Map <Corporation>(corporationDto); corporation.CreatorUserId = 1000; if (CorporationService.IsExisted(corporation)) { jsondata.Code = EnumCollection.ResponseStatusCode.FAIL; jsondata.Message = "操作失败:分公司信息已存在,请核实!"; return(Json(jsondata)); } CorporationService.Create(corporation); var result = await CorporationService.SaveChangeAsync(); if (result > 0) { jsondata.Code = EnumCollection.ResponseStatusCode.SUCCESS; jsondata.Message = "操作成功"; return(Json(jsondata)); } return(Json(jsondata)); }
//Personel Satış Dataları public void PersonData() { var CaniasWebServiceYeni = new iasWebServiceImplService(); string sessionid = CaniasWebServiceYeni.login("00", "T", "NEW", "CANIAS", "192.168.1.50:27499/S2", "WSLIZAY", "Ws-123lizay"); //object resp = CaniasWebServiceYeni.callIASService(sessionid, "mobilExpenseList", "40,16.01.2018,16.01.2018,1,1", "STRING", true); object resp = CaniasWebServiceYeni.callIASService(sessionid, "mobilExpenseList", "0,40,01.03.2018,31.03.2018,0,1", "STRING", true); string jsonString = resp.ToString(); CaniasWebServiceYeni.logout(sessionid); JArray jsonVal = JArray.Parse(jsonString) as JArray; dynamic lizaylist = jsonVal; JSONData d = new JSONData(); foreach (dynamic x in lizaylist) { Lizay.dll.method.MOBILEXPENSELIST.AddData(new Lizay.dll.entity.MOBILEXPENSELIST() { SATISD = x.SATISD.ToString(), SALDEPT = x.SALDEPT.ToString(), COMPANY = x.COMPANY.ToString(), DOCTYPE = x.DOCTYPE.ToString(), DOCNUM = x.DOCNUM.ToString(), DOCDATE = x.DOCDATE.ToString(), CUSTOMER = x.CUSTOMER.ToString(), NAME1 = x.NAME1.ToString(), CUSTGRP = x.CUSTGRP.ToString(), COUNTRY = x.COUNTRY.ToString(), DISCAMNT = x.DISCAMNT.ToString(), CURRENCY = x.CURRENCY.ToString(), ITEMNUM = x.ITEMNUM.ToString(), MATERIAL = x.MATERIAL.ToString(), MTEXT = x.MTEXT.ToString(), QUANTITY = x.QUANTITY.ToString(), QUNIT = x.QUNIT.ToString(), BUSAREA = x.BUSAREA.ToString(), SPRICE = x.SPRICE.ToString(), PRICEFACTOR = x.PRICEFACTOR.ToString(), GROSS = x.GROSS.ToString(), TDISCAMNT = x.TDISCAMNT.ToString(), DISCFROMHEAD = x.DISCFROMHEAD.ToString(), SUBTOTAL = x.SUBTOTAL.ToString(), ITENDORSE = x.ITENDORSE.ToString(), MATTYPE = x.MATTYPE.ToString(), MATGRP = x.MATGRP.ToString(), EXHM = x.EXHM.ToString(), EXHR = x.EXHR.ToString(), MONTSUBTOTAL = x.MONTSUBTOTAL.ToString(), YEARSUBTOTAL = x.YEARSUBTOTAL.ToString(), MONTHQUANTITY = x.MONTHQUANTITY.ToString(), YEARQUANTITY = x.YEARQUANTITY.ToString(), ISVARIANT = x.ISVARIANT.ToString(), QUANTITYX = x.QUANTITYX.ToString(), TCOST = x.TCOST.ToString(), BATCHNUM = x.BATCHNUM.ToString(), TOTPROF = x.TOTPROF.ToString(), TOTRATE = x.TOTRATE.ToString(), PRINTEDINVNUM = x.PRINTEDINVNUM.ToString(), MAINMATGRP = x.MAINMATGRP.ToString(), PAYMCOND = x.PAYMCOND.ToString(), PAYMTYPE = x.PAYMTYPE.ToString(), SCMADEN = x.SCMADEN.ToString(), SCGRUP = x.SCGRUP.ToString(), SCTEMEL = x.SCTEMEL.ToString(), SALDEPTX = x.SALDEPTX.ToString(), PUAN = x.PUAN.ToString(), TEGI = x.TEGI.ToString(), TERW = x.TERW.ToString(), INVTYPE = x.INVTYPE.ToString(), DATATYPE = "PERSONEL", }); } Label2.Text = jsonVal.Count.ToString() + " Adet personel kaydı aktarılmıştır."; }
/// <summary> /// Use a JSON Object to build the corresponding string /// </summary> /// <param name="data">JSON object to convert</param> /// <returns>returns the Minecraft-formatted string</returns> private static string JSONData2String(JSONData data) { string colorcode = ""; switch (data.Type) { case JSONData.DataType.Object: if (data.Properties.ContainsKey("color")) { colorcode = color2tag(JSONData2String(data.Properties["color"])); } if (data.Properties.ContainsKey("text")) { return colorcode + JSONData2String(data.Properties["text"]) + colorcode; } else if (data.Properties.ContainsKey("translate")) { List<string> using_data = new List<string>(); if (data.Properties.ContainsKey("using")) { JSONData[] array = data.Properties["using"].DataArray.ToArray(); for (int i = 0; i < array.Length; i++) { using_data.Add(JSONData2String(array[i])); } } return colorcode + TranslateString(JSONData2String(data.Properties["translate"]), using_data) + colorcode; } else return ""; case JSONData.DataType.Array: string result = ""; foreach (JSONData item in data.DataArray) { result += JSONData2String(item); } return result; case JSONData.DataType.String: return data.StringValue; } return ""; }
private void processJsonData(string _url) { jsonData = JsonUtility.FromJson <JSONData>(_url); highscoreDisplay.updateHighscore(jsonData); }
public static void AddJSONData(Dictionary <string, object> outDict, string key, JSONData obj) { outDict.Add(key, obj.ToJSONData()); }
private Question PickQuestion(List <string> _subjectList, bool _free, bool _mcq, bool _alreadyAsked) { Question output = new Question(); // Récupération des données du fichier data.json string jsonString = File.ReadAllText(jsonDataPath); data = JsonUtility.FromJson <JSONData>(jsonString); // Transformation des bools en paramètres en un nombre décimal string optStr = BoolToInt(_free).ToString() + BoolToInt(_mcq).ToString() + BoolToInt(_alreadyAsked).ToString(); int options = System.Convert.ToInt32(optStr, 2); if (options > 7) { Debug.Log("ERROR : trop d'options données pour la recherche aléatoire de question"); } // Récupération de la liste des questions appartenant aux matières choisies. Question[] allQuestions = data.questions; List <Question> allQuestionsReduced = new List <Question>(); string subjects = string.Join(", ", _subjectList); foreach (Question question in allQuestions) { if (subjects.Contains(question.matiere)) { allQuestionsReduced.Add(question); } } // Récupération de la liste des questions en suivant les options données en paramètres List <Question> questionList = new List <Question>(); switch (options) { // Pas encore posée case 0: case 6: foreach (Question question in allQuestionsReduced) { if (!question.deja_pose) { questionList.Add(question); } } break; // Déjà posée case 1: case 7: foreach (Question question in allQuestionsReduced) { questionList.Add(question); } break; // QCM & Pas encore posée case 2: foreach (Question question in allQuestionsReduced) { if (question.type.Equals("qcm") && !question.deja_pose) { questionList.Add(question); } } break; // QCM & Déjà posée case 3: foreach (Question question in allQuestionsReduced) { if (question.type.Equals("qcm")) { questionList.Add(question); } } break; // libre & Pas encore posée case 4: foreach (Question question in allQuestionsReduced) { if (question.type.Equals("libre") && !question.deja_pose) { questionList.Add(question); } } break; // libre & Déjà posée case 5: foreach (Question question in allQuestionsReduced) { if (question.type.Equals("libre")) { questionList.Add(question); } } break; } // On récupère au hasard une question dans la liste obtenue. if (questionList.Count != 0) { output = questionList[Random.Range(0, questionList.Count)]; } else { output = null; Debug.Log("Il n'y a plus de questions à poser pour la/les matière/s choisies."); } return(output); }