public bool TryParseUInt64(out ulong value) { int consumed; var unread = Unread; if (CustomParser.TryParseUInt64(unread, out value, out consumed, default, _symbolTable)) { if (unread.Length > consumed) { _currentSegmentIndex += consumed; return(true); } } Span <byte> tempSpan = stackalloc byte[32]; var copied = CopyTo(tempSpan); if (CustomParser.TryParseUInt64(tempSpan.Slice(0, copied), out value, out consumed, 'G', _symbolTable)) { Advance(consumed); return(true); } return(false); }
public IHttpActionResult Token(LoginModel user) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } string hashedPassword = Auth.HashPassword(user.Password); List <user> currentUser = _db.user.Where(x => x.login == user.Login && x.password == hashedPassword).ToList(); if (currentUser.Count != 1) { return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Invalid login or password"))); } string token = Auth.GenerateToken(); token newToken = new token() { active = true, expire = DateTime.Now + _tokenExpire, tokenValue = token, user = currentUser.First(), type = 0 }; _db.token.Add(newToken); _db.SaveChanges(); dynamic JsonObject = CustomParser.ParseTokenToJson(token, _tokenExpire.TotalSeconds); return(Ok(JsonObject)); }
// TODO: how to we chose the lengths of the temp buffers? // TODO: these methods call the slow overloads of Parsers.Custom.TryParseXXX. Do we need fast path? // TODO: these methods hardcode the format. Do we need this to be something that can be specified? public bool TryParseBoolean(out bool value) { int consumed; var unread = Unread; if (CustomParser.TryParseBoolean(unread, out value, out consumed, _symbolTable)) { Debug.Assert(consumed <= unread.Length); if (unread.Length > consumed) { _currentSegmentIndex += consumed; _index += consumed; return(true); } } Span <byte> tempSpan = stackalloc byte[15]; var copied = CopyTo(tempSpan); if (CustomParser.TryParseBoolean(tempSpan.Slice(0, copied), out value, out consumed, _symbolTable)) { Advance(consumed); return(true); } return(false); }
private static RestaurantWithAvrgRatingView ParseReaderResult(DbDataReader reader) => new RestaurantWithAvrgRatingView { Id = reader.SafeGetGuid("Id"), Name = reader["Name"].ToString(), AverageRating = CustomParser.ParseDecimal(reader["AverageRating"]), TownId = reader.SafeGetGuid("TownId") };
public IHttpActionResult GetUser() { List <user> users = _db.user.ToList(); dynamic JsonObject = CustomParser.ParseUserToJson(users); return(Ok(JsonObject)); }
/// <summary> /// Read table into list /// </summary> /// <typeparam name="T"></typeparam> /// <param name="tablePath"></param> /// <param name="customParser"></param> /// <returns>table list. null if not found</returns> public List <T> ReadList <T>(string tablePath, CustomParser customParser = null) where T : new() { var context = new ReadContext() { customParser = customParser }; return(ReadListInternal <T>(tablePath, context)); }
public IHttpActionResult GetFood() { user currentUser = Auth.GetUserFromToken(ActionContext.Request.Headers.Authorization.ToString()); List<food> foods = _db.food.Where(x => x.userId == currentUser.id).ToList(); dynamic JsonObject = CustomParser.ParseFoodToJson(foods); return Ok(JsonObject); }
public void ParseTokenToJsonTest() { string token = "5555aasdqfa54sd654a6s5d4as6d4"; double expire = 55.5; dynamic json = CustomParser.ParseTokenToJson(token, expire); Assert.That(Is.Equals(token, json.token.ToString())); Assert.That(Is.Equals(expire, Double.Parse(json.token_expire.ToString()))); }
/// <summary> /// Returns a delegate that wraps the specified, safe /// parser in order to support custom defined parsers. /// </summary> /// <param name="targetType">The target type of the parser.</param> /// <param name="parser">The original parser to wrap.</param> /// <returns> /// A safe parser delegate that supports custom parsers and falls /// back to calling the specified <paramref name="parser" />. /// </returns> private static TPF <T> InitTryParse(Type targetType, TPF <T> parser) { return(!CustomParser.TryGetParser(targetType, out TPF <T> custom) ? parser : (string s, IFormatProvider provider, out T result) => { return custom(s, provider, out result) || parser(s, provider, out result); }); }
/// <summary> /// Returns a delegate that wraps the specified parser /// in order to support custom defined parsers. /// </summary> /// <param name="targetType">The target type of the parser.</param> /// <param name="parser">The original parser to wrap.</param> /// <returns> /// A parser delegate that supports custom parsers and falls /// back to calling the specified <paramref name="parser" />. /// </returns> private static PF <T> InitParse(Type targetType, PF <T> parser) { return(!CustomParser.TryGetParser(targetType, out TPF <T> custom) ? parser : (s, provider) => { return custom(s, provider, out var result) ? result : parser(s, provider); }); }
/// <summary> /// Read table into list and return first row /// </summary> /// <typeparam name="T"></typeparam> /// <param name="tablePath"></param> /// <param name="customParser"></param> /// <returns>first row object. default value if not found.</returns> public T ReadSingle <T>(string tablePath, CustomParser customParser = null) where T : new() { var context = new ReadContext() { customParser = customParser, readMaxRows = 1 }; var list = ReadListInternal <T>(tablePath, context); return(list != null ? list[0] : default(T)); }
private static PendingOrderView ParseReaderResult(DbDataReader reader) => new PendingOrderView { Id = reader.SafeGetGuid("Id"), CreatedOn = CustomParser.ParseDateTime(reader["CreatedOn"]), Quantity = CustomParser.ParseInteger(reader["Quantity"]), Meal = new MealView { Id = reader.SafeGetGuid("MealId"), Name = reader["MealName"].ToString(), Price = CustomParser.ParseDecimal(reader["MealPrice"]) } };
/// <summary> /// Connects to a Websocket endpoint. /// </summary> /// <typeparam name="T">Type used to parsed the response message.</typeparam> /// <param name="parameters">Paremeters to send to the Websocket.</param> /// <param name="messageDelegate">Deletage to callback after receive a message.</param> /// <param name="useCustomParser">Specifies if needs to use a custom parser for the response message.</param> public WebSocket ConnectToWebSocket <T>(string parameters, MessageHandler <T> messageHandler, Action <CloseEventArgs> onClose = null, bool useCustomParser = false) { var finalEndpoint = _webSocketEndpoint + parameters; var ws = new WebSocket(finalEndpoint); ws.OnMessage += (sender, e) => { dynamic eventData = null; if (useCustomParser) { var customParser = new CustomParser(); var datum = JsonConvert.DeserializeObject <dynamic>(e.Data); if (datum is JObject jobject) { if (jobject["lastUpdateId"] != null) { eventData = customParser.GetParsedDepthPartialMessage(jobject); } else { eventData = customParser.GetParsedDepthMessage(jobject); } } } else { eventData = JsonConvert.DeserializeObject <T>(e.Data); } messageHandler(eventData); }; ws.OnClose += (sender, e) => { _openSockets.Remove(ws); onClose?.Invoke(e); }; ws.OnError += (sender, e) => { if (ws.ReadyState != WebSocketState.Open) { _openSockets.Remove(ws); } }; ws.OnOpen += (s, e) => _openSockets.Add(ws); ws.Connect(); return(ws); }
/// <summary> /// Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time. /// </summary> /// <param name="symbol">Ticker symbol.</param> /// <param name="interval">Time interval to retreive.</param> /// <param name="limit">Limit of records to retrieve.</param> /// <returns></returns> public async Task <IEnumerable <Candlestick> > GetCandleSticks(string symbol, TimeInterval interval, int limit = 500) { if (string.IsNullOrWhiteSpace(symbol)) { throw new ArgumentException("symbol cannot be empty. ", "symbol"); } var result = await _apiClient.CallAsync <dynamic>(ApiMethod.GET, EndPoints.Candlesticks, false, $"symbol={symbol.ToUpper()}&interval={interval.GetDescription()}&limit={limit}"); var parser = new CustomParser(); var parsedResult = parser.GetParsedCandlestick(result); return(parsedResult); }
/// <summary> /// Get order book for a particular symbol. /// </summary> /// <param name="symbol">Ticker symbol.</param> /// <param name="limit">Limit of records to retrieve.</param> /// <returns></returns> public async Task <OrderBook> GetOrderBook(string symbol, int limit = 100) { if (string.IsNullOrWhiteSpace(symbol)) { throw new ArgumentException("symbol cannot be empty. ", nameof(symbol)); } dynamic result = await _binanceApi.CallAsync <dynamic>(ApiMethod.GET, EndPoints.OrderBook, false, $"symbol={symbol.ToUpper()}&limit={limit}"); CustomParser parser = new CustomParser(); dynamic parsedResult = parser.GetParsedOrderBook(result); return(parsedResult); }
/// <summary> /// Get order book for a particular symbol. /// </summary> /// <param name="symbol">Ticker symbol.</param> /// <param name="limit">Limit of records to retrieve.</param> /// <returns></returns> public async Task <OrderBook> GetOrderBook(string symbol, int limit = 100) { if (string.IsNullOrWhiteSpace(symbol)) { throw new ArgumentException("symbol cannot be empty. ", "symbol"); } var result = await _apiClient.CallAsync <dynamic>(ApiMethod.GET, EndPoints.OrderBook, false, $"symbol={symbol.ToUpper()}&limit={limit}").ConfigureAwait(false); var parser = new CustomParser(); var parsedResult = parser.GetParsedOrderBook(result); return(parsedResult); }
public void ParseUserToJsonTest() { user user = new user() { id = 0, login = "******", mail = "*****@*****.**" }; dynamic json = CustomParser.ParseUserToJson(user); Assert.That(Is.Equals(user.id, int.Parse(json.id.ToString()))); Assert.That(Is.Equals(user.login, json.login.ToString())); Assert.That(Is.Equals(user.mail, json.mail.ToString())); }
public void ParseInt16Thai(string text) { ReadOnlySpan <byte> utf8Span = TestHelper.UtfEncode(text, false); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { CustomParser.TryParseInt16(utf8Span, out short value, out int bytesConsumed, 'G', TestHelper.ThaiTable); TestHelper.DoNotIgnore(value, bytesConsumed); } } } }
/// <summary> /// Connects to a Websocket endpoint. /// </summary> /// <typeparam name="T">Type used to parsed the response message.</typeparam> /// <param name="parameters">Paremeters to send to the Websocket.</param> /// <param name="messageDelegate">Deletage to callback after receive a message.</param> /// <param name="useCustomParser">Specifies if needs to use a custom parser for the response message.</param> public void ConnectToWebSocket <T>(string parameters, MessageHandler <T> messageHandler, int useCustomParser = 0) { var finalEndpoint = _webSocketEndpoint + parameters; var ws = new WebSocket(finalEndpoint); ws.OnMessage += (sender, e) => { dynamic eventData; if (useCustomParser == 0) //DEPTH { var customParser = new CustomParser(); eventData = customParser.GetParsedDepthMessage(JsonConvert.DeserializeObject <dynamic>(e.Data)); } else if (useCustomParser == 1) //TRADEAGG { //eventData = JsonConvert.DeserializeObject<T>(e.Data); var customParser = new CustomParser(); eventData = customParser.GetAggTradeMessage(JsonConvert.DeserializeObject <dynamic>(e.Data)); } else// if (useCustomParser == 2) //PARTIAL_DEPTH { var customParser = new CustomParser(); eventData = customParser.GetParsedPartialDepthMessage(JsonConvert.DeserializeObject <dynamic>(e.Data)); } messageHandler(eventData); }; ws.OnClose += (sender, e) => { _openSockets.Remove(ws); }; ws.OnError += (sender, e) => { _openSockets.Remove(ws); }; ws.Connect(); _openSockets.Add(ws); }
/// <summary> /// Connects to a Websocket endpoint. /// </summary> /// <typeparam name="T">Type used to parsed the response message.</typeparam> /// <param name="parameters">Paremeters to send to the Websocket.</param> /// <param name="messageDelegate">Deletage to callback after receive a message.</param> /// <param name="useCustomParser">Specifies if needs to use a custom parser for the response message.</param> public string ConnectToWebSocket <T>(string parameters, MessageHandler <T> messageHandler, Action <string> openHandler, bool useCustomParser = false) { string finalEndpoint = _webSocketEndpoint + parameters; WebSocket ws = new WebSocket(finalEndpoint); string sid = ws.GetHashCode().ToString(); ws.OnMessage += (sender, e) => { dynamic eventData; if (useCustomParser) { CustomParser customParser = new CustomParser(); var test = JsonConvert.DeserializeObject <dynamic>(e.Data); eventData = customParser.GetParsedDepthMessage(test); } else { eventData = JsonConvert.DeserializeObject <T>(e.Data); } messageHandler(eventData); }; ws.OnOpen += (sender, e) => { _openSockets.Add(sid, ws); //openHandler(sid); }; ws.OnClose += (sender, e) => { //throw new Exception("on close" + e.Reason + " - " + sender.ToString()); _openSockets.Remove(sid); }; ws.OnError += (sender, e) => { //throw new Exception("on error" + e.Message); _openSockets.Remove(sid); }; ws.Connect(); return(sid); }
private bool QueryParametersAreValid(Dictionary <string, StringValues> dict) { if (!QueryParametersArePresent(dict)) { return(false); } if ( CustomParser.TryParseEnum <SkiStyle>(dict["style"]) && CustomParser.TryParseInt(dict["age"]) && CustomParser.TryParseInt(dict["height"]) ) { return(true); } return(false); }
/// <summary> /// Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time. /// </summary> /// <param name="symbol">Ticker symbol.</param> /// <param name="interval">Time interval to retreive.</param> /// <param name="limit">Limit of records to retrieve.</param> /// <returns></returns> public async Task <IEnumerable <Candlestick> > GetCandleSticks(string symbol, TimeInterval interval, DateTime?startTime = null, DateTime?endTime = null, int limit = 500) { if (string.IsNullOrWhiteSpace(symbol)) { throw new ArgumentException("symbol cannot be empty. ", "symbol"); } var args = $"symbol={symbol.ToUpper()}&interval={interval.GetDescription()}" + (startTime.HasValue ? $"&startTime={startTime.Value.GetUnixTimeStamp()}" : "") + (endTime.HasValue ? $"&endTime={endTime.Value.GetUnixTimeStamp()}" : "") + $"&limit={limit}"; var result = await _apiClient.CallAsync <dynamic>(ApiMethod.GET, EndPoints.Candlesticks, false, args).ConfigureAwait(false); var parser = new CustomParser(); var parsedResult = parser.GetParsedCandlestick(result); return(parsedResult); }
/// <summary> /// Connects to a Websocket endpoint. /// </summary> /// <typeparam name="T">Type used to parsed the response message.</typeparam> /// <param name="parameters">Paremeters to send to the Websocket.</param> /// <param name="messageDelegate">Deletage to callback after receive a message.</param> /// <param name="useCustomParser">Specifies if needs to use a custom parser for the response message.</param> public void ConnectToWebSocket <T>(string parameters, MessageHandler <T> messageHandler, bool useCustomParser = false) { var finalEndpoint = _webSocketEndpoint + parameters; var ws = new PureWebSocket(finalEndpoint, new PureWebSocketOptions() { DebugMode = false,//true, SendDelay = 10, IgnoreCertErrors = true, MyReconnectStrategy = new ReconnectStrategy(2000, 4000, 20) }); ws.OnMessage += (data) => { dynamic eventData; if (useCustomParser) { var customParser = new CustomParser(); eventData = customParser.GetParsedDepthMessage(JsonConvert.DeserializeObject <dynamic>(data)); } else { eventData = JsonConvert.DeserializeObject <T>(data); } messageHandler(eventData); }; ws.OnClosed += (reason) => { _openSockets.Remove(ws); }; ws.OnError += (error) => { _openSockets.Remove(ws); }; ws.Connect(); _openSockets.Add(ws); }
public string Get() { var queryParams = QueryHelpers.ParseQuery(Request.QueryString.Value); if (QueryParametersAreValid(queryParams)) { var recommendation = calculator.CalculateRecomendation( new CalculatorParameters( CustomParser.ParseEnum <SkiStyle>(queryParams["style"]), int.Parse(queryParams["age"]), int.Parse(queryParams["height"]))); Response.Headers.Add("Access-Control-Allow-Origin", "*"); return(JsonConvert.SerializeObject(recommendation)); } Response.StatusCode = (int)HttpStatusCode.BadRequest; return(string.Empty); }
public void ParseFoodToJsonTest() { food food = new food() { id = 0, calories = 5.0, carbs = 4.0, protein = 6.6, foodName = "test", fat = 78.6, userId = 99 }; dynamic json = CustomParser.ParseFoodToJson(food); Assert.That(Is.Equals(food.calories, Double.Parse(json.calories.ToString()))); Assert.That(Is.Equals(food.carbs, Double.Parse(json.carbs.ToString()))); Assert.That(Is.Equals(food.protein, Double.Parse(json.protein.ToString()))); Assert.That(Is.Equals(food.foodName, json.foodName.ToString())); Assert.That(Is.Equals(food.fat, Double.Parse(json.fat.ToString()))); }
private static Value GetValue(ref JsonReader jsonReader) { int consumed; var value = new Value { Type = MapValueType(jsonReader.ValueType) }; switch (value.Type) { case Value.ValueType.String: value.StringValue = ReadString(ref jsonReader); break; case Value.ValueType.Number: CustomParser.TryParseDecimal(jsonReader.Value, out decimal num, out consumed, jsonReader.SymbolTable); value.NumberValue = Convert.ToDouble(num); break; case Value.ValueType.True: break; case Value.ValueType.False: break; case Value.ValueType.Null: break; case Value.ValueType.Object: value.ObjectValue = ReadObject(ref jsonReader); break; case Value.ValueType.Array: value.ArrayValue = ReadArray(ref jsonReader); break; default: throw new ArgumentOutOfRangeException(); } return(value); }
public unsafe void DecimalPositiveTests(string text, int length, decimal expectedValue, int expectedConsumed) { byte[] byteBuffer = Text.Encoding.UTF8.GetBytes(text); ReadOnlySpan <byte> byteSpan = new ReadOnlySpan <byte>(byteBuffer); char[] charBuffer = text.ToCharArray(); ReadOnlySpan <char> charSpan = new ReadOnlySpan <char>(charBuffer); bool result; result = CustomParser.TryParseDecimal(byteSpan, out decimal actualValue, out int actualConsumed, SymbolTable.InvariantUtf8); Assert.True(result); Assert.Equal(expectedValue, actualValue); Assert.Equal(expectedConsumed, actualConsumed); result = Utf8Parser.TryParse(byteSpan, out actualValue, out actualConsumed); Assert.True(result); Assert.Equal(expectedValue, actualValue); Assert.Equal(expectedConsumed, actualConsumed); ReadOnlySpan <byte> utf16ByteSpan = charSpan.AsBytes(); result = CustomParser.TryParseDecimal(utf16ByteSpan, out actualValue, out actualConsumed, SymbolTable.InvariantUtf16); Assert.True(result); Assert.Equal(expectedValue, actualValue); Assert.Equal(expectedConsumed, actualConsumed / 2); result = Utf16Parser.TryParseDecimal(charSpan, out actualValue); Assert.True(result); Assert.Equal(expectedValue, actualValue); result = Utf16Parser.TryParseDecimal(charSpan, out actualValue, out actualConsumed); Assert.True(result); Assert.Equal(expectedValue, actualValue); Assert.Equal(expectedConsumed, actualConsumed); }
/// <summary> /// Connects to a Websocket endpoint. /// </summary> /// <typeparam name="T">Type used to parsed the response message.</typeparam> /// <param name="parameters">Paremeters to send to the Websocket.</param> /// <param name="messageDelegate">Deletage to callback after receive a message.</param> /// <param name="useCustomParser">Specifies if needs to use a custom parser for the response message.</param> public WebSocket ConnectToWebSocket <T>(string parameters, MessageHandler <T> messageHandler, bool useCustomParser = false) { var finalEndpoint = _webSocketEndpoint + parameters; var ws = new WebSocket(finalEndpoint); ws.OnMessage += (sender, e) => { dynamic eventData; if (useCustomParser) { var customParser = new CustomParser(); eventData = customParser.GetParsedDepthMessage(JsonConvert.DeserializeObject <dynamic>(e.Data)); } else { eventData = JsonConvert.DeserializeObject <T>(e.Data); } messageHandler(eventData); }; ws.OnClose += (sender, e) => { _openSockets.Remove(ws); }; ws.OnError += (sender, e) => { _openSockets.Remove(ws); }; ws.Connect(); _openSockets.Add(ws); return(ws); }
public static void CustomParserTestsInitialize(TestContext testContext) { customParser = new CustomParser(); }
public void Init() { parser = new CustomParser(); }
public void SetUp() { _config = new CommandLineInterpreterConfiguration(); _config.Command("first", s => new TestCommand()) .Description("Description of the first commmand."); _config .Command("second", s => new TestCommand()) .Description("The second command is a command with a number of parameters.") .Positional<string>("dateofthing", (command, s) => { }) .Description("The date the thing should have.") .Positional<string>("numberofthing", (command, s) => { }) .Description("The number of things that should be."); _config .Command("third", s => new TestCommand()) .Description("The third command has a number of options but no parameters.") .Option("on", (command, b) => { }) .Description("A simple option with no argument.") .Option<string, int>("fiddly", (command, s, n) => { }) .Alias("f") .Description("An option with two arguments. The arguments need to be described in the text."); _config .Command("fourth", s => new TestCommand()) .Description("The fourth command is really complicated with a number of parameters and also options. This is the sort of command that needs lots of text.") .Positional<string>("date", (command, s) => { }) .Description("The date the complicated nonsense should be forgotten.") .Positional<string>("crpyticnum", (command, s) => { }) .Description("The amount of nonsense the user needs to forget.") .Option("ignore", (command, b) => { }) .Description("Use this option to consign this command to history, where it belongs.") .Option<string, int>("more", (command, s, n) => { }) .Description("Even more."); _config .Command("desc", s => new TestCommand()) .Description( @"Descriptions can contain embedded line breaks --> <-- like that one. These should be respected in the formatting. (This is meant to look a bit odd. Also, you should be aware that the deliberate line break is the only one in this text.)") .Positional<string>("pos", (command, s) => { }) .Description(@"A parameter with a line break.") .Option("lb", (command, b) => { }) .Description("Another\nbreak."); _config .Command("exp", s => new TestCommand()) .Description(@"Command with a positional and options configured using a Linq Expression, not a lambda.") .Positional("pos", command => command.StringProp) .Description(@"A positional configured with an expression.") .Option("B", command => command.BoolProp) .Description("A boolean option configured with an expression.") .Option("I", command => command.IntProp) .Description("A boolean option configured with an expression."); _customParser = new CustomParser(); _consoleOutInterface = new ConsoleInterfaceForTesting(); _console = new ConsoleAdapter(_consoleOutInterface); _console.WriteLine(RulerFormatter.MakeRuler(40)); }