// Adds child parts and generates content of the specified part.
        public static void CreateTable(WorkbookPart workbookPart, WorksheetPart worksheetPart, string[] columns, int topLeftColumn, int topLeftRow, int width, int height)
        {
            List<WorksheetPart> worksheets = workbookPart.GetPartsOfType<WorksheetPart>().ToList();
            uint maxTableId = worksheets.Select(ws => ws.TableDefinitionParts.ToList()).SelectMany(tableDefinitions => tableDefinitions).Aggregate<TableDefinitionPart, uint>(0, (current, tableDef) => Math.Max(tableDef.Table.Id, current));

            uint tableId = maxTableId + 1;

            var tables = new TableParts { Count = 1U };
            worksheetPart.Worksheet.Append((IEnumerable<OpenXmlElement>)tables);

            var newTableDefnPart = worksheetPart.AddNewPart<TableDefinitionPart>();
            string relationshipId = worksheetPart.GetIdOfPart(newTableDefnPart);

            string cellReference = string.Format("{0}{1}:{2}{3}", GetColumnIdentifier(topLeftColumn), topLeftRow, GetColumnIdentifier(topLeftColumn + width - 1), topLeftRow + height);
            var table1 = new Table { Id = tableId, Name = "Table" + relationshipId, DisplayName = "Table" + relationshipId, Reference = cellReference, TotalsRowShown = false };
            var autoFilter1 = new AutoFilter { Reference = cellReference };

            var tableColumns1 = new TableColumns { Count = (uint)columns.Length };
            for (int iColumn = 0; iColumn < columns.Length; iColumn++)
            {
                var tableColumn = new TableColumn { Id = (UInt32Value)(uint)iColumn + 1, Name = columns[iColumn] };
                tableColumns1.Append((IEnumerable<OpenXmlElement>)tableColumn);
            }
            var tableStyleInfo1 = new TableStyleInfo { Name = "TableStyleMedium2", ShowFirstColumn = false, ShowLastColumn = false, ShowRowStripes = true, ShowColumnStripes = false };

            table1.Append((IEnumerable<OpenXmlElement>)autoFilter1);
            table1.Append((IEnumerable<OpenXmlElement>)tableColumns1);
            table1.Append((IEnumerable<OpenXmlElement>)tableStyleInfo1);

            newTableDefnPart.Table = table1;

            var table = new TablePart { Id = relationshipId };
            tables.Append((IEnumerable<OpenXmlElement>)table);

            //TableStyles tableStyles1 = new TableStyles() { Count = (UInt32Value)0U, DefaultTableStyle = "TableStyleMedium2", DefaultPivotStyle = "PivotStyleMedium9" };
            //worksheetPart.Worksheet.Append(tableStyles1);
        }
Example #2
0
        public void AddTable(string tableName, params string[] headers)
        {
            var table = new Table
                            {
                                CellSpacing = 0,
                                BorderThickness = new Thickness(0.5, 0.5, 0, 0),
                                BorderBrush = Brushes.Black

                            };

            Document.Blocks.Add(table);
            Tables.Add(tableName, table);

            var lengths = ColumnLengths.ContainsKey(tableName)
                ? ColumnLengths[tableName]
                : new[] { GridLength.Auto, GridLength.Auto, new GridLength(1, GridUnitType.Star) };

            for (var i = 0; i < headers.Count(); i++)
            {
                var c = new TableColumn { Width = lengths[i] };
                table.Columns.Add(c);
            }

            var rows = new TableRowGroup();
            table.RowGroups.Add(rows);
            rows.Rows.Add(CreateRow(headers, new[] { TextAlignment.Center }, true));
        }
Example #3
0
        internal void FromTableColumn(TableColumn tc)
        {
            this.SetAllNull();

            if (tc.CalculatedColumnFormula != null)
            {
                this.HasCalculatedColumnFormula = true;
                this.CalculatedColumnFormula.FromCalculatedColumnFormula(tc.CalculatedColumnFormula);
            }
            if (tc.TotalsRowFormula != null)
            {
                this.HasTotalsRowFormula = true;
                this.TotalsRowFormula.FromTotalsRowFormula(tc.TotalsRowFormula);
            }
            if (tc.XmlColumnProperties != null)
            {
                this.HasXmlColumnProperties = true;
                this.XmlColumnProperties.FromXmlColumnProperties(tc.XmlColumnProperties);
            }

            this.Id = tc.Id.Value;
            if (tc.UniqueName != null) this.UniqueName = tc.UniqueName.Value;
            this.Name = tc.Name.Value;

            if (tc.TotalsRowFunction != null) this.TotalsRowFunction = tc.TotalsRowFunction.Value;
            if (tc.TotalsRowLabel != null) this.TotalsRowLabel = tc.TotalsRowLabel.Value;
            if (tc.QueryTableFieldId != null) this.QueryTableFieldId = tc.QueryTableFieldId.Value;
            if (tc.HeaderRowDifferentialFormattingId != null) this.HeaderRowDifferentialFormattingId = tc.HeaderRowDifferentialFormattingId.Value;
            if (tc.DataFormatId != null) this.DataFormatId = tc.DataFormatId.Value;
            if (tc.TotalsRowDifferentialFormattingId != null) this.TotalsRowDifferentialFormattingId = tc.TotalsRowDifferentialFormattingId.Value;
            if (tc.HeaderRowCellStyle != null) this.HeaderRowCellStyle = tc.HeaderRowCellStyle.Value;
            if (tc.DataCellStyle != null) this.DataCellStyle = tc.DataCellStyle.Value;
            if (tc.TotalsRowCellStyle != null) this.TotalsRowCellStyle = tc.TotalsRowCellStyle.Value;
        }
Example #4
0
        internal static Table BuildTable(int rowCount, 
                                         int columnCount,
                                         Brush borderBrush,
                                         Thickness borderThickness,
                                         double dLineHeight,
                                         TableType tableType)
        {
            Table table = new Table();
            table.Tag = tableType;
            table.CellSpacing = 2;
            table.BorderBrush = borderBrush;
            table.BorderThickness = borderThickness;
            table.MouseEnter += new MouseEventHandler(table_MouseEnter);
            table.MouseLeave += new MouseEventHandler(table_MouseLeave);

            for (int columnIndex = 0; columnIndex < columnCount; columnIndex++)
            {
                TableColumn tableColumn = new TableColumn();
                tableColumn.Width = double.IsNaN(dLineHeight) ? GridLength.Auto : new GridLength(dLineHeight);
                table.Columns.Add(tableColumn);
            }

            TableRowGroup rowGroup = new TableRowGroup();
            for (int rowIndex = 0; rowIndex < rowCount; rowIndex++)
            {
                TableRow row = BuildTableRow(columnCount,borderBrush,borderThickness,dLineHeight);
                rowGroup.Rows.Add(row);
            }
            table.RowGroups.Add(rowGroup);
            return table;
        }
