public static GcmNotification WithData(this GcmNotification n, IDictionary<string, string> data) { if (data == null) return n; var json = new Newtonsoft.Json.Linq.JObject(); try { if (!String.IsNullOrEmpty (n.JsonData)) json = Newtonsoft.Json.Linq.JObject.Parse (n.JsonData); } catch { } foreach (var pair in data) json.Add (pair.Key, new Newtonsoft.Json.Linq.JValue (pair.Value)); n.JsonData = json.ToString (Newtonsoft.Json.Formatting.None); return n; }
public void unsubscribeTrades() { JSONObject ob = new JSONObject(); ob.Add("command", "stopTrades"); writeMessage(ob.ToString()); }
/// <summary> /// A simple function that takes a string and does a ToUpper /// /// To use this handler to respond to an AWS event, reference the appropriate package from /// https://github.com/aws/aws-lambda-dotnet#events /// and change the string input parameter to the desired event type. /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public static string FunctionHandler(Newtonsoft.Json.Linq.JObject evnt, ILambdaContext context) { var response = evnt.ToString(); context.Logger.Log("Complete JSON of the event is:" + evnt.ToString()); var records = evnt.Property("Records"); context.Logger.Log("\nRecord Array:" + records.Value); // TODO check to see if only one, handle multiple Newtonsoft.Json.Linq.JObject record = (Newtonsoft.Json.Linq.JObject)records.First[0]; var awsRegionString = record.Property("awsRegion").Value; context.Logger.Log("\nAWS Region String is:" + awsRegionString); Newtonsoft.Json.Linq.JObject tmpObject = (Newtonsoft.Json.Linq.JObject)record.Property("s3").Value; Newtonsoft.Json.Linq.JObject tmpObject2 = (Newtonsoft.Json.Linq.JObject)tmpObject.Property("bucket").Value; string bucketName = tmpObject2.Property("name").Value.ToString(); context.Logger.Log("\nBucket Property Name:" + bucketName); tmpObject2 = (Newtonsoft.Json.Linq.JObject)tmpObject.Property("object").Value; string keyName = tmpObject2.Property("key").Value.ToString(); context.Logger.Log("\nKey Property Name:" + keyName); // TODO assign a region based on text found Amazon.RegionEndpoint awsRegion = Amazon.RegionEndpoint.USEast1; ReadObjectDataAsync(awsRegion, bucketName, keyName).Wait(); return(response); }
internal void NewMessage(Newtonsoft.Json.Linq.JObject msg) { _lastMessage = DateTime.Now; try { string text = msg.ToString(); long id = (long)msg["message_id"]; if (_lastMessageId < id) { _lastMessageId = id; string ChatText = (string)msg["text"]; string Sender = (string)msg["user_name"]; DateTime time = UnixTimeStampToDateTime(double.Parse((string)msg["timestamp"])); TwoRatChat.Model.ChatMessage chatMessage = new TwoRatChat.Model.ChatMessage() { Date = time, Name = Sender, Text = ReplaceSmiles(ChatText .Replace(""", "\"") .Replace("'", "'")), Source = this, //Form = 0, Id = _id, ToMe = this.ContainKeywords(ChatText) }; newMessagesArrived(new TwoRatChat.Model.ChatMessage[] { chatMessage }); } } catch (Exception er) { App.Log('!', "Goodgame message parsing exception: {0} - {1}", er, msg.ToString()); } }
/// <summary> /// Automatic Recognition 开始自动识别 /// </summary> private void IDRecognition() { string apiKey = ConfigurationHelper.GetConfig(ConfigItemName.baiduApiKey.ToString()); string apiScret = ConfigurationHelper.GetConfig(ConfigItemName.baiduApiSecretKey.ToString()); Ocr ocr = new Ocr(apiKey, apiScret); Newtonsoft.Json.Linq.JObject ob = ocr.Idcard(FileHelper.GetBytes(imagePath), "front"); //BaiduLicenseRecognition baiduLicense = BaiduAipHelper.getLicenseRecognition(ob); ConsoleHelper.writeLine(ob.ToString()); MessageBox.Show(ob.ToString()); }
internal static NIMIMMessage CreateMessage(Newtonsoft.Json.Linq.JObject token) { if (!token.HasValues || token.Type != Newtonsoft.Json.Linq.JTokenType.Object) { return(null); } var msgTypeToken = token.SelectToken(NIMIMMessage.MessageTypePath); if (msgTypeToken == null) { throw new ArgumentException("message type must be seted:" + token.ToString(Formatting.None)); } var msgType = msgTypeToken.ToObject <NIMMessageType>(); NIMIMMessage message = null; ConvertAttachStringToObject(token); switch (msgType) { case NIMMessageType.kNIMMessageTypeAudio: message = token.ToObject <NIMTextMessage>(); break; case NIMMessageType.kNIMMessageTypeFile: message = token.ToObject <NIMFileMessage>(); break; case NIMMessageType.kNIMMessageTypeImage: message = token.ToObject <NIMImageMessage>(); break; case NIMMessageType.kNIMMessageTypeLocation: message = token.ToObject <NIMLocationMessage>(); break; case NIMMessageType.kNIMMessageTypeText: message = token.ToObject <NIMTextMessage>(); break; case NIMMessageType.kNIMMessageTypeVideo: message = token.ToObject <NIMVedioMessage>(); break; case NIMMessageType.kNIMMessageTypeNotification: message = token.ToObject <NIMTeamNotificationMessage>(); break; default: message = token.ToObject <NIMUnknownMessage>(); (message as NIMUnknownMessage).RawMessage = token.ToString(Formatting.None); break; } return(message); }
/// <summary> /// [自校验] 将流数据发送至套接字,具体发送细节将在继承类中实现,如果结果异常,则结束通讯 /// </summary> /// <param name="socket">套接字</param> /// <param name="stream">文件名称,文件必须存在</param> /// <param name="servername">远程端的文件名称</param> /// <param name="filetag">文件的额外标签</param> /// <param name="fileupload">文件的上传人</param> /// <param name="sendReport">发送进度报告</param> /// <returns></returns> protected OperateResult SendFileAndCheckReceive( Socket socket, Stream stream, string servername, string filetag, string fileupload, Action <long, long> sendReport = null ) { // 文件存在的情况 Newtonsoft.Json.Linq.JObject json = new Newtonsoft.Json.Linq.JObject { { "FileName", new Newtonsoft.Json.Linq.JValue(servername) }, { "FileSize", new Newtonsoft.Json.Linq.JValue(stream.Length) }, { "FileTag", new Newtonsoft.Json.Linq.JValue(filetag) }, { "FileUpload", new Newtonsoft.Json.Linq.JValue(fileupload) } }; // 发送文件信息 OperateResult fileResult = SendStringAndCheckReceive(socket, 1, json.ToString( )); if (!fileResult.IsSuccess) { return(fileResult); } return(SendStream(socket, stream, stream.Length, sendReport, true)); }
public SpeechToTextResponse(string jsonString, string httpError) { if (!string.IsNullOrEmpty(jsonString)) { JsonObject jsonObject = JsonObject.Parse(jsonString); Newtonsoft.Json.Linq.JObject obj = Newtonsoft.Json.Linq.JObject.Parse(jsonString); displayString = obj.ToString(); recognitionStatus = jsonObject.GetNamedString(RecognitionStatusKey, ""); offset = jsonObject.GetNamedNumber(OffsetKey, 0); duration = jsonObject.GetNamedNumber(DurationKey, 0); displayText = jsonObject.GetNamedString(DisplayTextKey, ""); results = new ObservableCollection <SpeechToTextResult>(); if (results != null) { foreach (IJsonValue jsonValue in jsonObject.GetNamedArray(NBestKey, new JsonArray())) { if (jsonValue.ValueType == JsonValueType.Object) { results.Add(new SpeechToTextResult(jsonValue.GetObject())); } } } } if (!string.IsNullOrEmpty(httpError)) { HttpError = httpError; } }
public override string ToJSONString() { JSONObject obj = new JSONObject(); obj.Add("command", this.commandName); return(obj.ToString()); }
public IActionResult JsonRequestTest(Newtonsoft.Json.Linq.JObject userDetail) { var data = _ManageUser.uspSaveUserAccessRequest_JSON(userDetail.ToString()); RouteData.Values.Add(MessageConstants.ReturnMessage, MessageConstants.UserApproved); return(Ok(data)); }
public File create() { var req = WebRequest.Create("https://www.googleapis.com/drive/v3/files?uploadType=multipart&fields=*"); req.Method = "POST"; req.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + access_token); req.ContentType = " multipart/related; boundary=foo_bar_baz"; var w = new System.IO.StreamWriter(req.GetRequestStream()); w.WriteLine("--foo_bar_baz"); w.WriteLine("Content-Type: application/json; charset=UTF-8"); w.WriteLine(); var j = new Newtonsoft.Json.Linq.JObject( new Newtonsoft.Json.Linq.JProperty("name", new Newtonsoft.Json.Linq.JValue("new folder01")), new Newtonsoft.Json.Linq.JProperty("mimeType", new Newtonsoft.Json.Linq.JValue("application/vnd.google-apps.folder")) ); w.WriteLine(j.ToString()); w.WriteLine("--foo_bar_baz--"); w.Close(); var res = req.GetResponse(); var json = new System.IO.StreamReader(res.GetResponseStream()).ReadToEnd(); res.Dispose(); return(JsonConvert.DeserializeObject <File>(json)); }
public static GcmNotification WithData(this GcmNotification n, IDictionary <string, string> data) { if (data == null) { return(n); } var json = new Newtonsoft.Json.Linq.JObject(); try { if (!String.IsNullOrEmpty(n.JsonData)) { json = Newtonsoft.Json.Linq.JObject.Parse(n.JsonData); } } catch { } foreach (var pair in data) { json.Add(pair.Key, new Newtonsoft.Json.Linq.JValue(pair.Value)); } n.JsonData = json.ToString(Newtonsoft.Json.Formatting.None); return(n); }
public async Task <IActionResult> Post([FromBody] Newtonsoft.Json.Linq.JObject product) { var document = BsonSerializer.Deserialize <Product>(BsonDocument.Parse(product.ToString(Formatting.Indented))); await _productRepository.Create(document); return(new OkObjectResult(document)); }
public ActionResult <ItemResponse <Stripe.Subscription> > GetSubscription() { int responseCode = 200; BaseResponse responseData = null; try { int userId = _authService.GetCurrentUserId(); StripeConfiguration.ApiKey = _appKeys.StripeApiKey; Sabio.Models.Domain.Stripe.Subscription subscription = _service.GetSubscriptionByUserId(userId); if (subscription == null) { responseCode = 404; responseData = new ErrorResponse("Subscription not found."); return(StatusCode(responseCode, responseData)); } string subscriptionId = subscription.SubscriptionId; Newtonsoft.Json.Linq.JObject subscriptionRawJObject = GetStripeSubscription(subscriptionId).RawJObject; string subscriptionString = subscriptionRawJObject.ToString(); Stripe.Subscription stripeSubscription = JsonConvert.DeserializeObject <Stripe.Subscription>(subscriptionString); responseData = new ItemResponse <Stripe.Subscription>() { Item = stripeSubscription }; } catch (Exception exception) { responseCode = 500; responseData = new ErrorResponse($"Generic Error: {exception.Message}"); base.Logger.LogError(exception.ToString()); } return(StatusCode(responseCode, responseData)); }
public static T DeserializeObject <T>(object data) { Newtonsoft.Json.Linq.JObject jObject = Newtonsoft.Json.Linq.JObject.FromObject(data); T obj = Newtonsoft.Json.JsonConvert.DeserializeObject <T>(jObject.ToString()); return(obj); }
/// <summary> /// 保存配置文件 /// </summary> /// <param name="jsonfile"></param> public static void SaveConfigs(string jsonfile) { if (m_config != null) { System.IO.File.WriteAllText(jsonfile, m_config.ToString(), Encoding.UTF8); } }
public static string GetOpponent(string uirWebAPI, string u_name, out string exceptionMessage) { exceptionMessage = string.Empty; string webResponse = string.Empty; try { Uri uri = new Uri(uirWebAPI); System.Net.WebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { dynamic user = new Newtonsoft.Json.Linq.JObject(); user.u_name = u_name; streamWriter.Write(user.ToString()); } HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream())) { webResponse = streamReader.ReadToEnd(); } } catch (Exception ex) { exceptionMessage = $"An error occurred. {ex.Message}"; } return(webResponse); }
//Konvertiert eine xml in eine json Datei public bool xml2json(string InPath, string OutPath, bool considerXMLRootObj) { XmlDocument _domDoc = new XmlDocument(); string _jsonTxt; try { _domDoc.Load(InPath); //convert XML2Json if (considerXMLRootObj) { _jsonTxt = JsonConvert.SerializeXmlNode(_domDoc); } else { _jsonTxt = JsonConvert.SerializeXmlNode(_domDoc, Newtonsoft.Json.Formatting.None, true); } Newtonsoft.Json.Linq.JObject _jsonObj = Newtonsoft.Json.Linq.JObject.Parse(_jsonTxt); File.WriteAllText(OutPath, _jsonObj.ToString()); Status = "okay"; return(true); } catch (Exception ex) { Status = ex.ToString(); return(false); } }
public string TestReadJsonFromFile() { Linq2Json l2j = new Linq2Json(); Newtonsoft.Json.Linq.JObject jarray = l2j.GetJObject4(); return(jarray.ToString()); }
public void DecodeStructuredModeMessage_AllAttributeTypes() { var obj = new JObject { // Required attributes ["specversion"] = "1.0", ["type"] = "test-type", ["id"] = "test-id", ["source"] = "//source", // Extension attributes ["binary"] = SampleBinaryDataBase64, ["boolean"] = true, ["integer"] = 10, ["string"] = "text", ["timestamp"] = SampleTimestampText, ["uri"] = SampleUriText, ["urireference"] = SampleUriReferenceText }; byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString()); var formatter = new JsonEventFormatter(); var cloudEvent = formatter.DecodeStructuredModeMessage(bytes, s_jsonCloudEventContentType, AllTypesExtensions); Assert.Equal(SampleBinaryData, cloudEvent["binary"]); Assert.True((bool)cloudEvent["boolean"]); Assert.Equal(10, cloudEvent["integer"]); Assert.Equal("text", cloudEvent["string"]); AssertTimestampsEqual(SampleTimestamp, (DateTimeOffset)cloudEvent["timestamp"]); Assert.Equal(SampleUri, cloudEvent["uri"]); Assert.Equal(SampleUriReference, cloudEvent["urireference"]); }
public void CallLongOperation(int progressStatus) { Newtonsoft.Json.Linq.JObject jsonMessage = Newtonsoft.Json.Linq.JObject.Parse(@"{ 'msg': 'message', 'value': " someValue "}"); Clients.Caller.sendMessage(jsonMessage.ToString()); }
public static void LogBCRReadInfo(string VehicleID, string portID, string mcsCmdID, string ohtcCmdID, string carrierID, string readCarrierID, ProtocolFormat.OHTMessage.BCRReadResult bCRReadResult, bool IsEnableIDReadFailScenario, [CallerMemberName] string Method = "") { try { dynamic logEntry = new Newtonsoft.Json.Linq.JObject(); logEntry.dateTime = DateTime.Now; logEntry.Method = Method; logEntry.VH_ID = VehicleID; logEntry.PortID = SCUtility.Trim(portID); logEntry.CarrierID = SCUtility.Trim(carrierID); logEntry.ReadCarrierID = SCUtility.Trim(readCarrierID); logEntry.MCS_CMD_ID = SCUtility.Trim(mcsCmdID); logEntry.OHTC_CMD_ID = SCUtility.Trim(ohtcCmdID); logEntry.BCRReadResult = bCRReadResult.ToString(); logEntry.IsEnableIDReadFailScenario = IsEnableIDReadFailScenario; logEntry.Index = "BCRReadInfo"; var json = logEntry.ToString(Newtonsoft.Json.Formatting.None); json = json.Replace("dateTime", "@timestamp"); LogManager.GetLogger("BCRReadInfo").Info(json); } catch (Exception e) { LogHelper.logger.Error($"{e}, Exception"); } }
private void buttonExtEDShipyard_Click(object sender, EventArgs e) { ShipInformation si = null; if (comboBoxShips.Text == travelhistorytext || comboBoxShips.Text.Length == 0) // second is due to the order History gets called vs this on start { if (last_he != null && last_he.ShipInformation != null) { si = last_he.ShipInformation; } } else { si = discoveryform.history.shipinformationlist.GetShipByNameIdentType(comboBoxShips.Text); } if (si != null) { Newtonsoft.Json.Linq.JObject jo = si.ToJSONLoadout(); string loadoutjournalline = jo.ToString(Newtonsoft.Json.Formatting.Indented); // File.WriteAllText(@"c:\code\loadoutout.txt", loadoutjournalline); string uri = EDDConfig.Instance.EDDShipyardURL + "#/I=" + BaseUtils.HttpUriEncode.URIGZipBase64Escape(loadoutjournalline); if (!BaseUtils.BrowserInfo.LaunchBrowser(uri)) { ExtendedControls.InfoForm info = new ExtendedControls.InfoForm(); info.Info("Cannot launch browser, use this JSON for manual ED Shipyard import", FindForm().Icon, loadoutjournalline); info.ShowDialog(FindForm()); } } }
public void cadastrarTag(String id) { long idEvento = (long)cbEventos.SelectedValue; long idTag = Convert.ToInt64(id, 16); MessageBox.Show("id " + idTag + " evento " + idEvento); HttpClient client = new HttpClient(); client.BaseAddress = new Uri(url); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); dynamic jsonObject = new Newtonsoft.Json.Linq.JObject(); jsonObject.id = idTag; jsonObject.idEvento = idEvento; jsonObject.ativo = true; var json = jsonObject.ToString(); var content = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = client.PostAsync(url + "rfid", content).Result; if (response.IsSuccessStatusCode) { MessageBox.Show("Cadastrado com sucesso"); } }
/// <summary> /// Convenience method to serialize a JObject to bytes, then /// decode it as a structured event with a specialized formatter and no extension attributes. /// </summary> private static CloudEvent DecodeStructuredModeMessage(JObject obj) { byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString()); var formatter = new SpecializedFormatter(); return(formatter.DecodeStructuredModeMessage(bytes, null, null)); }
public async Task AGitHubConnector_WillReturnAGitHubUser_WhenSearchingSuccessfully() { Newtonsoft.Json.Linq.JObject expectedUser = Generators.JsonGitHubUser.Sample(50, 1).First(); HttpResponseMessage expectedResponseFromGitHub = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(expectedUser.ToString()) }; HttpResponseMessage expectedRepositoriesResponse = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent("[]") }; Mock <IAppHttpClient> appHttpClient = new Mock <IAppHttpClient>(); appHttpClient.SetupSequence(c => c.Get(It.IsAny <string>())) .ReturnsAsync(expectedResponseFromGitHub) .ReturnsAsync(expectedRepositoriesResponse); GitHubConnector connector = new GitHubConnector(appHttpClient.Object); GitHubUser result = await connector.FindUser("test"); Assert.AreEqual(result.FullName, expectedUser.GetValue("name").ToString()); }
public File move(string fileId, string addParents = null, string removeParents = null) { var builder = new UriBuilder("https://www.googleapis.com/drive/v3/files/" + fileId); var sb = new StringBuilder(); sb.Append("fields=*"); if (addParents != null && removeParents != null) { sb.AppendFormat("&addParents={0}", addParents); sb.AppendFormat("&removeParents={0}", removeParents); } builder.Query = sb.ToString(); var req = WebRequest.Create(builder.Uri); req.Method = "PATCH"; req.ContentType = "application/json"; req.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + access_token); var w = new System.IO.StreamWriter(req.GetRequestStream()); var j = new Newtonsoft.Json.Linq.JObject(new Newtonsoft.Json.Linq.JProperty("name", new Newtonsoft.Json.Linq.JValue("new01.zip"))); w.Write(j.ToString()); w.Close(); var res = req.GetResponse(); var json = new System.IO.StreamReader(res.GetResponseStream()).ReadToEnd(); res.Dispose(); return(JsonConvert.DeserializeObject <File>(json)); }
public SpeechToTextResponse(string jsonString, string httpError = null) { if (!string.IsNullOrEmpty(jsonString)) { JsonObject jsonObject = JsonObject.Parse(jsonString); Newtonsoft.Json.Linq.JObject obj = Newtonsoft.Json.Linq.JObject.Parse(jsonString); displayString = obj.ToString(); version = jsonObject.GetNamedString(versionKey, ""); header = new SpeechToTextHeader(jsonObject.GetNamedObject(headerKey, null)); results = new ObservableCollection <SpeechToTextResult>(); if (results != null) { foreach (IJsonValue jsonValue in jsonObject.GetNamedArray(resultsKey, new JsonArray())) { if (jsonValue.ValueType == JsonValueType.Object) { results.Add(new SpeechToTextResult(jsonValue.GetObject())); } } } } if (!string.IsNullOrEmpty(httpError)) { HttpError = httpError; } }
public static baiduVehicleRecognition getvehicleRecognition(Newtonsoft.Json.Linq.JObject jObject) { if (jObject == null) { return(null); } baiduVehicleRecognition vehicle = new baiduVehicleRecognition(); Newtonsoft.Json.Linq.JToken jtError = jObject.SelectToken("error_code"); if (jtError != null) { vehicle.errorCode = jtError.ToString(); vehicle.ErrorMsg = jObject.SelectToken("error_msg").ToString(); return(vehicle); } MyHelper.ConsoleHelper.writeLine(jObject.ToString()); Newtonsoft.Json.Linq.JToken wordsResult = jObject.SelectToken("words_result"); if (wordsResult != null) { vehicle.brand = wordsResult.SelectToken("品牌型号").SelectToken("words").ToString(); vehicle.SendTime = wordsResult.SelectToken("发证日期").SelectToken("words").ToString(); vehicle.useType = wordsResult.SelectToken("使用性质").SelectToken("words").ToString(); vehicle.engineNumber = wordsResult.SelectToken("发动机号码").SelectToken("words").ToString(); vehicle.carNumber = wordsResult.SelectToken("号牌号码").SelectToken("words").ToString(); vehicle.owner = wordsResult.SelectToken("所有人").SelectToken("words").ToString(); vehicle.address = wordsResult.SelectToken("住址").SelectToken("words").ToString(); vehicle.registerDate = wordsResult.SelectToken("注册日期").SelectToken("words").ToString(); vehicle.carRecongnitionCode = wordsResult.SelectToken("车辆识别代号").SelectToken("words").ToString(); vehicle.carType = wordsResult.SelectToken("车辆类型").SelectToken("words").ToString(); } return(vehicle); }
private void doSigninCentercode() { string UserID = tbEmail.Text; string Password = tbPassword.Text; Newtonsoft.Json.Linq.JObject result = cloud_client.AuthenticateCenterCode(UserID, Password); MessageBox.Show(result.ToString()); }
private void ConfigSave() { jsonConfig["lastfile"] = openFileDialog1.FileName; string data = jsonConfig.ToString(); File.WriteAllText(configfileName, data); }
public string ConvertJsonString() { Newtonsoft.Json.Linq.JObject jObject = Newtonsoft.Json.Linq.JObject.FromObject(this); string jsonString = jObject.ToString(); jsonString = jsonString.Replace("\"System.Drawing.Bitmap\"", "null"); //load시, exception 방지 return(jsonString); }
public override string toJSONString() { JSONObject obj = new JSONObject(); obj.Add("command", commandName); obj.Add("prettyPrint", prettyPrint); obj.Add("arguments", arguments); obj.Add("extended", true); return obj.ToString(); }
public string ToJson() { Newtonsoft.Json.Linq.JObject res = new Newtonsoft.Json.Linq.JObject(); res.Add("state", _state); if (_state) { if (_data.Count > 0) { Newtonsoft.Json.Linq.JObject data = new Newtonsoft.Json.Linq.JObject(); Newtonsoft.Json.Linq.JProperty propData = new Newtonsoft.Json.Linq.JProperty("data", data); res.Add(propData); foreach (string key in _data.Keys) { data.Add(key, _data[key].ToString()); } } } else { res.Add("message", _message ?? "错误"); } return res.ToString(); }
public void subscribeTrades() { JSONObject ob = new JSONObject(); ob.Add("command", "getTrades"); ob.Add("streamSessionId", streamingSessionId); writeMessage(ob.ToString()); }
public void subscribePrice(String symbol) { JSONObject ob = new JSONObject(); ob.Add("command", "getTickPrices"); ob.Add("symbol", symbol); ob.Add("streamSessionId", streamingSessionId); writeMessage(ob.ToString()); }
public void LogError(string message) { try { string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), SettingConstants.SettingFolder, SettingConstants.ErrorLogFile); Newtonsoft.Json.Linq.JObject json = new Newtonsoft.Json.Linq.JObject(); json["Version"] = SettingConstants.Version; json["Guid"] = UserGUID; json["Type"] = "LogMessage"; json["Time"] = DateTime.Now.ToString(); json["Message"] = message; using (StreamWriter writer = new StreamWriter(path, true, new UTF8Encoding(false))) { writer.WriteLine(json.ToString()); writer.WriteLine(); } } catch { } }
public override string toJSONString() { JSONObject obj = new JSONObject(); obj.Add("command", this.commandName); return obj.ToString(); }
public void Deploy() { Console.WriteLine(""); Console.WriteLine("Deploying JSON"); Console.WriteLine("Loading Module directory " + sModulePath + "..."); DirectoryResourceRepository directoryResourceRepository = new DirectoryResourceRepository(sModulePath); ContentManager contentManager = new ContentManager(sClientPath, sServerPath); NWN2ResourceManager manager = new NWN2ResourceManager(); contentManager.ServerContentItemScanning += (name, status, bBegin) => { if (!bBegin) Console.Write(" -> Staging (" + status.ToString() + ")"); else Console.Write("\nScanning: " + name); }; contentManager.InitializeModule(directoryResourceRepository); contentManager.ResetAllResourcesToDefaultServer(); contentManager.ResetScanResults(); checked { manager.AddRepository(directoryResourceRepository); string sModuleName = Path.GetFileNameWithoutExtension(sModulePath); string sTlkPath = ""; foreach (DownloadableResource d in contentManager.GetDownloadableResources()) { switch (d.Type) { case DownloadableResource.FileType.Hak: string hakPath = sHomePath + "\\hak\\" + d.Name; Console.WriteLine("Adding Hak: " + d.Name); if (File.Exists(hakPath)) manager.AddRepository(new ERFResourceRepository(hakPath)); else Console.WriteLine("ERROR - Hak file not found in " + hakPath); break; case DownloadableResource.FileType.Tlk: sTlkPath = sHomePath + "\\tlk\\" + d.Name; if (File.Exists(sTlkPath)) Console.WriteLine("Found TLK: " + d.Name); else Console.WriteLine("ERROR - Tlk not found in " + sTlkPath); break; } } KeyValuePair<String, ushort>[] resourceTypes = { new KeyValuePair<String, ushort>("creature", ResUTC), new KeyValuePair<String, ushort>("door", ResUTD), new KeyValuePair<String, ushort>("encounter", ResUTE), new KeyValuePair<String, ushort>("item", ResUTI), new KeyValuePair<String, ushort>("store", ResUTM), new KeyValuePair<String, ushort>("placeable", ResUTP), new KeyValuePair<String, ushort>("tree", ResUTR), new KeyValuePair<String, ushort>("sound", ResUTS), new KeyValuePair<String, ushort>("trigger", ResUTT), new KeyValuePair<String, ushort>("waypoint", ResUTW), new KeyValuePair<String, ushort>("light", ResULT), new KeyValuePair<String, ushort>("prefab", ResPFB) }; //ushort[] resourceTypes = { ResUTC, ResUTD, ResUTE, ResUTI, ResUTM, ResUTP, ResUTR, ResUTS, ResUTT, ResUTW, ResULT, ResPFB }; var json = new Newtonsoft.Json.Linq.JObject(); foreach (KeyValuePair<String, ushort> rType in resourceTypes) { var jsonArray = new Newtonsoft.Json.Linq.JArray(); foreach (IResourceEntry resource in manager.FindEntriesByType(rType.Value)) { Console.WriteLine(rType.Key + ": " + resource.FullName); var gff = new OEIShared.IO.GFF.GFFFile(resource.GetStream(false)); if (gff != null) { Newtonsoft.Json.Linq.JObject jsonData = null; jsonData = new Newtonsoft.Json.Linq.JObject(parseGFF(gff)); //Console.WriteLine(jsonData); /* switch (rType.Value) { case ResUTC: var creature = new NWN2Toolset.NWN2.Data.Blueprints.NWN2CreatureBlueprint(gff.TopLevelStruct); jsonData = new Newtonsoft.Json.Linq.JObject(creature); break; case ResUTD: var door = new NWN2Toolset.NWN2.Data.Blueprints.NWN2DoorBlueprint(gff.TopLevelStruct); jsonData = new Newtonsoft.Json.Linq.JObject(door); break; case ResUTE: var encounter = new NWN2Toolset.NWN2.Data.Blueprints.NWN2EncounterBlueprint(gff.TopLevelStruct); jsonData = new Newtonsoft.Json.Linq.JObject(encounter); break; case ResUTI: var item = new NWN2Toolset.NWN2.Data.Blueprints.NWN2ItemBlueprint(gff.TopLevelStruct); jsonData = new Newtonsoft.Json.Linq.JObject(item); break; case ResUTM: var store = new NWN2Toolset.NWN2.Data.Blueprints.NWN2StoreBlueprint(gff.TopLevelStruct); jsonData = new Newtonsoft.Json.Linq.JObject(store); break; case ResUTP: var placeable = new NWN2Toolset.NWN2.Data.Blueprints.NWN2PlaceableBlueprint(gff.TopLevelStruct); jsonData = new Newtonsoft.Json.Linq.JObject(placeable); break; case ResUTR: var tree = new NWN2Toolset.NWN2.Data.Blueprints.NWN2TreeBlueprint(gff.TopLevelStruct); jsonData = new Newtonsoft.Json.Linq.JObject(tree); break; case ResUTS: var sound = new NWN2Toolset.NWN2.Data.Blueprints.NWN2SoundBlueprint(gff.TopLevelStruct); jsonData = new Newtonsoft.Json.Linq.JObject(sound); break; case ResUTT: var trigger = new NWN2Toolset.NWN2.Data.Blueprints.NWN2TriggerBlueprint(gff.TopLevelStruct); jsonData = new Newtonsoft.Json.Linq.JObject(trigger); break; case ResUTW: var waypoint = new NWN2Toolset.NWN2.Data.Blueprints.NWN2WaypointBlueprint(gff.TopLevelStruct); jsonData = new Newtonsoft.Json.Linq.JObject(waypoint); break; case ResULT: var light = new NWN2Toolset.NWN2.Data.Blueprints.NWN2LightBlueprint(gff.TopLevelStruct); jsonData = new Newtonsoft.Json.Linq.JObject(light); break; case ResPFB: //blueprint = new NWN2Toolset.NWN2.Data.Blueprints.NWN2BlueprintSet(gff.TopLevelStruct); break; default: break; } */ if (jsonData != null) jsonArray.Add(jsonData); } } if (jsonArray.Count > 0) json.Add(rType.Key,jsonArray); } Console.WriteLine(""); Console.WriteLine("Staging JSON Complete."); Console.WriteLine(""); Console.WriteLine(json); System.IO.File.WriteAllText(@".\nwn2.json", json.ToString()); } }
private string ObtenerConsulta() { System.IO.StreamReader lector = new System.IO.StreamReader(txtXML.Text); var xml = lector.ReadToEnd(); lector.Close(); /* Crear el JSON que se envía al servicio web */ // El servidor espera los datos en formato JSON, por ello en este ejemplo // estaremos utilizando la popular librería Newtonsoft.Json.dll, también // conocida como Json.NET var jObj = new Newtonsoft.Json.Linq.JObject( // Método, este valor identifica el servicio solicitado new Newtonsoft.Json.Linq.JProperty("method", "cfd2cfdi"), new Newtonsoft.Json.Linq.JProperty("xml_version", "3.2"), new Newtonsoft.Json.Linq.JProperty("cuenta", "demo"), new Newtonsoft.Json.Linq.JProperty("user", "administrador"), new Newtonsoft.Json.Linq.JProperty("password", "Administr4dor"), new Newtonsoft.Json.Linq.JProperty("include_stamps", true), new Newtonsoft.Json.Linq.JProperty("xml_data", xml) ); /* Creación de la consulta */ // Aquí es importante utilizar HttpUtility.UrlEncode para una correcta // interpretación de los datos del lado del servidor. string consulta = "q=" + System.Web.HttpUtility.UrlEncode(jObj.ToString()); // - NOTA: Asegúrese de incluir una referencia al ensamblado System.Web // para poder utilizar HttpUtility.UrlEncode // - NOTA 2: El ensamblado System.Web no forma parte del 'Client Profile' // por ello asegúrece de que su aplicación está configurada para utilizar, // por ejemplo, '.NET Framework 4' y no '.NET Framework 4 Client Profile'. // - NOTA 3: Lo anterior puede configurarse en la ventana: // Propiedades del Proyecto / Pestaña 'Application' / Combo 'Target framework' return consulta; }
public void unsubscribePrice(String symbol) { JSONObject ob = new JSONObject(); ob.Add("command", "stopTickPrices"); ob.Add("symbol", symbol); writeMessage(ob.ToString()); }
public void LogError(Exception e) { try { string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), SettingConstants.SettingFolder, SettingConstants.ErrorLogFile); Newtonsoft.Json.Linq.JObject json = new Newtonsoft.Json.Linq.JObject(); json["Version"] = SettingConstants.Version; json["Guid"] = UserGUID; json["Type"] = e.GetType().FullName; json["Time"] = DateTime.Now.ToString(); json["Position"] = string.Format("{0}--->{1}", e.Source, e.TargetSite); json["Message"] = e.Message; json["StackTrace"] = e.StackTrace; using (StreamWriter writer = new StreamWriter(path, true, new UTF8Encoding(false))) { writer.WriteLine(json.ToString()); writer.WriteLine(); } } catch { } }