/// <summary> /// Parse bytes to json string /// </summary> /// <typeparam name="T"></typeparam> /// <param name="bytes">Bytes to be parsed</param> /// <param name="logger">Optional, logger</param> /// <param name="methodName">Optional, calling method name</param> /// <param name="isDictionary">Option, Is json object is a dictionary</param> /// <returns>Returns T</returns> public static T ParseBytes <T>(byte[] bytes, IKiteLogger logger = null, [CallerMemberName] string methodName = null, bool isDictionary = false) { if (bytes == null) { return(default(T)); } try { T obj = default(T); //using dataContractSerializer DataContractJsonSerializer serializer = null; if (isDictionary) { serializer = new DataContractJsonSerializer(typeof(T), new DataContractJsonSerializerSettings() { UseSimpleDictionaryFormat = true }); } else { serializer = new DataContractJsonSerializer(typeof(T)); } using (MemoryStream ms = new MemoryStream(bytes)) { ms.Position = 0; obj = (T)serializer.ReadObject(ms); } /* * using Newtonsoft * T obj = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(str, new Newtonsoft.Json.JsonSerializerSettings() * { * NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, * MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore * }); */ if (obj == null) { try { logger?.OnLog($"{methodName} : Failed to parse data"); } catch (Exception ex) { } return(default(T)); } return(obj); } catch (Exception ex) { try { logger?.OnException(ex); } catch (Exception ex1) { } return(default(T)); } }
/// <summary> /// Downloads the symbol list /// </summary> /// <param name="apiKey">Api key</param> /// <param name="accessToken">Access token</param> /// <param name="exchange">Queried exchange. If set to null will download the all available symbols</param> /// <param name="filepath">If specified, will save the downloaded data to the specified path</param> /// <param name="logger">Optional logger</param> /// <returns></returns> public static T[] GetSymbols <T>(string apiKey, string accessToken, string url, string filepath = null, IKiteLogger logger = null) where T : SymbolBase, new() { if (string.IsNullOrEmpty(url)) { return(null); } try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Headers.Add(versionHeader, version); request.Headers.Add("Authorization", $"token {apiKey}:{accessToken}"); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { if (response?.StatusCode == HttpStatusCode.OK) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { List <T> tmp = new List <T>(); List <string> tmpLines = new List <string>(); while (!reader.EndOfStream) { string line = reader.ReadLine(); T obj = new T(); if (obj.TryParse(line)) { tmp.Add(obj as T); tmpLines.Add(line); } } if (!string.IsNullOrWhiteSpace(filepath)) { string folder = Path.GetDirectoryName(filepath); if (Directory.Exists(folder)) { if (File.Exists(filepath)) { File.Delete(filepath); } File.AppendAllLines(filepath, tmpLines); } } if (tmp.Count > 0) { return(tmp.ToArray()); } } } } } catch (Exception ex) { try { logger?.OnException(ex); } catch (Exception ex1) { } } return(null); }
/// <summary> /// The http request method /// </summary> /// <typeparam name="T"></typeparam> /// <param name="method">Query method</param> /// <param name="apiKey">Api key</param> /// <param name="accessToken">Access token</param> /// <param name="url">Url</param> /// <param name="payload">Payload</param> /// <param name="logger">Optional, logger</param> /// <param name="isDictionary">Is json string is a dictionary object. Default value is false</param> /// <returns></returns> private static T QueryHttp <T>(QueryMethod method, string apiKey, string accessToken, string url, string payload = null, IKiteLogger logger = null, bool isDictionary = false) { if (!Enum.IsDefined(typeof(QueryMethod), method)) { return(default(T)); } if (string.IsNullOrEmpty(url)) { return(default(T)); } try { logger?.OnLog($"{method}|apiKey={apiKey}, accessToken= {accessToken}, Url={url}, Payload= {payload}"); } catch (Exception ex) { } try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = method.ToString().ToUpper(); request.AllowAutoRedirect = true; request.Headers.Add(versionHeader, version); request.Headers.Add("Authorization", $"token {apiKey}:{accessToken}"); if (method == QueryMethod.POST || method == QueryMethod.PUT) { request.ContentType = "application/x-www-form-urlencoded"; if (!string.IsNullOrEmpty(payload)) { byte[] postData = Encoding.ASCII.GetBytes(payload); request.ContentLength = postData.Length; using (Stream stream = request.GetRequestStream()) { stream.Write(postData, 0, postData.Length); } } } using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode == HttpStatusCode.OK) { //if logger is not null we will log the json string if (logger != null) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { Response <T> obj = ParseString <Response <T> >(reader.ReadToEnd(), logger: logger, methodName: typeof(T).Name, isDictionary: isDictionary); if (obj == null) { return(default(T)); } return(obj.data); } } else //we serialize straight away { DataContractJsonSerializer serializer = null; if (isDictionary) { serializer = new DataContractJsonSerializer(typeof(Response <T>), new DataContractJsonSerializerSettings() { UseSimpleDictionaryFormat = true }); } else { serializer = new DataContractJsonSerializer(typeof(Response <T>)); } Response <T> obj = serializer.ReadObject(response.GetResponseStream()) as Response <T>; if (obj == null) { return(default(T)); } return(obj.data); } } } } catch (WebException we) { try { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ServerError)); ServerError se = serializer.ReadObject(we.Response.GetResponseStream()) as ServerError; if (se != null) { try { logger?.OnLog($"{se.error_type} | {se.status} | {se.message}"); } catch (Exception ex) { } try { logger?.OnException(new ServerException(se, we.Status, typeof(T))); } catch (Exception ex) { } } } catch (Exception ex) { try { logger?.OnException(ex); } catch (Exception ex1) { } } } catch (Exception ex) { try { logger?.OnException(ex); } catch (Exception ex1) { } } return(default(T)); }