/// <summary> /// Gets the property <typeparamref name="T">value</typeparamref> by the <paramref name="parameter">property name</paramref>. /// </summary> /// <param name="parameter">The stream parameter name.</param> /// <param name="convert"></param> /// <param name="extractResult">The manual extract result function.</param> /// <returns>Returns property <typeparamref name="T">value</typeparamref> of specified stream <paramref name="parameter">property name</paramref>.</returns> protected T Get <T>(string parameter, ParseDelegate <T> convert, Func <string, string> extractResult = null) { if (convert == null) { throw new ArgumentNullException(nameof(convert)); } return(convert(Get(parameter, extractResult), out var parsedValue) ? parsedValue : default(T)); }
public void Initialize() { var ambrellaType = typeof (AmbarellaBrowser); _instance = Activator.CreateInstance<AmbarellaBrowser>(); (_instance as IGeneralBrowser).Initialize(null, null); var method = ambrellaType.GetMethod("Parse", BindingFlags.Instance | BindingFlags.NonPublic); _parseDelegate = (ParseDelegate) method.CreateDelegate(typeof (ParseDelegate), _instance); }
public void Initialize() { _instance = Activator.CreateInstance<GoProMediaBrowser>(); (_instance as IGeneralBrowser).Initialize(null, null); var browserType = _instance.GetType(); var method=browserType.GetMethod("Parse", BindingFlags.NonPublic | BindingFlags.Instance); _parseDelegate= (ParseDelegate)method.CreateDelegate(typeof(ParseDelegate), _instance); }
private IParseResult <T> StartRuleHelper <T>(Cursor cursor, ParseDelegate <T> startRule, string ruleName) { var result = startRule(ref cursor); if (result == null) { throw ExceptionHelper(cursor, state => "Failed to parse '" + ruleName + "'."); } return(result); }
public void Initialize() { _instance = Activator.CreateInstance <GoProMediaBrowser>(); (_instance as IGeneralBrowser).Initialize(null, null); var browserType = _instance.GetType(); var method = browserType.GetMethod("Parse", BindingFlags.NonPublic | BindingFlags.Instance); _parseDelegate = (ParseDelegate)method.CreateDelegate(typeof(ParseDelegate), _instance); }
public static T Parse <T>(string s) { ParseDelegate <T> parse = ParseDelegateStore <T> .Parse; if (parse == null) { parse = (ParseDelegate <T>)Delegate.CreateDelegate(typeof(ParseDelegate <T>), typeof(T), "Parse", true); ParseDelegateStore <T> .Parse = parse; } return(parse(s)); }
public void Initialize() { var ambrellaType = typeof(AmbarellaBrowser); _instance = Activator.CreateInstance <AmbarellaBrowser>(); (_instance as IGeneralBrowser).Initialize(null, null); var method = ambrellaType.GetMethod("Parse", BindingFlags.Instance | BindingFlags.NonPublic); _parseDelegate = (ParseDelegate)method.CreateDelegate(typeof(ParseDelegate), _instance); }
internal Oper(AssocType assoc, TokenType type, int level, ParseDelegate parseFunc = null, CombineDelegate combineFunc = null) : this(assoc, type, level) { if (parseFunc != null) { Parse = parseFunc; } if (combineFunc != null) { Combine = combineFunc; } }
public static T Read(string text, ParseDelegate func) { while (true) { Console.Write($"{text}: "); if (func(Console.ReadLine(), out T value)) { return(value); } } }
private static T?Parse <T>(string input, ParseDelegate <T> DelegateTheParse) { if (string.IsNullOrEmpty(input)) { return(null); } else { return(DelegateTheParse(input)); } }
private void TryParse <T>(ParseDelegate <T> parser, T expected, string formatString, char standardFormat) where T : unmanaged, IEquatable <T>, IFormattable, IConvertible { // Note that there is no support in Utf8Parser for localized separators string text = expected.ToString(formatString, CultureInfo.InvariantCulture); ReadOnlySequence <byte> bytes = BufferFactory.CreateUtf8(text); BufferReader <byte> reader = new BufferReader <byte>(bytes); Assert.True(parser(ref reader, out T value, standardFormat)); Assert.Equal(text, value.ToString(formatString, CultureInfo.InvariantCulture)); }
/// <summary> /// 2項演算子に関する構文解析 /// </summary> /// <returns>構文木</returns> /// <param name="childParser">優先順位の高い構文解析関数</param> /// <param name="operators">演算子</param> IExpression ParseBinary(ParseDelegate childParser, params string[] operators) { var node = childParser(); Token operatorToken; while ((operatorToken = PeekToken()).IsOperator(operators)) { NextToken(); node = new BinaryExpression(operatorToken.Text, node, childParser()); } return(node); }
public async Task<MiddlemanRequest> ParseAsync(InboundConnection conn, Stream stream) { var del = new ParseDelegate(); var parser = new HttpParser(del); int read; var readTotal = 0; var buffer = new byte[8192]; Log.Debug("{0}: RequestParser starting", conn.RemoteEndPoint); var requestString = ""; while (stream != null && (read = await stream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0) { requestString += Encoding.ASCII.GetString(buffer.Where(x => x != 0).ToArray(), 0, read); readTotal += read; if (parser.Execute(new ArraySegment<byte>(buffer, 0, read)) != read) throw new FormatException("Parse error in request"); if (del.HeaderComplete) break; } conn.MustClose = del.Request.Headers.AllKeys.Any(h => h.Equals("Connection", StringComparison.InvariantCultureIgnoreCase) && del.Request.Headers[h].Equals("Close", StringComparison.InvariantCultureIgnoreCase)); Log.Debug("{0}: RequestParser read enough ({1} bytes)", conn.RemoteEndPoint, readTotal); Log.Info("ORIGINAL REQUEST: " + Environment.NewLine + requestString + Environment.NewLine); if (readTotal == 0) return null; if (!del.HeaderComplete) throw new FormatException("Parse error in request"); var request = del.Request; request.ProtocolVersion = new Version(parser.MajorVersion, parser.MinorVersion); conn.RequestVersion = request.ProtocolVersion; var cl = request.ContentLength; if (cl > 0 && stream != null) { request.RequestBody = del.RequestBodyStart.Count > 0 ? new MaxReadStream(new StartAvailableStream(del.RequestBodyStart, stream), cl) : new MaxReadStream(stream, cl); } return request; }
static ExpressionParser() { foreach (Assembly telerikAssembly in AppDomain.CurrentDomain.GetAssemblies()) { Type expressionParserType = telerikAssembly.GetType("Telerik.Data.Expressions.ExpressionParser"); if (expressionParserType != null) { MethodInfo parseMethod = expressionParserType.GetMethod("Parse"); parse = (ParseDelegate)Delegate.CreateDelegate(typeof(ParseDelegate), parseMethod); return; } } }
private DxfCodePair GetCodePair <T>(int code, string s, ParseDelegate <T> parser, NumberStyles style, Creator <T> creator) { T result; if (parser(s, style, CultureInfo.InvariantCulture, out result)) { return(creator(code, result)); } else { throw new DxfReadException("Unsupported value for code", _lineNumber); } }
/// <summary> /// The parse ping. /// </summary> /// <param name="buffer"> The buffer.</param> /// <param name="offset"> The offset.</param> /// <param name="count">The count.</param> /// <returns>Number of bytes parsed.</returns> private int ParsePing(byte[] buffer, int offset, int count) { int num = this.pingResponseBuffer.Read(buffer, offset, count); if (this.pingResponseBuffer.Complete) { int serverTime = BitConverter.ToInt32(buffer, 0); int clienttime = BitConverter.ToInt32(buffer, 4); this.tcpListener.OnPingResponse(serverTime, clienttime); this.parseFunction = new ParseDelegate(this.ParseMagicNumber); } return(num); }
/// <summary> /// The parse header. /// </summary> /// <param name="buffer"> The buffer.</param> /// <param name="offset">The offset.</param> /// <param name="count">The count.</param> /// <returns>Number of bytes parsed.</returns> private int ParseHeader(byte[] buffer, int offset, int count) { int num = this.headerBuffer.Read(buffer, offset, count); if (this.headerBuffer.Complete) { byte[] buffer2 = this.headerBuffer.Buffer; int num2 = (((buffer2[1] << 0x18) | (buffer2[2] << 0x10)) | (buffer2[3] << 8)) | buffer2[4]; this.messageBuffer = new ByteBuffer(num2 - 7); this.parseFunction = new ParseDelegate(this.ParseMessage); } return(num); }
/// <summary> /// The parse message. /// </summary> /// <param name="buffer"> The buffer.</param> /// <param name="offset"> The offset.</param> /// <param name="count">The count.</param> /// <returns>Number of bytes parsed.</returns> private int ParseMessage(byte[] buffer, int offset, int count) { int num = this.messageBuffer.Read(buffer, offset, count); if (this.messageBuffer.Complete) { byte channelId = this.headerBuffer.Buffer[5]; MessageReliablity reliablity = (this.headerBuffer.Buffer[6] == 0) ? MessageReliablity.UnReliable : MessageReliablity.Reliable; this.tcpListener.OnReceive(this.messageBuffer.Buffer, channelId, reliablity); this.parseFunction = new ParseDelegate(this.ParseMagicNumber); } return(num); }
public static T?[] ToNullable <T>(this string[] values, ParseDelegate <T> parseMethod) where T : struct { IEnumerable <T?> cos = values.Select(s => { T result; if (parseMethod(s, out result)) { return((T?)result); } return(null); }); return(cos.ToArray()); }
public async Task<SwitchboardRequest> ParseAsync(InboundConnection conn, Stream stream) { var del = new ParseDelegate(); var parser = new HttpParser(del); int read; int readTotal = 0; byte[] buffer = new byte[8192]; Debug.WriteLine(string.Format("{0}: RequestParser starting", conn.RemoteEndPoint)); while ((read = await stream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0) { readTotal += read; if (parser.Execute(new ArraySegment<byte>(buffer, 0, read)) != read) throw new FormatException("Parse error in request"); if (del.headerComplete) break; } Debug.WriteLine(string.Format("{0}: RequestParser read enough ({1} bytes)", conn.RemoteEndPoint, readTotal)); if (readTotal == 0) return null; if (!del.headerComplete) throw new FormatException("Parse error in request"); var request = del.request; request.ProtocolVersion = new Version(parser.MajorVersion, parser.MinorVersion); int cl = request.ContentLength; if (cl > 0) { if (del.requestBodyStart.Count > 0) { request.RequestBody = new MaxReadStream(new StartAvailableStream(del.requestBodyStart, stream), cl); } else { request.RequestBody = new MaxReadStream(stream, cl); } } return request; }
/// <summary> /// The parse message. /// </summary> /// <param name="buffer"> The buffer.</param> /// <param name="offset"> The offset.</param> /// <param name="count"> The count.</param> /// <returns> Number of bytes parsed.</returns> private int ParseMessage(byte[] buffer, int offset, int count) { int num = this.messageBuffer.Read(buffer, offset, count); if (this.messageBuffer.Complete) { Action <byte[], SendParameters> onDataReceived = this.OnDataReceived; if (onDataReceived != null) { onDataReceived(this.messageBuffer.Buffer, this.sendParameters); } this.parseFunction = new ParseDelegate(this.ParseMagicNumber); } return(num); }
/// <summary> /// The try parse. /// </summary> /// <param name="value"> /// The value. /// </param> /// <param name="parse"> /// The parse. /// </param> /// <param name="defaultValue"> /// The default value. /// </param> /// <typeparam name="T"> /// </typeparam> /// <returns> /// The <see cref="Type"/>. /// </returns> private static T TryParse <T>(this string value, ParseDelegate <T> parse, T defaultValue) where T : struct { T result; // if ( string.IsNullOrEmpty( value ) ) // return defaultValue; if (!parse(value, out result)) { return(defaultValue); } else { return(result); } }
private static T TryParse <T>(this string value, ParseDelegate <T> parse, T defaultValue) where T : struct { T result; try { result = parse(value); } catch (Exception) { result = defaultValue; } return(result); }
private IParseResult <T> ParseHelper <T>(ref Cursor cursor, ParseDelegate <T> wrappedCode) { var startCursor = cursor; var result = wrappedCode(ref cursor); if (result == null) { cursor = startCursor; return(null); } else { cursor = cursor.WithMutability(false); return(result); } }
/// <summary> /// The parse ping. /// </summary> /// <param name="buffer"> The buffer.</param> /// <param name="offset"> The offset.</param> /// <param name="count">The count.</param> /// <returns>Number of bytes parsed.</returns> private int ParsePing(byte[] buffer, int offset, int count) { int num = this.pingResponseBuffer.Read(buffer, offset, count); if (this.pingResponseBuffer.Complete) { PingResponse response = new PingResponse(this.pingResponseBuffer.Buffer); Action <PingResponse> onPingResponse = this.OnPingResponse; if (onPingResponse != null) { onPingResponse(response); } this.parseFunction = new ParseDelegate(this.ParseMagicNumber); } return(num); }
private static T?TryParse <T>(this string value, ParseDelegate <T> parse) where T : struct { if (string.IsNullOrEmpty(value)) { return(null); } T result; if (parse(value, out result)) { return(result); } return(null); }
private static bool GetCustomProperty<T>(AssetInfo assetInfo, string key, ParseDelegate<T> conversion, out T value) { value = default(T); if (assetInfo.details == null) return false; var existing = assetInfo.details.FirstOrDefault(x => x.name == key); if (existing != null) { return conversion(existing.value, out value); } else { return false; } }
public DefaultTStringConverter() { Type type = typeof(T); if (type == typeof(string)) { isString = true; } else if (type.IsEnum) { isEnum = true; } else { isEnum = false; parse = Reflection.GetStaticDelegate <ParseDelegate <T>, T>("Parse"); } }
/// <summary> /// Converts the string representation of a number to its <see cref="Rational{T}"/> equivalent. /// </summary> /// <param name="value">The value to convert.</param> /// <returns> /// The <see cref="Rational{T}"/>. /// </returns> public static Rational <T> Parse(string value) { if (string.IsNullOrEmpty(value)) { return(Empty); } if (parser == null) { parser = BuildParser(); } string[] parts = value.Split(DelimSet, 2, StringSplitOptions.RemoveEmptyEntries); T numerator = parser(parts[0]); T denominator = parts.Length > 1 ? parser(parts[1]) : default(T); return(new Rational <T>(numerator, denominator)); }
/// <summary> /// Execute parsing method checking research deep. /// </summary> private static bool Parse(ParseDelegate action, SyntacticState state, SyntacticItem[] args) { state.Deep++; #if DEBUG Debug.WriteLine(String.Empty); Debug.WriteLine(state.GetOuterDebug()); SyntacticItem debugItem = (SyntacticItem)action.Target; Debug.WriteLine("[{0}] ({1})", debugItem.Key, state.Deep); string debugMethod = action.Method.Name; debugMethod = debugMethod .Split( new[] { "Parse", "Internal", "<", ">" }, StringSplitOptions.RemoveEmptyEntries) .First() .ToUpperInvariant(); Debug.Write(debugMethod); Debug.Write(" ="); foreach (var arg in args.Where(arg => arg != null)) { Debug.Write(" | "); Debug.Write(arg.Key); } Debug.WriteLine(String.Empty); #endif if (state.Deep >= c_maxResearchDeep) { throw new InvalidOperationException( String.Format("Maximum research deep {0} has been reached.", c_maxResearchDeep)); } bool parsed = action.Invoke(state, args); state.Deep--; return(parsed); }
public static ParseStringDelegate GetParseFn <T>(string parseMethod) { // Get the static Parse(string) method on the type supplied var parseMethodInfo = typeof(T).GetStaticMethod(parseMethod, new[] { typeof(string) }); if (parseMethodInfo == null) { return(null); } ParseDelegate parseDelegate = null; try { if (parseMethodInfo.ReturnType != typeof(T)) { parseDelegate = (ParseDelegate)parseMethodInfo.MakeDelegate(typeof(ParseDelegate), false); } if (parseDelegate == null) { // Try wrapping strongly-typed return with wrapper fn. var typedParseDelegate = (Func <string, T>)parseMethodInfo.MakeDelegate(typeof(Func <string, T>)); parseDelegate = x => typedParseDelegate(x); } } catch (ArgumentException) { Tracer.Instance.WriteDebug("Nonstandard Parse method on type {0}", typeof(T)); } if (parseDelegate != null) { return(value => parseDelegate(value.FromCsvField())); } return(null); }
/// <summary> /// The parse magic number. /// </summary> /// <param name="buffer"> The buffer.</param> /// <param name="offset"> The offset.</param> /// <param name="count">The count.</param> /// <returns> The parsed magic number.</returns> private int ParseMagicNumber(byte[] buffer, int offset, int count) { switch (buffer[offset]) { case 240: this.pingResponseBuffer = new ByteBuffer(PingResponse.SizeInBytes); this.parseFunction = new ParseDelegate(this.ParsePing); break; case 0xfb: this.headerBuffer = new ByteBuffer(7); this.parseFunction = new ParseDelegate(this.ParseHeader); return(0); default: if (log.IsDebugEnabled) { log.DebugFormat("Received invalid data: {0}", new object[] { BitConverter.ToString(buffer, offset) }); } break; } return(1); }
/// <summary> /// Tries to parse the expected value for a data type then uses it as a comparison. /// </summary> /// <typeparam name="T">The data type to try</typeparam> /// <param name="expected">The expected.</param> /// <param name="actual">The actual.</param> /// <param name="parseDelegate">The parse delegate.</param> /// <param name="comparisonFunc">The comparison function.</param> /// <param name="comparisonResult">The result of the comparison.</param> /// <returns><c>true</c> if the data type matches, <c>false</c> otherwise.</returns> private static bool TryCompare <T>( string expected, string actual, ParseDelegate <T> parseDelegate, Func <T, T, bool> comparisonFunc, out bool comparisonResult) { T typedExpected; if (parseDelegate(expected, out typedExpected)) { T parseActual; var typedActual = parseDelegate(actual, out parseActual) ? parseActual : default(T); try { comparisonResult = comparisonFunc(typedExpected, typedActual); return(true); } catch (NotSupportedException) { } } comparisonResult = false; return(false); }
/// <summary> /// Supports a parse method for nullable types. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="expression"></param> /// <param name="parseMethod"></param> /// <returns></returns> public static Nullable <T> NullableParse <T>(string expression, ParseDelegate <T> parseMethod) where T : struct { if (string.IsNullOrEmpty(expression)) { return(null); } else { try { MethodInfo mi = typeof(T).GetMethod("Parse", new[] { typeof(string) }); if (mi != null) { var del = (ParseDelegate <T>)Delegate.CreateDelegate(typeof(ParseDelegate <T>), mi); return(del(expression)); } else { throw new ApplicationException("Type does not support the Parse method."); } } catch (Exception ex) { return(null); } } }
public async Task<SwitchboardResponse> ParseAsync(Stream stream) { var del = new ParseDelegate(); var parser = new HttpResponseParser(del); int read; byte[] buffer = new byte[8192]; while ((read = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0) { parser.Execute(buffer, 0, read); if (del.headerComplete) break; } if (!del.headerComplete) throw new FormatException("Parse error in response"); var response = del.response; int cl = response.ContentLength; if (cl > 0) { if (del.responseBodyStart.Count > 0) { response.ResponseBody = new MaxReadStream(new StartAvailableStream(del.responseBodyStart, stream), cl); } else { response.ResponseBody = new MaxReadStream(stream, cl); } } else if (response.Headers["Transfer-Encoding"] == "chunked") { if (response.Headers["Connection"] == "close") { if (del.responseBodyStart.Count > 0) { response.ResponseBody = new StartAvailableStream(del.responseBodyStart, stream); } else { response.ResponseBody = stream; } } else { if (del.responseBodyStart.Count > 0) { response.ResponseBody = new ChunkedStream(new StartAvailableStream(del.responseBodyStart, stream)); } else { response.ResponseBody = new ChunkedStream(stream); } } } return response; }
/// <summary> /// Execute parsing method checking research deep. /// </summary> private static bool Parse(ParseDelegate action, SyntacticState state, SyntacticItem[] args) { state.Deep++; #if DEBUG Debug.WriteLine(String.Empty); Debug.WriteLine(state.GetOuterDebug()); SyntacticItem debugItem = (SyntacticItem)action.Target; Debug.WriteLine("[{0}] ({1})", debugItem.Key, state.Deep); string debugMethod = action.Method.Name; debugMethod = debugMethod .Split( new[] { "Parse", "Internal", "<", ">" }, StringSplitOptions.RemoveEmptyEntries) .First() .ToUpperInvariant(); Debug.Write(debugMethod); Debug.Write(" ="); foreach (var arg in args.Where(arg => arg != null)) { Debug.Write(" | "); Debug.Write(arg.Key); } Debug.WriteLine(String.Empty); #endif if (state.Deep >= c_maxResearchDeep) throw new InvalidOperationException( String.Format("Maximum research deep {0} has been reached.", c_maxResearchDeep)); bool parsed = action.Invoke(state, args); state.Deep--; return parsed; }
public void Updated() { implementation = null; }
public Item(string name, string format, ParseDelegate parse, ConvertDelegate toBase, ConvertDelegate toUnit) { Name = name; Format = format; _parse = parse; _toBase = toBase; _toUnit = toUnit; }
public async Task<MiddlemanResponse> ParseAsync(Stream stream) { var del = new ParseDelegate(); var parser = new HttpResponseParser(del); int read; var buffer = new byte[8192]; var responseString = ""; while ((read = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0) { responseString += Encoding.ASCII.GetString(buffer.Where(x => x != 0).ToArray(), 0, read); parser.Execute(buffer, 0, read); if (del.HeaderComplete) break; } if (responseString.ToLowerInvariant().Contains("content-type: image/")) { responseString = responseString.Substring(0, responseString.IndexOf(Environment.NewLine + Environment.NewLine)).Trim(); } Log.Info("RESPONSE FROM SERVER: " + Environment.NewLine + responseString.Trim() + Environment.NewLine); if (!del.HeaderComplete) { throw new FormatException("Parse error in response"); } var response = del.Response; var cl = response.ContentLength; if (cl > 0) { if (del.ResponseBodyStart.Count > 0) { response.ResponseBody = new MaxReadStream(new StartAvailableStream(del.ResponseBodyStart, stream), cl); } else { response.ResponseBody = new MaxReadStream(stream, cl); } } //else if ((int)response.StatusCode == 100) //{ // throw new Exception(); //} else if (response.Headers["Transfer-Encoding"] == "chunked") { if (response.Headers["Connection"] == "close") { response.ResponseBody = del.ResponseBodyStart.Count > 0 ? new StartAvailableStream(del.ResponseBodyStart, stream) : stream; } else { response.ResponseBody = del.ResponseBodyStart.Count > 0 ? new ChunkedStream(new StartAvailableStream(del.ResponseBodyStart, stream)) : new ChunkedStream(stream); } } return response; }
public static DateTime[] ParseDateTimeRange(string date, ParseDelegate pd) { if (string.IsNullOrEmpty(date)) { return null; } int hypPos = date.IndexOf('-'); var range = new DateTime[2]; range[1] = pd(date.Substring(hypPos + 1)); if (hypPos == - 1) { range[0] = range[1]; } else if (hypPos != 0) { range[0] = pd(date.Substring(0, (hypPos) - (0))); } return range; }
public static DateTime[] ParseDateTimeRange(String date, ParseDelegate pd) { if (date == null || date.Length == 0) return null; int hypPos = date.IndexOf((Char) '-'); DateTime[] range = new DateTime[2]; range[1] = pd(date.Substring(hypPos + 1)); if (hypPos == - 1) range[0] = range[1]; else if (hypPos != 0) range[0] = pd(date.Substring(0, (hypPos) - (0))); return range; }