/// <inheritdoc/> public override ExpNode Execute(VectorProductOperNode node) { // Verify left and right child are two multiplyable vectors. if (node.LeftChild is TensorNode vector1 && vector1.DimensionCount == 1 && node.RightChild is TensorNode vector2 && vector2.DimensionCount == 1 && vector1.SizeIdentity == vector2.SizeIdentity) { int size = vector1.GetDimensionSize(1); switch (node.ProductMethod) { case VectorProductMethod.DOT: ExpNode[] terms = new ExpNode[size]; for (int i = 0; i < size; i++) { terms[i] = QuickOpers.Multiply(vector1.GetChild(i), vector2.GetChild(i)); } return(QuickOpers.Sum(terms).Execute(this)); case VectorProductMethod.CROSS: // TODO: Convert to matrix notation for determinant default: return(node); } } return(HandleError(new CannotMultiplyTensors(this, node))); }
/// <summary> /// Creates a new <see cref="RecipricalOperNode"/> around <paramref name="node"/>. /// </summary> /// <param name="node">The <see cref="ExpNode"/> to take the reciprical of.</param> /// <returns>A new <see cref="RecipricalOperNode"/> around <paramref name="node"/>.</returns> public static RecipricalOperNode Reciprical(ExpNode node) { return(new RecipricalOperNode() { Child = node }); }
public virtual void RunModel() { QueryModel model = new QueryModel(_workspace, _kind, null); ModelEngine engine = new ModelEngine(model); engine.Options.WeightScheme = WeightScheme.Custom; engine.Options.Timeout = 100; engine.RunUntil(delegate() { return model.Actions.Accessed > 5; }); _query = model.QueryResult; _container = model.ResContainer; _pType = model.ResultType; if (_query != null || _pType != null) { switch (_queryType) { case "server": VerifyServer(_query); break; case "client": VerifyClient(model); break; case "linq": VerifyClientLinq(model); break; } } }
private ExpNode parseElmnt() { if (lex.Peek() == Token.NUM) { return(new NumExpNode(lex.Take())); } if (lex.Peek() == Token.ID) { LexUnit id = lex.Take(); if (lex.Peek() == Token.LPN) { lex.Take(); FncCallExpNode fnc = new FncCallExpNode(); fnc.ID = id; fnc.args = parseArgs(); Match(Token.RPN, "expected ')' for valid function call"); return(fnc); } else { return(new IdExpNode(id)); } } if (lex.Peek() == Token.LPN) { lex.Take(); ExpNode exp = parseExp(); Match(Token.RPN, "expected ')' for valid expression"); return(exp); } throw new ParseException(ref lex.unit, "invalid in expression"); }
public ExpNode parseExp() { OpExpNode exp = null; ExpNode fact = null; if (lex.Peek() == Token.SUB) { exp = new OpExpNode(); exp.left = null; exp.OP = lex.Take(); exp.right = parseFact(); } else { fact = parseFact(); } while (lex.Peek() == Token.ADD || lex.Peek() == Token.SUB) { OpExpNode tmp = new OpExpNode(); tmp.left = exp == null ? fact : exp; tmp.OP = lex.Take(); tmp.right = parseFact(); exp = tmp; } return(exp == null ? fact : exp); }
public TypeVisiter(ExpNode node) : base(node) { rootParam = new Stack <ParameterExpression>(); rootParam.Push(Expression.Parameter(typeof(T))); this.context = new MContext(typeof(T)); }
private TreeNode getFactor() { TreeNode treeNode; switch (tokens[currentTokenIndex].Type) { case TokenType.BracketLeft: match(TokenType.BracketLeft); currentTokenIndex++; treeNode = getExp(); currentTokenIndex++; match(TokenType.BracketRight); break; case TokenType.Id: treeNode = new ExpNode(tokens[currentTokenIndex]); match(TokenType.Id); break; case TokenType.Integer: treeNode = new ExpNode(tokens[currentTokenIndex]); match(TokenType.Integer); break; case TokenType.Float: treeNode = new ExpNode(tokens[currentTokenIndex]); match(TokenType.Float); break; default: throw new InvalidSyntaxException(tokens[currentTokenIndex]); } return(treeNode); }
public ExpVisiter(ExpNode root) { rootParam = new Stack <ParameterExpression>(); rootParam.Push(Expression.Parameter(typeof(T))); this.context = new MContext(typeof(T)); this.rootNode = root; }
/// <summary> /// Creates a new negative <see cref="SignOperNode"/> around <paramref name="node"/>. /// </summary> /// <param name="node">The <see cref="ExpNode"/> to negate.</param> /// <returns>A new negative <see cref="SignOperNode"/> around <paramref name="node"/>.</returns> public static SignOperNode Negative(ExpNode node) { return(new SignOperNode(Sign.NEGATIVE) { Child = node }); }
/// <summary> /// Creates a new <see cref="PowOperNode"/> as <paramref name="base"/>^<paramref name="exponent"/>. /// </summary> /// <param name="base">The base of the <see cref="PowOperNode"/>.</param> /// <param name="exponent">The exponent of the <see cref="PowOperNode"/>.</param> /// <returns>A new <see cref="PowOperNode"/> as <paramref name="base"/>^<paramref name="exponent"/>.</returns> public static PowOperNode Pow(ExpNode @base, ExpNode exponent) { PowOperNode powNode = new(); powNode.LeftChild = @base; powNode.RightChild = exponent; return(powNode); }
/// <inheritdoc/> public override void InsertChild(BranchNode node) { ExpNode lastChild = Children[ChildCount - 1]; Children.RemoveAt(ChildCount - 1); node.AddChild(lastChild); AddChild(node); }
/// <inheritdoc/> public override ExpNode Execute(MultiplicationOperNode node) { // TODO: Sinusoidal u substitutions // TODO: Constants recognitions for v Differentiator differentiator = new(_variable); // \int{u'vwx} = uvwx - \int{uv'wx} - \int{uvw'x} - \int{uvwx'} int partCount = node.ChildCount - 1; // Get u and du ExpNode du = node.GetChild(partCount); ExpNode u = du.Clone().Execute(this); // Get dvs and vs ExpNode[] dvs = new ExpNode[partCount]; ExpNode[] vs = new ExpNode[partCount]; for (int i = 0; i < partCount; i++) { vs[i] = node.GetChild(i); dvs[i] = vs[i].Clone().Execute(differentiator); } AdditionOperNode aNode = new(); // u*vs MultiplicationOperNode mNode = new(); mNode.AddChild(u.Clone()); for (int i = 0; i < partCount; i++) { mNode.AddChild(vs[i].Clone()); } aNode.AddChild(mNode); // Combinatoric integrals for (int i = 0; i < partCount; i++) { IntegralOperNode intNode = new(); mNode = new MultiplicationOperNode(); intNode.Variable = new VarValueNode(_variable); mNode.AddChild(u.Clone()); for (int j = 0; j < partCount; j++) { if (i == j) { mNode.AddChild(dvs[j].Clone()); } else { mNode.AddChild(vs[j].Clone()); } } intNode.AddChild(mNode); aNode.AddChild(QuickOpers.Negative(intNode)); } return(aNode); }
public override void Visit(IBinaryOpToken t) { ExpNode operand2 = m_nodes.Pop(); ExpNode operand1 = m_nodes.Pop(); char op = char.Parse(t.ToString()); m_nodes.Push(Tables.BinaryOperatorsExpTable[op](operand1, operand2)); }
/// <summary> /// Multiplies a tensor by scalars. /// </summary> /// <param name="node">The <see cref="MultiplicationOperNode"/> to simplify.</param> /// <param name="simplifier">The <see cref="Simplifier"/> calling.</param> /// <returns>The resuling <see cref="MultiplicationOperNode"/>.</returns> public static MultiplicationOperNode MultiplyScalarTensor(MultiplicationOperNode node, Simplifier simplifier) { TensorNode tensor1 = null; int ti = -1; for (int i = 0; i < node.ChildCount; i++) { if (i == ti) { continue; } if (node.GetChild(i) is TensorNode tensor2) { if (tensor1 != null) { if (i < ti) { TensorNode swap = tensor1; tensor1 = tensor2; tensor2 = swap; } if (!tensor1.CanMatrixMultiply(tensor2)) { return((MultiplicationOperNode)simplifier.HandleError(new CannotMultiplyTensors(simplifier, node, $"Tensor nodes of size {tensor1.SizeIdentity} and {tensor2.SizeIdentity} could not be multiplied."))); } } else { tensor1 = tensor2; ti = i; i = -1; } } else { if (tensor1 != null) { for (int j = 0; j < tensor1.ChildCount; j++) { ExpNode simpleChild = QuickOpers.Multiply(tensor1.GetChild(j), node.GetChild(i)).Execute(simplifier); tensor1.ReplaceChild(simpleChild, j); } node.RemoveChild(i); if (i < ti) { ti--; } i--; } } } return(node); }
/// <inheritdoc/> public override ExpNode Execute(MultiplicationOperNode node) { double valueProg = 1; for (int i = 0; i < node.ChildCount; i++) { ExpNode simpleChild = node.GetChild(i).Execute(this); if (simpleChild is NumericalValueNode nvNode) { valueProg *= nvNode.DoubleValue; node.RemoveChild(i); i--; } else if (simpleChild is MultiplicationOperNode mNode) { mNode.TransferChildren(node); node.RemoveChild(i); i--; } else { node.ReplaceChild(simpleChild, i); } } // Anything multiplied by 0, is zero if (valueProg == 0) { return(QuickOpers.MakeNumericalNode(0)); } if (node.ChildCount == 0 || valueProg != 1) { node.AddChild(QuickOpers.MakeNumericalNode(valueProg)); } MultiplicationHelpers.SimplfiyMTerms(node, this); if (node.ChildCount == 0) { return(QuickOpers.MakeNumericalNode(0)); } else if (node.ChildCount == 1) { return(node.GetChild(0)); } node = MultiplicationHelpers.MultiplyScalarTensor(node, this); if (node == null) { return(node); } return(MultiplicationHelpers.Distribute(node, this)); }
private void FindInsertionNode(ExpNode node) { while ((_activeNode.Priority != Priority.OVERRIDE) && node.Priority > _activeNode.Priority && !_activeNode.IsRoot) { _activeNode = _activeNode.Parent; } }
/// <inheritdoc/> public override ExpNode Execute(TensorNode node) { for (int i = 0; i < node.ChildCount; i++) { ExpNode simpleChild = node.GetChild(i).Execute(this); node.ReplaceChild(simpleChild, i); } return(node); }
/// <summary> /// Adds a <see cref="OperNode"/> to the expression tree. /// </summary> /// <param name="node">The <see cref="OperNode"/> to add to the expression tree.</param> public void AddNode(OperNode node) { bool insert = !(node is UOperNode); if (_activeNode == null) { // This is the first Branch Node if (Root != null) { // The first node is often a ValueNode // That is the only time a ValueNode will be the active or root node // Makes node the new active_node node.AddChild(Root); } Root = node; _activeNode = node; return; } FindInsertionNode(node); if (node.Priority > _activeNode.Priority) { // The new node is a lower priority than any node so far // or a parenthesis/function was hit // Add new node to top if (_activeNode.Priority == Priority.OVERRIDE) { InsertOperNode(node, insert); } else if (Root == _activeNode) { // node is new root node.AddChild(Root); Root = node; } } else if (node.Priority == _activeNode.Priority && (node is NOperNode)) { for (int i = 0; i < node.ChildCount; i++) { _activeNode.AddChild(node); } return; } else { InsertOperNode(node, insert); } _activeNode = node; }
/// <inheritdoc/> public override ExpNode Execute(AdditionOperNode node) { // Sum rule for (int i = 0; i < node.ChildCount; i++) { ExpNode diffChild = node.GetChild(i).Execute(this); node.ReplaceChild(diffChild, i); } return(node); }
/// <summary> /// Checks if two <see cref="TensorNode"/>s are vectors and equal size. /// </summary> /// <param name="node">The first <see cref="ExpNode"/>.</param> /// <param name="other">The second <see cref="ExpNode"/>.</param> /// <param name="vector1">The first <see cref="ExpNode"/> as a <see cref="TensorNode"/>.</param> /// <param name="vector2">The second <see cref="ExpNode"/> as a <see cref="TensorNode"/>.</param> /// <returns>True if two <see cref="TensorNode"/>s are equal size and vectors.</returns> public static bool AreEqualSizeVectors(this ExpNode node, ExpNode other, out TensorNode vector1, out TensorNode vector2) { if (node is TensorNode tensor1 && other is TensorNode tensor2) { vector1 = tensor1; vector2 = tensor2; return(AreEqualSizeVectors(tensor1, tensor2)); } vector1 = vector2 = null; return(false); }
/// <summary> /// Adds a <see cref="ValueNode"/> to the expression tree. /// </summary> /// <param name="node">The <see cref="ValueNode"/> to add to the expression tree.</param> public void AddNode(ValueNode node) { if (_activeNode == null) { // If first node Root = node; } else { _activeNode.AddChild(node); } }
public override void Visit(IUnaryOpToken t) { ExpNode operand = m_nodes.Peek(); char op = char.Parse(t.ToString()); ExpNode unaryOperator = Tables.UnaryOperatorsExpTable[op](operand); if (unaryOperator != null) { m_nodes.Pop(); m_nodes.Push(unaryOperator); } }
/// <summary> /// Initializes a new instance of the <see cref="AdditiveTerm"/> class. /// </summary> /// <param name="node">The node to create as a term.</param> public AdditiveTerm(ExpNode node) { DefaultPrinter printer = new(); if (node is MultiplicationOperNode mNode && mNode.GetChild(0) is NumericalValueNode nvNode) { // Node is a multiply and it's first child is a numerical value // That numerical value is the coefficient _coefficient = nvNode.DoubleValue; // Remove coefficient from base mNode.RemoveChild(0); _base = mNode; }
public override void Visit(IFuncNameToken t) { // Get number of nessessary arguments int n = Tables.FunctionsArgsNumberTable[t.ToString()]; // Pop arguments ExpNode[] arguments = new ExpNode[n]; for (int i = 0; i < n; i++) { arguments[i] = m_nodes.Pop(); } m_nodes.Push(Tables.FunctionsExpTable[t.ToString()](arguments)); }
private ExpNode parseFact() { ExpNode expn = parseExpnt(); OpExpNode exp = null; while (lex.Peek() == Token.MUL || lex.Peek() == Token.DIV) { OpExpNode tmp = new OpExpNode(); tmp.left = exp == null ? expn : exp; tmp.OP = lex.Take(); tmp.right = parseExpnt(); exp = tmp; } return(exp == null ? expn : exp); }
/// <summary> /// Adds a <see cref="BranchNode"/> to the expression tree. /// </summary> /// <param name="node">The <see cref="BranchNode"/> to add to the expression tree.</param> public void AddNode(BranchNode node) { if (node is OperNode oNode) { AddNode(oNode); } else if (_activeNode == null) { Root = node; } else { _activeNode.AddChild(node); } }
private ExpNode parseExpnt() { ExpNode elm = parseElmnt(); if (lex.Peek() != Token.POW) { return(elm); } OpExpNode exp = new OpExpNode(); exp.left = elm; exp.OP = lex.Take(); exp.right = parseExpnt(); return(exp); }
/// <inheritdoc/> public override void ReplaceChild(ExpNode node, int index) { switch (index) { case 0: LeftChild = node; break; case 1: RightChild = node; break; default: throw new ArgumentOutOfRangeException($"{nameof(BOperNode)} only contains two (2) children. Zero (0) and one (1) are the only indicies."); } }
/// <summary> /// Initializes a new instance of the <see cref="MultiplicativeTerm"/> class. /// </summary> /// <param name="node">The node to create as a term.</param> public MultiplicativeTerm(ExpNode node) { DefaultPrinter printer = new(); if (node is PowOperNode powNode) { _base = powNode.LeftChild; _exponent = powNode.RightChild; } else { _base = node; _exponent = QuickOpers.MakeNumericalNode(1); } _baseString = _base.Print(printer); }
/// <inheritdoc/> public override void AddChild(ExpNode node) { if (LeftChild == null) { LeftChild = node; } else if (RightChild == null) { RightChild = node; } else { throw new BOperNodeAlreadyHasChildrenException(this); } node.Parent = this; }
/// <summary> /// Adds tensors. /// </summary> /// <param name="node">The <see cref="AdditionOperNode"/> containing tensors.</param> /// <param name="simplifier">The <see cref="Simplifier"/> calling.</param> /// <returns>The resuling <see cref="ExpNode"/>.</returns> public static ExpNode SumTensors(AdditionOperNode node, Simplifier simplifier) { if (node.GetChild(0) is TensorNode tensorNode) { for (int i = 1; i < node.ChildCount; i++) { if (node.GetChild(i) is TensorNode otherTensorNode) { if (otherTensorNode.SizeIdentity == tensorNode.SizeIdentity) { for (int j = 0; j < tensorNode.ChildCount; j++) { ExpNode addedNode = QuickOpers .Sum(tensorNode.GetChild(j), otherTensorNode.GetChild(j)) .Execute(simplifier); tensorNode.ReplaceChild(addedNode, j); } } else { return(simplifier.HandleError(new CannotAddTensors(simplifier, node, $"Cannot add tensor of shape {otherTensorNode.SizeIdentity} and tensor of shape {tensorNode.SizeIdentity}."))); } } else { return(simplifier.HandleError(new CannotAddTensors(simplifier, node, "Cannot add scalar and tensor."))); } } return(tensorNode); } else { // There is a scalar. // There cannot be any tensors for (int i = 1; i < node.ChildCount; i++) { if (node.GetChild(i) is TensorNode) { return(simplifier.HandleError(new CannotAddTensors(simplifier, node, "Cannot add tensor and scalar."))); } } } return(node); }
public override string Build(ExpNode node) { nodeStack = new Stack<ExpNode>(); document = new XmlDocument(); // document.AppendChild(document.CreateXmlDeclaration("1.0", Encoding.UTF8.WebName, "yes")); this.Visit(null, node, null); StringBuilder builder = new StringBuilder(); // settings taken from server XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; settings.Indent = true; settings.NewLineHandling = NewLineHandling.Entitize; XmlWriter writer = XmlWriter.Create(builder, settings); writer.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"" + Encoding.UTF8.WebName + "\" standalone=\"yes\""); document.Save(writer); return builder.ToString(); }
protected virtual string BuildMemberOrMethodExpression(ExpNode node, ExpNode caller, ExpNode[] arguments, string name) { string instance = null; string args = ""; string actualName = null; if (caller != null) instance = this.Visit(node, caller); if (name.ToLowerInvariant() == "contains") { actualName = "contains"; args = this.Visit(node, arguments[0]); return string.Format("{0}({1},{2})", actualName, instance, args); } else { actualName = name.ToLowerInvariant(); if (arguments != null && arguments.Length > 0) { for (int i = 0; i < arguments.Length; i++) args += this.Visit(node, arguments[i]) + ", "; args = args.Substring(0, args.Length - 2); if (instance == null) return string.Format("{0}({1})", actualName, args); else return string.Format("{0}({1},{2})", actualName, instance, args); } else return string.Format("{0}({1})", actualName, instance); } }
public ServiceOperationExpression(ExpNode input, ServiceOperationParameterExpression[] arguments) : base(input) { this.Arguments = arguments; }
public static MemberBindExpression Bind(this ResourceType resourceType, string LeftHandSide, ExpNode RightHandSide) { TypedMemberExpression targetProperty = new TypedMemberExpression(resourceType.ClientClrType, resourceType.Properties[LeftHandSide].Name); return new MemberBindExpression(RightHandSide, targetProperty); }
public virtual KeyExpressions GetAllExistingKeys(ExpNode query, ResourceContainer resourceContainer) { KeyExpressions keys = new KeyExpressions(); IQueryable objects = this.GetUnderlyingProviderQueryResults(query); IEnumerator enumerator = null; try { enumerator = objects.GetEnumerator(); while (enumerator.MoveNext()) { Type t = enumerator.Current.GetType(); if (AstoriaTestProperties.EdmObjectLayer == ServiceEdmObjectLayer.PocoWithProxy && AstoriaTestProperties.DataLayerProviderKinds.Contains(Astoria.DataLayerProviderKind.Edm)) t = t.BaseType; List<ResourceType> types = resourceContainer.ResourceTypes.Where(rt => rt.Name.Equals(t.Name) && rt.Namespace.Equals(t.Namespace)).ToList(); ResourceType actualResourceType = types.Single(); keys.Add(GetKeyExpression(resourceContainer, actualResourceType, enumerator.Current)); } } catch (NullReferenceException exc) { //TODO: Due to a client bug } finally { IDisposable disposable = (enumerator as IDisposable); if (null != disposable) { disposable.Dispose(); } } return keys; }
public virtual IQueryable GetUnderlyingProviderQueryResults(ExpNode q) { LinqQueryBuilder linqQueryBuilder = new LinqQueryBuilder(this); linqQueryBuilder.Build(q); return linqQueryBuilder.QueryResult; }
//Constructor public PredicateExpression(QueryNode input, ExpNode predicate) : base(input) { _predicate = predicate; _type = input.Type; }
public void Expand() { string sExpand = String.Empty; PropertyExpression[] expandValues = new PropertyExpression[1]; List<ResourceProperty> properties = new List<ResourceProperty>(); foreach (ResourceProperty property in from.Properties) { if (property.IsNavigation && from.Properties.Contains(property) && !(from.Name == "BugDefectTrackingSet" || from.Name == "BugProjectTrackingSet")) properties.Add(property); } if (properties.Count > 0) { expandValues[0] = new PropertyExpression(properties[0]); sExpand = expandValues[0].ToString(); if (_query is TopExpression) _query = ((TopExpression)_query).Expand(expandValues) as ExpandExpression; else if (_query is OrderByExpression) _query = ((OrderByExpression)_query).Expand(expandValues) as ExpandExpression; else if (_query is ScanExpression) _query = ((ScanExpression)_query).Expand(expandValues) as ExpandExpression; else if (_query is NavigationExpression) _query = ((NavigationExpression)_query).Expand(expandValues) as ExpandExpression; else if (_query is SkipExpression) _query = ((SkipExpression)_query).Expand(expandValues) as ExpandExpression; else if (_query is PredicateExpression) _query = ((PredicateExpression)_query).Expand(expandValues) as ExpandExpression; else if (_query is CountExpression) _query = ((CountExpression)_query).Expand(expandValues) as ExpandExpression; else if (_query is NavigationExpression) _query = ((NavigationExpression)_query).Expand(expandValues) as ExpandExpression; bExpand = true; _action = LastAction.Expand; bIsOption = true; AstoriaTestLog.WriteLineIgnore(".Expand(" + sExpand + ")"); } }
public OrderByExpression(QueryNode input, ExpNode[] properties, QueryNode scannode, bool bAscDesc, bool excludeFromUri) : base(input) { _properties = properties; _scannode = scannode; _bAscDesc = bAscDesc; _excludeFromUri = excludeFromUri; if (excludeFromUri) _properties = properties.OrderBy(p => p.Name).ToArray(); }
public static OrderByExpression Sort(this QueryNode input, ExpNode[] properties, bool bAscDesc) { return Sort(input, properties, bAscDesc, false); }
protected override String Visit(ExpNode caller, ExpNode node) { if (node is ProjectExpression) { ProjectExpression e = (ProjectExpression)node; if (e.Projections.Count == 0) { return String.Format("{0}", this.Visit(e, e.Input) ); } else if (e.Projections.Count == 1) { if (e.Projections[0] is PropertyExpression) { return String.Format("{0}/{1}", this.Visit(e, e.Input), this.Visit(e, e.Projections[0]) ); } } else throw new Exception("More than 1 projection, invalid"); } else if (node is ServiceOperationExpression) { AstoriaTestLog.WriteLine("Calling Service Operation"); ServiceOperationExpression e = (ServiceOperationExpression)node; string serviceOp = this.Visit(e, e.Input); AstoriaTestLog.WriteLine(serviceOp); StringBuilder sbParametersString = new StringBuilder(); if (!serviceOp.Contains("?")) { sbParametersString.Append("?"); } for (int index = 0; index < e.Arguments.Length; index++) { ServiceOperationParameterExpression parameter = e.Arguments[index]; if (index > 0) { sbParametersString.Append("&"); } string strLiteralString = CreateKeyStringValue(parameter.ParameterValue); sbParametersString.AppendFormat("{0}={1}", parameter.ParameterName, strLiteralString); } return String.Format("{0}{1}", serviceOp, sbParametersString.ToString()); } else if (node is ScanExpression) { ScanExpression e = (ScanExpression)node; if (e.Input is VariableExpression && ((VariableExpression)e.Input).Variable is ResourceContainer) return String.Format("{0}", this.Visit(e, e.Input) ); throw new Exception("Unsupported on in scan expression"); } else if (node is PredicateExpression) { PredicateExpression e = (PredicateExpression)node; KeyExpression key = e.Predicate as KeyExpression; if (key != null) { return String.Format("{0}({1})", this.Visit(e, e.Input), this.Visit(e, e.Predicate) ); } else return String.Format("{0}?$filter={1}", this.Visit(e, e.Input), this.Visit(e, e.Predicate) ); } else if (node is CountExpression) { CountExpression e = (CountExpression)node; string sCount = ""; string visit = ""; if (!e.IsInline) { visit = this.Visit(e, e.Input); sCount = string.Format("{0}/$count", visit); } else { visit = this.Visit(e, e.Input); if (visit.IndexOf("?$") == -1) sCount = string.Format("{0}?$inlinecount={1}", visit, e.CountKind); else sCount = string.Format("{0}&$inlinecount={1}", visit, e.CountKind); } return sCount; } else if (node is NewExpression) { NewExpression e = (NewExpression)node; string uri = this.Visit(e, e.Input); ExpNode[] pe = new ExpNode[] { }; List<ExpNode> nodes = new List<ExpNode>(); foreach (ExpNode parameter in e.Arguments) { nodes.Add(parameter as ExpNode); } pe = nodes.ToArray(); string _select = String.Format("{0}", this.Visit(e, pe[0])); if (nodes.Count > 1) { for (int j = 1; j < nodes.Count; j++) { _select = String.Format("{0},{1}", _select, this.Visit(e, pe[j])); } } if (uri.IndexOf("?$") == -1) return string.Format("{0}?$select={1}", uri, _select); else return string.Format("{0}&$select={1}", uri, _select); } else if (node is MemberBindExpression) { return this.Visit(node, ((MemberBindExpression)node).SourceProperty); } else if (node is TopExpression) { TopExpression e = (TopExpression)node; string visit = this.Visit(e, e.Input); if (visit.IndexOf("?$") == -1) return string.Format("{0}?$top={1}", visit, e.Predicate); else return string.Format("{0}&$top={1}", visit, e.Predicate); } else if (node is SkipExpression) { SkipExpression e = (SkipExpression)node; string visit = this.Visit(e, e.Input); if (visit.IndexOf("?$") == -1) return string.Format("{0}?$skip={1}", visit, e.Predicate); else return string.Format("{0}&$skip={1}", visit, e.Predicate); } else if (node is OrderByExpression) { OrderByExpression e = (OrderByExpression)node; string ordervalue = String.Empty; int i = 0; string visit = this.Visit(e, e.Input); if (e.ExcludeFromUri) { return visit; } string propVisit = this.Visit(e, e.PropertiesExp[0]); switch (e.AscDesc) { case true: if (visit.IndexOf("?$") == -1) ordervalue = String.Format("{0}?$orderby={1}", visit, propVisit); else ordervalue = String.Format("{0}&$orderby={1}", visit, propVisit); break; case false: if (visit.IndexOf("?$") == -1) ordervalue = String.Format("{0}?$orderby={1} desc", visit, propVisit); else ordervalue = String.Format("{0}&$orderby={1} desc", visit, propVisit); break; }; if (e.PropertiesExp.Length > 0) { for (i++; i < e.PropertiesExp.Length; i++) { String nextValue = this.Visit(e, e.PropertiesExp[i]); nextValue = String.Format("{0}", nextValue); switch (e.AscDesc) { case true: ordervalue = String.Format("{0},{1}", ordervalue, nextValue); break; case false: ordervalue = String.Format("{0},{1} desc", ordervalue, nextValue); break; } } } return ordervalue; } else if (node is ThenByExpression) { ThenByExpression e = (ThenByExpression)node; string ordervalue = String.Empty; int i = 0; string visit = this.Visit(e, e.Input); if (e.ExcludeFromUri) { return visit; } switch (e.AscDesc) { case true: ordervalue = String.Format("{0},{1}", visit, e.Properties[0].Name); break; case false: ordervalue = String.Format("{0},{1} desc", visit, e.Properties[0].Name); break; } if (e.Properties.Length > 0) { for (i++; i < e.Properties.Length; i++) { String nextValue = e.Properties[i].Name; nextValue = String.Format("{0}", nextValue); switch (e.AscDesc) { case true: ordervalue = String.Format("{0},{1}", ordervalue, nextValue); break; case false: ordervalue = String.Format("{0},{1} desc", ordervalue, nextValue); break; } } } return ordervalue; } else if (node is ExpandExpression) { ExpandExpression e = (ExpandExpression)node; string uri = this.Visit(e, e.Input); string expand = String.Format("{0}", this.Visit(e, e.PropertiesExp[0])); if (e.Properties.Length > 1) for (int i = 1; i < e.Properties.Length; i++) expand = String.Format("{0},{1}", expand, this.Visit(e, e.PropertiesExp[i])); if (uri.IndexOf("?$") == -1) return string.Format("{0}?$expand={1}", uri, expand); else return string.Format("{0}&$expand={1}", uri, expand); } else if (node is NavigationExpression) { NavigationExpression e = (NavigationExpression)node; if (!e.IsLink) return String.Format("{0}/{1}", this.Visit(e, e.Input), this.Visit(e, e.PropertyExp)); else return String.Format("{0}/{1}/$ref", this.Visit(e, e.Input), this.Visit(e, e.PropertyExp)); } else if (node is KeyExpression) { KeyExpression key = node as KeyExpression; return CreateKeyString(key); } else if (node is NestedPropertyExpression) { NestedPropertyExpression e = (NestedPropertyExpression)node; string enitySetname = e.Name; string nestedProperty = ""; foreach (PropertyExpression p in e.PropertyExpressions) { string interim = this.Visit(e, p); //AstoriaTestLog.WriteLine(interim); if (p.ValueOnly) nestedProperty = String.Format("{0}/{1}/{2},", nestedProperty, enitySetname, interim + "/$value").TrimStart('/'); else nestedProperty = String.Format("{0}/{1}/{2},", nestedProperty, enitySetname, interim).TrimStart('/'); } return nestedProperty.TrimEnd(',').Replace(",/", ","); } else if (node is PropertyExpression) { PropertyExpression e = (PropertyExpression)node; if (e.ValueOnly) return e.Property.Name + "/$value"; else return e.Property.Name; } else if (node is VariableExpression) { VariableExpression e = (VariableExpression)node; return e.Variable.Name; } if (node is LogicalExpression) { LogicalExpression e = (LogicalExpression)node; string left = this.Visit(e, e.Left); string right = null; if (e.Operator != LogicalOperator.Not) { right = this.Visit(e, e.Right); } string logical; switch (e.Operator) { case LogicalOperator.And: logical = string.Format("{0} and {1}", left, right); break; case LogicalOperator.Or: logical = string.Format("{0} or {1}", left, right); break; case LogicalOperator.Not: logical = string.Format("not {0}", left); break; default: throw new Exception("Unhandled Comparison Type: " + e.Operator); } return logical; } else if (node is ComparisonExpression) { ComparisonExpression e = (ComparisonExpression)node; String left = this.Visit(e, e.Left); String right = this.Visit(e, e.Right); switch (e.Operator) { case ComparisonOperator.Equal: return String.Format("{0} eq {1}", left, right); case ComparisonOperator.NotEqual: return String.Format("{0} ne {1}", left, right); case ComparisonOperator.GreaterThan: return String.Format("{0} gt {1}", left, right); case ComparisonOperator.GreaterThanOrEqual: return String.Format("{0} ge {1}", left, right); case ComparisonOperator.LessThan: return String.Format("{0} lt {1}", left, right); case ComparisonOperator.LessThanOrEqual: return String.Format("{0} le {1}", left, right); default: throw new Exception("Unhandled Comparison Type: " + e.Operator); }; } else if (node is IsOfExpression || node is CastExpression) { ExpNode target; NodeType targetType; string operation; if (node is IsOfExpression) { IsOfExpression e = (IsOfExpression)node; operation = "isof"; target = e.Target; targetType = e.TargetType; } else { CastExpression e = (CastExpression)node; operation = "cast"; target = e.Target; targetType = e.TargetType; } string targetTypeName = targetType.FullName; if (targetType is PrimitiveType) { targetTypeName = TypeData.FindForType(targetType.ClrType).GetEdmTypeName(); } if (target == null) { return String.Format("{0}('{1}')", operation, targetTypeName); } else { return String.Format("{0}({1}, '{2}')", operation, this.Visit(node, target), targetTypeName); } } else if (node is ArithmeticExpression) { ArithmeticExpression e = (ArithmeticExpression)node; String left = this.Visit(e, e.Left); String right = this.Visit(e, e.Right); switch (e.Operator) { case ArithmeticOperator.Add: return String.Format("{0} add {1}", left, right); case ArithmeticOperator.Div: return String.Format("{0} div {1}", left, right); case ArithmeticOperator.Mod: return String.Format("{0} mod {1}", left, right); case ArithmeticOperator.Mult: return String.Format("{0} mul {1}", left, right); case ArithmeticOperator.Sub: return String.Format("{0} sub {1}", left, right); default: throw new Exception("Unhandled Arithmetic Type: " + e.Operator); }; } else if (node is MethodExpression) { MethodExpression e = (MethodExpression)node; return BuildMemberOrMethodExpression(node, e.Caller, e.Arguments, e.Name); } else if (node is MemberExpression) { MemberExpression e = (MemberExpression)node; return BuildMemberOrMethodExpression(node, e.Caller, e.Arguments, e.Name); } else if (node is ConstantExpression) { ConstantExpression e = (ConstantExpression)node; object value = e.Value.ClrValue; string val = TypeData.FormatForKey(value, this.UseSmallCasing, false); if (this.EscapeUriValues) { // FormatForKey already does this for doubles that don't have the D if (!(value is double) || Versioning.Server.SupportsV2Features) val = Uri.EscapeDataString(val); } if (value == null) val = "null"; else if (!(value is String)) { val = val.Replace("+", "").Replace("%2B", ""); } return val; } else if (node is NegateExpression) { NegateExpression e = (NegateExpression)node; return "-(" + this.Visit(e, e.Argument) + ")"; } else if (node is FirstExpression) { FirstExpression first = node as FirstExpression; return this.Visit(first, first.Input); } else if (node is FirstOrDefaultExpression) { FirstOrDefaultExpression first = node as FirstOrDefaultExpression; return this.Visit(first, first.Input); } else if (node is SingleExpression) { SingleExpression first = node as SingleExpression; return this.Visit(first, first.Input); } else if (node is SingleOrDefaultExpression) { SingleOrDefaultExpression first = node as SingleOrDefaultExpression; return this.Visit(first, first.Input); } else { throw new Exception(this.GetType().Name + " Unhandled Node: " + node.GetType().Name); } }
protected void Visit(ExpNode caller, ExpNode node, XmlElement parentNode) { nodeStack.Push(node); if (node == null) { throw new ArgumentNullException("node"); } if (node is KeyedResourceInstance && (!(node is AssociationResourceInstance))) { KeyedResourceInstance e = (KeyedResourceInstance)node; CreateEntryElement(e, parentNode); } else if (node is AssociationResourceInstance) { AssociationResourceInstance e = (AssociationResourceInstance)node; if (caller == null) CreateLinkPayload(e, parentNode); else CreateBinding(e, parentNode); } //Below are two special cases else if (caller == null && node is ResourceInstanceSimpleProperty) { this.VisitResourceInstanceSimpleProperty(node as ResourceInstanceSimpleProperty, parentNode); } else if (caller == null && node is ResourceInstanceComplexProperty) { this.VisitResourceInstanceComplexProperty(node as ResourceInstanceComplexProperty, parentNode); } else if (caller == null && node is ResourceInstanceNavRefProperty) { ResourceInstanceNavRefProperty navRef = node as ResourceInstanceNavRefProperty; AssociationResourceInstance associationResourceInstance = navRef.TreeNode as AssociationResourceInstance; if (associationResourceInstance != null && associationResourceInstance.Operation == AssociationOperation.Remove) { this.CreateUnBinding(parentNode); } else throw new Exception("Unknown node type:" + navRef.TreeNode.GetType()); } else if (caller == null && node is ResourceInstanceCollection) { ResourceInstanceCollection collection = node as ResourceInstanceCollection; CreateLinksElement(collection, null); } else { throw new Exception("Unknown node type: " + node.GetType()); } nodeStack.Pop(); }
public AstoriaRequest CreateRequest(ExpNode query, ResourceBodyTree updateTree, RequestVerb operation) { AstoriaRequest request = new AstoriaRequest(this); request.Verb = operation; request.Query = query as QueryNode; request.UpdateTree = updateTree; PrepareRequest(request); return request; }
public abstract string Build(ExpNode node);
public override string Build(ExpNode node) { string serviceName; string queryUri = base.Build(node); return this.Workspace.ServiceUri + "/" + queryUri; }
public virtual void DirectedTests() { QueryModel model = new QueryModel(_workspace, SerializationFormatKind.Atom, null); ModelEngine engine = new ModelEngine(model); engine.Options.WeightScheme = WeightScheme.Custom; engine.Options.Timeout = 100; engine.RunUntil(delegate() { return engine.Models.Actions.AllCovered; }); //engine.RunScenario(model.Actions.Find("From", "Where", " Navigation","Select","Expand")); //engine.RunUntil(delegate() //{ // return model.Actions.Accessed > 4; //}); _query = model.QueryResult; _container = model.ResContainer; _pType = model.ResultType; if (_query != null || _pType != null) { VerifyClient(model); } }
public AstoriaRequest CreateRequest(ExpNode query) { return this.CreateRequest(query, null, RequestVerb.Get); }
public static PredicateExpression Where(this QueryNode input, ExpNode predicate) { return new PredicateExpression(input, predicate); }
public void VerifyServer(ExpNode q) { AstoriaTestLog.WriteLineIgnore("Verify server query"); try { UriQueryBuilder ub = new UriQueryBuilder(_workspace, ""); string ruri = ub.Build(q); AstoriaTestLog.WriteLineIgnore(ruri); AstoriaRequest request = _workspace.CreateRequest(q); request.Format = _kind; if (request.URI.Length > 260) { return; } AstoriaResponse response = request.GetResponse(); response.Verify(); } catch (Exception e) { AstoriaTestLog.WriteLineIgnore(e.ToString()); } }
public MemberBindExpression(ExpNode sourceProperty, TypedMemberExpression targetProperty) : base("MemberBindExpression") { SourceProperty = sourceProperty; TargetProperty = targetProperty; //SourceProperty = new PropertyExpression( }
public static void Verify(Workspace w, ExpNode q, IEnumerable results, ResourceType resType) { Verify(w, q, results, resType, null, false); }
//Data //Constructor public ScanExpression(ExpNode input) : base(input) { _type = input.Type; }
public static void Verify(Workspace w, ExpNode q, IEnumerable results, ResourceType resType, ComplexType cType, bool bCount) { long count = 0; if (bCount) { object[] args = new object[] { results }; Type qorType = typeof(QueryOperationResponseWrapper<>).MakeGenericType(resType.ClientClrType); object qor = Activator.CreateInstance(qorType, args); PropertyInfo pi = qor.GetType().GetProperty("GetTotalCount"); object i = pi.GetValue(qor, new object[] { }); count = (long)i; LinqQueryBuilder lb = new LinqQueryBuilder(w); lb.CountingMode = true; lb.Build(q); object baselineElementsCount = CommonPayload.CreateList(lb.QueryResult).Count; AstoriaTestLog.IsTrue(count == Convert.ToInt64(baselineElementsCount), "Count is different.Count is " + count.ToString() + ". Baseline count is " + baselineElementsCount.ToString()); } LinqQueryBuilder linqBuilder = new LinqQueryBuilder(w); linqBuilder.Build(q); IQueryable baselines = linqBuilder.QueryResult; IEnumerator b = null; IEnumerator r = null; try { b = TrustedMethods.IQueryableGetEnumerator(baselines); r = results.GetEnumerator(); } catch (InvalidOperationException invalidOperation) { if (!AstoriaTestProperties.IsRemoteClient) throw invalidOperation; } PropertyInfo propertyInfo = null; Object expectedResult1 = null; Object expectedResult2 = null; try { while (b.MoveNext() && r.MoveNext()) { if (b.Current == null) { return; } if (r.Current == null) { throw new TestFailedException("Less results than expected"); } //skip verification for Binary data type for Linq to Sql if (AstoriaTestProperties.DataLayerProviderKinds[0] == DataLayerProviderKind.LinqToSql && b.Current is System.Byte[]) return; if (b.Current is System.Byte[]) { byte[] newBase = (byte[])b.Current; byte[] newAct = (byte[])r.Current; if (newBase.Length != newAct.Length) throw new TestFailedException("Failed to compare the results!"); } #if !ClientSKUFramework else if (b.Current is System.Data.Linq.Binary) { System.Data.Linq.Binary newBase = (System.Data.Linq.Binary)b.Current; System.Data.Linq.Binary newAct = new System.Data.Linq.Binary((byte[])r.Current); if (newBase.Length != newAct.Length) throw new TestFailedException("Failed to compare the results!"); } #endif else if (b.Current is System.Xml.Linq.XElement) { if (b.Current.ToString() != r.Current.ToString()) throw new TestFailedException("Failed to compare the results!"); } else { if (!b.Current.Equals(r.Current)) { if (cType != null) { foreach (ResourceProperty property in cType.Properties) { if (!property.IsNavigation && !property.IsComplexType && !(property.Type is CollectionType)) { propertyInfo = b.Current.GetType().GetProperty(property.Name); expectedResult1 = propertyInfo.GetValue(b.Current, null); PropertyInfo propertyInfo2 = r.Current.GetType().GetProperty(property.Name); expectedResult2 = propertyInfo2.GetValue(r.Current, null); if (expectedResult1 != expectedResult2) { if (expectedResult1 is System.Xml.Linq.XElement) { expectedResult1 = ((System.Xml.Linq.XElement)expectedResult1).ToString(System.Xml.Linq.SaveOptions.None); } if (expectedResult2 is System.Xml.Linq.XElement) { expectedResult2 = ((System.Xml.Linq.XElement)expectedResult2).ToString(System.Xml.Linq.SaveOptions.None); } #if !ClientSKUFramework if (expectedResult1 is byte[]) { expectedResult1 = new System.Data.Linq.Binary((byte[])expectedResult1); } if (expectedResult2 is byte[]) { expectedResult2 = new System.Data.Linq.Binary((byte[])expectedResult2); } #endif AstoriaTestLog.AreEqual(expectedResult1, expectedResult2, String.Format("Resource value for {0} does not match", property.Name), false); } } } } else { foreach (ResourceProperty property in resType.Properties) { if (!property.IsNavigation && !property.IsComplexType && !(property.Type is CollectionType)) { //skip verification for Binary data type for Linq to Sql if (AstoriaTestProperties.DataLayerProviderKinds[0] == DataLayerProviderKind.LinqToSql && property.Type.Name == "LinqToSqlBinary") return; propertyInfo = b.Current.GetType().GetProperty(property.Name); expectedResult1 = propertyInfo.GetValue(b.Current, null); PropertyInfo propertyinfo2 = r.Current.GetType().GetProperty(property.Name); expectedResult2 = propertyinfo2.GetValue(r.Current, null); if (expectedResult1 != expectedResult2) { if (expectedResult1 is System.Xml.Linq.XElement) { expectedResult1 = ((System.Xml.Linq.XElement)expectedResult1).ToString(System.Xml.Linq.SaveOptions.None); } if (expectedResult2 is System.Xml.Linq.XElement) { expectedResult2 = ((System.Xml.Linq.XElement)expectedResult2).ToString(System.Xml.Linq.SaveOptions.None); } #if !ClientSKUFramework if (expectedResult1 is byte[]) { expectedResult1 = new System.Data.Linq.Binary((byte[])expectedResult1); } if (expectedResult2 is byte[]) { expectedResult2 = new System.Data.Linq.Binary((byte[])expectedResult2); } #endif AstoriaTestLog.AreEqual(expectedResult1, expectedResult2, String.Format("Resource value for {0} does not match", property.Name), false); } } } } } } } } catch (Exception e) { AstoriaTestLog.WriteLine(e.ToString()); throw; } }
public OrderByExpression(QueryNode input, ExpNode[] properties, QueryNode scannode, bool bAscDesc) : this(input, properties, scannode, bAscDesc, false) { }
public static void ExecuteLinq(Workspace workspace, ExpNode q, ResourceContainer container) { try { ExecuteLinq(workspace, q, container, false, null); } catch (Exception e) { AstoriaTestLog.FailAndContinue(e); } }
//Constructor public NewExpression(ExpNode input, params ExpNode[] arguments) : base(input) { _target = input; _arguments = new Nodes<ExpNode>(this, arguments); //_type = target.Type; }
public static void ExecuteLinq(Workspace workspace, ExpNode q, ResourceContainer container, bool bSingle, ExpNode altq) { System.Uri uri = new Uri(workspace.ServiceUri); WebDataCtxWrapper ctx = new WebDataCtxWrapper(uri); ctx.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; ctx.MergeOption = MergeOption.NoTracking; Type resType = container.BaseType.ClientClrType; ResolveClientType(workspace, ctx, resType); Type cType = typeof(WebDataCtxWrapper); MethodInfo mi = cType.GetMethod("CreateQuery", new Type[] { typeof(string) }); Type pType = container.BaseType.ClientClrType; MethodInfo miConstructed = mi.MakeGenericMethod(pType); string uri2 = container.Name; AstoriaTestLog.WriteLineIgnore(workspace.ServiceUri + "/" + uri2); object[] args = { uri2 }; object query = miConstructed.Invoke(ctx, args); LinqQueryBuilder lb = new LinqQueryBuilder(workspace, (IQueryable)query); string uri3 = lb.Build(q); AstoriaTestLog.WriteLineIgnore("Linq expression: " + lb.QueryExpression); //if (bSingle) //{ // var single = lb.QueryResultSingle; // VerifyLinqSingle(workspace, altq, single, container); //} //else //{ var queryable = lb.QueryResult; VerifyLinq(workspace, q, (IQueryable)queryable); //} }
public static OrderByExpression Sort(this QueryNode input, ExpNode[] properties, bool bAscDesc, bool excludeFromUri) { QueryNode scaninput = input; while (!(scaninput is ScanExpression) && !(scaninput is PredicateExpression) && !(scaninput is NavigationExpression)) { scaninput = scaninput.Input as QueryNode; } if (input is ScanExpression || input is PredicateExpression || input is NavigationExpression) return new OrderByExpression(input, properties, input, bAscDesc, excludeFromUri); else return new OrderByExpression(input, properties, scaninput, bAscDesc, excludeFromUri); }
public static void VerifyLinq(Workspace workspace, ExpNode q, IQueryable results) { //verify if the results are ok before building the URI System.Collections.ArrayList list = new System.Collections.ArrayList(); foreach (object element in results) list.Add(element); //UriQueryBuilder ub = new UriQueryBuilder(workspace, ""); // string ruri = ub.Build(q); //System.Uri uri = new Uri(workspace.ServiceUri); // string uriRel = ruri.Substring(ruri.IndexOf("/") + 1); // AstoriaTestLog.WriteLineIgnore(uri.ToString() + uriRel); AstoriaRequest request = workspace.CreateRequest(q); request.Format = SerializationFormatKind.Atom; try { AstoriaResponse response = request.GetResponse(); //response.VerifyHttpStatusCodeOk(response.StatusCode); CommonPayload payload = response.CommonPayload; if (payload.Value != null) payload.CompareValue(results, false, false); else payload.Compare(results); //AstoriaTestLog.AreEqual(response.ContentType, SerializationFormatKinds.ContentTypeFromKind(response.OriginalRequest.SerializationKind), //"Content-Type does not match Accept header request"); } catch (Exception e) { AstoriaTestLog.FailAndContinue(e); } }