public void TestMethodParsePredicate() { var predicateUtils = new PredicateUtils(); var filter = predicateUtils.ParsePredicate <PeopleFilter>("Age = 42"); Assert.AreEqual(filter.AgeFilter, 42); }
public void TestMethodPredicate() { var peopleList = new List <People>() { new People { Name = "Name1", Age = 41, Height = 1.1 }, new People { Name = "Name2", Age = 42, Height = 1.2 }, new People { Name = "Name3", Age = 43, Height = 1.3 } }; var predicate = new PredicateUtils(); var filter = new PeopleFilter { AgeFilter = 42 }; var result = predicate.FilterList(peopleList, filter); Assert.IsTrue(result.Any()); Assert.AreEqual(result.First().Name, "Name2"); filter = new PeopleFilter { Name = "Name3" }; result = predicate.FilterList(peopleList, filter); Assert.IsTrue(result.Any()); Assert.AreEqual(result.First().Age, 43); }
public void TestMethodGeneratePredicate1() { var predicate = new PredicateUtils(); var filterClass = new PeopleFilter { Height = 182 }; var filter = predicate.GeneratePredicate(filterClass); Assert.AreEqual(filter, "Height=182"); }
private void StabilizeClientState(bool forWrite = false) { lock (this.client.SyncLock) { if (this.readBytesLeft > 0) { this.client.WriteStream.Flush(); if (this.tempBuffer == null) { this.tempBuffer = new byte[64 * 1024]; } while (this.readBytesLeft > 0) { this.readBytesLeft -= this.client.ReadStream.Read(this.tempBuffer, 0, Math.Min(this.readBytesLeft, this.tempBuffer.Length)); } this.client.ReadReady(); } } if (!forWrite) { bool wait = false; if (this.writeResponsesQueue.TaskState == TaskState.Running) { this.writeResponsesQueue.Enqueue(delegate { this.writeResponsesQueue.Stop(); }); this.client.WriteStream.Flush(); wait = true; } if (wait) { this.writeResponsesQueue.WaitForAnyTaskState(PredicateUtils.ObjectNotEquals(TaskState.Running)); this.writeResponsesQueue.Reset(); } } if (this.errorResponse != null) { var localErrorResponse = this.errorResponse; this.errorResponse = null; localErrorResponse.ProcessError(); } }
public StandardTempIdentityFileService(IFile file, TempIdentityFileServiceType serviceType) { IDirectory dir; var buffer = new StringBuilder(file.Address.Uri.Length * 2); this.file = file; this.serviceType = serviceType; buffer.Append("$TMP_ID_"); buffer.Append(file.Name).Append('_'); if (serviceType.TempFileSystem != null) { buffer.Append(TextConversion.ToBase32String(new MD5CryptoServiceProvider().ComputeHash(Encoding.ASCII.GetBytes(file.Address.Uri))).Trim('=')); buffer.Append('_'); } string s; if (serviceType.UniqueIdentifier.IndexOf(PredicateUtils.Not <char>(Char.IsLetterOrDigit)) >= 0) { s = TextConversion.ToBase32String(Encoding.ASCII.GetBytes(serviceType.UniqueIdentifier)).Trim('='); } else { s = serviceType.UniqueIdentifier; } buffer.Append(s); if (serviceType.TempFileSystem == null) { dir = file.ParentDirectory; this.tempFile = dir.ResolveFile(buffer.ToString()); } else { var tempFileSystem = serviceType.TempFileSystem; dir = tempFileSystem.ResolveDirectory("/VFSTempIdentity"); dir.Create(); this.tempFile = dir.ResolveFile(buffer.ToString()); } }
public override void VisitLikeExpression(LikeExpression likeExpression) { likeExpression.Left.Accept(this); var leftExpression = PopStack(); var visitResult = VisitInternal(likeExpression.Right); Expression expression = null; if (visitResult.StartsWith && visitResult.EndsWith) { expression = PredicateUtils.CallContains( leftExpression, visitResult.Expression, _visitorMetadata.OperationsProvider); } //Starts with else if (visitResult.StartsWith) { expression = PredicateUtils.CallStartsWith( leftExpression, visitResult.Expression, _visitorMetadata.OperationsProvider); } //Ends with else if (visitResult.EndsWith) { expression = PredicateUtils.CallEndsWith( leftExpression, visitResult.Expression, _visitorMetadata.OperationsProvider); } else { expression = PredicateUtils.CreateComparisonExpression( leftExpression, visitResult.Expression, BooleanComparisonType.Equals, _visitorMetadata.OperationsProvider); } if (likeExpression.Not) { expression = Expression.Not(expression); } AddExpressionToStack(expression); }
public virtual bool WaitForFinish(TimeSpan timeout) { lock (this.TaskStateLock) { TaskState taskState = this.TaskState; if (taskState == TaskState.Unknown || taskState == TaskState.NotStarted || taskState == TaskState.Stopped) { return(true); } } return(this.WaitForAnyTaskState(timeout, PredicateUtils.ObjectEqualsAny(TaskState.Finished, TaskState.Stopped))); }
public override void VisitBooleanComparisonExpression(BooleanComparisonExpression booleanComparisonExpression) { booleanComparisonExpression.Left.Accept(this); booleanComparisonExpression.Right.Accept(this); var rightExpression = PopStack(); var leftExpression = PopStack(); var expression = PredicateUtils.CreateComparisonExpression( leftExpression, rightExpression, booleanComparisonExpression.Type, _visitorMetadata.OperationsProvider); AddExpressionToStack(expression); }
/// <summary> /// Initializes a new instance of the <see cref="SparseProbabilisticTransition"/> class. /// </summary> /// <param name="nIndex">The number of indices in the transition.</param> /// <param name="transitions">A list of transitions that are stored in this <see cref="SparseProbabilisticTransition"/>.</param> /// <remarks> /// <para> /// Transitions from and to indices larger than or eqaul to <paramref name="nIndex"/> will be ignored /// as well as transitions with indices less than zero. /// </para> /// <para> /// The given <paramref name="transitions"/> are not required to be ordered. /// </para> /// </remarks> public SparseProbabilisticTransition(int nIndex, IEnumerable <Tuple <int, int, double> > transitions) { int[] idcs = new int[nIndex]; Predicate <int> pred = PredicateUtils.RangePredicate(0x00, nIndex - 0x01); List <Tuple <int, int, double> > ts = transitions.Where(t => t.Item3 > 0.0d && pred(t.Item1) && pred(t.Item2)).OrderBy(TransitionComparator.Instance).ToList(); int i = 0x00, j = 0x00, k = ts.Count; Arrow[] arws = new Arrow[k]; idcs [nIndex - 0x01] = k; foreach (Tuple <int, int, double> t in ts) { k = t.Item1; arws [i++] = new Arrow(t); while (j < k) { idcs [j++] = i; } } this.indices = idcs; this.arrows = arws; }
/// <summary> /// Reads a string form the <see cref="TextReader"/> until a space is encountered /// </summary> /// <param name="reader">The reader to read from</param> /// <param name="maximumLength">The maximum number of characters to read</param> /// <param name="overflow">A bool that will return True if the maximumLength was reached before a full word was read</param> /// <returns>The string that was read</returns> public static string ReadWord(this TextReader reader, int maximumLength, out bool overflow) { return(reader.ReadWhile(PredicateUtils.ObjectNotEquals(' '), maximumLength, out overflow)); }
public virtual void Run() { Play(); TaskUtils.WaitForAnyTaskState(this, PredicateUtils.ObjectEqualsAny(TaskState.Finished, TaskState.Stopped)); }
public override IEnumerable <Pair <string, NodeType> > List(string uri, string regex) { Predicate <string> acceptName = null; using (this.AcquireCommandContext(false)) { try { try { if (!String.IsNullOrEmpty(regex)) { SendCommand(DefaultTryCount, @"list -regex=""{0}"" ""{1}""", TextConversion.ToEscapedHexString(regex), uri).ProcessError(); } else { SendCommand(DefaultTryCount, @"list ""{0}""", uri).ProcessError(); acceptName = PredicateUtils.NewRegex(regex); } } catch { ReadReady(); throw; } } catch (TextNetworkProtocolException) { this.connected = false; throw; } catch (IOException) { this.connected = false; throw; } for (; ;) { string line; NodeType currentNodeType; Pair <string, string> currentFile; try { line = TextConversion.FromEscapedHexString(ReadNextLine()); } catch (TextNetworkProtocolException) { this.connected = false; throw; } catch (IOException) { this.connected = false; throw; } if (line.EqualsIgnoreCase(ResponseCodes.READY)) { break; } currentFile = line.SplitAroundFirstCharFromLeft(':'); currentFile.Right = TextConversion.FromEscapedHexString(currentFile.Right); currentNodeType = TextNetworkProtocol.GetNodeType(currentFile.Left); if (currentNodeType == null || currentFile.Right.Length == 0) { continue; } if (acceptName != null) { if (acceptName(currentFile.Right)) { yield return(new Pair <string, NodeType>(currentFile.Right, currentNodeType)); } } else { yield return(new Pair <string, NodeType>(currentFile.Right, currentNodeType)); } } } }
public override IEnumerable <NetworkFileSystemEntry> ListAttributes(string uri, string regex) { Predicate <string> acceptName = null; using (this.AcquireCommandContext(false)) { try { try { if (!String.IsNullOrEmpty(regex)) { try { SendCommand(DefaultTryCount, @"list -a -regex=""{0}"" ""{1}""", TextConversion.ToEscapedHexString(regex), uri).ProcessError(); } catch (TextNetworkProtocolErrorResponseException) { ReadReady(); SendCommand(DefaultTryCount, @"list -a ""{1}""", regex, uri).ProcessError(); acceptName = PredicateUtils.NewRegex(regex); } } else { SendCommand(DefaultTryCount, @"list -a ""{0}""", uri).ProcessError(); } } catch { ReadReady(); throw; } } catch (TextNetworkProtocolException) { this.connected = false; throw; } catch (IOException) { this.connected = false; throw; } var enumerator = TextNetworkProtocol.ReadEntries(this.ReadNextLine).GetEnumerator(); try { for (; ;) { try { if (!enumerator.MoveNext()) { break; } } catch (TextNetworkProtocolException) { this.connected = false; throw; } catch (IOException) { this.connected = false; throw; } if (enumerator.Current.Right != null) { CommandResponse response; response = ParseResponse(enumerator.Current.Right); response.ProcessError(); } if (acceptName != null) { if (acceptName(enumerator.Current.Left.Name)) { yield return(enumerator.Current.Left); } } else { yield return(enumerator.Current.Left); } } } finally { enumerator.Dispose(); } } }
public static LocalNodeAddress Parse(string uri) { Group group; Match match = null; string root, scheme, query; // Often Parse will be called with the exact same URI reference that was last passed // to CanParse. If this is the case then use the results cached by the last call to // CanParse from this thread. if ((object)uri == (object)lastCanParseUri) { match = lastCanParseMatch; } while (true) { if (match == null) { match = localFileNameRegEx.Match(uri); } if (!match.Success) { throw new MalformedUriException(uri); } bool schemeExplicitlyProvided; group = match.Groups["scheme"]; if (group.Value == "") { scheme = "file"; schemeExplicitlyProvided = false; } else { scheme = group.Value; schemeExplicitlyProvided = true; } group = match.Groups["uncserver"]; if (group.Success) { string path; Pair <string, string> result; path = match.Groups["path1"].Value; result = path.SplitAroundCharFromLeft(1, PredicateUtils.ObjectEqualsAny('\\', '/')); root = "//" + group.Value + result.Left.Replace('\\', '/'); path = "/" + result.Right; if (path == "") { path = "/"; } query = match.Groups["query"].Value; return(new LocalNodeAddress(scheme, root, true, StringUriUtils.NormalizePath(path), query)); } else { string path; group = match.Groups["root"]; if (group.Captures.Count > 0) { // // Windows path specification // root = group.Value; path = match.Groups["path2"].Value; if (path.Length == 0) { path = FileSystemManager.SeperatorString; } query = match.Groups["query"].Value; path = StringUriUtils.NormalizePath(path); if (schemeExplicitlyProvided) { // // Explicitly provided scheme means // special characters are hexcoded // path = TextConversion.FromEscapedHexString(path); query = TextConversion.FromEscapedHexString(query); } return(new LocalNodeAddress(scheme, root, true, path, query)); } else if (match.Groups["path3"].Value != "") { // // Unix path specification // path = match.Groups["path3"].Value; query = match.Groups["query"].Value; path = StringUriUtils.NormalizePath(path); if (schemeExplicitlyProvided) { // // Explicitly provided scheme means // special characters are hexcoded // path = TextConversion.FromEscapedHexString(path); query = TextConversion.FromEscapedHexString(query); } return(new LocalNodeAddress(scheme, "", true, path, query)); } else { // // Relative path specification // path = match.Groups["path4"].Value; query = match.Groups["query"].Value; path = StringUriUtils.Combine(Environment.CurrentDirectory, path); path = StringUriUtils.NormalizePath(path); if (!string.IsNullOrEmpty(query)) { query = "?" + query; } else { query = ""; } if (schemeExplicitlyProvided) { uri = scheme + "://" + path + "query"; } else { uri = path + query; } match = null; } } } }
/// <summary> /// Construct a new <see cref="MeterValueEvent{V}"/> based on the specified value. /// </summary> /// <param name="meter"> /// The <see cref="IMeter"/> to monitor. /// </param> /// <param name="value"> /// The value that will be compared with the current <see cref="IMeter"/> value. /// </param> public MeterValueEvent(IMeter meter, V value) : this(meter, PredicateUtils.ObjectEquals(value)) { }
/// <summary> /// Reads a string form the <see cref="TextReader"/> until a space is encountered /// </summary> /// <param name="reader">The reader to read from</param> /// <param name="maximumLength">The maximum number of characters to read</param> /// <returns>The string that was read</returns> public static string ReadWord(TextReader reader, int maximumLength) { return(reader.ReadWhile(PredicateUtils.ObjectNotEquals(' '), maximumLength)); }
public override void Process(Command command) { var count = 0; var options = this.LoadOptions <CommandOptions>((TextCommand)command); var dir = this.Connection.FileSystemManager.ResolveDirectory(options.Uri); dir.Refresh(); if (options.Regex != null) { options.Regex = TextConversion.FromEscapedHexString(options.Regex); } if (!dir.Exists) { throw new DirectoryNodeNotFoundException(dir.Address); } Connection.WriteOk(); if (options.IncludeAttributes) { Exception exception = null; InvocationQueue queue; if (t_InvocationQueue == null) { t_InvocationQueue = new InvocationQueue(); } queue = t_InvocationQueue; queue.TaskAsynchronisity = TaskAsynchronisity.AsyncWithSystemPoolThread; queue.Start(); try { IEnumerable <INode> children = null; if (String.IsNullOrEmpty(options.Regex)) { children = dir.GetChildren(); } else { children = dir.GetChildren(RegexBasedNodePredicateHelper.New(options.Regex)); } foreach (var node in children) { var enclosedNode = node; if (queue.TaskState == TaskState.Stopped) { break; } queue.Enqueue ( delegate { try { if (enclosedNode.NodeType == NodeType.Directory) { Connection.WriteTextPartialBlock("d:"); } else { Connection.WriteTextPartialBlock("f:"); } Connection.WriteTextBlock(TextConversion.ToEscapedHexString(enclosedNode.Name, TextConversion.IsStandardUrlEscapedChar)); AttributesCommands.PrintAttributes(this.Connection, enclosedNode); count++; if (count % 15 == 0) { Connection.Flush(); } } catch (Exception e) { queue.Stop(); exception = e; } } ); } if (queue.TaskState == TaskState.Stopped) { throw exception; } } finally { queue.Enqueue(queue.Stop); queue.WaitForAnyTaskState(value => value != TaskState.Running); queue.Reset(); Connection.Flush(); } } else { IEnumerable <string> children; if (string.IsNullOrEmpty(options.Regex)) { children = dir.GetChildNames(NodeType.Directory); } else { children = dir.GetChildNames(NodeType.Directory, PredicateUtils.NewRegex(options.Regex)); } foreach (var name in children) { Connection.WriteTextPartialBlock("d:"); Connection.WriteTextBlock(TextConversion.ToEscapedHexString(name, TextConversion.IsStandardUrlEscapedChar)); count++; if (count % 15 == 0) { Connection.Flush(); } } count = 0; if (string.IsNullOrEmpty(options.Regex)) { children = dir.GetChildNames(NodeType.File); } else { children = dir.GetChildNames(NodeType.File, PredicateUtils.NewRegex(options.Regex)); } foreach (var name in children) { Connection.WriteTextPartialBlock("f:"); Connection.WriteTextBlock(TextConversion.ToEscapedHexString(name)); count++; if (count % 15 == 0) { Connection.Flush(); } } } Connection.Flush(); }
/// <summary> /// Prescans the type. /// </summary> protected virtual void Scan(SerializerOptions options, bool includeIfUnattributed) { XmlApproachAttribute approach = null; XmlElementAttribute elementAttribute; // Get the applicable attributes LoadAttributes(options); // Get the setter/getter and serializer if (memberInfo is FieldInfo) { getterSetter = new FieldGetterSetter(memberInfo); returnType = ((FieldInfo)memberInfo).FieldType; } else if (memberInfo is PropertyInfo) { var propertyInfo = (PropertyInfo)memberInfo; getterSetter = new PropertyGetterSetter(memberInfo); returnType = ((PropertyInfo)memberInfo).PropertyType; } else if (memberInfo is Type) { getterSetter = null; serializedName = memberInfo.Name; returnType = (Type)memberInfo; } else { throw new ArgumentException($"Unsupported member type: {this.memberInfo.MemberType.ToString()}"); } // Get the [XmlExclude] [XmlAttribute] or [XmlElement] attribute var attribute = GetFirstApplicableAttribute(false, typeof(XmlExcludeAttribute), typeof(XmlTextAttribute), typeof(XmlAttributeAttribute), typeof(XmlElementAttribute)); if (attribute != null) { if (attribute is XmlExcludeAttribute) { // This member needs to be excluded serializedNodeType = XmlNodeType.None; } else if (attribute is XmlTextAttribute) { serializedNodeType = XmlNodeType.Text; } else if ((approach = attribute as XmlApproachAttribute) != null) { ApproachAttribute = approach; // This member needs to be included as an attribute or an element serializedNodeType = approach is XmlElementAttribute ? XmlNodeType.Element : XmlNodeType.Attribute; if (approach.Type != null) { returnType = approach.Type; } serializedName = approach.Name; serializedNamespace = approach.Namespace; if ((elementAttribute = approach as XmlElementAttribute) != null) { if (elementAttribute.SerializeAsValueNode) { serializeAsValueNodeAttributeName = elementAttribute.ValueNodeAttributeName; } } if (approach.SerializeUnattribted) { this.includeIfUnattributed = true; } if (approach.SerializeIfNull) { this.serializeIfNull = true; } } } else { if (includeIfUnattributed) { serializedName = memberInfo.Name; serializedNodeType = XmlNodeType.Element; } else { serializedNodeType = XmlNodeType.None; } } if (serializedNodeType == XmlNodeType.None) { return; } // Check if the member should be serialized as CDATA attribute = GetFirstApplicableAttribute(typeof(XmlCDataAttribute)); if (attribute != null) { serializeAsCData = ((XmlCDataAttribute)attribute).Enabled; } attribute = GetFirstApplicableAttribute(typeof(XmlVariableSubstitutionAttribute)); if (attribute != null) { Substitutor = (IVariableSubstitutor)Activator.CreateInstance(((XmlVariableSubstitutionAttribute)attribute).SubstitutorType); } // Set the serialized (element or attribute) name to the name of the member if it hasn't already been set if (serializedName.Length == 0) { if (approach != null && approach.UseNameFromAttributedType && memberInfo.MemberType == MemberTypes.TypeInfo) { serializedName = GetAttributeDeclaringType((Type)memberInfo, approach).Name; } else { serializedName = this.memberInfo.Name.Left(PredicateUtils.ObjectEquals('`').Not()); } } // Make the serialized (element or attribute) name lowercase if requested if (approach != null) { if (approach.MakeNameLowercase) { serializedName = serializedName.ToLower(); } } // Get the explicitly specified TypeSerializer if requested attribute = GetFirstApplicableAttribute(typeof(XmlTypeSerializerTypeAttribute)); if (attribute != null) { if (((XmlTypeSerializerTypeAttribute)attribute).SerializerType != null) { typeSerializer = typeSerializerCache.GetTypeSerializerBySerializerType(((XmlTypeSerializerTypeAttribute)attribute).SerializerType, this); if (!returnType.IsAssignableFrom(typeSerializer.SupportedType)) { throw new InvalidOperationException($"Explicitly specified serializer ({((XmlTypeSerializerTypeAttribute)attribute).SerializerType.Name}) doesn't support serializing of associated program element."); } } } else { typeSerializer = typeSerializerCache.GetTypeSerializerBySupportedType(returnType, this); } // Check if the member should be treated as a null value if it is empty treatAsNullIfEmpty = HasApplicableAttribute(typeof(XmlTreatAsNullIfEmptyAttribute)); // Check if the member's declared type is polymorphic var polymorphicTypeAttribute = (XmlPolymorphicTypeAttribute)GetFirstApplicableAttribute(typeof(XmlPolymorphicTypeAttribute)); if (polymorphicTypeAttribute != null) { polymorphicTypeProvider = (IXmlDynamicTypeProvider)Activator.CreateInstance(polymorphicTypeAttribute.PolymorphicTypeProvider); } }
/// <summary> /// Reads a string form the <see cref="TextReader"/> until a space is encountered /// </summary> /// <param name="reader">The reader to read from</param> /// <returns>The string that was read</returns> public static string ReadWord(this TextReader reader) { return(reader.ReadWhile(PredicateUtils.ObjectNotEquals(' '))); }