/// <summary> /// Interprets the parsed expression list. /// </summary> internal void InterpretExpression() { //Create an interpreter and construct a tree of the expression list. Interpreter interpreter = new Interpreter(parsedExpression); interpretedExpression = interpreter.Interpret(); }
/// <summary> /// Adds the supplied operator to the tree. /// The operator is added according to precedence and associativity. /// </summary> /// <param name="topNode">The top node of the tree.</param> /// <param name="next">The operator to add.</param> private void AddToTree(ref ExpressionItem topNode, ExpressionItem next) { if (topNode is OperatorItem) { OperatorItem currentNode = (OperatorItem)topNode; if (currentNode.Configuration.Precedence < ((OperatorItem)next).Configuration.Precedence || (currentNode.Configuration.Precedence == ((OperatorItem)next).Configuration.Precedence && ((OperatorItem)next).Configuration.Associativity == Associativity.left)) { //The top node has lower precedence, or the new operator has left associativity: //add it as top node and add the current tree as left parameter. ((OperatorItem)next).AddParameter(currentNode); topNode = next; } else if (((OperatorItem)next).Configuration.Associativity == Associativity.left) { //The new operator has associativity left. //Find the first node with same precedence and add the new operator at that position //with the found node as left parameter. ExpressionItem child = currentNode.Parameters[currentNode.Parameters.Length - 1]; while (child is OperatorItem && ((OperatorItem)child).Configuration.Precedence > ((OperatorItem)next).Configuration.Precedence) { currentNode = (OperatorItem)child; child = currentNode.Parameters[currentNode.Parameters.Length - 1]; } ExpressionItem[] currentParams = currentNode.Parameters; currentNode.RemoveParameters(); ((OperatorItem)next).AddParameter(currentParams[currentParams.Length - 1]); currentParams[currentParams.Length - 1] = next; currentNode.AddParameterRange(currentParams); } else if (((OperatorItem)next).Configuration.Associativity == Associativity.right) { //The new node has right associativity. //find the first node with lower precedence and add the new operator at that position //with the found node as left parameter. ExpressionItem child = currentNode.Parameters[currentNode.Parameters.Length - 1]; while (child is OperatorItem && ((OperatorItem)child).Configuration.Precedence >= ((OperatorItem)next).Configuration.Precedence) { currentNode = (OperatorItem)child; child = currentNode.Parameters[currentNode.Parameters.Length - 1]; } ExpressionItem[] currentParams = currentNode.Parameters; currentNode.RemoveParameters(); ((OperatorItem)next).AddParameter(currentParams[currentParams.Length - 1]); currentParams[currentParams.Length - 1] = next; currentNode.AddParameterRange(currentParams); } } else { //The next item isn't an operator. This case will not be used. ((OperatorItem)next).AddParameter(topNode); topNode = next; } //Fill the right hand side of the new operator. FillParameters(next); }
private void listControl_MouseUp(object sender, MouseEventArgs e) { this.listItemClicked = false; if (!this.dragging) { return; } if (this.outlineForm != null) { this.outlineForm.Close(); this.outlineForm.Dispose(); this.outlineForm = (Form)null; } if (this.textBox.Bounds.Contains(this.treeControl.FindForm().PointToClient(this.treeControl.PointToScreen(e.Location)))) { ExpressionItem dataBoundItem = this.treeControl.SelectedNode.DataBoundItem as ExpressionItem; if (dataBoundItem != null) { this.textBox.Text = this.textBox.Text + dataBoundItem.Value + " "; this.textBox.SelectionStart = this.textBox.Text.Length; this.textBox.Focus(); } } this.treeControl.FindForm().Cursor = Cursors.Arrow; this.treeControl.Capture = false; this.dragging = false; }
/// <summary> /// creates a logical expression AND, OR /// </summary> /// <param name="logical"></param> internal LogicalOperator(ExpressionItem left, TokenType logical, ExpressionItem right) : base(left, logical, right) { if (!(logical == TokenType.AND || logical == TokenType.OR)) { throw new ArgumentException($"Invalid logical operator: {logical}"); } }
internal static ExpressionOperator Create(ExpressionItem left, TokenType oper, ExpressionItem right) { if (oper == TokenType.AND || oper == TokenType.OR) { return(new LogicalOperator(left, oper, right)); } else if (oper.IsComparison()) { return(new ComparisonOperator(left, oper, right)); } return(null); }
//public IBinaryTree<ExpressionItem> Data => this; /// <summary> /// returns true if left and right operands are table columns /// </summary> //public bool TwoColumns => Left.GroupType == OperandType.Column && Right.GroupType == OperandType.Column; /// <summary> /// creates a WHERE expression /// </summary> /// <param name="left">left expression</param> /// <param name="oper">operator</param> /// <param name="right">right expression</param> internal ExpressionOperator(ExpressionItem left, TokenType oper, ExpressionItem right) : base(ExpressionItemType.Operator) { if ((Left = left) == null) { throw new ArgumentException($"invalid left operand in expression: {left}"); } if ((Right = right) == null) { throw new ArgumentException($"invalid right operand in expression: {right}"); } Operator = oper; }
public void testParseIncludesExcludes() { string adl = System.IO.File.ReadAllText(@"..\..\..\..\java-libs\adl-parser\src\test\resources\adl-test-entry.archetype_slot.test.adl"); se.acode.openehr.parser.ADLParser parser = new se.acode.openehr.parser.ADLParser(adl); org.openehr.am.archetype.Archetype archetype = parser.parse(); Assert.IsNotNull(archetype); ArchetypeConstraint node = archetype.node("/content[at0001]"); // Type e = typeof(node); ArchetypeSlot slot = (ArchetypeSlot)node; Assert.AreEqual("at0001", slot.getNodeId(), "nodeId wrong"); Assert.AreEqual("SECTION", slot.getRmTypeName(), "rmTypeName wrong"); Interval a = new Interval(0, 1); // Assert.AreEqual( a, slot.getOccurrences());//错误??? Assert.AreEqual("/content[at0001]", slot.path(), "path wrong"); Assert.AreEqual(1, slot.getIncludes().size(), "includes total wrong"); Assert.AreEqual(2, slot.getExcludes().size(), "Excludes total wrong"); object b = slot.getIncludes().iterator().next(); Assertion assertion = (Assertion)b; ExpressionItem item = assertion.getExpression(); Assert.IsInstanceOfType(item, typeof(ExpressionBinaryOperator)); //assertTrue("expressionItem type wrong", // item instanceof ExpressionBinaryOperator); ExpressionBinaryOperator bo = (ExpressionBinaryOperator)item; ExpressionItem leftOp = bo.getLeftOperand(); ExpressionItem rightOp = bo.getRightOperand(); Assert.IsInstanceOfType(leftOp, typeof(ExpressionLeaf)); //assertTrue("left operator type wrong", // leftOp instanceof ExpressionLeaf); ExpressionLeaf left = (ExpressionLeaf)leftOp; Assert.AreEqual("domain_concept", left.getItem(), "left value wrong"); Assert.IsInstanceOfType(rightOp, typeof(ExpressionLeaf)); // assertTrue("right operator type wrong", rightOp instanceof ExpressionLeaf); ExpressionLeaf right = (ExpressionLeaf)rightOp; Assert.IsInstanceOfType(right.getItem(), typeof(CString)); // assertTrue("right item type wrong", right.getItem() instanceof CString); CString cstring = (CString)right.getItem(); Assert.AreEqual("blood_pressure.v1", cstring.getPattern(), "right value wrong"); }
public void testParseSingleInclude() { string adl = System.IO.File.ReadAllText(@"..\..\..\..\java-libs\adl-parser\src\test\resources\adl-test-entry.archetype_slot.test2.adl"); se.acode.openehr.parser.ADLParser parser = new se.acode.openehr.parser.ADLParser(adl); org.openehr.am.archetype.Archetype archetype = parser.parse(); Assert.IsNotNull(archetype); ArchetypeConstraint node = archetype.node("/content[at0001]"); ArchetypeSlot slot = (ArchetypeSlot)node; Assert.AreEqual("at0001", slot.getNodeId(), "nodeId wrong"); Assert.AreEqual("SECTION", slot.getRmTypeName(), "rmTypeName wrong"); // Assert.AreEqual("occurrences wrong", new Interval<Integer>(0, 1),slot.getOccurrences()); Assert.AreEqual("/content[at0001]", slot.path(), "path wrong"); Assert.AreEqual(1, slot.getIncludes().size(), "includes total wrong"); Assertion assertion = (Assertion)slot.getIncludes().iterator().next(); ExpressionItem item = assertion.getExpression(); //assertTrue("expressionItem type wrong", // item instanceof ExpressionBinaryOperator); ExpressionBinaryOperator bo = (ExpressionBinaryOperator)item; ExpressionItem leftOp = bo.getLeftOperand(); ExpressionItem rightOp = bo.getRightOperand(); //assertTrue("left operator type wrong", // leftOp instanceof ExpressionLeaf); ExpressionLeaf left = (ExpressionLeaf)leftOp; Assert.AreEqual("archetype_id/value", left.getItem(), "left value wrong"); //assertTrue("right operator type wrong", // rightOp instanceof ExpressionLeaf); ExpressionLeaf right = (ExpressionLeaf)rightOp; //assertTrue("right item type wrong", right.getItem() instanceof CString); string cstring = Convert.ToString(right.getItem()); //Assert.AreEqual("right value wrong", "openEHR-EHR-CLUSTER\\.device\\.v1", // cstring.getPattern()); Assert.IsNotNull("stringExpression missing", assertion.getStringExpression()); String expectedStringExpression = "archetype_id/value matches {/openEHR-EHR-CLUSTER\\.device\\.v1/}"; Assert.AreEqual(expectedStringExpression, assertion.getStringExpression(), "stringExpression wrong, got: " + assertion.getStringExpression()); }
/// <summary> /// Negotiates recursively with the operator which parameter configuration to use. /// The operator suggest a config and the interpreter tries to find parameters. /// If it fails, this function is called again with new parameters. /// </summary> /// <param name="topNode">The top node in the tree.</param> /// <param name="next">The operator to negotiate with.</param> /// <param name="param">the suggested parameters.</param> private void Negotiate(ref ExpressionItem topNode, ExpressionItem next, ExpressionItem[] param) { OperatorConfiguration config; //The suggested parameters are accepted. //Add the operator to the tree. if (((OperatorItem)next).SuggestParameters(param, out config)) { AddToTree(ref topNode, next); } else if (config != null) { //If the operator suggests a valid config //try to supply better parameters. if (config.NrOfParameters == 1 && config.Associativity == Associativity.left) { //The operator is unary with the operator to the left. //Suggest the right parameter and continue to negotiate. ExpressionItem[] param1 = new ExpressionItem[1]; param1[0] = param[1]; Negotiate(ref topNode, next, param1); } else if (config.NrOfParameters == 1) { //The operator is unary with the operator to the right. //Suggest the left parameter and continue to negotiate. ExpressionItem[] param1 = new ExpressionItem[1]; param1[0] = param[0]; Negotiate(ref topNode, next, param1); } else { //Suggest one less parameter. Only used when the operator is ternary or more. ExpressionItem[] param1 = new ExpressionItem[config.NrOfParameters]; for (int i = 0; i < param1.Length; i++) { param1[i] = param[i]; } Negotiate(ref topNode, next, param1); } } else { //The operator didn't accept the parameters, //and has no alternative. throw new Exception("Interpreter.Negotiate(): MalformedExpression"); } }
/// <summary> /// Print the value of an expression item. /// </summary> /// <param name="item">The expression item.</param> private void PrintValue(ExpressionItem item) { if (item is AssignmentOperatorItem) { //If the expression was an assignment display the new varaible name and its value. string variableName = ((AssignmentOperatorItem)item).VariableName; lstResultList.Items.Add(String.Format(" {1} = {0}", item.Value, variableName)); } else { //Otherwise, store the result in 'answer'. lstResultList.Items.Add(String.Format(" answer = {0}", item.Value)); //Save the result in the variable 'answer' resolver.GetReference("answer").Value = item.Value; } }
int GetPriority(ExpressionItem ei) { if (ei.OperationType == Operation.Plus || ei.OperationType == Operation.Minus) { return(1); } if (ei.OperationType == Operation.Multiply || ei.OperationType == Operation.Divide) { return(2); } if (ei.OperationType == Operation.Power) { return(3); } return(0); }
/// <summary> /// creates an expression operator /// </summary> /// <param name="oper">operator type</param> public ComparisonOperator(ExpressionItem left, TokenType oper, ExpressionItem right) : base(left, oper, right) { switch (oper) { case TokenType.Equal: case TokenType.NotEqual: case TokenType.Greater: case TokenType.GreaterOrEqual: case TokenType.Less: case TokenType.LessOrEqual: Token = oper; break; default: throw new ArgumentException($"Invalid sql comparison operator: {oper}"); } }
/// <summary> /// Takes an operator and fills the right hand side parameters recurively to form an valid expression. /// </summary> /// <param name="item">An operator to fill.</param> private void FillParameters(ExpressionItem item) { //If the item is already valid, return. if (item.IsValid()) { return; } //Find the NextItem item ExpressionItem next = NextItem(); //If the next item is an operator, //check if the operator accepts the only valid config and check whether the //supplied parameters are accepted. if (next is OperatorItem) { OperatorConfiguration[] configs = ((OperatorItem)next).AcceptedConfigurations; OperatorConfiguration config = new OperatorConfiguration(Associativity.left, 1); bool result = false; for (int i = 0; i < configs.Length; i++) { ExpressionItem rightParam = Peek(); ExpressionItem[] param = new ExpressionItem[1]; param[0] = rightParam; OperatorConfiguration oc; if (config.Equals(configs[i]) && ((OperatorItem)next).SuggestParameters(param, out oc)) { //The operator accepts the parameters and config which it is given result = true; ((OperatorItem)next).Configuration = configs[i]; break; } } if (!result) { //The operator can't be used in the way supplied throw new Exception("Interpreter.FillParameters: Malformed expression"); } //Fill the parameters of the new operator recursively FillParameters(next); } //Add the next item as a parameter to the operator. ((FunctionItem)item).AddParameter(next); }
/// <summary> /// Parses the expression string. If the expression is well-formed /// a tree will be constructed and the top node of the tree is returned. /// </summary> /// <returns>The top node of the tree.</returns> public ExpressionItem Interpret() { ExpressionItem topNode = NextItem(); //Inserts the first node into the tree. //This has to be managed separatly. if (topNode is OperatorItem) { //Find out the accepted configurations of the item to add. OperatorConfiguration[] configs = ((OperatorItem)topNode).AcceptedConfigurations; //The only valid config is a unary operator with the data on the right. OperatorConfiguration config = new OperatorConfiguration(Associativity.left, 1); //Find out whether the operator may have the only possible config bool result = false; for (int i = 0; i < configs.Length; i++) { if (config.Equals(configs[i])) { //A valid configuration is found. //Indicate success and tell the operator which configuration it is in. result = true; ((OperatorItem)topNode).Configuration = configs[i]; break; } } if (!result) { throw new Exception("Interpreter.Interpret(): Malformed expression"); } //Fill all the parameter places of the top node to acquire a valid expression. FillParameters(topNode); } //As long as there exists more items in the expression, //add the next item to the tree. while (HasNext()) { AddNextToTree(ref topNode); } return(topNode); }
public ExpressionCollection <T> Build(List <ISequenceSymbol> sequenceOfSymbols) { var expressionCollection = new ExpressionCollection <T>(); for (var i = 0; i < sequenceOfSymbols.Count(); i++) { var sequenceSymbol = sequenceOfSymbols.ElementAt(i); var expressionBaseToAdd = (ExpressionBase <T>)null; switch (sequenceSymbol) { case ParenthesisOpenSymbol _: var nextParenthesisCloseSymbolIndex = sequenceOfSymbols.FindIndex(i, x => x is ParenthesisCloseSymbol); var subSequenceOfSymbols = sequenceOfSymbols.Skip(i + 1).Take(nextParenthesisCloseSymbolIndex - i).ToList(); // extracting subsequence of symbols inside parentheses expressionBaseToAdd = Build(subSequenceOfSymbols); i = nextParenthesisCloseSymbolIndex; // going to closing parenthesis position break; case ExpressionSymbol <T> _: expressionBaseToAdd = new ExpressionItem <T>((sequenceSymbol as ExpressionSymbol <T>).Expression); break; default: // should not happen // ParenthesisCloseSymbol // LogicalOperatorAndSymbol // LogicalOperatorOrSymbol throw new NotImplementedException(string.Format(GeneralResources.Exception_UnexpectedTokenDuringAnalysisOfSequenceOfSymbols, sequenceSymbol.GetType())); } var nextLogicalOperator = sequenceOfSymbols.ElementAtOrDefault(++i) as ILogicalOperatorSymbol; // going to next position (after closing parenthesis or expression symbol) if (nextLogicalOperator != null) { expressionBaseToAdd.LogicalOperator = nextLogicalOperator.ToLogicalOperator(); } expressionCollection.Add(expressionBaseToAdd); } return(expressionCollection); }
/// <summary> /// Creates a widget based on the type of the item pased. /// </summary> /// <param name="item"> /// The <see cref="ExpressionItem"/> that will be contained in the /// widget. /// </param> /// <param name="container"> /// The container holding the new widget. /// </param> /// <returns> /// The widget holding the given item. /// </returns> public static ExpressionItemWidget CreateWidget(ExpressionItem item, IExpressionItemContainer container) { ExpressionItemWidget widget = null; if (item.GetType() == typeof(ExpressionGroupItem)) { widget = new ExpressionGroupWidget(container); } else if (item.GetType() == typeof(ExpressionTokenItem)) { widget = new ExpressionTokenWidget(container); } if (item.GetType() == typeof(ExpressionRuleCallItem)) { widget = new ExpressionRuleCallWidget(container); } widget.ExpressionItem = item; return(widget); }
public static IEnumerable <Column> GetColumns(this ExpressionItem root) { switch (root.ExpressionType) { case ExpressionItemType.Operator: var oper = root as ExpressionOperator; if (oper != null) { foreach (var col in GetColumns(oper.Left).Concat(GetColumns(oper.Right))) { yield return(col); } } break; case ExpressionItemType.Operand: var column = root as ColumnOperand; if (column != null) { yield return(column.Column); } break; } }
/// <summary> /// Creates a widget based on the type of the item pased. /// </summary> /// <param name="item"> /// The <see cref="ExpressionItem"/> that will be contained in the /// widget. /// </param> /// <param name="container"> /// The container holding the new widget. /// </param> /// <returns> /// The widget holding the given item. /// </returns> public static ExpressionItemWidget CreateWidget(ExpressionItem item, IExpressionItemContainer container) { ExpressionItemWidget widget = null; if(item.GetType() == typeof(ExpressionGroupItem)) { widget= new ExpressionGroupWidget(container); } else if(item.GetType() == typeof(ExpressionTokenItem)) { widget = new ExpressionTokenWidget(container); } if(item.GetType() == typeof(ExpressionRuleCallItem)) { widget = new ExpressionRuleCallWidget(container); } widget.ExpressionItem = item; return widget; }
public List <ExpressionItem> InfixToPostfix(List <ExpressionItem> infixExp) { //http://aliev.me/runestone/BasicDS/InfixPrefixandPostfixExpressions.html //https://habr.com/ru/post/489744/ Stack <ExpressionItem> stack = new Stack <ExpressionItem>(); Queue <ExpressionItem> queue = new Queue <ExpressionItem>(); foreach (ExpressionItem item in infixExp) { switch (item.Type) { case ItemType.Number: queue.Enqueue(item); break; case ItemType.Operation: if (GetPriority(item) == 0) { stack.Push(item); } else { int currentPriority = GetPriority(item); while (stack.Count > 0 && (stack.Peek().Type == ItemType.Operation && GetPriority(stack.Peek()) == 0 || GetPriority(stack.Peek()) > currentPriority)) { queue.Enqueue(stack.Pop()); } stack.Push(item); } break; case ItemType.Bracket: if (item.BraketType == Bracket.LeftBracket) { stack.Push(item); } else { ExpressionItem el = stack.Pop(); while (el.BraketType != Bracket.LeftBracket) { queue.Enqueue(el); if (stack.Count == 0) { throw new Exception(); } el = stack.Pop(); } } break; } } while (stack.Count != 0) { queue.Enqueue(stack.Pop()); } return(queue.ToList()); }
public ColumnsWhere(ExpressionItem root = null) { Root = root; }
/// <summary> /// Add the next item to the expression tree. /// </summary> /// <param name="topNode">The top node of the tree.</param> private void AddNextToTree(ref ExpressionItem topNode) { //Get the next item. If the next item is an operator, //find the possible configurations and try to add it to the tree. ExpressionItem next = NextItem(); if (next is OperatorItem && HasNext()) { int nrOfParameters = 2; OperatorConfiguration[] configs = ((OperatorItem)next).AcceptedConfigurations; OperatorConfiguration oc; ExpressionItem rightParam = Peek(); ExpressionItem leftParam = scannedItems[scannedItems.Count - 2]; ExpressionItem[] param = new ExpressionItem[nrOfParameters]; param[0] = leftParam; param[1] = rightParam; bool result = false; //Find the correct configuration. for (int i = 0; i < configs.Length; i++) { if (configs[i].NrOfParameters == nrOfParameters && ((OperatorItem)next).SuggestParameters(param, out oc)) { ((OperatorItem)next).Configuration = configs[i]; result = true; break; } } if (result) { //The parameters were accepted as is and the item can be addd to the tree. AddToTree(ref topNode, next); } else { //The parameters were not accepted, negotiate config. Negotiate(ref topNode, next, param); } } //The current item is an operator, but no items to the right of it. //Try to add it as unary operator. else if (next is OperatorItem) { int nrOfParameters = 1; OperatorConfiguration[] configs = ((OperatorItem)next).AcceptedConfigurations; OperatorConfiguration config = new OperatorConfiguration(Associativity.right, 1); OperatorConfiguration oc; ExpressionItem leftParam = scannedItems[scannedItems.Count - 2]; ExpressionItem[] param = new ExpressionItem[nrOfParameters]; param[0] = leftParam; bool result = false; for (int i = 0; i < configs.Length; i++) { if (configs[i].Equals(config) && ((OperatorItem)next).SuggestParameters(param, out oc)) { //The configuration were accepted ((OperatorItem)next).Configuration = configs[i]; result = true; break; } } if (result) { //Add the opeartor to the tree AddToTree(ref topNode, next); } else { //The operator wouldn't accept to be unary, throw exception throw new Exception("Interpreter.AddNextToTree()1: Cannot form expression"); } } else { //The next item is not an operator, //the tree is valid, but the next item can't be linked to the tree. throw new Exception("Interpreter.AddNextToTree()2: Cannot form expression"); } }
public static void PrepareReport(Report nreport, DataGridView ngrid, DataGridViewPrintOptions opts) { const int DefaultScreenDPI = 142; int BOOL_WIDTH = 100; int BOOL_SEP = 20; if (nreport.SubReports[0].Sections.Count == 1) { nreport.SubReports[0].AddGroup("TOTAL"); } Section Detail = nreport.SubReports[0].Sections[nreport.SubReports[0].FirstDetail]; Section GroupHeader = nreport.SubReports[0].Sections[nreport.SubReports[0].FirstDetail - 1]; Section GroupFooter = nreport.SubReports[0].Sections[nreport.SubReports[0].LastDetail + 1]; string aliasname = nreport.DataInfo[0].Alias; int totalwidth = Detail.Width; int rowcount = ngrid.Rows.Count; if (opts.PrintSelected) { rowcount = ngrid.SelectedRows.Count; } SortedList <string, DataGridViewColumn> CampoColumna = new SortedList <string, DataGridViewColumn>(); List <DataGridViewColumn> Columnas = new List <DataGridViewColumn>(); SortedList <int, DataGridViewColumn> ColumnasString = new SortedList <int, DataGridViewColumn>(); SortedList <int, DataGridViewColumn> ColumnasBool = new SortedList <int, DataGridViewColumn>(); SortedList <int, DataGridViewColumn> ColumnasImage = new SortedList <int, DataGridViewColumn>(); List <string> Campos = new List <string>(); int idxcol = 0; if (opts.SelectedColumns.Count == 0) { foreach (DataGridViewColumn ncol in ngrid.Columns) { if (ncol.Visible) { Columnas.Add(ncol); idxcol++; CampoColumna.Add("CAMPO" + idxcol.ToString(), ncol); Campos.Add("CAMPO" + idxcol.ToString()); } } } else { foreach (DataGridViewColumn ncol in opts.SelectedColumns) { Columnas.Add(ncol); idxcol++; CampoColumna.Add("CAMPO" + idxcol.ToString(), ncol); Campos.Add("CAMPO" + idxcol.ToString()); } } int separator = 40; int level_separator = 200; int level_separator_gap = 50; // Calculate total width for the selected int maxwidth = 0; float screendpi = GraphicUtils.ScreenDPI(); float scalepixels = 1440f / screendpi; for (idxcol = 0; idxcol < Columnas.Count; idxcol++) { DataGridViewColumn ncol = Columnas[idxcol]; int newwidth = System.Convert.ToInt32(Math.Round(ncol.Width * scalepixels)); maxwidth = maxwidth + newwidth; if (idxcol < (Columnas.Count - 1)) { maxwidth = maxwidth + separator; } } List <ShapeItem> HorzShapes = new List <ShapeItem>(); int pagewidth = opts.PaperWidth(); pagewidth = pagewidth - nreport.LeftMargin - nreport.RightMargin; float fsize = ngrid.Font.Size; float fontscale = 1.0f; float scalesep = 1.0f; float newscale = 1.0f; if (opts.AdjustWidth) { newscale = (float)pagewidth / maxwidth; scalepixels = 1440f / screendpi * newscale; scalesep = newscale; if (maxwidth > pagewidth) { fontscale = newscale; fsize = fsize * fontscale; if (fsize <= 0) { fsize = 1; } } } // Calculate font size and width scale int rowheight = System.Convert.ToInt32(Math.Round(ngrid.RowTemplate.Height * scalepixels)); BOOL_WIDTH = System.Convert.ToInt32(BOOL_WIDTH * fontscale); BOOL_SEP = System.Convert.ToInt32(BOOL_SEP * fontscale); separator = System.Convert.ToInt32(separator * fontscale); level_separator = System.Convert.ToInt32(level_separator * fontscale); level_separator_gap = System.Convert.ToInt32(level_separator_gap * fontscale); GroupHeader.Height = rowheight; Detail.Height = rowheight; // Prepare datatable DataTable ntable = new DataTable(); idxcol = 0; int posx = 0; // Grey header ShapeItem sitem = new ShapeItem(nreport); sitem.Shape = ShapeType.Rectangle; sitem.BrushStyle = BrushType.Solid; sitem.PenStyle = Reportman.Drawing.PenType.Clear; sitem.BrushColor = GraphicUtils.IntegerFromColor(Color.FromArgb(200, 200, 200)); sitem.Height = rowheight; sitem.Align = PrintItemAlign.TopBottom; HorzShapes.Add(sitem); nreport.GenerateNewName(sitem); GroupHeader.Components.Add(sitem); sitem = new ShapeItem(nreport); sitem.Shape = ShapeType.VertLine; sitem.Height = rowheight; sitem.Align = PrintItemAlign.TopBottom; nreport.GenerateNewName(sitem); GroupHeader.Components.Add(sitem); if (opts.DrawBackGroundColors) { // Background color sitem = new ShapeItem(nreport); sitem.PrintCondition = aliasname + ".BACKCOLOR<>NULL"; sitem.BrushColorExpression = aliasname + ".BACKCOLOR"; sitem.Shape = ShapeType.Rectangle; sitem.Width = maxwidth; sitem.PenStyle = Reportman.Drawing.PenType.Clear; sitem.PosX = posx; sitem.Align = PrintItemAlign.TopBottom; Detail.Components.Add(sitem); HorzShapes.Add(sitem); } sitem = new ShapeItem(nreport);; sitem.Shape = ShapeType.HorzLine; sitem.Width = maxwidth; HorzShapes.Add(sitem); nreport.GenerateNewName(sitem); GroupHeader.Components.Add(sitem); sitem = new ShapeItem(nreport);; sitem.Shape = ShapeType.HorzLine; sitem.Width = maxwidth; HorzShapes.Add(sitem); nreport.GenerateNewName(sitem); GroupFooter.Components.Add(sitem); sitem = new ShapeItem(nreport);; sitem.Shape = ShapeType.HorzLine; sitem.Width = maxwidth; HorzShapes.Add(sitem); sitem.Align = PrintItemAlign.Bottom; nreport.GenerateNewName(sitem); GroupHeader.Components.Add(sitem); if (opts.VerticalLines) { sitem = new ShapeItem(nreport); sitem.Shape = ShapeType.VertLine; sitem.Height = rowheight; sitem.Align = PrintItemAlign.TopBottom; nreport.GenerateNewName(sitem); Detail.Components.Add(sitem); } string columnlevel = ""; for (idxcol = 0; idxcol < Columnas.Count; idxcol++) { DataGridViewColumn ncol = Columnas[idxcol]; DataGridViewContentAlignment cellalign = DataGridViewContentAlignment.NotSet; if (ngrid.DefaultCellStyle != null) { cellalign = ngrid.DefaultCellStyle.Alignment; } if (ncol.DefaultCellStyle != null) { cellalign = ncol.DefaultCellStyle.Alignment; } LabelItem litem = new LabelItem(nreport); SetAlignFromCellFormat(cellalign, litem); litem.VAlignment = TextAlignVerticalType.Top; if (litem.Alignment == TextAlignType.Left) { litem.Alignment = TextAlignType.Justify; } litem.Height = rowheight; litem.FontSize = System.Convert.ToInt16(fsize); nreport.GenerateNewName(litem); litem.Text = ncol.HeaderText; GroupHeader.Components.Add(litem); litem.Height = rowheight; litem.PosX = posx; litem.WordWrap = opts.WordWrap; litem.CutText = !opts.WordWrap; litem.Width = System.Convert.ToInt32(Math.Round(ncol.Width * scalepixels)); bool istextcolumn = false; istextcolumn = ncol is DataGridViewTextBoxColumn; if (!istextcolumn) { if (ncol is DataGridViewColumnAdvanced) { istextcolumn = true; } } TreeGridAdvanced ngridav; if (istextcolumn) { ntable.Columns.Add(Campos[idxcol], System.Type.GetType("System.String")); ColumnasString.Add(idxcol, ncol); if ((ncol is TreeGridAdvancedColumn) && (ngrid is TreeGridAdvanced)) { if (columnlevel == "") { columnlevel = "LEVEL"; } ngridav = (TreeGridAdvanced)ngrid; for (int idxlevel = 1; idxlevel <= ngridav.MaxLevel; idxlevel++) { // Add Image for level ImageItem imaitem = new ImageItem(nreport); imaitem.Expression = aliasname + ".IMAGE"; imaitem.PrintCondition = aliasname + ".LEVEL=" + idxlevel.ToString(); imaitem.Height = rowheight; imaitem.Align = PrintItemAlign.TopBottom; imaitem.Width = level_separator; imaitem.PosX = level_separator_gap + posx + level_separator * (idxlevel) - level_separator + level_separator_gap; imaitem.PosY = 0; imaitem.DrawStyle = ImageDrawStyleType.Full; imaitem.dpires = System.Convert.ToInt32(DefaultScreenDPI); nreport.GenerateNewName(imaitem); Detail.Components.Add(imaitem); // Add expression foreach level ExpressionItem exitem = new ExpressionItem(nreport); exitem.Expression = aliasname + "." + Campos[idxcol]; exitem.PrintCondition = aliasname + ".LEVEL=" + idxlevel.ToString(); exitem.WordWrap = opts.WordWrap; exitem.CutText = !opts.WordWrap; SetAlignFromCellFormat(cellalign, exitem); if (exitem.Alignment == TextAlignType.Left) { exitem.Alignment = TextAlignType.Justify; } exitem.VAlignment = TextAlignVerticalType.Top; exitem.FontSize = System.Convert.ToInt16(fsize); exitem.Height = rowheight; exitem.PosX = level_separator_gap * 2 + posx + level_separator * idxlevel; exitem.Height = rowheight; nreport.GenerateNewName(exitem); exitem.Width = litem.Width - level_separator * (idxlevel + 1); Detail.Components.Add(exitem); if (opts.DrawTreeLines) { // Last child line sitem = new ShapeItem(nreport); sitem.PrintCondition = "((" + aliasname + ".LEVEL=" + idxlevel.ToString() + ") AND (" + aliasname + ".LASTCHILD))"; sitem.Shape = ShapeType.VertLine; sitem.PenStyle = Reportman.Drawing.PenType.Dot; sitem.PosX = level_separator_gap + posx + level_separator * idxlevel - level_separator; sitem.Height = rowheight / 3; Detail.Components.Add(sitem); // Not last child horz line sitem = new ShapeItem(nreport); sitem.PrintCondition = "((" + aliasname + ".LEVEL=" + idxlevel.ToString() + ") AND (NOT (" + aliasname + ".LASTCHILD)))"; sitem.Shape = ShapeType.VertLine; sitem.PenStyle = Reportman.Drawing.PenType.Dot; sitem.PosX = level_separator_gap + posx + level_separator * idxlevel - level_separator; sitem.Align = PrintItemAlign.TopBottom; Detail.Components.Add(sitem); // Other parent lines sitem = new ShapeItem(nreport); sitem.PrintCondition = aliasname + ".LEVEL>" + idxlevel.ToString(); sitem.Shape = ShapeType.VertLine; sitem.Align = PrintItemAlign.TopBottom; sitem.PenStyle = Reportman.Drawing.PenType.Dot; sitem.PosX = level_separator_gap + posx + level_separator * idxlevel - level_separator; sitem.Height = rowheight / 2; Detail.Components.Add(sitem); // Horz arrow sitem = new ShapeItem(nreport); sitem.PrintCondition = aliasname + ".LEVEL=" + idxlevel.ToString(); sitem.PenStyle = Reportman.Drawing.PenType.Dot; sitem.Shape = ShapeType.HorzLine; sitem.PosX = level_separator_gap + posx + level_separator * idxlevel - level_separator; sitem.PosY = rowheight / 3; sitem.Width = level_separator / 2; Detail.Components.Add(sitem); } } } else { ExpressionItem exitem = new ExpressionItem(nreport); exitem.Expression = aliasname + "." + Campos[idxcol]; exitem.WordWrap = opts.WordWrap; exitem.CutText = !opts.WordWrap; SetAlignFromCellFormat(cellalign, exitem); if (exitem.Alignment == TextAlignType.Left) { exitem.Alignment = TextAlignType.Justify; } exitem.VAlignment = TextAlignVerticalType.Top; exitem.FontSize = System.Convert.ToInt16(fsize); exitem.Height = rowheight; exitem.PosX = posx; exitem.Height = rowheight; nreport.GenerateNewName(exitem); exitem.Width = litem.Width; Detail.Components.Add(exitem); } } else { if (ncol is DataGridViewImageColumn) { ColumnasImage.Add(idxcol, ncol); ntable.Columns.Add(Campos[idxcol], System.Type.GetType("System.Object")); ImageItem imaitem = new ImageItem(nreport); imaitem.Expression = aliasname + "." + Campos[idxcol]; imaitem.Height = rowheight; imaitem.Align = PrintItemAlign.TopBottom; imaitem.Width = litem.Width; imaitem.PosX = posx + separator; imaitem.PosY = 0; imaitem.DrawStyle = ImageDrawStyleType.Full; imaitem.dpires = System.Convert.ToInt32(DefaultScreenDPI); nreport.GenerateNewName(imaitem); Detail.Components.Add(imaitem); } else if (ncol is DataGridViewCheckBoxColumn) { ColumnasBool.Add(idxcol, ncol); ntable.Columns.Add(Campos[idxcol], System.Type.GetType("System.Boolean")); ShapeItem cuaditem = new ShapeItem(nreport); cuaditem.Shape = ShapeType.Rectangle; cuaditem.PrintCondition = aliasname + "." + Campos[idxcol] + "<>NULL"; //cuaditem.Align = PrintItemAlign.TopBottom; cuaditem.BrushStyle = BrushType.Clear; cuaditem.Height = rowheight; int shapepos = posx + (litem.Width / 2) - BOOL_WIDTH / 2; cuaditem.PosX = shapepos; cuaditem.PosY = BOOL_SEP; cuaditem.Width = BOOL_WIDTH; cuaditem.Height = BOOL_WIDTH; nreport.GenerateNewName(cuaditem); Detail.Components.Add(cuaditem); cuaditem = new ShapeItem(nreport); cuaditem.Shape = ShapeType.Oblique1; cuaditem.PrintCondition = aliasname + "." + Campos[idxcol]; //cuaditem.Align = PrintItemAlign.TopBottom; cuaditem.BrushStyle = BrushType.Clear; cuaditem.Height = rowheight; cuaditem.PosX = shapepos; cuaditem.PosY = BOOL_SEP; cuaditem.Width = BOOL_WIDTH; cuaditem.Height = BOOL_WIDTH; nreport.GenerateNewName(cuaditem); Detail.Components.Add(cuaditem); cuaditem = new ShapeItem(nreport); cuaditem.Shape = ShapeType.Oblique2; cuaditem.PrintCondition = aliasname + "." + Campos[idxcol]; //cuaditem.Align = PrintItemAlign.TopBottom; cuaditem.BrushStyle = BrushType.Clear; cuaditem.Height = rowheight; cuaditem.PosX = shapepos; cuaditem.PosY = BOOL_SEP; cuaditem.Width = BOOL_WIDTH; cuaditem.Height = BOOL_WIDTH; nreport.GenerateNewName(cuaditem); Detail.Components.Add(cuaditem); } else { throw new Exception("Tipo de columna no soportada:" + ncol.GetType().ToString()); } } posx = posx + litem.Width; posx = posx + System.Convert.ToInt32(separator * scalesep); if (opts.VerticalLines) { sitem = new ShapeItem(nreport); sitem.Shape = ShapeType.VertLine; sitem.PosX = posx; sitem.Height = rowheight; sitem.Align = PrintItemAlign.TopBottom; Detail.Components.Add(sitem); } sitem = new ShapeItem(nreport); sitem.Shape = ShapeType.VertLine; sitem.PosX = posx; sitem.Height = rowheight; sitem.Align = PrintItemAlign.TopBottom; GroupHeader.Components.Add(sitem); if (opts.HorizontalLines) { sitem = new ShapeItem(nreport); sitem.Shape = ShapeType.HorzLine; sitem.Width = maxwidth; HorzShapes.Add(sitem); //sitem.Align = PrintItemAlign.Top; Detail.Components.Add(sitem); sitem = new ShapeItem(nreport); sitem.PrintCondition = "CURRENTGROUP=0"; sitem.Shape = ShapeType.HorzLine; sitem.Width = maxwidth; HorzShapes.Add(sitem); sitem.Align = PrintItemAlign.Bottom; Detail.Components.Add(sitem); } } foreach (ShapeItem nshape in HorzShapes) { nshape.Width = posx; } int colbackground = 0; if (opts.DrawBackGroundColors) { ntable.Columns.Add("BACKCOLOR", System.Type.GetType("System.Int32")); colbackground = ntable.Columns.Count - 1; } if (columnlevel != "") { ntable.Columns.Add("IMAGE", System.Type.GetType("System.Object")); ntable.Columns.Add("LEVEL", System.Type.GetType("System.Int32")); ntable.Columns.Add("LASTCHILD", System.Type.GetType("System.Boolean")); } object[] nvalues = new object[ntable.Columns.Count]; int counter = 0; foreach (DataGridViewRow dgrow in ngrid.Rows) { if ((!opts.PrintSelected) || ((opts.PrintSelected) && (dgrow.Selected))) { foreach (int index in ColumnasString.Keys) { nvalues[index] = dgrow.Cells[ColumnasString[index].Index].FormattedValue; } foreach (int index in ColumnasBool.Keys) { nvalues[index] = dgrow.Cells[ColumnasBool[index].Index].Value; } foreach (int index in ColumnasImage.Keys) { MemoryStream mstream = GetImageStreamFromObject(dgrow.Cells[ColumnasImage[index].Index].Value); if (mstream != null) { nvalues[index] = mstream; } else { nvalues[index] = DBNull.Value; } } if (opts.DrawBackGroundColors) { DataGridViewCellStyle nstyle = null; if (!dgrow.DefaultCellStyle.BackColor.IsEmpty) { nstyle = dgrow.DefaultCellStyle; } if (nstyle == null) { if ((!ngrid.AlternatingRowsDefaultCellStyle.BackColor.IsEmpty)) { if (counter % 2 == 1) { nstyle = ngrid.AlternatingRowsDefaultCellStyle; } else if (!ngrid.DefaultCellStyle.BackColor.IsEmpty) { nstyle = ngrid.DefaultCellStyle; } } else { if (!ngrid.DefaultCellStyle.BackColor.IsEmpty) { nstyle = ngrid.AlternatingRowsDefaultCellStyle; } } } nvalues[colbackground] = DBNull.Value; if (nstyle != null) { if (nstyle.BackColor != Color.White) { if (nstyle.BackColor != Color.FromArgb(255, 255, 255)) { nvalues[colbackground] = GraphicUtils.IntegerFromColor(nstyle.BackColor); } } } } if (columnlevel.Length > 0) { TreeGridRow trow = (TreeGridRow)dgrow; MemoryStream mstream = GetImageStreamFromObject(trow.Image); if (mstream != null) { nvalues[nvalues.Length - 3] = mstream; } nvalues[nvalues.Length - 2] = trow.Level; nvalues[nvalues.Length - 1] = trow.IsLastSibling; /* * if (trow.Parent != null) * nvalues[nvalues.Length - 1] = ((trow.Node.Childs.Count == 0) || (!trow.Node.Expanded)) && (((TreeGridRow)dgrow).ChildIndex + 1) == ((TreeGridRow)dgrow).Parent.Node.Childs.Count; * else * { * nvalues[nvalues.Length - 1] = ((trow.Node.Childs.Count == 0) || (!trow.Node.Expanded)) && (((TreeGridAdvanced)ngrid).MainNode.Childs.Count == trow.ChildIndex + 1); * }*/ } ntable.Rows.Add(nvalues); counter++; } } nreport.DataInfo[aliasname].DataViewOverride = new DataView(ntable); //return meta; }