protected internal Response(JsonObject json) { try { JsonArray error = (JsonArray)json["error"]; if (error.Count() > 0) { Result = ResultType.error; List <string> errors = new List <string>(); foreach (var item in error) { errors.Add(item.ToString()); } Errors = errors; } else { Result = ResultType.content; Content = (JsonObject)json["result"]; } } catch (Exception ex) { throw new Exception("Unable to Parse Response.", ex); } }
/// <summary> /// /// Method retrieves a list of category objects from /// specified filename within local storage. /// /// Returns an empty list if anything goes wrong. /// /// </summary> /// <param name="filename"></param> /// <returns></returns> public async Task <List <Category> > GetCategories(string filename) { List <Category> results = new List <Category>(); JsonObject categoriesObject = new JsonObject(); string jsonstring = await _accessor.getJsonString(filename); bool success = JsonObject.TryParse(jsonstring, out categoriesObject); if (success) { JsonArray categoriesArray = categoriesObject.GetNamedArray(_categoriesString); for (int i = 0; i < categoriesArray.Count(); i++) { JsonObject categoryObject = categoriesArray[i].GetObject(); string categoryName = categoryObject.GetNamedString(_nameString); JsonArray phrasesArray = categoryObject.GetNamedArray(_phrasesString); List <Phrase> phrasesList = new List <Phrase>(); foreach (JsonValue phraseValue in phrasesArray) { JsonObject phraseObject = phraseValue.GetObject(); string phraseName = phraseObject.GetNamedString(_nameString); int frequency = (int)phraseObject.GetNamedNumber(_frequencyString); string dateTimeString = phraseObject.GetNamedString(_recentString); phrasesList.Add(new Phrase(phraseName, frequency, dateTimeString)); } results.Add(new Category(categoryName, phrasesList)); } } return(results); }
/// <summary> /// This method get all videos from sharepoint site. /// </summary> /// <returns></returns> private async Task PopulateVideos() { JsonObject videobj; byte[] responseStream = await SharePointOnlineLoginHelper.AuthObj.CreateHttpRequest(System.Net.Http.HttpMethod.Get, new Uri(String.Format("{0}/_api/web/lists/getByTitle('" + SharePointOnlineLoginHelper.AuthObj.LibraryName + "')/items()", SharePointOnlineLoginHelper.AuthObj.SiteUrl.AbsoluteUri))); // the "results" json structure contains the list metadata JsonObject listDict = JsonObject.Parse(Encoding.UTF8.GetString(responseStream, 0, responseStream.Length)); JsonArray lists = listDict["d"].GetObject()["results"].GetArray(); for (int i = 1; i < lists.Count(); i++) { try { JsonObject list = lists[i].GetObject(); if (list["Title"].ValueType.ToString() != "Null") { string title = list.ContainsKey("Title") ? list["Title"].GetString() : string.Empty; string description = list.ContainsKey("Description") ? list["Description"].GetString() : string.Empty; //string basetemplate = list.ContainsKey("BaseTemplate") ? // list["BaseTemplate"].GetNumber().ToString() : string.Empty; i = i + 1; videobj = lists[i].GetObject(); string videoname = videobj["VideoRenditionLabel"].GetString(); string videourl = SharePointOnlineLoginHelper.AuthObj.SiteUrl + "/" + SharePointOnlineLoginHelper.AuthObj.LibraryName + "/"; videourl += list["Title"].GetString() + "/" + videobj["VideoRenditionLabel"].GetString(); var video = new VideoData(title, videoname, description, videourl); this._videoList.Add(video); } else if (list["VideoRenditionLabel"].ValueType.ToString() != "Null") { string videoname = list["VideoRenditionLabel"].GetString(); i = i + 1; videobj = lists[i].GetObject(); // } string description = videobj.ContainsKey("Description") ? videobj["Description"].GetString() : string.Empty; //string basetemplate = videobj.ContainsKey("BaseTemplate") ? // videobj["BaseTemplate"].GetNumber().ToString() : string.Empty; string title = videobj.ContainsKey("Title") ? videobj["Title"].GetString() : string.Empty; string videourl = SharePointOnlineLoginHelper.AuthObj.SiteUrl + "/" + SharePointOnlineLoginHelper.AuthObj.LibraryName + "/"; videourl += videobj["Title"].GetString() + "/" + list["VideoRenditionLabel"].GetString(); var video = new VideoData(title, videoname, description, videourl); this._videoList.Add(video); } } catch { // Do no crash the app if we cannot parse the payload for a list } } }
public void parseFromData(string output, string[] fields, out string[] results, bool allData) { results = new string[fields.Length]; JsonObject value = JsonObject.Parse(output); IJsonValue j, k; int i = 0; value.TryGetValue("data", out j); JsonArray value2 = j.GetArray(); // In case the search does not return any results, this array will be empty"" if (value2.Count == 0) { results[0] = "empty"; } else { if (!allData) { // Otherwise go on and parse it JsonObject object2 = value2[0].GetArray()[0].GetObject(); object2.TryGetValue("data", out k); // Go through each string fields specified in the array JsonObject object3 = k.GetObject(); foreach (string field in fields) { IJsonValue l; object3.TryGetValue(field, out l); results[i++] = l.GetString(); } } else { value2 = value2[0].GetArray(); results = new string[value2.Count()]; for (int m = 0; m < value2.Count(); m++) { // TODO: Type-checking needed here results[m] = Convert.ToString(value2[m].GetNumber()); } } } }
public static void TestHandlingNulls() { var jsonArray = new JsonArray() { "to be replaced" }; jsonArray[0] = null; Assert.Equal(1, jsonArray.Count()); Assert.IsType <JsonNull>(jsonArray[0]); jsonArray.Add(null); Assert.Equal(2, jsonArray.Count()); Assert.IsType <JsonNull>(jsonArray[1]); jsonArray.Add(new JsonNull()); Assert.Equal(3, jsonArray.Count()); Assert.IsType <JsonNull>(jsonArray[2]); jsonArray.Insert(3, null); Assert.Equal(4, jsonArray.Count()); Assert.IsType <JsonNull>(jsonArray[3]); jsonArray.Insert(4, new JsonNull()); Assert.Equal(5, jsonArray.Count()); Assert.IsType <JsonNull>(jsonArray[4]); Assert.True(jsonArray.Contains(null)); Assert.Equal(0, jsonArray.IndexOf(null)); Assert.Equal(4, jsonArray.LastIndexOf(null)); jsonArray.Remove(null); Assert.Equal(4, jsonArray.Count()); }
public async Task <IList <T> > NextPage(uint ExpectedCount = 30) { TaskCompletionSource <T[]> Ts = new TaskCompletionSource <T[]>(); RCache.POST( Shared.ShRequest.Server , PostArgs(Target, CurrentPage, ExpectedCount, new string[] { Id }) , (e, Id) => { try { JsonObject JObj = JsonStatus.Parse(e.ResponseString); JsonArray JData = JObj.GetNamedArray("data"); int LoadedCount = JData.Count(); List <T> HSI = new List <T>(LoadedCount); foreach (JsonValue ItemDef in JData) { HSI.Add(( T )Activator.CreateInstance(TType, ItemDef.GetObject())); } PageEnded = LoadedCount < ExpectedCount; CurrentPage += LoadedCount; Ts.SetResult(ConvertResult(HSI)); } catch (Exception ex) { Logger.Log(ID, ex.Message, LogType.WARNING); PageEnded = true; Ts.TrySetResult(new T[0]); } } , (cacheName, Id, ex) => { Logger.Log(ID, ex.Message, LogType.WARNING); PageEnded = true; Ts.TrySetResult(new T[0]); } , false ); T[] Cs = await Ts.Task; return(Cs); }
public List <PairingStatus> GetUserPairings(string userName) { IDictionary <string, object> user = SearchForUser(userName); string endpoint = "users/" + (string)user["id"] + "/pairings"; NameValueCollection parameters = new NameValueCollection(); parameters["deactivated"] = "0"; JsonArray jArr = getArray(endpoint, parameters); List <PairingStatus> result = new List <PairingStatus> (jArr.Count()); foreach (JsonObject o in jArr) { result.Add(new PairingStatus(o)); } return(result); }
public static string GetRandomWord(char c) { Random random = new Random(); string questMark = new string('?', random.Next(5, 10)); string ans = c + questMark; var client = new RestClient("https://api.datamuse.com/"); var request = new RestRequest($"words?sp={ans}", Method.GET); IRestResponse response = client.Execute(request); JsonArray obj = (JsonArray)SimpleJson.DeserializeObject(response.Content); JsonObject word = (JsonObject)obj[random.Next(0, obj.Count() - 1)]; string randomWord = (string)word["word"]; if (randomWord.Contains(" ") || randomWord.Any(char.IsDigit) || randomWord.Contains("-")) { randomWord = GetRandomWord(c); } return(randomWord); }
/// <summary> /// Cancels the order /// </summary> /// <param name="order">Order to cancel</param> /// <returns>CancelOrderResult containing info about eventual success or failure of the request</returns> public CancelOrderResult CancelOrder(ref KrakenOrder order) { CancelOrderResult cancelOrderResult = new CancelOrderResult(); try { JsonObject res = client.CancelOrder(order.TxId); JsonArray error = (JsonArray)res["error"]; if (error.Count() > 0) { cancelOrderResult.ResultType = CancelOrderResultType.error; List <string> errorList = new List <string>(); foreach (var item in error) { errorList.Add(item.ToString()); } cancelOrderResult.Errors = errorList; return(cancelOrderResult); } else { JsonObject result = (JsonObject)res["result"]; var count = int.Parse(result["count"].ToString()); var pending = (string)result["pending"]; RefreshOrder(ref order); cancelOrderResult.ResultType = CancelOrderResultType.success; cancelOrderResult.OrdersCanceled = count; cancelOrderResult.OrdersPending = pending; return(cancelOrderResult); } } catch (Exception ex) { cancelOrderResult.ResultType = CancelOrderResultType.exception; cancelOrderResult.Exception = ex; return(cancelOrderResult); } }
public async Task <IList <HubScriptItem> > NextPage(uint ExpectedCount = 0) { TaskCompletionSource <HubScriptItem[]> HSItems = new TaskCompletionSource <HubScriptItem[]>(); RCache.POST( Shared.ShRequest.Server , Shared.ShRequest.Search(Query, CurrentPage, ExpectedCount, AccessTokens) , (e, Id) => { try { JsonObject JResponse = JsonStatus.Parse(e.ResponseString); JsonArray JHS = JResponse.GetNamedArray("data"); int LoadedCount = JHS.Count(); PageEnded = LoadedCount < ExpectedCount; CurrentPage += LoadedCount; HSItems.SetResult(JHS.Remap(x => HubScriptItem.Create(x.GetObject())).ToArray()); } catch (Exception ex) { Logger.Log(ID, ex.Message, LogType.WARNING); PageEnded = true; HSItems.TrySetResult(new HubScriptItem[0]); } } , (cacheName, Id, ex) => { Logger.Log(ID, ex.Message, LogType.WARNING); PageEnded = true; HSItems.TrySetResult(new HubScriptItem[0]); } , false ); return(await HSItems.Task); }
public async Task <List <Pronunciation> > GetPronunciations(string filename) { List <Pronunciation> result = new List <Pronunciation>(); JsonObject pronunicationsObject = new JsonObject(); string jsonString = await _accessor.getJsonString(filename); bool success = JsonObject.TryParse(jsonString, out pronunicationsObject); if (success) { Debug.WriteLine("JsonConverter.cs: pronunciations jsonString successfully parsed"); JsonArray pronunciationsArray = pronunicationsObject.GetNamedArray(_pronunciationsString); for (int i = 0; i < pronunciationsArray.Count(); i++) { JsonObject pronunciationObject = pronunciationsArray[i].GetObject(); string word = pronunciationObject.GetNamedString(_wordString); string sound = pronunciationObject.GetNamedString(_soundString); result.Add(new Pronunciation(word, sound)); } } return(result); }
public async Task <List <Abbreviation> > GetAbbreviations(string filename) { List <Abbreviation> result = new List <Abbreviation>(); JsonObject abbreviationsObject = new JsonObject(); string jsonString = await _accessor.getJsonString(filename); bool success = JsonObject.TryParse(jsonString, out abbreviationsObject); if (success) { Debug.WriteLine("JsonConverter.cs: abbreviations jsonString successfully parsed"); JsonArray abbreviationsArray = abbreviationsObject.GetNamedArray(_abbreviationsString); for (int i = 0; i < abbreviationsArray.Count(); i++) { JsonObject abbreviationObject = abbreviationsArray[i].GetObject(); string shortcut = abbreviationObject.GetNamedString(_shortcutString); string expansion = abbreviationObject.GetNamedString(_expansionString); result.Add(new Abbreviation(shortcut, expansion)); } Debug.WriteLine("JsonConverter.cs: List has " + result.Count + " abbreviations."); } return(result); }
/// <summary> /// Call Kraken to update info about order execution. /// </summary> /// <param name="order">Order to update</param> /// <returns>RefreshOrderResult containing info about eventual success or failure of the request</returns> private RefreshOrderResult RefreshOrder(ref KrakenOrder order) { RefreshOrderResult refreshOrderResult = new RefreshOrderResult(); try { JsonObject res = _kraken.QueryOrders(order.TxId); JsonArray error = (JsonArray)res["error"]; if (error.Count() > 0) { refreshOrderResult.ResultType = RefreshOrderResultType.error; List <string> errorList = new List <string>(); foreach (var item in error) { errorList.Add(item.ToString()); } refreshOrderResult.Errors = errorList; return(refreshOrderResult); } else { JsonObject result = (JsonObject)res["result"]; JsonObject orderDetails = (JsonObject)result[order.TxId]; if (orderDetails == null) { refreshOrderResult.ResultType = RefreshOrderResultType.order_not_found; return(refreshOrderResult); } else { string status = (orderDetails["status"] != null) ? orderDetails["status"].ToString() : null; string reason = (orderDetails["reason"] != null) ? orderDetails["reason"].ToString() : null; string openTime = (orderDetails["opentm"] != null) ? orderDetails["opentm"].ToString() : null; string closeTime = (orderDetails["closetm"] != null) ? orderDetails["closetm"].ToString() : null; string vol_exec = (orderDetails["vol_exec"] != null) ? orderDetails["vol_exec"].ToString() : null; string cost = (orderDetails["cost"] != null) ? orderDetails["cost"].ToString() : null; string fee = (orderDetails["fee"] != null) ? orderDetails["fee"].ToString() : null; string price = (orderDetails["price"] != null) ? orderDetails["price"].ToString() : null; string misc = (orderDetails["misc"] != null) ? orderDetails["misc"].ToString() : null; string oflags = (orderDetails["oflags"] != null) ? orderDetails["oflags"].ToString() : null; JsonArray tradesArray = (JsonArray)orderDetails["trades"]; string trades = null; if (tradesArray != null) { foreach (var item in tradesArray) { trades += item.ToString() + ","; } trades = trades.TrimEnd(','); } order.Status = status; order.Reason = reason; order.OpenTime = openTime; order.CloseTime = closeTime; order.VolumeExecuted = double.Parse(vol_exec.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture); order.Cost = decimal.Parse(cost.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture); order.Fee = decimal.Parse(fee.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture); order.AveragePrice = decimal.Parse(price.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture); order.Info = misc; order.OFlags = oflags; order.Trades = trades; refreshOrderResult.ResultType = RefreshOrderResultType.success; return(refreshOrderResult); } } } catch (Exception ex) { refreshOrderResult.ResultType = RefreshOrderResultType.exception; refreshOrderResult.Exception = ex; return(refreshOrderResult); } }
/// <summary> /// Submit an order to Kraken. The order passed by reference will be updated with info set by Kraken. /// </summary> /// <param name="order">Order to submit.</param> /// <param name="wait">If set to true, the function will wait until the order is closed or canceled.</param> /// <returns>PlaceOrderResult containing info about eventual success or failure of the request</returns> private PlaceOrderResult PlaceOrder(ref KrakenOrder order, bool wait) { PlaceOrderResult placeOrderResult = new PlaceOrderResult(); try { JsonObject res = _kraken.AddOrder(order); JsonArray error = (JsonArray)res["error"]; if (error.Count() > 0) { placeOrderResult.ResultType = PlaceOrderResultType.error; List <string> errorList = new List <string>(); foreach (var item in error) { errorList.Add(item.ToString()); } placeOrderResult.Errors = errorList; return(placeOrderResult); } else { JsonObject result = (JsonObject)res["result"]; JsonObject descr = (JsonObject)result["descr"]; JsonArray txid = (JsonArray)result["txid"]; if (txid == null) { placeOrderResult.ResultType = PlaceOrderResultType.txid_null; return(placeOrderResult); } else { string transactionIds = ""; foreach (var item in txid) { transactionIds += item.ToString() + ","; } transactionIds = transactionIds.TrimEnd(','); order.TxId = transactionIds; if (wait) { #region Repeatedly check order status by calling RefreshOrder bool keepSpinning = true; while (keepSpinning) { RefreshOrderResult refreshOrderResult = RefreshOrder(ref order); switch (refreshOrderResult.ResultType) { case RefreshOrderResultType.success: switch (order.Status) { case "closed": placeOrderResult.ResultType = PlaceOrderResultType.success; return(placeOrderResult); case "pending": break; case "open": break; case "canceled": if (order.VolumeExecuted > 0) { placeOrderResult.ResultType = PlaceOrderResultType.partial; return(placeOrderResult); } else { placeOrderResult.ResultType = PlaceOrderResultType.canceled_not_partial; return(placeOrderResult); } default: throw new Exception(string.Format("Unknown type of order status: {0}", order.Status)); } break; case RefreshOrderResultType.error: throw new Exception( string.Format( "An error occured while trying to refresh the order.\nError List: {0}", refreshOrderResult.Errors.ToString())); case RefreshOrderResultType.order_not_found: throw new Exception( "An error occured while trying to refresh the order.\nOrder not found"); case RefreshOrderResultType.exception: throw new Exception( "An unexpected exception occured while trying to refresh the order.", refreshOrderResult.Exception); default: keepSpinning = false; break; } Thread.Sleep(5000); } #endregion } placeOrderResult.ResultType = PlaceOrderResultType.success; return(placeOrderResult); } } } catch (Exception ex) { placeOrderResult.ResultType = PlaceOrderResultType.exception; placeOrderResult.Exception = ex; return(placeOrderResult); } }
public GetOrderResult GetOpenOrders() { GetOrderResult getOrderResult = new GetOrderResult(); try { JsonObject res = client.GetOpenOrders(); JsonArray error = (JsonArray)res["error"]; if (error.Count() > 0) { getOrderResult.ResultType = GetOrderResultType.error; List <string> errorList = new List <string>(); foreach (var item in error) { errorList.Add(item.ToString()); } getOrderResult.Errors = errorList; return(getOrderResult); } else { JsonObject result = (JsonObject)res["result"]; JsonObject openOrders = (JsonObject)result["open"]; var orderIds = openOrders.Names; List <KrakenOrder> orderList = new List <KrakenOrder>(); foreach (var id in orderIds) { JsonObject orderDetails = (JsonObject)openOrders[id.ToString()]; if (orderDetails == null) { getOrderResult.ResultType = GetOrderResultType.error; return(getOrderResult); } else { //string pair = orderDetails["pair"].ToString(); string txid = id.ToString(); JsonObject descr = (JsonObject)orderDetails["descr"]; string pair = descr["pair"].ToString(); string type = descr["type"].ToString(); string ordertype = descr["ordertype"].ToString(); string price = descr["price"].ToString(); string price2 = descr["price2"].ToString(); string leverage = descr["leverage"].ToString(); string status = (orderDetails["status"] != null) ? orderDetails["status"].ToString() : null; string reason = (orderDetails["reason"] != null) ? orderDetails["reason"].ToString() : null; string openTime = (orderDetails["opentm"] != null) ? orderDetails["opentm"].ToString() : null; string closeTime = (orderDetails["closetm"] != null) ? orderDetails["closetm"].ToString() : null; string vol_exec = (orderDetails["vol_exec"] != null) ? orderDetails["vol_exec"].ToString() : null; string cost = (orderDetails["cost"] != null) ? orderDetails["cost"].ToString() : null; string fee = (orderDetails["fee"] != null) ? orderDetails["fee"].ToString() : null; string averagePrice = (orderDetails["price"] != null) ? orderDetails["price"].ToString() : null; string misc = (orderDetails["misc"] != null) ? orderDetails["misc"].ToString() : null; string oflags = (orderDetails["oflags"] != null) ? orderDetails["oflags"].ToString() : null; JsonArray tradesArray = (JsonArray)orderDetails["trades"]; string trades = null; if (tradesArray != null) { foreach (var trade in tradesArray) { trades += trade.ToString() + ","; } trades = trades.TrimEnd(','); } KrakenOrder order = new KrakenOrder(); order.Status = status; order.Reason = reason; order.OpenTime = openTime; order.CloseTime = closeTime; order.VolumeExecuted = double.Parse(vol_exec); order.Cost = decimal.Parse(cost); order.Fee = decimal.Parse(fee); order.AveragePrice = decimal.Parse(averagePrice); order.Info = misc; order.OFlags = oflags; order.Trades = trades; orderList.Add(order); } } getOrderResult.Order = orderList.FirstOrDefault();; getOrderResult.ResultType = GetOrderResultType.success; return(getOrderResult); } } catch (Exception ex) { getOrderResult.ResultType = GetOrderResultType.exception; getOrderResult.Exception = ex; return(getOrderResult); } }
public BrokerMessage(JsonArray values) { String messageTypeIdentifer = values.GetString(0); _messageType = BrokerMessageType.lookup(messageTypeIdentifer); _metaData = values.GetJsonObject(1); _serviceName = values.GetString(2); // int majorVersion = values.GetInteger(3); // int minorVersion = values.GetInteger(4); _methodName = values.GetString(5); _associativeParamaters = values.GetJsonObject(6); if (7 < values.Count()) { _orderedParamaters = values.GetJsonArray(7); } else { _orderedParamaters = new JsonArray(0); } }