Example #5
0
        private void btnAddTable_Click(object sender, EventArgs e)
        {
            Table table = new Table();
            table.TableName = txtTableName.Text;
            table.MaxScores = spnScore.Value + "";

            TableColumn[] cols = new TableColumn[dgTable.Rows.Count];
            int cnt = 0;
            foreach (DataGridViewRow dgvr in dgTable.Rows)
            {
                String name = dgvr.Cells[0].Value + "";
                if (!name.Equals(""))
                {
                    cols[cnt] = new TableColumn();
                    cols[cnt].ColName = name + "";
                    cols[cnt].DataType = dgvr.Cells[1].Value + "";
                    cols[cnt].Contraint = dgvr.Cells[2].Value + "";
                    cnt++;
                }
            }

            table.Cols = cols;
            TestSuiteDB.saveTable(table);
            MessageBox.Show("Table Details Saved Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.Hide();
        }
Example #6
0
        // Build a table with a given number of rows and columns
        internal static Table UpdateTable(Table table,
                                         int rowCount, 
                                         int columnCount,
                                         Brush borderBrush,
                                         Thickness borderThickness,
                                         double dLineHeight,
                                         TableType tableType)
        {
            table.Tag = tableType;
            table.CellSpacing = 2;
            table.BorderBrush = borderBrush;
            table.BorderThickness = borderThickness;
            table.MouseEnter += new MouseEventHandler(table_MouseEnter);
            table.MouseLeave += new MouseEventHandler(table_MouseLeave);
         
            if (0 >= table.Columns.Count)
            {
                for (int columnIndex = 0; columnIndex < columnCount; columnIndex++)
                {
                    TableColumn tableColumn = new TableColumn();
                    tableColumn.Width = double.IsNaN(dLineHeight) ? GridLength.Auto : new GridLength(dLineHeight);
                    table.Columns.Add(tableColumn);
                }
            }
            else
            {
                foreach (TableColumn tableColumn in table.Columns)
                {
                    tableColumn.Width = double.IsNaN(dLineHeight) ? GridLength.Auto : new GridLength(dLineHeight);
                }
            }

            foreach(TableRowGroup rowGroup in table.RowGroups)
            {
                foreach (TableRow row in rowGroup.Rows)
                {
                    foreach (TableCell cell in row.Cells)
                    {
                        cell.BorderBrush = borderBrush;
                        cell.BorderThickness = borderThickness; 
                    }
                }
            }

            return table;
        }
Example #7
0
        public Grid CreateNewGrid(TableColumn[] tableColumns)
        {
            return (Grid)Invoke(new Func<Grid>(() =>
                {
                    TabPage newPage = new TabPage("Grid " + (tabControl.TabPages.Count + 1));

                    tabControl.TabPages.Add(newPage);

                    DataGridView newDataGridView = new DataGridView
                                                       {
                                                           AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells,
                                                           AllowUserToAddRows = false,
                                                           AllowUserToDeleteRows = false,
                                                           ReadOnly = true,
                                                           RowHeadersVisible = false
                                                       };

                    newPage.Controls.Add(newDataGridView);

                    newDataGridView.Dock = DockStyle.Fill;

                    foreach (var tc in tableColumns)
                    {
                        newDataGridView.Columns.Add(tc.Name, tc.Title);
                    }

                    Grid grid = new Grid()
                    {
                        DataGridView = newDataGridView
                    };

                    _grids.Add(grid);

                    return grid;
                })
            );
        }
Example #8
0
        static void Main()
        {
            // Load XML document
            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.Load(@"sample.xml");

            // Read columns information from XML data
            List <string> columns        = new List <string>();
            XmlNodeList   columnNodeList = xmlDocument.SelectNodes("/Report/Columns/Column");

            foreach (XmlNode node in columnNodeList)
            {
                columns.Add(node.Attributes["Name"].Value);
            }

            // Read row nodes from XML data
            XmlNodeList rowNodeList = xmlDocument.SelectNodes("/Report/ReportData");


            // Create new PDF document
            Document pdfDocument = new Document();

            pdfDocument.RegistrationName = "demo";
            pdfDocument.RegistrationKey  = "demo";
            // Add page
            Page page = new Page(PaperFormat.A4);

            pdfDocument.Pages.Add(page);

            DeviceColor lightGrayColor = new ColorGray(200);
            DeviceColor whiteColor     = new ColorGray(255);


            // Create PDF table
            Table table = new Table();

            table.BackgroundColor = lightGrayColor;

            // Add columns
            for (int c = 0; c < columns.Count; c++)
            {
                TableColumn column = new TableColumn(columns[c], columns[c]);
                // Set column width
                column.Width = (c == 0)? 100 : 60;
                table.Columns.Add(column);
            }

            // Add rows
            foreach (XmlNode rowNode in rowNodeList)
            {
                // Create new row and set its background color
                TableRow row = table.NewRow();
                row.BackgroundColor = whiteColor;

                // Get cell values from XML data
                foreach (XmlNode childNode in rowNode.ChildNodes)
                {
                    // Get cell info from XML data
                    string columnName  = childNode.Name;
                    int    columnIndex = columns.IndexOf(childNode.Name);
                    string cellValue   = childNode.InnerText;

                    // Set cell text
                    row[columnName].Text = cellValue;
                    // Set cell text alignment
                    row[columnName].TextFormat.HorizontalAlign = (columnIndex == 0) ? HorizontalAlign.Left : HorizontalAlign.Right;
                }

                // Add the row to the table
                table.Rows.Add(row);
            }

            // Draw the table on canvas
            page.Canvas.DrawTable(table, 20, 20);


            // Save document to file
            pdfDocument.Save("result.pdf");

            // Cleanup
            pdfDocument.Dispose();

            // Open result document in default associated application (for demo purpose)
            ProcessStartInfo processStartInfo = new ProcessStartInfo("result.pdf");

            processStartInfo.UseShellExecute = true;
            Process.Start(processStartInfo);
        }
        public void Category1_14Test()
        {
            OpenXmlValidator o12Validator = new OpenXmlValidator(FileFormatVersions.Office2007);
            OpenXmlValidator o14Validator = new OpenXmlValidator(FileFormatVersions.Office2010);

            TableColumn column = new TableColumn();

            column.TotalsRowFunction = TotalsRowFunctionValues.Custom;
            Assert.False(ErrorShowsUp(o12Validator.Validate(column), "Attribute 'totalsRowLabel' should be absent when the value of attribute 'totalsRowFunction' is 'custom'."));
            Assert.False(ErrorShowsUp(o14Validator.Validate(column), "Attribute 'totalsRowLabel' should be absent when the value of attribute 'totalsRowFunction' is 'custom'."));

            column.TotalsRowLabel = "somevalue";
            Assert.True(ErrorShowsUp(o12Validator.Validate(column), "Attribute 'totalsRowLabel' should be absent when the value of attribute 'totalsRowFunction' is 'custom'."));
            Assert.True(ErrorShowsUp(o14Validator.Validate(column), "Attribute 'totalsRowLabel' should be absent when the value of attribute 'totalsRowFunction' is 'custom'."));
        }
Example #10
0
 private DbType GetDbType(TableColumn column)
 {
     switch (column.ColumnName)
     {
         case "bit_FLD": return DbType.Boolean;
         case "tinyint_FLD": return DbType.Byte;
         case "smallint_FLD": return DbType.Int16;
         case "int_FLD": return DbType.Int32;
         case "PrimaryKey": return DbType.Int32;
         case "bigint_FLD": return DbType.Int64;
         case "real_FLD": return DbType.Single;
         case "float_FLD": return DbType.Double;
         case "smallmoney_FLD": return DbType.Decimal;
         case "money_FLD": return DbType.Decimal;
         case "decimal_FLD": return DbType.Decimal;
         case "numeric_FLD": return DbType.Decimal;
         case "datetime_FLD": return DbType.DateTime;
         case "smalldatetime_FLD": return DbType.DateTime;
         case "datetime2_FLD": return DbType.DateTime2;
         case "timestamp_FLD": return DbType.Binary;
         case "date_FLD": return DbType.Date;
         case "time_FLD": return DbType.Time;
         case "datetimeoffset_FLD": return DbType.DateTimeOffset;
         case "uniqueidentifier_FLD": return DbType.Guid;
         case "sql_variant_FLD": return DbType.Object;
         case "image_FLD": return DbType.Binary;
         case "varbinary_FLD": return DbType.Binary;
         case "binary_FLD": return DbType.Binary;
         case "char_FLD": return DbType.String;
         case "varchar_FLD": return DbType.String;
         case "text_FLD": return DbType.String;
         case "ntext_FLD": return DbType.String;
         case "nvarchar_FLD": return DbType.String;
         case "nchar_FLD": return DbType.String;
         case "nvarcharmax_FLD": return DbType.String;
         case "varbinarymax_FLD": return DbType.Binary;
         case "varcharmax_FLD": return DbType.String;
         case "xml_FLD": return DbType.Xml;
         default: throw DataStressErrors.UnhandledCaseError(column.ColumnName);
     }
 }
Example #11
0
        public async Task<ContentSaveResult> GenerateChangeScripts(SchemaDesignerInfo schemaDesignerInfo, bool isNew)
        {
            string validateMsg;

            Table table = null;

            try
            {
                bool isValid = this.ValidateModel(schemaDesignerInfo, out validateMsg);

                if (!isValid)
                {
                    return this.GetFaultSaveResult(validateMsg);
                }

                TableDesignerGenerateScriptsData scriptsData = new TableDesignerGenerateScriptsData();

                SchemaInfo schemaInfo = this.GetSchemaInfo(schemaDesignerInfo);

                table = schemaInfo.Tables.First();

                scriptsData.Table = table;               

                List<Script> scripts = new List<Script>();

                if (isNew)
                {
                    ScriptBuilder scriptBuilder = this.scriptGenerator.GenerateSchemaScripts(schemaInfo);

                    scripts.AddRange(scriptBuilder.Scripts);
                }
                else
                {
                    #region Alter Table                   

                    TableDesignerInfo tableDesignerInfo = schemaDesignerInfo.TableDesignerInfo;

                    SchemaInfoFilter filter = new SchemaInfoFilter() { Strict = true };
                    filter.TableNames = new string[] { tableDesignerInfo.OldName };
                    filter.DatabaseObjectType = DatabaseObjectType.Table
                        | DatabaseObjectType.TableColumn
                        | DatabaseObjectType.TablePrimaryKey
                        | DatabaseObjectType.TableForeignKey
                        | DatabaseObjectType.TableIndex
                        | DatabaseObjectType.TableConstraint;

                    if (this.dbInterpreter.DatabaseType == DatabaseType.Oracle)
                    {
                        this.dbInterpreter.Option.IncludePrimaryKeyWhenGetTableIndex = true;
                    }

                    SchemaInfo oldSchemaInfo = await this.dbInterpreter.GetSchemaInfoAsync(filter);
                    Table oldTable = oldSchemaInfo.Tables.FirstOrDefault();

                    if (oldTable == null)
                    {
                        return this.GetFaultSaveResult($"Table \"{tableDesignerInfo.OldName}\" is not existed");
                    }

                    if (tableDesignerInfo.OldName != tableDesignerInfo.Name)
                    {
                        scripts.Add(this.scriptGenerator.RenameTable(new Table() { Owner = tableDesignerInfo.Owner, Name = tableDesignerInfo.OldName }, tableDesignerInfo.Name));
                    }

                    if (!this.IsStringEquals(tableDesignerInfo.Comment, oldTable.Comment))
                    {
                        oldTable.Comment = tableDesignerInfo.Comment;
                        scripts.Add(this.scriptGenerator.SetTableComment(oldTable, string.IsNullOrEmpty(oldTable.Comment)));
                    }

                    #region Columns
                    List<TableColumnDesingerInfo> columnDesingerInfos = schemaDesignerInfo.TableColumnDesingerInfos;
                    List<TableColumn> oldColumns = oldSchemaInfo.TableColumns;

                    List<TableDefaultValueConstraint> defaultValueConstraints = await this.GetTableDefaultConstraints(filter);

                    foreach (TableColumnDesingerInfo columnDesignerInfo in columnDesingerInfos)
                    {
                        TableColumn oldColumn = oldColumns.FirstOrDefault(item => item.Name.ToLower() == columnDesignerInfo.Name.ToLower());
                        TableColumn newColumn = schemaInfo.TableColumns.FirstOrDefault(item => item.Name == columnDesignerInfo.Name);

                        if (oldColumn == null)
                        {
                            scripts.Add(this.scriptGenerator.AddTableColumn(table, newColumn));
                        }
                        else
                        {
                            if (!this.IsValueEqualsIgnoreCase(columnDesignerInfo.OldName, columnDesignerInfo.Name))
                            {
                                scripts.Add(this.scriptGenerator.RenameTableColumn(table, oldColumn, newColumn.Name));
                            }

                            scripts.AddRange(this.GetColumnAlterScripts(oldTable, table, oldColumn, newColumn, defaultValueConstraints));
                        }
                    }

                    foreach (TableColumn oldColumn in oldColumns)
                    {
                        if (!columnDesingerInfos.Any(item => item.Name == oldColumn.Name))
                        {
                            scripts.Add(this.scriptGenerator.DropTableColumn(oldColumn));
                        }
                    }
                    #endregion

                    #region Primary Key
                    TablePrimaryKey oldPrimaryKey = oldSchemaInfo.TablePrimaryKeys.FirstOrDefault();
                    TablePrimaryKey newPrimaryKey = schemaInfo.TablePrimaryKeys.FirstOrDefault();

                    scripts.AddRange(this.GetPrimaryKeyAlterScripts(oldPrimaryKey, newPrimaryKey, schemaDesignerInfo.IgnoreTableIndex));
                    #endregion

                    #region Index
                    if (!schemaDesignerInfo.IgnoreTableIndex)
                    {
                        IEnumerable<TableIndex> oldIndexes = oldSchemaInfo.TableIndexes.Where(item => !item.IsPrimary);

                        IEnumerable<TableIndexDesignerInfo> indexDesignerInfos = schemaDesignerInfo.TableIndexDesingerInfos.Where(item => !item.IsPrimary);

                        foreach (TableIndexDesignerInfo indexDesignerInfo in indexDesignerInfos)
                        {
                            TableIndex newIndex = schemaInfo.TableIndexes.FirstOrDefault(item => item.Name == indexDesignerInfo.Name);

                            TableIndex oldIndex = oldIndexes.FirstOrDefault(item => item.Name == indexDesignerInfo.OldName);

                            if (this.IsValueEqualsIgnoreCase(indexDesignerInfo.OldName, indexDesignerInfo.Name)
                                && this.IsValueEqualsIgnoreCase(indexDesignerInfo.OldType, indexDesignerInfo.Type)
                              )
                            {
                                if (oldIndex != null && this.IsStringEquals(oldIndex.Comment, newIndex.Comment) && SchemaInfoHelper.IsIndexColumnsEquals(oldIndex.Columns, newIndex.Columns))
                                {
                                    continue;
                                }
                            }

                            scripts.AddRange(this.GetIndexAlterScripts(oldIndex, newIndex));
                        }

                        foreach (TableIndex oldIndex in oldIndexes)
                        {
                            if (!indexDesignerInfos.Any(item => item.Name == oldIndex.Name))
                            {
                                scripts.Add(this.scriptGenerator.DropIndex(oldIndex));
                            }
                        }
                    }
                    #endregion

                    #region Foreign Key
                    if (!schemaDesignerInfo.IgnoreTableForeignKey)
                    {
                        List<TableForeignKey> oldForeignKeys = oldSchemaInfo.TableForeignKeys;

                        IEnumerable<TableForeignKeyDesignerInfo> foreignKeyDesignerInfos = schemaDesignerInfo.TableForeignKeyDesignerInfos;

                        foreach (TableForeignKeyDesignerInfo foreignKeyDesignerInfo in foreignKeyDesignerInfos)
                        {
                            TableForeignKey newForeignKey = schemaInfo.TableForeignKeys.FirstOrDefault(item => item.Name == foreignKeyDesignerInfo.Name);

                            TableForeignKey oldForeignKey = oldForeignKeys.FirstOrDefault(item => item.Name == foreignKeyDesignerInfo.OldName);

                            if (this.IsValueEqualsIgnoreCase(foreignKeyDesignerInfo.OldName, foreignKeyDesignerInfo.Name) &&
                                foreignKeyDesignerInfo.UpdateCascade == oldForeignKey.UpdateCascade &&
                                foreignKeyDesignerInfo.DeleteCascade == oldForeignKey.DeleteCascade)
                            {
                                if (oldForeignKey != null && this.IsStringEquals(oldForeignKey.Comment, newForeignKey.Comment)
                                    && SchemaInfoHelper.IsForeignKeyColumnsEquals(oldForeignKey.Columns, newForeignKey.Columns))
                                {
                                    continue;
                                }
                            }

                            scripts.AddRange(this.GetForeignKeyAlterScripts(oldForeignKey, newForeignKey));
                        }

                        foreach (TableForeignKey oldForeignKey in oldForeignKeys)
                        {
                            if (!foreignKeyDesignerInfos.Any(item => item.Name == oldForeignKey.Name))
                            {
                                scripts.Add(this.scriptGenerator.DropForeignKey(oldForeignKey));
                            }
                        }
                    }
                    #endregion

                    #region Constraint
                    if (!schemaDesignerInfo.IgnoreTableConstraint)
                    {
                        List<TableConstraint> oldConstraints = oldSchemaInfo.TableConstraints;

                        IEnumerable<TableConstraintDesignerInfo> constraintDesignerInfos = schemaDesignerInfo.TableConstraintDesignerInfos;

                        foreach (TableConstraintDesignerInfo constraintDesignerInfo in constraintDesignerInfos)
                        {
                            TableConstraint newConstraint = schemaInfo.TableConstraints.FirstOrDefault(item => item.Name == constraintDesignerInfo.Name);

                            TableConstraint oldConstraint = oldConstraints.FirstOrDefault(item => item.Name == constraintDesignerInfo.OldName);

                            if (this.IsValueEqualsIgnoreCase(constraintDesignerInfo.OldName, constraintDesignerInfo.Name))
                            {
                                if (oldConstraint != null && this.IsStringEquals(oldConstraint.Comment, newConstraint.Comment))
                                {
                                    continue;
                                }
                            }

                            scripts.AddRange(this.GetConstraintAlterScripts(oldConstraint, newConstraint));
                        }

                        foreach (TableConstraint oldConstraint in oldConstraints)
                        {
                            if (!constraintDesignerInfos.Any(item => item.Name == oldConstraint.Name))
                            {
                                scripts.Add(this.scriptGenerator.DropCheckConstraint(oldConstraint));
                            }
                        }
                    }
                    #endregion

                    #endregion
                }

                scriptsData.Scripts.AddRange(scripts);

                return new ContentSaveResult() { IsOK = true, ResultData = scriptsData };
            }
            catch (Exception ex)
            {
                return this.GetFaultSaveResult(ExceptionHelper.GetExceptionDetails(ex));
            }
        }
			internal void While(IEnumerable<TriggerAction> stringActions, TableColumn tc)
			{
                int shortest = stringActions.Min(t => t.Trigger.Length);
                if (_index + shortest > _text.Length)
                    return;

                while (_index + shortest < _text.Length)
                {
                    string peek = _text.Substring(_index, shortest);
					
					var shortlist = stringActions.Where( t => t.Trigger.StartsWith( peek ) );

                    while (shortlist.Count() > 1 && _index + shortest < _text.Length)
                    {
                        shortest++;
                        peek = _text.Substring(_index, shortest);


						shortlist = stringActions.Where( t => t.Trigger.StartsWith(peek));
						if (shortlist.Count() == 1)
							break;

						if (shortlist.Count() == 0)	
						{
							shortlist = stringActions.Where( t => t.Trigger == _text.Substring( _index, shortest -1 ) );
							if (shortlist.Count() == 1)
								break;
						}
                    }

                    if (shortlist.Count() != 1)
                        return;

                    var match = shortlist.First();
                    if (!Peek(match.Trigger))
                        return;

                    _index += match.Trigger.Length;

                    // do the action associated with the string
                    match.Action(this, tc);

                    SkipWhitespace();
                }
			}
Example #13
0
 private void OnColumnsListViewItemCheck(object sender, ItemCheckEventArgs e)
 {
     string text = this._columnsListView.Items[e.Index].Text;
     string key = this._tableListBox.Text + "." + text;
     if (e.CurrentValue == CheckState.Unchecked)
     {
         TableColumn column = new TableColumn(this._tableListBox.Text, this._columnsListView.Items[e.Index].Text);
         this.CheckedItems[key] = column;
         if (text == "*")
         {
             for (int i = 1; i < this._columnsListView.Items.Count; i++)
             {
                 if (this._columnsListView.Items[i].Checked)
                 {
                     this._columnsListView.Items[i].Checked = false;
                 }
             }
         }
         else if (this._columnsListView.Items[0].Checked)
         {
             this._columnsListView.Items[0].Checked = false;
         }
     }
     else
     {
         this.CheckedItems.Remove(key);
     }
     this.UpdatePreview();
 }
Example #14
0
        protected override Drawable CreateHeader(int index, TableColumn column)
        {
            var title = column?.Header ?? string.Empty;

            return(new HeaderText(title, title == HighlightedColumn));
        }
Example #15
0
        private void InitializeRetrieveProgressTable(Table <RetrieveProgressResult> table)
        {
            TableColumn <RetrieveProgressResult, string> column;

            column = new TableColumn <RetrieveProgressResult, string>("Status", delegate(RetrieveProgressResult result)
            {
                string msg = string.IsNullOrEmpty(result.ProgressMessage)
                                                                ? null
                                                                : result.ProgressMessage;

                switch (result.Status)
                {
                case RetrieveStatus.Queued:
                    return("Waiting");

                case RetrieveStatus.InProgress:
                    return(msg ?? "Downloading...");

                case RetrieveStatus.Canceled:
                    return("Canceled");

                case RetrieveStatus.Completed:
                    return("Done");

                case RetrieveStatus.CancelRequested:
                    return(string.Format("{0}...Canceling", msg ?? ""));
                }
                return(msg ?? "");
            }, 0.25F);
            table.Columns.Add(column);

            column = new TableColumn <RetrieveProgressResult, string>("Study Count", delegate(RetrieveProgressResult result)
            {
                return(result.QueryItems.Count.ToString());
            }, 0.05F);
            table.Columns.Add(column);

            column = new TableColumn <RetrieveProgressResult, string>("Patient Id", delegate(RetrieveProgressResult result)
            {
                switch (result.QueryItems.Count)
                {
                case 0:
                    break;

                case 1:
                    return(result.QueryItems[0].Patient.PatientId ?? "");

                default:
                    return(string.Format("1. {0}...", result.QueryItems[0].Patient.PatientId ?? ""));
                }
                return("");
            }, 0.25F);
            column.TooltipTextProvider =
                delegate(RetrieveProgressResult result)
            {
                if (result.QueryItems.Count > 1)
                {
                    List <string> tooltipList = new List <string>();
                    int           cnt         = 0;
                    foreach (RetrieveQueryItem queryItem in result.QueryItems)
                    {
                        tooltipList.Add(string.Format("{0}. {1}", ++cnt, queryItem.Patient.PatientId ?? ""));
                    }

                    return(StringUtilities.Combine(tooltipList, "\n"));
                }

                return(result.QueryItems.Count > 0 ? result.QueryItems[0].Patient.PatientId ?? "" : "");
            };
            table.Columns.Add(column);

            column = new TableColumn <RetrieveProgressResult, string>("Patient's Name", delegate(RetrieveProgressResult result)
            {
                switch (result.QueryItems.Count)
                {
                case 0:
                    break;

                case 1:
                    return(result.QueryItems[0].Patient.PatientsName ?? "");

                default:
                    return(string.Format("1. {0}...", result.QueryItems[0].Patient.PatientsName ?? ""));
                }
                return("");
            }, 0.25F);
            column.TooltipTextProvider =
                delegate(RetrieveProgressResult result)
            {
                if (result.QueryItems.Count > 1)
                {
                    List <string> tooltipList = new List <string>();
                    int           cnt         = 0;
                    foreach (RetrieveQueryItem queryItem in result.QueryItems)
                    {
                        tooltipList.Add(string.Format("{0}. {1}", ++cnt, queryItem.Patient.PatientsName ?? ""));
                    }

                    return(StringUtilities.Combine(tooltipList, "\n"));
                }

                return(result.QueryItems.Count > 0 ? result.QueryItems[0].Patient.PatientsName ?? "" : "");
            };
            table.Columns.Add(column);

            column = new TableColumn <RetrieveProgressResult, string>("Study", delegate(RetrieveProgressResult result)
            {
                switch (result.QueryItems.Count)
                {
                case 0:
                    break;

                case 1:
                    return(result.QueryItems[0].Study.StudyInstanceUid ?? "");

                default:
                    return(string.Format("1. {0}...", result.QueryItems[0].Study.StudyInstanceUid ?? ""));
                }
                return("");
            }, 0.25F);
            column.TooltipTextProvider =
                delegate(RetrieveProgressResult result)
            {
                if (result.QueryItems.Count > 1)
                {
                    List <string> tooltipList = new List <string>();
                    int           cnt         = 0;
                    foreach (RetrieveQueryItem queryItem in result.QueryItems)
                    {
                        tooltipList.Add(string.Format("{0}. {1}", ++cnt, queryItem.Study.StudyInstanceUid ?? ""));
                    }

                    return(StringUtilities.Combine(tooltipList, "\n"));
                }

                return(result.QueryItems.Count > 0 ? result.QueryItems[0].Study.StudyInstanceUid ?? "" : "");
            };
            table.Columns.Add(column);
        }
Example #16
0
        private void InitializeTable()
        {
            _table = new TableView <Power>
            {
                Dock    = DockStyle.Fill,
                ToolTip = _tipTooltip
            };
            // create columns
            TableColumn <Power> nameColumn = new TableColumn <Power>(() => new TextTableCell())
            {
                Text      = "Power",
                Extractor = (power => power.CurrentDisplayName),
                Tag       = "String_Power",
                Sorter    = (name1, name2) => string.Compare((string)name1, (string)name2, GlobalOptions.CultureInfo, CompareOptions.Ordinal)
            };

            nameColumn.AddDependency(nameof(Power.CurrentDisplayName));

            TableColumn <Power> actionColumn = new TableColumn <Power>(() => new TextTableCell())
            {
                Text      = "Action",
                Extractor = (power => power.DisplayAction),
                Tag       = "ColumnHeader_Action",
                Sorter    = (action1, action2) => string.Compare((string)action1, (string)action2, GlobalOptions.CultureInfo, CompareOptions.Ordinal)
            };

            actionColumn.AddDependency(nameof(Power.DisplayAction));

            TableColumn <Power> ratingColumn = new TableColumn <Power>(() => new SpinnerTableCell <Power>(_table)
            {
                EnabledExtractor = (p => p.LevelsEnabled),
                MaxExtractor     = (p => Math.Max(p.TotalMaximumLevels - p.FreeLevels, 0)),
                ValueUpdater     = (p, newRating) =>
                {
                    int delta = ((int)newRating) - p.Rating;
                    if (delta != 0)
                    {
                        p.Rating += delta;
                    }
                },
                MinExtractor = (p => 0),
                ValueGetter  = (p => p.Rating),
            })
            {
                Text   = "Rating",
                Tag    = "String_Rating",
                Sorter = (o1, o2) =>
                {
                    if (o1 is Power objPower1 && o2 is Power objPower2)
                    {
                        return(objPower1.Rating - objPower2.Rating);
                    }
                    StringBuilder msg = new StringBuilder("Can't sort an Object of Type ")
                                        .Append(o1.GetType()).Append(" against another one of Type ")
                                        .Append(o2.GetType()).AppendLine(" in the ratingColumn.")
                                        .Append("Both objects SHOULD be of the type \"Power\".");
                    throw new ArgumentException(msg.ToString(), nameof(o1));
                },
            };

            ratingColumn.AddDependency(nameof(Power.LevelsEnabled));
            ratingColumn.AddDependency(nameof(Power.FreeLevels));
            ratingColumn.AddDependency(nameof(Power.TotalMaximumLevels));
            ratingColumn.AddDependency(nameof(Power.TotalRating));
            TableColumn <Power> totalRatingColumn = new TableColumn <Power>(() => new TextTableCell())
            {
                Text      = "Total Rating",
                Extractor = (power => power.TotalRating),
                Tag       = "String_TotalRating",
                Sorter    = (o1, o2) =>
                {
                    if (o1 is Power objPower1 && o2 is Power objPower2)
                    {
                        return(objPower1.TotalRating - objPower2.TotalRating);
                    }
                    StringBuilder msg = new StringBuilder("Can't sort an Object of Type ")
                                        .Append(o1.GetType()).Append(" against another one of Type ")
                                        .Append(o2.GetType()).AppendLine(" in the totalRatingColumn.")
                                        .Append("Both objects SHOULD be of the type \"Power\".");
                    throw new ArgumentException(msg.ToString(), nameof(o1));
                },
            };

            totalRatingColumn.AddDependency(nameof(Power.TotalRating));

            TableColumn <Power> powerPointsColumn = new TableColumn <Power>(() => new TextTableCell())
            {
                Text             = "Power Points",
                Extractor        = (power => power.DisplayPoints),
                Tag              = "ColumnHeader_Power_Points",
                ToolTipExtractor = (item => item.ToolTip)
            };

            powerPointsColumn.AddDependency(nameof(Power.DisplayPoints));
            powerPointsColumn.AddDependency(nameof(Power.ToolTip));

            TableColumn <Power> sourceColumn = new TableColumn <Power>(() => new TextTableCell
            {
                Cursor = Cursors.Hand
            })
            {
                Text             = "Source",
                Extractor        = (power => power.SourceDetail),
                Tag              = "Label_Source",
                ToolTipExtractor = (item => item.SourceDetail.LanguageBookTooltip),
            };

            powerPointsColumn.AddDependency(nameof(Power.Source));

            TableColumn <Power> adeptWayColumn = new TableColumn <Power>(() => new CheckBoxTableCell <Power>
            {
                ValueGetter      = p => p.DiscountedAdeptWay,
                ValueUpdater     = (p, check) => p.DiscountedAdeptWay = check,
                VisibleExtractor = p => p.AdeptWayDiscountEnabled,
                EnabledExtractor = p => (p.CharacterObject.AllowAdeptWayPowerDiscount || p.DiscountedAdeptWay),
                Alignment        = Alignment.Center
            })
            {
                Text = "Adept Way",
                Tag  = "Checkbox_Power_AdeptWay"
            };

            adeptWayColumn.AddDependency(nameof(Power.DiscountedAdeptWay));
            adeptWayColumn.AddDependency(nameof(Power.AdeptWayDiscountEnabled));
            adeptWayColumn.AddDependency(nameof(Character.AllowAdeptWayPowerDiscount));
            adeptWayColumn.AddDependency(nameof(Power.Rating));

            /*
             * TableColumn<Power> geasColumn = new TableColumn<Power>(() => new CheckBoxTableCell<Power>()
             * {
             *  ValueGetter = (p => p.DiscountedGeas),
             *  ValueUpdater = (p, check) => p.DiscountedGeas = check,
             *  Alignment = Alignment.Center
             * })
             * {
             *  Text = "Geas",
             *  Tag = "Checkbox_Power_Geas"
             * };
             * geasColumn.AddDependency(nameof(Power.DiscountedGeas));
             */

            TableColumn <Power> noteColumn = new TableColumn <Power>(() => new ButtonTableCell <Power>(new PictureBox
            {
                Image = Resources.note_edit,
                Size  = GetImageSize(Resources.note_edit),
            })
            {
                ClickHandler = p => {
                    using (frmNotes frmPowerNotes = new frmNotes(p.Notes))
                    {
                        frmPowerNotes.ShowDialog(this);
                        if (frmPowerNotes.DialogResult == DialogResult.OK)
                        {
                            p.Notes = frmPowerNotes.Notes;
                        }
                    }
                },
                Alignment = Alignment.Center
            })
            {
                Text             = "Notes",
                Tag              = "ColumnHeader_Notes",
                ToolTipExtractor = (p => {
                    string strTooltip = LanguageManager.GetString("Tip_Power_EditNotes");
                    if (!string.IsNullOrEmpty(p.Notes))
                    {
                        strTooltip += Environment.NewLine + Environment.NewLine + p.Notes.RtfToPlainText();
                    }
                    return(strTooltip.WordWrap());
                })
            };

            noteColumn.AddDependency(nameof(Power.Notes));

            TableColumn <Power> deleteColumn = new TableColumn <Power>(() => new ButtonTableCell <Power>(new Button
            {
                Text = LanguageManager.GetString("String_Delete"),
                Tag  = "String_Delete",
                Dock = DockStyle.Fill
            })
            {
                ClickHandler = p =>
                {
                    //Cache the parentform prior to deletion, otherwise the relationship is broken.
                    Form frmParent = ParentForm;
                    if (p.FreeLevels > 0)
                    {
                        string strImprovementSourceName = p.CharacterObject.Improvements.FirstOrDefault(x => x.ImproveType == Improvement.ImprovementType.AdeptPowerFreePoints && x.ImprovedName == p.Name && x.UniqueName == p.Extra)?.SourceName;
                        Gear objGear = p.CharacterObject.Gear.FirstOrDefault(x => x.Bonded && x.InternalId == strImprovementSourceName);
                        if (objGear != null)
                        {
                            objGear.Equipped = false;
                            objGear.Extra    = string.Empty;
                        }
                    }
                    p.DeletePower();
                    p.UnbindPower();

                    if (frmParent is CharacterShared objParent)
                    {
                        objParent.IsCharacterUpdateRequested = true;
                    }
                },
                EnabledExtractor = (p => p.FreeLevels == 0)
            });
Example #17
0
        private void InitResultTable(bool isTemplate)
        {
            Matrix.Data.Columns.AddTotalItems(isTemplate);
            Matrix.Data.Rows.AddTotalItems(isTemplate);
            List <MatrixHeaderItem> columnTerminalItems = Matrix.Data.Columns.RootItem.GetTerminalItems();
            List <MatrixHeaderItem> rowTerminalItems    = Matrix.Data.Rows.RootItem.GetTerminalItems();

            // create corner
            List <MatrixDescriptor> descrList = new List <MatrixDescriptor>();

            if (Matrix.ShowTitle)
            {
                descrList.Add(titleDescriptor);
            }
            descrList.AddRange(Matrix.Data.Columns.ToArray());
            if (Matrix.Data.Cells.Count > 1 && Matrix.CellsSideBySide)
            {
                descrList.Add(cellHeaderDescriptor);
            }

            foreach (MatrixDescriptor descr in descrList)
            {
                TableRow row = new TableRow();
                if (descr.TemplateRow != null)
                {
                    row.Assign(descr.TemplateRow);
                }
                ResultTable.Rows.Add(row);
            }

            descrList.Clear();
            descrList.AddRange(Matrix.Data.Rows.ToArray());
            if (Matrix.Data.Cells.Count > 1 && !Matrix.CellsSideBySide)
            {
                descrList.Add(cellHeaderDescriptor);
            }

            foreach (MatrixDescriptor descr in descrList)
            {
                TableColumn column = new TableColumn();
                if (descr.TemplateColumn != null)
                {
                    column.Assign(descr.TemplateColumn);
                }
                ResultTable.Columns.Add(column);
            }

            // determine the body location
            Point bodyLocation = GetBodyLocation();

            // create columns
            foreach (MatrixHeaderItem item in columnTerminalItems)
            {
                foreach (MatrixCellDescriptor descr in Matrix.Data.Cells)
                {
                    TableColumn column = new TableColumn();
                    if (item.TemplateColumn != null && descr.TemplateColumn != null)
                    {
                        column.Assign(Matrix.Columns[item.TemplateColumn.Index + (descr.TemplateColumn.Index - bodyLocation.X)]);
                    }
                    ResultTable.Columns.Add(column);

                    if (!Matrix.CellsSideBySide)
                    {
                        break;
                    }
                }
            }

            // create rows
            foreach (MatrixHeaderItem item in rowTerminalItems)
            {
                foreach (MatrixCellDescriptor descr in Matrix.Data.Cells)
                {
                    TableRow row = new TableRow();
                    if (item.TemplateRow != null && descr.TemplateRow != null)
                    {
                        row.Assign(Matrix.Rows[item.TemplateRow.Index + (descr.TemplateRow.Index - bodyLocation.Y)]);
                    }
                    ResultTable.Rows.Add(row);

                    if (Matrix.CellsSideBySide)
                    {
                        break;
                    }
                }
            }
        }
Example #18
0
        public void Parsing()
        {
            DB db = new DB("MyDB", "admin", "admin");

            TableColumn tc1 = new TableColumn("NombreAdmin");

            TableColumn tc2 = new TableColumn("EdadAdmin");

            TableColumn tc3 = new TableColumn("PerrosAdmin");

            List <TableColumn> tableColumns = new List <TableColumn>()
            {
                tc1, tc2, tc3
            };

            Table table = new Table("DatosAdmin", tableColumns);

            table.AddRow(new List <string>()
            {
                "Gaizka", "22", "Boss&Drogo"
            });
            table.AddRow(new List <string>()
            {
                "Edurne", "22", "Zuri"
            });
            table.AddRow(new List <string>()
            {
                "Iker", "22", "Null"
            });
            table.AddRow(new List <string>()
            {
                "Xabi", "21", "Null"
            });

            TableColumn tc4 = new TableColumn("GG");

            TableColumn tc5 = new TableColumn("WELLPLAY");

            List <TableColumn> tableColumns2 = new List <TableColumn>()
            {
                tc4, tc5
            };

            Table table2 = new Table("AdminRules", tableColumns2);

            table2.AddRow(new List <string>()
            {
                "G", "a"
            });
            table2.AddRow(new List <string>()
            {
                "E", "d"
            });

            db.AddTable(table);
            db.AddTable(table2);

            IQuery query = Parser.Parse("SELECT * FROM DatosAdmin;");

            Assert.IsTrue(query is SelectAll);
            Assert.AreEqual("DatosAdmin", (query as SelectAll).Table());
            Assert.AreEqual(db.RunMiniSqlQuery("SELECT * FROM DatosAdmin;"), table.ToString());

            IQuery query2 = Parser.Parse("INSERT INTO DatosAdmin VALUES ('Tamara','23','Xia');");

            Assert.IsTrue(query2 is Insert);


            IQuery query3 = Parser.Parse("SELECT EdadAdmin FROM DatosAdmin;");

            Assert.IsTrue(query3 is SelectColumns);
            string resultadoSelectColumns = "['EdadAdmin']{'22'}{'22'}{'22'}{'21'}";

            Assert.AreEqual(db.RunMiniSqlQuery("SELECT EdadAdmin FROM DatosAdmin;"), resultadoSelectColumns);

            IQuery query4 = Parser.Parse("SELECT EdadAdmin FROM DatosAdmin WHERE EdadAdmin=21;");

            Assert.IsTrue(query4 is SelectWhere);
            string resultadoSelectWhere = "['EdadAdmin']{'22'}{'22'}{'22'}";

            Assert.AreEqual(resultadoSelectWhere, db.RunMiniSqlQuery("SELECT EdadAdmin FROM DatosAdmin WHERE EdadAdmin=22;"));


            IQuery query5 = Parser.Parse("DROP TABLE DatosAdmin;");

            Assert.IsTrue(query5 is DropTable);
            Assert.IsNotNull(db.FindTableWithName("AdminRules"));
            db.RunMiniSqlQuery("DROP TABLE AdminRules;");
            Assert.AreEqual(-1, db.FindTableWithName("AdminRules")); //Compruebas que ese nombre ya no esta en la database


            IQuery query6 = Parser.Parse("CREATE TABLE Table2 (Nombre,Edad);");

            Assert.IsTrue(query6 is CreateTable);

            db.RunMiniSqlQuery("CREATE TABLE AdminRules (Nombre,Edad);");
            Assert.IsNotNull(db.FindTableWithName("AdminRules"));
            Assert.AreEqual(1, db.FindTableWithName("AdminRules"));
            string resultadoCreateTable = "['Nombre','Edad']";

            Assert.AreEqual(resultadoCreateTable, db.GetTableWithName("AdminRules").ToString());

            db.RunMiniSqlQuery("CREATE TABLE MyTable (Name TEXT,Age INT,Address TEXT);");
            string resultadoCreateTable2 = "['Name','Age','Address']";

            Assert.AreEqual(resultadoCreateTable2, db.GetTableWithName("MyTable").ToString());

            IQuery query7 = Parser.Parse("DELETE FROM Table1 WHERE Edad='21';");

            Assert.IsTrue(query7 is DeleteFrom);


            IQuery query8 = Parser.Parse("SELECT * FROM DatosAdmin WHERE EdadAdmin=22;");

            Assert.IsTrue(query8 is SelectAllWhere);

            IQuery query9 = Parser.Parse("CLOSE;");

            Assert.IsTrue(query9 is Close);


            IQuery query10 = Parser.Parse("UPDATE Employees SET Name='Patxi',Surname='Elorriaga' WHERE Id=2;");

            Assert.IsTrue(query10 is Update);
            db.RunMiniSqlQuery("UPDATE DatosAdmin SET EdadAdmin=24,PerrosAdmin='Kong' WHERE EdadAdmin=21;");
            string resultadoUpdate = "['NombreAdmin','EdadAdmin','PerrosAdmin']{Gaizka,'22',Boss&Drogo}{Edurne,'22',Zuri}{Iker,'22',Null}{Xabi,'24','Kong'}";

            Assert.AreEqual(resultadoUpdate, db.RunMiniSqlQuery("SELECT * FROM DatosAdmin;"));

            IQuery query11 = Parser.Parse("ADD USER ('Eva','1234',Employee);");

            Assert.IsTrue(query11 is AddUser);

            IQuery query12 = Parser.Parse("CREATE SECURITY PROFILE Employee;");

            Assert.IsTrue(query12 is CreateSecurityProfile);

            IQuery query13 = Parser.Parse("DROP SECURITY PROFILE securityProfile;");

            Assert.IsTrue(query13 is DropSecurityProfile);

            IQuery query14 = Parser.Parse("GRANT SELECT ON EmployeesPublic TO Employee;");

            Assert.IsTrue(query14 is Grant);

            IQuery query15 = Parser.Parse("REVOKE privilegeType ON table TO securityProfile;");

            Assert.IsTrue(query15 is Revoke);

            IQuery query16 = Parser.Parse("DELETE USER user;");

            Assert.IsTrue(query16 is DeleteUser);

            IQuery query17 = Parser.Parse("Database1,admin,admin");

            Assert.IsTrue(query17 is Login);
        }
Example #19
0
 protected sealed override Drawable CreateHeader(int index, TableColumn column)
 => (column as RankingsTableColumn)?.CreateHeaderText() ?? new HeaderText(column?.Header ?? default, false);
Example #20
0
        private string GetColumnText(DbInterpreter dbInterpreter, Table table, TableColumn column)
        {
            string text = dbInterpreter.ParseColumn(table, column).Replace(dbInterpreter.QuotationLeftChar.ToString(), "").Replace(dbInterpreter.QuotationRightChar.ToString(), "");

            return($"{column.Name} ({text.Replace(column.Name + " ", "").ToLower().Trim()})");
        }
Example #21
0
        /// <summary>
        /// Processes the information about table columns - COLGROUP and COL html elements.
        /// </summary>
        /// <param name="htmlTableElement">
        /// XmlElement representing a source html table.
        /// </param>
        /// <param name="xamlTableElement">
        /// XmlElement repesenting a resulting xaml table.
        /// </param>
        /// <param name="columnStartsAllRows">
        /// Array of doubles - column start coordinates.
        /// Can be null, which means that column size information is not available
        /// and we must use source colgroup/col information.
        /// In case wneh it's not null, we will ignore source colgroup/col information.
        /// </param>
        /// <param name="currentProperties"></param>
        /// <param name="stylesheet"></param>
        /// <param name="sourceContext"></param>
        private void AddColumnInformation(Table current, XmlElement htmlTableElement, ArrayList columnStartsAllRows, Hashtable currentProperties, CssStylesheet stylesheet)
        {
            // Add column information
            if (columnStartsAllRows != null)
            {
                // We have consistent information derived from table cells; use it
                // The last element in columnStarts represents the end of the table
                for (int columnIndex = 0; columnIndex < columnStartsAllRows.Count - 1; columnIndex++)
                {
                    // XmlElement xamlColumnElement;

                    TableColumn tc = new TableColumn();


                    //xamlColumnElement = xamlTableElement.OwnerDocument.CreateElement(null, Xaml_TableColumn, _xamlNamespace);
                    double w = ((double)columnStartsAllRows[columnIndex + 1] - (double)columnStartsAllRows[columnIndex]);
                    tc.Width = new GridLength(w, GridUnitType.Star);

                    //xamlColumnElement.SetAttribute(Xaml_Width,
                    //    .ToString());
                    // xamlTableElement.AppendChild(xamlColumnElement);
                    current.Columns.Add(tc);
                }
            }
            else
            {
                // We do not have consistent information from table cells;
                // Translate blindly colgroups from html.                
                for (XmlNode htmlChildNode = htmlTableElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling)
                {
                    if (htmlChildNode.LocalName.ToLower() == "colgroup")
                    {
                        // TODO: add column width information to this function as a parameter and process it
                        AddTableColumnGroup(current, (XmlElement)htmlChildNode, currentProperties, stylesheet);
                    }
                    else if (htmlChildNode.LocalName.ToLower() == "col")
                    {
                        AddTableColumn(current, (XmlElement)htmlChildNode, currentProperties, stylesheet);
                    }
                    else if (htmlChildNode is XmlElement)
                    {
                        // Some element which belongs to table body. Stop column loop.
                        break;
                    }
                }
            }
        }
Example #22
0
 protected override Drawable CreateHeader(int index, TableColumn column) => new HeaderText(column?.Header ?? string.Empty);
Example #23
0
        private void btnGenerate_Click(object sender, EventArgs e)
        {
            string path = txtFilePath.Text.Trim();
            List<TableEntity> lstTable = new List<TableEntity>();
            using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                XSSFWorkbook xssfworkbook = new XSSFWorkbook(fs);

                for (int i = 0; i < xssfworkbook.NumberOfSheets; i++)
                {
                    ISheet sheet = xssfworkbook.GetSheetAt(i);
                    TableEntity tbl = new TableEntity();//实例化一个

                    System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
                    int rowIndex = 1;
                    int columnIndex = 0;//列
                    int indexIndex = 0;//索引
                    int fkIndex = 0;//外键
                    List<string> lstKeyWords = new List<string>();
                    string strCell0 = string.Empty;
                BigCycle:
                    while (rows.MoveNext())
                    {
                        IRow row = (XSSFRow)rows.Current;
                        strCell0 = row.GetCell(0).ToStringEx();

                        #region 将每行第一个单元格保存下
                        if (!strCell0.IsNullOrEmpty())
                        {
                            if (!lstKeyWords.Contains(strCell0))
                            {
                                lstKeyWords.Add(strCell0);
                            }
                        }
                        #endregion

                        #region 获取开始行
                        if (strCell0 == "表名(英文):")
                        {
                            tbl.TableName = row.GetCell(2).ToStringEx();
                            tbl.TableDesc = row.GetCell(7).ToStringEx();
                            rowIndex++;
                            continue;
                        }
                        if (strCell0 == "字段名(英文)")
                        {
                            columnIndex = rowIndex + 1;
                            rowIndex++;
                            continue;
                        }

                        if (strCell0 == "索引名称")
                        {
                            indexIndex = rowIndex + 1;
                            rowIndex++;
                            continue;
                        }

                        if (strCell0 == "外键列")
                        {
                            fkIndex = rowIndex + 1;
                            rowIndex++;
                            continue;
                        }
                        #endregion

                        #region 获取列
                        if (columnIndex == rowIndex)
                        {
                            TableColumn col = new TableColumn();
                            for (int j = 0; j < row.LastCellNum; j++)
                            {
                                ICell cell = row.GetCell(j);
                                switch (j)
                                {
                                    case 0:
                                        if (cell.ToStringEx().IsNullOrEmpty() || cell.ToStringEx() == "索引名称")
                                        {
                                            rowIndex++;
                                            goto BigCycle;
                                        }
                                        columnIndex++;
                                        col.ColumnName = cell.ToStringEx();
                                        break;
                                    case 1:
                                        if (cell.ToStringEx().IsNullOrEmpty())
                                        {
                                            this.ShowMessage(tbl.TableName, col.ColumnName, "中文名称不能为空!");
                                            return;
                                        }
                                        col.ColumnCnName = cell.ToStringEx();
                                        break;
                                    case 2:
                                        if (cell.ToStringEx().IsNullOrEmpty())
                                        {
                                            this.ShowMessage(tbl.TableName, col.ColumnName, "数据类型不能为空!");
                                            return;
                                        }
                                        col.DataType = cell.ToStringEx();
                                        break;
                                    case 4:
                                        if (cell.ToStringEx().IsNullOrEmpty())
                                        {
                                            this.ShowMessage(tbl.TableName, col.ColumnName, "主键不能为空!");
                                            return;
                                        }
                                        col.IsPrimaryKey = cell.ToStringEx();
                                        break;
                                    case 5:
                                        if (cell.ToStringEx().IsNullOrEmpty())
                                        {
                                            this.ShowMessage(tbl.TableName, col.ColumnName, "允许空不能为空!");
                                            return;
                                        }
                                        col.IsAllowNull = cell.ToStringEx();
                                        break;
                                    case 6:
                                        if (cell.ToStringEx().IsNullOrEmpty())
                                        {
                                            this.ShowMessage(tbl.TableName, col.ColumnName, "是否唯一不能为空!");
                                            return;
                                        }
                                        col.IsUnique = cell.ToStringEx();
                                        break;
                                    case 7:
                                        if (!cell.ToStringEx().IsNullOrEmpty())
                                        {
                                            col.DefaultValue = cell.ToStringEx();
                                        }
                                        break;
                                    case 8:
                                        col.ColumnDesc = cell.ToStringEx();
                                        break;
                                    default:
                                        break;
                                }
                            }
                            tbl.Columns.Add(col);
                        }
                        #endregion

                        #region 获取索引
                        if (indexIndex == rowIndex)
                        {
                            TableIndex idx = new TableIndex();
                            for (int j = 0; j < row.LastCellNum; j++)
                            {
                                ICell cell = row.GetCell(j);
                                switch (j)
                                {
                                    case 0:
                                        if (cell.ToStringEx().IsNullOrEmpty() || cell.ToStringEx() == "外键列")
                                        {
                                            rowIndex++;
                                            goto BigCycle;
                                        }
                                        indexIndex++;
                                        idx.IndexName = cell.ToStringEx();
                                        break;
                                    case 1:
                                        if (cell.ToStringEx().IsNullOrEmpty())
                                        {
                                            this.ShowMessage(tbl.TableName, idx.IndexName, "索引列不能为空!");
                                            return;
                                        }
                                        idx.IndexColumn = cell.ToStringEx();
                                        break;
                                    case 2:
                                        idx.IndexIncludeColumn = cell.ToStringEx();
                                        break;
                                    default:
                                        break;
                                }
                            }
                            tbl.Indexs.Add(idx);
                        }
                        #endregion

                        #region 获取外键
                        if (fkIndex == rowIndex)
                        {
                            TableForeignKey fk = new TableForeignKey();
                            for (int j = 0; j < row.LastCellNum; j++)
                            {
                                ICell cell = row.GetCell(j);
                                switch (j)
                                {
                                    case 0:
                                        if (cell.ToStringEx().IsNullOrEmpty())
                                        {
                                            rowIndex++;
                                            goto BigCycle;
                                        }
                                        columnIndex++;
                                        fk.ForeignKey = cell.ToStringEx();
                                        break;
                                    case 1:
                                        if (cell.ToStringEx().IsNullOrEmpty())
                                        {
                                            this.ShowMessage(tbl.TableName, fk.ForeignKey, "主键表不能为空!");
                                            return;
                                        }
                                        fk.ForeignTable = cell.ToStringEx();
                                        break;
                                    case 2:
                                        if (cell.ToStringEx().IsNullOrEmpty())
                                        {
                                            this.ShowMessage(tbl.TableName, fk.ForeignKey, "对应主键表的列不能为空!");
                                            return;
                                        }
                                        fk.ForeignTablePK = cell.ToStringEx();
                                        break;
                                    default:
                                        break;
                                }
                            }
                            tbl.ForeignKeys.Add(fk);
                        }
                        #endregion
                        rowIndex++;
                    }
                    if (!tbl.TableName.IsNullOrEmpty() && tbl.TableName.Contains("_"))
                    {
                        if (!lstKeyWords.Contains("表名(英文):") || !lstKeyWords.Contains("字段名(英文)")
                            || !lstKeyWords.Contains("索引名称") || !lstKeyWords.Contains("外键列"))
                        {
                            MessageBox.Show("Sheet" + tbl.TableName + "格式有问题,缺少列:表名(英文):、字段名(英文)、索引名称、外键列");
                            return;
                        }
                        else
                        {
                            lstTable.Add(tbl);
                        }
                    }
                }
            }
            StringBuilder sb = this.GenerateSQL(lstTable);
            string savePath = ConfigurationManager.AppSettings["GenerateTable"];
            if (!string.IsNullOrEmpty(savePath))
            {
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }
                GenerateFileHelper.GenerateFile(sb.ToStringEx(), savePath + DateTime.Now.ToString("yyyy-MM-dd") + "-GenerateTable.sql");
                MessageBox.Show("生成成功!", "消息");
                System.Diagnostics.Process.Start("Explorer.exe", savePath);
            }
        }
        private void InitializeTable()
        {
            _table = new TableView <Power>
            {
                Location = new Point(3, 3),
                ToolTip  = _tipTooltip
            };
            // create columns
            TableColumn <Power> nameColumn = new TableColumn <Power>(() => new TextTableCell())
            {
                Text      = "Power",
                Extractor = (power => power.DisplayName),
                Tag       = "String_Power",
                Sorter    = (name1, name2) => string.Compare((string)name1, (string)name2, GlobalOptions.CultureInfo, CompareOptions.Ordinal)
            };

            nameColumn.AddDependency(nameof(Power.DisplayName));

            TableColumn <Power> actionColumn = new TableColumn <Power>(() => new TextTableCell())
            {
                Text      = "Action",
                Extractor = (power => power.DisplayAction),
                Tag       = "ColumnHeader_Action",
                Sorter    = (action1, action2) => string.Compare((string)action1, (string)action2, GlobalOptions.CultureInfo, CompareOptions.Ordinal)
            };

            actionColumn.AddDependency(nameof(Power.DisplayAction));

            TableColumn <Power> ratingColumn = new TableColumn <Power>(() => new SpinnerTableCell <Power>(_table)
            {
                EnabledExtractor = (p => p.LevelsEnabled),
                MaxExtractor     = (p => Math.Max(p.TotalMaximumLevels - p.FreeLevels, 0)),
                ValueUpdater     = (p, newRating) =>
                {
                    int delta = ((int)newRating) - p.Rating;
                    if (delta != 0)
                    {
                        p.Rating += delta;
                    }
                },
                MinExtractor = (p => 0),
                ValueGetter  = (p => p.Rating),
            })
            {
                Text   = "Rating",
                Tag    = "String_Rating",
                Sorter = (o1, o2) => ((Power)o1).Rating - ((Power)o2).Rating
            };


            ratingColumn.AddDependency(nameof(Power.LevelsEnabled));
            ratingColumn.AddDependency(nameof(Power.FreeLevels));
            ratingColumn.AddDependency(nameof(Power.TotalMaximumLevels));
            ratingColumn.AddDependency(nameof(Power.TotalRating));
            TableColumn <Power> totalRatingColumn = new TableColumn <Power>(() => new TextTableCell())
            {
                Text      = "Total Rating",
                Extractor = (power => power.TotalRating),
                Tag       = "String_TotalRating",
                Sorter    = (o1, o2) => ((Power)o1).TotalRating - ((Power)o2).TotalRating
            };

            totalRatingColumn.AddDependency(nameof(Power.TotalRating));

            TableColumn <Power> powerPointsColumn = new TableColumn <Power>(() => new TextTableCell())
            {
                Text             = "Power Points",
                Extractor        = (power => power.DisplayPoints),
                Tag              = "ColumnHeader_Power_Points",
                ToolTipExtractor = (item => item.ToolTip)
            };

            powerPointsColumn.AddDependency(nameof(Power.DisplayPoints));
            powerPointsColumn.AddDependency(nameof(Power.ToolTip));

            TableColumn <Power> sourceColumn = new TableColumn <Power>(() => new TextTableCell())
            {
                Text             = "Source",
                Extractor        = (power => power.SourceDetail),
                Tag              = "Label_Source",
                ToolTipExtractor = (item => item.SourceDetail.LanguageBookTooltip)
            };

            powerPointsColumn.AddDependency(nameof(Power.Source));

            TableColumn <Power> adeptWayColumn = new TableColumn <Power>(() => new CheckBoxTableCell <Power>()
            {
                ValueGetter      = (p => p.DiscountedAdeptWay),
                ValueUpdater     = (p, check) => p.DiscountedAdeptWay = check,
                VisibleExtractor = (p => p.AdeptWayDiscountEnabled),
                Alignment        = Alignment.Center
            })
            {
                Text = "Adept Way",
                Tag  = "Checkbox_Power_AdeptWay"
            };

            adeptWayColumn.AddDependency(nameof(Power.DiscountedAdeptWay));
            adeptWayColumn.AddDependency(nameof(Power.AdeptWayDiscountEnabled));
            adeptWayColumn.AddDependency(nameof(Power.Rating));

            /*
             * TableColumn<Power> geasColumn = new TableColumn<Power>(() => new CheckBoxTableCell<Power>()
             * {
             *  ValueGetter = (p => p.DiscountedGeas),
             *  ValueUpdater = (p, check) => p.DiscountedGeas = check,
             *  Alignment = Alignment.Center
             * })
             * {
             *  Text = "Geas",
             *  Tag = "Checkbox_Power_Geas"
             * };
             * geasColumn.AddDependency(nameof(Power.DiscountedGeas));
             */

            TableColumn <Power> noteColumn = new TableColumn <Power>(() => new ButtonTableCell <Power>(new PictureBox()
            {
                Image = Properties.Resources.note_edit,
                Size  = GetImageSize(Properties.Resources.note_edit),
            })
            {
                ClickHandler = p => {
                    frmNotes frmPowerNotes = new frmNotes
                    {
                        Notes = p.Notes
                    };
                    frmPowerNotes.ShowDialog(this);

                    if (frmPowerNotes.DialogResult == DialogResult.OK)
                    {
                        p.Notes = frmPowerNotes.Notes;
                    }
                },
                Alignment = Alignment.Center
            })
            {
                Text             = "Notes",
                Tag              = "ColumnHeader_Notes",
                ToolTipExtractor = (p => {
                    string strTooltip = LanguageManager.GetString("Tip_Power_EditNotes", GlobalOptions.Language);
                    if (!string.IsNullOrEmpty(p.Notes))
                    {
                        strTooltip += Environment.NewLine + Environment.NewLine + p.Notes;
                    }
                    return(strTooltip.WordWrap(100));
                })
            };

            noteColumn.AddDependency(nameof(Power.Notes));

            TableColumn <Power> deleteColumn = new TableColumn <Power>(() => new ButtonTableCell <Power>(new Button()
            {
                Text = "Delete", Tag = "String_Delete", BackColor = SystemColors.Control
            })
            {
                ClickHandler = p =>
                {
                    //Cache the parentform prior to deletion, otherwise the relationship is broken.
                    Form frmParent = ParentForm;
                    if (p.FreeLevels > 0)
                    {
                        string strImprovementSourceName = p.CharacterObject.Improvements.FirstOrDefault(x => x.ImproveType == Improvement.ImprovementType.AdeptPowerFreePoints && x.ImprovedName == p.Name && x.UniqueName == p.Extra)?.SourceName;
                        Gear objGear = p.CharacterObject.Gear.FirstOrDefault(x => x.Bonded && x.InternalId == strImprovementSourceName);
                        if (objGear != null)
                        {
                            objGear.Equipped = false;
                            objGear.Extra    = string.Empty;
                        }
                    }
                    p.DeletePower();
                    p.UnbindPower();

                    if (frmParent is CharacterShared objParent)
                    {
                        objParent.IsCharacterUpdateRequested = true;
                    }
                },
                EnabledExtractor = (p => p.FreeLevels == 0)
            });
Example #25
0
 public override string GetDBFieldType(TableColumn f)
 {
     throw new Exception("The method or operation is not implemented.");
 }
        private Table CreateSummaryTable()
        {
            int resultCount = _testResults.Count;

            Table summaryTable = new Table();

            summaryTable.CellSpacing     = 0;
            summaryTable.BorderBrush     = Brushes.Gray;
            summaryTable.BorderThickness = new Thickness(1);
            summaryTable.Margin          = new Thickness(16, 0, 16, 16);

            TableColumn categoryCol = new TableColumn();

            categoryCol.Width = new GridLength(2, GridUnitType.Star);
            summaryTable.Columns.Add(categoryCol);

            TableColumn totalCol = new TableColumn();

            totalCol.Width = new GridLength(1, GridUnitType.Star);
            summaryTable.Columns.Add(totalCol);

            for (int i = 0; i < resultCount; i++)
            {
                TableColumn successCol = new TableColumn();
                successCol.Width = new GridLength(1, GridUnitType.Star);
                summaryTable.Columns.Add(successCol);
            }

            TableRowGroup headerGroup = new TableRowGroup();

            headerGroup.Background = Brushes.LightGray;
            TableRow headerRow = new TableRow();

            headerRow.Cells.Add(CreateHeaderCell("Category", false, false));
            headerRow.Cells.Add(CreateHeaderCell("Total", false, false));

            for (int i = 0; i < resultCount; i++)
            {
                SvgTestResult testResult = _testResults[i];
                headerRow.Cells.Add(CreateHeaderCell(testResult.Version + " (%)",
                                                     (i == (resultCount - 1)), false));
            }

            headerGroup.Rows.Add(headerRow);
            summaryTable.RowGroups.Add(headerGroup);

            int[] successValues = new int[resultCount];
            int   totalValue    = 0;

            for (int k = 0; k < _categoryLabels.Count; k++)
            {
                TableRowGroup resultGroup = new TableRowGroup();
                TableRow      resultRow   = new TableRow();

                bool lastBottom = (k == (_categoryLabels.Count - 1));

                resultRow.Cells.Add(CreateCell(_categoryLabels[k], false, lastBottom));

                for (int i = 0; i < resultCount; i++)
                {
                    SvgTestResult testResult = _testResults[i];

                    IList <SvgTestCategory> testCategories = testResult.Categories;

                    SvgTestCategory testCategory = testCategories[k];
                    if (!testCategory.IsValid)
                    {
                        continue;
                    }

                    int total = testCategory.Total;

                    if (i == 0)
                    {
                        resultRow.Cells.Add(CreateCell(total, false, lastBottom));
                    }

                    successValues[i] = testCategory.Successes;
                    totalValue       = total;
                    bool lastRight = (i == (resultCount - 1));

                    double percentValue = Math.Round(testCategory.Successes * 100.0d / total, 2);

                    resultRow.Cells.Add(CreateCell(percentValue.ToString("00.00"),
                                                   lastRight, lastBottom, false, false));
                }

                int cellCount = resultRow.Cells.Count;
                if (IsAllZero(successValues))
                {
                    for (int i = 1; i < cellCount; i++)
                    {
                        resultRow.Cells[i].Background = Brushes.PaleVioletRed;
                    }
                }
                else if (IsAllDone(successValues, totalValue))
                {
                    for (int i = 1; i < cellCount; i++)
                    {
                        resultRow.Cells[i].Background = Brushes.Silver;
                    }
                }
                else
                {
                    // TODO: Improve this, currently only good for two results...
                    if (resultCount > 1 && IsBetterResult(successValues, resultCount - 1))
                    {
                        resultRow.Cells[cellCount - 1].Background = Brushes.LightSkyBlue;
                    }
                }

                resultGroup.Rows.Add(resultRow);
                summaryTable.RowGroups.Add(resultGroup);
            }

            return(summaryTable);
        }
Example #27
0
        private DbParameter CreateRandomParameter(Random rnd, string prefix, TableColumn column)
        {
            DbParameter param = DbFactory.CreateParameter();

            param.ParameterName = GetParameterName(prefix);

            param.Value = GetRandomData(rnd, column);

            return param;
        }
        private Table CreateResultTable(IList <SvgTestCategory> testCategories)
        {
            Table resultTable = new Table();

            resultTable.CellSpacing     = 0;
            resultTable.BorderBrush     = Brushes.Gray;
            resultTable.BorderThickness = new Thickness(1);
            resultTable.Margin          = new Thickness(16, 0, 16, 16);

            TableColumn categoryCol = new TableColumn();
            TableColumn failureCol  = new TableColumn();
            TableColumn successCol  = new TableColumn();
            TableColumn partialCol  = new TableColumn();
            TableColumn unknownCol  = new TableColumn();
            TableColumn totalCol    = new TableColumn();

            categoryCol.Width = new GridLength(2, GridUnitType.Star);
            failureCol.Width  = new GridLength(1, GridUnitType.Star);
            successCol.Width  = new GridLength(1, GridUnitType.Star);
            partialCol.Width  = new GridLength(1, GridUnitType.Star);
            unknownCol.Width  = new GridLength(1, GridUnitType.Star);
            totalCol.Width    = new GridLength(1, GridUnitType.Star);

            resultTable.Columns.Add(categoryCol);
            resultTable.Columns.Add(failureCol);
            resultTable.Columns.Add(successCol);
            resultTable.Columns.Add(partialCol);
            resultTable.Columns.Add(unknownCol);
            resultTable.Columns.Add(totalCol);

            TableRowGroup headerGroup = new TableRowGroup();

            headerGroup.Background = Brushes.LightGray;
            TableRow headerRow = new TableRow();

            headerRow.Cells.Add(CreateHeaderCell("Category", false, false));
            headerRow.Cells.Add(CreateHeaderCell("Failure", false, false));
            headerRow.Cells.Add(CreateHeaderCell("Success", false, false));
            headerRow.Cells.Add(CreateHeaderCell("Partial", false, false));
            headerRow.Cells.Add(CreateHeaderCell("Unknown", false, false));
            headerRow.Cells.Add(CreateHeaderCell("Total", true, false));

            headerGroup.Rows.Add(headerRow);
            resultTable.RowGroups.Add(headerGroup);

            for (int i = 0; i < testCategories.Count; i++)
            {
                SvgTestCategory testCategory = testCategories[i];
                if (!testCategory.IsValid)
                {
                    continue;
                }

                TableRowGroup resultGroup = new TableRowGroup();
                TableRow      resultRow   = new TableRow();

                bool lastBottom = (i == (testCategories.Count - 1));

                resultRow.Cells.Add(CreateCell(testCategory.Label, false, lastBottom));
                resultRow.Cells.Add(CreateCell(testCategory.Failures, false, lastBottom));
                resultRow.Cells.Add(CreateCell(testCategory.Successes, false, lastBottom));
                resultRow.Cells.Add(CreateCell(testCategory.Partials, false, lastBottom));
                resultRow.Cells.Add(CreateCell(testCategory.Unknowns, false, lastBottom));
                resultRow.Cells.Add(CreateCell(testCategory.Total, true, lastBottom));

                resultGroup.Rows.Add(resultRow);
                resultTable.RowGroups.Add(resultGroup);
            }

            return(resultTable);
        }
        private static void GenerateTableDefinitionPartContent(TableDefinitionPart tableDefinitionPart, XLTable xlTable,
            SaveContext context)
        {
            context.TableId++;
            var reference = xlTable.RangeAddress.FirstAddress + ":" + xlTable.RangeAddress.LastAddress;
            var tableName = GetTableName(xlTable.Name, context);
            var table = new Table
            {
                Id = context.TableId,
                Name = tableName,
                DisplayName = tableName,
                Reference = reference
            };

            if (!xlTable.ShowHeaderRow)
                table.HeaderRowCount = 0;

            if (xlTable.ShowTotalsRow)
                table.TotalsRowCount = 1;
            else
                table.TotalsRowShown = false;

            var tableColumns1 = new TableColumns {Count = (UInt32)xlTable.ColumnCount()};

            UInt32 columnId = 0;
            foreach (var fieldName in xlTable.FieldNames.Keys)
            {
                columnId++;
                var xlField = xlTable.Field(fieldName);
                var tableColumn1 = new TableColumn
                {
                    Id = columnId,
                    Name = fieldName.Replace("_x000a_", "_x005f_x000a_").Replace(Environment.NewLine, "_x000a_")
                };
                if (xlTable.ShowTotalsRow)
                {
                    if (xlField.TotalsRowFunction != XLTotalsRowFunction.None)
                    {
                        tableColumn1.TotalsRowFunction = xlField.TotalsRowFunction.ToOpenXml();

                        if (xlField.TotalsRowFunction == XLTotalsRowFunction.Custom)
                            tableColumn1.TotalsRowFormula = new TotalsRowFormula(xlField.TotalsRowFormulaA1);
                    }

                    if (!XLHelper.IsNullOrWhiteSpace(xlField.TotalsRowLabel))
                        tableColumn1.TotalsRowLabel = xlField.TotalsRowLabel;
                }
                tableColumns1.AppendChild(tableColumn1);
            }

            var tableStyleInfo1 = new TableStyleInfo
            {
                ShowFirstColumn = xlTable.EmphasizeFirstColumn,
                ShowLastColumn = xlTable.EmphasizeLastColumn,
                ShowRowStripes = xlTable.ShowRowStripes,
                ShowColumnStripes = xlTable.ShowColumnStripes
            };

            if (xlTable.Theme != XLTableTheme.None)
                tableStyleInfo1.Name = Enum.GetName(typeof(XLTableTheme), xlTable.Theme);

            if (xlTable.ShowAutoFilter)
            {
                var autoFilter1 = new AutoFilter();
                if (xlTable.ShowTotalsRow)
                {
                    xlTable.AutoFilter.Range = xlTable.Worksheet.Range(
                        xlTable.RangeAddress.FirstAddress.RowNumber, xlTable.RangeAddress.FirstAddress.ColumnNumber,
                        xlTable.RangeAddress.LastAddress.RowNumber - 1, xlTable.RangeAddress.LastAddress.ColumnNumber);
                }
                else
                    xlTable.AutoFilter.Range = xlTable.Worksheet.Range(xlTable.RangeAddress);

                PopulateAutoFilter(xlTable.AutoFilter, autoFilter1);

                table.AppendChild(autoFilter1);
            }

            table.AppendChild(tableColumns1);
            table.AppendChild(tableStyleInfo1);

            tableDefinitionPart.Table = table;
        }
        internal TableColumn ToTableColumn()
        {
            TableColumn tc = new TableColumn();
            if (HasCalculatedColumnFormula)
            {
                tc.CalculatedColumnFormula = this.CalculatedColumnFormula.ToCalculatedColumnFormula();
            }
            if (HasTotalsRowFormula)
            {
                tc.TotalsRowFormula = this.TotalsRowFormula.ToTotalsRowFormula();
            }
            if (HasXmlColumnProperties)
            {
                tc.XmlColumnProperties = this.XmlColumnProperties.ToXmlColumnProperties();
            }

            tc.Id = this.Id;
            if (this.UniqueName != null) tc.UniqueName = this.UniqueName;
            tc.Name = this.Name;

            if (HasTotalsRowFunction) tc.TotalsRowFunction = this.TotalsRowFunction;
            if (this.TotalsRowLabel != null) tc.TotalsRowLabel = this.TotalsRowLabel;
            if (this.QueryTableFieldId != null) tc.QueryTableFieldId = this.QueryTableFieldId.Value;
            if (this.HeaderRowDifferentialFormattingId != null) tc.HeaderRowDifferentialFormattingId = this.HeaderRowDifferentialFormattingId.Value;
            if (this.DataFormatId != null) tc.DataFormatId = this.DataFormatId.Value;
            if (this.TotalsRowDifferentialFormattingId != null) tc.TotalsRowDifferentialFormattingId = this.TotalsRowDifferentialFormattingId.Value;
            if (this.HeaderRowCellStyle != null) tc.HeaderRowCellStyle = this.HeaderRowCellStyle;
            if (this.DataCellStyle != null) tc.DataCellStyle = this.DataCellStyle;
            if (this.TotalsRowCellStyle != null) tc.TotalsRowCellStyle = this.TotalsRowCellStyle;

            return tc;
        }
Example #31
0
 public override bool CanAlter(TableColumn actual)
 {
     return(false);
 }
Example #32
0
    void DrawObjectsTable()
    {
        SerializedObject serializedObject = new SerializedObject(AdvancedExample.Instance);
        AdvancedExample  targetObject     = (AdvancedExample)serializedObject.targetObject;

        List <SelectorColumn> columns = new List <SelectorColumn> ();

        columns.Add(new SelectObjectReferenceColumn("Enemy Prefab", TableColumn.Width(75f), TableColumn.EnabledCells(false), TableColumn.Optional(true)));
        columns.Add(new SelectFromPropertyNameColumn("type", "Type", TableColumn.Width(50f), TableColumn.Optional(true)));
        columns.Add(new SelectFromPropertyNameColumn("health", "Health", TableColumn.Width(50f)));
        columns.Add(new SelectFromPropertyNameColumn("speed", "Speed", TableColumn.Width(50f)));
        columns.Add(new SelectFromPropertyNameColumn("color", "Color", TableColumn.Width(50f), TableColumn.Optional(true)));
        columns.Add(new SelectFromPropertyNameColumn("canSwim", "Can Swim", TableColumn.Width(30f), TableColumn.Optional(true)));
        columns.Add(new SelectFromFunctionColumn(
                        sp => new SpawnersCell(new SerializedObject(sp.objectReferenceValue), "spawnersMask"),
                        "Spawners",
                        TableColumn.Width(450f),
                        TableColumn.Optional(true)));
        columns.Add(new SelectFromFunctionColumn(
                        sp =>
        {
            Enemy enemy       = (Enemy)sp.objectReferenceValue;
            int sentenceIndex = targetObject.introSentences.FindIndex(s => s.enemyType == enemy.type);
            return(new PropertyCell(serializedObject, string.Format("introSentences.Array.data[{0}].sentence", sentenceIndex)));
        },
                        "Intro (shared by type)",
                        TableColumn.Width(110f),
                        TableColumn.Optional(true)));
        columns.Add(new SelectFromFunctionColumn(
                        sp =>
        {
            Enemy enemy = (Enemy)sp.objectReferenceValue;
            return(new ActionCell("Instantiate", () => enemy.Instantiate()));
        },
                        "Instantiation",
                        TableColumn.Width(110f),
                        TableColumn.Optional(true)));

        tableState = GUITableLayout.DrawTable(tableState, serializedObject.FindProperty("enemies"), columns);
    }
Example #33
0
 /// <summary>
 /// Removes <code>aColumn</code> from this <code>JTable</code>'s
 /// array of columns.
 /// </summary>
 public void removeColumn(TableColumn @aColumn)
 {
 }
Example #34
0
 /// <summary>
 /// Appends <code>aColumn</code> to the end of the array of columns held by
 /// this <code>JTable</code>'s column model.
 /// </summary>
 public void addColumn(TableColumn @aColumn)
 {
 }
Example #35
0
        List<TableColumn> LoadColumns(Table tbl)
        {
            var result = new List<TableColumn>();

            var cmd = GetCommand(PK_SQL);
            cmd.Parameters.AddWithValue("@tableName", tbl.Name);
            var pkCol = cmd.ExecuteScalar();
            var pkColName = pkCol as string;

            cmd = GetCommand(COLUMN_SQL);
            cmd.Parameters.AddWithValue("@tableName", tbl.Name);

            using (IDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
            {
                while (rdr.Read())
                {
                    TableColumn col = new TableColumn();
                    col.Name = rdr["ColumnName"].ToString();
                    if (pkColName == col.Name)
                    {
                        col.IsPrimaryKey = true;
                    }
                    col.DataType = rdr["DataType"].ToString();
                    col.IsNullable = rdr["IsNullable"].ToString() == "YES";
                    col.SysType = GetSysType(col.DataType, col.IsNullable);
                    col.DbType = GetDbType(col.DataType);
                    col.AutoIncrement = rdr["IsIdentity"].ToString() == "1";
                    int colMaxLength;
                    if (int.TryParse(rdr["MaxLength"].ToString(), out colMaxLength))
                    {
                        col.MaxLength = colMaxLength;
                    }

                    result.Add(col);
                }

            }

            return result;
        }
 protected abstract void AppendColumn(TableColumn column);
Example #37
0
        public void FillTableSchema(Table tbl, TableType tableType)
        {
            TableColumnCollection columns = new TableColumnCollection();
            DataSet dsColumns;

            tbl.ForeignKeys = new ForeignKeyCollection();

            if (tableType == TableType.Function)
            {
                if (dsColumns2.Tables[Name] == null)
                {
                    var cmdColumns = new SqlCommand(ROUTINE_COLUMN_SQL_ALL);
                    var dt = new DataTable(Name);
                    dt.Load(cmdColumns.GetReader());
                    dsColumns2.Tables.Add(dt);
                }
                dsColumns = dsColumns2;
            }
            else
            {
                if (dsColumns1.Tables[Name] == null)
                {
                    var cmdColumns = new SqlCommand(TABLE_COLUMN_SQL_ALL);
                    var dt = new DataTable(Name);
                    dt.Load(cmdColumns.GetReader());
                    dsColumns1.Tables.Add(dt);
                }
                dsColumns = dsColumns1;
            }

            DataRow[] drColumns = dsColumns.Tables[Name].Select("TableName ='" + tbl.Name + "'", "OrdinalPosition ASC");

            for (int i = 0; i < drColumns.Length; i++)
            {
                TableColumn column = new TableColumn(tbl);
                column.ColumnName = drColumns[i][SqlSchemaVariable.COLUMN_NAME].ToString();
                column.NativeDataType = drColumns[i][SqlSchemaVariable.DATA_TYPE].ToString();
                if (column.NativeDataType == "numeric")
                    column.NativeDataType = string.Format("Decimal({0},{1})", drColumns[i]["precision"], drColumns[i]["scale"]);
                column.DataType = GetDbType(column.NativeDataType);
                if (drColumns[i][SqlSchemaVariable.COLUMN_DEFAULT] != DBNull.Value)
                {
                    string defaultSetting = drColumns[i][SqlSchemaVariable.COLUMN_DEFAULT].ToString().Trim();
                    if (defaultSetting.ToLower().IndexOf("newsequentialid()") > -1)
                        column.DefaultSetting = SqlSchemaVariable.DEFAULT;
                    else
                        column.DefaultSetting = defaultSetting;
                }
                column.AutoIncrement = Convert.ToBoolean(drColumns[i][SqlSchemaVariable.IS_IDENTITY]);
                int maxLength;
                int.TryParse(drColumns[i][SqlSchemaVariable.MAX_LENGTH].ToString(), out maxLength);
                column.MaxLength = maxLength;
                if (maxLength > 0)
                    column.NativeDataType += "(" + maxLength + ")";
                column.IsNullable = drColumns[i][SqlSchemaVariable.IS_NULLABLE].ToString() == "YES";
                bool isComputed = (drColumns[i][SqlSchemaVariable.IS_COMPUTED].ToString() == "1");
                column.IsReadOnly = (column.NativeDataType == "timestamp" || isComputed);
                columns.Add(column);
                tbl.SchemaName = drColumns[i]["Owner"].ToString();
            }
            tbl.Columns = columns;

            if (dsIndex.Tables[Name] == null)
            {
                var cmdIndex = new SqlCommand(INDEX_SQL_ALL);
                DataTable dt = new DataTable(Name);
                dt.Load(cmdIndex.GetReader());
                dsIndex.Tables.Add(dt);
            }

            DataRow[] drIndexes = dsIndex.Tables[Name].Select("TableName ='" + tbl.Name + "'");
            for (int i = 0; i < drIndexes.Length; i++)
            {
                string colName = drIndexes[i][SqlSchemaVariable.COLUMN_NAME].ToString();
                string constraintType = drIndexes[i][SqlSchemaVariable.CONSTRAINT_TYPE].ToString();
                TableColumn column = columns.GetColumn(colName);

                if (Utility.IsMatch(constraintType, SqlSchemaVariable.PRIMARY_KEY))
                    column.IsPrimaryKey = true;
                else if (Utility.IsMatch(constraintType, SqlSchemaVariable.FOREIGN_KEY))
                    column.IsForeignKey = true;
                //HACK: Allow second pass naming adjust based on whether a column is keyed
                column.ColumnName = column.ColumnName;
            }

            if (dtFKR == null)
            {
                var cmdFKR = new SqlCommand(FOREIGN_KEY_RELATIONSHIPS);
                dtFKR = new DataTable();
                dtFKR.Load(cmdFKR.GetReader());

                var cmdFK = new SqlCommand(FOREIGN_KEYS);
                dtFK = new DataTable();
                dtFK.Load(cmdFK.GetReader());
            }

            DataRow[] drfkr;
            drfkr = dtFKR.Select("PkTable ='" + tbl.Name + "'");
            for (int i = 0; i < drfkr.Length; i++)
            {
                Relationship rel = new Relationship();
                rel.Name = drfkr[i]["RelName"].ToString();
                Table fktable = Db.Service.GetSchema(drfkr[i]["FkTable"].ToString());
                rel.ClassNameOne = tbl.ClassName;
                rel.ClassNameMany = fktable.ClassName;
                string[] a = Regex.Split(rel.Name, "__");
                if (a.Length == 2)
                {
                    rel.PropertyNameMany = a[0]; // name used in primary table to fetch many of this table
                    rel.PropertyNameOne = a[1]; // named used for foreign key in this table
                }
                else
                {
                    rel.PropertyNameOne = tbl.ClassName;
                    rel.PropertyNameMany = fktable.ClassNamePlural;
                }

                DataRow[] drfk = dtFK.Select("PkTable = '" + tbl.Name + "' and RelName = '" + rel.Name + "'");
                for (int ii = 0; ii < drfk.Length; ii++)
                {
                    Relationship.KeyPair kp = new Relationship.KeyPair();
                    TableColumn fkcol = fktable.Columns.GetColumn(drfk[ii]["FkColumn"].ToString());
                    TableColumn pkcol = columns.GetColumn(drfk[ii]["PkColumn"].ToString());
                    kp.vartype = fkcol.VarType;
                    kp.ForeignKey = fkcol.Name;
                    kp.PrimaryKey = pkcol.Name;
                    rel.KeyPairs.Add(kp);
                    if (ii > 0)
                    {
                        rel.ForeignKey += ",";
                        rel.PrimaryKey += ",";
                    }
                    rel.PrimaryKey += kp.PrimaryKey;
                    rel.ForeignKey += kp.ForeignKey;
                }


                tbl.ForeignKeyTables.Add(rel);
            }

            drfkr = dtFKR.Select("FkTable ='" + tbl.Name + "'");
            for (int i = 0; i < drfkr.Length; i++)
            {
                Relationship rel = new Relationship();
                rel.Name = drfkr[i]["RelName"].ToString();
                Table pktable = Db.Service.GetSchema(drfkr[i]["PkTable"].ToString());
                rel.ClassNameOne = pktable.ClassName;
                rel.ClassNameMany = tbl.ClassName;
                string[] a = Regex.Split(rel.Name, "__");
                if (a.Length == 2)
                {
                    rel.PropertyNameMany = a[0]; // name used in primary table to fetch many of this table
                    rel.PropertyNameOne = a[1]; // named used for foreign key in this table
                }
                else
                {
                    rel.PropertyNameOne = pktable.ClassName;
                    rel.PropertyNameMany = tbl.ClassNamePlural;
                }

                DataRow[] drfk = dtFK.Select("FkTable = '" + tbl.Name + "' and RelName = '" + rel.Name + "'");
                for (int ii = 0; ii < drfk.Length; ii++)
                {
                    Relationship.KeyPair kp = new Relationship.KeyPair();
                    TableColumn fkcol = columns.GetColumn(drfk[ii]["FkColumn"].ToString());
                    TableColumn pkcol = pktable.Columns.GetColumn(drfk[ii]["PkColumn"].ToString());
                    kp.vartype = fkcol.VarType;
                    kp.ForeignKey = fkcol.Name;
                    kp.PrimaryKey = pkcol.Name;
                    rel.KeyPairs.Add(kp);
                    if (ii > 0)
                    {
                        rel.ForeignKey += ",";
                        rel.PrimaryKey += ",";
                    }
                    rel.PrimaryKey += kp.PrimaryKey;
                    rel.ForeignKey += kp.ForeignKey;
                    fkcol.PropertyNameOne = rel.PropertyNameOne;
                }

                tbl.ForeignKeys.Add(rel);
            }

            if (dsManyToManyCheck.Tables[Name] == null)
            {
                var cmdM2M = new SqlCommand(MANY_TO_MANY_CHECK_ALL);
                var dt = new DataTable(Name);
                dt.Load(cmdM2M.GetReader());
                dsManyToManyCheck.Tables.Add(dt);
            }

            DataRow[] drs = dsManyToManyCheck.Tables[Name].Select("PK_Table = '" + tbl.Name + "'");
            if (drs.Length > 0)
            {
                for (int count = 0; count < drs.Length; count++)
                {
                    string mapTable = drs[count]["FK_Table"].ToString();
                    string localKey = drs[count]["FK_Column"].ToString();
                    if (dsManyToManyMap.Tables[Name] == null)
                    {
                        var cmdM2MMap = new SqlCommand(MANY_TO_MANY_FOREIGN_MAP_ALL);
                        DataTable dt = new DataTable(Name);
                        dt.Load(cmdM2MMap.GetReader());
                        dsManyToManyMap.Tables.Add(dt);
                    }


                    DataRow[] drMap = dsManyToManyMap.Tables[Name].Select("FK_Table = '" + mapTable + "' AND PK_Table <> '" + tbl.Name + "'");

                    for (int i = 0; i < drMap.Length; i++)
                    {
                        ManyToManyRelationship m = new ManyToManyRelationship(mapTable);
                        m.ForeignTableName = drMap[i]["PK_Table"].ToString();
                        m.ForeignPrimaryKey = drMap[i]["PK_Column"].ToString();
                        m.MapTableLocalTableKeyColumn = localKey;
                        m.MapTableForeignTableKeyColumn = drMap[i]["FK_Column"].ToString();
                        tbl.ManyToManys.Add(m);
                    }
                }
            }
        }
 public NotNullConstraint(Table table, string name, TableColumn column) : base(table, name)
 {
     Column   = column;
     IsInline = true;
 }
Example #39
0
        /// <summary>
        /// Adds a column to the table
        /// </summary>
        /// <param name="tableName">name of the table</param>
        /// <param name="column">The column</param>
        /// <returns>Boolean</returns>
        public override bool AddColumn(string tableName, TableColumn column)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("ALTER TABLE ");
            sb.Append(tableName);
            sb.Append(" ADD ");
            sb.Append(column.Name);
            sb.Append(" ");
            sb.Append(GetDbSpecificColumnType(column.DataType));
            if (column.Length != null)
            {
                sb.Append("(");
                sb.Append(column.Length.Value.ToString());
                sb.Append(") ");
            }

            ExecuteNonQuery(CreateQuery(sb.ToString()));
            return false;
        }
 /// <summary>
 /// 初始化<see cref="ColumnResolveContext"/>对象
 /// </summary>
 /// <param name="template">字段解析的模板</param>
 /// <param name="column"><see cref="TableColumn"/>对象</param>
 public ColumnResolveContext(string template, TableColumn column)
 {
     this._output = template;
     _column      = column;
 }
Example #41
0
        void InitializeDescriptiveTextTab()
        {
            var selectedTypeface = new Typeface(
                SelectedFontFamily,
                SelectedFontStyle,
                SelectedFontWeight,
                SelectedFontStretch
                );

            GlyphTypeface glyphTypeface;
            if (selectedTypeface.TryGetGlyphTypeface(out glyphTypeface))
            {
                // Create a table with two columns.
                var table = new Table();
                table.CellSpacing = 5;
                var leftColumn = new TableColumn();
                leftColumn.Width = new GridLength(2.0, GridUnitType.Star);
                table.Columns.Add(leftColumn);
                var rightColumn = new TableColumn();
                rightColumn.Width = new GridLength(3.0, GridUnitType.Star);
                table.Columns.Add(rightColumn);

                var rowGroup = new TableRowGroup();
                AddTableRow(rowGroup, "Family:", glyphTypeface.FamilyNames);
                AddTableRow(rowGroup, "Face:", glyphTypeface.FaceNames);
                AddTableRow(rowGroup, "Description:", glyphTypeface.Descriptions);
                AddTableRow(rowGroup, "Version:", glyphTypeface.VersionStrings);
                AddTableRow(rowGroup, "Copyright:", glyphTypeface.Copyrights);
                AddTableRow(rowGroup, "Trademark:", glyphTypeface.Trademarks);
                AddTableRow(rowGroup, "Manufacturer:", glyphTypeface.ManufacturerNames);
                AddTableRow(rowGroup, "Designer:", glyphTypeface.DesignerNames);
                AddTableRow(rowGroup, "Designer URL:", glyphTypeface.DesignerUrls);
                AddTableRow(rowGroup, "Vendor URL:", glyphTypeface.VendorUrls);
                AddTableRow(rowGroup, "Win32 Family:", glyphTypeface.Win32FamilyNames);
                AddTableRow(rowGroup, "Win32 Face:", glyphTypeface.Win32FaceNames);

                try
                {
                    AddTableRow(rowGroup, "Font File URI:", glyphTypeface.FontUri.ToString());
                }
                catch (System.Security.SecurityException)
                {
                    // Font file URI is privileged information; just skip it if we don't have access.
                }

                table.RowGroups.Add(rowGroup);

                fontDescriptionBox.Document = new FlowDocument(table);

                fontLicenseBox.Text = NameDictionaryHelper.GetDisplayName(glyphTypeface.LicenseDescriptions);
            }
            else
            {
                fontDescriptionBox.Document = new FlowDocument();
                fontLicenseBox.Text = String.Empty;
            }
        }
Example #42
0
        public override string GetDBFieldType(TableColumn f)
        {
            string ret = "";

            switch (f.TypeName)
            {
            case "Int16":
                ret = "smallint";
                break;

            case "DateTime":
                ret = "TIMESTAMP";
                break;

            case "Byte":
                ret = "SMALLINT";
                break;

            case "Int32":
            case "Int64":
                ret = "integer";
                break;

            case "String":
                //UPGRADE_WARNING: Couldn't resolve default property of object RS.Fields. Click for more: 'ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'

                /* if (f.DefinedSize > 255)
                 * {
                 *   ret = "ntext";
                 * }
                 * else
                 * {*/
                ret = "Varchar(" + f.DefinedSize + ")";
                // }

                break;

            case "Decimal":
                ret = "Decimal(15,6)";
                break;

            case "Double":
                ret = "DOUBLE PRECISION";
                break;

            case "Float":
            case "Single":
                ret = "Float";
                break;

            case "Char[]":
                ret = "char(" + f.DefinedSize + ")";
                break;

            default:
                ret = " unknowed ";
                //TODO: Exception
                break;
            }
            return(ret);
        }
Example #43
0
        /// <summary>
        /// Converts htmlColElement into Xaml TableColumn element, and appends it to the parent
        /// xamlTableColumnGroupElement
        /// </summary>
        /// <param name="xamlTableElement"></param>
        /// <param name="htmlColElement">
        /// XmlElement representing Html col element to be converted
        /// </param>
        /// <param name="inheritedProperties">
        /// properties inherited from parent context
        /// </param>
        /// <param name="stylesheet"></param>
        /// <param name="sourceContext"></param>
        private void AddTableColumn(Table table, XmlElement htmlColElement, Hashtable inheritedProperties, CssStylesheet stylesheet)
        {
            //Hashtable currentProperties = new Hashtable();
            //  GetElementProperties((XmlElement)htmlColElement, inheritedProperties, currentProperties, stylesheet);

            TableColumn tcol = new TableColumn();

            //  ApplyLocalProperties(tcol, currentProperties,/*isBlock*/true);
            // TODO: process local properties for TableColumn element

            // Col is an empty element, with no subtree 
            //  xamlTableElement.AppendChild(xamlTableColumnElement);
            table.Columns.Add(tcol);
        }
 public void Visit(TableColumn tableColumn)
 {
     foreach (var elem in tableColumn.Contents)
     {
         elem.Accept(this);
     }
 }
		public static TableMeta ToMeta(string tableName)
		{
            // Parse a string like;
            // CREATE TABLE SimpleTable ([Id] long not null,[Test] nvarchar(300) ,[When] date , PRIMARY KEY ([Id] ))
			
            TableMeta meta = new TableMeta {ParameterizedTableName = tableName};

			string schema = GetDbSchemaFor( tableName );
			if (string.IsNullOrEmpty( schema ))
				return null;

			StringParse parse = new StringParse( schema );
			if (!parse.Read("CREATE TABLE " + tableName + " ("))
				return null;
			
			while (!parse.Peek(")") && !parse.IsEmpty)
			{
                parse.SkipWhitespace();


				if (parse.Peek("[") || parse.Contains(' '))
				{
                    string fieldName;
                    if (parse.Peek("["))
                    {
                        fieldName = parse.ReadBetween('[', ']');
                    }
                    else
                    {
                        if (parse.Peek("PRIMARY KEY"))
                            break;

                        fieldName = parse.ReadTo(' ');                        
                    }

                    parse.SkipWhitespace();

					TableColumn tc = new TableColumn
					                 	{
					                 		Name = fieldName,
					                 		Get = (t, inst) => ((AnonmousTable) inst)[ t.RawName ],
					                 		Set = (t, inst, val) => ((AnonmousTable) inst)[ t.RawName ] = val
					                 	};

					parse.While( KeywordTriggerDefinitions, tc );

                    meta.Columns.Add(tc);
				}

                if (parse.Peek(","))
                {
                    parse.Read(",");
                    continue;
                }

                if (parse.Peek(")"))
                    break;

                if (parse.Peek("PRIMARY KEY"))
                    break;
             
  				throw new NotImplementedException("Incomplete parsing of " + tableName);
			}

			return meta;
		}
 // Used also in TextTreeExtractElementUndoUnit
 internal static void RestoreColumns(Table table, TableColumn[] savedColumns)
 {
     if (savedColumns != null)
     {
         for (int columnIndex = 0; columnIndex < savedColumns.Length; columnIndex++)
         {
             if (table.Columns.Count <= columnIndex)
             {
                 table.Columns.Add(CopyColumn(savedColumns[columnIndex]));
             }
         }
     }
 }
        public override BUSJoinSpecification DataToBusiness(JoinSpecification dataEntity, TContext context)
        {
            BUSJoinSpecification businessEntity = base.DataToBusiness(dataEntity, context);

            // Join
            Join join = context.Joins
                        .AsNoTracking()
                        .Select(j => new
            {
                id    = j.Id,
                name  = j.Name,
                table = new
                {
                    id           = j.Table.Id,
                    tableColumns = j.Table.TableColumns.Select(joinColumn => new
                    {
                        id   = joinColumn.Id,
                        name = joinColumn.Name
                    })
                },
                tableId   = j.TableId,
                busCompId = j.BusCompId
            })
                        .Select(j => new Join
            {
                Id    = j.id,
                Name  = j.name,
                Table = new Table
                {
                    Id           = j.table.id,
                    TableColumns = j.table.tableColumns.Select(joinColumn => new TableColumn
                    {
                        Id   = joinColumn.id,
                        Name = joinColumn.name
                    }).ToList()
                },
                TableId   = j.tableId,
                BusCompId = j.busCompId
            })
                        .FirstOrDefault(i => i.Id == dataEntity.JoinId);

            businessEntity.Join   = join;
            businessEntity.JoinId = join.Id;

            // BusComp
            BusinessComponent busComp = context.BusinessComponents
                                        .AsNoTracking()
                                        .Select(bc => new
            {
                id     = bc.Id,
                fields = bc.Fields.Select(f => new
                {
                    id   = f.Id,
                    name = f.Name
                })
            })
                                        .Select(bc => new BusinessComponent
            {
                Id     = bc.id,
                Fields = bc.fields.Select(f => new Field
                {
                    Id   = f.id,
                    Name = f.name
                }).ToList()
            })
                                        .FirstOrDefault(i => i.Id == join.BusCompId);

            businessEntity.BusComp   = busComp;
            businessEntity.BusCompId = busComp.Id;

            // Source field
            Field field = busComp.Fields.FirstOrDefault(i => i.Id == dataEntity.SourceFieldId);

            if (field != null)
            {
                businessEntity.SourceField     = field;
                businessEntity.SourceFieldId   = field.Id;
                businessEntity.SourceFieldName = field.Name;
            }

            // Destination column
            Table table = join.Table;

            businessEntity.Table   = table;
            businessEntity.TableId = table.Id;

            TableColumn destinationColumn = table.TableColumns.FirstOrDefault(i => i.Id == dataEntity.DestinationColumnId);

            if (destinationColumn != null)
            {
                businessEntity.DestinationColumn     = destinationColumn;
                businessEntity.DestinationColumnId   = destinationColumn.Id;
                businessEntity.DestinationColumnName = destinationColumn.Name;
            }
            return(businessEntity);
        }
 internal SqlSetDefault(SqlExpression defaultValue, TableColumn column)
 {
     DefaultValue = defaultValue;
     Column       = column;
 }
        //------------------------------------------------------
        //
        //  Internal Methods
        //
        //------------------------------------------------------

        #region Internal Methods

        // Used also in TextTreeExtractElementUndoUnit
        internal static TableColumn[] SaveColumns(Table table)
        {
            TableColumn[] savedColumns;
            if (table.Columns.Count > 0)
            {
                savedColumns = new TableColumn[table.Columns.Count];
                for (int columnIndex = 0; columnIndex < table.Columns.Count; columnIndex++)
                {
                    savedColumns[columnIndex] = CopyColumn(table.Columns[columnIndex]);
                }
            }
            else
            {
                savedColumns = null;
            }

            return savedColumns;
        }
    void DrawCustomColumns()
    {
        SerializedObject      serializedObject = new SerializedObject(SimpleExample.Instance);
        List <SelectorColumn> propertyColumns  = new List <SelectorColumn>()
        {
            new SelectFromPropertyNameColumn("stringProperty", "String", TableColumn.Width(60f)),
            new SelectFromPropertyNameColumn("floatProperty", "Float", TableColumn.Width(50f), TableColumn.Optional(true)),
            new SelectFromPropertyNameColumn("objectProperty", "Object", TableColumn.Width(50f), TableColumn.EnabledTitle(false), TableColumn.Optional(true)),
        };

        tableState = GUITableLayout.DrawTable(tableState, serializedObject.FindProperty("simpleObjects"), propertyColumns);
    }
        private static TableColumn CopyColumn(TableColumn sourceTableColumn)
        {
            TableColumn newTableColumn = new TableColumn();
            LocalValueEnumerator properties = sourceTableColumn.GetLocalValueEnumerator();
            while (properties.MoveNext())
            {
                LocalValueEntry propertyEntry = properties.Current;
                if (!propertyEntry.Property.ReadOnly)
                {
                    newTableColumn.SetValue(propertyEntry.Property, propertyEntry.Value);
                }
            }

            return newTableColumn;
        }
Example #52
0
        public Dictionary <List <AppFunc>, List <TableColumn> > ListFuncTableColumn(string ObjectFolder, string strFileName, ref string MsgLinkUrl)
        {
            Dictionary <List <AppFunc>, List <TableColumn> > FuncTableColumn = new Dictionary <List <AppFunc>, List <TableColumn> >();

            try
            {
                List <AppFunc> list = new List <AppFunc>();
                string         Path = System.Web.Hosting.HostingEnvironment.MapPath("~/BusinessObjects/" + ObjectFolder + "/" + strFileName + ".xml");
                XDocument      xdoc = XDocument.Load(Path);
                try
                {
                    string strXml = xdoc.Document.ToString();
                    int    Start  = strXml.IndexOf("<MsgOpen>") + "<MsgOpen>".Length;
                    int    End    = strXml.IndexOf("</MsgOpen>");
                    MsgLinkUrl = strXml.Substring(Start, End - Start);
                }
                catch { }
                var xmlTree = from c in xdoc.Descendants("Function")
                              select c;
                if (xmlTree.Count() > 0)
                {
                    foreach (var v in xmlTree)
                    {
                        AppFunc sys = new AppFunc();
                        sys.Language = v.Attribute("Description").Value;
                        sys.FuncName = v.Attribute("FuncName").Value;

                        // sys.Parameter = v.Attribute("Parameter").Value;
                        sys.Address   = v.Attribute("Address").Value;
                        sys.Binding   = v.Attribute("Binding").Value;
                        sys.SplitChar = v.Attribute("SplitChar").Value;
                        List <Parameter> ListParam = new List <Parameter>();
                        var param = v.Descendants("ParaStr").Descendants <XElement>("Para");
                        if (param.Count() > 0)
                        {
                            foreach (var p in param)
                            {
                                Parameter para = new Parameter();
                                para.Description = p.Attribute("Description").Value.CvtString();
                                para.Name        = p.Attribute("Name").Value.CvtString();
                                para.Value       = p.Attribute("Value").Value.CvtString();
                                para.TableName   = p.Attribute("TableName").Value.CvtString();
                                ListParam.Add(para);
                            }
                        }
                        sys.Parameter = ListParam;
                        list.Add(sys);
                    }
                }
                List <TableColumn> lists = new List <TableColumn>();
                var xmlTrees             = from c in xdoc.Descendants("Object").Descendants <XElement>("Attribute")
                                           select c;
                if (xmlTrees.Count() > 0)
                {
                    foreach (var v in xmlTrees)
                    {
                        TableColumn sys = new TableColumn();
                        sys.Language    = v.Attribute("Description").Value;
                        sys.DataType    = v.Attribute("DataType").Value;
                        sys.DataValue   = v.Attribute("DataValue").Value;
                        sys.Description = v.Attribute("Description").Value;
                        sys.FieldName   = v.Attribute("Name").Value;
                        lists.Add(sys);
                    }
                }
                xdoc = null;
                FuncTableColumn.Add(list, lists);
                return(FuncTableColumn);
            }
            catch (Exception ex)
            {
                //ErrorLog.WriteErrorMessage(ex.Message + "|" + DateTime.Now.ToString() + "|" + ex.Source + "|" + "UserDefine.svc方法GetSystemFuncList");
            }
            return(null);
        }
Example #53
0
 public virtual void AppendPropertyAttributes(StringBuilder content, TableColumn column)
 {
     content.Append(CreateTabSpaces(2));
     if (column.IsIdentity && column.IsPrimaryKey)
     {
         content.Append("[Column(ColumnName = \"" + column.ColumnName + "\",IsIdentity = true,IsPrimaryKey = true)]\n");
     }
     else if (column.IsIdentity)
     {
         content.Append("[Column(ColumnName = \"" + column.ColumnName + "\",IsIdentity = true)]\n");
     }
     else if (column.IsPrimaryKey)
     {
         content.Append("[Column(ColumnName = \"" + column.ColumnName + "\",IsPrimaryKey = true)]\n");
     }
     else if (column.IsForeignKey)
     {
         content.Append("[Column(ColumnName = \"" + column.ColumnName + "\",IsForeignKey = true,ReferenceType=typeof(" +
             column.ReferenceTableName + "))]\n");
     }
     else
     {
         content.Append("[Column(ColumnName = \"" + column.ColumnName + "\")]\n");
     }
 }
Example #54
0
        static StandardElementMapping()
        {
            foObjs       = new Hashtable();
            s_fObjMakers = new Dictionary <string, FObj.MakerBase>();

            // Declarations and Pagination and Layout Formatting Objects
            foObjs.Add("root", Root.GetMaker());
            foObjs.Add("declarations", Declarations.GetMaker());
            foObjs.Add("color-profile", ColorProfile.GetMaker());
            foObjs.Add("page-sequence", PageSequence.GetMaker());
            foObjs.Add("layout-master-set", LayoutMasterSet.GetMaker());
            foObjs.Add("page-sequence-master", PageSequenceMaster.GetMaker());
            foObjs.Add("single-page-master-reference", SinglePageMasterReference.GetMaker());
            foObjs.Add("repeatable-page-master-reference", RepeatablePageMasterReference.GetMaker());
            foObjs.Add("repeatable-page-master-alternatives", RepeatablePageMasterAlternatives.GetMaker());
            foObjs.Add("conditional-page-master-reference", ConditionalPageMasterReference.GetMaker());
            foObjs.Add("simple-page-master", SimplePageMaster.GetMaker());
            foObjs.Add("region-body", RegionBody.GetMaker());
            foObjs.Add("region-before", RegionBefore.GetMaker());
            foObjs.Add("region-after", RegionAfter.GetMaker());
            foObjs.Add("region-start", RegionStart.GetMaker());
            foObjs.Add("region-end", RegionEnd.GetMaker());
            foObjs.Add("flow", Flow.Flow.GetMaker());
            foObjs.Add("static-content", StaticContent.GetMaker());
            foObjs.Add("title", Title.GetMaker());

            // Block-level Formatting Objects
            foObjs.Add("block", Block.GetMaker());
            foObjs.Add("block-container", BlockContainer.GetMaker());

            // Inline-level Formatting Objects
            foObjs.Add("bidi-override", BidiOverride.GetMaker());
            foObjs.Add("character", Character.GetMaker());
            foObjs.Add("initial-property-set", InitialPropertySet.GetMaker());
            foObjs.Add("external-graphic", ExternalGraphic.GetMaker());
            foObjs.Add("instream-foreign-object", InstreamForeignObject.GetMaker());
            foObjs.Add("inline", Inline.GetMaker());
            foObjs.Add("inline-container", InlineContainer.GetMaker());
            foObjs.Add("leader", Leader.GetMaker());
            foObjs.Add("page-number", PageNumber.GetMaker());
            foObjs.Add("page-number-citation", PageNumberCitation.GetMaker());

            // Formatting Objects for Tables
            foObjs.Add("table-and-caption", TableAndCaption.GetMaker());
            foObjs.Add("table", Table.GetMaker());
            foObjs.Add("table-column", TableColumn.GetMaker());
            foObjs.Add("table-caption", TableCaption.GetMaker());
            foObjs.Add("table-header", TableHeader.GetMaker());
            foObjs.Add("table-footer", TableFooter.GetMaker());
            foObjs.Add("table-body", TableBody.GetMaker());
            foObjs.Add("table-row", TableRow.GetMaker());
            foObjs.Add("table-cell", TableCell.GetMaker());

            // Formatting Objects for Lists
            foObjs.Add("list-block", ListBlock.GetMaker());
            foObjs.Add("list-item", ListItem.GetMaker());
            foObjs.Add("list-item-body", ListItemBody.GetMaker());
            foObjs.Add("list-item-label", ListItemLabel.GetMaker());

            // Dynamic Effects: Link and Multi Formatting Objects
            foObjs.Add("basic-link", BasicLink.GetMaker());
            foObjs.Add("multi-switch", MultiSwitch.GetMaker());
            foObjs.Add("multi-case", MultiCase.GetMaker());
            foObjs.Add("multi-toggle", MultiToggle.GetMaker());
            foObjs.Add("multi-properties", MultiProperties.GetMaker());
            foObjs.Add("multi-property-set", MultiPropertySet.GetMaker());

            // Out-of-Line Formatting Objects
            foObjs.Add("float", Float.GetMaker());
            foObjs.Add("footnote", Footnote.GetMaker());
            foObjs.Add("footnote-body", FootnoteBody.GetMaker());

            // Other Formatting Objects
            foObjs.Add("wrapper", Wrapper.GetMaker());
            foObjs.Add("marker", Marker.GetMaker());
            foObjs.Add("retrieve-marker", RetrieveMarker.GetMaker());
        }
Example #55
0
        /// <summary>
        /// Returns random data
        /// </summary>
        public object GetRandomData(Random rnd, TableColumn column)
        {
            int length = column.MaxLength;
            int maxTargetLength = (length > 255 || length == -1) ? 255 : length;

            DbType dbType = GetDbType(column);
            return GetRandomData(rnd, dbType, maxTargetLength);
        }
Example #56
0
 /// <summary>
 /// Set the table column
 /// </summary>
 /// <param name="tc"></param>
 public void SetTableColumn(TableColumn tc)
 {
     TableName  = tc.TableName;
     ColumnName = tc.ColumnName;
     MDV.SetRow(tc);
 }
        private void InitializeRetrieveProgressTable(Table<RetrieveProgressResult> table)
        {
            TableColumn<RetrieveProgressResult, string> column;

            column = new TableColumn<RetrieveProgressResult, string>("Status", delegate(RetrieveProgressResult result)
            {
                string msg = string.IsNullOrEmpty(result.ProgressMessage)
                                ? null
                                : result.ProgressMessage;

                switch (result.Status)
                {
                    case RetrieveStatus.Queued:
                        return "Waiting";
                    case RetrieveStatus.InProgress:
                        return msg ?? "Downloading...";
                    case RetrieveStatus.Canceled:
                        return "Canceled";
                    case RetrieveStatus.Completed:
                        return "Done";
                    case RetrieveStatus.CancelRequested:
                        return string.Format("{0}...Canceling", msg ?? "");
                }
                return msg ?? "";
            }, 0.25F);
            table.Columns.Add(column);

            column = new TableColumn<RetrieveProgressResult, string>("Study Count", delegate(RetrieveProgressResult result)
            {
                return result.QueryItems.Count.ToString();
            }, 0.05F);
            table.Columns.Add(column);

            column = new TableColumn<RetrieveProgressResult, string>("Patient Id", delegate(RetrieveProgressResult result)
            {
                switch (result.QueryItems.Count)
                {
                    case 0:
                        break;
                    case 1:
                        return result.QueryItems[0].Patient.PatientId ?? "";
                    default:
                        return string.Format("1. {0}...", result.QueryItems[0].Patient.PatientId ?? "");
                }
                return "";
            }, 0.25F);
            column.TooltipTextProvider =
                delegate(RetrieveProgressResult result)
                {
                    if (result.QueryItems.Count > 1)
                    {
                        List<string> tooltipList = new List<string>();
                        int cnt = 0;
                        foreach (RetrieveQueryItem queryItem in result.QueryItems)
                        {
                            tooltipList.Add(string.Format("{0}. {1}", ++cnt, queryItem.Patient.PatientId ?? ""));
                        }

                        return StringUtilities.Combine(tooltipList, "\n");
                    }

                    return result.QueryItems.Count > 0 ? result.QueryItems[0].Patient.PatientId ?? "" : "";
                };
            table.Columns.Add(column);

            column = new TableColumn<RetrieveProgressResult, string>("Patient's Name", delegate(RetrieveProgressResult result)
            {
                switch (result.QueryItems.Count)
                {
                    case 0:
                        break;
                    case 1:
                        return result.QueryItems[0].Patient.PatientsName ?? "";
                    default:
                        return string.Format("1. {0}...", result.QueryItems[0].Patient.PatientsName ?? "");
                }
                return "";
            }, 0.25F);
            column.TooltipTextProvider =
                delegate(RetrieveProgressResult result)
                {
                    if (result.QueryItems.Count > 1)
                    {
                        List<string> tooltipList = new List<string>();
                        int cnt = 0;
                        foreach (RetrieveQueryItem queryItem in result.QueryItems)
                        {
                            tooltipList.Add(string.Format("{0}. {1}", ++cnt, queryItem.Patient.PatientsName ?? ""));
                        }

                        return StringUtilities.Combine(tooltipList, "\n");
                    }

                    return result.QueryItems.Count > 0 ? result.QueryItems[0].Patient.PatientsName ?? "" : "";
                };
            table.Columns.Add(column);

            column = new TableColumn<RetrieveProgressResult, string>("Study", delegate(RetrieveProgressResult result)
            {
                switch (result.QueryItems.Count)
                {
                    case 0:
                        break;
                    case 1:
                        return result.QueryItems[0].Study.StudyInstanceUid ?? "";
                    default:
                        return string.Format("1. {0}...", result.QueryItems[0].Study.StudyInstanceUid ?? "");
                }
                return "";

            }, 0.25F);
            column.TooltipTextProvider =
                delegate(RetrieveProgressResult result)
                {
                    if (result.QueryItems.Count > 1)
                    {
                        List<string> tooltipList = new List<string>();
                        int cnt = 0;
                        foreach (RetrieveQueryItem queryItem in result.QueryItems)
                        {
                            tooltipList.Add(string.Format("{0}. {1}", ++cnt, queryItem.Study.StudyInstanceUid ?? ""));
                        }

                        return StringUtilities.Combine(tooltipList, "\n");
                    }

                    return result.QueryItems.Count > 0 ? result.QueryItems[0].Study.StudyInstanceUid ?? "" : "";
                };
            table.Columns.Add(column);
        }
Example #58
0
        private bool SaveSettings()
        {
            try
            {
                TableName = txtTableDesc.Text;
                if (string.IsNullOrEmpty(TableName))
                {
                    EnvDteHelper.ShowError("Table name is required");
                    return(false);
                }

                var validation = TableColumn.ValidateColumns(_columns.ToList());
                if (!string.IsNullOrEmpty(validation))
                {
                    EnvDteHelper.ShowError(validation);
                    return(false);
                }
                TableColumns = TableColumn.BuildColumns(_columns.ToList(), TableName);
                PkScript     = TableColumn.BuildPkScript(_columns.ToList(), TableName);
                PkScript     = _dbType == DatabaseType.SQLite ? BuildSqLitePkScript(_columns.ToList(), TableName) : TableColumn.BuildPkScript(_columns.ToList(), TableName);
                return(true);
            }
            catch (Exception ex)
            {
                DataConnectionHelper.SendError(ex, DatabaseType.SQLServer);
            }
            return(false);
        }
Example #59
0
 //public TableModel GetTableModel(string TableName)
 //{
 //    TableModel model = new TableModel();
 //    model.TableName = TableName;
 //    model.TableNameRemark = this.GetTableAlone(model.TableName, TableFlg.表说明);
 //    model.TablePK = this.GetTableAlone(model.TableName, TableFlg.主键列);
 //    bool istree = false;
 //    List<TableColumn> columnsList = this.GetColumnsList(TableName, out istree);
 //    model.Columns = columnsList;
 //    model.IsTree = istree;
 //    return model;
 //}
 public List<TableColumn> GetColumnsList(string TableName, out bool istree)
 {
     istree = false;
     DataTable dtcolumns = this.GetTablesColumnsList(TableName);
     List<TableColumn> columnsList = new List<TableColumn>();
     foreach (DataRow row in dtcolumns.Rows)
     {
         TableColumn column = new TableColumn();
         column.ColumnName = row["字段名"].ToString();
         column.ColumnRemark = row["字段说明"].ToString();
         column.DefaultValue = row["默认值"].ToString();
         if (column.ColumnRemark.Length == 0) column.ColumnRemark = column.ColumnName;
         column.ColumnType = datatype.IniReadValue("DbToCS", row["类型"].ToString());
         if (row["主键"].ToString().Length > 0)
         {
             column.PK = true;
         }
         if (row["标识"].ToString().Length > 0)
         {
             column.Identifying = true;
         }
         if (column.ColumnName.ToLower() == "parentid")
         {
             istree = true;
         }
         if (!arrlist.Contains(column.ColumnName))
             columnsList.Add(column);
     }
     return columnsList;
 }
Example #60
0
        protected TableColumns CreateColumns(XmlNode node)
        {
            TableColumns columns = new TableColumns();

            if (node is XmlElement)
            {
                XmlElement elem = (XmlElement)node;
                if (elem.HasAttributes)
                {
                    foreach (XmlAttribute attr in elem.Attributes)
                    {
                        TableColumn col = columns.Add();
                        col.type = typeof(XmlAttribute);
                        col.name = attr.Name;
                    }
                }
            }
            if (node.HasChildNodes)
            {
                int            i      = 0;
                List <XmlNode> childs = SelectChilds(node);
                while (i < childs.Count)
                {
                    XmlNode     cur = childs[i];
                    TableColumn col = columns.Add();
                    col.type  = cur.GetType();
                    col.name  = GetNodeName(cur);
                    col.pos   = 0;
                    col.count = 1;
                    int k;
                    for (k = 0; k < i; k++)
                    {
                        cur = childs[k];
                        if (!(cur is XmlSignificantWhitespace))
                        {
                            if (cur.GetType() == col.type && (!(cur is XmlElement) || GetNodeName(cur) == col.name))
                            {
                                col.pos++;
                            }
                        }
                    }
                    k = i + 1;
                    while (k < childs.Count)
                    {
                        cur = childs[k];
                        if (!(cur is XmlSignificantWhitespace))
                        {
                            if (cur.GetType() == col.type && (!(cur is XmlElement) || GetNodeName(cur) == col.name))
                            {
                                col.count++;
                            }
                            else
                            {
                                break;
                            }
                        }
                        k++;
                    }
                    i = k;
                }
            }
            return(columns);
        }